This commit is contained in:
misson20000 2020-11-21 13:05:07 +01:00 committed by GitHub
commit 506f889282
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
56 changed files with 12180 additions and 1345 deletions

1
.gitignore vendored
View File

@ -95,3 +95,4 @@ sept/sept-secondary/KEYS.py
**/build_nintendo_nx_arm **/build_nintendo_nx_arm
**/build_nintendo_nx_x64 **/build_nintendo_nx_x64
**/build_nintendo_nx_x86 **/build_nintendo_nx_x86
extras

168
Makefile
View File

@ -39,94 +39,86 @@ clean:
$(MAKE) -C fusee clean $(MAKE) -C fusee clean
rm -rf out rm -rf out
dist-no-debug: all MAJORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MAJOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \
$(eval MAJORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MAJOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \ | tr -s [:blank:] \
| cut -d' ' -f3)
MINORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MINOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \
| tr -s [:blank:] \ | tr -s [:blank:] \
| cut -d' ' -f3)) | cut -d' ' -f3)
$(eval MINORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MINOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \ MICROVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MICRO\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \
| tr -s [:blank:] \ | tr -s [:blank:] \
| cut -d' ' -f3)) | cut -d' ' -f3)
$(eval MICROVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MICRO\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \ AMSVER = $(MAJORVER).$(MINORVER).$(MICROVER)-$(AMSREV)
| tr -s [:blank:] \
| cut -d' ' -f3)) out/atmosphere-$(AMSVER): all
$(eval AMSVER = $(MAJORVER).$(MINORVER).$(MICROVER)-$(AMSREV)) rm -rf out/atmosphere-$(AMSVER)
rm -rf atmosphere-$(AMSVER) mkdir -p out/atmosphere-$(AMSVER)
rm -rf out mkdir -p out/atmosphere-$(AMSVER)/atmosphere
mkdir atmosphere-$(AMSVER) mkdir -p out/atmosphere-$(AMSVER)/sept
mkdir atmosphere-$(AMSVER)/atmosphere mkdir -p out/atmosphere-$(AMSVER)/switch
mkdir atmosphere-$(AMSVER)/sept mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008
mkdir atmosphere-$(AMSVER)/switch mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008 mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032 mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034 mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036 mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037 mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C mkdir -p out/atmosphere-$(AMSVER)/atmosphere/fatal_errors
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042 mkdir -p out/atmosphere-$(AMSVER)/atmosphere/config_templates
mkdir -p atmosphere-$(AMSVER)/atmosphere/fatal_errors mkdir -p out/atmosphere-$(AMSVER)/atmosphere/config
mkdir -p atmosphere-$(AMSVER)/atmosphere/config_templates cp fusee/fusee-primary/fusee-primary.bin out/atmosphere-$(AMSVER)/atmosphere/reboot_payload.bin
mkdir -p atmosphere-$(AMSVER)/atmosphere/config cp fusee/fusee-mtc/fusee-mtc.bin out/atmosphere-$(AMSVER)/atmosphere/fusee-mtc.bin
cp fusee/fusee-primary/fusee-primary.bin atmosphere-$(AMSVER)/atmosphere/reboot_payload.bin cp fusee/fusee-secondary/fusee-secondary-experimental.bin out/atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin
cp fusee/fusee-mtc/fusee-mtc.bin atmosphere-$(AMSVER)/atmosphere/fusee-mtc.bin cp fusee/fusee-secondary/fusee-secondary-experimental.bin out/atmosphere-$(AMSVER)/sept/payload.bin
cp fusee/fusee-secondary/fusee-secondary-experimental.bin atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin cp sept/sept-primary/sept-primary.bin out/atmosphere-$(AMSVER)/sept/sept-primary.bin
cp fusee/fusee-secondary/fusee-secondary-experimental.bin atmosphere-$(AMSVER)/sept/payload.bin cp sept/sept-secondary/sept-secondary.bin out/atmosphere-$(AMSVER)/sept/sept-secondary.bin || true
cp sept/sept-primary/sept-primary.bin atmosphere-$(AMSVER)/sept/sept-primary.bin cp sept/sept-secondary/sept-secondary_00.enc out/atmosphere-$(AMSVER)/sept/sept-secondary_00.enc
cp sept/sept-secondary/sept-secondary.bin atmosphere-$(AMSVER)/sept/sept-secondary.bin cp sept/sept-secondary/sept-secondary_01.enc out/atmosphere-$(AMSVER)/sept/sept-secondary_01.enc
cp sept/sept-secondary/sept-secondary_00.enc atmosphere-$(AMSVER)/sept/sept-secondary_00.enc cp sept/sept-secondary/sept-secondary_dev_00.enc out/atmosphere-$(AMSVER)/sept/sept-secondary_dev_00.enc
cp sept/sept-secondary/sept-secondary_01.enc atmosphere-$(AMSVER)/sept/sept-secondary_01.enc cp sept/sept-secondary/sept-secondary_dev_01.enc out/atmosphere-$(AMSVER)/sept/sept-secondary_dev_01.enc
cp sept/sept-secondary/sept-secondary_dev_00.enc atmosphere-$(AMSVER)/sept/sept-secondary_dev_00.enc cp config_templates/BCT.ini out/atmosphere-$(AMSVER)/atmosphere/config/BCT.ini
cp sept/sept-secondary/sept-secondary_dev_01.enc atmosphere-$(AMSVER)/sept/sept-secondary_dev_01.enc cp config_templates/override_config.ini out/atmosphere-$(AMSVER)/atmosphere/config_templates/override_config.ini
cp config_templates/BCT.ini atmosphere-$(AMSVER)/atmosphere/config/BCT.ini cp config_templates/system_settings.ini out/atmosphere-$(AMSVER)/atmosphere/config_templates/system_settings.ini
cp config_templates/override_config.ini atmosphere-$(AMSVER)/atmosphere/config_templates/override_config.ini cp config_templates/exosphere.ini out/atmosphere-$(AMSVER)/atmosphere/config_templates/exosphere.ini
cp config_templates/system_settings.ini atmosphere-$(AMSVER)/atmosphere/config_templates/system_settings.ini cp -r config_templates/kip_patches out/atmosphere-$(AMSVER)/atmosphere/kip_patches
cp config_templates/exosphere.ini atmosphere-$(AMSVER)/atmosphere/config_templates/exosphere.ini cp -r config_templates/hbl_html out/atmosphere-$(AMSVER)/atmosphere/hbl_html
cp -r config_templates/kip_patches atmosphere-$(AMSVER)/atmosphere/kip_patches cp stratosphere/boot2/boot2.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008/exefs.nsp
cp -r config_templates/hbl_html atmosphere-$(AMSVER)/atmosphere/hbl_html cp stratosphere/dmnt/dmnt.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D/exefs.nsp
cp stratosphere/boot2/boot2.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008/exefs.nsp cp stratosphere/erpt/erpt.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B/exefs.nsp
cp stratosphere/dmnt/dmnt.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D/exefs.nsp cp stratosphere/eclct.stub/eclct.stub.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/exefs.nsp
cp stratosphere/erpt/erpt.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B/exefs.nsp cp stratosphere/fatal/fatal.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034/exefs.nsp
cp stratosphere/eclct.stub/eclct.stub.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/exefs.nsp cp stratosphere/creport/creport.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036/exefs.nsp
cp stratosphere/fatal/fatal.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034/exefs.nsp cp stratosphere/ro/ro.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/exefs.nsp
cp stratosphere/creport/creport.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036/exefs.nsp cp stratosphere/jpegdec/jpegdec.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C/exefs.nsp
cp stratosphere/ro/ro.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/exefs.nsp cp stratosphere/pgl/pgl.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042/exefs.nsp
cp stratosphere/jpegdec/jpegdec.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C/exefs.nsp mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags
cp stratosphere/pgl/pgl.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042/exefs.nsp touch out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags/boot2.flag
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags
touch atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags/boot2.flag touch out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags/boot2.flag
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags cp troposphere/reboot_to_payload/reboot_to_payload.nro out/atmosphere-$(AMSVER)/switch/reboot_to_payload.nro
touch atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags/boot2.flag cp troposphere/daybreak/daybreak.nro out/atmosphere-$(AMSVER)/switch/daybreak.nro
cp troposphere/reboot_to_payload/reboot_to_payload.nro atmosphere-$(AMSVER)/switch/reboot_to_payload.nro
cp troposphere/daybreak/daybreak.nro atmosphere-$(AMSVER)/switch/daybreak.nro out/atmosphere-EXPERIMENTAL-$(AMSVER): out/atmosphere-$(AMSVER)
cd atmosphere-$(AMSVER); zip -r ../atmosphere-EXPERIMENTAL-$(AMSVER).zip ./*; cd ../; rm -rf out/atmosphere-EXPERIMENTAL-$(AMSVER)
cp fusee/fusee-secondary/fusee-secondary.bin atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin cp -r out/atmosphere-$(AMSVER) out/atmosphere-EXPERIMENTAL-$(AMSVER)
cp fusee/fusee-secondary/fusee-secondary.bin atmosphere-$(AMSVER)/sept/payload.bin cp fusee/fusee-secondary/fusee-secondary.bin out/atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin
cd atmosphere-$(AMSVER); zip -r ../atmosphere-$(AMSVER).zip ./*; cd ../; cp fusee/fusee-secondary/fusee-secondary.bin out/atmosphere-$(AMSVER)/sept/payload.bin
rm -r atmosphere-$(AMSVER)
mkdir out dist-no-debug: out/atmosphere-$(AMSVER) out/atmosphere-EXPERIMENTAL-$(AMSVER)
mv atmosphere-EXPERIMENTAL-$(AMSVER).zip out/atmosphere-EXPERIMENTAL-$(AMSVER).zip cd out/atmosphere-EXPERIMENTAL-$(AMSVER); zip -r ../atmosphere-EXPERIMENTAL-$(AMSVER).zip ./*; cd ../;
mv atmosphere-$(AMSVER).zip out/atmosphere-$(AMSVER).zip cd out/atmosphere-$(AMSVER); zip -r ../atmosphere-$(AMSVER).zip ./*; cd ../;
cp fusee/fusee-primary/fusee-primary.bin out/fusee-primary.bin cp fusee/fusee-primary/fusee-primary.bin out/fusee-primary.bin
dist: dist-no-debug dist: dist-no-debug
$(eval MAJORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MAJOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \
| tr -s [:blank:] \
| cut -d' ' -f3))
$(eval MINORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MINOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \
| tr -s [:blank:] \
| cut -d' ' -f3))
$(eval MICROVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MICRO\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \
| tr -s [:blank:] \
| cut -d' ' -f3))
$(eval AMSVER = $(MAJORVER).$(MINORVER).$(MICROVER)-$(AMSREV))
rm -rf atmosphere-$(AMSVER)-debug rm -rf atmosphere-$(AMSVER)-debug
mkdir atmosphere-$(AMSVER)-debug mkdir atmosphere-$(AMSVER)-debug
cp fusee/fusee-primary/fusee-primary.elf atmosphere-$(AMSVER)-debug/fusee-primary.elf cp fusee/fusee-primary/fusee-primary.elf atmosphere-$(AMSVER)-debug/fusee-primary.elf
cp fusee/fusee-mtc/fusee-mtc.elf atmosphere-$(AMSVER)-debug/fusee-mtc.elf cp fusee/fusee-mtc/fusee-mtc.elf atmosphere-$(AMSVER)-debug/fusee-mtc.elf
cp fusee/fusee-secondary/fusee-secondary-experimental.elf atmosphere-$(AMSVER)-debug/fusee-secondary.elf cp fusee/fusee-secondary/fusee-secondary-experimental.elf atmosphere-$(AMSVER)-debug/fusee-secondary.elf
cp sept/sept-primary/sept-primary.elf atmosphere-$(AMSVER)-debug/sept-primary.elf cp sept/sept-primary/sept-primary.elf atmosphere-$(AMSVER)-debug/sept-primary.elf
cp sept/sept-secondary/sept-secondary.elf atmosphere-$(AMSVER)-debug/sept-secondary.elf cp sept/sept-secondary/sept-secondary.elf atmosphere-$(AMSVER)-debug/sept-secondary.elf || true
cp sept/sept-secondary/key_derivation/key_derivation.elf atmosphere-$(AMSVER)-debug/sept-secondary-key-derivation.elf cp sept/sept-secondary/key_derivation/key_derivation.elf atmosphere-$(AMSVER)-debug/sept-secondary-key-derivation.elf
cp exosphere/loader_stub/loader_stub.elf atmosphere-$(AMSVER)-debug/exosphere-loader-stub.elf cp exosphere/loader_stub/loader_stub.elf atmosphere-$(AMSVER)-debug/exosphere-loader-stub.elf
cp exosphere/program/program.elf atmosphere-$(AMSVER)-debug/exosphere-program.elf cp exosphere/program/program.elf atmosphere-$(AMSVER)-debug/exosphere-program.elf
@ -154,5 +146,25 @@ dist: dist-no-debug
rm -r atmosphere-$(AMSVER)-debug rm -r atmosphere-$(AMSVER)-debug
mv atmosphere-$(AMSVER)-debug.zip out/atmosphere-$(AMSVER)-debug.zip mv atmosphere-$(AMSVER)-debug.zip out/atmosphere-$(AMSVER)-debug.zip
image: out/sd.img
.PHONY: $(TOPTARGETS) $(COMPONENTS) extras:
mkdir -p extras
out/sd.img: out/atmosphere-$(AMSVER) extras
@dd if=/dev/zero of=out/sd.img bs=1M count=64 status=noxfer
@mformat -i out/sd.img -F -v "Atmosphere"
@mkdir -p out/sd/
# rsync is the best solution that:
# copies directory contents without copying directory itself
# doesn't fail on empty directories
# resolves symbolic links (this is useful for symlinking sysmodules into extras/)
rsync -Lr --delete out/atmosphere-$(AMSVER)/ extras/ out/sd/
rsync -Lr extras/ out/sd/
@cd out/sd; mcopy -i ../sd.img -bsQ ./* '::'
@echo 'Produced out/sd.img.'
flash: image
fastboot -S 2G flash sd out/sd.img reboot
.PHONY: $(TOPTARGETS) $(COMPONENTS) dist-no-debug dist image flash

View File

@ -10,3 +10,7 @@ stage2_entrypoint = 0xF0000000
; To force-disable nogc, add nogc = 0 ; To force-disable nogc, add nogc = 0
; To opt out of using Atmosphere's NCM reimplementation, add disable_ncm = 1 ; To opt out of using Atmosphere's NCM reimplementation, add disable_ncm = 1
[fastboot]
force_enable = 0
button_timeout_ms = 0

View File

@ -5,14 +5,17 @@ define ATMOSPHERE_ADD_TARGET
ATMOSPHERE_BUILD_CONFIGS += $(strip $1) ATMOSPHERE_BUILD_CONFIGS += $(strip $1)
$(strip $1): exosphere$(strip $2).bin check_warmboot_$(strip $1) $(strip $1): exosphere$(strip $2).bin warmboot$(strip $2).bin
@cp warmboot/warmboot$(strip $2).bin warmboot$(strip $2).bin
exosphere$(strip $2).bin: loader_stub/loader_stub$(strip $2).bin exosphere$(strip $2).bin: loader_stub/loader_stub$(strip $2).bin
@cp loader_stub/loader_stub$(strip $2).bin exosphere$(strip $2).bin @cp loader_stub/loader_stub$(strip $2).bin exosphere$(strip $2).bin
@printf LENY >> exosphere$(strip $2).bin @printf LENY >> exosphere$(strip $2).bin
@echo "Built exosphere$(strip $2).bin..." @echo "Built exosphere$(strip $2).bin..."
warmboot$(strip $2).bin: warmboot/warmboot$(strip $2).bin
@cp warmboot/warmboot$(strip $2).bin warmboot$(strip $2).bin
@echo "Built warmboot$(strip $2).bin..."
check_program_$(strip $1): check_program_$(strip $1):
@$$(MAKE) -C program $(strip $1) @$$(MAKE) -C program $(strip $1)
@ -22,6 +25,8 @@ check_warmboot_$(strip $1):
loader_stub/loader_stub$(strip $2).bin: check_program_$(strip $1) loader_stub/loader_stub$(strip $2).bin: check_program_$(strip $1)
@$$(MAKE) -C loader_stub $(strip $1) @$$(MAKE) -C loader_stub $(strip $1)
warmboot/warmboot$(strip $2).bin: check_warmboot_$(strip $1)
clean-$(strip $1): clean-program-$(strip $1) clean-loader_stub-$(strip $1) clean-warmboot-$(strip $1) clean-$(strip $1): clean-program-$(strip $1) clean-loader_stub-$(strip $1) clean-warmboot-$(strip $1)
@rm -rf exosphere$(strip $2).bin warmboot$(strip $2).bin @rm -rf exosphere$(strip $2).bin warmboot$(strip $2).bin

View File

@ -27,7 +27,7 @@ endif
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR)) TARGET := $(notdir $(CURDIR))
BUILD := build BUILD := build
SOURCES := src src/sdmmc src/lib src/lib/fatfs src/display SOURCES := src src/sdmmc src/lib src/lib/fatfs src/display src/fastboot
DATA := data DATA := data
INCLUDES := include ../../libraries/libvapours/include INCLUDES := include ../../libraries/libvapours/include
@ -39,11 +39,10 @@ DEFINES := -D__BPMP__ -DFUSEE_STAGE1_SRC -DATMOSPHERE_GIT_BRANCH=\"$(AMSBRANCH)\
CFLAGS := \ CFLAGS := \
-g \ -g \
-O2 \ -Os \
-fomit-frame-pointer \ -fomit-frame-pointer \
-ffunction-sections \ -ffunction-sections \
-fdata-sections \ -fdata-sections \
-std=gnu11 \
-Werror \ -Werror \
-Wall \ -Wall \
-fstrict-volatile-bitfields \ -fstrict-volatile-bitfields \
@ -51,7 +50,7 @@ CFLAGS := \
CFLAGS += $(INCLUDE) CFLAGS += $(INCLUDE)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11 CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=c++2a
ASFLAGS := -g $(ARCH) ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(TOPDIR)/linker.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) LDFLAGS = -specs=$(TOPDIR)/linker.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)

View File

@ -15,6 +15,7 @@ MEMORY
NULL : ORIGIN = 0x00000000, LENGTH = 0x1000 NULL : ORIGIN = 0x00000000, LENGTH = 0x1000
main : ORIGIN = 0x40010000, LENGTH = 0x20000 main : ORIGIN = 0x40010000, LENGTH = 0x20000
low_iram : ORIGIN = 0x40003000, LENGTH = 0x8000 low_iram : ORIGIN = 0x40003000, LENGTH = 0x8000
dram : ORIGIN = 0xC0000000, LENGTH = 0x40000000
} }
SECTIONS SECTIONS
@ -150,6 +151,16 @@ SECTIONS
} >main :NONE } >main :NONE
__end__ = ABSOLUTE(.) ; __end__ = ABSOLUTE(.) ;
.dram (NOLOAD) :
{
. = ALIGN(32);
PROVIDE (__dram_start__ = ABSOLUTE(.));
*(.framebuffer)
*(.dram)
. = ALIGN(32);
PROVIDE (__dram_end__ = ABSOLUTE(.));
} >dram :NONE
/* ================== /* ==================
==== Metadata ==== ==== Metadata ====
================== */ ================== */

View File

@ -0,0 +1,99 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bct0.h"
#include "lib/ini.h"
#include <string.h>
#define CONFIG_LOG_LEVEL_KEY "log_level"
#define STAGE2_NAME_KEY "stage2_path"
#define STAGE2_MTC_NAME_KEY "stage2_mtc_path"
#define STAGE2_ADDRESS_KEY "stage2_addr"
#define STAGE2_ENTRYPOINT_KEY "stage2_entrypoint"
#define FASTBOOT_FORCE_ENABLE_KEY "force_enable"
#define FASTBOOT_BUTTON_TIMEOUT_KEY "button_timeout_ms"
static int bct0_ini_handler(void *user, const char *section, const char *name, const char *value) {
bct0_t *bct0 = (bct0_t*) user;
if (strcmp(section, "config") == 0) {
if (strcmp(name, CONFIG_LOG_LEVEL_KEY) == 0) {
int log_level = bct0->log_level;
sscanf(value, "%d", &log_level);
bct0->log_level = (ScreenLogLevel) log_level;
} else {
return 0;
}
} else if (strcmp(section, "stage1") == 0) {
if (strcmp(name, STAGE2_NAME_KEY) == 0) {
strncpy(bct0->stage2_path, value, sizeof(bct0->stage2_path) - 1);
bct0->stage2_path[sizeof(bct0->stage2_path) - 1] = '\0';
} else if (strcmp(name, STAGE2_MTC_NAME_KEY) == 0) {
strncpy(bct0->stage2_mtc_path, value, sizeof(bct0->stage2_mtc_path) - 1);
bct0->stage2_mtc_path[sizeof(bct0->stage2_mtc_path) - 1] = '\0';
} else if (strcmp(name, STAGE2_ADDRESS_KEY) == 0) {
/* Read in load address as a hex string. */
uintptr_t x;
sscanf(value, "%x", &x);
bct0->stage2_load_address = x;
if (bct0->stage2_entrypoint == 0) {
bct0->stage2_entrypoint = bct0->stage2_load_address;
}
} else if (strcmp(name, STAGE2_ENTRYPOINT_KEY) == 0) {
/* Read in entrypoint as a hex string. */
uintptr_t x;
sscanf(value, "%x", &x);
bct0->stage2_entrypoint = x;
} else {
return 0;
}
} else if (strcmp(section, "fastboot") == 0) {
if (strcmp(name, FASTBOOT_FORCE_ENABLE_KEY) == 0) {
int tmp = 0;
sscanf(value, "%d", &tmp);
bct0->fastboot_force_enable = (tmp != 0);
} else if (strcmp(name, FASTBOOT_BUTTON_TIMEOUT_KEY) == 0) {
int tmp = 0;
sscanf(value, "%d", &tmp);
bct0->fastboot_button_timeout = tmp;
} else {
return 0;
}
} else {
return 0;
}
return 1;
}
int bct0_parse(const char *ini, bct0_t *out) {
/* Initialize some default configuration. */
out->log_level = SCREEN_LOG_LEVEL_NONE;
strcpy(out->stage2_path, "atmosphere/fusee-secondary.bin");
strcpy(out->stage2_mtc_path, "atmosphere/fusee-mtc.bin");
out->stage2_load_address = 0xf0000000;
out->stage2_entrypoint = 0xf0000000;
out->fastboot_force_enable = false;
out->fastboot_button_timeout = 3000;
return ini_parse_string(ini, bct0_ini_handler, out);
}

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FUSEE_BCT0_H
#define FUSEE_BCT0_H
#include <stdint.h>
#include <stdbool.h>
#include "lib/log.h"
#define BCTO_MAX_SIZE 0x5800
typedef struct {
/* [config] */
ScreenLogLevel log_level;
/* [stage1] */
char stage2_path[0x100];
char stage2_mtc_path[0x100];
uintptr_t stage2_load_address;
uintptr_t stage2_entrypoint;
/* [fastboot] */
bool fastboot_force_enable;
int fastboot_button_timeout;
} bct0_t;
int bct0_parse(const char *ini, bct0_t *out);
#endif

View File

@ -0,0 +1,84 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fastboot.h"
#include "fastboot_gadget.h"
extern "C" {
#include "../lib/log.h"
#include "../timers.h"
#include "../utils.h"
#include "../btn.h"
}
static ams::fastboot::FastbootGadget fastboot_gadget((uint8_t*) 0xf0000000, 1024 * 1024 * 256); // 256 MiB download buffer reaches end of address space
extern "C" fastboot_return fastboot_enter(const bct0_t *bct0, bool force) {
bool should_enter = force || bct0->fastboot_force_enable;
if(should_enter) {
log_setup_display();
} else {
if (bct0->fastboot_button_timeout > 0) {
log_setup_display();
uint32_t timeout = bct0->fastboot_button_timeout;
uint32_t start_time = get_time_ms();
uint32_t last_message_secs = 0;
while (get_time_ms() - start_time < timeout) {
uint32_t seconds_remaining = (start_time + timeout - get_time_ms() + 999) / 1000;
if (seconds_remaining != last_message_secs) {
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "\rPress volume up in %d seconds to enter fastboot. ", seconds_remaining);
last_message_secs = seconds_remaining;
}
if (btn_read() & BTN_VOL_UP) {
should_enter = true;
break;
}
}
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "\n\n");
if (!should_enter) {
log_cleanup_display();
return FASTBOOT_SKIPPED;
}
} else {
/* We did not initialize the display, so don't need to clean it up here. */
return FASTBOOT_SKIPPED;
}
}
print(SCREEN_LOG_LEVEL_DEBUG, "Entering fastboot. (forced = %d)\n", force);
ams::xusb::Initialize();
print(SCREEN_LOG_LEVEL_DEBUG, "Finished initializing USB hardware.\n");
ams::xusb::EnableDevice(fastboot_gadget);
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "Fastboot mode:\n");
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "-------------------------------\n");
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "Volume up: Reboot to RCM.\n");
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "Volume down: Boot normally.\n");
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "POWER: Reboot to fusee-primary.\n");
fastboot_return r = fastboot_gadget.Run();
log_cleanup_display();
return r;
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "../bct0.h"
enum fastboot_return {
FASTBOOT_INVALID,
FASTBOOT_SKIPPED,
FASTBOOT_LOAD_STAGE2,
FASTBOOT_CHAINLOAD,
};
enum fastboot_return fastboot_enter(const bct0_t *bct0, bool force);
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,192 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace ams {
namespace fastboot {
namespace descriptors {
USB_DECLARE_STRING_DESCRIPTOR(langid, u"\x0409"); // English (US)
USB_DECLARE_STRING_DESCRIPTOR(manu, u"Atmosphère");
USB_DECLARE_STRING_DESCRIPTOR(product, u"Fusée Fastboot Gadget");
USB_DECLARE_STRING_DESCRIPTOR(serial, u"Serial Number");
USB_DECLARE_STRING_DESCRIPTOR(configuration, u"Fastboot");
USB_DECLARE_STRING_DESCRIPTOR(interface, u"Fastboot");
static constexpr usb::StringDescriptorIndexer<SD_langid,
SD_manu,
SD_product,
SD_serial,
SD_configuration,
SD_interface> sd_indexer;
static constexpr usb::DeviceDescriptor device_descriptor = {
{
.bLength = sizeof(usb::DeviceDescriptor),
.bDescriptorType = usb::DescriptorType::DEVICE,
},
{
.bcdUSB = 0x210,
.bDeviceClass = 0,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
.bMaxPacketSize0 = 64,
.idVendor = 0x1209,
.idProduct = 0x8b01,
.bcdDevice = 0x100,
.iManufacturer = sd_indexer.manu,
.iProduct = sd_indexer.product,
.iSerialNumber = sd_indexer.serial,
.bNumConfigurations = 1,
}
};
static constexpr usb::DeviceQualifierDescriptor device_qualifier_descriptor = {
{
.bLength = sizeof(usb::DeviceQualifierDescriptor),
.bDescriptorType = usb::DescriptorType::DEVICE_QUALIFIER,
},
{
.bcdUSB = 0x210,
.bDeviceClass = 0,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
.bMaxPacketSize0 = 64,
.bNumConfigurations = 1,
.bReserved = 0,
}
};
static constexpr struct WholeConfigurationDescriptor {
usb::ConfigurationDescriptor configuration_descriptor = {
{
.bLength = sizeof(usb::ConfigurationDescriptor),
.bDescriptorType = usb::DescriptorType::CONFIGURATION,
},
{
.wTotalLength = sizeof(WholeConfigurationDescriptor),
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = 4,
.bmAttributes = 0x80,
.bMaxPower = 0,
}
};
usb::InterfaceDescriptor interface_descriptor {
{
.bLength = sizeof(usb::InterfaceDescriptor),
.bDescriptorType = usb::DescriptorType::INTERFACE,
},
{
.bInterfaceNumber = 0,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = 0xff, // Vendor Specific Class.
.bInterfaceSubClass = 0x42, // Fastboot.
.bInterfaceProtocol = 0x03, // Fastboot.
.iInterface = 5,
}
};
usb::EndpointDescriptor endpoint_in_descriptor {
{
.bLength = sizeof(usb::EndpointDescriptor),
.bDescriptorType = usb::DescriptorType::ENDPOINT,
},
{
.bEndpointAddress = 0x81,
.bmAttributes = 0x2,
.wMaxPacketSize = 512,
.bInterval = 1,
}
};
usb::EndpointDescriptor endpoint_out_descriptor {
{
.bLength = sizeof(usb::EndpointDescriptor),
.bDescriptorType = usb::DescriptorType::ENDPOINT,
},
{
.bEndpointAddress = 0x01,
.bmAttributes = 0x2,
.wMaxPacketSize = 512,
.bInterval = 1,
}
};
} __attribute__((packed)) whole_configuration_descriptor;
static const uint8_t bMS_VendorCode = 37; /* chosen by fair dice roll */
/* This helps Windows figure out that it should use the ADB driver with our device without having to get a driver package signed. */
static constexpr struct {
usb::ms::os20::DescriptorSetHeader descriptor_set_header1 = {
.wLength = sizeof(usb::ms::os20::DescriptorSetHeader),
.wDescriptorType = usb::ms::os20::DescriptorType::SetHeaderDescriptor,
.dwWindowsVersion = usb::ms::NTDDI_WIN8_1,
.wTotalLength = sizeof(*this),
};
/* https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/automatic-installation-of-winusb#how-to-configure-a-winusb-device */
usb::ms::os20::FeatureCompatibleID feature_compatible_id = usb::ms::os20::FeatureCompatibleID("WINUSB", "");
/* https://android.googlesource.com/platform/development/+/8c78ba643862731c603677284ae88089a959cc52/host/windows/usb/api/adb_api_extra.h#64 */
usb::ms::os20::FeatureRegistryProperty<usb::ms::os20::PropertyDataType::REG_SZ, u"DeviceInterfaceGUID", u"{F72FE0D4-CBCB-407d-8814-9ED673D0DD6B}"> feature_registry_device_interface_guid;
} __attribute__((packed)) ms_os20_descriptor;
static constexpr auto bos_container = usb::make_bos_descriptor_container(usb::caps::USB_2_0_EXTENSION {
{
{
.bLength = sizeof(usb::caps::USB_2_0_EXTENSION),
.bDescriptorType = usb::DescriptorType::DEVICE_CAPABILITY,
},
{
.bDevCapabilityType = usb::DeviceCapabilityType::USB_2_0_EXTENSION,
}
},
{
.bmAttributes = 0,
}
}, usb::caps::SUPERSPEED {
{
{
.bLength = sizeof(usb::caps::SUPERSPEED),
.bDescriptorType = usb::DescriptorType::DEVICE_CAPABILITY,
},
{
.bDevCapabilityType = usb::DeviceCapabilityType::SUPERSPEED_USB,
}
},
{
.bmAttributes = 0,
.wSpeedsSupported = 0b1111,
.bFunctionalitySupport = 1,
.bU1DevExitLat = 0,
.wU2DevExitLat = 0
}
}, usb::caps::make_platform_capability(
/* Indicate to Windows hosts that they can retrieve their OS-specific descriptor through a special vendor-specific request. */
usb::ms::DescriptorSetInformation {
.dwWindowsVersion = usb::ms::NTDDI_WIN8_1,
.wMSOSDescriptorSetTotalLength = sizeof(ms_os20_descriptor),
.bMS_VendorCode = bMS_VendorCode,
.bAltEnumCode = 0,
})
);
} // namespace descriptors
} // namespace fastboot
} // namespace ams

View File

@ -0,0 +1,402 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fastboot_gadget.h"
#include "fastboot.h"
#include "xusb.h"
#include "xusb_control.h"
#include "xusb_endpoint.h"
extern "C" {
#include "../lib/log.h"
#include "../lib/vsprintf.h"
#include "../utils.h"
#include "../btn.h"
}
#include "fastboot_descriptors.inc"
#include<vapours/util/util_scope_guard.hpp>
#include<algorithm>
#include<cstdarg>
namespace ams {
namespace fastboot {
namespace {
xusb::TRB in_ring[5];
xusb::TRB out_ring[5];
namespace ep {
static constexpr auto out = xusb::endpoints[xusb::EpAddr {1, xusb::Dir::Out}];
static constexpr auto in = xusb::endpoints[xusb::EpAddr {1, xusb::Dir::In}];
}
} // anonymous namespace
FastbootGadget::FastbootGadget(uint8_t *download_buffer, size_t download_buffer_size) :
impl(*this),
download_buffer(download_buffer),
download_buffer_size(download_buffer_size) {
}
fastboot_return FastbootGadget::Run() {
bool usb_error = false;
uint32_t last_button = btn_read();
while (this->state < State::Exit || usb_error) {
if (!usb_error) {
xusb::Process();
}
if (this->state == State::UsbError && !usb_error) {
print((ScreenLogLevel) (SCREEN_LOG_LEVEL_NONE | SCREEN_LOG_LEVEL_NO_PREFIX), "\nFastboot encountered a USB error (0x%x).\nPress one of the buttons listed above to continue.\n", this->usb_error.GetValue());
usb_error = true;
}
uint32_t button = btn_read();
if (button & BTN_VOL_UP && !(last_button & BTN_VOL_UP)) {
/* Reboot to RCM. */
pmc_reboot(0);
return FASTBOOT_INVALID;
}
if (button & BTN_VOL_DOWN && !(last_button & BTN_VOL_DOWN)) {
/* Boot normally. */
print(SCREEN_LOG_LEVEL_INFO, "Booting normally.\n");
return FASTBOOT_LOAD_STAGE2;
}
if (button & BTN_POWER && !(last_button & BTN_POWER)) {
/* Reboot to fusee-primary. */
reboot_to_self();
return FASTBOOT_INVALID;
}
last_button = button;
}
switch(this->state) {
case State::Exit:
return FASTBOOT_LOAD_STAGE2;
case State::Reboot:
reboot_to_self();
return FASTBOOT_INVALID;
case State::Chainload:
return FASTBOOT_CHAINLOAD;
default:
return FASTBOOT_INVALID;
}
}
void FastbootGadget::FormatResponse(ResponseToken token, const char *fmt, std::va_list args) {
const char *token_str = nullptr;
switch(token) {
case ResponseToken::OKAY:
token_str = "OKAY";
break;
case ResponseToken::INFO:
token_str = "INFO";
break;
case ResponseToken::FAIL:
token_str = "FAIL";
break;
case ResponseToken::DATA:
token_str = "DATA";
break;
}
strcpy(this->response_buffer, token_str);
vsnprintf(this->response_buffer + 4, sizeof(this->response_buffer) - 4, fmt, args);
}
Result FastbootGadget::SendResponse(ResponseDisposition disposition, ResponseToken token, const char *fmt, ...) {
std::va_list args;
va_start(args, fmt);
FormatResponse(token, fmt, args);
va_end(args);
R_TRY(ep::in.TransferNormal((void*) this->response_buffer, strlen(this->response_buffer), &last_trb));
this->response_disposition = disposition;
this->state = State::SendingResponse;
return ResultSuccess();
}
static const size_t max_trb_size = 0x10000; // 64 KiB
Result FastbootGadget::PrepareDownload(size_t size) {
R_UNLESS(size <= this->download_buffer_size, xusb::ResultDownloadTooLarge());
this->download_head = 0;
this->download_size = size;
this->download_needs_zlp = (size % max_trb_size) == 0;
return ResultSuccess();
}
size_t FastbootGadget::GetMaxDownloadSize() const {
return this->download_buffer_size;
}
size_t FastbootGadget::GetLastDownloadSize() const {
return this->download_size;
}
void *FastbootGadget::GetLastDownloadBuffer() const {
return this->download_buffer;
}
Result FastbootGadget::ReadHostCommand() {
R_TRY(ep::out.TransferNormal((void*) this->command_buffer, 64, &last_trb));
this->state = State::WaitingForHostCommand;
return ResultSuccess();
}
Result FastbootGadget::QueueTRBsForReceive() {
xusb::TRBBorrow trb;
bool has_queued_any = false;
while (ep::out.GetFreeTRBCount() > 0 && (this->download_head < this->download_size || this->download_needs_zlp)) {
size_t remaining_in_download = this->download_size - this->download_head;
size_t num_trbs_remaining = (remaining_in_download + max_trb_size - 1) / max_trb_size;
if (this->download_needs_zlp) {
num_trbs_remaining++;
}
size_t td_size = std::min(std::min(num_trbs_remaining, (size_t) 32), (size_t) 32) - 1;
/* Attempt to queue a TRB. */
size_t attempted_size = std::min(remaining_in_download, max_trb_size);
/* If TRBBorrow is already holding a TRB, it will be queued implicitly when EnqueueTRB overwrites it. */
R_TRY(ep::out.EnqueueTRB(&trb, num_trbs_remaining > 0));
R_UNLESS(&*trb != nullptr, xusb::ResultTransferRingFull());
trb->transfer.InitializeNormal(download_buffer + download_head, attempted_size);
if (td_size > 0) {
trb->transfer.chain_bit = 1;
trb->transfer.td_size = td_size;
}
if (attempted_size == 0) {
this->download_needs_zlp = false;
} else {
this->download_head+= attempted_size;
}
has_queued_any = true;
}
if (has_queued_any) {
trb->transfer.interrupt_on_completion = true;
trb->transfer.interrupt_on_short_packet = true;
trb.Release();
if (this->download_head == this->download_size && !this->download_needs_zlp) {
last_trb = &*trb;
}
this->state = State::DataPhaseReceive;
ep::out.RingDoorbell();
}
return ResultSuccess();
}
/* xusb::Gadget implementation */
Result FastbootGadget::ProcessTransferEventImpl(xusb::TransferEventTRB *event, xusb::TRBBorrow transfer) {
if (event->completion_code != 1 && event->completion_code != 13) { // success or short packet
print(SCREEN_LOG_LEVEL_DEBUG, "failing due to transfer completion with bad code %d\n", event->completion_code);
return xusb::ResultUnexpectedCompletionCode();
}
switch(this->state) {
case State::WaitingForHostCommand:
R_UNLESS(event->ep_id == ep::out.GetIndex(), xusb::ResultUnexpectedEndpoint());
R_UNLESS(&*transfer == this->last_trb, xusb::ResultUnexpectedTRB());
{
size_t received_size = transfer->transfer.transfer_length - event->trb_transfer_length;
this->command_buffer[received_size] = 0;
return this->impl.ProcessCommand(this->command_buffer);
}
case State::SendingResponse:
R_UNLESS(event->ep_id == ep::in.GetIndex(), xusb::ResultUnexpectedEndpoint());
R_UNLESS(&*transfer == this->last_trb, xusb::ResultUnexpectedTRB());
switch(this->response_disposition) {
case ResponseDisposition::ReadHostCommand:
return this->ReadHostCommand();
case ResponseDisposition::Download:
this->last_trb = nullptr;
return this->QueueTRBsForReceive();
case ResponseDisposition::Okay:
return this->SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::OKAY, "");
case ResponseDisposition::Continue:
this->state = State::Continuing;
return this->impl.Continue();
case ResponseDisposition::Reboot:
this->state = State::Reboot;
return ResultSuccess();
case ResponseDisposition::Chainload:
this->state = State::Chainload;
return ResultSuccess();
default:
return ResultSuccess();
}
case State::DataPhaseReceive:
R_UNLESS(event->ep_id == ep::out.GetIndex(), xusb::ResultUnexpectedEndpoint());
/* Release completed TRBs back to ring early so we can reuse them. */
transfer.Release();
if (&*transfer == last_trb) {
return this->SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::OKAY, "");
} else {
return this->QueueTRBsForReceive();
}
case State::DataPhaseTransmit:
/* TODO, if we ever implement a command that involves sending data. */
return ResultSuccess();
case State::Continuing:
return this->impl.Continue();
default:
return ResultSuccess();
}
}
void FastbootGadget::ProcessTransferEvent(xusb::TransferEventTRB *trb, xusb::TRBBorrow transfer) {
Result r = this->ProcessTransferEventImpl(trb, std::move(transfer));
if (r.IsFailure()) {
print(SCREEN_LOG_LEVEL_ERROR, "fastboot error while processing transfer event: 0x%x\n", r.GetValue());
this->state = State::UsbError;
this->usb_error = r;
}
}
Result FastbootGadget::HandleSetupRequest(usb::SetupPacket &packet) {
if (packet.bmRequestType == usb::SetupPacket::PackRequestType(
usb::SetupPacket::RequestDirection::DeviceToHost,
usb::SetupPacket::RequestType::Vendor,
usb::SetupPacket::RequestRecipient::Device) &&
packet.bRequest == descriptors::bMS_VendorCode) {
/* Retrieve MS OS 2.0 vendor-specific descriptor */
R_UNLESS(packet.wValue == 0, xusb::ResultMalformedSetupRequest());
R_UNLESS(packet.wIndex == usb::ms::MS_OS_20_DESCRIPTOR_INDEX, xusb::ResultMalformedSetupRequest());
uint16_t actual_length = sizeof(descriptors::ms_os20_descriptor);
if (actual_length > packet.wLength) {
actual_length = packet.wLength;
}
return xusb::control::SendData((void*) &descriptors::ms_os20_descriptor, actual_length);
}
return xusb::ResultUnknownSetupRequest();
}
Result FastbootGadget::GetDeviceDescriptor(uint8_t index, const usb::DeviceDescriptor **descriptor, uint16_t *length) {
R_UNLESS(index == 0, xusb::ResultInvalidDescriptorIndex());
*descriptor = &descriptors::device_descriptor;
*length = sizeof(descriptors::device_descriptor);
return ResultSuccess();
}
Result FastbootGadget::GetDeviceQualifierDescriptor(uint8_t index, const usb::DeviceQualifierDescriptor **descriptor, uint16_t *length) {
R_UNLESS(index == 0, xusb::ResultInvalidDescriptorIndex());
*descriptor = &descriptors::device_qualifier_descriptor;
*length = sizeof(descriptors::device_qualifier_descriptor);
return ResultSuccess();
}
Result FastbootGadget::GetConfigurationDescriptor(uint8_t index, const usb::ConfigurationDescriptor **descriptor, uint16_t *length) {
R_UNLESS(index == 0, xusb::ResultInvalidDescriptorIndex());
*descriptor = &descriptors::whole_configuration_descriptor.configuration_descriptor;
*length = sizeof(descriptors::whole_configuration_descriptor);
return ResultSuccess();
}
Result FastbootGadget::GetBOSDescriptor(const usb::BOSDescriptor **descriptor, uint16_t *length) {
*descriptor = &descriptors::bos_container.bos_descriptor;
*length = sizeof(descriptors::bos_container);
return ResultSuccess();
}
Result FastbootGadget::GetStringDescriptor(uint8_t index, uint16_t language, const usb::CommonDescriptor **descriptor, uint16_t *length) {
R_UNLESS(language == 0x0409 || (language == 0 && index == 0), xusb::ResultInvalidDescriptorIndex());
R_UNLESS(descriptors::sd_indexer.GetStringDescriptor(index, language, descriptor, length), xusb::ResultInvalidDescriptorIndex());
return ResultSuccess();
}
Result FastbootGadget::SetConfiguration(uint16_t configuration) {
R_UNLESS(configuration <= 1, xusb::ResultInvalidConfiguration());
xusb::endpoints.ClearNonControlEndpoints();
ep::out.Initialize(descriptors::whole_configuration_descriptor.endpoint_out_descriptor, out_ring, std::size(out_ring));
ep::in .Initialize(descriptors::whole_configuration_descriptor.endpoint_in_descriptor, in_ring, std::size(in_ring));
return ResultSuccess();
}
Result FastbootGadget::Deconfigure() {
ep::out.Disable();
ep::in.Disable();
return ResultSuccess();
}
void FastbootGadget::PostConfigure() {
this->state = State::Invalid;
ReadHostCommand();
}
} // namespace fastboot
} // namespace ams

View File

@ -0,0 +1,116 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "xusb.h"
#include "fastboot.h"
#include "fastboot_impl.h"
#include<cstdarg>
namespace ams {
namespace fastboot {
class FastbootGadget : public xusb::Gadget {
public:
FastbootGadget(uint8_t *download_buffer, size_t download_buffer_size);
enum class ResponseDisposition {
ReadHostCommand,
/* After this response completes, begin receive data phase. */
Download,
/* After this response completes, send an empty OKAY response with
* ReadHostCommand disposition. */
Okay,
/* After this response completes, call impl.Continue(). */
Continue,
Reboot,
Chainload,
} response_disposition;
enum class ResponseToken {
OKAY,
INFO,
FAIL,
DATA,
};
fastboot_return Run();
Result SendResponse(ResponseDisposition disposition, ResponseToken token, const char *fmt, ...);
Result PrepareDownload(size_t size);
size_t GetMaxDownloadSize() const;
size_t GetLastDownloadSize() const;
void *GetLastDownloadBuffer() const;
private:
void FormatResponse(ResponseToken token, const char *fmt, std::va_list args);
Result ReadHostCommand();
Result QueueTRBsForReceive();
FastbootImpl impl;
enum class State {
Invalid,
WaitingForHostCommand,
SendingResponse,
DataPhaseReceive,
DataPhaseTransmit,
Continuing,
Exit,
UsbError,
Reboot,
Chainload,
} state;
Result usb_error;
uint8_t *download_buffer;
size_t download_buffer_size;
size_t download_head;
size_t download_size;
bool download_needs_zlp;
int download_active_trbs;
char command_buffer[65];
char response_buffer[65];
xusb::TRB *last_trb = nullptr;
private:
/* xusb::Gadget implementation */
Result ProcessTransferEventImpl(xusb::TransferEventTRB *event, xusb::TRBBorrow transfer);
virtual void ProcessTransferEvent(xusb::TransferEventTRB *event, xusb::TRBBorrow transfer) override;
virtual Result HandleSetupRequest(usb::SetupPacket &packet) override;
virtual Result GetDeviceDescriptor(uint8_t index, const usb::DeviceDescriptor **descriptor, uint16_t *length) override;
virtual Result GetDeviceQualifierDescriptor(uint8_t index, const usb::DeviceQualifierDescriptor **descriptor, uint16_t *length) override;
virtual Result GetConfigurationDescriptor(uint8_t index, const usb::ConfigurationDescriptor **descriptor, uint16_t *length) override;
virtual Result GetBOSDescriptor(const usb::BOSDescriptor **descriptor, uint16_t *length) override;
virtual Result GetStringDescriptor(uint8_t index, uint16_t language, const usb::CommonDescriptor **descriptor, uint16_t *length) override;
virtual Result SetConfiguration(uint16_t configuration) override;
virtual Result Deconfigure() override;
virtual void PostConfigure() override;
};
} // namespace fastboot
} // namespace ams

View File

@ -0,0 +1,392 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fastboot.h"
#include "fastboot_gadget.h"
#include "../lib/miniz.h"
extern "C" {
#include "../lib/log.h"
#include "../utils.h"
#include "../fs_utils.h"
#include "../sdmmc/sdmmc.h"
#include "../chainloader.h"
#include "../lib/fatfs/ff.h"
}
#include<array>
#include<stdio.h>
#include<vapours/util/util_scope_guard.hpp>
uint32_t crc32(uint32_t crc, const uint8_t *buf, size_t len) {
int k;
crc = ~crc;
while (len--) {
crc ^= *buf++;
for (k = 0; k < 8; k++)
crc = crc & 1 ? (crc >> 1) ^ 0xedb88320 : crc >> 1;
}
return ~crc;
}
struct android_boot_image_v2 {
// version 0
uint8_t magic[8];
uint32_t kernel_size;
uint32_t kernel_addr;
uint32_t ramdisk_size;
uint32_t ramdisk_addr;
uint32_t second_size;
uint32_t second_addr;
uint32_t tags_addr;
uint32_t page_size;
uint32_t header_version;
uint32_t os_version;
uint8_t name[16];
uint8_t cmdline[512];
uint32_t id[8];
uint8_t extra_cmdline[1024];
// version 1
uint32_t recovery_dtbo_size;
uint64_t recovery_dtbo_offset;
uint32_t header_size;
// version 2
uint32_t dtb_size;
uint64_t dtb_addr;
} __attribute__((packed));
/* Simple bump heap for zip extraction. */
struct MzHeap {
public:
static void Reset() {
heap_head = heap;
}
static void *Alloc(void *opaque, size_t items, size_t size) {
if (heap_head + items * size > heap + sizeof(heap)) {
return nullptr;
} else {
uint8_t *ret = heap_head;
heap_head+= items * size;
return ret;
}
}
static void Free(void *opaque, void *addr) {
/* No-op. */
}
static void *Realloc(void *opaque, void *addr, size_t items, size_t size) {
void *new_allocation = Alloc(opaque, items, size);
memmove(new_allocation, addr, items * size);
return new_allocation;
}
private:
static inline uint8_t heap[8 * 1024 * 1024] __attribute__((section(".dram")));
static inline uint8_t *heap_head;
};
namespace ams {
namespace fastboot {
using ResponseDisposition = FastbootGadget::ResponseDisposition;
using ResponseToken = FastbootGadget::ResponseToken;
FastbootImpl::FastbootImpl(FastbootGadget &gadget) : gadget(gadget) {
}
Result FastbootImpl::ProcessCommand(char *command_buffer) {
print(SCREEN_LOG_LEVEL_DEBUG, "got host command: '%s'\n", command_buffer);
const char *argument = nullptr;
for (size_t i = 0; command_buffer[i] != 0; i++) {
if (command_buffer[i] == ':') {
command_buffer[i] = 0;
argument = command_buffer + i + 1;
break;
}
}
if (!strcmp(command_buffer, "getvar")) {
return this->GetVar(argument);
} else if (!strcmp(command_buffer, "download")) {
return this->Download(argument);
} else if (!strcmp(command_buffer, "flash")) {
return this->Flash(argument);
} else if (!strcmp(command_buffer, "reboot")) {
return this->Reboot(argument);
} else if (!strcmp(command_buffer, "boot")) {
return this->Boot(argument);
} else if (!strcmp(command_buffer, "oem crc32")) {
return this->OemCRC32(argument);
} else {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "unknown command: %s", command_buffer);
}
}
Result FastbootImpl::GetVar(const char *argument) {
if (strcmp(argument, "version") == 0) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::OKAY, "0.4");
} else if (strcmp(argument, "product") == 0) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::OKAY, "Fusée Fastboot");
} else if (strcmp(argument, "max-download-size") == 0) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::OKAY, "%08X", this->gadget.GetMaxDownloadSize());
} else {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "unknown variable");
}
}
Result FastbootImpl::Download(const char *argument) {
bool parsed_ok = true;
uint32_t download_size = 0;
for (int i = 0; i < 8; i++) {
download_size<<= 4;
char ch = argument[i];
if (ch >= '0' && ch <= '9') {
download_size|= ch - '0';
} else if (ch >= 'a' && ch <= 'f') {
download_size|= (ch - 'a') + 0xa;
} else if (ch >= 'A' && ch <= 'F') {
download_size|= (ch - 'A') + 0xa;
} else {
parsed_ok = false;
break;
}
}
if (!parsed_ok) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "failed to parse download size");
}
R_TRY_CATCH(gadget.PrepareDownload(download_size)) {
R_CATCH(xusb::ResultDownloadTooLarge) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "download size too large");
}
} R_END_TRY_CATCH;
return this->gadget.SendResponse(ResponseDisposition::Download, ResponseToken::DATA, "%08X", download_size);
}
Result FastbootImpl::Flash(const char *argument) {
if (!strcmp(argument, "ams")) {
memset(&this->flash_ams.zip, 0, sizeof(this->flash_ams.zip));
this->flash_ams.zip.m_pAlloc = &MzHeap::Alloc;
this->flash_ams.zip.m_pFree = &MzHeap::Free;
this->flash_ams.zip.m_pRealloc = &MzHeap::Realloc;
MzHeap::Reset();
if (!mz_zip_reader_init_mem(&this->flash_ams.zip, this->gadget.GetLastDownloadBuffer(), this->gadget.GetLastDownloadSize(), 0)) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "failed to initialize zip reader");
}
if (!mount_sd()) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "failed to mount sd card");
}
this->flash_ams.num_files = mz_zip_reader_get_num_files(&this->flash_ams.zip);
this->flash_ams.file_index = 0;
this->flash_ams.error = nullptr;
this->current_action = Action::FlashAms;
return this->ContinueFlashAms();
} else if (!strcmp(argument, "sd")) {
if (this->gadget.GetLastDownloadSize() % 512 != 0) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "image size is not a multiple of 512 bytes");
}
bool was_sd_mounted = false;
if (!acquire_sd_device()) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "Failed to initialize SD card. Check that it is inserted.");
}
temporary_unmount_sd(&was_sd_mounted);
ON_SCOPE_EXIT {
if (was_sd_mounted) {
temporary_remount_sd();
}
release_sd_device();
};
if (sdmmc_device_write(&g_sd_device, 0, this->gadget.GetLastDownloadSize() / 512, this->gadget.GetLastDownloadBuffer())) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::OKAY, "");
} else {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "I/O error");
}
} else {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "unknown partition");
}
}
Result FastbootImpl::Reboot(const char *argment) {
return this->gadget.SendResponse(ResponseDisposition::Reboot, ResponseToken::OKAY, "");
}
Result FastbootImpl::Boot(const char *argment) {
if (this->gadget.GetLastDownloadSize() == 0) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "no image has been downloaded");
}
/* Validate the boot image we have received. */
if (this->gadget.GetLastDownloadSize() < sizeof(android_boot_image_v2)) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "received boot image is too small");
}
android_boot_image_v2 *bootimg = (android_boot_image_v2*) this->gadget.GetLastDownloadBuffer();
if (memcmp(bootimg->magic, "ANDROID!", sizeof(bootimg->magic)) != 0) {
print(SCREEN_LOG_LEVEL_DEBUG, "invalid magic: '%s'\n", bootimg->magic);
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "received boot image has invalid magic");
}
if (bootimg->header_version != 2) {
print(SCREEN_LOG_LEVEL_DEBUG, "invalid version: %d\n", bootimg->header_version);
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "received boot image has invalid version");
}
if (bootimg->header_size != sizeof(*bootimg)) {
print(SCREEN_LOG_LEVEL_DEBUG, "invalid size: %d, expected %d\n", bootimg->header_size, sizeof(*bootimg));
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "received boot image has invalid size");
}
if (bootimg->ramdisk_size != 0 ||
bootimg->second_size != 0 ||
bootimg->dtb_size != 0) {
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "received boot image has unexpected ramdisk, second stage bootloader, or dtb");
}
/* Setup chainloader. */
print(SCREEN_LOG_LEVEL_DEBUG, "loading kernel to 0x%lx\n", bootimg->kernel_addr);
g_chainloader_num_entries = 1;
g_chainloader_entries[0].load_address = bootimg->kernel_addr;
g_chainloader_entries[0].src_address = (uintptr_t) this->gadget.GetLastDownloadBuffer() + bootimg->page_size;
g_chainloader_entries[0].size = bootimg->kernel_size;
g_chainloader_entries[0].num = 0;
g_chainloader_entrypoint = bootimg->kernel_addr;
return this->gadget.SendResponse(ResponseDisposition::Chainload, ResponseToken::OKAY, "");
}
Result FastbootImpl::OemCRC32(const char *argument) {
uint32_t crc = crc32(0, (const uint8_t*) this->gadget.GetLastDownloadBuffer(), this->gadget.GetLastDownloadSize());
return this->gadget.SendResponse(ResponseDisposition::Okay, ResponseToken::INFO, "%08lx", crc);
}
Result FastbootImpl::Continue() {
switch(this->current_action) {
default:
case Action::Invalid:
fatal_error("fastboot implementation has invalid current action");
case Action::FlashAms:
return this->ContinueFlashAms();
}
}
namespace {
size_t flash_ams_mz_extract_callback(void *opaque, mz_uint64 file_ofs, const void *buf, size_t n) {
FIL *f = (FIL*) opaque;
if (f_lseek(f, file_ofs) != FR_OK) {
return 0;
}
UINT bw;
if (f_write(f, buf, n, &bw) != FR_OK) {
return 0;
}
return bw;
}
} // anonymous namespace
Result FastbootImpl::ContinueFlashAms() {
if (this->flash_ams.error != nullptr) {
unmount_sd();
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, this->flash_ams.error);
}
if (this->flash_ams.file_index == this->flash_ams.num_files) {
unmount_sd();
return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::OKAY, "");
}
mz_uint file_index = this->flash_ams.file_index++;
static char filename_buffer[261];
mz_zip_reader_get_filename(&this->flash_ams.zip, file_index, filename_buffer, sizeof(filename_buffer));
R_TRY(this->gadget.SendResponse(ResponseDisposition::Continue, ResponseToken::INFO, "(%d/%d): %s", file_index + 1, this->flash_ams.num_files, filename_buffer));
if (mz_zip_reader_is_file_a_directory(&this->flash_ams.zip, file_index)) {
size_t len = strlen(filename_buffer);
if (filename_buffer[len-1] == '/') {
/* FatFS needs us to trim trailing slash on directories. */
filename_buffer[len-1] = '\0';
}
FRESULT r = f_mkdir(filename_buffer);
if (r != FR_OK && r != FR_EXIST) {
this->flash_ams.error = "failed to create directory";
return ResultSuccess();
}
} else {
FIL f;
if (f_open(&f, filename_buffer, FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) {
this->flash_ams.error = "failed to open file";
return ResultSuccess();
}
f_sync(&f);
if (!mz_zip_reader_extract_to_callback(&this->flash_ams.zip, file_index, flash_ams_mz_extract_callback, &f, 0)) {
this->flash_ams.error = "failed to extract file";
f_close(&f);
return ResultSuccess();
}
if (f_close(&f) != FR_OK) {
this->flash_ams.error = "failed to close file";
return ResultSuccess();
}
}
return ResultSuccess();
}
} // namespace fastboot
} // namespace ams

View File

@ -0,0 +1,69 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include<stddef.h>
#include "../lib/miniz.h"
namespace ams {
namespace fastboot {
class FastbootGadget;
class FastbootImpl {
public:
FastbootImpl(FastbootGadget &gadget);
/* Implementation is allowed to modify the command buffer for string
parsing reasons. */
Result ProcessCommand(char *command_buffer);
Result Continue();
private:
FastbootGadget &gadget;
enum class Action {
Invalid,
FlashAms,
} current_action;
union {
struct {
mz_zip_archive zip;
mz_uint num_files;
mz_uint file_index;
const char *error;
} flash_ams;
};
/* Commands */
Result GetVar(const char *arg);
Result Download(const char *arg);
Result Flash(const char *arg);
Result Reboot(const char *arg);
Result Boot(const char *arg);
Result OemCRC32(const char *arg);
/* Continuations */
Result ContinueFlashAms();
};
} // namespace fastboot
} // namespace ams

View File

@ -0,0 +1,31 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "xusb_result.h"
namespace fastboot {
class FastbootInterface {
public:
virtual xusb::Result SendOkayResponse(const char *message="") = 0;
virtual xusb::Result SendInfoForOkayResponse(const char *message) = 0;
virtual xusb::Result SendInfoForFlasher(const char *message) = 0;
virtual xusb::Result SendFailResponse(const char *message) = 0;
};
} // namespace fastboot

View File

@ -0,0 +1,489 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include<stdint.h>
#include<stddef.h>
#include<string.h>
namespace usb {
enum class DescriptorType : uint8_t {
DEVICE = 1,
CONFIGURATION = 2,
STRING = 3,
INTERFACE = 4,
ENDPOINT = 5,
DEVICE_QUALIFIER = 6,
OTHER_SPEED_CONFIGURATION = 7,
INTERFACE_POWER = 8,
OTG = 9,
DEBUG = 10,
INTERFACE_ASSOCIATION = 11,
BOS = 15,
DEVICE_CAPABILITY = 16,
SUPERSPEED_USB_ENDPOINT_COMPANION = 48,
SUPERSPEEDPLUS_ISOCHRONOUS_ENDPOINT_COMPANION = 49,
};
enum class EndpointFeatureSelector : uint8_t {
ENDPOINT_HALT = 0,
};
enum class DeviceCapabilityType : uint8_t {
WIRELESS_USB = 0x1,
USB_2_0_EXTENSION = 0x2,
SUPERSPEED_USB = 0x3,
CONTAINER_ID = 0x4,
PLATFORM = 0x5,
POWER_DELIVERY_CAPABILITY = 0x6,
BATTERY_INFO_CAPABILITY = 0x7,
PD_CONSUMER_PORT_CAPABILITY = 0x8,
PD_PROVIDER_PORT_CAPABILITY = 0x9,
SUPERSPEED_PLUS = 0xa,
PRECISION_TIME_MEASUREMENT = 0xb,
WIRELESS_USB_EXT = 0xc,
BILLBOARD = 0xd,
AUTHENTICATION = 0xe,
BILLBOARD_EX = 0xf,
CONFIGURATION_SUMMARY = 0x10,
};
enum class EndpointType : uint8_t {
Control = 0,
Isochronous = 1,
Bulk = 2,
Interrupt = 3,
};
struct CommonDescriptor {
uint8_t bLength;
DescriptorType bDescriptorType;
} __attribute__((packed));
struct DeviceDescriptor : public CommonDescriptor {
struct {
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} __attribute__((packed));
} __attribute__((packed));
struct DeviceQualifierDescriptor : public CommonDescriptor {
struct {
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint8_t bNumConfigurations;
uint8_t bReserved;
} __attribute__((packed));
} __attribute__((packed));
struct ConfigurationDescriptor : public CommonDescriptor {
struct {
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t bMaxPower;
} __attribute__((packed));
} __attribute__((packed));
static_assert(sizeof(ConfigurationDescriptor) == 9);
struct InterfaceDescriptor : public CommonDescriptor {
struct {
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
} __attribute__((packed));
} __attribute__((packed));
static_assert(sizeof(InterfaceDescriptor) == 9);
struct EndpointDescriptor : public CommonDescriptor {
struct {
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
} __attribute__((packed));
EndpointType GetEndpointType() const {
return (EndpointType) (bmAttributes & 0b11);
}
} __attribute__((packed));
static_assert(sizeof(EndpointDescriptor) == 7);
namespace detail {
template<size_t N>
struct FixedString {
constexpr FixedString(char16_t const* s) {
for (size_t i = 0; i < N; i++) {
buffer[i] = s[i];
}
}
static const size_t length = N;
char16_t buffer[N + 1]{};
};
template<size_t N> FixedString(char16_t const (&)[N]) -> FixedString<N - 1>;
} // namespace detail
template <detail::FixedString string>
struct StringDescriptor : public CommonDescriptor {
inline constexpr StringDescriptor() : bString {} {
this->bLength = (string.length * 2) + 2;
this->bDescriptorType = DescriptorType::STRING;
for (size_t i = 0; i < string.length; i++) {
this->bString[i] = string.buffer[i];
}
}
char16_t bString[string.length];
} __attribute__((packed));
namespace detail {
template<size_t I, typename First, typename... T>
struct StringDescriptorIndexer : public First::template WithIndex<I>, public StringDescriptorIndexer<I + 1, T...> {
using ThisDescriptor = First::template WithIndex<I>;
using NextIndexer = StringDescriptorIndexer<I + 1, T...>;
bool GetStringDescriptor(uint8_t index, uint16_t language, const CommonDescriptor **descriptor, uint16_t *length) const {
if (index == I) {
*descriptor = &ThisDescriptor::_descriptor;
*length = sizeof(ThisDescriptor::_descriptor);
return true;
} else {
return NextIndexer::GetStringDescriptor(index, language, descriptor, length);
}
}
};
template<size_t I, typename First>
struct StringDescriptorIndexer<I, First> : public First::template WithIndex<I> {
using ThisDescriptor = First::template WithIndex<I>;
bool GetStringDescriptor(uint8_t index, uint16_t language, const CommonDescriptor **descriptor, uint16_t *length) const {
if (index == I) {
*descriptor = &ThisDescriptor::_descriptor;
*length = sizeof(ThisDescriptor::_descriptor);
return true;
} else {
return false;
}
}
};
} // namespace detail
template<typename... T>
using StringDescriptorIndexer = detail::StringDescriptorIndexer<0, T...>;
/* The wrapper type is here because we can't pass templates as template
* parameters directly. */
#define USB_DECLARE_STRING_DESCRIPTOR(id, english_value) struct SD_##id { \
template<size_t I> \
struct WithIndex { \
static constexpr ::usb::StringDescriptor<english_value> _descriptor = {}; \
static constexpr size_t id = I; \
}; \
}
struct BOSDescriptor : public CommonDescriptor {
struct {
uint16_t wTotalLength;
uint8_t bNumDeviceCaps;
} __attribute__((packed));
} __attribute__((packed));
struct DeviceCapabilityDescriptor : public CommonDescriptor {
struct {
DeviceCapabilityType bDevCapabilityType;
} __attribute__((packed));
} __attribute__((packed));
namespace caps {
struct USB_2_0_EXTENSION : public DeviceCapabilityDescriptor {
struct {
uint32_t bmAttributes;
} __attribute__((packed));
} __attribute__((packed));
struct SUPERSPEED : public DeviceCapabilityDescriptor {
struct {
uint8_t bmAttributes;
uint16_t wSpeedsSupported;
uint8_t bFunctionalitySupport;
uint8_t bU1DevExitLat;
uint16_t wU2DevExitLat;
} __attribute__((packed));
} __attribute__((packed));
template<typename PlatformCapability>
struct PLATFORM : public DeviceCapabilityDescriptor {
uint8_t bReserved;
uint8_t PlatformCapabilityUUID[16];
PlatformCapability platform_cap;
constexpr PLATFORM(PlatformCapability platform_cap) :
DeviceCapabilityDescriptor({
{
.bLength = sizeof(*this),
.bDescriptorType = usb::DescriptorType::DEVICE_CAPABILITY,
},
{
.bDevCapabilityType = usb::DeviceCapabilityType::PLATFORM
}
}),
bReserved(0),
platform_cap(platform_cap) {
static_assert(sizeof(PlatformCapability::UUID[0]) == 1);
static_assert(sizeof(PlatformCapability::UUID) == sizeof(PlatformCapabilityUUID));
for (size_t i = 0; i < sizeof(PlatformCapability::UUID); i++) {
PlatformCapabilityUUID[i] = PlatformCapability::UUID[i];
}
}
} __attribute__((packed));
template<typename T>
constexpr PLATFORM<T> make_platform_capability(T cap) {
return PLATFORM<T>(cap);
}
} // namespace caps
namespace ms {
inline const uint32_t NTDDI_WIN8_1 = 0x06030000;
inline const uint8_t MS_OS_20_DESCRIPTOR_INDEX = 0x7;
struct DescriptorSetInformation {
static inline const uint8_t UUID[16] = {0xDF, 0x60, 0xDD, 0xD8, 0x89, 0x45, 0xC7, 0x4C, 0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F};
uint32_t dwWindowsVersion;
uint16_t wMSOSDescriptorSetTotalLength;
uint8_t bMS_VendorCode;
uint8_t bAltEnumCode;
} __attribute__((packed));
namespace os20 {
enum class DescriptorType : uint16_t {
SetHeaderDescriptor = 0,
SubsetHeaderConfiguration = 1,
SubsetHeaderFunction = 2,
FeatureCompatibleID = 3,
FeatureRegProperty = 4,
FeatureMinResumeTime = 5,
FeatureModelID = 6,
FeatureCCGPDevice = 7,
FeatureVendorRevision = 8
};
struct DescriptorSetHeader {
uint16_t wLength;
DescriptorType wDescriptorType;
uint32_t dwWindowsVersion;
uint16_t wTotalLength;
} __attribute__((packed));
/*
struct ConfigurationSubsetHeader {
uint16_t wLength;
uint16_t wDescriptorType;
uint8_t bConfigurationValue;
uint8_t bReserved;
uint16_t wTotalLength;
} __attribute__((packed));
struct FunctionSubsetHeader {
uint16_t wLength;
uint16_t wDescriptorType;
uint8_t bFirstInterface;
uint8_t bReserved;
uint16_t wSubsetLength;
} __attribute__((packed));
*/
struct FeatureCompatibleID {
uint16_t wLength = sizeof(*this);
DescriptorType wDescriptorType = DescriptorType::FeatureCompatibleID;
uint8_t CompatibleID[8] = {0};
uint8_t SubCompatibleID[8] = {0};
constexpr FeatureCompatibleID(const char CompatibleID[], const char SubCompatibleID[]) {
for (size_t i = 0; i < sizeof(this->CompatibleID) && CompatibleID[i] != '\0'; i++) {
this->CompatibleID[i] = CompatibleID[i];
}
for (size_t i = 0; i < sizeof(this->SubCompatibleID) && SubCompatibleID[i] != '\0'; i++) {
this->SubCompatibleID[i] = SubCompatibleID[i];
}
}
} __attribute__((packed));
enum PropertyDataType : uint16_t {
REG_SZ = 1,
REG_EXPAND_SZ = 2,
REG_BINARY = 3,
REG_DWORD_LITTLE_ENDIAN = 4,
REG_DWORD_BIG_ENDIAN = 5,
REG_LINK = 6,
REG_MULTI_SZ = 7,
};
template<PropertyDataType property_data_type, detail::FixedString property_name, detail::FixedString property_data>
struct FeatureRegistryProperty {
uint16_t wLength = sizeof(*this);
DescriptorType wDescriptorType = DescriptorType::FeatureRegProperty;
uint16_t wPropertyDataType = property_data_type;
uint16_t wPropertyNameLength = (property_name.length + 1) * 2;
char16_t PropertyName[property_name.length + 1] = {0};
uint16_t wPropertyDataLength = (property_data.length + 1) * 2;
char16_t PropertyData[property_data.length + 1] = {0};
constexpr FeatureRegistryProperty() {
for (size_t i = 0; i < property_name.length; i++) {
this->PropertyName[i] = property_name.buffer[i];
}
for (size_t i = 0; i < property_data.length; i++) {
this->PropertyData[i] = property_data.buffer[i];
}
}
} __attribute__((packed));
} // namespace os20
} // namespace ms
namespace detail {
template<typename First, typename... T>
struct PackedTuple {
First first;
PackedTuple<T...> remaining;
constexpr PackedTuple(First first, T... remaining) :
first(first),
remaining(remaining...) {
}
} __attribute__((packed));
template<typename First>
struct PackedTuple<First> {
First first;
constexpr PackedTuple(First first) : first(first) {
}
} __attribute__((packed));
} // namespace detail
template<typename... T>
struct BOSDescriptorContainer {
BOSDescriptor bos_descriptor;
detail::PackedTuple<T...> tuple;
constexpr BOSDescriptorContainer(T... members) : bos_descriptor {
{
.bLength = sizeof(BOSDescriptor),
.bDescriptorType = DescriptorType::BOS,
},
{
.wTotalLength = sizeof(*this),
.bNumDeviceCaps = sizeof...(T),
}
}, tuple(members...) {
}
} __attribute__((packed));
template<typename... T>
constexpr BOSDescriptorContainer<T...> make_bos_descriptor_container(T... members) {
return BOSDescriptorContainer<T...>(members...);
}
struct SetupPacket {
enum class StandardRequest : uint8_t {
GET_STATUS = 0,
CLEAR_FEATURE = 1,
// reserved
SET_FEATURE = 3,
// reserved
SET_ADDRESS = 5,
GET_DESCRIPTOR = 6,
SET_DESCRIPTOR = 7,
GET_CONFIGURATION = 8,
SET_CONFIGURATION = 9,
GET_INTERFACE = 10,
SET_INTERFACE = 11,
SYNCH_FRAME = 12
};
enum class RequestDirection {
HostToDevice = 0,
DeviceToHost = 1,
};
enum class RequestType {
Standard = 0,
Class = 1,
Vendor = 2,
Reserved = 3,
};
enum class RequestRecipient {
Device = 0,
Interface = 1,
Endpoint = 2,
Other = 3
};
static inline uint8_t PackRequestType(RequestDirection dir, RequestType type, RequestRecipient recipient) {
return ((uint8_t) dir << 7) |
((uint8_t) type << 5) |
((uint8_t) recipient << 0);
}
uint8_t bmRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} __attribute__((packed));
} // namespace usb

View File

@ -0,0 +1,600 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xusb.h"
#include "xusb_event_ring.h"
#include "xusb_endpoint.h"
#include "../reg/reg_apbdev_pmc.h"
#include "../reg/reg_car.h"
#include "../reg/reg_fuse.h"
#include "../reg/reg_xusb_padctl.h"
#include "../reg/reg_xusb_dev.h"
extern "C" {
#include "../timers.h"
#include "../lib/log.h"
#include "../utils.h"
#include "../mc.h"
}
#include<array>
namespace ams {
namespace xusb {
namespace impl {
namespace padctl {
void SetupPads(t210::CLK_RST_CONTROLLER::OscFreq osc_freq);
void SetupPllu(t210::CLK_RST_CONTROLLER::OscFreq osc_freq);
void SetupUTMIP(t210::CLK_RST_CONTROLLER::OscFreq osc_freq);
void ApplyFuseCalibration();
void DisablePd();
void SetupTracking(t210::CLK_RST_CONTROLLER::OscFreq osc_freq);
}
void ConfigureClockAndResetForDeviceMode();
EventRing event_ring;
TRB ep0_transfer_ring[16];
Gadget *current_gadget = nullptr;
}
void Initialize() {
const bool use_bootrom = false;
t210::CLK_RST_CONTROLLER
.CLK_OUT_ENB_W_0()
.CLK_ENB_XUSB.Enable()
.Commit()
.RST_DEVICES_W_0()
.SWR_XUSB_PADCTL_RST.Set(0)
.Commit();
udelay(2);
t210::XUSB_PADCTL
.USB2_PAD_MUX_0()
.USB2_OTG_PAD_PORT0.SetXUSB()
.USB2_BIAS_PAD.SetXUSB()
.Commit();
if (use_bootrom) {
((bool (*)()) (0x1104fd))();
} else {
impl::padctl::SetupPads(t210::CLK_RST_CONTROLLER.OSC_CTRL_0().OSC_FREQ.Get());
}
t210::XUSB_PADCTL
.USB2_PORT_CAP_0()
.PORT0_CAP.SetDeviceOnly()
.Commit()
.SS_PORT_MAP_0()
.PORT0_MAP.SetUSB2Port0()
.Commit();
t210::APBDEV_PMC
.USB_AO_0()
.VBUS_WAKEUP_PD_P0.Set(0)
.ID_PD_P0.Set(0)
.Commit();
udelay(1);
if (use_bootrom) {
((void (*)()) (0x110227))();
} else {
impl::ConfigureClockAndResetForDeviceMode();
}
impl::event_ring.Initialize();
endpoints[0].InitializeForControl(impl::ep0_transfer_ring, std::size(impl::ep0_transfer_ring));
t210::T_XUSB_DEV_XHCI
.ECPLO()
.ADDRLO.Set(endpoints.GetContextsForHardware())
.Commit()
.ECPHI()
.ADDRHI.Set(0)
.Commit();
endpoints[0].Reload();
t210::T_XUSB_DEV_XHCI
.CTRL()
.LSE.Enable()
.IE.Enable()
.Commit();
}
void EnableDevice(Gadget &gadget) {
impl::current_gadget = &gadget;
t210::XUSB_PADCTL
.ELPG_PROGRAM_0_0(0).Commit()
.ELPG_PROGRAM_1_0(0).Commit()
.USB2_VBUS_ID_0()
.VBUS_SOURCE_SELECT.SetOVERRIDE()
.ID_SOURCE_SELECT.SetOVERRIDE()
.Commit();
t210::T_XUSB_DEV_XHCI
.PORTHALT()
.HALT_LTSSM.Set(0)
.Commit()
.CTRL()
.ENABLE.Enable()
.Commit()
.CFG_DEV_FE()
.PORTREGSEL.SetHSFS() // PortSC accesses route to register for HS
.Commit()
.PORTSC()
.LWS.Set(1)
.PLS.SetRXDETECT()
.Commit()
.CFG_DEV_FE()
.PORTREGSEL.SetSS() // PortSC accesses route to register for SS
.Commit()
.PORTSC()
.LWS.Set(1)
.PLS.SetRXDETECT()
.Commit()
.CFG_DEV_FE()
.PORTREGSEL.SetINIT() // PortSC Accesses route to register based on current link speed
.Commit();
t210::XUSB_PADCTL
.USB2_VBUS_ID_0()
.VBUS_OVERRIDE.Set(1)
.ID_OVERRIDE.SetFLOAT()
.Commit();
}
void Process() {
impl::event_ring.Process();
}
void Finalize() {
mc_release_ahb_redirect();
}
Gadget *GetCurrentGadget() {
return impl::current_gadget;
}
namespace impl {
namespace padctl {
void SetupPads(t210::CLK_RST_CONTROLLER::OscFreq osc_freq) {
constexpr bool use_bootrom = false;
SetupPllu(osc_freq);
if (use_bootrom) {
((void (*)(t210::CLK_RST_CONTROLLER::OscFreq)) (0x11039b))(osc_freq);
((void (*)()) (0x110357))();
((int (*)()) (0x110327))();
((bool (*)(t210::CLK_RST_CONTROLLER::OscFreq)) (0x1102cb))(osc_freq);
} else {
SetupUTMIP(osc_freq);
ApplyFuseCalibration();
DisablePd();
SetupTracking(osc_freq);
}
udelay(30);
}
void SetupPllu(t210::CLK_RST_CONTROLLER::OscFreq osc_freq) {
struct {
uint8_t divn, divm, divp;
} pllu_config;
using OscFreq = t210::CLK_RST_CONTROLLER::OscFreq;
switch(osc_freq) {
case OscFreq::OSC13:
pllu_config = {37, 1, 1};
break;
case OscFreq::OSC16P8:
pllu_config = {28, 1, 1};
break;
case OscFreq::OSC19P2:
pllu_config = {25, 1, 1};
break;
case OscFreq::OSC38P4:
pllu_config = {25, 2, 1};
break;
case OscFreq::OSC12:
pllu_config = {40, 1, 1};
break;
case OscFreq::OSC48:
pllu_config = {40, 4, 1};
break;
case OscFreq::OSC26:
pllu_config = {37, 2, 1};
break;
default:
fatal_error("xusb initialization failed: invalid oscillator frequency");
break;
}
// reset PLLU
t210::CLK_RST_CONTROLLER
.PLLU_BASE_0()
.PLLU_ENABLE.Disable()
.PLLU_CLKENABLE_48M.Disable()
.PLLU_OVERRIDE.Set(1)
.PLLU_CLKENABLE_ICUSB.Disable()
.PLLU_CLKENABLE_HSIC.Disable()
.PLLU_CLKENABLE_USB.Disable()
.Commit();
udelay(100);
t210::CLK_RST_CONTROLLER
.PLLU_MISC_0()
.PLLU_EN_LCKDET.Enable()
.Commit()
.PLLU_BASE_0()
.PLLU_DIVM.Set(pllu_config.divm)
.PLLU_DIVN.Set(pllu_config.divn)
.PLLU_DIVP.Set(pllu_config.divp)
.PLLU_OVERRIDE.Set(1)
.PLLU_ENABLE.Enable()
.Commit();
int i = 0;
while (!t210::CLK_RST_CONTROLLER.PLLU_BASE_0().PLLU_LOCK && i < 100000) {
i++;
}
if (t210::CLK_RST_CONTROLLER.PLLU_BASE_0().PLLU_LOCK) {
print(SCREEN_LOG_LEVEL_DEBUG, "got PLLU lock in %d iterations\n", i);
} else {
fatal_error("xusb initialization failed: PLLU lock not acquired in %d iterations\n", i);
}
t210::CLK_RST_CONTROLLER
.PLLU_BASE_0()
.PLLU_CLKENABLE_USB.Enable()
.PLLU_CLKENABLE_HSIC.Enable()
.PLLU_CLKENABLE_48M.Enable()
.PLLU_CLKENABLE_ICUSB.Enable()
.Commit();
}
void SetupUTMIP(t210::CLK_RST_CONTROLLER::OscFreq osc_freq) {
t210::CLK_RST_CONTROLLER
.UTMIPLL_HW_PWRDN_CFG0_0()
.UTMIPLL_IDDQ_SWCTL.Set(1) // "IDDQ by software."
.UTMIPLL_IDDQ_OVERRIDE_VALUE.Set(0) // "PLL not in IDDQ mode... Override value used only when UTMIP_LL_IDDQ_SWCTL is set"
.Commit();
constexpr bool use_pllu = false; // works either way
struct {
uint8_t ndiv, mdiv;
} pll_config;
struct {
uint16_t enable_dly_count;
/* only used with PLLU reference source */
uint16_t stable_count;
/* only used with PLLU reference source */
uint16_t active_dly_count;
uint16_t xtal_freq_count;
} count_config;
using OscFreq = t210::CLK_RST_CONTROLLER::OscFreq;
switch(osc_freq) {
case OscFreq::OSC13:
pll_config = {74, 1};
count_config = {2, 51, 9, 127};
break;
case OscFreq::OSC16P8:
pll_config = {57, 1};
count_config = {3, 66, 11, 165};
break;
case OscFreq::OSC19P2:
pll_config = {50, 1};
count_config = {3, 75, 12, 188};
break;
case OscFreq::OSC38P4:
pll_config = {25, 1};
count_config = {5, 150, 24, 375};
break;
case OscFreq::OSC12:
pll_config = {80, 1};
count_config = {2, 47, 8, 118};
break;
case OscFreq::OSC48:
pll_config = {40, 2};
count_config = {6, 188, 31, 469};
break;
case OscFreq::OSC26:
pll_config = {74, 2};
count_config = {4, 102, 17, 254};
break;
default:
fatal_error("xusb initialization failed: invalid oscillator frequency");
break;
}
if (use_pllu) {
t210::CLK_RST_CONTROLLER
.UTMIP_PLL_CFG3_0()
.UTMIP_PLL_REF_SRC_SEL.Set(1)
.Commit();
/* 480 MHz * 30 / 15 = 960 MHz */
pll_config = {30, 15};
} else {
// TODECIDE: set PLL_REF_SRC_SEL? or assume correct from reset?
/* don't need to wait for PLLU to become stable if we're not using it */
count_config.stable_count = 0;
count_config.enable_dly_count = 0;
}
t210::CLK_RST_CONTROLLER
.UTMIP_PLL_CFG0_0()
.UTMIP_PLL_NDIV.Set(pll_config.ndiv)
.UTMIP_PLL_MDIV.Set(pll_config.mdiv)
.Commit()
.UTMIP_PLL_CFG2_0()
.UTMIP_PHY_XTAL_CLOCKEN.Set(1)
.UTMIP_PLLU_STABLE_COUNT.Set(count_config.stable_count)
.UTMIP_PLL_ACTIVE_DLY_COUNT.Set(count_config.active_dly_count)
.Commit()
.UTMIP_PLL_CFG1_0()
.UTMIP_PLLU_ENABLE_DLY_COUNT.Set(count_config.enable_dly_count)
.UTMIP_XTAL_FREQ_COUNT.Set(count_config.xtal_freq_count)
.UTMIP_FORCE_PLL_ACTIVE_POWERDOWN.Set(0)
.UTMIP_FORCE_PLL_ENABLE_POWERUP.Set(1)
.UTMIP_FORCE_PLL_ENABLE_POWERDOWN.Set(0)
.Commit();
for (int i = 0; i < 100 && !t210::CLK_RST_CONTROLLER.UTMIPLL_HW_PWRDN_CFG0_0().UTMIPLL_LOCK; i++) {
udelay(1);
}
if (t210::CLK_RST_CONTROLLER.UTMIPLL_HW_PWRDN_CFG0_0().UTMIPLL_LOCK) {
print(SCREEN_LOG_LEVEL_DEBUG, "got UTMIPLL lock\n");
print(SCREEN_LOG_LEVEL_DEBUG, "UTMIP_PLL_CFG0_0: 0x%08x\n", t210::CLK_RST_CONTROLLER.UTMIP_PLL_CFG0_0().read_value);
print(SCREEN_LOG_LEVEL_DEBUG, "UTMIP_PLL_CFG1_0: 0x%08x\n", t210::CLK_RST_CONTROLLER.UTMIP_PLL_CFG1_0().read_value);
print(SCREEN_LOG_LEVEL_DEBUG, "UTMIP_PLL_CFG2_0: 0x%08x\n", t210::CLK_RST_CONTROLLER.UTMIP_PLL_CFG2_0().read_value);
} else {
/* There is some issue where occasionally after a reboot-to-self we
* fail to get a UTMIP lock. The BootROM ignores this failure and
* continues on. It seems that in these cases it eventually starts
* working, but may take a few seconds to do so. */
print(SCREEN_LOG_LEVEL_ERROR, "failed to get UTMIP lock\n");
print(SCREEN_LOG_LEVEL_DEBUG, "UTMIP_PLL_CFG0_0: 0x%08x\n", t210::CLK_RST_CONTROLLER.UTMIP_PLL_CFG0_0().read_value);
print(SCREEN_LOG_LEVEL_DEBUG, "UTMIP_PLL_CFG1_0: 0x%08x\n", t210::CLK_RST_CONTROLLER.UTMIP_PLL_CFG1_0().read_value);
print(SCREEN_LOG_LEVEL_DEBUG, "UTMIP_PLL_CFG2_0: 0x%08x\n", t210::CLK_RST_CONTROLLER.UTMIP_PLL_CFG2_0().read_value);
}
t210::CLK_RST_CONTROLLER
.UTMIP_PLL_CFG2_0()
.UTMIP_FORCE_PD_SAMP_A_POWERDOWN.Set(0)
.UTMIP_FORCE_PD_SAMP_A_POWERUP.Set(1)
.UTMIP_FORCE_PD_SAMP_B_POWERDOWN.Set(0)
.UTMIP_FORCE_PD_SAMP_B_POWERUP.Set(1)
.UTMIP_FORCE_PD_SAMP_C_POWERDOWN.Set(0)
.UTMIP_FORCE_PD_SAMP_C_POWERUP.Set(1)
.UTMIP_FORCE_PD_SAMP_D_POWERDOWN.Set(0)
.UTMIP_FORCE_PD_SAMP_D_POWERUP.Set(1)
.Commit()
.UTMIP_PLL_CFG1_0()
.UTMIP_FORCE_PLL_ENABLE_POWERUP.Set(0)
.UTMIP_FORCE_PLL_ENABLE_POWERDOWN.Set(0)
.Commit()
.UTMIPLL_HW_PWRDN_CFG0_0()
.UTMIPLL_USE_LOCKDET.Set(1)
.UTMIPLL_CLK_ENABLE_SWCTL.Set(0)
.UTMIPLL_SEQ_ENABLE.Set(1)
.Commit();
udelay(2);
}
void ApplyFuseCalibration() {
auto fuse = t210::FUSE.SKU_USB_CALIB();
t210::XUSB_PADCTL
.USB2_OTG_PAD0_CTL_0_0()
.HS_CURR_LEVEL.Set(fuse.HS_CURR_LEVEL.Get())
.Commit()
.USB2_OTG_PAD0_CTL_1_0()
.TERM_RANGE_ADJ.Set(fuse.TERM_RANGE_ADJ.Get())
.RPD_CTRL.Set(t210::FUSE.USB_CALIB_EXT().RPD_CTRL.Get())
.Commit()
.USB2_BATTERY_CHRG_OTGPAD0_CTL1_0()
.VREG_FIX18.Set(0)
.VREG_LEV.Set(1)
.Commit();
}
void DisablePd() {
t210::XUSB_PADCTL
.USB2_OTG_PAD0_CTL_0_0()
.PD_ZI.Set(0)
.PD.Set(0)
.Commit()
.USB2_OTG_PAD0_CTL_1_0()
.PD_DR.Set(0)
.Commit()
.USB2_BATTERY_CHRG_OTGPAD0_CTL0_0()
.PD_CHG.Set(0)
.Commit()
.USB2_BIAS_PAD_CTL_0_0()
.PD.Set(0)
.Commit();
}
void SetupTracking(t210::CLK_RST_CONTROLLER::OscFreq osc_freq) {
uint8_t divisor;
using OscFreq = t210::CLK_RST_CONTROLLER::OscFreq;
switch(osc_freq) {
case OscFreq::OSC13:
divisor = 2;
break;
case OscFreq::OSC16P8:
divisor = 2;
break;
case OscFreq::OSC19P2:
divisor = 2;
break;
case OscFreq::OSC38P4:
divisor = 6;
break;
case OscFreq::OSC12:
divisor = 2;
break;
case OscFreq::OSC48:
divisor = 6;
break;
case OscFreq::OSC26:
divisor = 4;
break;
default:
fatal_error("xusb initialization failed: invalid oscillator frequency");
break;
}
t210::CLK_RST_CONTROLLER
.CLK_OUT_ENB_Y_0()
.CLK_ENB_USB2_TRK.Enable()
.Commit()
.CLK_SOURCE_USB2_HSIC_TRK_0()
.USB2_HSIC_TRK_CLK_DIVISOR.Set(divisor)
.Commit();
auto reg = t210::XUSB_PADCTL
.USB2_BIAS_PAD_CTL_1_0(0)
.TRK_DONE_RESET_TIMER.Set(10)
.TRK_START_TIMER.Set(30);
reg.PD_TRK.Set(0).Commit();
udelay(100);
reg.PD_TRK.Set(1).Commit();
udelay(3);
reg.PD_TRK.Set(0).Commit();
udelay(100);
t210::XUSB_PADCTL
.USB2_BIAS_PAD_CTL_1_0()
.PD_TRK.Set(1)
.Commit();
t210::CLK_RST_CONTROLLER
.CLK_OUT_ENB_Y_0()
.CLK_ENB_USB2_TRK.Disable()
.Commit();
}
} // namespace padctl
void ConfigureClockAndResetForDeviceMode() {
t210::CLK_RST_CONTROLLER
.PLLU_OUTA_0()
.PLLU_OUT1_RSTN.Set(1) // RESET_DISABLE
.Commit();
udelay(2);
t210::CLK_RST_CONTROLLER
.CLK_OUT_ENB_U_0()
.CLK_ENB_XUSB_DEV.Enable()
.Commit()
.CLK_SOURCE_XUSB_CORE_DEV_0()
.XUSB_CORE_DEV_CLK_SRC.SetPLLP_OUT0()
.XUSB_CORE_DEV_CLK_DIVISOR.Set(6)
.Commit();
udelay(2);
t210::CLK_RST_CONTROLLER
.CLK_SOURCE_XUSB_FS_0()
.XUSB_FS_CLK_SRC.SetFO_48M()
.Commit()
.CLK_OUT_ENB_W_0()
.CLK_ENB_XUSB_SS.Enable()
.Commit()
.CLK_SOURCE_XUSB_SS_0()
.XUSB_SS_CLK_SRC.SetHSIC_480()
.XUSB_SS_CLK_DIVISOR.Set(6)
.Commit()
.RST_DEVICES_W_0()
.SWR_XUSB_SS_RST.Set(0) // DISABLE
.Commit()
.RST_DEVICES_U_0()
.SWR_XUSB_DEV_RST.Set(0) // DISABLE
.Commit();
udelay(2);
mc_acquire_ahb_redirect();
t210::XUSB_DEV
.CONFIGURATION_0()
.EN_FPCI.Enable()
.Commit();
t210::T_XUSB_DEV
.CFG_1()
.IO_SPACE.Enable()
.MEMORY_SPACE.Enable()
.BUS_MASTER.Enable()
.Commit();
udelay(1);
t210::T_XUSB_DEV
.CFG_4(0)
.BASE_ADDRESS.Set(t210::XUSB_DEV_BASE)
.PREFETCHABLE.SetNOT()
.ADDRESS_TYPE.Set32_BIT()
.SPACE_TYPE.SetMEMORY()
.Commit();
t210::XUSB_DEV
.INTR_MASK_0()
.IP_INT_MASK.Set(1) // "IP (SATA/AZ) interrupt to MPCORE gated by mask."
.Commit();
}
} // namespace impl
Result xusb::Gadget::HandleSetupRequest(usb::SetupPacket &packet) {
return ResultUnknownSetupRequest();
}
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "usb_types.h"
#include "xusb_trb.h"
#include "xusb_endpoint.h"
#include<vapours/results/xusb_gadget_results.hpp>
#include<stddef.h>
namespace ams {
namespace xusb {
class Gadget {
public:
virtual Result HandleSetupRequest(usb::SetupPacket &packet);
virtual Result GetDeviceDescriptor(uint8_t index, const usb::DeviceDescriptor **descriptor, uint16_t *length) = 0;
virtual Result GetDeviceQualifierDescriptor(uint8_t index, const usb::DeviceQualifierDescriptor **descriptor, uint16_t *length) = 0;
virtual Result GetConfigurationDescriptor(uint8_t index, const usb::ConfigurationDescriptor **descriptor, uint16_t *length) = 0;
virtual Result GetBOSDescriptor(const usb::BOSDescriptor **descriptor, uint16_t *length) = 0;
virtual Result GetStringDescriptor(uint8_t index, uint16_t language, const usb::CommonDescriptor **descriptor, uint16_t *length) = 0;
/* It is the implementor's responsibility to configure endpoints before this returns. */
virtual Result SetConfiguration(uint16_t configuration) = 0;
virtual void PostConfigure() = 0;
virtual Result Deconfigure() = 0;
virtual void ProcessTransferEvent(TransferEventTRB *event, TRBBorrow transfer) = 0;
};
void Initialize();
void EnableDevice(Gadget &gadget);
void Process();
void Finalize();
Gadget *GetCurrentGadget();
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,414 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xusb_control.h"
#include "usb_types.h"
#include "xusb.h"
#include "xusb_endpoint.h"
#include "../reg/reg_xusb_dev.h"
extern "C" {
#include "../timers.h"
#include "../lib/log.h"
}
#include<string.h>
#include<vapours/results/xusb_gadget_results.hpp>
namespace ams {
namespace xusb {
namespace control {
DeviceState device_state = DeviceState::Powered;
namespace {
enum class ControlEpState {
Idle,
DataInStage,
DataOutStage,
StatusStage,
} control_ep_state = ControlEpState::Idle;
TRB *control_ep_last_trb = nullptr;
uint16_t control_ep_seq_num = 0;
void ResetControlEndpoint() {
xusb::endpoints[0].Pause();
xusb::endpoints[0].ResetAndReloadTransferRing();
xusb::endpoints[0].ClearPause();
control_ep_state = ControlEpState::Idle;
control_ep_last_trb = nullptr;
}
void ChangeDeviceState(DeviceState new_state) {
// if we are transitioning in or out of configured state,
if ((device_state == DeviceState::Configured) != (new_state == DeviceState::Configured)) {
t210::T_XUSB_DEV_XHCI.CTRL().RUN.Set(new_state == DeviceState::Configured).Commit();
if (new_state == DeviceState::Configured) {
t210::T_XUSB_DEV_XHCI.ST().RC.Clear().Commit();
xusb::GetCurrentGadget()->PostConfigure();
}
}
switch(new_state) {
case DeviceState::Default:
device_state = DeviceState::Default;
print(SCREEN_LOG_LEVEL_DEBUG, "entering default state, resetting control endpoint state...\n");
ResetControlEndpoint();
break;
case DeviceState::Address:
device_state = DeviceState::Address;
break;
case DeviceState::Configured:
device_state = DeviceState::Configured;
break;
default:
print(SCREEN_LOG_LEVEL_ERROR, "ChangeDeviceState(%d) state unknown\n", (int) new_state);
break;
}
}
} // anonymous namespace
Result SendData(void *data, size_t size) {
TRBBorrow trb;
R_TRY(xusb::endpoints[0].EnqueueTRB(&trb));
trb->transfer.InitializeDataStage(true, (void*) data, size);
trb->transfer.interrupt_on_completion = true;
trb->transfer.interrupt_on_short_packet = true;
trb.Release();
udelay(1000);
xusb::endpoints[0].RingDoorbell(control_ep_seq_num);
control_ep_state = ControlEpState::DataInStage;
control_ep_last_trb = &*trb;
return ResultSuccess();
}
Result SendStatus(bool direction) {
TRBBorrow trb;
R_TRY(xusb::endpoints[0].EnqueueTRB(&trb));
trb->transfer.InitializeStatusStage(direction);
trb->transfer.interrupt_on_completion = true;
trb->transfer.interrupt_on_short_packet = true;
trb.Release();
udelay(1000);
xusb::endpoints[0].RingDoorbell(control_ep_seq_num);
control_ep_state = ControlEpState::StatusStage;
control_ep_last_trb = &*trb;
return ResultSuccess();
}
namespace impl {
Result SetAddress(uint16_t addr) {
print(SCREEN_LOG_LEVEL_DEBUG, "got SET_ADDRESS request(%d)\n", addr);
R_UNLESS(addr <= 127, ams::xusb::ResultInvalidAddress());
t210::T_XUSB_DEV_XHCI
.CTRL()
.DEVADR.Set(addr)
.Commit();
xusb::endpoints.SetEP0DeviceAddress(addr);
ChangeDeviceState(DeviceState::Address);
return SendStatus(true);
}
Result GetDescriptor(usb::DescriptorType type, uint8_t index, uint16_t language_id, uint16_t length) {
print(SCREEN_LOG_LEVEL_DEBUG, "got GET_DESCRIPTOR request(%d, %d, %d, %d)\n", type, index, language_id, length);
uint16_t actual_length = 0;
const usb::CommonDescriptor *descriptor = nullptr;
switch(type) {
case usb::DescriptorType::DEVICE:
R_UNLESS(language_id == 0, xusb::ResultMalformedSetupRequest());
R_TRY(xusb::GetCurrentGadget()->GetDeviceDescriptor(index, (const usb::DeviceDescriptor**) &descriptor, &actual_length));
break;
case usb::DescriptorType::CONFIGURATION:
R_UNLESS(language_id == 0, xusb::ResultMalformedSetupRequest());
R_TRY(xusb::GetCurrentGadget()->GetConfigurationDescriptor(index, (const usb::ConfigurationDescriptor**) &descriptor, &actual_length));
break;
case usb::DescriptorType::BOS:
R_UNLESS(index == 0, xusb::ResultInvalidDescriptorIndex());
R_UNLESS(language_id == 0, xusb::ResultMalformedSetupRequest());
R_TRY(xusb::GetCurrentGadget()->GetBOSDescriptor((const usb::BOSDescriptor**) &descriptor, &actual_length));
break;
case usb::DescriptorType::STRING:
R_TRY(xusb::GetCurrentGadget()->GetStringDescriptor(index, language_id, &descriptor, &actual_length));
break;
case usb::DescriptorType::DEVICE_QUALIFIER:
R_UNLESS(language_id == 0, xusb::ResultMalformedSetupRequest());
R_TRY(xusb::GetCurrentGadget()->GetDeviceQualifierDescriptor(index, (const usb::DeviceQualifierDescriptor**) &descriptor, &actual_length));
break;
default:
return xusb::ResultUnknownDescriptorType();
}
if (actual_length > length) {
actual_length = length;
}
return SendData((void*) descriptor, actual_length);
}
Result SetConfiguration(uint16_t config) {
print(SCREEN_LOG_LEVEL_DEBUG, "got SET_CONFIGURATION request(%d)\n", config);
R_UNLESS(device_state == DeviceState::Address || device_state == DeviceState::Configured, xusb::ResultInvalidDeviceState());
// if we are already configured, deconfigure first.
if (device_state == DeviceState::Configured) {
R_TRY(xusb::GetCurrentGadget()->Deconfigure());
ChangeDeviceState(DeviceState::Address);
}
// if we need to reconfigure, do it.
if (config != 0) {
R_TRY(xusb::GetCurrentGadget()->SetConfiguration(config));
ChangeDeviceState(DeviceState::Configured);
}
return SendStatus(true);
}
Result ClearEndpointHaltFeature(uint8_t index) {
xusb::endpoints[EpAddr::Decode(index)].ClearHalt();
return SendStatus(true);
}
} // namespace impl
Result ProcessEP0TransferEventImpl(TransferEventTRB *event, TRBBorrow transfer) {
if (event->completion_code == 1 || event->completion_code == 13) {
/* Success or short packet. */
} else if (event->completion_code == 223) { // sequence number error
/* Sequence number error; skip to latest packet. */
control_ep_state = ControlEpState::Idle;
} else {
/* Error. */
control_ep_state = ControlEpState::Idle;
}
if (&*transfer != control_ep_last_trb) {
/* This can happen when we skip packets. */
print(SCREEN_LOG_LEVEL_ERROR, "got transfer event for wrong TRB (got %p, expected %p)\n", &*transfer, control_ep_last_trb);
return xusb::ResultUnexpectedTRB();
} else {
control_ep_last_trb = nullptr;
switch(control_ep_state) {
case ControlEpState::Idle:
return xusb::ResultInvalidControlEndpointState();
case ControlEpState::DataInStage:
return SendStatus(false); // OUT
case ControlEpState::DataOutStage:
return SendStatus(false); // IN
case ControlEpState::StatusStage:
control_ep_state = ControlEpState::Idle;
return ResultSuccess();
default:
return ResultSuccess();
}
}
}
void ProcessEP0TransferEvent(TransferEventTRB *event, TRBBorrow transfer) {
Result r = ProcessEP0TransferEventImpl(event, std::move(transfer));
if (r.IsFailure()) {
print(SCREEN_LOG_LEVEL_DEBUG, "failed to handle ep0 transfer event: 0x%x\n", r.GetValue());
xusb::endpoints[0].Halt();
}
}
Result ProcessSetupPacketEventImpl(SetupPacketEventTRB *trb) {
R_UNLESS(trb->seq_num != 0xfffe, xusb::ResultInvalidSetupPacketSequenceNumber());
R_UNLESS(trb->seq_num != 0xffff, xusb::ResultInvalidSetupPacketSequenceNumber());
R_UNLESS(device_state >= DeviceState::Default && device_state <= DeviceState::Configured, xusb::ResultInvalidDeviceState());
R_UNLESS(control_ep_state == ControlEpState::Idle, xusb::ResultControlEndpointBusy());
control_ep_seq_num = trb->seq_num;
xusb::endpoints[0].ClearHalt();
/* Let gadget try to service request first. */
do {
R_TRY_CATCH(xusb::GetCurrentGadget()->HandleSetupRequest(trb->packet)) {
R_CATCH(xusb::ResultUnknownSetupRequest) { break; }
} R_END_TRY_CATCH;
return ResultSuccess();
} while (0);
/* If gadget did not recognize the request, handle it ourselves. */
switch((usb::SetupPacket::StandardRequest) trb->packet.bRequest) {
case usb::SetupPacket::StandardRequest::CLEAR_FEATURE:
if (trb->packet.bmRequestType == usb::SetupPacket::PackRequestType(
usb::SetupPacket::RequestDirection::HostToDevice,
usb::SetupPacket::RequestType::Standard,
usb::SetupPacket::RequestRecipient::Endpoint) &&
trb->packet.wValue == (uint8_t) usb::EndpointFeatureSelector::ENDPOINT_HALT) {
R_UNLESS(trb->packet.wLength == 0, xusb::ResultMalformedSetupRequest());
return impl::ClearEndpointHaltFeature(trb->packet.wIndex);
} else {
return xusb::ResultUnknownSetupRequest();
}
case usb::SetupPacket::StandardRequest::SET_ADDRESS:
if (trb->packet.bmRequestType != usb::SetupPacket::PackRequestType(
usb::SetupPacket::RequestDirection::HostToDevice,
usb::SetupPacket::RequestType::Standard,
usb::SetupPacket::RequestRecipient::Device) ||
trb->packet.wIndex != 0 ||
trb->packet.wLength != 0) {
return xusb::ResultMalformedSetupRequest();
}
if (device_state == DeviceState::Configured) {
return xusb::ResultInvalidDeviceState();
}
return impl::SetAddress(trb->packet.wValue);
case usb::SetupPacket::StandardRequest::GET_DESCRIPTOR:
if (trb->packet.bmRequestType != usb::SetupPacket::PackRequestType(
usb::SetupPacket::RequestDirection::DeviceToHost,
usb::SetupPacket::RequestType::Standard,
usb::SetupPacket::RequestRecipient::Device)) {
return xusb::ResultMalformedSetupRequest();
}
return impl::GetDescriptor(
(usb::DescriptorType) (trb->packet.wValue >> 8),
trb->packet.wValue & 0xff,
trb->packet.wIndex,
trb->packet.wLength);
case usb::SetupPacket::StandardRequest::SET_CONFIGURATION:
if (trb->packet.bmRequestType != usb::SetupPacket::PackRequestType(
usb::SetupPacket::RequestDirection::HostToDevice,
usb::SetupPacket::RequestType::Standard,
usb::SetupPacket::RequestRecipient::Device) ||
trb->packet.wIndex != 0 ||
trb->packet.wLength != 0) {
return xusb::ResultMalformedSetupRequest();
}
return impl::SetConfiguration(trb->packet.wValue);
default:
return xusb::ResultUnknownSetupRequest();
}
}
void ProcessSetupPacketEvent(SetupPacketEventTRB *trb) {
Result r = ProcessSetupPacketEventImpl(trb);
if (r.IsFailure()) {
print(SCREEN_LOG_LEVEL_WARNING, "error 0x%x while handling setup request\n", r.GetValue());
print(SCREEN_LOG_LEVEL_WARNING, " bmRequestType: %d\n", trb->packet.bmRequestType);
print(SCREEN_LOG_LEVEL_WARNING, " bRequest: %d\n", trb->packet.bRequest);
print(SCREEN_LOG_LEVEL_WARNING, " wValue: %d\n", trb->packet.wValue);
print(SCREEN_LOG_LEVEL_WARNING, " wIndex: %d\n", trb->packet.wIndex);
print(SCREEN_LOG_LEVEL_WARNING, " wLenth: %d\n", trb->packet.wLength);
xusb::endpoints[0].Halt();
}
}
void ProcessPortStatusChangeEvent(AbstractTRB *trb) {
auto portsc = t210::T_XUSB_DEV_XHCI.PORTSC();
auto porthalt = t210::T_XUSB_DEV_XHCI.PORTHALT();
print(SCREEN_LOG_LEVEL_DEBUG, "port status changed (0x%08x)\n", portsc.read_value);
if (portsc.CSC) { // connect status change
int port_speed = portsc.PS.Get();
print(SCREEN_LOG_LEVEL_DEBUG, "connect status changed (port speed %d)\n", port_speed);
portsc.CSC.Clear().Commit();
}
if (portsc.PRC.Get()) { // port reset change
print(SCREEN_LOG_LEVEL_DEBUG, "port reset changed (%d)\n", portsc.PR.Get());
if (!portsc.PR.Get()) {
ChangeDeviceState(DeviceState::Default);
}
portsc.PRC.Clear().Commit();
}
if (portsc.WRC) { // warm port reset change
t210::T_XUSB_DEV_XHCI.PORTHALT().HALT_LTSSM.Set(0).Commit();
print(SCREEN_LOG_LEVEL_DEBUG, "warm port reset changed (%d)\n", portsc.WPR.Get());
portsc.WRC.Clear().Commit();
}
if (porthalt.STCHG_REQ) {
print(SCREEN_LOG_LEVEL_DEBUG, "porthalt STCHG_REQ\n");
porthalt.HALT_LTSSM.Set(0).Commit();
}
if (portsc.PLC) { // port link state change
print(SCREEN_LOG_LEVEL_DEBUG, "port link state changed (%d)\n", portsc.PLS.Get());
if (portsc.PLS.Get() == 3) { // U3
ChangeDeviceState(DeviceState::Default);
}
portsc.PLC.Clear().Commit();
}
if (portsc.CEC) { // port configuration link error
print(SCREEN_LOG_LEVEL_DEBUG, "port configuration link error\n");
portsc.CEC.Clear().Commit();
}
}
} // namespace control
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "xusb_trb.h"
#include "xusb_endpoint.h"
namespace ams {
namespace xusb {
namespace control {
enum class DeviceState {
Powered,
Default,
Address,
Configured,
};
extern DeviceState state;
Result SendData(void *data, size_t size);
Result SendStatus(bool direction);
void ProcessEP0TransferEvent(TransferEventTRB *event, TRBBorrow transfer);
void ProcessSetupPacketEvent(SetupPacketEventTRB *trb);
void ProcessPortStatusChangeEvent(AbstractTRB *trb);
} // namespace control
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,368 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xusb_endpoint.h"
#include "xusb.h"
#include "xusb_control.h"
extern "C" {
#include "../lib/log.h"
}
#include<string.h>
namespace ams {
namespace xusb {
void EndpointContext::InitializeForControl() {
memset((void*) this, 0, sizeof(*this));
this->ep_state = 1;
this->cerr = 3;
this->ep_type = 4;
this->max_packet_size = 64;
this->dcs = 1;
this->average_trb_length = 8;
this->cec = 3;
this->seqnum = 0;
}
void EndpointContext::Initialize(const usb::EndpointDescriptor &desc) {
memset((void*) this, 0, sizeof(*this));
this->ep_state = 1;
if (desc.GetEndpointType() != usb::EndpointType::Control && (desc.bEndpointAddress & 0x80)) {
/* In endpoint types are offset by 4. */
this->ep_type = (uint8_t) desc.GetEndpointType() + 4;
} else {
this->ep_type = (uint8_t) desc.GetEndpointType();
}
this->cerr = 3;
this->max_packet_size = desc.wMaxPacketSize;
this->max_burst_size = 0;
this->cec = 3;
}
void EndpointAccessor::RingDoorbell() const {
t210::T_XUSB_DEV_XHCI.DB()
.TARGET.Set(this->no)
.Commit();
}
void EndpointAccessor::RingDoorbell(uint16_t stream_id) const {
t210::T_XUSB_DEV_XHCI.DB()
.STREAMID.Set(stream_id)
.TARGET.Set(this->no)
.Commit();
}
void EndpointAccessor::InitializeForControl(TRB *ring, size_t ring_size) const {
/* Initialize hardware endpoint context for control endpont. */
this->GetContext().InitializeForControl();
/* Initialize transfer ring. */
this->GetRingManager().Initialize(this->GetContext(), ring, ring_size);
}
void EndpointAccessor::Initialize(const usb::EndpointDescriptor &desc, TRB *ring, size_t ring_size) const {
/* Initialize hardawre endpoint context for regular endpoint. */
this->GetContext().Initialize(desc);
/* Initialize transfer ring. */
this->GetRingManager().Initialize(this->GetContext(), ring, ring_size);
this->Reload();
t210::T_XUSB_DEV_XHCI.EP_PAUSE()[this->no].Set(0).Commit();
t210::T_XUSB_DEV_XHCI.EP_HALT()[this->no].Set(0).Commit();
}
void EndpointAccessor::Disable() const {
this->GetContext().ep_state = 0;
this->Reload();
this->ClearPause();
this->ClearHalt();
auto stopped = t210::T_XUSB_DEV_XHCI.EP_STOPPED();
if (stopped[this->no]) {
stopped[this->no].Clear().Commit();
}
}
Result EndpointAccessor::TransferNormal(void *data, size_t size, TRB **trb_out) const {
TRBBorrow trb;
R_TRY(this->EnqueueTRB(&trb));
trb->transfer.InitializeNormal(data, size);
trb->transfer.interrupt_on_completion = true;
trb->transfer.interrupt_on_short_packet = true;
trb.Release();
this->RingDoorbell();
*trb_out = &*trb;
return ResultSuccess();
}
void EndpointAccessor::Halt() const {
auto ep_halt = t210::T_XUSB_DEV_XHCI.EP_HALT();
if (ep_halt[this->no]) {
return;
}
(ep_halt[this->no] = 1).Commit();
/* BootROM polls EP_HALT register, but TRM says to poll STCHG instead. */
while (!t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no]) {
}
t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no].Clear().Commit();
}
void EndpointAccessor::ClearHalt() const {
auto ep_halt = t210::T_XUSB_DEV_XHCI.EP_HALT();
if (!ep_halt[this->no]) {
return;
}
(ep_halt[this->no] = 0).Commit();
/* Bootrom polls EP_HALT register, but TRM says to poll STCHG instead. */
while (!t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no]) {
}
t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no].Clear().Commit();
}
void EndpointAccessor::Pause() const {
auto ep_pause = t210::T_XUSB_DEV_XHCI.EP_PAUSE();
if (ep_pause[this->no]) {
return;
}
(ep_pause[this->no] = 1).Commit();
/* Bootrom polls EP_PAUSE register, but TRM says to poll STCHG instead. */
while (!t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no]) {
}
t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no].Clear().Commit();
}
void EndpointAccessor::ClearPause() const {
auto ep_pause = t210::T_XUSB_DEV_XHCI.EP_PAUSE();
if (!ep_pause[this->no]) {
return;
}
(ep_pause[this->no] = 0).Commit();
/* Bootrom polls EP_PAUSE register, but TRM says to poll STCHG instead. */
while (!t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no]) {
}
t210::T_XUSB_DEV_XHCI.EP_STCHG()[this->no].Clear().Commit();
}
void EndpointAccessor::Reload() const {
auto ep_reload = t210::T_XUSB_DEV_XHCI.EP_RELOAD();
ep_reload[this->no] = 1;
ep_reload.Commit();
while (t210::T_XUSB_DEV_XHCI.EP_RELOAD()[this->no]) {
}
}
TRBBorrow EndpointAccessor::AcceptCompletedTRB(TransferEventTRB *trb) const {
return TRBBorrow(&this->GetRingManager(), trb->GetSourceTRB());
}
void EndpointAccessor::ResetAndReloadTransferRing() const {
this->GetRingManager().Reset(this->GetContext());
this->Reload();
}
void EndpointAccessor::DumpTransferRingForDebug() const {
this->GetRingManager().DumpTransferRingForDebug();
}
TRBBorrow::TRBBorrow(TRBBorrow &&other) :
ring(other.ring),
trb(other.trb),
state(other.state),
cycle_state(other.cycle_state) {
other.state = State::Empty;
}
TRBBorrow &TRBBorrow::operator=(TRBBorrow &&other) {
this->Release();
this->ring = other.ring;
this->trb = other.trb;
this->state = other.state;
this->cycle_state = other.cycle_state;
other.state = State::Empty;
return *this;
}
void TRBBorrow::Release() {
if (this->state == State::BorrowForEnqueue) {
this->trb->abstract.SetCycle(this->cycle_state);
this->state = State::Empty;
} else if (this->state == State::BorrowForRecycle) {
this->ring->RecycleTRB(this->trb);
this->state = State::Empty;
}
}
void EndpointRingManager::Initialize(EndpointContext &ep_context, TRB *ring, size_t ring_size) {
this->ring = ring;
this->ring_size = ring_size;
this->Reset(ep_context);
}
void EndpointRingManager::Reset(EndpointContext &ep_context) {
memset(this->ring, 0, sizeof(TRB) * this->ring_size);
this->producer_cycle_state = true;
this->enqueue = &this->ring[0];
this->dequeue = &this->ring[0];
ep_context.dcs = this->producer_cycle_state;
ep_context.tr_dequeue_ptr = ((uint64_t) &this->ring[0]) >> 4;
}
size_t EndpointRingManager::GetFreeTRBCount() {
/* Last TRB is reserved for link. */
size_t adjusted_ring_size = (this->ring_size - 1);
if (this->ring_full) {
return 0;
}
return adjusted_ring_size - ((this->enqueue + adjusted_ring_size - this->dequeue) % adjusted_ring_size);
}
TRB *EndpointRingManager::EnqueueTRB(bool chain) {
if (ring_full) {
return nullptr;
}
TRB *trb = this->enqueue++;
if (this->enqueue == this->ring + (this->ring_size - 1)) {
this->enqueue->link.Initialize(&this->ring[0]);
this->enqueue->link.SetToggleCycle(true);
this->enqueue->link.SetChain(chain);
this->enqueue->abstract.SetCycle(this->producer_cycle_state);
this->enqueue = &this->ring[0];
this->producer_cycle_state = !this->producer_cycle_state;
}
if (this->enqueue == this->dequeue) {
this->ring_full = true;
}
trb->abstract.Clear();
return trb;
}
void EndpointRingManager::RecycleTRB(TRB *trb) {
if (trb + 1 == &this->ring[this->ring_size-1]) {
this->dequeue = &this->ring[0];
} else {
this->dequeue = trb + 1;
}
this->ring_full = false;
}
void EndpointRingManager::DebugState() {
ScreenLogLevel ll = (ScreenLogLevel) (SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX);
print(ll, "%8s", "address ");
for (size_t i = 0; i < this->ring_size; i++) {
TRB *ptr = &this->ring[i];
print(ll, "%x", ((uint32_t) ptr >> 4) & 0xf);
}
print(ll, "\n%8s", "cycle ");
for (size_t i = 0; i < this->ring_size; i++) {
TRB *ptr = &this->ring[i];
print(ll, "%d", ptr->abstract.GetCycle());
}
print(ll, "\n%8s", "deq/enq ");
for (size_t i = 0; i < this->ring_size; i++) {
TRB *ptr = &this->ring[i];
if (this->dequeue == ptr && this->enqueue == ptr) {
print(ll, "!");
} else if (this->dequeue == ptr) {
print(ll, "D");
} else if (this->enqueue == ptr) {
print(ll, "E");
} else if (ptr == &this->ring[this->ring_size-1]) {
print(ll, "L");
} else {
print(ll, " ");
}
}
print(ll, "\n%8s", "ioc ");
for (size_t i = 0; i < this->ring_size; i++) {
TRB *ptr = &this->ring[i];
print(ll, "%d", ptr->transfer.interrupt_on_completion);
}
print(ll, "\n");
}
void EndpointRingManager::DumpTransferRingForDebug() {
ScreenLogLevel ll = (ScreenLogLevel) (SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX);
print(ll, " enq deq type \n");
for (TRB *ptr = &this->ring[0]; ptr < &this->ring[this->ring_size]; ptr++) {
print(ll, " %3s %3s %3d %08x %08x %08x %08x\n",
ptr == this->enqueue ? "[E]" : "",
ptr == this->dequeue ? "[D]" : "",
ptr->transfer.trb_type,
ptr->abstract.field0,
ptr->abstract.field1,
ptr->abstract.field2,
ptr->abstract.field3);
}
print(ll, "pcs: %d\n", this->producer_cycle_state);
print(ll, "full: %s\n", this->ring_full ? "yes" : "no");
}
void Endpoints::ClearNonControlEndpoints() {
memset(&contexts[2], 0, sizeof(contexts) - 2*sizeof(contexts[0]));
}
void Endpoints::SetEP0DeviceAddress(uint16_t addr) {
this->contexts[0].device_address = addr;
}
Endpoints endpoints __attribute__((section(".dram")));
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,346 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "xusb_trb.h"
#include "../reg/reg_xusb_dev.h"
#include<vapours/results/xusb_gadget_results.hpp>
#include<stddef.h>
namespace ams {
namespace xusb {
struct EndpointContext {
uint32_t ep_state:3;
uint32_t :5;
uint32_t multi:2;
uint32_t max_p_streams:5;
uint32_t lsa:1;
uint32_t interval:8;
uint32_t :8;
uint32_t :1;
uint32_t cerr:2;
uint32_t ep_type:3;
uint32_t :1;
uint32_t hid:1;
uint32_t max_burst_size:8;
uint32_t max_packet_size:16;
uint64_t dcs:1;
uint64_t :3;
uint64_t tr_dequeue_ptr:60;
uint32_t average_trb_length:16;
uint32_t max_esit_payload:16;
uint32_t event_data_transfer_length_accumulator:24;
uint32_t :1;
uint32_t ptd:1;
uint32_t sxs:1;
uint32_t seqnum:5;
uint32_t cprog:8;
uint32_t s_byte:7;
uint32_t tp:2;
uint32_t rec:1;
uint32_t cec:2;
uint32_t ced:1;
uint32_t hsp:1;
uint32_t rty:1;
uint32_t std:1;
uint32_t status:8;
uint32_t data_offset:17;
uint32_t :4;
uint32_t lpa:1;
uint32_t num_trb:5;
uint32_t num_p:5;
uint32_t scratchpad1;
uint32_t scratchpad2;
uint32_t cping:8;
uint32_t sping:8;
uint32_t tc:2;
uint32_t ns:1;
uint32_t ro:1;
uint32_t tlm:1;
uint32_t dlm:1;
uint32_t hsp2:1;
uint32_t rty2:1;
uint32_t stop_reclaim_request:8;
uint32_t device_address:8;
uint32_t hub_address:8;
uint32_t root_port_number:8;
uint32_t slot_id:8;
uint32_t routing_string:20;
uint32_t speed:4;
uint32_t lpu:1;
uint32_t myy:1;
uint32_t hub:1;
uint32_t dci:5;
uint32_t tt_hub_slot_id:8;
uint32_t tt_port_num:8;
uint32_t ssf:4;
uint32_t sps:2;
uint32_t interrupt_target:10;
uint64_t frz:1;
uint64_t end:1;
uint64_t elm:1;
uint64_t mrk:1;
uint64_t endpoint_link:60;
void InitializeForControl();
void Initialize(const usb::EndpointDescriptor &desc);
} __attribute__((aligned(64)));
enum Dir {
Out,
In,
};
struct EpAddr {
static inline EpAddr Decode(uint8_t addr) {
return EpAddr {
.no = (uint8_t) (addr & 0b1111),
.direction = (addr >> 7) ? Dir::In : Dir::Out,
};
}
uint8_t no;
Dir direction;
};
class EndpointRingManager {
public:
void Initialize(EndpointContext &ep_context, TRB *ring, size_t ring_size);
void Reset(EndpointContext &ep_context);
inline size_t GetRingUsableCount() {
return this->ring_size - 1;
}
size_t GetFreeTRBCount();
void DumpTransferRingForDebug(); // long form
void DebugState();
TRB *EnqueueTRB(bool chain);
void RecycleTRB(TRB *trb);
inline bool GetProducerCycleState() {
return this->producer_cycle_state;
}
private:
TRB *ring = nullptr;
size_t ring_size = 0;
bool ring_full = false;
bool producer_cycle_state = true;
TRB *dequeue = nullptr;
TRB *enqueue = nullptr;
};
/* TRB ownership:
Initially, all TRBs are owned by the transfer ring manager.
By calling EnqueueTRB(), you are borrowing a TRB from the ring.
By calling Release() or allowing TRBBorrow to be destructed, the borrow is transferred to the hardware.
When the hardware is finished with the TRB and interrupts for completion, the borrow is transferred back to the software.
By calling Release() or allowing TRBRecycleHelper to be destructed, the TRB is recycled to the transfer ring manager.
*/
class EndpointAccessor;
class TRBBorrow {
public:
inline TRBBorrow() :
state(State::Empty) {
}
private:
friend class EndpointAccessor;
inline TRBBorrow(EndpointRingManager *ring, TRB *trb) :
ring(ring),
trb(trb),
state(State::BorrowForRecycle) {
}
inline TRBBorrow(EndpointRingManager *ring, TRB *trb, bool cycle_state) :
ring(ring),
trb(trb),
state(State::BorrowForEnqueue),
cycle_state(cycle_state) {
}
public:
inline ~TRBBorrow() {
Release();
}
TRBBorrow(TRBBorrow &) = delete;
TRBBorrow(TRBBorrow &&);
TRBBorrow &operator=(TRBBorrow &) = delete;
TRBBorrow &operator=(TRBBorrow &&);
void Release();
inline TRB &operator*() {
return *this->trb;
}
inline TRB *operator->() {
return this->trb;
}
private:
EndpointRingManager *ring;
TRB *trb;
enum class State {
Empty,
BorrowForEnqueue,
BorrowForRecycle
} state;
bool cycle_state;
};
class Endpoints;
class EndpointAccessor {
public:
constexpr inline EndpointAccessor(uint8_t ep_index, Endpoints &eps) :
no(ep_index),
endpoints(eps) {
}
void InitializeForControl(TRB *ring, size_t ring_size) const;
void Initialize(const usb::EndpointDescriptor &desc, TRB *ring, size_t ring_size) const;
void Disable() const;
inline size_t GetRingUsableCount() const {
return this->GetRingManager().GetRingUsableCount();
}
inline size_t GetFreeTRBCount() const {
return this->GetRingManager().GetFreeTRBCount();
}
inline Result EnqueueTRB(TRBBorrow *borrow, bool chain=false) const {
// it is important to call this before Enqueue
bool cycle_state = this->GetRingManager().GetProducerCycleState();
TRB *trb = this->GetRingManager().EnqueueTRB(chain);
R_UNLESS(trb != nullptr, xusb::ResultTransferRingFull());
*borrow = TRBBorrow(
&this->GetRingManager(),
trb,
cycle_state);
return ResultSuccess();
}
Result TransferNormal(void *buffer, size_t size, TRB **trb_out) const;
void Halt() const;
void ClearHalt() const;
void Pause() const;
void ClearPause() const;
void Reload() const;
void RingDoorbell() const;
void RingDoorbell(uint16_t stream_id) const;
TRBBorrow AcceptCompletedTRB(TransferEventTRB *trb) const;
inline uint8_t GetIndex() const {
return this->no;
}
void ResetAndReloadTransferRing() const;
void DumpTransferRingForDebug() const;
private:
inline EndpointContext &GetContext() const;
inline EndpointRingManager &GetRingManager() const;
void Initialize(TRB *ring, size_t ring_size);
uint8_t no;
Endpoints &endpoints;
};
class Endpoints {
public:
static const size_t NR_EPS = 32;
private:
friend class EndpointAccessor;
// structure-of-arrays instead of array-of-structures
// to improve alignment.
EndpointRingManager rings[NR_EPS];
EndpointContext contexts[NR_EPS];
public:
void ClearNonControlEndpoints();
void SetEP0DeviceAddress(uint16_t addr);
constexpr inline EndpointAccessor operator[](EpAddr addr) {
return EndpointAccessor(addr.no * 2 + (addr.direction == Dir::In ? 1 : 0), *this);
};
constexpr inline EndpointAccessor operator[](int no) {
return EndpointAccessor(no, *this);
};
inline uintptr_t GetContextsForHardware() {
return (uintptr_t) contexts;
}
};
inline EndpointContext &EndpointAccessor::GetContext() const {
return this->endpoints.contexts[this->no];
}
inline EndpointRingManager &EndpointAccessor::GetRingManager() const {
return this->endpoints.rings[this->no];
}
extern Endpoints endpoints;
static_assert(sizeof(EndpointContext) == 64, "Endpoint context should be 64 bytes");
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,120 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xusb_event_ring.h"
#include "xusb.h"
#include "xusb_control.h"
#include "xusb_endpoint.h"
#include "../reg/reg_xusb_dev.h"
extern "C" {
#include "../lib/log.h"
#include "../utils.h"
}
#include<array>
#include<string.h>
namespace ams {
namespace xusb {
void EventRing::Initialize() {
memset((void*) &storage[0], 0, sizeof(storage));
if (((uintptr_t) &storage[0] & 0b1111) != 0) {
fatal_error("xusb initialization failed: event ring storage is misaligned\n");
}
this->consumer_dequeue_ptr = &this->storage[0];
this->consumer_cycle_state = true;
t210::T_XUSB_DEV_XHCI
.ERST0BALO(0).ADDRLO.Set((uint32_t) &this->storage[0]).Commit()
.ERST0BAHI(0).ADDRHI.Set(0).Commit()
.ERST1BALO(0).ADDRLO.Set((uint32_t) &this->storage[0x10]).Commit()
.ERST1BAHI(0).ADDRHI.Set(0).Commit()
.ERSTSZ(0)
.ERST0SZ.Set(0x10)
.ERST1SZ.Set(0x10)
.Commit()
.EREPLO(0)
.ADDRLO.Set((uint32_t) &this->storage[0])
.ECS.Set(this->consumer_cycle_state)
.Commit()
.EREPHI(0).ADDRHI.Set(0).Commit()
.ERDPLO(0).ADDRLO.Set((uint32_t) &this->storage[0]).Commit()
.ERDPHI(0).ADDRHI.Set(0).Commit();
}
void EventRing::Process() {
auto st = t210::T_XUSB_DEV_XHCI.ST();
if (st.IP) {
/* Clear interrupt pending. */
st.IP.Clear().Commit();
}
while (this->consumer_dequeue_ptr->abstract.GetCycle() == this->consumer_cycle_state) {
switch(this->consumer_dequeue_ptr->abstract.GetType()) {
case TRBType::SetupPacketEvent:
control::ProcessSetupPacketEvent(&this->consumer_dequeue_ptr->setup_packet_event);
break;
case TRBType::PortStatusChangeEvent:
control::ProcessPortStatusChangeEvent(&this->consumer_dequeue_ptr->abstract);
break;
case TRBType::TransferEvent: {
TransferEventTRB *te = &this->consumer_dequeue_ptr->transfer_event;
TRBBorrow completed_transfer = xusb::endpoints[te->ep_id].AcceptCompletedTRB(te);
if (te->ep_id == 0) {
xusb::control::ProcessEP0TransferEvent(te, std::move(completed_transfer));
} else {
xusb::GetCurrentGadget()->ProcessTransferEvent(te, std::move(completed_transfer));
}
break; }
default:
print(SCREEN_LOG_LEVEL_WARNING, "got unrecognized TRB type on event ring: %d\n", (int) this->consumer_dequeue_ptr->abstract.GetType());
break;
}
if ((size_t) (this->consumer_dequeue_ptr - &this->storage[0]) == std::size(this->storage) - 1) {
this->consumer_dequeue_ptr = &this->storage[0];
this->consumer_cycle_state = !this->consumer_cycle_state;
} else {
this->consumer_dequeue_ptr++;
}
/* Some situations cause the event ring to continue filling up while
we're processing it, such as if we are submitting transfers and
they are completing before we fully yield out to the main
loop. */
t210::T_XUSB_DEV_XHCI.ERDPLO()
.ADDRLO.Set((uint32_t) this->consumer_dequeue_ptr)
.Commit();
}
t210::T_XUSB_DEV_XHCI.ERDPLO()
.EHB.Clear()
.ADDRLO.Set((uint32_t) this->consumer_dequeue_ptr)
.Commit();
}
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "xusb_trb.h"
namespace ams {
namespace xusb {
class EventRing {
public:
void Initialize();
void Process();
private:
TRB storage[0x20];
TRB *consumer_dequeue_ptr;
bool consumer_cycle_state;
} __attribute__((aligned(16)));
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,287 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xusb.h"
#include "xusb_control.h"
#include "xusb_endpoint.h"
#include<array>
extern "C" {
#include "../lib/log.h"
#include "../utils.h"
#include "../btn.h"
}
namespace ams {
namespace xusb {
namespace test {
USB_DECLARE_STRING_DESCRIPTOR(langid, u"\x0409"); // English (US)
USB_DECLARE_STRING_DESCRIPTOR(manu, u"Test Manufacturer");
USB_DECLARE_STRING_DESCRIPTOR(product, u"Test Product");
USB_DECLARE_STRING_DESCRIPTOR(serial, u"Test Serial Number");
USB_DECLARE_STRING_DESCRIPTOR(configuration, u"Test Configuration");
USB_DECLARE_STRING_DESCRIPTOR(interface, u"Test Interface");
static constexpr usb::StringDescriptorIndexer<SD_langid,
SD_manu,
SD_product,
SD_serial,
SD_configuration,
SD_interface> sd_indexer;
static xusb::TRB in_ring[5];
static xusb::TRB out_ring[5];
static char buffer[513] __attribute__((section(".dram"))) = {0};
class XusbTestGadget : public Gadget {
public:
static constexpr usb::DeviceDescriptor device_descriptor = {
{
.bLength = sizeof(usb::DeviceDescriptor),
.bDescriptorType = usb::DescriptorType::DEVICE,
},
{
.bcdUSB = 0x210,
.bDeviceClass = 0,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
.bMaxPacketSize0 = 64,
.idVendor = 0x1209,
.idProduct = 0x8b00,
.bcdDevice = 0x100,
.iManufacturer = sd_indexer.manu,
.iProduct = sd_indexer.product,
.iSerialNumber = sd_indexer.serial,
.bNumConfigurations = 1,
}
};
static constexpr usb::DeviceQualifierDescriptor device_qualifier_descriptor = {
{
.bLength = sizeof(usb::DeviceQualifierDescriptor),
.bDescriptorType = usb::DescriptorType::DEVICE_QUALIFIER,
},
{
.bcdUSB = 0x210,
.bDeviceClass = 0,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
.bMaxPacketSize0 = 64,
.bNumConfigurations = 1,
.bReserved = 0,
}
};
static const struct WholeConfigurationDescriptor {
usb::ConfigurationDescriptor configuration_descriptor = {
{
.bLength = sizeof(usb::ConfigurationDescriptor),
.bDescriptorType = usb::DescriptorType::CONFIGURATION,
},
{
.wTotalLength = sizeof(WholeConfigurationDescriptor),
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = 4,
.bmAttributes = 0x80,
.bMaxPower = 0,
}
};
usb::InterfaceDescriptor interface_descriptor {
{
.bLength = sizeof(usb::InterfaceDescriptor),
.bDescriptorType = usb::DescriptorType::INTERFACE,
},
{
.bInterfaceNumber = 0,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = 0xff,
.bInterfaceSubClass = 0xff,
.bInterfaceProtocol = 0xff,
.iInterface = 5,
}
};
usb::EndpointDescriptor endpoint_in_descriptor {
{
.bLength = sizeof(usb::EndpointDescriptor),
.bDescriptorType = usb::DescriptorType::ENDPOINT,
},
{
.bEndpointAddress = 0x81,
.bmAttributes = 0x2,
.wMaxPacketSize = 512,
.bInterval = 1,
}
};
usb::EndpointDescriptor endpoint_out_descriptor {
{
.bLength = sizeof(usb::EndpointDescriptor),
.bDescriptorType = usb::DescriptorType::ENDPOINT,
},
{
.bEndpointAddress = 0x01,
.bmAttributes = 0x2,
.wMaxPacketSize = 512,
.bInterval = 1,
}
};
} __attribute__((packed)) whole_configuration_descriptor;
virtual Result GetDeviceDescriptor(uint8_t index, const usb::DeviceDescriptor **descriptor, uint16_t *length) override {
R_UNLESS(index == 0, xusb::ResultInvalidDescriptorIndex());
*descriptor = &device_descriptor;
*length = sizeof(device_descriptor);
return ResultSuccess();
}
virtual Result GetDeviceQualifierDescriptor(uint8_t index, const usb::DeviceQualifierDescriptor **descriptor, uint16_t *length) override {
R_UNLESS(index == 0, xusb::ResultInvalidDescriptorIndex());
*descriptor = &device_qualifier_descriptor;
*length = sizeof(device_qualifier_descriptor);
return ResultSuccess();
}
virtual Result GetConfigurationDescriptor(uint8_t index, const usb::ConfigurationDescriptor **descriptor, uint16_t *length) override {
R_UNLESS(index == 0, xusb::ResultInvalidDescriptorIndex());
*descriptor = &whole_configuration_descriptor.configuration_descriptor;
*length = sizeof(whole_configuration_descriptor);
return ResultSuccess();
}
virtual Result GetBOSDescriptor(const usb::BOSDescriptor **descriptor, uint16_t *length) override {
return ResultUnknownDescriptorType();
}
virtual Result GetStringDescriptor(uint8_t index, uint16_t language, const usb::CommonDescriptor **descriptor, uint16_t *length) override {
R_UNLESS(language == 0x0409 || (language == 0 && index == 0), xusb::ResultInvalidDescriptorIndex());
R_UNLESS(sd_indexer.GetStringDescriptor(index, language, descriptor, length), xusb::ResultInvalidDescriptorIndex());
return ResultSuccess();
}
static constexpr auto out = xusb::endpoints[xusb::EpAddr {1, xusb::Dir::Out}];
static constexpr auto in = xusb::endpoints[xusb::EpAddr {1, xusb::Dir::In}];
virtual Result SetConfiguration(uint16_t configuration) override {
R_UNLESS(configuration <= 1, xusb::ResultInvalidConfiguration());
xusb::endpoints.ClearNonControlEndpoints();
out.Initialize(whole_configuration_descriptor.endpoint_out_descriptor, out_ring, std::size(out_ring));
in.Initialize(whole_configuration_descriptor.endpoint_in_descriptor, in_ring, std::size(in_ring));
print(SCREEN_LOG_LEVEL_DEBUG, "configured and enabled endpoints!\n");
return ResultSuccess();
}
virtual Result Deconfigure() override {
out.Disable();
in.Disable();
return ResultSuccess();
}
TRB *last_out_trb = nullptr;
TRB *last_in_trb = nullptr;
Result SubmitOutTRB() {
TRBBorrow trb;
R_TRY(out.EnqueueTRB(&trb));
print(SCREEN_LOG_LEVEL_DEBUG, "submitting out trb %p\n", &*trb);
trb->transfer.InitializeNormal((void*) buffer, sizeof(buffer)-1);
trb->transfer.interrupt_on_completion = true;
trb->transfer.interrupt_on_short_packet = true;
trb.Release();
last_out_trb = &*trb;
out.RingDoorbell();
return ResultSuccess();
}
Result SubmitInTRB(size_t length) {
TRBBorrow trb;
R_TRY(in.EnqueueTRB(&trb));
print(SCREEN_LOG_LEVEL_DEBUG, "submitting in trb %p\n", &*trb);
trb->transfer.InitializeNormal((void*) buffer, length);
trb->transfer.interrupt_on_completion = true;
trb->transfer.interrupt_on_short_packet = true;
trb.Release();
last_in_trb = &*trb;
in.RingDoorbell();
return ResultSuccess();
}
virtual void PostConfigure() override {
SubmitOutTRB();
}
virtual void ProcessTransferEvent(TransferEventTRB *event, TRBBorrow transfer) override {
print(SCREEN_LOG_LEVEL_DEBUG, "gadget got transfer event for ep %d\n", event->ep_id);
if (event->ep_id == out.GetIndex()) {
if (&*transfer == last_out_trb) {
print(SCREEN_LOG_LEVEL_DEBUG, " out transfer completed: %d bytes remain\n", event->trb_transfer_length);
buffer[transfer->transfer.transfer_length - event->trb_transfer_length] = 0;
print(SCREEN_LOG_LEVEL_DEBUG, " \"%s\"\n", buffer);
SubmitInTRB(transfer->transfer.transfer_length - event->trb_transfer_length);
} else {
print(SCREEN_LOG_LEVEL_DEBUG, " got completion for unexpected OUT trb (got %p, expected %p)\n", &*transfer, last_out_trb);
}
} else if (event->ep_id == in.GetIndex()) {
if (&*transfer == last_in_trb) {
SubmitOutTRB();
} else {
print(SCREEN_LOG_LEVEL_DEBUG, " got completion for unexpected IN trb (got %p, expected %p)\n", &*transfer, last_out_trb);
}
}
}
};
static XusbTestGadget test_gadget;
Gadget &GetTestGadget() {
return test_gadget;
}
} // namespace test
} // namespace xusb
} // namespace ams

View File

@ -0,0 +1,29 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "xusb.h"
namespace xusb {
namespace test {
Gadget &GetTestGadget();
} // namespace test
} // namespace xusb

View File

@ -0,0 +1,185 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "usb_types.h"
#include<stdint.h>
#include<string.h>
namespace ams {
namespace xusb {
enum class TRBType : uint8_t {
// transfer TRBs
Normal = 1,
SetupStage = 2,
DataStage = 3,
StatusStage = 4,
Isoch = 5,
Link = 6,
EventData = 7,
NoOp = 8,
// event TRBs
TransferEvent = 32,
PortStatusChangeEvent = 34,
SetupPacketEvent = 63, // vendor defined
};
union TRB;
struct AbstractTRB {
uint32_t field0;
uint32_t field1;
uint32_t field2;
uint32_t field3;
inline void Clear() {
// leave cycle bit so hardware doesn't accidentlly consume this TRB
this->field0 = 0;
this->field1 = 0;
this->field2 = 0;
this->field3&= 1;
}
inline bool GetCycle() {
return this->field3 & 1;
}
inline void SetCycle(bool cycle) {
this->field3&= ~1;
this->field3|= cycle;
}
inline TRBType GetType() {
return (TRBType) ((this->field3 >> 10) & 0b111111);
}
inline void SetType(TRBType type) {
this->field3&= ~(0b111111 << 10);
this->field3|= (((uint32_t) type) & 0b111111) << 10;
}
} __attribute__((aligned(16)));
struct LinkTRB : protected AbstractTRB {
inline void Initialize(TRB *link) {
AbstractTRB::SetType(TRBType::Link);
this->field0 = (uint32_t) link;
}
inline void SetToggleCycle(bool tc) {
this->field3&= ~2;
this->field3|= tc << 1;
}
inline void SetChain(bool chain) {
this->field3&= ~0x10;
this->field3|= chain << 4;
}
} __attribute__((aligned(16)));
struct TransferTRB {
uint32_t data_ptr_lo;
uint32_t data_ptr_hi;
uint32_t transfer_length:17;
uint32_t td_size:5;
uint32_t interrupter_target:10;
uint32_t :0;
uint32_t cycle:1;
uint32_t evaluate_next_trb:1;
uint32_t interrupt_on_short_packet:1;
uint32_t no_snoop:1;
uint32_t chain_bit:1;
uint32_t interrupt_on_completion:1;
uint32_t immediate_data:1;
uint32_t :2; // reserved
uint32_t block_event_interrupt:1;
uint32_t trb_type:6;
uint32_t dir:1;
uint32_t :15;
inline void InitializeNoOp() {
this->trb_type = (uint32_t) TRBType::NoOp;
}
inline void InitializeNormal(void *data, size_t length) {
this->data_ptr_lo = (uint32_t) data;
this->transfer_length = length;
this->trb_type = (uint32_t) TRBType::Normal;
}
inline void InitializeDataStage(bool dir, void *data, size_t length) {
this->data_ptr_lo = (uint32_t) data;
this->transfer_length = length;
this->trb_type = (uint32_t) TRBType::DataStage;
this->dir = dir;
}
// see Table 4-7 on page 213 of XHCI spec
inline void InitializeStatusStage(bool dir) {
this->trb_type = (uint32_t) TRBType::StatusStage;
this->dir = dir;
}
} __attribute__((aligned(16)));
struct TransferEventTRB {
uint32_t trb_ptr_lo;
uint32_t trb_ptr_hi;
uint32_t trb_transfer_length:24;
uint32_t completion_code:8;
uint32_t cycle:1;
uint32_t :1;
uint32_t ed:1;
uint32_t :7;
uint32_t trb_type:6;
uint32_t ep_id:5;
inline TRB *GetSourceTRB() {
return (TRB*) trb_ptr_lo;
}
} __attribute__((aligned(16)));
struct SetupPacketEventTRB {
usb::SetupPacket packet;
uint16_t seq_num;
uint16_t field2;
uint32_t field3;
inline bool GetEventDataFlag() {
return (field3 & 0b100) != 0;
}
} __attribute__((aligned(16)));
union TRB {
public:
AbstractTRB abstract;
LinkTRB link;
TransferTRB transfer;
TransferEventTRB transfer_event;
SetupPacketEventTRB setup_packet_event;
} __attribute__((aligned(16)));
static_assert(sizeof(TRB) == 16, "TRB should be 16 bytes");
} // namespace xusb
} // namespace ams

View File

@ -20,64 +20,98 @@
#include "lib/log.h" #include "lib/log.h"
FATFS sd_fs; FATFS sd_fs;
static bool g_sd_mounted = false; static int g_sd_device_rc = 0;
static bool g_sd_initialized = false; static int g_sd_fs_rc = 0;
static bool g_ahb_redirect_enabled = false;
sdmmc_t g_sd_sdmmc; sdmmc_t g_sd_sdmmc;
sdmmc_device_t g_sd_device; sdmmc_device_t g_sd_device;
bool acquire_sd_device(void)
{
/* Already initialized. */
if (g_sd_device_rc++ > 0)
return true;
/* Enable AHB redirection if necessary. */
mc_acquire_ahb_redirect();
if (sdmmc_device_sd_init(&g_sd_device, &g_sd_sdmmc, SDMMC_BUS_WIDTH_4BIT, SDMMC_SPEED_UHS_SDR104))
return true;
mc_release_ahb_redirect();
g_sd_device_rc--;
return false;
}
void release_sd_device(void)
{
/* No need to finalize. */
if (--g_sd_device_rc > 0)
return;
sdmmc_device_finish(&g_sd_device);
/* Disable AHB redirection if necessary. */
mc_release_ahb_redirect();
}
bool mount_sd(void) bool mount_sd(void)
{ {
/* Already mounted. */ /* Already mounted. */
if (g_sd_mounted) if (g_sd_fs_rc++ > 0)
return true; return true;
/* Enable AHB redirection if necessary. */ /* Make sure SD device is initialized. */
if (!g_ahb_redirect_enabled) { if (!acquire_sd_device()) {
mc_enable_ahb_redirect(); g_sd_fs_rc--;
g_ahb_redirect_enabled = true; return false;
} }
if (!g_sd_initialized) { /* Mount SD filesystem. */
/* Initialize SD. */ if (f_mount(&sd_fs, "", 1) == FR_OK) {
if (sdmmc_device_sd_init(&g_sd_device, &g_sd_sdmmc, SDMMC_BUS_WIDTH_4BIT, SDMMC_SPEED_UHS_SDR104)) print(SCREEN_LOG_LEVEL_INFO, "Mounted SD card!\n");
{ return true;
g_sd_initialized = true;
/* Mount SD. */
if (f_mount(&sd_fs, "", 1) == FR_OK) {
print(SCREEN_LOG_LEVEL_INFO, "Mounted SD card!\n");
g_sd_mounted = true;
}
}
else
fatal_error("Failed to initialize the SD card!.\n");
} }
return g_sd_mounted; release_sd_device();
g_sd_fs_rc--;
return false;
} }
void unmount_sd(void) void unmount_sd(void)
{ {
if (g_sd_mounted) if (--g_sd_fs_rc > 0)
{ return;
f_mount(NULL, "", 1);
sdmmc_device_finish(&g_sd_device);
g_sd_mounted = false;
}
/* Disable AHB redirection if necessary. */ f_mount(NULL, "", 1);
if (g_ahb_redirect_enabled) {
mc_disable_ahb_redirect(); release_sd_device();
g_ahb_redirect_enabled = false; }
void temporary_unmount_sd(bool *was_mounted)
{
if (g_sd_fs_rc > 0) {
f_mount(NULL, "", 1);
*was_mounted = true;
} else {
*was_mounted = false;
}
}
void temporary_remount_sd(void)
{
if (f_mount(&sd_fs, "", 1) != FR_OK) {
fatal_error("Failed to remount SD card after temporary operation!\n");
} }
} }
uint32_t get_file_size(const char *filename) uint32_t get_file_size(const char *filename)
{ {
/* SD card hasn't been mounted yet. */ /* SD card hasn't been mounted yet. */
if (!g_sd_mounted) if (g_sd_fs_rc == 0)
return 0; return 0;
/* Open the file for reading. */ /* Open the file for reading. */
@ -97,7 +131,7 @@ uint32_t get_file_size(const char *filename)
int read_from_file(void *dst, uint32_t dst_size, const char *filename) int read_from_file(void *dst, uint32_t dst_size, const char *filename)
{ {
/* SD card hasn't been mounted yet. */ /* SD card hasn't been mounted yet. */
if (!g_sd_mounted) if (g_sd_fs_rc == 0)
return 0; return 0;
/* Open the file for reading. */ /* Open the file for reading. */
@ -119,7 +153,7 @@ int read_from_file(void *dst, uint32_t dst_size, const char *filename)
int write_to_file(void *src, uint32_t src_size, const char *filename) int write_to_file(void *src, uint32_t src_size, const char *filename)
{ {
/* SD card hasn't been mounted yet. */ /* SD card hasn't been mounted yet. */
if (!g_sd_mounted) if (g_sd_fs_rc == 0)
return 0; return 0;
/* Open the file for writing. */ /* Open the file for writing. */

View File

@ -26,8 +26,14 @@
extern sdmmc_t g_sd_sdmmc; extern sdmmc_t g_sd_sdmmc;
extern sdmmc_device_t g_sd_device; extern sdmmc_device_t g_sd_device;
bool acquire_sd_device(void);
void release_sd_device(void);
bool mount_sd(void); bool mount_sd(void);
void unmount_sd(void); void unmount_sd(void);
void temporary_unmount_sd(bool *was_mounted);
void temporary_remount_sd(void);
uint32_t get_file_size(const char *filename); uint32_t get_file_size(const char *filename);
int read_from_file(void *dst, uint32_t dst_size, const char *filename); int read_from_file(void *dst, uint32_t dst_size, const char *filename);
int write_to_file(void *src, uint32_t src_size, const char *filename); int write_to_file(void *src, uint32_t src_size, const char *filename);

View File

@ -66,8 +66,8 @@ void config_gpios()
pinmux->pe6 = PINMUX_INPUT; pinmux->pe6 = PINMUX_INPUT;
pinmux->ph6 = PINMUX_INPUT; pinmux->ph6 = PINMUX_INPUT;
gpio_configure_mode(TEGRA_GPIO(G, 0), GPIO_MODE_GPIO); gpio_configure_mode(TEGRA_GPIO(G, 0), GPIO_MODE_SFIO);
gpio_configure_mode(TEGRA_GPIO(D, 1), GPIO_MODE_GPIO); gpio_configure_mode(TEGRA_GPIO(D, 1), GPIO_MODE_SFIO);
gpio_configure_mode(TEGRA_GPIO(E, 6), GPIO_MODE_GPIO); gpio_configure_mode(TEGRA_GPIO(E, 6), GPIO_MODE_GPIO);
gpio_configure_mode(TEGRA_GPIO(H, 6), GPIO_MODE_GPIO); gpio_configure_mode(TEGRA_GPIO(H, 6), GPIO_MODE_GPIO);
gpio_configure_direction(TEGRA_GPIO(G, 0), GPIO_DIRECTION_INPUT); gpio_configure_direction(TEGRA_GPIO(G, 0), GPIO_DIRECTION_INPUT);
@ -78,6 +78,7 @@ void config_gpios()
i2c_config(I2C_1); i2c_config(I2C_1);
i2c_config(I2C_5); i2c_config(I2C_5);
uart_config(UART_A); uart_config(UART_A);
uart_config(UART_B);
/* Configure volume up/down as inputs. */ /* Configure volume up/down as inputs. */
gpio_configure_mode(GPIO_BUTTON_VOL_UP, GPIO_MODE_GPIO); gpio_configure_mode(GPIO_BUTTON_VOL_UP, GPIO_MODE_GPIO);
@ -178,6 +179,8 @@ void config_se_brom()
pmc->reset_status = 0; pmc->reset_status = 0;
} }
extern uint8_t __dram_start__[], __dram_end__[];
void nx_hwinit() void nx_hwinit()
{ {
volatile tegra_pmc_t *pmc = pmc_get_regs(); volatile tegra_pmc_t *pmc = pmc_get_regs();
@ -213,10 +216,9 @@ void nx_hwinit()
config_gpios(); config_gpios();
/* Uncomment for UART debugging. */ /* Uncomment for UART debugging. */
/*
clkrst_reboot(CARDEVICE_UARTC); clkrst_reboot(CARDEVICE_UARTB);
uart_init(UART_C, 115200); uart_init(UART_B, 115200);
*/
/* Reboot CL-DVFS. */ /* Reboot CL-DVFS. */
clkrst_reboot(CARDEVICE_CL_DVFS); clkrst_reboot(CARDEVICE_CL_DVFS);
@ -292,6 +294,9 @@ void nx_hwinit()
/* Initialize SDRAM. */ /* Initialize SDRAM. */
sdram_init(); sdram_init();
/* Zero-fill the .dram section */
memset(__dram_start__, 0, __dram_end__ - __dram_start__);
/* Save SDRAM LP0 parameters. */ /* Save SDRAM LP0 parameters. */
sdram_lp0_save_params(sdram_get_params()); sdram_lp0_save_params(sdram_get_params());
} }

View File

@ -17,6 +17,8 @@
#include "log.h" #include "log.h"
#include "../display/video_fb.h" #include "../display/video_fb.h"
#include "../di.h"
#include "../uart.h"
#include "vsprintf.h" #include "vsprintf.h"
/* default log level for screen output */ /* default log level for screen output */
@ -30,8 +32,42 @@ ScreenLogLevel log_get_log_level() {
return g_screen_log_level; return g_screen_log_level;
} }
static uint32_t g_framebuffer[1280*768] __attribute__((section(".framebuffer"))) = {0};
static int g_log_display_reference_count = 0;
void log_setup_display() {
if (g_log_display_reference_count++ == 0) {
/* Zero-fill the framebuffer and register it as printk provider. */
video_init(g_framebuffer);
/* Initialize the display. */
display_init();
/* Set the framebuffer. */
display_init_framebuffer(g_framebuffer);
/* Turn on the backlight after initializing the lfb */
/* to avoid flickering. */
display_backlight(true);
}
}
void log_cleanup_display() {
if (--g_log_display_reference_count == 0) {
/* Turn off the backlight. */
display_backlight(false);
/* Terminate the display. */
display_end();
}
}
void *log_get_display_framebuffer() {
return g_framebuffer;
}
void log_to_uart(const char *message) { void log_to_uart(const char *message) {
/* TODO: add UART logging */ uart_send(UART_B, message, strlen(message));
} }
static void print_to_screen(ScreenLogLevel screen_log_level, char *message) { static void print_to_screen(ScreenLogLevel screen_log_level, char *message) {

View File

@ -36,7 +36,10 @@ extern ScreenLogLevel g_screen_log_level;
void log_set_log_level(ScreenLogLevel screen_log_level); void log_set_log_level(ScreenLogLevel screen_log_level);
ScreenLogLevel log_get_log_level(); ScreenLogLevel log_get_log_level();
void log_to_uart(const char *message); void log_setup_display();
void log_cleanup_display();
void *log_get_display_framebuffer();
void vprint(ScreenLogLevel screen_log_level, const char *fmt, va_list args); void vprint(ScreenLogLevel screen_log_level, const char *fmt, va_list args);
void print(ScreenLogLevel screen_log_level, const char* fmt, ...); void print(ScreenLogLevel screen_log_level, const char* fmt, ...);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,889 @@
#ifndef MINIZ_HEADER_INCLUDED
#define MINIZ_HEADER_INCLUDED
#include <stdlib.h>
// Defines to completely disable specific portions of miniz.c:
// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
#define MINIZ_NO_STDIO
// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
// get/set file times, and the C run-time funcs that get/set times won't be called.
// The current downside is the times written to your archives will be from 1979.
#define MINIZ_NO_TIME
// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
//#define MINIZ_NO_ARCHIVE_APIS
// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
#define MINIZ_NO_ARCHIVE_WRITING_APIS
// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
//#define MINIZ_NO_ZLIB_APIS
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
#define MINIZ_NO_MALLOC
#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux
#define MINIZ_NO_TIME
#endif
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
#define MINIZ_X86_OR_X64_CPU 1
#endif
#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
#if MINIZ_X86_OR_X64_CPU
// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions).
#define MINIZ_HAS_64BIT_REGISTERS 1
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API Definitions.
// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
typedef unsigned long mz_ulong;
// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap.
void mz_free(void *p);
#define MZ_ADLER32_INIT (1)
// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
// Compression strategies.
enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
// Method
#define MZ_DEFLATED 8
#ifndef MINIZ_NO_ZLIB_APIS
// Heap allocation callbacks.
// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
typedef void (*mz_free_func)(void *opaque, void *address);
typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
#define MZ_VERSION "9.1.15"
#define MZ_VERNUM 0x91F0
#define MZ_VER_MAJOR 9
#define MZ_VER_MINOR 1
#define MZ_VER_REVISION 15
#define MZ_VER_SUBREVISION 0
// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs).
enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
// Return status codes. MZ_PARAM_ERROR is non-standard.
enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 };
// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 };
// Window bits
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
// Compression/decompression stream struct.
typedef struct mz_stream_s
{
const unsigned char *next_in; // pointer to next byte to read
unsigned int avail_in; // number of bytes available at next_in
mz_ulong total_in; // total number of bytes consumed so far
unsigned char *next_out; // pointer to next byte to write
unsigned int avail_out; // number of bytes that can be written to next_out
mz_ulong total_out; // total number of bytes produced so far
char *msg; // error msg (unused)
struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc)
mz_free_func zfree; // optional heap free function (defaults to free)
void *opaque; // heap alloc function user pointer
int data_type; // data_type (unused)
mz_ulong adler; // adler32 of the source or uncompressed data
mz_ulong reserved; // not used
} mz_stream;
typedef mz_stream *mz_streamp;
// Returns the version string of miniz.c.
const char *mz_version(void);
// mz_deflateInit() initializes a compressor with default options:
// Parameters:
// pStream must point to an initialized mz_stream struct.
// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if the input parameters are bogus.
// MZ_MEM_ERROR on out of memory.
int mz_deflateInit(mz_streamp pStream, int level);
// mz_deflateInit2() is like mz_deflate(), except with more control:
// Additional parameters:
// method must be MZ_DEFLATED
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer)
// mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
int mz_deflateReset(mz_streamp pStream);
// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
// Return values:
// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full).
// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.)
int mz_deflate(mz_streamp pStream, int flush);
// mz_deflateEnd() deinitializes a compressor:
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
int mz_deflateEnd(mz_streamp pStream);
// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH.
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
// Single-call compression functions mz_compress() and mz_compress2():
// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
mz_ulong mz_compressBound(mz_ulong source_len);
// Initializes a decompressor.
int mz_inflateInit(mz_streamp pStream);
// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer:
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
int mz_inflateInit2(mz_streamp pStream, int window_bits);
// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster).
// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data.
// Return values:
// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full.
// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_DATA_ERROR if the deflate stream is invalid.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again
// with more input data, or with more room in the output buffer (except when using single call decompression, described above).
int mz_inflate(mz_streamp pStream, int flush);
// Deinitializes a decompressor.
int mz_inflateEnd(mz_streamp pStream);
// Single-call decompression.
// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
// Returns a string description of the specified error code, or NULL if the error code is invalid.
const char *mz_error(int err);
// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports.
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void *voidpf;
typedef uLong uLongf;
typedef void *voidp;
typedef void *const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Types and macros
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef long long mz_int64;
typedef unsigned long long mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
// ------------------- ZIP archive reading/writing
#ifndef MINIZ_NO_ARCHIVE_APIS
enum
{
MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
};
typedef struct
{
mz_uint32 m_file_index;
mz_uint32 m_central_dir_ofs;
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
time_t m_time;
#endif
mz_uint32 m_crc32;
mz_uint64 m_comp_size;
mz_uint64 m_uncomp_size;
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
mz_uint64 m_local_header_ofs;
mz_uint32 m_comment_size;
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
#ifdef MINIZ_NO_STDIO
#define MZ_FILE void *
#else
#include <stdio.h>
#include <sys/stat.h>
#if defined(_MSC_VER) || defined(__MINGW64__)
static FILE *mz_fopen(const char *pFilename, const char *pMode)
{
FILE* pFile = NULL;
fopen_s(&pFile, pFilename, pMode);
return pFile;
}
static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream)
{
FILE* pFile = NULL;
if (freopen_s(&pFile, pPath, pMode, pStream))
return NULL;
return pFile;
}
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN mz_fopen
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 _ftelli64
#define MZ_FSEEK64 _fseeki64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN mz_freopen
#define MZ_DELETE_FILE remove
#elif defined(__MINGW32__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__TINYC__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftell
#define MZ_FSEEK64 fseek
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__GNUC__) && _LARGEFILE64_SOURCE
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen64(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT stat64
#define MZ_FILE_STAT stat64
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
#define MZ_DELETE_FILE remove
#else
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello
#define MZ_FSEEK64 fseeko
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#endif // #ifdef _MSC_VER
#endif // #ifdef MINIZ_NO_STDIO
typedef struct
{
void *m_p;
size_t m_size, m_capacity;
mz_uint m_element_size;
} mz_zip_array;
typedef struct mz_zip_internal_state_tag
{
mz_zip_array m_central_dir;
mz_zip_array m_central_dir_offsets;
mz_zip_array m_sorted_central_dir_offsets;
MZ_FILE *m_pFile;
void *m_pMem;
size_t m_mem_size;
size_t m_mem_capacity;
} mz_zip_internal_state;
#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size
#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index]
typedef enum
{
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef struct mz_zip_archive_tag
{
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
mz_uint m_total_files;
mz_zip_mode m_zip_mode;
mz_uint m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void *m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
void *m_pIO_opaque;
mz_zip_internal_state m_State;
mz_zip_internal_state *m_pState;
} mz_zip_archive;
typedef enum
{
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
} mz_zip_flags;
// ZIP archive reading
// Inits a ZIP archive reader.
// These functions read and validate the archive's central directory.
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
#endif
// Returns the total number of files in the archive.
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
// Returns detailed information about an archive file entry.
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);
// Determines if an archive file entry is a directory entry.
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
// Retrieves the filename of an archive file entry.
// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename.
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);
// Attempts to locates a file in the archive's central directory.
// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
// Returns -1 if the file cannot be found.
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
// Extracts a archive file to a memory buffer using no memory allocation.
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
// Extracts a archive file to a memory buffer.
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags);
// Extracts a archive file to a dynamically allocated heap buffer.
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);
// Extracts a archive file using a callback function to output the file's data.
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
#ifndef MINIZ_NO_STDIO
// Extracts a archive file to a disk file and sets its last accessed and modified times.
// This function only extracts files, not archive directory records.
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);
#endif
// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
// ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
// Inits a ZIP archive writer.
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);
#endif
// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.
// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it).
// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
// the archive is finalized the file's central directory will be hosed.
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags);
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
#ifndef MINIZ_NO_STDIO
// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
#endif
// Adds a file to an archive by fully cloning the data from another archive.
// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index);
// Finalizes the archive by writing the central directory records followed by the end of central directory record.
// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
// An archive must be manually finalized by calling this function for it to be valid.
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize);
// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
// Note for the archive to be valid, it must have been finalized before ending.
mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
// Misc. high-level helper functions:
// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
// Reads a single file from an archive into a heap block.
// Returns NULL on failure.
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags);
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
// ------------------- Low-level Decompression API Definitions
// Decompression flags used by tinfl_decompress().
// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.
// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.
// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).
// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
enum
{
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
// High level decompression functions:
// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
// On return:
// Function returns a pointer to the decompressed data, or NULL on failure.
// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
// The caller must call mz_free() on the returned block when it's no longer needed.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer.
// Returns 1 on success or 0 on failure.
typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
// Max size of LZ dictionary.
#define TINFL_LZ_DICT_SIZE 32768
// Return status.
typedef enum
{
TINFL_STATUS_BAD_PARAM = -3,
TINFL_STATUS_ADLER32_MISMATCH = -2,
TINFL_STATUS_FAILED = -1,
TINFL_STATUS_DONE = 0,
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
// Initializes the decompressor to its initial state.
#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability.
// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output.
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
// Internal/private bits follow.
enum
{
TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct
{
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag
{
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
// ------------------- Low-level Compression API Definitions
// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
#define TDEFL_LESS_MEMORY 0
// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression).
enum
{
TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
};
// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data.
// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory).
// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
enum
{
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
// High level compression functions:
// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of source block to compress.
// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
// The caller must free() the returned block when it's no longer needed.
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
// Returns 0 on failure.
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
// Compresses an image to a compressed PNG file in memory.
// On entry:
// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pLen_out will be set to the size of the PNG image file.
// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip);
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };
// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
#if TDEFL_LESS_MEMORY
enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
#else
enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
#endif
// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions.
typedef enum
{
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1,
} tdefl_status;
// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
typedef enum
{
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
// tdefl's compression state structure.
typedef struct
{
tdefl_put_buf_func_ptr m_pPut_buf_func;
void *m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
tdefl_status m_prev_return_status;
const void *m_pIn_buf;
void *m_pOut_buf;
size_t *m_pIn_buf_size, *m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8 *m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
// Initializes the compressor.
// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression.
// If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible.
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
// tdefl_compress_buffer() always consumes the entire input buffer.
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros.
#ifndef MINIZ_NO_ZLIB_APIS
// Create tdefl_compress() flags given zlib-style compression parameters.
// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
// window_bits may be -15 (raw deflate) or 15 (zlib)
// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
#endif // #ifndef MINIZ_NO_ZLIB_APIS
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_INCLUDED

View File

@ -18,7 +18,6 @@
#include "exception_handlers.h" #include "exception_handlers.h"
#include "panic.h" #include "panic.h"
#include "hwinit.h" #include "hwinit.h"
#include "di.h"
#include "timers.h" #include "timers.h"
#include "fs_utils.h" #include "fs_utils.h"
#include "stage2.h" #include "stage2.h"
@ -27,15 +26,13 @@
#include "lib/fatfs/ff.h" #include "lib/fatfs/ff.h"
#include "lib/log.h" #include "lib/log.h"
#include "lib/vsprintf.h" #include "lib/vsprintf.h"
#include "lib/ini.h"
#include "display/video_fb.h" #include "display/video_fb.h"
#include "fastboot/fastboot.h"
#include "btn.h"
extern void (*__program_exit_callback)(int rc); extern void (*__program_exit_callback)(int rc);
static void *g_framebuffer; static char g_bct0_buffer[BCTO_MAX_SIZE] __attribute__((section(".dram"))) = {0};
static char g_bct0_buffer[BCTO_MAX_SIZE];
#define CONFIG_LOG_LEVEL_KEY "log_level"
#define DEFAULT_BCT0 \ #define DEFAULT_BCT0 \
"BCT0\n"\ "BCT0\n"\
@ -48,7 +45,10 @@ static char g_bct0_buffer[BCTO_MAX_SIZE];
"debugmode = 1\n"\ "debugmode = 1\n"\
"debugmode_user = 0\n"\ "debugmode_user = 0\n"\
"disable_user_exception_handlers = 0\n"\ "disable_user_exception_handlers = 0\n"\
"[stratosphere]\n" "[stratosphere]\n" \
"[fastboot]\n" \
"force_enable = 0\n" \
"button_timeout_ms = 0\n"
static const char *load_config(void) { static const char *load_config(void) {
if (!read_from_file(g_bct0_buffer, BCTO_MAX_SIZE, "atmosphere/config/BCT.ini")) { if (!read_from_file(g_bct0_buffer, BCTO_MAX_SIZE, "atmosphere/config/BCT.ini")) {
@ -74,61 +74,12 @@ static const char *load_config(void) {
return bct0; return bct0;
} }
static int config_ini_handler(void *user, const char *section, const char *name, const char *value) {
if (strcmp(section, "config") == 0) {
if (strcmp(name, CONFIG_LOG_LEVEL_KEY) == 0) {
ScreenLogLevel *config_log_level = (ScreenLogLevel *)user;
int log_level = 0;
sscanf(value, "%d", &log_level);
*config_log_level = (ScreenLogLevel)log_level;
} else {
return 0;
}
} else {
return 0;
}
return 1;
}
static void setup_display(void) {
g_framebuffer = (void *)0xC0000000;
/* Zero-fill the framebuffer and register it as printk provider. */
video_init(g_framebuffer);
/* Initialize the display. */
display_init();
/* Set the framebuffer. */
display_init_framebuffer(g_framebuffer);
/* Turn on the backlight after initializing the lfb */
/* to avoid flickering. */
display_backlight(true);
}
static void cleanup_display(void) {
/* Turn off the backlight. */
display_backlight(false);
/* Terminate the display. */
display_end();
}
static void setup_env(void) { static void setup_env(void) {
/* Initialize hardware. */ /* Initialize hardware. */
nx_hwinit(); nx_hwinit();
/* Set up the exception handlers. */ /* Set up the exception handlers. */
setup_exception_handlers(); setup_exception_handlers();
/* Mount the SD card. */
mount_sd();
}
static void cleanup_env(void) {
/* Unmount the SD card. */
unmount_sd();
} }
static void exit_callback(int rc) { static void exit_callback(int rc) {
@ -137,11 +88,10 @@ static void exit_callback(int rc) {
} }
int main(void) { int main(void) {
const char *bct0; const char *bct0_string = DEFAULT_BCT0;
const char *stage2_path;
stage2_args_t *stage2_args; stage2_args_t *stage2_args;
uint32_t stage2_version = 0; uint32_t stage2_version = 0;
ScreenLogLevel log_level = SCREEN_LOG_LEVEL_NONE; bct0_t bct0;
/* Initialize the boot environment. */ /* Initialize the boot environment. */
setup_env(); setup_env();
@ -149,49 +99,150 @@ int main(void) {
/* Check for panics. */ /* Check for panics. */
check_and_display_panic(); check_and_display_panic();
/* Load the BCT0 configuration ini off of the SD. */ bool should_greet = true;
bct0 = load_config(); bool skip_fastboot = false;
bool stage2_loaded = false;
bool has_sd_card = false;
/* Extract the logging level from the BCT.ini file. */ while (!stage2_loaded) {
if (ini_parse_string(bct0, config_ini_handler, &log_level) < 0) {
fatal_error("Failed to parse BCT.ini!\n"); /* Try to mount the SD card and load configuration. */
if (has_sd_card || mount_sd()) {
/* Load the BCT0 configuration ini off of the SD. */
bct0_string = load_config();
/* Parse the BCT0 configuration ini. */
if (bct0_parse(bct0_string, &bct0) < 0) {
fatal_error("Failed to parse BCT.ini!\n");
}
/* Override the global logging level. */
log_set_log_level(bct0.log_level);
if (should_greet && bct0.log_level != SCREEN_LOG_LEVEL_NONE) {
/* Initialize the display for debugging. */
log_setup_display();
/* Say hello. */
print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, "Welcome to Atmosph\xe8re Fus\xe9" "e!\n");
print(SCREEN_LOG_LEVEL_DEBUG, "Using color linear framebuffer at 0x%p!\n", log_get_display_framebuffer());
should_greet = false;
}
/* Run the MTC binary, if it hasn't already been run. */
if (!stage2_run_mtc(&bct0)) {
print(SCREEN_LOG_LEVEL_WARNING, "DRAM training failed! Continuing with untrained DRAM.\n");
}
/* Assert that our configuration is sane. */
stage2_validate_config(&bct0);
has_sd_card = true;
} else {
/* Initialize the display to show messages. */
log_setup_display();
/* Override logging level. */
log_set_log_level(SCREEN_LOG_LEVEL_INFO);
/* Prompt user for action. */
print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, "Failed to mount SD card!\n");
print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, " Press Volume Up to retry.\n");
print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, " Press Volume Down to enter fastboot mode.\n");
print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, "\n Press POWER to reboot.\n");
/* Wait for user action. */
uint32_t last_button = btn_read();
while (true) {
uint32_t button = btn_read();
if (button & BTN_VOL_UP && !(last_button & BTN_VOL_UP)) {
/* Skip the rest of the loop and return to beginning. If we
* succeed, don't offer to enter fastboot. */
skip_fastboot = true;
break;
}
if (button & BTN_VOL_DOWN && !(last_button & BTN_VOL_DOWN)) {
/* Do not skip entering fastboot mode, even if we were previously requested to. */
skip_fastboot = false;
break;
}
if (button & BTN_POWER) {
/* Reboot. */
reboot_to_self();
}
last_button = button;
}
log_cleanup_display();
}
if (!skip_fastboot) {
/* Try to enter fastboot if we are configured to, or force it if SD mount failed and we reached this point. */
switch(fastboot_enter(&bct0, !has_sd_card)) {
case FASTBOOT_INVALID:
case FASTBOOT_SKIPPED:
break;
case FASTBOOT_LOAD_STAGE2:
/* Return to start of loop to reload configuration and try again. Do
not attempt to enter fastboot again if config loads correctly,
but do offer to enter fastboot again if SD mount still fails. */
skip_fastboot = true;
continue;
case FASTBOOT_CHAINLOAD:
print(SCREEN_LOG_LEVEL_DEBUG, "fastboot: chainloading\n");
/* Break out of outer loop. Note that it is possible to reach
* this codepath with no SD card, in which case we forward the
* default BCT0 string to stage2.. */
stage2_loaded = true;
continue;
}
}
/* Load stage2 if the SD card mounted successfully and fastboot didn't continue out of the loop. */
if (has_sd_card) {
print(SCREEN_LOG_LEVEL_DEBUG, "Loading stage2 from sd card...\n");
stage2_load(&bct0);
print(SCREEN_LOG_LEVEL_DEBUG, "Finished loading stage2.\n");
stage2_loaded = true;
}
} }
/* Override the global logging level. */ print(SCREEN_LOG_LEVEL_DEBUG, "Continuing to stage2...\n");
log_set_log_level(log_level);
if (log_level != SCREEN_LOG_LEVEL_NONE) {
/* Initialize the display for debugging. */
setup_display();
}
/* Say hello. */
print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, "Welcome to Atmosph\xe8re Fus\xe9" "e!\n");
print(SCREEN_LOG_LEVEL_DEBUG, "Using color linear framebuffer at 0x%p!\n", g_framebuffer);
/* Load the loader payload into DRAM. */
load_stage2(bct0);
/* Setup argument data. */ /* Setup argument data. */
stage2_path = stage2_get_program_path(); strcpy(g_chainloader_arg_data, bct0.stage2_path);
strcpy(g_chainloader_arg_data, stage2_path); stage2_args = (stage2_args_t *)(g_chainloader_arg_data + strlen(bct0.stage2_path) + 1); /* May be unaligned. */
stage2_args = (stage2_args_t *)(g_chainloader_arg_data + strlen(stage2_path) + 1); /* May be unaligned. */
memcpy(&stage2_args->version, &stage2_version, 4); memcpy(&stage2_args->version, &stage2_version, 4);
memcpy(&stage2_args->log_level, &log_level, sizeof(log_level)); memcpy(&stage2_args->log_level, &bct0.log_level, sizeof(bct0.log_level));
strcpy(stage2_args->bct0, bct0); strcpy(stage2_args->bct0, bct0_string);
g_chainloader_argc = 2; g_chainloader_argc = 2;
/* Terminate the boot environment. */ /* Cleanup environment. */
cleanup_env(); if (has_sd_card) {
unmount_sd();
}
if (log_level != SCREEN_LOG_LEVEL_NONE) { if (bct0.log_level != SCREEN_LOG_LEVEL_NONE) {
/* Wait a while for debugging. */ /* Wait a while for debugging. */
mdelay(1000); mdelay(1000);
/* Terminate the display for debugging. */ /* Terminate the display for debugging. */
cleanup_display(); log_cleanup_display();
} }
print(SCREEN_LOG_LEVEL_DEBUG, "Exiting...\n");
/* Finally, after the cleanup routines (__libc_fini_array, etc.) are called, jump to Stage2. */ /* Finally, after the cleanup routines (__libc_fini_array, etc.) are called, jump to Stage2. */
__program_exit_callback = exit_callback; __program_exit_callback = exit_callback;
return 0; return 0;

View File

@ -124,16 +124,21 @@ void mc_config_carveout_finalize()
MAKE_MC_REG(MC_SECURITY_CARVEOUT2_CFG0) = 0x440167E; MAKE_MC_REG(MC_SECURITY_CARVEOUT2_CFG0) = 0x440167E;
} }
void mc_enable_ahb_redirect() static int mc_ahb_redirect_users = 0;
{
volatile tegra_car_t *car = car_get_regs();
car->lvl2_clk_gate_ovrd = ((car->lvl2_clk_gate_ovrd & 0xFFF7FFFF) | 0x80000);
MAKE_MC_REG(MC_IRAM_BOM) = 0x40000000; void mc_acquire_ahb_redirect()
MAKE_MC_REG(MC_IRAM_TOM) = 0x4003F000; {
if ((mc_ahb_redirect_users++) == 0)
{
volatile tegra_car_t *car = car_get_regs();
car->lvl2_clk_gate_ovrd = ((car->lvl2_clk_gate_ovrd & 0xFFF7FFFF) | 0x80000);
MAKE_MC_REG(MC_IRAM_BOM) = 0x40000000;
MAKE_MC_REG(MC_IRAM_TOM) = 0x4003F000;
}
} }
void mc_disable_ahb_redirect() static void mc_disable_ahb_redirect()
{ {
volatile tegra_car_t *car = car_get_regs(); volatile tegra_car_t *car = car_get_regs();
@ -141,6 +146,16 @@ void mc_disable_ahb_redirect()
MAKE_MC_REG(MC_IRAM_TOM) = 0; MAKE_MC_REG(MC_IRAM_TOM) = 0;
car->lvl2_clk_gate_ovrd &= 0xFFF7FFFF; car->lvl2_clk_gate_ovrd &= 0xFFF7FFFF;
mc_ahb_redirect_users = 0;
}
void mc_release_ahb_redirect()
{
if ((--mc_ahb_redirect_users) == 0)
{
mc_disable_ahb_redirect();
}
} }
void mc_enable() void mc_enable()

View File

@ -598,8 +598,8 @@ typedef enum {
void mc_config_tsec_carveout(uint32_t bom, uint32_t size1mb, bool lock); void mc_config_tsec_carveout(uint32_t bom, uint32_t size1mb, bool lock);
void mc_config_carveout(); void mc_config_carveout();
void mc_config_carveout_finalize(); void mc_config_carveout_finalize();
void mc_enable_ahb_redirect(); void mc_acquire_ahb_redirect();
void mc_disable_ahb_redirect(); void mc_release_ahb_redirect();
void mc_enable(); void mc_enable();
#endif #endif

View File

@ -148,7 +148,7 @@ static void _check_and_display_atmosphere_fatal_error(void) {
print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, "Error Desc: %s (0x%x)\n", get_error_desc_str(ctx.error_desc), ctx.error_desc); print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, "Error Desc: %s (0x%x)\n", get_error_desc_str(ctx.error_desc), ctx.error_desc);
/* Save context to the SD card. */ /* Save context to the SD card. */
{ if (mount_sd()) {
char filepath[0x40]; char filepath[0x40];
snprintf(filepath, sizeof(filepath) - 1, "/atmosphere/fatal_errors/report_%016llx.bin", ctx.report_identifier); snprintf(filepath, sizeof(filepath) - 1, "/atmosphere/fatal_errors/report_%016llx.bin", ctx.report_identifier);
filepath[sizeof(filepath)-1] = 0; filepath[sizeof(filepath)-1] = 0;
@ -157,6 +157,10 @@ static void _check_and_display_atmosphere_fatal_error(void) {
} else { } else {
print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, "Report saved to %s\n", filepath); print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, "Report saved to %s\n", filepath);
} }
unmount_sd();
} else {
print(SCREEN_LOG_LEVEL_ERROR | SCREEN_LOG_LEVEL_NO_PREFIX, "Failed to mount SD card to save report!\n");
} }
/* Try to print a fix suggestion via automatic error detection. */ /* Try to print a fix suggestion via automatic error detection. */

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "reg_util.h"
namespace t210 {
const struct APBDEV_PMC {
static const uintptr_t base_addr = 0x7000e400;
using Peripheral = APBDEV_PMC;
BEGIN_DEFINE_REGISTER(USB_AO_0, uint32_t, 0xf0)
DEFINE_RW_FIELD(ID_PD_P0, 3)
DEFINE_RW_FIELD(VBUS_WAKEUP_PD_P0, 2)
END_DEFINE_REGISTER(USB_AO_0)
} APBDEV_PMC;
} // namespace t210

View File

@ -0,0 +1,221 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "reg_util.h"
namespace t210 {
const struct CLK_RST_CONTROLLER {
static const uintptr_t base_addr = 0x60006000;
using Peripheral = CLK_RST_CONTROLLER;
enum class OscFreq {
OSC13 = 0,
OSC16P8 = 1,
OSC19P2 = 4,
OSC38P4 = 5,
OSC12 = 8,
OSC48 = 9,
OSC26 = 12,
};
BEGIN_DEFINE_REGISTER(RST_DEVICES_U_0, uint32_t, 0xc)
DEFINE_RW_FIELD(SWR_XUSB_DEV_RST, 31)
DEFINE_RW_FIELD(SWR_XUSB_HOST_RST, 25)
END_DEFINE_REGISTER(RST_DEVICES_U_0)
BEGIN_DEFINE_REGISTER(CLK_OUT_ENB_U_0, uint32_t, 0x18)
DEFINE_RW_FIELD(CLK_ENB_XUSB_DEV, 31)
DEFINE_RW_FIELD(CLK_ENB_XUSB_HOST, 25)
END_DEFINE_REGISTER(CLK_OUT_ENB_U_0)
BEGIN_DEFINE_REGISTER(OSC_CTRL_0, uint32_t, 0x50)
DEFINE_RW_FIELD(OSC_FREQ, 28, 31, OscFreq)
END_DEFINE_REGISTER(OSC_CTRL_0)
BEGIN_DEFINE_REGISTER(PLLU_BASE_0, uint32_t, 0xc0)
DEFINE_RW_FIELD(PLLU_BYPASS, 31)
DEFINE_RW_FIELD(PLLU_ENABLE, 30)
DEFINE_RW_FIELD(PLLU_REF_DIS, 29)
DEFINE_RO_FIELD(PLLU_LOCK, 27)
DEFINE_RW_FIELD(PLLU_CLKENABLE_48M, 25)
DEFINE_RW_FIELD(PLLU_OVERRIDE, 24)
DEFINE_RW_FIELD(PLLU_CLKENABLE_ICUSB, 23)
DEFINE_RW_FIELD(PLLU_CLKENABLE_HSIC, 22)
DEFINE_RW_FIELD(PLLU_CLKENABLE_USB, 21)
DEFINE_RW_FIELD(PLLU_DIVP, 16, 20)
DEFINE_RW_FIELD(PLLU_DIVN, 8, 15)
DEFINE_RW_FIELD(PLLU_DIVM, 0, 7)
END_DEFINE_REGISTER(PLLU_BASE_0)
BEGIN_DEFINE_REGISTER(PLLU_OUTA_0, uint32_t, 0xc4)
DEFINE_RW_FIELD(PLLU_OUT2_RATIO, 24, 21)
DEFINE_RW_FIELD(PLLU_OUT2_OVRRIDE, 18)
DEFINE_RW_FIELD(PLLU_OUT2_CLKEN, 17)
DEFINE_RW_FIELD(PLLU_OUT2_RSTEN, 16)
DEFINE_RW_FIELD(PLLU_OUT1_RATIO, 8, 15)
DEFINE_RW_FIELD(PLLU_OUT1_OVRRIDE, 2)
DEFINE_RW_FIELD(PLLU_OUT1_CLKEN, 1)
DEFINE_RW_FIELD(PLLU_OUT1_RSTN, 0)
END_DEFINE_REGISTER(PLLU_OUTA_0)
BEGIN_DEFINE_REGISTER(PLLU_MISC_0, uint32_t, 0xcc)
DEFINE_RW_FIELD(PLLU_IDDQ, 31)
DEFINE_RO_FIELD(PLLU_FREQLOCK, 30)
DEFINE_RW_FIELD(PLLU_EN_LCKDET, 29)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(PLLU_PTS, 27, 28)
DEFINE_RW_SYMBOLIC_VALUE(DISABLE, 0)
DEFINE_RW_SYMBOLIC_VALUE(VCO, 1)
DEFINE_RW_SYMBOLIC_VALUE(FO, 2)
DEFINE_RW_SYMBOLIC_VALUE(FO_ICUSB, 3)
END_DEFINE_SYMBOLIC_FIELD(PLLU_PTS)
DEFINE_RW_FIELD(PLLU_KCP, 25, 26)
DEFINE_RW_FIELD(PLLU_KVCO, 24)
DEFINE_RW_FIELD(PLLU_SETUP, 0, 23)
END_DEFINE_REGISTER(PLLU_MISC_0)
BEGIN_DEFINE_REGISTER(CLK_OUT_ENB_Y_0, uint32_t, 0x298)
DEFINE_RW_FIELD(CLK_ENB_USB2_TRK, 18)
END_DEFINE_REGISTER(CLK_OUT_ENB_Y_0)
BEGIN_DEFINE_REGISTER(RST_DEVICES_W_0, uint32_t, 0x35c)
DEFINE_RW_FIELD(SWR_XUSB_SS_RST, 28)
DEFINE_RW_FIELD(SWR_DVFS_RST, 27)
DEFINE_RW_FIELD(SWR_ENTROPY_RST, 21)
DEFINE_RW_FIELD(SWR_XUSB_PADCTL_RST, 14)
DEFINE_RW_FIELD(SWR_RESERVED10_RST, 13)
DEFINE_RW_FIELD(SWR_RESERVED9_RST, 12)
// SWR_RESERVED8_RST conspicuously missing from TRM
DEFINE_RW_FIELD(SWR_RESERVED7_RST, 10)
DEFINE_RW_FIELD(SWR_RESERVED6_RST, 9)
DEFINE_RW_FIELD(SWR_CEC_RST, 8)
DEFINE_RW_FIELD(SWR_RESERVED5_RST, 7)
DEFINE_RW_FIELD(SWR_RESERVED4_RST, 6)
DEFINE_RW_FIELD(SWR_RESERVED3_RST, 5)
DEFINE_RW_FIELD(SWR_RESERVED2_RST, 4)
DEFINE_RW_FIELD(SWR_RESERVED1_RST, 3)
DEFINE_RW_FIELD(SWR_RESERVED0_RST, 2)
DEFINE_RW_FIELD(SWR_SATACOLD_RST, 1)
END_DEFINE_REGISTER(RST_DEVICES_W_0)
BEGIN_DEFINE_REGISTER(CLK_OUT_ENB_W_0, uint32_t, 0x364)
DEFINE_RW_FIELD(CLK_ENB_XUSB_SS, 28)
DEFINE_RW_FIELD(CLK_ENB_XUSB, 15)
END_DEFINE_REGISTER(CLK_OUT_ENB_W_0)
BEGIN_DEFINE_REGISTER(UTMIP_PLL_CFG0_0, uint32_t, 0x480)
DEFINE_RW_FIELD(UTMIP_PLL_VREG_CTRL, 27, 28)
DEFINE_RW_FIELD(UTMIP_PLL_KCP, 25, 26)
DEFINE_RW_FIELD(UTMIP_PLL_NDIV, 16, 23)
DEFINE_RW_FIELD(UTMIP_PLL_MDIV, 8, 15)
DEFINE_RW_FIELD(UTMIP_PLL_LOCK_OVR, 2)
DEFINE_RW_FIELD(UTMIP_PLL_RESERVED2, 1)
DEFINE_RW_FIELD(UTMIP_PLL_EN_LCKDET, 0)
END_DEFINE_REGISTER(UTMIP_PLL_CFG0_0)
BEGIN_DEFINE_REGISTER(UTMIP_PLL_CFG1_0, uint32_t, 0x484)
DEFINE_RW_FIELD(UTMIP_PLLU_ENABLE_DLY_COUNT, 27, 31)
DEFINE_RW_FIELD(UTMIP_PLL_RSVD, 18, 26)
DEFINE_RW_FIELD(UTMIP_FORCE_PLLU_POWERUP, 17)
DEFINE_RW_FIELD(UTMIP_FORCE_PLLU_POWERDOWN, 16)
DEFINE_RW_FIELD(UTMIP_FORCE_PLL_ENABLE_POWERUP, 15)
DEFINE_RW_FIELD(UTMIP_FORCE_PLL_ENABLE_POWERDOWN, 14)
DEFINE_RW_FIELD(UTMIP_FORCE_PLL_ACTIVE_POWERUP, 13)
DEFINE_RW_FIELD(UTMIP_FORCE_PLL_ACTIVE_POWERDOWN, 12)
DEFINE_RW_FIELD(UTMIP_XTAL_FREQ_COUNT, 0, 11)
END_DEFINE_REGISTER(UTMIP_PLL_CFG1_0)
BEGIN_DEFINE_REGISTER(UTMIP_PLL_CFG2_0, uint32_t, 0x488)
DEFINE_RW_FIELD(UTMIP_PHY_XTAL_CLOCKEN, 30)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_RESERVED, 26, 29)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_D_POWERUP, 25)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_D_POWERDOWN, 24)
DEFINE_RW_FIELD(UTMIP_PLL_ACTIVE_DLY_COUNT, 18, 23)
DEFINE_RW_FIELD(UTMIP_PLLU_STABLE_COUNT, 6, 17)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_C_POWERUP, 5)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_C_POWERDOWN, 4)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_B_POWERUP, 3)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_B_POWERDOWN, 2)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_A_POWERUP, 1)
DEFINE_RW_FIELD(UTMIP_FORCE_PD_SAMP_A_POWERDOWN, 0)
END_DEFINE_REGISTER(UTMIP_PLL_CFG2_0)
BEGIN_DEFINE_REGISTER(UTMIP_PLL_CFG3_0, uint32_t, 0x4c0)
DEFINE_RW_FIELD(UTMIP_PLL_REF_SRC_SEL, 26)
DEFINE_RW_FIELD(UTMIP_PLL_REF_DIS, 25)
DEFINE_RW_FIELD(UTMIP_PLL_PTS, 24)
DEFINE_RW_FIELD(UTMIP_PLL_SETUP, 0, 23) // "Debug control bits."
END_DEFINE_REGISTER(UTMIP_PLL_CFG3_0)
BEGIN_DEFINE_REGISTER(UTMIPLL_HW_PWRDN_CFG0_0, uint32_t, 0x52c)
DEFINE_RO_FIELD(UTMIPLL_LOCK, 31)
DEFINE_RO_FIELD(UTMIPLL_SEQ_STATE, 26, 27)
DEFINE_RW_FIELD(UTMIPLL_SEQ_START_STATE, 25)
DEFINE_RW_FIELD(UTMIPLL_SEQ_ENABLE, 24)
DEFINE_RW_FIELD(UTMIPLL_IDDQ_PD_INCLUDE, 7)
DEFINE_RW_FIELD(UTMIPLL_USE_LOCKDET, 6)
DEFINE_RW_FIELD(UTMIPLL_SEQ_RESET_INPUT_VALUE, 5)
DEFINE_RW_FIELD(UTMIPLL_SEQ_IN_SWCTL, 4)
DEFINE_RW_FIELD(UTMIPLL_CLK_ENABLE_OVERRIDE_VALUE, 3)
DEFINE_RW_FIELD(UTMIPLL_CLK_ENABLE_SWCTL, 2)
DEFINE_RW_FIELD(UTMIPLL_IDDQ_OVERRIDE_VALUE, 1)
DEFINE_RW_FIELD(UTMIPLL_IDDQ_SWCTL, 0)
END_DEFINE_REGISTER(UTMIPLL_HW_PWRDN_CFG0_0)
BEGIN_DEFINE_REGISTER(CLK_SOURCE_XUSB_FS_0, uint32_t, 0x608)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(XUSB_FS_CLK_SRC, 29, 31)
DEFINE_RW_SYMBOLIC_VALUE(CLK_M, 0)
DEFINE_RW_SYMBOLIC_VALUE(FO_48M, 2)
DEFINE_RW_SYMBOLIC_VALUE(PLLP_OUT0, 4)
DEFINE_RW_SYMBOLIC_VALUE(HSIC_480, 6)
END_DEFINE_SYMBOLIC_FIELD(XUSB_FS_CLK_SRC)
DEFINE_RW_FIELD(XUSB_FS_CLK_DIVISOR, 0, 7)
END_DEFINE_REGISTER(CLK_SOURCE_XUSB_FS_0)
BEGIN_DEFINE_REGISTER(CLK_SOURCE_XUSB_CORE_DEV_0, uint32_t, 0x60c)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(XUSB_CORE_DEV_CLK_SRC, 29, 31)
DEFINE_RW_SYMBOLIC_VALUE(CLK_M, 0)
DEFINE_RW_SYMBOLIC_VALUE(PLLP_OUT0, 1)
DEFINE_RW_SYMBOLIC_VALUE(PLLREFE_CLKOUT, 5)
END_DEFINE_SYMBOLIC_FIELD(XUSB_CORE_DEV_CLK_SRC)
DEFINE_RW_FIELD(XUSB_CORE_DEV_CLK_DIVISOR, 0, 7)
END_DEFINE_REGISTER(CLK_SOURCE_XUSB_CORE_DEV_0)
BEGIN_DEFINE_REGISTER(CLK_SOURCE_XUSB_SS_0, uint32_t, 0x610)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(XUSB_SS_CLK_SRC, 29, 31)
DEFINE_RW_SYMBOLIC_VALUE(CLK_M, 0)
DEFINE_RW_SYMBOLIC_VALUE(PLLREFE_CLKOUT, 1)
DEFINE_RW_SYMBOLIC_VALUE(CLK_S, 2)
DEFINE_RW_SYMBOLIC_VALUE(HSIC_480, 3)
END_DEFINE_SYMBOLIC_FIELD(XUSB_SS_CLK_SRC)
DEFINE_RW_FIELD(XUSB_HS_HSICP_CLK_SEL, 26)
DEFINE_RW_FIELD(XUSB_HS_CLK_BYPASS_SWITCH, 25)
DEFINE_RW_FIELD(XUSB_SS_CLK_BYPASS_SWITCH, 24)
DEFINE_RW_FIELD(XUSB_SS_CLK_DIVISOR, 0, 7)
END_DEFINE_REGISTER(CLK_SOURCE_XUSB_SS_0)
BEGIN_DEFINE_REGISTER(CLK_SOURCE_USB2_HSIC_TRK_0, uint32_t, 0x6cc)
DEFINE_RW_FIELD(USB2_HSIC_TRK_CLK_DIVISOR, 0, 7)
END_DEFINE_REGISTER(CLK_SOURCE_USB2_HSIC_TRK_0)
} CLK_RST_CONTROLLER;
} // namespace t210

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "reg_util.h"
namespace t210 {
const struct FUSE {
static const uintptr_t base_addr = 0x7000f800;
using Peripheral = FUSE;
BEGIN_DEFINE_REGISTER(SKU_USB_CALIB, uint32_t, 0x1f0)
DEFINE_RO_FIELD(TERM_RANGE_ADJ, 7, 10) // TODO: check?
DEFINE_RO_FIELD(HS_CURR_LEVEL, 0, 5) // TODO: check?
END_DEFINE_REGISTER(SKU_USB_CALIB)
BEGIN_DEFINE_REGISTER(USB_CALIB_EXT, uint32_t, 0x350)
DEFINE_RO_FIELD(RPD_CTRL, 0, 5)
END_DEFINE_REGISTER(USB_CALIB_EXT)
} FUSE;
} // namespace t210

View File

@ -0,0 +1,495 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include<stdint.h>
template<typename Peripheral, typename _Base, uintptr_t _offset>
class RegisterAccessor {
public:
using Base = _Base;
static const uintptr_t offset = _offset;
__attribute__((always_inline)) RegisterAccessor(const Peripheral &p) :
peripheral(p),
ptr(reinterpret_cast<volatile Base *>(p.base_addr + _offset)),
read_value(*ptr),
write_value(read_value) {
}
__attribute__((always_inline)) RegisterAccessor(const Peripheral &p, Base value) :
peripheral(p),
ptr(reinterpret_cast<volatile Base *>(p.base_addr + _offset)),
read_value(value),
write_value(value) {
}
__attribute__((always_inline)) const Peripheral &Commit() {
*ptr = write_value;
return peripheral;
}
const Peripheral &peripheral;
volatile Base *ptr;
Base read_value;
Base write_value;
};
struct rw1c_marker {};
template<typename Peripheral, typename _Base>
class BitArrayRegisterAccessor {
public:
using Base = _Base;
__attribute__((always_inline)) BitArrayRegisterAccessor(const Peripheral &p, uintptr_t offset) :
peripheral(p),
ptr(reinterpret_cast<volatile Base *>(p.base_addr + offset)),
read_value(*ptr),
write_value(read_value) {
}
__attribute__((always_inline)) BitArrayRegisterAccessor(const Peripheral &p, uintptr_t offset, Base value) :
peripheral(p),
ptr(reinterpret_cast<volatile Base *>(p.base_addr + offset)),
read_value(value),
write_value(value) {
}
__attribute__((always_inline)) BitArrayRegisterAccessor(const Peripheral &p, uintptr_t offset, rw1c_marker _marker) :
peripheral(p),
ptr(reinterpret_cast<volatile Base *>(p.base_addr + offset)),
read_value(*ptr),
write_value(0) {
}
class BitAccessor {
public:
__attribute__((always_inline)) BitAccessor(BitArrayRegisterAccessor &reg, int idx) :
reg(reg),
idx(idx) {
}
__attribute__((always_inline)) bool Get() const {
return (reg.read_value >> idx) & 1;
}
__attribute__((always_inline)) BitArrayRegisterAccessor &Set(bool value) {
reg.write_value&= ~(1 << idx);
reg.write_value|= (value << idx);
return reg;
}
__attribute__((always_inline)) explicit operator bool() const {
return Get();
}
__attribute__((always_inline)) BitArrayRegisterAccessor &operator=(bool value) {
return Set(value);
}
__attribute__((always_inline)) BitArrayRegisterAccessor &Clear() {
return Set(1);
}
private:
BitArrayRegisterAccessor &reg;
int idx;
};
__attribute__((always_inline)) BitAccessor operator[](int idx) {
return BitAccessor(*this, idx);
}
__attribute__((always_inline)) const Peripheral &Commit() {
*ptr = write_value;
read_value = write_value;
return peripheral;
}
const Peripheral &peripheral;
volatile Base *ptr;
Base read_value;
Base write_value;
};
// [low, high] is an inclusive range, since that's the way these things are written in the TRM
template<typename RegAcc, uint8_t low, uint8_t high = low, typename Type = typename RegAcc::Base, uint8_t internal_shift = 0>
class RegisterFieldAccessorBase {
public:
__attribute__((always_inline)) RegisterFieldAccessorBase(RegAcc &acc) : acc(acc) { }
protected:
__attribute__((always_inline)) Type Get() {
return Type(((this->acc.read_value & mask) >> low) << internal_shift);
}
__attribute__((always_inline)) RegAcc &Set(Type value) {
this->acc.write_value&= ~mask;
this->acc.write_value|= ((typename RegAcc::Base(value) >> internal_shift) << low) & mask;
return acc;
}
public:
static const typename RegAcc::Base mask = ((typename RegAcc::Base(2) << (high-low)) - 1) << low;
protected:
using FieldType = Type;
using RegisterAccessor = RegAcc;
RegAcc &acc;
};
// base accessors
template<typename RegAcc, uint8_t low, uint8_t high = low, typename Type = typename RegAcc::Base, uint8_t internal_shift = 0>
class RegisterRWFieldAccessorBase : public RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift> {
public:
__attribute__((always_inline)) RegisterRWFieldAccessorBase(RegAcc &acc) : RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift>(acc) {
}
__attribute__((always_inline)) Type Get() {
return RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift>::Get();
}
__attribute__((always_inline)) explicit operator Type() {
return Get();
}
__attribute__((always_inline)) RegAcc &Set(Type value) {
return RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift>::Set(value);
}
};
template<typename RegAcc, uint8_t low, uint8_t high = low, typename Type = typename RegAcc::Base, uint8_t internal_shift = 0>
class RegisterROFieldAccessorBase : public RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift> {
public:
__attribute__((always_inline)) RegisterROFieldAccessorBase(RegAcc &acc) : RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift>(acc) {
}
__attribute__((always_inline)) Type Get() {
return RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift>::Get();
}
__attribute__((always_inline)) explicit operator Type() {
return Get();
}
};
template<typename RegAcc, uint8_t low, uint8_t high = low, typename Type = typename RegAcc::Base, uint8_t internal_shift = 0>
class RegisterWOFieldAccessorBase : public RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift> {
public:
__attribute__((always_inline)) RegisterWOFieldAccessorBase(RegAcc &acc) : RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift>(acc) {
}
__attribute__((always_inline)) RegAcc &Set(Type value) {
return RegisterFieldAccessorBase<RegAcc, low, high, Type, internal_shift>::Set(value);
}
};
// generic accessors
template<typename RegAcc, uint8_t low, uint8_t high = low, typename Type = typename RegAcc::Base, uint8_t internal_shift = 0>
class RegisterRWFieldAccessor : public RegisterRWFieldAccessorBase<RegAcc, low, high, Type, internal_shift> {
public:
__attribute__((always_inline)) RegisterRWFieldAccessor(RegAcc &acc) : RegisterRWFieldAccessorBase<RegAcc, low, high, Type, internal_shift>(acc) {
}
};
template<typename RegAcc, uint8_t low, uint8_t high = low, typename Type = typename RegAcc::Base, uint8_t internal_shift = 0>
class RegisterROFieldAccessor : public RegisterROFieldAccessorBase<RegAcc, low, high, Type, internal_shift> {
public:
__attribute__((always_inline)) RegisterROFieldAccessor(RegAcc &acc) : RegisterROFieldAccessorBase<RegAcc, low, high, Type, internal_shift>(acc) {
}
};
template<typename RegAcc, uint8_t low, uint8_t high = low, typename Type = typename RegAcc::Base, uint8_t internal_shift = 0>
class RegisterWOFieldAccessor : public RegisterWOFieldAccessorBase<RegAcc, low, high, Type, internal_shift> {
public:
__attribute__((always_inline)) RegisterWOFieldAccessor(RegAcc &acc) : RegisterWOFieldAccessorBase<RegAcc, low, high, Type, internal_shift>(acc) {
}
};
// unusual accessors
template<typename RegAcc, uint8_t low>
class RegisterRW1CFieldAccessor : public RegisterFieldAccessorBase<RegAcc, low, low, bool, 0> {
public:
__attribute__((always_inline)) RegisterRW1CFieldAccessor(RegAcc &acc) : RegisterFieldAccessorBase<RegAcc, low, low, bool, 0>(acc) {
acc.write_value&= ~RegisterFieldAccessorBase<RegAcc, low, low, bool>::mask;
}
__attribute__((always_inline)) bool Get() {
return RegisterFieldAccessorBase<RegAcc, low, low, bool>::Get();
}
__attribute__((always_inline)) operator bool() {
return RegisterFieldAccessorBase<RegAcc, low, low, bool>::Get();
}
__attribute__((always_inline)) RegAcc &Clear() {
return RegisterFieldAccessorBase<RegAcc, low, low, bool>::Set(true);
}
};
// templated-specialized accessors
template<typename RegAcc, uint8_t low>
class RegisterRWFieldAccessor<RegAcc, low, low> : public RegisterRWFieldAccessorBase<RegAcc, low, low, bool> {
public:
__attribute__((always_inline)) RegisterRWFieldAccessor(RegAcc &acc) : RegisterRWFieldAccessorBase<RegAcc, low, low, bool>(acc) {
}
__attribute__((always_inline)) RegAcc &Disable() {
return RegisterFieldAccessorBase<RegAcc, low, low, bool>::Set(false);
}
__attribute__((always_inline)) RegAcc &Enable() {
return RegisterFieldAccessorBase<RegAcc, low, low, bool>::Set(true);
}
__attribute__((always_inline)) operator bool() {
return RegisterFieldAccessorBase<RegAcc, low, low, bool>::Get();
}
};
template<typename RegAcc, uint8_t low>
class RegisterROFieldAccessor<RegAcc, low, low> : public RegisterROFieldAccessorBase<RegAcc, low, low, bool> {
public:
__attribute__((always_inline)) RegisterROFieldAccessor(RegAcc &acc) : RegisterROFieldAccessorBase<RegAcc, low, low, bool>(acc) {
}
__attribute__((always_inline)) operator bool() {
return RegisterROFieldAccessorBase<RegAcc, low, low, bool>::Get();
}
};
#define BEGIN_DEFINE_REGISTER(name, type, offset) \
class name##_Accessor : public RegisterAccessor<Peripheral, type, offset> { \
public: \
using RegSelf = name##_Accessor; \
__attribute__((always_inline)) name##_Accessor(const Peripheral &p) : RegisterAccessor(p) {} \
__attribute__((always_inline)) name##_Accessor(const Peripheral &p, type value) : RegisterAccessor(p, value) {}
#define BEGIN_DEFINE_WO_REGISTER(name, type, offset) \
class name##_Accessor : public RegisterAccessor<Peripheral, type, offset> { \
public: \
using RegSelf = name##_Accessor; \
__attribute__((always_inline)) name##_Accessor(const Peripheral &p) : RegisterAccessor(p, 0) {}
#define DEFINE_RW_FIELD(name, ...) \
RegisterRWFieldAccessor<RegSelf, __VA_ARGS__> name = RegisterRWFieldAccessor<RegSelf, __VA_ARGS__>(*this);
#define DEFINE_RO_FIELD(name, ...) \
RegisterROFieldAccessor<RegSelf, __VA_ARGS__> name = RegisterROFieldAccessor<RegSelf, __VA_ARGS__>(*this);
#define DEFINE_WO_FIELD(name, ...) \
RegisterWOFieldAccessor<RegSelf, __VA_ARGS__> name = RegisterWOFieldAccessor<RegSelf, __VA_ARGS__>(*this);
#define DEFINE_RW1C_FIELD(name, ...) \
RegisterRW1CFieldAccessor<RegSelf, __VA_ARGS__> name = RegisterRW1CFieldAccessor<RegSelf, __VA_ARGS__>(*this);
#define BEGIN_DEFINE_RO_SYMBOLIC_FIELD(name, low, high) \
struct name##_Accessor : public RegisterROFieldAccessor<RegSelf, low, high, RegSelf::Base> {\
using SymSelf = name##_Accessor; \
__attribute__((always_inline)) name##_Accessor(RegSelf &acc) : RegisterROFieldAccessor(acc) { }
#define BEGIN_DEFINE_RW_SYMBOLIC_FIELD(name, low, high) \
struct name##_Accessor : public RegisterRWFieldAccessor<RegSelf, low, high, RegSelf::Base> {\
using SymSelf = name##_Accessor; \
__attribute__((always_inline)) name##_Accessor(RegSelf &acc) : RegisterRWFieldAccessor(acc) { }
#define DEFINE_RO_SYMBOLIC_VALUE(name, value) \
__attribute__((always_inline)) bool Is##name() { \
return Get() == typename SymSelf::FieldType(value); \
}
#define DEFINE_RW_SYMBOLIC_VALUE(name, value) \
__attribute__((always_inline)) RegisterAccessor &Set##name() {\
return Set(typename SymSelf::FieldType(value)); \
} \
__attribute__((always_inline)) bool Is##name() { \
return Get() == typename SymSelf::FieldType(value); \
}
#define END_DEFINE_SYMBOLIC_FIELD(name) \
} name = name##_Accessor(*this);
#define END_DEFINE_REGISTER(name) \
}; \
__attribute__((always_inline)) name##_Accessor name() const { \
return name##_Accessor(*this); \
} \
__attribute__((always_inline)) name##_Accessor name(name##_Accessor::Base value) const { \
return name##_Accessor(*this, value); \
}
#define END_DEFINE_WO_REGISTER(name) \
}; \
__attribute__((always_inline)) name##_Accessor name() const { \
return name##_Accessor(*this); \
}
#define DEFINE_BIT_ARRAY_REGISTER(name, type, offset) \
__attribute__((always_inline)) BitArrayRegisterAccessor<Peripheral, type> name() const { \
return BitArrayRegisterAccessor<Peripheral, type>(*this, offset); \
} \
__attribute__((always_inline)) BitArrayRegisterAccessor<Peripheral, type> name(type value) const { \
return BitArrayRegisterAccessor<Peripheral, type>(*this, offset, value); \
}
#define DEFINE_RW1C_BIT_ARRAY_REGISTER(name, type, offset) \
__attribute__((always_inline)) BitArrayRegisterAccessor<Peripheral, type> name() const { \
return BitArrayRegisterAccessor<Peripheral, type>(*this, offset, rw1c_marker {}); \
}
#if (0)
/*
This can look a little obtuse, so here's an example of how it's meant to be used:
*/
namespace t210 {
const struct T_XUSB_DEV_XHCI {
/* This field needs to have this name and this type, since it is used by the *_DEFINE_REGISTER macros. */
/* However, it is allowed to be non-static, in case you have multiple instances of the same kind of peripheral. */
static const uintptr_t base_addr = 0x7000d000;
/* This using needs to have this name, since it is used by the macros. */
using Peripheral = T_XUSB_DEV_XHCI;
/* You can use your own types with register fields, as long as they can be casted to and from integer types. */
enum class LinkSpeed {
/* ... */
};
/* BEGIN_DEFINE_REGISTER(name, base type, offset from periphal base)
Defines a register. */
BEGIN_DEFINE_REGISTER(EREPLO, uint32_t, 0x28)
/* DEFINE_RW_FIELD(name, lo, [hi], [type], [internal shift])
Internal shift is used for fields that store values without low bits.
Here, we want to be able to access a pointer directly, but the low 4 bits
belong to a different field, so the internal shift automatically shifts
reads and writes for us. */
DEFINE_RW_FIELD(ADDRLO, 4, 31, uintptr_t, 4)
DEFINE_RW_FIELD(SEGI, 1)
DEFINE_RW_FIELD(ECS, 0)
END_DEFINE_REGISTER(EREPLO)
BEGIN_DEFINE_REGISTER(PORTSC, uint32_t, 0x3c)
/* DEFINE_RO_FIELD(name, lo, [hi], [base type], [internal shift])
Same as DEFINE_RW_FIELD except it creates a different accessor type
that does not have methods for writing. */
DEFINE_RO_FIELD(WPR, 30)
DEFINE_RO_FIELD(RSVD4, 28, 29)
/* DEFINE_RW1C_FIELD(name, lo)
Defines a bit that is cleared when 1 is written to it, so we
need to be sure to not write it back if we don't mean to. Will not
write back unless you call .Clear() on it.
Forced to be a single-bit boolean type. */
DEFINE_RW1C_FIELD(CEC, 23)
DEFINE_RW1C_FIELD(PLC, 22)
DEFINE_RW1C_FIELD(PRC, 21)
DEFINE_RO_FIELD(RSVD3, 20)
DEFINE_RW1C_FIELD(WRC, 19)
DEFINE_RW1C_FIELD(CSC, 17)
DEFINE_RW_FIELD(LWS, 16)
DEFINE_RO_FIELD(RSVD2, 15)
/* BEGIN_DEFINE_RO_SYMBOLIC_FIELD(name, lo, hi)
Defines an enumerated field without writer accessor methods. */
BEGIN_DEFINE_RO_SYMBOLIC_FIELD(PS, 10, 13)
/* Defines an enumerated value without writer accessor methods. */
DEFINE_RO_SYMBOLIC_VALUE(UNDEFINED, 0)
DEFINE_RO_SYMBOLIC_VALUE(FS, 1)
DEFINE_RO_SYMBOLIC_VALUE(LS, 2)
DEFINE_RO_SYMBOLIC_VALUE(HS, 3)
DEFINE_RO_SYMBOLIC_VALUE(SS, 4)
END_DEFINE_SYMBOLIC_FIELD(PS)
DEFINE_RO_FIELD(LANE_POLARITY_VALUE, 9)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(PLS, 5, 8)
DEFINE_RW_SYMBOLIC_VALUE(U0, 0)
DEFINE_RW_SYMBOLIC_VALUE(U1, 1)
DEFINE_RW_SYMBOLIC_VALUE(U2, 2)
DEFINE_RW_SYMBOLIC_VALUE(U3, 3)
DEFINE_RW_SYMBOLIC_VALUE(DISABLED, 4)
DEFINE_RW_SYMBOLIC_VALUE(RXDETECT, 5)
DEFINE_RW_SYMBOLIC_VALUE(INACTIVE, 6)
DEFINE_RW_SYMBOLIC_VALUE(POLLING, 7)
DEFINE_RW_SYMBOLIC_VALUE(RECOVERY, 8)
DEFINE_RW_SYMBOLIC_VALUE(HOTRESET, 9)
DEFINE_RW_SYMBOLIC_VALUE(COMPLIANCE, 0xa)
DEFINE_RW_SYMBOLIC_VALUE(LOOPBACK, 0xb)
DEFINE_RW_SYMBOLIC_VALUE(RESUME, 0xf)
END_DEFINE_SYMBOLIC_FIELD(PLS)
DEFINE_RO_FIELD(PR, 4)
DEFINE_RW_FIELD(LANE_POLARITY_OVRD_VALUE, 3)
DEFINE_RW_FIELD(LANE_POLARITY_OVRD, 2)
DEFINE_RW_FIELD(PED, 1)
DEFINE_RW_FIELD(CCS, 0)
END_DEFINE_REGISTER(PORTSC)
} T_XUSB_DEV_XHCI;
void chaining_example() {
t210::CLK_RST_CONTROLLER
.CLK_OUT_ENB_W_0()
.CLK_ENB_XUSB().Enable()
.Commit()
.RST_DEVICES_W_0()
.SWR_XUSB_SS_RST().Set(0)
.Commit();
t210::XUSB_PADCTL
.USB2_PAD_MUX_0()
.USB2_OTG_PAD_PORT0().SetXUSB()
.USB2_BIAS_PAD().SetXUSB()
.Commit();
}
void rw1c_example() {
auto portsc = t210::XUSB_DEV.PORTSC();
if (portsc.CEC) {
portsc.CEC.Clear();
}
portsc.PED.Set(true);
portsc.Commit();
}
uintptr_t internal_shift_example() {
t210::XUSB_DEV
.EREPLO()
.ADDRLO.Set((uintptr_t) &internal_shift_example)
.Commit();
return t210::XUSB_DEV.EREPLO().ADDRLO.Get();
}
void no_read_example() {
t210::XUSB_DEV
.EREPLO(0) // does not read from register- instead assumes it contains 0
.ADDRLO.Set((uintptr_t) &no_read_example)
.Commit();
}
#endif

View File

@ -0,0 +1,222 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "reg_util.h"
namespace t210 {
static const uintptr_t XUSB_DEV_BASE = 0x700d0000;
const struct T_XUSB_DEV_XHCI {
static const uintptr_t base_addr = XUSB_DEV_BASE;
using Peripheral = T_XUSB_DEV_XHCI;
BEGIN_DEFINE_WO_REGISTER(DB, uint32_t, 0x4)
DEFINE_WO_FIELD(STREAMID, 16, 31)
DEFINE_WO_FIELD(TARGET, 8, 15)
END_DEFINE_WO_REGISTER(DB)
BEGIN_DEFINE_REGISTER(ERSTSZ, uint32_t, 0x8)
DEFINE_RW_FIELD(ERST1SZ, 16, 31)
DEFINE_RW_FIELD(ERST0SZ, 0, 15)
END_DEFINE_REGISTER(ERSTSZ)
BEGIN_DEFINE_REGISTER(ERST0BALO, uint32_t, 0x10)
DEFINE_RW_FIELD(ADDRLO, 4, 31, uintptr_t, 4)
END_DEFINE_REGISTER(ERST0BALO)
BEGIN_DEFINE_REGISTER(ERST0BAHI, uint32_t, 0x14)
DEFINE_RW_FIELD(ADDRHI, 0, 31)
END_DEFINE_REGISTER(ERST0BAHI)
BEGIN_DEFINE_REGISTER(ERST1BALO, uint32_t, 0x18)
DEFINE_RW_FIELD(ADDRLO, 4, 31, uintptr_t, 4)
END_DEFINE_REGISTER(ERST1BALO)
BEGIN_DEFINE_REGISTER(ERST1BAHI, uint32_t, 0x1c)
DEFINE_RW_FIELD(ADDRHI, 0, 31)
END_DEFINE_REGISTER(ERST1BAHI)
BEGIN_DEFINE_REGISTER(ERDPLO, uint32_t, 0x20)
DEFINE_RW_FIELD(ADDRLO, 4, 31, uintptr_t, 4)
DEFINE_RW1C_FIELD(EHB, 3)
END_DEFINE_REGISTER(ERDPLO)
BEGIN_DEFINE_REGISTER(ERDPHI, uint32_t, 0x24)
DEFINE_RW_FIELD(ADDRHI, 0, 31)
END_DEFINE_REGISTER(ERDPHI)
BEGIN_DEFINE_REGISTER(EREPLO, uint32_t, 0x28)
DEFINE_RW_FIELD(ADDRLO, 4, 31, uintptr_t, 4)
DEFINE_RW_FIELD(SEGI, 1)
DEFINE_RW_FIELD(ECS, 0)
END_DEFINE_REGISTER(EREPLO)
BEGIN_DEFINE_REGISTER(EREPHI, uint32_t, 0x2c)
DEFINE_RW_FIELD(ADDRHI, 0, 31)
END_DEFINE_REGISTER(EREPHI)
BEGIN_DEFINE_REGISTER(CTRL, uint32_t, 0x30)
DEFINE_RW_FIELD(ENABLE, 31)
DEFINE_RW_FIELD(DEVADR, 24, 30)
DEFINE_RW_FIELD(RSVD0, 8, 23)
DEFINE_RW_FIELD(EWE, 7)
DEFINE_RW_FIELD(SMI_DSE, 6)
DEFINE_RW_FIELD(SMI_EVT, 5)
DEFINE_RW_FIELD(IE, 4)
DEFINE_RW_FIELD(RSVD1, 2, 3)
DEFINE_RW_FIELD(LSE, 1)
DEFINE_RW_FIELD(RUN, 0)
END_DEFINE_REGISTER(CTRL)
BEGIN_DEFINE_REGISTER(ST, uint32_t, 0x34)
DEFINE_RO_FIELD(RSVD1, 6, 1)
DEFINE_RW1C_FIELD(DSE, 5)
DEFINE_RW1C_FIELD(IP, 4)
DEFINE_RO_FIELD(RSVD0, 1, 3)
DEFINE_RW1C_FIELD(RC, 0)
END_DEFINE_REGISTER(ST)
BEGIN_DEFINE_REGISTER(PORTSC, uint32_t, 0x3c)
DEFINE_RW_FIELD(WPR, 30)
DEFINE_RW_FIELD(RSVD4, 28, 29)
DEFINE_RW1C_FIELD(CEC, 23)
DEFINE_RW1C_FIELD(PLC, 22)
DEFINE_RW1C_FIELD(PRC, 21)
DEFINE_RW_FIELD(RSVD3, 20)
DEFINE_RW1C_FIELD(WRC, 19)
DEFINE_RW1C_FIELD(CSC, 17)
DEFINE_RW_FIELD(LWS, 16)
DEFINE_RW_FIELD(RSVD2, 15)
BEGIN_DEFINE_RO_SYMBOLIC_FIELD(PS, 10, 13)
DEFINE_RO_SYMBOLIC_VALUE(UNDEFINED, 0)
DEFINE_RO_SYMBOLIC_VALUE(FS, 1)
DEFINE_RO_SYMBOLIC_VALUE(LS, 2)
DEFINE_RO_SYMBOLIC_VALUE(HS, 3)
DEFINE_RO_SYMBOLIC_VALUE(SS, 4)
END_DEFINE_SYMBOLIC_FIELD(PS)
DEFINE_RO_FIELD(LANE_POLARITY_VALUE, 9)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(PLS, 5, 8)
DEFINE_RW_SYMBOLIC_VALUE(U0, 0)
DEFINE_RW_SYMBOLIC_VALUE(U1, 1)
DEFINE_RW_SYMBOLIC_VALUE(U2, 2)
DEFINE_RW_SYMBOLIC_VALUE(U3, 3)
DEFINE_RW_SYMBOLIC_VALUE(DISABLED, 4)
DEFINE_RW_SYMBOLIC_VALUE(RXDETECT, 5)
DEFINE_RW_SYMBOLIC_VALUE(INACTIVE, 6)
DEFINE_RW_SYMBOLIC_VALUE(POLLING, 7)
DEFINE_RW_SYMBOLIC_VALUE(RECOVERY, 8)
DEFINE_RW_SYMBOLIC_VALUE(HOTRESET, 9)
DEFINE_RW_SYMBOLIC_VALUE(COMPLIANCE, 0xa)
DEFINE_RW_SYMBOLIC_VALUE(LOOPBACK, 0xb)
DEFINE_RW_SYMBOLIC_VALUE(RESUME, 0xf)
END_DEFINE_SYMBOLIC_FIELD(PLS)
DEFINE_RO_FIELD(PR, 4)
DEFINE_RW_FIELD(LANE_POLARITY_OVRD_VALUE, 3)
DEFINE_RW_FIELD(LANE_POLARITY_OVRD, 2)
DEFINE_RW1C_FIELD(PED, 1) // TODO: is this rw1c?
DEFINE_RW_FIELD(CCS, 0)
END_DEFINE_REGISTER(PORTSC)
BEGIN_DEFINE_REGISTER(ECPLO, uint32_t, 0x40)
DEFINE_RW_FIELD(ADDRLO, 6, 31, uintptr_t, 6)
END_DEFINE_REGISTER(ECPLO)
BEGIN_DEFINE_REGISTER(ECPHI, uint32_t, 0x44)
DEFINE_RW_FIELD(ADDRHI, 0, 31)
END_DEFINE_REGISTER(ECPHI)
DEFINE_BIT_ARRAY_REGISTER(EP_HALT, uint32_t, 0x50)
DEFINE_BIT_ARRAY_REGISTER(EP_PAUSE, uint32_t, 0x54)
DEFINE_BIT_ARRAY_REGISTER(EP_RELOAD, uint32_t, 0x58)
DEFINE_RW1C_BIT_ARRAY_REGISTER(EP_STCHG, uint32_t, 0x5c)
BEGIN_DEFINE_REGISTER(PORTHALT, uint32_t, 0x6c)
// TRM labels both bit 26 and bit 20 as STCHG_REQ, but Linux kernel sources disambiguate it.
// https://patchwork.kernel.org/patch/11129617/
//DEFINE_RW_FIELD(???, 26)
DEFINE_RW_FIELD(STCHG_PME_EN, 25)
DEFINE_RW_FIELD(STCHG_INTR_EN, 24)
DEFINE_RW1C_FIELD(STCHG_REQ, 20)
DEFINE_RW_FIELD(STCHG_STATE, 16, 19)
DEFINE_RW1C_FIELD(HALT_REJECT, 1) // TODO: RW1C semantics
DEFINE_RW_FIELD(HALT_LTSSM, 0)
END_DEFINE_REGISTER(PORTHALT)
DEFINE_RW1C_BIT_ARRAY_REGISTER(EP_STOPPED, uint32_t, 0x78)
BEGIN_DEFINE_REGISTER(CFG_DEV_FE, uint32_t, 0x85c)
// "Note: Do not change the values in bits 31:2"
DEFINE_RW_FIELD(INFINITE_SS_RETRY, 29)
DEFINE_RW_FIELD(EN_PRIME_EVENT, 28)
DEFINE_RW_FIELD(FEATURE_LPM, 27)
DEFINE_RW_FIELD(EN_STALL_EVENT, 26)
DEFINE_RW_FIELD(PORTDISCON_RST_HW, 25)
DEFINE_RW_FIELD(CTX_RESTORE, 24)
DEFINE_RW_FIELD(MFCOUNT_MIN, 4, 23)
DEFINE_RW_FIELD(PORTRST_HW, 3)
DEFINE_RW_FIELD(SEQNUM_INIT, 2)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(PORTREGSEL, 0, 1)
DEFINE_RW_SYMBOLIC_VALUE(INIT, 0)
DEFINE_RW_SYMBOLIC_VALUE(SS, 1)
DEFINE_RW_SYMBOLIC_VALUE(HSFS, 2)
END_DEFINE_SYMBOLIC_FIELD(PORTREGSEL)
END_DEFINE_REGISTER(CFG_DEV_FE)
} T_XUSB_DEV_XHCI;
const struct T_XUSB_DEV {
static const uintptr_t base_addr = XUSB_DEV_BASE + 0x8000;
using Peripheral = T_XUSB_DEV;
BEGIN_DEFINE_REGISTER(CFG_1, uint32_t, 0x4)
DEFINE_RW_FIELD(IO_SPACE, 0)
DEFINE_RW_FIELD(MEMORY_SPACE, 1)
DEFINE_RW_FIELD(BUS_MASTER, 2)
END_DEFINE_REGISTER(CFG_1)
BEGIN_DEFINE_REGISTER(CFG_4, uint32_t, 0x10)
DEFINE_RW_FIELD(BASE_ADDRESS, 15, 31, uintptr_t, 15)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(PREFETCHABLE, 3, 3)
DEFINE_RW_SYMBOLIC_VALUE(NOT, 0)
DEFINE_RW_SYMBOLIC_VALUE(MERGABLE, 1)
END_DEFINE_SYMBOLIC_FIELD(PREFETCHABLE)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(ADDRESS_TYPE, 1, 2)
DEFINE_RW_SYMBOLIC_VALUE(32_BIT, 0)
DEFINE_RW_SYMBOLIC_VALUE(64_BIT, 2)
END_DEFINE_SYMBOLIC_FIELD(ADDRESS_TYPE)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(SPACE_TYPE, 0, 0)
DEFINE_RW_SYMBOLIC_VALUE(MEMORY, 0)
DEFINE_RW_SYMBOLIC_VALUE(IO, 1)
END_DEFINE_SYMBOLIC_FIELD(SPACE_TYPE)
END_DEFINE_REGISTER(CFG_4)
} T_XUSB_DEV;
const struct XUSB_DEV {
static const uintptr_t base_addr = XUSB_DEV_BASE + 0x9000;
using Peripheral = XUSB_DEV;
BEGIN_DEFINE_REGISTER(CONFIGURATION_0, uint32_t, 0x180)
DEFINE_RW_FIELD(EN_FPCI, 0)
END_DEFINE_REGISTER(CONFIGURATION_0)
BEGIN_DEFINE_REGISTER(INTR_MASK_0, uint32_t, 0x188)
DEFINE_RW_FIELD(IP_INT_MASK, 16)
DEFINE_RW_FIELD(MSI_MASK, 8)
DEFINE_RW_FIELD(INT_MASK, 0)
END_DEFINE_REGISTER(INTR_MASK_0)
} XUSB_DEV;
} // namespace t210

View File

@ -0,0 +1,211 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "reg_util.h"
namespace t210 {
const struct XUSB_PADCTL {
static const uintptr_t base_addr = 0x7009f000;
using Peripheral = XUSB_PADCTL;
BEGIN_DEFINE_REGISTER(USB2_PAD_MUX_0, uint32_t, 0x4)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(USB2_OTG_PAD_PORT0, 0, 1)
DEFINE_RW_SYMBOLIC_VALUE(SNPS, 0)
DEFINE_RW_SYMBOLIC_VALUE(XUSB, 1)
DEFINE_RW_SYMBOLIC_VALUE(UART, 2)
END_DEFINE_SYMBOLIC_FIELD(USB2_OTG_PAD_PORT0)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(USB2_BIAS_PAD, 18, 19)
DEFINE_RW_SYMBOLIC_VALUE(SNPS, 0)
DEFINE_RW_SYMBOLIC_VALUE(XUSB, 1)
DEFINE_RW_SYMBOLIC_VALUE(UART, 2)
END_DEFINE_SYMBOLIC_FIELD(USB2_BIAS_PAD)
END_DEFINE_REGISTER(USB2_PAD_MUX_0)
BEGIN_DEFINE_REGISTER(USB2_PORT_CAP_0, uint32_t, 0x8)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(PORT0_CAP, 0, 1)
DEFINE_RW_SYMBOLIC_VALUE(Disabled, 0)
DEFINE_RW_SYMBOLIC_VALUE(HostOnly, 1)
DEFINE_RW_SYMBOLIC_VALUE(DeviceOnly, 2)
DEFINE_RW_SYMBOLIC_VALUE(OtgCap, 3)
END_DEFINE_SYMBOLIC_FIELD(PORT0_CAP)
END_DEFINE_REGISTER(USB2_PORT_CAP_0)
BEGIN_DEFINE_REGISTER(SS_PORT_MAP_0, uint32_t, 0x14)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(PORT0_MAP, 0, 3)
DEFINE_RW_SYMBOLIC_VALUE(USB2Port0, 0)
DEFINE_RW_SYMBOLIC_VALUE(USB2Port1, 1)
DEFINE_RW_SYMBOLIC_VALUE(USB2Port2, 2)
DEFINE_RW_SYMBOLIC_VALUE(USB2Port3, 3)
DEFINE_RW_SYMBOLIC_VALUE(InitDisabled, 7)
END_DEFINE_SYMBOLIC_FIELD(PORT0_MAP)
END_DEFINE_REGISTER(SS_PORT_MAP_0)
BEGIN_DEFINE_REGISTER(ELPG_PROGRAM_0_0, uint32_t, 0x20)
END_DEFINE_REGISTER(ELPG_PROGRAM_0_0)
BEGIN_DEFINE_REGISTER(ELPG_PROGRAM_1_0, uint32_t, 0x24)
END_DEFINE_REGISTER(ELPG_PROGRAM_1_0)
BEGIN_DEFINE_REGISTER(USB2_BATTERY_CHRG_OTGPAD0_CTL0_0, uint32_t, 0x80)
DEFINE_RW_FIELD(GENERATE_SRP, 31)
DEFINE_RW_FIELD(SRP_INTR_EN, 30)
DEFINE_RW_FIELD(SRP_DETECTED, 29)
DEFINE_RW_FIELD(SRP_DETECT_EN, 28)
DEFINE_RW_FIELD(DCD_INTR_EN, 27)
DEFINE_RW_FIELD(DCD_DETECTED, 26)
DEFINE_RW_FIELD(ZIN_FILTER_EN, 25)
DEFINE_RW_FIELD(ZIN_CHNG_INTR_EN, 24)
DEFINE_RW_FIELD(ZIN_ST_CHNG, 23)
DEFINE_RO_FIELD(ZIN, 22)
DEFINE_RW_FIELD(ZIP_FILTER_EN, 21)
DEFINE_RW_FIELD(ZIP_CHNG_INTER_EN, 20)
DEFINE_RW_FIELD(ZIP_ST_CHNG, 19)
DEFINE_RO_FIELD(ZIP, 18)
DEFINE_RW_FIELD(OP_I_SRC_EN, 13)
DEFINE_RW_FIELD(ON_SRC_EN, 12)
DEFINE_RW_FIELD(ON_SINK_EN, 11)
DEFINE_RW_FIELD(OP_SRV_EN, 10)
DEFINE_RW_FIELD(OP_SINK_EN, 9)
DEFINE_RW_FIELD(VDAT_DET_FILTER_EN, 8)
DEFINE_RW_FIELD(VDAT_DET_CHNG_INTER_EN, 7)
DEFINE_RW_FIELD(VDAT_DET_ST_CHNG, 6)
DEFINE_RO_FIELD(VDAT_DET, 5)
DEFINE_RW_FIELD(VDCD_DET_FILTER_EN, 4)
DEFINE_RW_FIELD(VDCD_DET_CHNG_INTR_EN, 3)
DEFINE_RW_FIELD(VDCD_DET_ST_CHNG, 2)
DEFINE_RO_FIELD(VDCD_DET, 1)
DEFINE_RW_FIELD(PD_CHG, 0)
END_DEFINE_REGISTER(USB2_BATTERY_CHRG_OTGPAD0_CTL0_0)
BEGIN_DEFINE_REGISTER(USB2_BATTERY_CHRG_OTGPAD0_CTL1_0, uint32_t, 0x84)
DEFINE_RW_FIELD(USBON_RPU_OVRD_VAL, 23)
DEFINE_RW_FIELD(USBON_RPU_OVRD, 22)
DEFINE_RW_FIELD(USBON_RPD_OVRD_VAL, 21)
DEFINE_RW_FIELD(USBON_RPD_OVRD, 20)
DEFINE_RW_FIELD(USBOP_RPU_OVRD_VAL, 19)
DEFINE_RW_FIELD(USBOP_RPU_OVRD, 18)
DEFINE_RW_FIELD(USBOP_RPD_OVRD_VAL, 17)
DEFINE_RW_FIELD(USBOP_RPD_OVRD, 16)
DEFINE_RW_FIELD(VREG_DYN_DLY, 9, 10)
DEFINE_RW_FIELD(VREG_LEV, 7, 8)
DEFINE_RW_FIELD(VREG_FIX18, 6)
DEFINE_RW_FIELD(DIV_DET_EN, 4)
DEFINE_RO_FIELD(VOP_DIV2P7_DET, 3)
DEFINE_RO_FIELD(VOP_DIV2P0_DET, 2)
DEFINE_RO_FIELD(VON_DIV2P7_DET, 1)
DEFINE_RO_FIELD(VON_DIV2P0_DET, 0)
END_DEFINE_REGISTER(USB2_BATTERY_CHRG_OTGPAD0_CTL1_0)
BEGIN_DEFINE_REGISTER(USB2_OTG_PAD0_CTL_0_0, uint32_t, 0x88)
DEFINE_RW_FIELD(PD_ZI, 29)
DEFINE_RW_FIELD(PD2_OVRD_EN, 28)
DEFINE_RW_FIELD(PD2, 27)
DEFINE_RW_FIELD(PD, 26)
DEFINE_RW_FIELD(TERM_SEL, 25)
DEFINE_RW_FIELD(LS_FSLEW, 21, 24)
DEFINE_RW_FIELD(LS_RSLEW, 17, 20)
DEFINE_RW_FIELD(FS_FSLEW, 13, 16)
DEFINE_RW_FIELD(FS_RSLEW, 9, 12)
DEFINE_RW_FIELD(HS_SLEW, 6, 8)
DEFINE_RW_FIELD(HS_CURR_LEVEL, 0, 5)
END_DEFINE_REGISTER(USB2_OTG_PAD0_CTL_0_0)
BEGIN_DEFINE_REGISTER(USB2_OTG_PAD0_CTL_1_0, uint32_t, 0x8c)
DEFINE_RW_FIELD(RPD_CTRL, 26, 30)
DEFINE_RO_FIELD(RPU_STATUS_HIGH, 25)
DEFINE_RW_FIELD(RPU_SWITCH_LOW, 24)
DEFINE_RW_FIELD(RPU_SWITCH_OVRD, 23)
DEFINE_RW_FIELD(HS_LOOPBACK_OVRD_VAL, 22)
DEFINE_RW_FIELD(HS_LOOPBACK_OVRD_EN, 21)
DEFINE_RW_FIELD(PTERM_RANGE_ADJ, 17, 20)
DEFINE_RW_FIELD(PD_DISC_OVRD_VAL, 16)
DEFINE_RW_FIELD(PD_CHRP_OVRD_VAL, 15)
DEFINE_RW_FIELD(RPU_RANGE_ADJ, 13, 14)
DEFINE_RW_FIELD(HS_COUP_EN, 11, 12)
DEFINE_RW_FIELD(SPARE, 7, 10)
DEFINE_RW_FIELD(TERM_RANGE_ADJ, 3, 6)
DEFINE_RW_FIELD(PD_DR, 2)
DEFINE_RW_FIELD(PD_DISC_OVRD, 1)
DEFINE_RW_FIELD(PD_CHRP_OVRD, 0)
END_DEFINE_REGISTER(USB2_OTG_PAD0_CTL_1_0)
BEGIN_DEFINE_REGISTER(USB2_BIAS_PAD_CTL_0_0, uint32_t, 0x284)
DEFINE_RW_FIELD(TRK_POWER_ENA, 29)
DEFINE_RW_FIELD(SPARE, 25, 28)
DEFINE_RW_FIELD(CHG_DIV, 21, 24)
DEFINE_RW_FIELD(TEMP_COEF, 18, 20)
DEFINE_RW_FIELD(VREF_CTRL, 15, 17)
DEFINE_RW_FIELD(ADJRPU, 12, 14)
DEFINE_RW_FIELD(PD, 11)
DEFINE_RW_FIELD(TERM_OFFSET, 8, 10)
DEFINE_RW_FIELD(HS_CHIRP_LEVEL, 6, 7)
DEFINE_RW_FIELD(HS_DISCON_LEVEL, 3, 5)
DEFINE_RW_FIELD(HS_SQUELCH_LEVEL, 0, 2)
END_DEFINE_REGISTER(USB2_BIAS_PAD_CTL_0_0)
BEGIN_DEFINE_REGISTER(USB2_BIAS_PAD_CTL_1_0, uint32_t, 0x288)
DEFINE_RW_FIELD(FORCE_TRK_CLK_EN, 30)
DEFINE_RW_FIELD(TRK_SW_OVRF, 29)
DEFINE_RO_FIELD(TRK_DONE, 28)
DEFINE_RW_FIELD(TRK_START, 27)
DEFINE_RW_FIELD(PD_TRK, 26)
DEFINE_RW_FIELD(TRK_DONE_RESET_TIMER, 19, 25)
DEFINE_RW_FIELD(TRK_START_TIMER, 12, 18)
DEFINE_RO_FIELD(PCTRL, 6, 11)
DEFINE_RO_FIELD(TCTRL, 0, 5)
END_DEFINE_REGISTER(USB2_BIAS_PAD_CTL_1_0)
BEGIN_DEFINE_REGISTER(USB2_VBUS_ID_0, uint32_t, 0xc60)
DEFINE_RW_FIELD(VBUS_WAKEUP_CHNG_INTR_EN, 24)
DEFINE_RW_FIELD(VBUS_WAKEUP_ST_CHNG, 23)
DEFINE_RO_FIELD(VBUS_WAKEUP, 22)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(ID_OVERRIDE, 18, 21)
DEFINE_RW_SYMBOLIC_VALUE(GND, 0)
DEFINE_RW_SYMBOLIC_VALUE(A, 4)
DEFINE_RW_SYMBOLIC_VALUE(B, 2)
DEFINE_RW_SYMBOLIC_VALUE(C, 1)
DEFINE_RW_SYMBOLIC_VALUE(FLOAT, 8)
END_DEFINE_SYMBOLIC_FIELD(ID_OVERRIDE)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(ID_SOURCE_SELECT, 16, 17)
DEFINE_RW_SYMBOLIC_VALUE(VGPIO, 0)
DEFINE_RW_SYMBOLIC_VALUE(OVERRIDE, 1)
END_DEFINE_SYMBOLIC_FIELD(ID_SOURCE_SELECT)
DEFINE_RW_FIELD(VBUS_WAKEUP_OVERRIDE, 15)
DEFINE_RW_FIELD(VBUS_OVERRIDE, 14)
BEGIN_DEFINE_RW_SYMBOLIC_FIELD(VBUS_SOURCE_SELECT, 12, 13)
DEFINE_RW_SYMBOLIC_VALUE(VGPIO, 0)
DEFINE_RW_SYMBOLIC_VALUE(OVERRIDE, 1)
END_DEFINE_SYMBOLIC_FIELD(VBUS_SOURCE_SELECT)
DEFINE_RW_FIELD(IDDIG_CHNG_INTR_EN, 11)
DEFINE_RW_FIELD(IDDIG_ST_CHNG, 10)
DEFINE_RO_FIELD(IDDIG_C, 9)
DEFINE_RO_FIELD(IDDIG_B, 8)
DEFINE_RO_FIELD(IDDIG_A, 7)
DEFINE_RO_FIELD(IDDIG, 6)
DEFINE_RW_FIELD(VBUS_VALID_CHNG_INTR_EN, 5)
DEFINE_RW_FIELD(VBUS_VALID_ST_CHNG, 4)
DEFINE_RO_FIELD(VBUS_VALID, 3)
DEFINE_RW_FIELD(OTG_VBUS_SESS_VLD_CHNG_INTR_EN, 2)
DEFINE_RW_FIELD(OTG_VBUS_SESS_VLD_ST_CHNG, 1)
DEFINE_RO_FIELD(OTG_VBUS_SESS_VLD, 0)
END_DEFINE_REGISTER(USB2_VBUS_ID_0)
} XUSB_PADCTL;
} // namespace t210

File diff suppressed because it is too large Load Diff

View File

@ -19,48 +19,17 @@
#include "fs_utils.h" #include "fs_utils.h"
#include "utils.h" #include "utils.h"
char g_stage2_path[0x100] = {0}; bool stage2_run_mtc(const bct0_t *bct0) {
static bool has_run_mtc = false;
const char *stage2_get_program_path(void) {
return g_stage2_path;
}
static int stage2_ini_handler(void *user, const char *section, const char *name, const char *value) {
stage2_config_t *config = (stage2_config_t *)user;
uintptr_t x = 0;
if (strcmp(section, "stage1") == 0) {
if (strcmp(name, STAGE2_NAME_KEY) == 0) {
strncpy(config->path, value, sizeof(config->path) - 1);
config->path[sizeof(config->path) - 1] = '\0';
} else if (strcmp(name, STAGE2_MTC_NAME_KEY) == 0) {
strncpy(config->mtc_path, value, sizeof(config->mtc_path) - 1);
config->mtc_path[sizeof(config->mtc_path) - 1] = '\0';
} else if (strcmp(name, STAGE2_ADDRESS_KEY) == 0) {
/* Read in load address as a hex string. */
sscanf(value, "%x", &x);
config->load_address = x;
if (config->entrypoint == 0) {
config->entrypoint = config->load_address;
}
} else if (strcmp(name, STAGE2_ENTRYPOINT_KEY) == 0) {
/* Read in entrypoint as a hex string. */
sscanf(value, "%x", &x);
config->entrypoint = x;
} else {
return 0;
}
} else {
return 0;
}
return 1;
}
static bool run_mtc(const char *mtc_path, uintptr_t mtc_address) {
FILINFO info; FILINFO info;
size_t size; size_t size;
if (has_run_mtc) {
return true;
}
/* Check if the MTC binary is present. */ /* Check if the MTC binary is present. */
if (f_stat(mtc_path, &info) != FR_OK) { if (f_stat(bct0->stage2_mtc_path, &info) != FR_OK) {
print(SCREEN_LOG_LEVEL_WARNING, "Stage2's MTC binary not found!\n"); print(SCREEN_LOG_LEVEL_WARNING, "Stage2's MTC binary not found!\n");
return false; return false;
} }
@ -68,8 +37,8 @@ static bool run_mtc(const char *mtc_path, uintptr_t mtc_address) {
size = (size_t)info.fsize; size = (size_t)info.fsize;
/* Try to read the MTC binary. */ /* Try to read the MTC binary. */
if (read_from_file((void *)mtc_address, size, mtc_path) != size) { if (read_from_file((void *)bct0->stage2_load_address, size, bct0->stage2_mtc_path) != size) {
print(SCREEN_LOG_LEVEL_WARNING, "Failed to read stage2's MTC binary (%s)!\n", mtc_path); print(SCREEN_LOG_LEVEL_WARNING, "Failed to read stage2's MTC binary (%s)!\n", bct0->stage2_mtc_path);
return false; return false;
} }
@ -83,53 +52,47 @@ static bool run_mtc(const char *mtc_path, uintptr_t mtc_address) {
memcpy(&mtc_args->log_level, &mtc_log_level, sizeof(mtc_log_level)); memcpy(&mtc_args->log_level, &mtc_log_level, sizeof(mtc_log_level));
/* Run the MTC binary. */ /* Run the MTC binary. */
mtc_res = (((int (*)(int, void *))mtc_address)(mtc_argc, mtc_arg_data) == 0); mtc_res = (((int (*)(int, void *))bct0->stage2_load_address)(mtc_argc, mtc_arg_data) == 0);
/* Cleanup right away. */ /* Cleanup right away. */
memset((void *)mtc_address, 0, size); memset((void *)bct0->stage2_load_address, 0, size);
has_run_mtc = true;
return mtc_res; return mtc_res;
} }
void load_stage2(const char *bct0) { void stage2_validate_config(const bct0_t *bct0) {
stage2_config_t config = {0}; if (bct0->stage2_load_address == 0 || bct0->stage2_path[0] == '\x00') {
FILINFO info;
size_t size;
uintptr_t tmp_addr;
if (ini_parse_string(bct0, stage2_ini_handler, &config) < 0) {
fatal_error("Failed to parse BCT.ini!\n");
}
if (config.load_address == 0 || config.path[0] == '\x00') {
fatal_error("Failed to determine where to load stage2!\n"); fatal_error("Failed to determine where to load stage2!\n");
} }
if (strlen(config.path) + 1 + sizeof(stage2_args_t) > CHAINLOADER_ARG_DATA_MAX_SIZE) { if (strlen(bct0->stage2_path) + 1 + sizeof(stage2_args_t) > CHAINLOADER_ARG_DATA_MAX_SIZE) {
fatal_error("Stage2's path name is too big!\n"); fatal_error("Stage2's path name is too big!\n");
} }
if (!check_32bit_address_loadable(config.entrypoint)) { if (!check_32bit_address_loadable(bct0->stage2_entrypoint)) {
fatal_error("Stage2's entrypoint is invalid!\n"); fatal_error("Stage2's entrypoint is invalid!\n");
} }
if (!check_32bit_address_loadable(config.load_address)) { if (!check_32bit_address_loadable(bct0->stage2_load_address)) {
fatal_error("Stage2's load address is invalid!\n"); fatal_error("Stage2's load address is invalid!\n");
} }
print(SCREEN_LOG_LEVEL_DEBUG, "Stage 2 Config:\n"); print(SCREEN_LOG_LEVEL_DEBUG, "Stage 2 Config:\n");
print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " File Path: %s\n", config.path); print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " File Path: %s\n", bct0->stage2_path);
print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " MTC File Path: %s\n", config.mtc_path); print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " MTC File Path: %s\n", bct0->stage2_mtc_path);
print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " Load Address: 0x%08x\n", config.load_address); print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " Load Address: 0x%08x\n", bct0->stage2_load_address);
print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " Entrypoint: 0x%p\n", config.entrypoint); print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " Entrypoint: 0x%p\n", bct0->stage2_entrypoint);
}
/* Run the MTC binary. */ void stage2_load(const bct0_t *bct0) {
if (!run_mtc(config.mtc_path, config.load_address)) { FILINFO info;
print(SCREEN_LOG_LEVEL_WARNING, "DRAM training failed! Continuing with untrained DRAM.\n"); size_t size;
} uintptr_t tmp_addr;
if (f_stat(config.path, &info) != FR_OK) { if (f_stat(bct0->stage2_path, &info) != FR_OK) {
fatal_error("Failed to stat stage2 (%s)!\n", config.path); fatal_error("Failed to stat stage2 (%s)!\n", bct0->stage2_path);
} }
size = (size_t)info.fsize; size = (size_t)info.fsize;
@ -139,32 +102,29 @@ void load_stage2(const char *bct0) {
fatal_error("Stage2 is way too big!\n"); fatal_error("Stage2 is way too big!\n");
} }
if (!check_32bit_address_range_loadable(config.load_address, size)) { if (!check_32bit_address_range_loadable(bct0->stage2_load_address, size)) {
fatal_error("Stage2 has an invalid load address & size combination (0x%08x 0x%08x)!\n", config.load_address, size); fatal_error("Stage2 has an invalid load address & size combination (0x%08x 0x%08x)!\n", bct0->stage2_load_address, size);
} }
if (config.entrypoint < config.load_address || config.entrypoint >= config.load_address + size) { if (bct0->stage2_entrypoint < bct0->stage2_load_address || bct0->stage2_entrypoint >= bct0->stage2_load_address + size) {
fatal_error("Stage2's entrypoint is outside Stage2!\n"); fatal_error("Stage2's entrypoint is outside Stage2!\n");
} }
if (check_32bit_address_range_in_program(config.load_address, size)) { if (check_32bit_address_range_in_program(bct0->stage2_load_address, size)) {
tmp_addr = 0x80000000u; tmp_addr = 0x80000000u;
} else { } else {
tmp_addr = config.load_address; tmp_addr = bct0->stage2_load_address;
} }
/* Try to read stage2. */ /* Try to read stage2. */
if (read_from_file((void *)tmp_addr, size, config.path) != size) { if (read_from_file((void *)tmp_addr, size, bct0->stage2_path) != size) {
fatal_error("Failed to read stage2 (%s)!\n", config.path); fatal_error("Failed to read stage2 (%s)!\n", bct0->stage2_path);
} }
g_chainloader_num_entries = 1; g_chainloader_num_entries = 1;
g_chainloader_entries[0].load_address = config.load_address; g_chainloader_entries[0].load_address = bct0->stage2_load_address;
g_chainloader_entries[0].src_address = tmp_addr; g_chainloader_entries[0].src_address = tmp_addr;
g_chainloader_entries[0].size = size; g_chainloader_entries[0].size = size;
g_chainloader_entries[0].num = 0; g_chainloader_entries[0].num = 0;
g_chainloader_entrypoint = config.entrypoint; g_chainloader_entrypoint = bct0->stage2_entrypoint;
strncpy(g_stage2_path, config.path, sizeof(g_stage2_path) - 1);
g_stage2_path[sizeof(g_stage2_path) - 1] = '\0';
} }

View File

@ -26,25 +26,13 @@
#include "lib/ini.h" #include "lib/ini.h"
#include "lib/fatfs/ff.h" #include "lib/fatfs/ff.h"
#include "bct0.h"
/* TODO: Is there a more concise way to do this? */ /* TODO: Is there a more concise way to do this? */
#define STAGE2_ARGV_PROGRAM_PATH 0 #define STAGE2_ARGV_PROGRAM_PATH 0
#define STAGE2_ARGV_ARGUMENT_STRUCT 1 #define STAGE2_ARGV_ARGUMENT_STRUCT 1
#define STAGE2_ARGC 2 #define STAGE2_ARGC 2
#define STAGE2_NAME_KEY "stage2_path"
#define STAGE2_MTC_NAME_KEY "stage2_mtc_path"
#define STAGE2_ADDRESS_KEY "stage2_addr"
#define STAGE2_ENTRYPOINT_KEY "stage2_entrypoint"
#define BCTO_MAX_SIZE 0x5800
typedef struct {
char path[0x100];
char mtc_path[0x100];
uintptr_t load_address;
uintptr_t entrypoint;
} stage2_config_t;
typedef struct { typedef struct {
uint32_t version; uint32_t version;
ScreenLogLevel log_level; ScreenLogLevel log_level;
@ -55,7 +43,8 @@ typedef struct {
ScreenLogLevel log_level; ScreenLogLevel log_level;
} stage2_mtc_args_t; } stage2_mtc_args_t;
const char *stage2_get_program_path(void); bool stage2_run_mtc(const bct0_t *bct0);
void load_stage2(const char *bct0); void stage2_validate_config(const bct0_t *bct0);
void stage2_load(const bct0_t *bct0);
#endif #endif

View File

@ -17,7 +17,6 @@
#include <stdbool.h> #include <stdbool.h>
#include <stdarg.h> #include <stdarg.h>
#include "utils.h" #include "utils.h"
#include "di.h"
#include "se.h" #include "se.h"
#include "fuse.h" #include "fuse.h"
#include "pmc.h" #include "pmc.h"
@ -27,7 +26,6 @@
#include "btn.h" #include "btn.h"
#include "lib/log.h" #include "lib/log.h"
#include "lib/vsprintf.h" #include "lib/vsprintf.h"
#include "display/video_fb.h"
#include <inttypes.h> #include <inttypes.h>
@ -99,21 +97,8 @@ __attribute__ ((noreturn)) void generic_panic(void) {
} }
__attribute__((noreturn)) void fatal_error(const char *fmt, ...) { __attribute__((noreturn)) void fatal_error(const char *fmt, ...) {
/* Forcefully initialize the screen if logging is disabled. */ /* Forcefully initialize the screen if not already initialized. */
if (log_get_log_level() == SCREEN_LOG_LEVEL_NONE) { log_setup_display();
/* Zero-fill the framebuffer and register it as printk provider. */
video_init((void *)0xC0000000);
/* Initialize the display. */
display_init();
/* Set the framebuffer. */
display_init_framebuffer((void *)0xC0000000);
/* Turn on the backlight after initializing the lfb */
/* to avoid flickering. */
display_backlight(true);
}
/* Override the global logging level. */ /* Override the global logging level. */
log_set_log_level(SCREEN_LOG_LEVEL_ERROR); log_set_log_level(SCREEN_LOG_LEVEL_ERROR);

View File

@ -22,6 +22,8 @@
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
#ifndef BIT
#define BIT(n) (1u << (n)) #define BIT(n) (1u << (n))
#define BITL(n) (1ull << (n)) #define BITL(n) (1ull << (n))
#define MASK(n) (BIT(n) - 1) #define MASK(n) (BIT(n) - 1)
@ -29,6 +31,8 @@
#define MASK2(a,b) (MASK(a) & ~MASK(b)) #define MASK2(a,b) (MASK(a) & ~MASK(b))
#define MASK2L(a,b) (MASKL(a) & ~MASKL(b)) #define MASK2L(a,b) (MASKL(a) & ~MASKL(b))
#endif
#define MAKE_REG32(a) (*(volatile uint32_t *)(a)) #define MAKE_REG32(a) (*(volatile uint32_t *)(a))
#define ALIGN(m) __attribute__((aligned(m))) #define ALIGN(m) __attribute__((aligned(m)))
@ -108,12 +112,13 @@ static inline bool overlaps_a(const void *as, const void *ae, const void *bs, co
static inline bool check_32bit_address_range_in_program(uintptr_t addr, size_t size) { static inline bool check_32bit_address_range_in_program(uintptr_t addr, size_t size) {
extern uint8_t __chainloader_start__[], __chainloader_end__[]; extern uint8_t __chainloader_start__[], __chainloader_end__[];
extern uint8_t __stack_bottom__[], __stack_top__[]; extern uint8_t __stack_bottom__[], __stack_top__[];
extern uint8_t __dram_start__[], __dram_end__[];
extern uint8_t __start__[], __end__[]; extern uint8_t __start__[], __end__[];
uint8_t *start = (uint8_t *)addr, *end = start + size; uint8_t *start = (uint8_t *)addr, *end = start + size;
return overlaps_a(start, end, __chainloader_start__, __chainloader_end__) || return overlaps_a(start, end, __chainloader_start__, __chainloader_end__) ||
overlaps_a(start, end, __stack_bottom__, __stack_top__) || overlaps_a(start, end, __stack_bottom__, __stack_top__) ||
overlaps_a(start, end, (void *)0xC0000000, (void *)0xC03C0000) || /* framebuffer */ overlaps_a(start, end, __dram_start__, __dram_end__) ||
overlaps_a(start, end, __start__, __end__); overlaps_a(start, end, __start__, __end__);
} }

View File

@ -216,7 +216,7 @@ sept_primary.bin.o sept_primary_bin.h: sept-primary.bin
@echo $(notdir $<) @echo $(notdir $<)
@$(_bin2o) @$(_bin2o)
sept_secondary_00.enc.o sept_secondary_00.h: sept-secondary_00.enc sept_secondary_00.enc.o sept_secondary_00_enc.h: sept-secondary_00.enc
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
@echo $(notdir $<) @echo $(notdir $<)
@$(_bin2o) @$(_bin2o)

View File

@ -63,3 +63,4 @@
/* Unofficial. */ /* Unofficial. */
#include <vapours/results/exosphere_results.hpp> #include <vapours/results/exosphere_results.hpp>
#include <vapours/results/xusb_gadget_results.hpp>

View File

@ -0,0 +1,47 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vapours/results/results_common.hpp>
namespace ams::xusb {
/* Please note: These results are all custom, and not official. */
R_DEFINE_NAMESPACE_RESULT_MODULE(445);
/* Result 1-1000 reserved for Atmosphere. */
/* USB protocol-level results. */
R_DEFINE_ERROR_RESULT(InvalidDeviceState, 1);
R_DEFINE_ERROR_RESULT(MalformedSetupRequest, 2);
R_DEFINE_ERROR_RESULT(UnknownSetupRequest, 3);
R_DEFINE_ERROR_RESULT(UnknownDescriptorType, 4);
R_DEFINE_ERROR_RESULT(InvalidDescriptorIndex, 5);
R_DEFINE_ERROR_RESULT(InvalidAddress, 6);
R_DEFINE_ERROR_RESULT(ControlEndpointBusy, 7);
R_DEFINE_ERROR_RESULT(InvalidSetupPacketSequenceNumber, 8);
R_DEFINE_ERROR_RESULT(InvalidControlEndpointState, 9);
R_DEFINE_ERROR_RESULT(InvalidConfiguration, 10);
R_DEFINE_ERROR_RESULT(TransferRingFull, 11);
/* Gadget-level results. */
R_DEFINE_ERROR_RESULT(UnexpectedCompletionCode, 101);
R_DEFINE_ERROR_RESULT(UnexpectedEndpoint, 102);
R_DEFINE_ERROR_RESULT(UnexpectedTRB, 103);
R_DEFINE_ERROR_RESULT(DownloadTooLarge, 104);
}

View File

@ -123,15 +123,24 @@ check_rebootstub:
check_key_derivation: check_key_derivation:
@$(MAKE) -C key_derivation @$(MAKE) -C key_derivation
$(BUILD): check_rebootstub check_key_derivation
ifeq ($(strip $(SEPT_00_ENC_PATH)),) ifeq ($(strip $(SEPT_00_ENC_PATH)),)
$(BUILD): check_rebootstub check_key_derivation
@[ -d $@ ] || mkdir -p $@ @[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
else else
$(BUILD): $(TOPDIR)/$(TARGET)_00.enc $(TOPDIR)/$(TARGET)_01.enc $(TOPDIR)/$(TARGET)_dev_00.enc $(TOPDIR)/$(TARGET)_dev_01.enc
@touch $(TOPDIR)/$(TARGET).bin @touch $(TOPDIR)/$(TARGET).bin
$(TOPDIR)/$(TARGET)_00.enc: $(SEPT_00_ENC_PATH)
@cp $(SEPT_00_ENC_PATH) $(TOPDIR)/$(TARGET)_00.enc @cp $(SEPT_00_ENC_PATH) $(TOPDIR)/$(TARGET)_00.enc
$(TOPDIR)/$(TARGET)_01.enc: $(SEPT_01_ENC_PATH)
@cp $(SEPT_01_ENC_PATH) $(TOPDIR)/$(TARGET)_01.enc @cp $(SEPT_01_ENC_PATH) $(TOPDIR)/$(TARGET)_01.enc
$(TOPDIR)/$(TARGET)_dev_00.enc: $(SEPT_DEV_00_ENC_PATH)
@cp $(SEPT_DEV_00_ENC_PATH) $(TOPDIR)/$(TARGET)_dev_00.enc @cp $(SEPT_DEV_00_ENC_PATH) $(TOPDIR)/$(TARGET)_dev_00.enc
$(TOPDIR)/$(TARGET)_dev_01.enc: $(SEPT_DEV_01_ENC_PATH)
@cp $(SEPT_DEV_01_ENC_PATH) $(TOPDIR)/$(TARGET)_dev_01.enc @cp $(SEPT_DEV_01_ENC_PATH) $(TOPDIR)/$(TARGET)_dev_01.enc
endif endif

View File

@ -24,16 +24,6 @@ SFILES := $(call FIND_SOURCE_FILES,$(SOURCES),s)
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) fusee-primary.bin BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) fusee-primary.bin
#---------------------------------------------------------------------------------
# boot has a custom bin2o rule for fusee-primary -> fusee_primary
#---------------------------------------------------------------------------------
define _bin2o
bin2s $< | $(AS) -o $(@)
echo "extern const u8" `(echo $(<F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _ | tr - _)`"_end[];" > `(echo $(<F) | tr . _ | tr - _)`.h
echo "extern const u8" `(echo $(<F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _ | tr - _)`"[];" >> `(echo $(<F) | tr . _ | tr - _)`.h
echo "extern const u32" `(echo $(<F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _ | tr - _)`_size";" >> `(echo $(<F) | tr . _ | tr - _)`.h
endef
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C # use CXX for linking C++ projects, CC for standard C
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
@ -106,14 +96,23 @@ $(OUTPUT).kip : $(OUTPUT).elf
$(OUTPUT).elf : $(OFILES) $(OUTPUT).elf : $(OFILES)
boot_power_utils.o: fusee_primary.bin.o fusee_primary_bin.h boot_power_utils.o: fusee-primary.bin.o fusee_primary_bin.h
#---------------------------------------------------------------------------------
# boot has a custom bin2o rule for fusee-primary -> fusee_primary
#---------------------------------------------------------------------------------
define _bin2o
bin2s $< | $(AS) -o $(@)
echo "extern const u8" `(echo $(<F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _ | tr - _)`"_end[];" > `(echo $(<F) | tr . _ | tr - _)`.h
echo "extern const u8" `(echo $(<F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _ | tr - _)`"[];" >> `(echo $(<F) | tr . _ | tr - _)`.h
echo "extern const u32" `(echo $(<F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _ | tr - _)`_size";" >> `(echo $(<F) | tr . _ | tr - _)`.h
endef
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data # you need a rule like this for each extension you use as binary data
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
fusee_primary.bin.o fusee_primary_bin.h: fusee-primary.bin fusee-primary.bin.o fusee_primary_bin.h: fusee-primary.bin
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(_bin2o) @$(_bin2o)
%.bin.o : %.bin %.bin.o : %.bin

View File

@ -16,7 +16,7 @@
#include <stratosphere.hpp> #include <stratosphere.hpp>
#include "boot_power_utils.hpp" #include "boot_power_utils.hpp"
#include "boot_pmic_driver.hpp" #include "boot_pmic_driver.hpp"
#include "fusee-primary_bin.h" #include "fusee_primary_bin.h"
namespace ams::boot { namespace ams::boot {