From 190fed22e295945606652ec70d75e7bbe8bf9f95 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Fri, 16 Oct 2020 20:18:11 -0700 Subject: [PATCH 01/14] build: fix some broken dependencies in Makefiles that were causing targets to get rebuild when they did not need to be rebuilt --- Makefile | 4 +-- exosphere/Makefile | 9 +++++-- fusee/fusee-secondary/Makefile | 2 +- sept/sept-secondary/Makefile | 11 +++++++- stratosphere/boot/Makefile | 25 +++++++++---------- stratosphere/boot/source/boot_power_utils.cpp | 2 +- 6 files changed, 33 insertions(+), 20 deletions(-) diff --git a/Makefile b/Makefile index eb4886941..38848b5f9 100644 --- a/Makefile +++ b/Makefile @@ -73,7 +73,7 @@ dist-no-debug: all cp fusee/fusee-secondary/fusee-secondary-experimental.bin atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin cp fusee/fusee-secondary/fusee-secondary-experimental.bin atmosphere-$(AMSVER)/sept/payload.bin cp sept/sept-primary/sept-primary.bin atmosphere-$(AMSVER)/sept/sept-primary.bin - cp sept/sept-secondary/sept-secondary.bin atmosphere-$(AMSVER)/sept/sept-secondary.bin + cp sept/sept-secondary/sept-secondary.bin atmosphere-$(AMSVER)/sept/sept-secondary.bin || true cp sept/sept-secondary/sept-secondary_00.enc atmosphere-$(AMSVER)/sept/sept-secondary_00.enc cp sept/sept-secondary/sept-secondary_01.enc atmosphere-$(AMSVER)/sept/sept-secondary_01.enc cp sept/sept-secondary/sept-secondary_dev_00.enc atmosphere-$(AMSVER)/sept/sept-secondary_dev_00.enc @@ -126,7 +126,7 @@ dist: dist-no-debug 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 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 exosphere/loader_stub/loader_stub.elf atmosphere-$(AMSVER)-debug/exosphere-loader-stub.elf cp exosphere/program/program.elf atmosphere-$(AMSVER)-debug/exosphere-program.elf diff --git a/exosphere/Makefile b/exosphere/Makefile index 6ce912754..9884554f3 100644 --- a/exosphere/Makefile +++ b/exosphere/Makefile @@ -5,14 +5,17 @@ define ATMOSPHERE_ADD_TARGET ATMOSPHERE_BUILD_CONFIGS += $(strip $1) -$(strip $1): exosphere$(strip $2).bin check_warmboot_$(strip $1) - @cp warmboot/warmboot$(strip $2).bin warmboot$(strip $2).bin +$(strip $1): exosphere$(strip $2).bin warmboot$(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 @printf LENY >> 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): @$$(MAKE) -C program $(strip $1) @@ -22,6 +25,8 @@ check_warmboot_$(strip $1): loader_stub/loader_stub$(strip $2).bin: check_program_$(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) @rm -rf exosphere$(strip $2).bin warmboot$(strip $2).bin diff --git a/fusee/fusee-secondary/Makefile b/fusee/fusee-secondary/Makefile index 62520cc2c..ffe4b323f 100644 --- a/fusee/fusee-secondary/Makefile +++ b/fusee/fusee-secondary/Makefile @@ -216,7 +216,7 @@ sept_primary.bin.o sept_primary_bin.h: sept-primary.bin @echo $(notdir $<) @$(_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 $<) @$(_bin2o) diff --git a/sept/sept-secondary/Makefile b/sept/sept-secondary/Makefile index 93624f79e..7eade86fd 100644 --- a/sept/sept-secondary/Makefile +++ b/sept/sept-secondary/Makefile @@ -123,15 +123,24 @@ check_rebootstub: check_key_derivation: @$(MAKE) -C key_derivation -$(BUILD): check_rebootstub check_key_derivation ifeq ($(strip $(SEPT_00_ENC_PATH)),) +$(BUILD): check_rebootstub check_key_derivation @[ -d $@ ] || mkdir -p $@ @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile else +$(BUILD): $(TOPDIR)/$(TARGET)_00.enc $(TOPDIR)/$(TARGET)_01.enc $(TOPDIR)/$(TARGET)_dev_00.enc $(TOPDIR)/$(TARGET)_dev_01.enc @touch $(TOPDIR)/$(TARGET).bin + +$(TOPDIR)/$(TARGET)_00.enc: $(SEPT_00_ENC_PATH) @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 + +$(TOPDIR)/$(TARGET)_dev_00.enc: $(SEPT_DEV_00_ENC_PATH) @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 endif diff --git a/stratosphere/boot/Makefile b/stratosphere/boot/Makefile index 40b971879..471a79260 100644 --- a/stratosphere/boot/Makefile +++ b/stratosphere/boot/Makefile @@ -24,16 +24,6 @@ SFILES := $(call FIND_SOURCE_FILES,$(SOURCES),s) 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 $( `(echo $(> `(echo $(> `(echo $( fusee_primary +#--------------------------------------------------------------------------------- +define _bin2o + bin2s $< | $(AS) -o $(@) + echo "extern const u8" `(echo $( `(echo $(> `(echo $(> `(echo $( #include "boot_power_utils.hpp" #include "boot_pmic_driver.hpp" -#include "fusee-primary_bin.h" +#include "fusee_primary_bin.h" namespace ams::boot { From f98ce0c90924237ff363a02e9680db5a0826b638 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sun, 18 Oct 2020 14:54:00 -0700 Subject: [PATCH 02/14] fusee-primary: log to UART-B --- fusee/fusee-primary/src/hwinit.c | 14 +++++++------- fusee/fusee-primary/src/lib/log.c | 5 +++-- fusee/fusee-primary/src/lib/log.h | 3 +-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/fusee/fusee-primary/src/hwinit.c b/fusee/fusee-primary/src/hwinit.c index 44b7d9456..a0632647a 100644 --- a/fusee/fusee-primary/src/hwinit.c +++ b/fusee/fusee-primary/src/hwinit.c @@ -65,9 +65,9 @@ void config_gpios() pinmux->uart3_tx = 0; pinmux->pe6 = PINMUX_INPUT; pinmux->ph6 = PINMUX_INPUT; - - gpio_configure_mode(TEGRA_GPIO(G, 0), GPIO_MODE_GPIO); - gpio_configure_mode(TEGRA_GPIO(D, 1), GPIO_MODE_GPIO); + + gpio_configure_mode(TEGRA_GPIO(G, 0), GPIO_MODE_SFIO); + 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(H, 6), GPIO_MODE_GPIO); gpio_configure_direction(TEGRA_GPIO(G, 0), GPIO_DIRECTION_INPUT); @@ -78,6 +78,7 @@ void config_gpios() i2c_config(I2C_1); i2c_config(I2C_5); uart_config(UART_A); + uart_config(UART_B); /* Configure volume up/down as inputs. */ gpio_configure_mode(GPIO_BUTTON_VOL_UP, GPIO_MODE_GPIO); @@ -213,10 +214,9 @@ void nx_hwinit() config_gpios(); /* Uncomment for UART debugging. */ - /* - clkrst_reboot(CARDEVICE_UARTC); - uart_init(UART_C, 115200); - */ + + clkrst_reboot(CARDEVICE_UARTB); + uart_init(UART_B, 115200); /* Reboot CL-DVFS. */ clkrst_reboot(CARDEVICE_CL_DVFS); diff --git a/fusee/fusee-primary/src/lib/log.c b/fusee/fusee-primary/src/lib/log.c index eb6734da7..26e0cb8a3 100644 --- a/fusee/fusee-primary/src/lib/log.c +++ b/fusee/fusee-primary/src/lib/log.c @@ -17,6 +17,7 @@ #include "log.h" #include "../display/video_fb.h" +#include "../uart.h" #include "vsprintf.h" /* default log level for screen output */ @@ -31,7 +32,7 @@ ScreenLogLevel log_get_log_level() { } 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) { @@ -124,4 +125,4 @@ void print(ScreenLogLevel screen_log_level, const char * fmt, ...) log_to_uart(message); print_to_screen(screen_log_level, message); -} \ No newline at end of file +} diff --git a/fusee/fusee-primary/src/lib/log.h b/fusee/fusee-primary/src/lib/log.h index d1c5777f3..eea293e33 100644 --- a/fusee/fusee-primary/src/lib/log.h +++ b/fusee/fusee-primary/src/lib/log.h @@ -36,8 +36,7 @@ extern ScreenLogLevel g_screen_log_level; void log_set_log_level(ScreenLogLevel screen_log_level); ScreenLogLevel log_get_log_level(); -void log_to_uart(const char *message); void vprint(ScreenLogLevel screen_log_level, const char *fmt, va_list args); void print(ScreenLogLevel screen_log_level, const char* fmt, ...); -#endif \ No newline at end of file +#endif From 4499c4392d771b12657082844c335c4272b858ee Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sun, 18 Oct 2020 14:59:53 -0700 Subject: [PATCH 03/14] fusee-primary: add reference counting to AHB redirect The SDMMC driver is currently the only user of the AHB redirect, but the upcoming XUSB driver will also need to use the AHB redirect, potentially at the same time. This ensures that the AHB redirect will not be disabled unexpectedly if one driver is deinitialized without the other. --- fusee/fusee-primary/src/fs_utils.c | 11 ++--------- fusee/fusee-primary/src/mc.c | 29 ++++++++++++++++++++++------- fusee/fusee-primary/src/mc.h | 4 ++-- 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/fusee/fusee-primary/src/fs_utils.c b/fusee/fusee-primary/src/fs_utils.c index da561a266..ff5a18bb5 100644 --- a/fusee/fusee-primary/src/fs_utils.c +++ b/fusee/fusee-primary/src/fs_utils.c @@ -22,7 +22,6 @@ FATFS sd_fs; static bool g_sd_mounted = false; static bool g_sd_initialized = false; -static bool g_ahb_redirect_enabled = false; sdmmc_t g_sd_sdmmc; sdmmc_device_t g_sd_device; @@ -34,10 +33,7 @@ bool mount_sd(void) return true; /* Enable AHB redirection if necessary. */ - if (!g_ahb_redirect_enabled) { - mc_enable_ahb_redirect(); - g_ahb_redirect_enabled = true; - } + mc_acquire_ahb_redirect(); if (!g_sd_initialized) { /* Initialize SD. */ @@ -68,10 +64,7 @@ void unmount_sd(void) } /* Disable AHB redirection if necessary. */ - if (g_ahb_redirect_enabled) { - mc_disable_ahb_redirect(); - g_ahb_redirect_enabled = false; - } + mc_release_ahb_redirect(); } uint32_t get_file_size(const char *filename) diff --git a/fusee/fusee-primary/src/mc.c b/fusee/fusee-primary/src/mc.c index 35048d98e..b88cb1a5c 100644 --- a/fusee/fusee-primary/src/mc.c +++ b/fusee/fusee-primary/src/mc.c @@ -124,16 +124,21 @@ void mc_config_carveout_finalize() MAKE_MC_REG(MC_SECURITY_CARVEOUT2_CFG0) = 0x440167E; } -void mc_enable_ahb_redirect() +static int mc_ahb_redirect_users = 0; + +void mc_acquire_ahb_redirect() { - volatile tegra_car_t *car = car_get_regs(); - car->lvl2_clk_gate_ovrd = ((car->lvl2_clk_gate_ovrd & 0xFFF7FFFF) | 0x80000); + 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; + 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(); @@ -141,6 +146,16 @@ void mc_disable_ahb_redirect() MAKE_MC_REG(MC_IRAM_TOM) = 0; 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() @@ -166,4 +181,4 @@ void mc_enable() udelay(5); mc_disable_ahb_redirect(); -} \ No newline at end of file +} diff --git a/fusee/fusee-primary/src/mc.h b/fusee/fusee-primary/src/mc.h index 63a263a59..b1e2a2651 100644 --- a/fusee/fusee-primary/src/mc.h +++ b/fusee/fusee-primary/src/mc.h @@ -598,8 +598,8 @@ typedef enum { void mc_config_tsec_carveout(uint32_t bom, uint32_t size1mb, bool lock); void mc_config_carveout(); void mc_config_carveout_finalize(); -void mc_enable_ahb_redirect(); -void mc_disable_ahb_redirect(); +void mc_acquire_ahb_redirect(); +void mc_release_ahb_redirect(); void mc_enable(); #endif \ No newline at end of file From c00c30c75175d018e2bb05f6cb4f7ed086124e5b Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sun, 18 Oct 2020 15:26:09 -0700 Subject: [PATCH 04/14] fusee-primary: move BCT0 buffer to dram to save on iram Add dram section to link script, and also creates a framebuffer section so we can start to use the link script as a single source of truth for how fusee-primary uses dram. --- fusee/fusee-primary/linker.ld | 11 +++++++++++ fusee/fusee-primary/src/hwinit.c | 5 +++++ fusee/fusee-primary/src/main.c | 6 ++---- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/fusee/fusee-primary/linker.ld b/fusee/fusee-primary/linker.ld index b442fd3b6..dfbf30d42 100644 --- a/fusee/fusee-primary/linker.ld +++ b/fusee/fusee-primary/linker.ld @@ -15,6 +15,7 @@ MEMORY NULL : ORIGIN = 0x00000000, LENGTH = 0x1000 main : ORIGIN = 0x40010000, LENGTH = 0x20000 low_iram : ORIGIN = 0x40003000, LENGTH = 0x8000 + dram : ORIGIN = 0xC0000000, LENGTH = 0x40000000 } SECTIONS @@ -150,6 +151,16 @@ SECTIONS } >main :NONE __end__ = ABSOLUTE(.) ; + .dram (NOLOAD) : + { + . = ALIGN(32); + PROVIDE (__dram_start__ = ABSOLUTE(.)); + *(.framebuffer) + *(.dram) + . = ALIGN(32); + PROVIDE (__dram_end__ = ABSOLUTE(.)); + } >dram :NONE + /* ================== ==== Metadata ==== ================== */ diff --git a/fusee/fusee-primary/src/hwinit.c b/fusee/fusee-primary/src/hwinit.c index a0632647a..dfc299244 100644 --- a/fusee/fusee-primary/src/hwinit.c +++ b/fusee/fusee-primary/src/hwinit.c @@ -179,6 +179,8 @@ void config_se_brom() pmc->reset_status = 0; } +extern uint8_t __dram_start__[], __dram_end__[]; + void nx_hwinit() { volatile tegra_pmc_t *pmc = pmc_get_regs(); @@ -291,6 +293,9 @@ void nx_hwinit() /* Initialize SDRAM. */ sdram_init(); + + /* Zero-fill the .dram section */ + memset(__dram_start__, 0, __dram_end__ - __dram_start__); /* Save SDRAM LP0 parameters. */ sdram_lp0_save_params(sdram_get_params()); diff --git a/fusee/fusee-primary/src/main.c b/fusee/fusee-primary/src/main.c index 3e3808209..d204885d2 100644 --- a/fusee/fusee-primary/src/main.c +++ b/fusee/fusee-primary/src/main.c @@ -32,8 +32,8 @@ extern void (*__program_exit_callback)(int rc); -static void *g_framebuffer; -static char g_bct0_buffer[BCTO_MAX_SIZE]; +static uint32_t g_framebuffer[1280*768] __attribute__((section(".framebuffer"))) = {0}; +static char g_bct0_buffer[BCTO_MAX_SIZE] __attribute__((section(".dram"))) = {0}; #define CONFIG_LOG_LEVEL_KEY "log_level" @@ -91,8 +91,6 @@ static int config_ini_handler(void *user, const char *section, const char *name, } static void setup_display(void) { - g_framebuffer = (void *)0xC0000000; - /* Zero-fill the framebuffer and register it as printk provider. */ video_init(g_framebuffer); From 45b170084e0cd6d3187d621ff1effc3092abf546 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sun, 18 Oct 2020 16:37:41 -0700 Subject: [PATCH 05/14] fusee-primary: refactor BCT0 parsing BCT0 is now only parsed once into a struct this is shared between log level logic and stage2 logic. This has been done in anticipation of needing config items for fastboot gadget. --- fusee/fusee-primary/src/bct0.c | 81 ++++++++++++++++++++++++++++++ fusee/fusee-primary/src/bct0.h | 40 +++++++++++++++ fusee/fusee-primary/src/main.c | 51 ++++++------------- fusee/fusee-primary/src/stage2.c | 86 ++++++++------------------------ fusee/fusee-primary/src/stage2.h | 21 ++------ 5 files changed, 161 insertions(+), 118 deletions(-) create mode 100644 fusee/fusee-primary/src/bct0.c create mode 100644 fusee/fusee-primary/src/bct0.h diff --git a/fusee/fusee-primary/src/bct0.c b/fusee/fusee-primary/src/bct0.c new file mode 100644 index 000000000..523071685 --- /dev/null +++ b/fusee/fusee-primary/src/bct0.c @@ -0,0 +1,81 @@ +/* + * 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 . + */ + +#include "bct0.h" + +#include "lib/ini.h" + +#include + +#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 CONFIG_LOG_LEVEL_KEY "log_level" + +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 { + 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; + + return ini_parse_string(ini, bct0_ini_handler, out); +} diff --git a/fusee/fusee-primary/src/bct0.h b/fusee/fusee-primary/src/bct0.h new file mode 100644 index 000000000..ebb86e2ee --- /dev/null +++ b/fusee/fusee-primary/src/bct0.h @@ -0,0 +1,40 @@ +/* + * 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 . + */ + +#ifndef FUSEE_BCT0_H +#define FUSEE_BCT0_H + +#include +#include + +#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; +} bct0_t; + +int bct0_parse(const char *ini, bct0_t *out); + +#endif diff --git a/fusee/fusee-primary/src/main.c b/fusee/fusee-primary/src/main.c index d204885d2..503256187 100644 --- a/fusee/fusee-primary/src/main.c +++ b/fusee/fusee-primary/src/main.c @@ -27,7 +27,6 @@ #include "lib/fatfs/ff.h" #include "lib/log.h" #include "lib/vsprintf.h" -#include "lib/ini.h" #include "display/video_fb.h" extern void (*__program_exit_callback)(int rc); @@ -35,8 +34,6 @@ extern void (*__program_exit_callback)(int rc); static uint32_t g_framebuffer[1280*768] __attribute__((section(".framebuffer"))) = {0}; static char g_bct0_buffer[BCTO_MAX_SIZE] __attribute__((section(".dram"))) = {0}; -#define CONFIG_LOG_LEVEL_KEY "log_level" - #define DEFAULT_BCT0 \ "BCT0\n"\ "[stage1]\n"\ @@ -74,22 +71,6 @@ static const char *load_config(void) { 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) { /* Zero-fill the framebuffer and register it as printk provider. */ video_init(g_framebuffer); @@ -134,12 +115,11 @@ static void exit_callback(int rc) { relocate_and_chainload(); } -int main(void) { - const char *bct0; - const char *stage2_path; +int main(void) { + const char *bct0_string; stage2_args_t *stage2_args; uint32_t stage2_version = 0; - ScreenLogLevel log_level = SCREEN_LOG_LEVEL_NONE; + bct0_t bct0; /* Initialize the boot environment. */ setup_env(); @@ -148,17 +128,17 @@ int main(void) { check_and_display_panic(); /* Load the BCT0 configuration ini off of the SD. */ - bct0 = load_config(); + bct0_string = load_config(); - /* Extract the logging level from the BCT.ini file. */ - if (ini_parse_string(bct0, config_ini_handler, &log_level) < 0) { + /* 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(log_level); + log_set_log_level(bct0.log_level); - if (log_level != SCREEN_LOG_LEVEL_NONE) { + if (bct0.log_level != SCREEN_LOG_LEVEL_NONE) { /* Initialize the display for debugging. */ setup_display(); } @@ -168,21 +148,20 @@ int main(void) { print(SCREEN_LOG_LEVEL_DEBUG, "Using color linear framebuffer at 0x%p!\n", g_framebuffer); /* Load the loader payload into DRAM. */ - load_stage2(bct0); + load_stage2(&bct0); /* Setup argument data. */ - stage2_path = stage2_get_program_path(); - strcpy(g_chainloader_arg_data, stage2_path); - stage2_args = (stage2_args_t *)(g_chainloader_arg_data + strlen(stage2_path) + 1); /* May be unaligned. */ + strcpy(g_chainloader_arg_data, bct0.stage2_path); + stage2_args = (stage2_args_t *)(g_chainloader_arg_data + strlen(bct0.stage2_path) + 1); /* May be unaligned. */ memcpy(&stage2_args->version, &stage2_version, 4); - memcpy(&stage2_args->log_level, &log_level, sizeof(log_level)); - strcpy(stage2_args->bct0, bct0); + memcpy(&stage2_args->log_level, &bct0.log_level, sizeof(bct0.log_level)); + strcpy(stage2_args->bct0, bct0_string); g_chainloader_argc = 2; /* Terminate the boot environment. */ cleanup_env(); - if (log_level != SCREEN_LOG_LEVEL_NONE) { + if (bct0.log_level != SCREEN_LOG_LEVEL_NONE) { /* Wait a while for debugging. */ mdelay(1000); @@ -193,4 +172,4 @@ int main(void) { /* Finally, after the cleanup routines (__libc_fini_array, etc.) are called, jump to Stage2. */ __program_exit_callback = exit_callback; return 0; -} \ No newline at end of file +} diff --git a/fusee/fusee-primary/src/stage2.c b/fusee/fusee-primary/src/stage2.c index 150fcb310..12a6e10d1 100644 --- a/fusee/fusee-primary/src/stage2.c +++ b/fusee/fusee-primary/src/stage2.c @@ -19,42 +19,6 @@ #include "fs_utils.h" #include "utils.h" -char g_stage2_path[0x100] = {0}; - -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; size_t size; @@ -91,45 +55,40 @@ static bool run_mtc(const char *mtc_path, uintptr_t mtc_address) { return mtc_res; } -void load_stage2(const char *bct0) { - stage2_config_t config = {0}; +void load_stage2(const bct0_t *bct0) { 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') { + if (bct0->stage2_load_address == 0 || bct0->stage2_path[0] == '\x00') { 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"); } - if (!check_32bit_address_loadable(config.entrypoint)) { + if (!check_32bit_address_loadable(bct0->stage2_entrypoint)) { 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"); } 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, " MTC File Path: %s\n", config.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, " Entrypoint: 0x%p\n", config.entrypoint); + 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", bct0->stage2_mtc_path); + 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", bct0->stage2_entrypoint); /* Run the MTC binary. */ - if (!run_mtc(config.mtc_path, config.load_address)) { + if (!run_mtc(bct0->stage2_mtc_path, bct0->stage2_load_address)) { print(SCREEN_LOG_LEVEL_WARNING, "DRAM training failed! Continuing with untrained DRAM.\n"); } - if (f_stat(config.path, &info) != FR_OK) { - fatal_error("Failed to stat stage2 (%s)!\n", config.path); + if (f_stat(bct0->stage2_path, &info) != FR_OK) { + fatal_error("Failed to stat stage2 (%s)!\n", bct0->stage2_path); } size = (size_t)info.fsize; @@ -139,32 +98,29 @@ void load_stage2(const char *bct0) { fatal_error("Stage2 is way too big!\n"); } - if (!check_32bit_address_range_loadable(config.load_address, size)) { - fatal_error("Stage2 has an invalid load address & size combination (0x%08x 0x%08x)!\n", 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", 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"); } - 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; } else { - tmp_addr = config.load_address; + tmp_addr = bct0->stage2_load_address; } /* Try to read stage2. */ - if (read_from_file((void *)tmp_addr, size, config.path) != size) { - fatal_error("Failed to read stage2 (%s)!\n", config.path); + if (read_from_file((void *)tmp_addr, size, bct0->stage2_path) != size) { + fatal_error("Failed to read stage2 (%s)!\n", bct0->stage2_path); } 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].size = size; g_chainloader_entries[0].num = 0; - g_chainloader_entrypoint = config.entrypoint; - - strncpy(g_stage2_path, config.path, sizeof(g_stage2_path) - 1); - g_stage2_path[sizeof(g_stage2_path) - 1] = '\0'; + g_chainloader_entrypoint = bct0->stage2_entrypoint; } diff --git a/fusee/fusee-primary/src/stage2.h b/fusee/fusee-primary/src/stage2.h index 27a399e44..f9d0dfdea 100644 --- a/fusee/fusee-primary/src/stage2.h +++ b/fusee/fusee-primary/src/stage2.h @@ -26,25 +26,13 @@ #include "lib/ini.h" #include "lib/fatfs/ff.h" +#include "bct0.h" + /* TODO: Is there a more concise way to do this? */ #define STAGE2_ARGV_PROGRAM_PATH 0 #define STAGE2_ARGV_ARGUMENT_STRUCT 1 #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 { uint32_t version; ScreenLogLevel log_level; @@ -55,7 +43,6 @@ typedef struct { ScreenLogLevel log_level; } stage2_mtc_args_t; -const char *stage2_get_program_path(void); -void load_stage2(const char *bct0); +void load_stage2(const bct0_t *bct0); -#endif \ No newline at end of file +#endif From 20dc027a2335d352f5a5c5265de713246120236b Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sun, 18 Oct 2020 16:48:44 -0700 Subject: [PATCH 06/14] fusee-primary: split stage2 handling into several functions --- fusee/fusee-primary/src/main.c | 10 +++++++++- fusee/fusee-primary/src/stage2.c | 27 ++++++++++++--------------- fusee/fusee-primary/src/stage2.h | 4 +++- 3 files changed, 24 insertions(+), 17 deletions(-) diff --git a/fusee/fusee-primary/src/main.c b/fusee/fusee-primary/src/main.c index 503256187..ee983c66c 100644 --- a/fusee/fusee-primary/src/main.c +++ b/fusee/fusee-primary/src/main.c @@ -147,8 +147,16 @@ int main(void) { 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); + /* Run the MTC binary. */ + 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); + /* Load the loader payload into DRAM. */ - load_stage2(&bct0); + stage2_load(&bct0); /* Setup argument data. */ strcpy(g_chainloader_arg_data, bct0.stage2_path); diff --git a/fusee/fusee-primary/src/stage2.c b/fusee/fusee-primary/src/stage2.c index 12a6e10d1..b0cfa85cc 100644 --- a/fusee/fusee-primary/src/stage2.c +++ b/fusee/fusee-primary/src/stage2.c @@ -19,12 +19,12 @@ #include "fs_utils.h" #include "utils.h" -static bool run_mtc(const char *mtc_path, uintptr_t mtc_address) { +bool stage2_run_mtc(const bct0_t *bct0) { FILINFO info; size_t size; /* 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"); return false; } @@ -32,8 +32,8 @@ static bool run_mtc(const char *mtc_path, uintptr_t mtc_address) { size = (size_t)info.fsize; /* Try to read the MTC binary. */ - if (read_from_file((void *)mtc_address, size, mtc_path) != size) { - print(SCREEN_LOG_LEVEL_WARNING, "Failed to read stage2's MTC binary (%s)!\n", mtc_path); + 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", bct0->stage2_mtc_path); return false; } @@ -47,19 +47,15 @@ static bool run_mtc(const char *mtc_path, uintptr_t mtc_address) { memcpy(&mtc_args->log_level, &mtc_log_level, sizeof(mtc_log_level)); /* 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. */ - memset((void *)mtc_address, 0, size); + memset((void *)bct0->stage2_load_address, 0, size); return mtc_res; } -void load_stage2(const bct0_t *bct0) { - FILINFO info; - size_t size; - uintptr_t tmp_addr; - +void stage2_validate_config(const bct0_t *bct0) { if (bct0->stage2_load_address == 0 || bct0->stage2_path[0] == '\x00') { fatal_error("Failed to determine where to load stage2!\n"); } @@ -81,11 +77,12 @@ void load_stage2(const bct0_t *bct0) { 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", bct0->stage2_load_address); print(SCREEN_LOG_LEVEL_DEBUG | SCREEN_LOG_LEVEL_NO_PREFIX, " Entrypoint: 0x%p\n", bct0->stage2_entrypoint); +} - /* Run the MTC binary. */ - if (!run_mtc(bct0->stage2_mtc_path, bct0->stage2_load_address)) { - print(SCREEN_LOG_LEVEL_WARNING, "DRAM training failed! Continuing with untrained DRAM.\n"); - } +void stage2_load(const bct0_t *bct0) { + FILINFO info; + size_t size; + uintptr_t tmp_addr; if (f_stat(bct0->stage2_path, &info) != FR_OK) { fatal_error("Failed to stat stage2 (%s)!\n", bct0->stage2_path); diff --git a/fusee/fusee-primary/src/stage2.h b/fusee/fusee-primary/src/stage2.h index f9d0dfdea..7787999a4 100644 --- a/fusee/fusee-primary/src/stage2.h +++ b/fusee/fusee-primary/src/stage2.h @@ -43,6 +43,8 @@ typedef struct { ScreenLogLevel log_level; } stage2_mtc_args_t; -void load_stage2(const bct0_t *bct0); +bool stage2_run_mtc(const bct0_t *bct0); +void stage2_validate_config(const bct0_t *bct0); +void stage2_load(const bct0_t *bct0); #endif From 1eded071c3f1686473189fd87f4b5ba1a0e50e7d Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sun, 25 Oct 2020 13:34:43 -0700 Subject: [PATCH 07/14] fusee-primary: tweak sdram_lp0_save_params to save code space This code is essentially a giant unrolled loop over an array of register copies. I've manually re-rolled the loop so that rather than emitting code for each parameter to read it, perform bit arithmetic on it, and write it, there is instead a static list of parameters which can be encoded using much less memory. --- fusee/fusee-primary/src/sdram_lp0.c | 2033 ++++++++++++++------------- 1 file changed, 1047 insertions(+), 986 deletions(-) diff --git a/fusee/fusee-primary/src/sdram_lp0.c b/fusee/fusee-primary/src/sdram_lp0.c index 12864e63c..8990bd67b 100644 --- a/fusee/fusee-primary/src/sdram_lp0.c +++ b/fusee/fusee-primary/src/sdram_lp0.c @@ -13,10 +13,46 @@ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ - + #include "pmc.h" #include "sdram_param_t210_lp0.h" +#include + +struct sdram_param { + uint16_t src_offset; + uint16_t dst_offset; + + uint8_t src_high_bit:5; + uint8_t is_constant:1; + uint8_t src_low_bit; + + uint8_t dst_high_bit; + uint8_t dst_low_bit; +}; + +static inline void sdram_lp0_save_one_param(struct sdram_params *sdram, volatile tegra_pmc_t *pmc, const struct sdram_param *param) { + uint32_t mask = 0xffffffff >> (31 - (param->src_high_bit - param->src_low_bit)); + uint32_t value = 0; + + if(param->is_constant) { + value = param->src_offset; + } else { + uint32_t *src = ((uint32_t*) sdram) + param->src_offset; + value = ((*src >> param->src_low_bit) & mask); + } + + uint32_t *dst = ((uint32_t*) pmc) + param->dst_offset; + *dst &= ~(mask << param->dst_low_bit); + *dst |= value << param->dst_low_bit; +} + +static void sdram_lp0_save_parameter_array(struct sdram_params *sdram, volatile tegra_pmc_t *pmc, const struct sdram_param *parameter_array, size_t count) { + for(size_t i = 0; i < count; i++) { + sdram_lp0_save_one_param(sdram, pmc, ¶meter_array[i]); + } +} + /* * This function reads SDRAM parameters from the common BCT format and * writes them into PMC scratch registers (where the BootROM expects them @@ -26,24 +62,31 @@ void sdram_lp0_save_params(const void *params) { struct sdram_params *sdram = (struct sdram_params *)params; volatile tegra_pmc_t *pmc = pmc_get_regs(); - -#define pack(src, src_bits, dst, dst_bits) { \ - uint32_t mask = 0xffffffff >> (31 - ((1 ? src_bits) - (0 ? src_bits))); \ - dst &= ~(mask << (0 ? dst_bits)); \ - dst |= ((src >> (0 ? src_bits)) & mask) << (0 ? dst_bits); \ -} -#define s(param, src_bits, pmcreg, dst_bits) \ - pack(sdram->param, src_bits, pmc->pmcreg, dst_bits) +#define s(param, src_bits, pmcreg, dst_bits) \ + { \ + .src_offset = offsetof(struct sdram_params, param) / sizeof(uint32_t), \ + .dst_offset = offsetof(tegra_pmc_t, pmcreg) / sizeof(uint32_t), \ + .is_constant = 0, \ + .src_high_bit = (1 ? src_bits), \ + .src_low_bit = (0 ? src_bits), \ + .dst_high_bit = (1 ? dst_bits), \ + .dst_low_bit = (0 ? dst_bits) \ + } -#define c(value, pmcreg, dst_bits) \ - pack(value, (1 ? dst_bits) - (0 ? dst_bits) : 0, pmc->pmcreg, dst_bits) +#define c(value, pmcreg, dst_bits) \ + { \ + .src_offset = value, \ + .dst_offset = offsetof(tegra_pmc_t, pmcreg), \ + .is_constant = 1, \ + .src_high_bit = (1 ? dst_bits), \ + .src_low_bit = (0 ? dst_bits), \ + .dst_high_bit = (1 ? dst_bits), \ + .dst_low_bit = (0 ? dst_bits) \ + } -/* 32 bits version of s macro */ -#define s32(param, pmcreg) pmc->pmcreg = sdram->param - -/* 32 bits version c macro */ -#define c32(value, pmcreg) pmc->pmcreg = value +#define s32(param, pmcreg) s(param, 31:0, pmcreg, 31:0) +#define c32(value, pmcreg) c(value, pmcreg, 31:0) //TODO: pkg1.1 (1.X - 3.X) reads them from MC. // Patch carveout parameters. @@ -139,987 +182,1005 @@ void sdram_lp0_save_params(const void *params) sdram->EmcBctSpare2 = 0x40000DD8; sdram->EmcBctSpare3 = t7; - s(EmcClockSource, 7:0, scratch6, 15:8); - s(EmcClockSourceDll, 7:0, scratch6, 23:16); - s(EmcClockSource, 31:29, scratch6, 26:24); - s(EmcClockSourceDll, 31:29, scratch6, 29:27); - s(EmcClockSourceDll, 11:10, scratch6, 31:30); - s(ClkRstControllerPllmMisc2Override, 9:8, scratch7, 1:0); - s(ClkRstControllerPllmMisc2Override, 2:1, scratch7, 3:2); - s(EmcZqCalLpDdr4WarmBoot, 31:30, scratch7, 5:4); - s(EmcClockSource, 15:15, scratch7, 6:6); - s(EmcClockSource, 26:26, scratch7, 7:7); - s(EmcClockSource, 20:20, scratch7, 8:8); - s(EmcClockSource, 19:19, scratch7, 9:9); - s(ClkRstControllerPllmMisc2Override, 13:13, scratch7, 10:10); - s(ClkRstControllerPllmMisc2Override, 12:12, scratch7, 11:11); - s(ClkRstControllerPllmMisc2Override, 11:11, scratch7, 12:12); - s(ClkRstControllerPllmMisc2Override, 10:10, scratch7, 13:13); - s(ClkRstControllerPllmMisc2Override, 5:5, scratch7, 14:14); - s(ClkRstControllerPllmMisc2Override, 4:4, scratch7, 15:15); - s(ClkRstControllerPllmMisc2Override, 3:3, scratch7, 16:16); - s(ClkRstControllerPllmMisc2Override, 0:0, scratch7, 17:17); - s(EmcZqCalLpDdr4WarmBoot, 1:0, scratch7, 19:18); - s(EmcZqCalLpDdr4WarmBoot, 4:4, scratch7, 20:20); - s(EmcOdtWrite, 5:0, scratch7, 26:21); - s(EmcOdtWrite, 11:8, scratch7, 30:27); - s(EmcOdtWrite, 31:31, scratch7, 31:31); - s(EmcFdpdCtrlCmdNoRamp, 0:0, scratch13, 30:30); - s(EmcCfgPipeClk, 0:0, scratch13, 31:31); - s(McEmemArbMisc2, 0:0, scratch14, 30:30); - s(McDaCfg0, 0:0, scratch14, 31:31); - s(EmcQRst, 6:0, scratch15, 26:20); - s(EmcQRst, 20:16, scratch15, 31:27); - s(EmcPmacroCmdTxDrv, 5:0, scratch16, 25:20); - s(EmcPmacroCmdTxDrv, 13:8, scratch16, 31:26); - s(EmcPmacroAutocalCfg0, 2:0, scratch17, 22:20); - s(EmcPmacroAutocalCfg0, 10:8, scratch17, 25:23); - s(EmcPmacroAutocalCfg0, 18:16, scratch17, 28:26); - s(EmcPmacroAutocalCfg0, 26:24, scratch17, 31:29); - s(EmcPmacroAutocalCfg1, 2:0, scratch18, 22:20); - s(EmcPmacroAutocalCfg1, 10:8, scratch18, 25:23); - s(EmcPmacroAutocalCfg1, 18:16, scratch18, 28:26); - s(EmcPmacroAutocalCfg1, 26:24, scratch18, 31:29); - s(EmcPmacroAutocalCfg2, 2:0, scratch19, 22:20); - s(EmcPmacroAutocalCfg2, 10:8, scratch19, 25:23); - s(EmcPmacroAutocalCfg2, 18:16, scratch19, 28:26); - s(EmcPmacroAutocalCfg2, 26:24, scratch19, 31:29); - s32(EmcCfgRsv,scratch22); - s32(EmcAutoCalConfig, scratch23); - s32(EmcAutoCalVrefSel0, scratch24); - s32(EmcPmacroBrickCtrlRfu1, scratch25); - s32(EmcPmacroBrickCtrlRfu2, scratch26); - s32(EmcPmcScratch1, scratch27); - s32(EmcPmcScratch2, scratch28); - s32(EmcPmcScratch3, scratch29); - s32(McEmemArbDaTurns, scratch30); - s(EmcFbioSpare, 31:24, scratch58, 7:0); - s(EmcFbioSpare, 23:16, scratch58, 15:8); - s(EmcFbioSpare, 15:8, scratch58, 23:16); - s(EmcFbioSpare, 7:2, scratch58, 29:24); - s(EmcFbioSpare, 0:0, scratch58, 30:30); - s(EmcDllCfg0, 29:0, scratch59, 29:0); - s(EmcPmacroDdllBypass, 11:0, scratch60, 11:0); - s(EmcPmacroDdllBypass, 27:13, scratch60, 26:12); - s(EmcPmacroDdllBypass, 31:29, scratch60, 29:27); - s(McEmemArbMisc0, 14:0, scratch61, 14:0); - s(McEmemArbMisc0, 30:16, scratch61, 29:15); - s(EmcFdpdCtrlCmd, 16:0, scratch62, 16:0); - s(EmcFdpdCtrlCmd, 31:20, scratch62, 28:17); - s(EmcAutoCalConfig2, 27:0, scratch63, 27:0); - s(EmcBurstRefreshNum, 3:0, scratch63, 31:28); - s(EmcPmacroZctrl, 27:0, scratch64, 27:0); - s(EmcTppd, 3:0, scratch64, 31:28); - s(EmcCfgDigDll, 10:0, scratch65, 10:0); - s(EmcCfgDigDll, 25:12, scratch65, 24:11); - s(EmcCfgDigDll, 27:27, scratch65, 25:25); - s(EmcCfgDigDll, 31:30, scratch65, 27:26); - s(EmcR2r, 3:0, scratch65, 31:28); - s(EmcFdpdCtrlDq, 16:0, scratch66, 16:0); - s(EmcFdpdCtrlDq, 28:20, scratch66, 25:17); - s(EmcFdpdCtrlDq, 31:30, scratch66, 27:26); - s(EmcW2w, 3:0, scratch66, 31:28); - s(EmcPmacroTxPwrd4, 13:0, scratch67, 13:0); - s(EmcPmacroTxPwrd4, 29:16, scratch67, 27:14); - s(EmcPmacroCommonPadTxCtrl, 3:0, scratch67, 31:28); - s(EmcPmacroTxPwrd5, 13:0, scratch68, 13:0); - s(EmcPmacroTxPwrd5, 29:16, scratch68, 27:14); - s(EmcPmacroDdllPwrd0, 4:0, scratch69, 4:0); - s(EmcPmacroDdllPwrd0, 12:6, scratch69, 11:5); - s(EmcPmacroDdllPwrd0, 20:14, scratch69, 18:12); - s(EmcPmacroDdllPwrd0, 28:22, scratch69, 25:19); - s(EmcPmacroDdllPwrd0, 31:30, scratch69, 27:26); - s(EmcCfg, 4:4, scratch69, 31:31); - s(EmcPmacroDdllPwrd1, 4:0, scratch70, 4:0); - s(EmcPmacroDdllPwrd1, 12:6, scratch70, 11:5); - s(EmcPmacroDdllPwrd1, 20:14, scratch70, 18:12); - s(EmcPmacroDdllPwrd1, 28:22, scratch70, 25:19); - s(EmcPmacroDdllPwrd1, 31:30, scratch70, 27:26); - s(EmcCfg, 5:5, scratch70, 31:31); - s(EmcPmacroDdllPwrd2, 4:0, scratch71, 4:0); - s(EmcPmacroDdllPwrd2, 12:6, scratch71, 11:5); - s(EmcPmacroDdllPwrd2, 20:14, scratch71, 18:12); - s(EmcPmacroDdllPwrd2, 28:22, scratch71, 25:19); - s(EmcPmacroDdllPwrd2, 31:30, scratch71, 27:26); - s(EmcFbioCfg5, 23:20, scratch71, 31:28); - s(EmcPmacroIbVrefDq_0, 6:0, scratch72, 6:0); - s(EmcPmacroIbVrefDq_0, 14:8, scratch72, 13:7); - s(EmcPmacroIbVrefDq_0, 22:16, scratch72, 20:14); - s(EmcPmacroIbVrefDq_0, 30:24, scratch72, 27:21); - s(EmcFbioCfg5, 15:13, scratch72, 30:28); - s(EmcCfg, 6:6, scratch72, 31:31); - s(EmcPmacroIbVrefDq_1, 6:0, scratch73, 6:0); - s(EmcPmacroIbVrefDq_1, 14:8, scratch73, 13:7); - s(EmcPmacroIbVrefDq_1, 22:16, scratch73, 20:14); - s(EmcPmacroIbVrefDq_1, 30:24, scratch73, 27:21); - s(EmcCfg2, 5:3, scratch73, 30:28); - s(EmcCfg, 7:7, scratch73, 31:31); - s(EmcPmacroIbVrefDqs_0, 6:0, scratch74, 6:0); - s(EmcPmacroIbVrefDqs_0, 14:8, scratch74, 13:7); - s(EmcPmacroIbVrefDqs_0, 22:16, scratch74, 20:14); - s(EmcPmacroIbVrefDqs_0, 30:24, scratch74, 27:21); - s(EmcCfg, 17:16, scratch74, 29:28); - s(EmcFbioCfg5, 1:0, scratch74, 31:30); - s(EmcPmacroIbVrefDqs_1, 6:0, scratch75, 6:0); - s(EmcPmacroIbVrefDqs_1, 14:8, scratch75, 13:7); - s(EmcPmacroIbVrefDqs_1, 22:16, scratch75, 20:14); - s(EmcPmacroIbVrefDqs_1, 30:24, scratch75, 27:21); - s(EmcFbioCfg5, 3:2, scratch75, 29:28); - s(EmcCfg2, 27:26, scratch75, 31:30); - s(EmcPmacroDdllShortCmd_0, 6:0, scratch76, 6:0); - s(EmcPmacroDdllShortCmd_0, 14:8, scratch76, 13:7); - s(EmcPmacroDdllShortCmd_0, 22:16, scratch76, 20:14); - s(EmcPmacroDdllShortCmd_0, 30:24, scratch76, 27:21); - s(EmcPmacroCmdPadTxCtrl, 3:2, scratch76, 29:28); - s(EmcPmacroCmdPadTxCtrl, 7:6, scratch76, 31:30); - s(EmcPmacroDdllShortCmd_1, 6:0, scratch77, 6:0); - s(EmcPmacroDdllShortCmd_1, 14:8, scratch77, 13:7); - s(EmcPmacroDdllShortCmd_1, 22:16, scratch77, 20:14); - s(EmcPmacroDdllShortCmd_1, 30:24, scratch77, 27:21); - s(EmcPmacroCmdPadTxCtrl, 11:10, scratch77, 29:28); - s(EmcPmacroCmdPadTxCtrl, 15:14, scratch77, 31:30); - s(EmcAutoCalChannel, 5:0, scratch78, 5:0); - s(EmcAutoCalChannel, 11:8, scratch78, 9:6); - s(EmcAutoCalChannel, 27:16, scratch78, 21:10); - s(EmcAutoCalChannel, 31:29, scratch78, 24:22); - s(EmcConfigSampleDelay, 6:0, scratch78, 31:25); - s(EmcPmacroRxTerm, 5:0, scratch79, 5:0); - s(EmcPmacroRxTerm, 13:8, scratch79, 11:6); - s(EmcPmacroRxTerm, 21:16, scratch79, 17:12); - s(EmcPmacroRxTerm, 29:24, scratch79, 23:18); - s(EmcRc, 7:0, scratch79, 31:24); - s(EmcPmacroDqTxDrv, 5:0, scratch80, 5:0); - s(EmcPmacroDqTxDrv, 13:8, scratch80, 11:6); - s(EmcPmacroDqTxDrv, 21:16, scratch80, 17:12); - s(EmcPmacroDqTxDrv, 29:24, scratch80, 23:18); - s(EmcSelDpdCtrl, 5:2, scratch80, 27:24); - s(EmcSelDpdCtrl, 8:8, scratch80, 28:28); - s(EmcSelDpdCtrl, 18:16, scratch80, 31:29); - s(EmcPmacroCaTxDrv, 5:0, scratch81, 5:0); - s(EmcPmacroCaTxDrv, 13:8, scratch81, 11:6); - s(EmcPmacroCaTxDrv, 21:16, scratch81, 17:12); - s(EmcPmacroCaTxDrv, 29:24, scratch81, 23:18); - s(EmcObdly, 5:0, scratch81, 29:24); - s(EmcObdly, 29:28, scratch81, 31:30); - s(EmcZcalInterval, 23:10, scratch82, 13:0); - s(EmcZcalInterval, 9:0, scratch82, 23:14); - s(EmcPmacroCmdRxTermMode, 1:0, scratch82, 25:24); - s(EmcPmacroCmdRxTermMode, 5:4, scratch82, 27:26); - s(EmcPmacroCmdRxTermMode, 9:8, scratch82, 29:28); - s(EmcPmacroCmdRxTermMode, 13:12, scratch82, 31:30); - s(EmcDataBrlshft0, 23:0, scratch83, 23:0); - s(EmcPmacroDataRxTermMode, 1:0, scratch83, 25:24); - s(EmcPmacroDataRxTermMode, 5:4, scratch83, 27:26); - s(EmcPmacroDataRxTermMode, 9:8, scratch83, 29:28); - s(EmcPmacroDataRxTermMode, 13:12, scratch83, 31:30); - s(EmcDataBrlshft1, 23:0, scratch84, 23:0); - s(McEmemArbTimingRc, 7:0, scratch84, 31:24); - s(EmcDqsBrlshft0, 23:0, scratch85, 23:0); - s(McEmemArbRsv, 7:0, scratch85, 31:24); - s(EmcDqsBrlshft1, 23:0, scratch86, 23:0); - s(EmcCfgPipe2, 11:0, scratch87, 11:0); - s(EmcCfgPipe2, 27:16, scratch87, 23:12); - s(EmcCfgPipe1, 11:0, scratch88, 11:0); - s(EmcCfgPipe1, 27:16, scratch88, 23:12); - s(EmcPmacroCmdCtrl0, 5:0, scratch89, 5:0); - s(EmcPmacroCmdCtrl0, 13:8, scratch89, 11:6); - s(EmcPmacroCmdCtrl0, 21:16, scratch89, 17:12); - s(EmcPmacroCmdCtrl0, 29:24, scratch89, 23:18); - s(EmcPmacroCmdCtrl1, 5:0, scratch90, 5:0); - s(EmcPmacroCmdCtrl1, 13:8, scratch90, 11:6); - s(EmcPmacroCmdCtrl1, 21:16, scratch90, 17:12); - s(EmcPmacroCmdCtrl1, 29:24, scratch90, 23:18); - s(EmcRas, 6:0, scratch90, 30:24); - s(EmcCfg, 8:8, scratch90, 31:31); - s(EmcPmacroVttgenCtrl2, 23:0, scratch91, 23:0); - s(EmcW2p, 6:0, scratch91, 30:24); - s(EmcCfg, 9:9, scratch91, 31:31); - s(EmcPmacroCmdPadRxCtrl, 2:0, scratch92, 2:0); - s(EmcPmacroCmdPadRxCtrl, 5:4, scratch92, 4:3); - s(EmcPmacroCmdPadRxCtrl, 10:8, scratch92, 7:5); - s(EmcPmacroCmdPadRxCtrl, 22:12, scratch92, 18:8); - s(EmcPmacroCmdPadRxCtrl, 28:24, scratch92, 23:19); - s(EmcQSafe, 6:0, scratch92, 30:24); - s(EmcCfg, 18:18, scratch92, 31:31); - s(EmcPmacroDataPadRxCtrl, 2:0, scratch93, 2:0); - s(EmcPmacroDataPadRxCtrl, 5:4, scratch93, 4:3); - s(EmcPmacroDataPadRxCtrl, 10:8, scratch93, 7:5); - s(EmcPmacroDataPadRxCtrl, 22:12, scratch93, 18:8); - s(EmcPmacroDataPadRxCtrl, 28:24, scratch93, 23:19); - s(EmcRdv, 6:0, scratch93, 30:24); - s(EmcCfg, 21:21, scratch93, 31:31); - s(McEmemArbDaCovers, 23:0, scratch94, 23:0); - s(EmcRw2Pden, 6:0, scratch94, 30:24); - s(EmcCfg, 22:22, scratch94, 31:31); - s(EmcPmacroCmdCtrl2, 5:0, scratch95, 5:0); - s(EmcPmacroCmdCtrl2, 13:9, scratch95, 10:6); - s(EmcPmacroCmdCtrl2, 21:16, scratch95, 16:11); - s(EmcPmacroCmdCtrl2, 29:24, scratch95, 22:17); - s(EmcRfcPb, 8:0, scratch95, 31:23); - s(EmcPmacroQuseDdllRank0_0, 10:0, scratch96, 10:0); - s(EmcPmacroQuseDdllRank0_0, 26:16, scratch96, 21:11); - s(EmcCfgUpdate, 2:0, scratch96, 24:22); - s(EmcCfgUpdate, 10:8, scratch96, 27:25); - s(EmcCfgUpdate, 31:28, scratch96, 31:28); - s(EmcPmacroQuseDdllRank0_1, 10:0, scratch97, 10:0); - s(EmcPmacroQuseDdllRank0_1, 26:16, scratch97, 21:11); - s(EmcRfc, 9:0, scratch97, 31:22); - s(EmcPmacroQuseDdllRank0_2, 10:0, scratch98, 10:0); - s(EmcPmacroQuseDdllRank0_2, 26:16, scratch98, 21:11); - s(EmcTxsr, 9:0, scratch98, 31:22); - s(EmcPmacroQuseDdllRank0_3, 10:0, scratch99, 10:0); - s(EmcPmacroQuseDdllRank0_3, 26:16, scratch99, 21:11); - s(EmcMc2EmcQ, 2:0, scratch99, 24:22); - s(EmcMc2EmcQ, 10:8, scratch99, 27:25); - s(EmcMc2EmcQ, 27:24, scratch99, 31:28); - s(EmcPmacroQuseDdllRank0_4, 10:0, scratch100, 10:0); - s(EmcPmacroQuseDdllRank0_4, 26:16, scratch100, 21:11); - s(McEmemArbRing1Throttle, 4:0, scratch100, 26:22); - s(McEmemArbRing1Throttle, 20:16, scratch100, 31:27); - s(EmcPmacroQuseDdllRank0_5, 10:0, scratch101, 10:0); - s(EmcPmacroQuseDdllRank0_5, 26:16, scratch101, 21:11); - s(EmcPmacroQuseDdllRank1_0, 10:0, scratch102, 10:0); - s(EmcPmacroQuseDdllRank1_0, 26:16, scratch102, 21:11); - s(EmcAr2Pden, 8:0, scratch102, 30:22); - s(EmcCfg, 23:23, scratch102, 31:31); - s(EmcPmacroQuseDdllRank1_1, 10:0, scratch103, 10:0); - s(EmcPmacroQuseDdllRank1_1, 26:16, scratch103, 21:11); - s(EmcRfcSlr, 8:0, scratch103, 30:22); - s(EmcCfg, 24:24, scratch103, 31:31); - s(EmcPmacroQuseDdllRank1_2, 10:0, scratch104, 10:0); - s(EmcPmacroQuseDdllRank1_2, 26:16, scratch104, 21:11); - s(EmcIbdly, 6:0, scratch104, 28:22); - s(EmcIbdly, 29:28, scratch104, 30:29); - s(EmcCfg, 25:25, scratch104, 31:31); - s(EmcPmacroQuseDdllRank1_3, 10:0, scratch105, 10:0); - s(EmcPmacroQuseDdllRank1_3, 26:16, scratch105, 21:11); - s(McEmemArbTimingRFCPB, 8:0, scratch105, 30:22); - s(EmcCfg, 26:26, scratch105, 31:31); - s(EmcPmacroQuseDdllRank1_4, 10:0, scratch106, 10:0); - s(EmcPmacroQuseDdllRank1_4, 26:16, scratch106, 21:11); - s(EmcTfaw, 6:0, scratch106, 28:22); - s(EmcPmacroDataPadTxCtrl, 3:2, scratch106, 30:29); - s(EmcCfg, 28:28, scratch106, 31:31); - s(EmcPmacroQuseDdllRank1_5, 10:0, scratch107, 10:0); - s(EmcPmacroQuseDdllRank1_5, 26:16, scratch107, 21:11); - s(EmcTClkStable, 6:0, scratch107, 28:22); - s(EmcPmacroDataPadTxCtrl, 7:6, scratch107, 30:29); - s(EmcCfg, 29:29, scratch107, 31:31); - s(EmcPmacroObDdllLongDqRank0_0, 10:0, scratch108, 10:0); - s(EmcPmacroObDdllLongDqRank0_0, 26:16, scratch108, 21:11); - s(EmcPdex2Mrr, 6:0, scratch108, 28:22); - s(EmcPmacroDataPadTxCtrl, 11:10, scratch108, 30:29); - s(EmcCfg, 30:30, scratch108, 31:31); - s(EmcPmacroObDdllLongDqRank0_1, 10:0, scratch109, 10:0); - s(EmcPmacroObDdllLongDqRank0_1, 26:16, scratch109, 21:11); - s(EmcRdvMask, 6:0, scratch109, 28:22); - s(EmcPmacroDataPadTxCtrl, 15:14, scratch109, 30:29); - s(EmcCfg, 31:31, scratch109, 31:31); - s(EmcPmacroObDdllLongDqRank0_2, 10:0, scratch110, 10:0); - s(EmcPmacroObDdllLongDqRank0_2, 26:16, scratch110, 21:11); - s(EmcRdvEarlyMask, 6:0, scratch110, 28:22); - s(EmcFbioCfg5, 4:4, scratch110, 29:29); - s(EmcFbioCfg5, 8:8, scratch110, 30:30); - s(EmcFbioCfg5, 10:10, scratch110, 31:31); - s(EmcPmacroObDdllLongDqRank0_3, 10:0, scratch111, 10:0); - s(EmcPmacroObDdllLongDqRank0_3, 26:16, scratch111, 21:11); - s(EmcRdvEarly, 6:0, scratch111, 28:22); - s(EmcFbioCfg5, 12:12, scratch111, 29:29); - s(EmcFbioCfg5, 25:24, scratch111, 31:30); - s(EmcPmacroObDdllLongDqRank0_4, 10:0, scratch112, 10:0); - s(EmcPmacroObDdllLongDqRank0_4, 26:16, scratch112, 21:11); - s(EmcPmacroDdllShortCmd_2, 6:0, scratch112, 28:22); - s(EmcFbioCfg5, 28:26, scratch112, 31:29); - s(EmcPmacroObDdllLongDqRank0_5, 10:0, scratch113, 10:0); - s(EmcPmacroObDdllLongDqRank0_5, 26:16, scratch113, 21:11); - s(McEmemArbTimingRp, 6:0, scratch113, 28:22); - s(EmcFbioCfg5, 31:30, scratch113, 30:29); - s(EmcCfg2, 0:0, scratch113, 31:31); - s(EmcPmacroObDdllLongDqRank1_0, 10:0, scratch114, 10:0); - s(EmcPmacroObDdllLongDqRank1_0, 26:16, scratch114, 21:11); - s(McEmemArbTimingRas, 6:0, scratch114, 28:22); - s(EmcCfg2, 2:1, scratch114, 30:29); - s(EmcCfg2, 7:7, scratch114, 31:31); - s(EmcPmacroObDdllLongDqRank1_1, 10:0, scratch115, 10:0); - s(EmcPmacroObDdllLongDqRank1_1, 26:16, scratch115, 21:11); - s(McEmemArbTimingFaw, 6:0, scratch115, 28:22); - s(EmcCfg2, 11:10, scratch115, 30:29); - s(EmcCfg2, 14:14, scratch115, 31:31); - s(EmcPmacroObDdllLongDqRank1_2, 10:0, scratch123, 10:0); - s(EmcPmacroObDdllLongDqRank1_2, 26:16, scratch123, 21:11); - s(McEmemArbTimingRap2Pre, 6:0, scratch123, 28:22); - s(EmcCfg2, 16:15, scratch123, 30:29); - s(EmcCfg2, 20:20, scratch123, 31:31); - s(EmcPmacroObDdllLongDqRank1_3, 10:0, scratch124, 10:0); - s(EmcPmacroObDdllLongDqRank1_3, 26:16, scratch124, 21:11); - s(McEmemArbTimingWap2Pre, 6:0, scratch124, 28:22); - s(EmcCfg2, 24:22, scratch124, 31:29); - s(EmcPmacroObDdllLongDqRank1_4, 10:0, scratch125, 10:0); - s(EmcPmacroObDdllLongDqRank1_4, 26:16, scratch125, 21:11); - s(McEmemArbTimingR2W, 6:0, scratch125, 28:22); - s(EmcCfg2, 25:25, scratch125, 29:29); - s(EmcCfg2, 29:28, scratch125, 31:30); - s(EmcPmacroObDdllLongDqRank1_5, 10:0, scratch126, 10:0); - s(EmcPmacroObDdllLongDqRank1_5, 26:16, scratch126, 21:11); - s(McEmemArbTimingW2R, 6:0, scratch126, 28:22); - s(EmcCfg2, 31:30, scratch126, 30:29); - s(EmcCfgPipe, 0:0, scratch126, 31:31); - s(EmcPmacroObDdllLongDqsRank0_0, 10:0, scratch127, 10:0); - s(EmcPmacroObDdllLongDqsRank0_0, 26:16, scratch127, 21:11); - s(EmcRp, 5:0, scratch127, 27:22); - s(EmcCfgPipe, 4:1, scratch127, 31:28); - s(EmcPmacroObDdllLongDqsRank0_1, 10:0, scratch128, 10:0); - s(EmcPmacroObDdllLongDqsRank0_1, 26:16, scratch128, 21:11); - s(EmcR2w, 5:0, scratch128, 27:22); - s(EmcCfgPipe, 8:5, scratch128, 31:28); - s(EmcPmacroObDdllLongDqsRank0_2, 10:0, scratch129, 10:0); - s(EmcPmacroObDdllLongDqsRank0_2, 26:16, scratch129, 21:11); - s(EmcW2r, 5:0, scratch129, 27:22); - s(EmcCfgPipe, 11:9, scratch129, 30:28); - s(EmcCfgPipe, 16:16, scratch129, 31:31); - s(EmcPmacroObDdllLongDqsRank0_3, 10:0, scratch130, 10:0); - s(EmcPmacroObDdllLongDqsRank0_3, 26:16, scratch130, 21:11); - s(EmcR2p, 5:0, scratch130, 27:22); - s(EmcCfgPipe, 20:17, scratch130, 31:28); - s(EmcPmacroObDdllLongDqsRank0_4, 10:0, scratch131, 10:0); - s(EmcPmacroObDdllLongDqsRank0_4, 26:16, scratch131, 21:11); - s(EmcCcdmw, 5:0, scratch131, 27:22); - s(EmcCfgPipe, 24:21, scratch131, 31:28); - s(EmcPmacroObDdllLongDqsRank0_5, 10:0, scratch132, 10:0); - s(EmcPmacroObDdllLongDqsRank0_5, 26:16, scratch132, 21:11); - s(EmcRdRcd, 5:0, scratch132, 27:22); - s(EmcCfgPipe, 27:25, scratch132, 30:28); - s(EmcPmacroTxPwrd0, 0:0, scratch132, 31:31); - s(EmcPmacroObDdllLongDqsRank1_0, 10:0, scratch133, 10:0); - s(EmcPmacroObDdllLongDqsRank1_0, 26:16, scratch133, 21:11); - s(EmcWrRcd, 5:0, scratch133, 27:22); - s(EmcPmacroTxPwrd0, 4:1, scratch133, 31:28); - s(EmcPmacroObDdllLongDqsRank1_1, 10:0, scratch134, 10:0); - s(EmcPmacroObDdllLongDqsRank1_1, 26:16, scratch134, 21:11); - s(EmcWdv, 5:0, scratch134, 27:22); - s(EmcPmacroTxPwrd0, 8:5, scratch134, 31:28); - s(EmcPmacroObDdllLongDqsRank1_2, 10:0, scratch135, 10:0); - s(EmcPmacroObDdllLongDqsRank1_2, 26:16, scratch135, 21:11); - s(EmcQUse, 5:0, scratch135, 27:22); - s(EmcPmacroTxPwrd0, 12:9, scratch135, 31:28); - s(EmcPmacroObDdllLongDqsRank1_3, 10:0, scratch136, 10:0); - s(EmcPmacroObDdllLongDqsRank1_3, 26:16, scratch136, 21:11); - s(EmcPdEx2Wr, 5:0, scratch136, 27:22); - s(EmcPmacroTxPwrd0, 13:13, scratch136, 28:28); - s(EmcPmacroTxPwrd0, 18:16, scratch136, 31:29); - s(EmcPmacroObDdllLongDqsRank1_4, 10:0, scratch137, 10:0); - s(EmcPmacroObDdllLongDqsRank1_4, 26:16, scratch137, 21:11); - s(EmcPdEx2Rd, 5:0, scratch137, 27:22); - s(EmcPmacroTxPwrd0, 22:19, scratch137, 31:28); - s(EmcPmacroObDdllLongDqsRank1_5, 10:0, scratch138, 10:0); - s(EmcPmacroObDdllLongDqsRank1_5, 26:16, scratch138, 21:11); - s(EmcPdex2Cke, 5:0, scratch138, 27:22); - s(EmcPmacroTxPwrd0, 26:23, scratch138, 31:28); - s(EmcPmacroIbDdllLongDqsRank0_0, 10:0, scratch139, 10:0); - s(EmcPmacroIbDdllLongDqsRank0_0, 26:16, scratch139, 21:11); - s(EmcPChg2Pden, 5:0, scratch139, 27:22); - s(EmcPmacroTxPwrd0, 29:27, scratch139, 30:28); - s(EmcPmacroTxPwrd1, 0:0, scratch139, 31:31); - s(EmcPmacroIbDdllLongDqsRank0_1, 10:0, scratch140, 10:0); - s(EmcPmacroIbDdllLongDqsRank0_1, 26:16, scratch140, 21:11); - s(EmcAct2Pden, 5:0, scratch140, 27:22); - s(EmcPmacroTxPwrd1, 4:1, scratch140, 31:28); - s(EmcPmacroIbDdllLongDqsRank0_2, 10:0, scratch141, 10:0); - s(EmcPmacroIbDdllLongDqsRank0_2, 26:16, scratch141, 21:11); - s(EmcCke2Pden, 5:0, scratch141, 27:22); - s(EmcPmacroTxPwrd1, 8:5, scratch141, 31:28); - s(EmcPmacroIbDdllLongDqsRank0_3, 10:0, scratch142, 10:0); - s(EmcPmacroIbDdllLongDqsRank0_3, 26:16, scratch142, 21:11); - s(EmcTcke, 5:0, scratch142, 27:22); - s(EmcPmacroTxPwrd1, 12:9, scratch142, 31:28); - s(EmcPmacroIbDdllLongDqsRank1_0, 10:0, scratch143, 10:0); - s(EmcPmacroIbDdllLongDqsRank1_0, 26:16, scratch143, 21:11); - s(EmcTrpab, 5:0, scratch143, 27:22); - s(EmcPmacroTxPwrd1, 13:13, scratch143, 28:28); - s(EmcPmacroTxPwrd1, 18:16, scratch143, 31:29); - s(EmcPmacroIbDdllLongDqsRank1_1, 10:0, scratch144, 10:0); - s(EmcPmacroIbDdllLongDqsRank1_1, 26:16, scratch144, 21:11); - s(EmcClkenOverride, 3:1, scratch144, 24:22); - s(EmcClkenOverride, 8:6, scratch144, 27:25); - s(EmcPmacroTxPwrd1, 22:19, scratch144, 31:28); - s(EmcPmacroIbDdllLongDqsRank1_2, 10:0, scratch145, 10:0); - s(EmcPmacroIbDdllLongDqsRank1_2, 26:16, scratch145, 21:11); - s(EmcEInput, 5:0, scratch145, 27:22); - s(EmcPmacroTxPwrd1, 26:23, scratch145, 31:28); - s(EmcPmacroIbDdllLongDqsRank1_3, 10:0, scratch146, 10:0); - s(EmcPmacroIbDdllLongDqsRank1_3, 26:16, scratch146, 21:11); - s(EmcEInputDuration, 5:0, scratch146, 27:22); - s(EmcPmacroTxPwrd1, 29:27, scratch146, 30:28); - s(EmcPmacroTxPwrd2, 0:0, scratch146, 31:31); - s(EmcPmacroDdllLongCmd_0, 10:0, scratch147, 10:0); - s(EmcPmacroDdllLongCmd_0, 26:16, scratch147, 21:11); - s(EmcPutermExtra, 5:0, scratch147, 27:22); - s(EmcPmacroTxPwrd2, 4:1, scratch147, 31:28); - s(EmcPmacroDdllLongCmd_1, 10:0, scratch148, 10:0); - s(EmcPmacroDdllLongCmd_1, 26:16, scratch148, 21:11); - s(EmcTckesr, 5:0, scratch148, 27:22); - s(EmcPmacroTxPwrd2, 8:5, scratch148, 31:28); - s(EmcPmacroDdllLongCmd_2, 10:0, scratch149, 10:0); - s(EmcPmacroDdllLongCmd_2, 26:16, scratch149, 21:11); - s(EmcTpd, 5:0, scratch149, 27:22); - s(EmcPmacroTxPwrd2, 12:9, scratch149, 31:28); - s(EmcPmacroDdllLongCmd_3, 10:0, scratch150, 10:0); - s(EmcPmacroDdllLongCmd_3, 26:16, scratch150, 21:11); - s(EmcWdvMask, 5:0, scratch150, 27:22); - s(EmcPmacroTxPwrd2, 13:13, scratch150, 28:28); - s(EmcPmacroTxPwrd2, 18:16, scratch150, 31:29); - s(McEmemArbCfg, 8:0, scratch151, 8:0); - s(McEmemArbCfg, 20:16, scratch151, 13:9); - s(McEmemArbCfg, 31:24, scratch151, 21:14); - s(EmcWdvChk, 5:0, scratch151, 27:22); - s(EmcPmacroTxPwrd2, 22:19, scratch151, 31:28); - s(McEmemArbMisc1, 12:0, scratch152, 12:0); - s(McEmemArbMisc1, 25:21, scratch152, 17:13); - s(McEmemArbMisc1, 31:28, scratch152, 21:18); - s(EmcCmdBrlshft0, 5:0, scratch152, 27:22); - s(EmcPmacroTxPwrd2, 26:23, scratch152, 31:28); - s(EmcMrsWaitCnt2, 9:0, scratch153, 9:0); - s(EmcMrsWaitCnt2, 26:16, scratch153, 20:10); - s(EmcPmacroIbRxrt, 10:0, scratch153, 31:21); - s(EmcMrsWaitCnt, 9:0, scratch154, 9:0); - s(EmcMrsWaitCnt, 26:16, scratch154, 20:10); - s(EmcPmacroDdllLongCmd_4, 10:0, scratch154, 31:21); - s(EmcAutoCalInterval, 20:0, scratch155, 20:0); - s(McEmemArbOutstandingReq, 8:0, scratch155, 29:21); - s(McEmemArbOutstandingReq, 31:30, scratch155, 31:30); - s(McEmemArbRefpbHpCtrl, 6:0, scratch156, 6:0); - s(McEmemArbRefpbHpCtrl, 14:8, scratch156, 13:7); - s(McEmemArbRefpbHpCtrl, 22:16, scratch156, 20:14); - s(EmcCmdBrlshft1, 5:0, scratch156, 26:21); - s(EmcRrd, 4:0, scratch156, 31:27); - s(EmcQuseBrlshft0, 19:0, scratch157, 19:0); - s(EmcFbioCfg8, 27:16, scratch157, 31:20); - s(EmcQuseBrlshft1, 19:0, scratch158, 19:0); - s(EmcTxsrDll, 11:0, scratch158, 31:20); - s(EmcQuseBrlshft2, 19:0, scratch159, 19:0); - s(EmcTxdsrvttgen, 11:0, scratch159, 31:20); - s(EmcQuseBrlshft3, 19:0, scratch160, 19:0); - s(EmcPmacroVttgenCtrl0, 3:0, scratch160, 23:20); - s(EmcPmacroVttgenCtrl0, 11:8, scratch160, 27:24); - s(EmcPmacroVttgenCtrl0, 19:16, scratch160, 31:28); - s(EmcPmacroVttgenCtrl1, 19:0, scratch161, 19:0); - s(EmcCmdBrlshft2, 5:0, scratch161, 25:20); - s(EmcCmdBrlshft3, 5:0, scratch161, 31:26); - s(EmcAutoCalConfig3, 5:0, scratch162, 5:0); - s(EmcAutoCalConfig3, 13:8, scratch162, 11:6); - s(EmcAutoCalConfig3, 18:16, scratch162, 14:12); - s(EmcAutoCalConfig3, 22:20, scratch162, 17:15); - s(EmcTRefBw, 13:0, scratch162, 31:18); - s(EmcAutoCalConfig4, 5:0, scratch163, 5:0); - s(EmcAutoCalConfig4, 13:8, scratch163, 11:6); - s(EmcAutoCalConfig4, 18:16, scratch163, 14:12); - s(EmcAutoCalConfig4, 22:20, scratch163, 17:15); - s(EmcQpop, 6:0, scratch163, 24:18); - s(EmcQpop, 22:16, scratch163, 31:25); - s(EmcAutoCalConfig5, 5:0, scratch164, 5:0); - s(EmcAutoCalConfig5, 13:8, scratch164, 11:6); - s(EmcAutoCalConfig5, 18:16, scratch164, 14:12); - s(EmcAutoCalConfig5, 22:20, scratch164, 17:15); - s(EmcPmacroAutocalCfgCommon, 5:0, scratch164, 23:18); - s(EmcPmacroAutocalCfgCommon, 13:8, scratch164, 29:24); - s(EmcPmacroAutocalCfgCommon, 16:16, scratch164, 30:30); - s(EmcPmacroTxPwrd2, 27:27, scratch164, 31:31); - s(EmcAutoCalConfig6, 5:0, scratch165, 5:0); - s(EmcAutoCalConfig6, 13:8, scratch165, 11:6); - s(EmcAutoCalConfig6, 18:16, scratch165, 14:12); - s(EmcAutoCalConfig6, 22:20, scratch165, 17:15); - s(EmcWev, 5:0, scratch165, 23:18); - s(EmcWsv, 5:0, scratch165, 29:24); - s(EmcPmacroTxPwrd2, 29:28, scratch165, 31:30); - s(EmcAutoCalConfig7, 5:0, scratch166, 5:0); - s(EmcAutoCalConfig7, 13:8, scratch166, 11:6); - s(EmcAutoCalConfig7, 18:16, scratch166, 14:12); - s(EmcAutoCalConfig7, 22:20, scratch166, 17:15); - s(EmcCfg3, 2:0, scratch166, 20:18); - s(EmcCfg3, 6:4, scratch166, 23:21); - s(EmcQuseWidth, 3:0, scratch166, 27:24); - s(EmcQuseWidth, 29:28, scratch166, 29:28); - s(EmcPmacroTxPwrd3, 1:0, scratch166, 31:30); - s(EmcAutoCalConfig8, 5:0, scratch167, 5:0); - s(EmcAutoCalConfig8, 13:8, scratch167, 11:6); - s(EmcAutoCalConfig8, 18:16, scratch167, 14:12); - s(EmcAutoCalConfig8, 22:20, scratch167, 17:15); - s(EmcPmacroBgBiasCtrl0, 2:0, scratch167, 20:18); - s(EmcPmacroBgBiasCtrl0, 6:4, scratch167, 23:21); - s(McEmemArbTimingRcd, 5:0, scratch167, 29:24); - s(EmcPmacroTxPwrd3, 3:2, scratch167, 31:30); - s(EmcXm2CompPadCtrl2, 17:0, scratch168, 17:0); - s(McEmemArbTimingCcdmw, 5:0, scratch168, 23:18); - s(McEmemArbOverride, 27:27, scratch168, 24:24); - s(McEmemArbOverride, 26:26, scratch168, 25:25); - s(McEmemArbOverride, 16:16, scratch168, 26:26); - s(McEmemArbOverride, 10:10, scratch168, 27:27); - s(McEmemArbOverride, 4:4, scratch168, 28:28); - s(McEmemArbOverride, 3:3, scratch168, 29:29); - s(EmcPmacroTxPwrd3, 5:4, scratch168, 31:30); - s(EmcXm2CompPadCtrl3, 17:0, scratch169, 17:0); - s(EmcRext, 4:0, scratch169, 22:18); - s(EmcTClkStop, 4:0, scratch169, 27:23); - s(EmcPmacroTxPwrd3, 9:6, scratch169, 31:28); - s(EmcZcalWaitCnt, 10:0, scratch170, 10:0); - s(EmcZcalWaitCnt, 21:16, scratch170, 16:11); - s(EmcZcalWaitCnt, 31:31, scratch170, 17:17); - s(EmcWext, 4:0, scratch170, 22:18); - s(EmcRefctrl2, 0:0, scratch170, 23:23); - s(EmcRefctrl2, 26:24, scratch170, 26:24); - s(EmcRefctrl2, 31:31, scratch170, 27:27); - s(EmcPmacroTxPwrd3, 13:10, scratch170, 31:28); - s(EmcZcalMrwCmd, 7:0, scratch171, 7:0); - s(EmcZcalMrwCmd, 23:16, scratch171, 15:8); - s(EmcZcalMrwCmd, 31:30, scratch171, 17:16); - s(EmcWeDuration, 4:0, scratch171, 22:18); - s(EmcWsDuration, 4:0, scratch171, 27:23); - s(EmcPmacroTxPwrd3, 19:16, scratch171, 31:28); - s(EmcSwizzleRank0Byte0, 2:0, scratch172, 2:0); - s(EmcSwizzleRank0Byte0, 6:4, scratch172, 5:3); - s(EmcSwizzleRank0Byte0, 10:8, scratch172, 8:6); - s(EmcSwizzleRank0Byte0, 14:12, scratch172, 11:9); - s(EmcSwizzleRank0Byte0, 18:16, scratch172, 14:12); - s(EmcSwizzleRank0Byte0, 22:20, scratch172, 17:15); - s(EmcPutermWidth, 31:31, scratch172, 18:18); - s(EmcPutermWidth, 3:0, scratch172, 22:19); - s(McEmemArbTimingRrd, 4:0, scratch172, 27:23); - s(EmcPmacroTxPwrd3, 23:20, scratch172, 31:28); - s(EmcSwizzleRank0Byte1, 2:0, scratch173, 2:0); - s(EmcSwizzleRank0Byte1, 6:4, scratch173, 5:3); - s(EmcSwizzleRank0Byte1, 10:8, scratch173, 8:6); - s(EmcSwizzleRank0Byte1, 14:12, scratch173, 11:9); - s(EmcSwizzleRank0Byte1, 18:16, scratch173, 14:12); - s(EmcSwizzleRank0Byte1, 22:20, scratch173, 17:15); - s(McEmemArbTimingR2R, 4:0, scratch173, 22:18); - s(McEmemArbTimingW2W, 4:0, scratch173, 27:23); - s(EmcPmacroTxPwrd3, 27:24, scratch173, 31:28); - s(EmcSwizzleRank0Byte2, 2:0, scratch174, 2:0); - s(EmcSwizzleRank0Byte2, 6:4, scratch174, 5:3); - s(EmcSwizzleRank0Byte2, 10:8, scratch174, 8:6); - s(EmcSwizzleRank0Byte2, 14:12, scratch174, 11:9); - s(EmcSwizzleRank0Byte2, 18:16, scratch174, 14:12); - s(EmcSwizzleRank0Byte2, 22:20, scratch174, 17:15); - s(EmcPmacroTxPwrd3, 29:28, scratch174, 19:18); - s(EmcPmacroTxSelClkSrc0, 11:0, scratch174, 31:20); - s(EmcSwizzleRank0Byte3, 2:0, scratch175, 2:0); - s(EmcSwizzleRank0Byte3, 6:4, scratch175, 5:3); - s(EmcSwizzleRank0Byte3, 10:8, scratch175, 8:6); - s(EmcSwizzleRank0Byte3, 14:12, scratch175, 11:9); - s(EmcSwizzleRank0Byte3, 18:16, scratch175, 14:12); - s(EmcSwizzleRank0Byte3, 22:20, scratch175, 17:15); - s(EmcPmacroTxSelClkSrc0, 27:16, scratch175, 29:18); - s(EmcPmacroTxSelClkSrc1, 1:0, scratch175, 31:30); - s(EmcSwizzleRank1Byte0, 2:0, scratch176, 2:0); - s(EmcSwizzleRank1Byte0, 6:4, scratch176, 5:3); - s(EmcSwizzleRank1Byte0, 10:8, scratch176, 8:6); - s(EmcSwizzleRank1Byte0, 14:12, scratch176, 11:9); - s(EmcSwizzleRank1Byte0, 18:16, scratch176, 14:12); - s(EmcSwizzleRank1Byte0, 22:20, scratch176, 17:15); - s(EmcPmacroTxSelClkSrc1, 11:2, scratch176, 27:18); - s(EmcPmacroTxSelClkSrc1, 19:16, scratch176, 31:28); - s(EmcSwizzleRank1Byte1, 2:0, scratch177, 2:0); - s(EmcSwizzleRank1Byte1, 6:4, scratch177, 5:3); - s(EmcSwizzleRank1Byte1, 10:8, scratch177, 8:6); - s(EmcSwizzleRank1Byte1, 14:12, scratch177, 11:9); - s(EmcSwizzleRank1Byte1, 18:16, scratch177, 14:12); - s(EmcSwizzleRank1Byte1, 22:20, scratch177, 17:15); - s(EmcPmacroTxSelClkSrc1, 27:20, scratch177, 25:18); - s(EmcPmacroTxSelClkSrc3, 5:0, scratch177, 31:26); - s(EmcSwizzleRank1Byte2, 2:0, scratch178, 2:0); - s(EmcSwizzleRank1Byte2, 6:4, scratch178, 5:3); - s(EmcSwizzleRank1Byte2, 10:8, scratch178, 8:6); - s(EmcSwizzleRank1Byte2, 14:12, scratch178, 11:9); - s(EmcSwizzleRank1Byte2, 18:16, scratch178, 14:12); - s(EmcSwizzleRank1Byte2, 22:20, scratch178, 17:15); - s(EmcPmacroTxSelClkSrc3, 11:6, scratch178, 23:18); - s(EmcPmacroTxSelClkSrc3, 23:16, scratch178, 31:24); - s(EmcSwizzleRank1Byte3, 2:0, scratch179, 2:0); - s(EmcSwizzleRank1Byte3, 6:4, scratch179, 5:3); - s(EmcSwizzleRank1Byte3, 10:8, scratch179, 8:6); - s(EmcSwizzleRank1Byte3, 14:12, scratch179, 11:9); - s(EmcSwizzleRank1Byte3, 18:16, scratch179, 14:12); - s(EmcSwizzleRank1Byte3, 22:20, scratch179, 17:15); - s(EmcPmacroTxSelClkSrc3, 27:24, scratch179, 21:18); - s(EmcPmacroTxSelClkSrc2, 9:0, scratch179, 31:22); - s(EmcPmacroCmdBrickCtrlFdpd, 17:0, scratch180, 17:0); - s(EmcPmacroTxSelClkSrc2, 11:10, scratch180, 19:18); - s(EmcPmacroTxSelClkSrc2, 27:16, scratch180, 31:20); - s(EmcPmacroDataBrickCtrlFdpd, 17:0, scratch181, 17:0); - s(EmcPmacroTxSelClkSrc4, 11:0, scratch181, 29:18); - s(EmcPmacroTxSelClkSrc4, 17:16, scratch181, 31:30); - s(EmcFbioCfg7, 16:0, scratch182, 16:0); - s(McEmemArbRefpbBankCtrl, 6:0, scratch182, 23:17); - s(McEmemArbRefpbBankCtrl, 14:8, scratch182, 30:24); - s(McEmemArbRefpbBankCtrl, 31:31, scratch182, 31:31); - s(EmcDynSelfRefControl, 15:0, scratch183, 15:0); - s(EmcDynSelfRefControl, 31:31, scratch183, 16:16); - s(EmcPmacroTxSelClkSrc4, 27:18, scratch183, 26:17); - s(EmcPmacroTxSelClkSrc5, 4:0, scratch183, 31:27); - s(EmcDllCfg1, 16:0, scratch184, 16:0); - s(EmcPmacroTxSelClkSrc5, 11:5, scratch184, 23:17); - s(EmcPmacroTxSelClkSrc5, 23:16, scratch184, 31:24); - s(EmcPmacroPadCfgCtrl, 1:0, scratch185, 1:0); - s(EmcPmacroPadCfgCtrl, 6:5, scratch185, 3:2); - s(EmcPmacroPadCfgCtrl, 11:9, scratch185, 6:4); - s(EmcPmacroPadCfgCtrl, 13:13, scratch185, 7:7); - s(EmcPmacroPadCfgCtrl, 17:16, scratch185, 9:8); - s(EmcPmacroPadCfgCtrl, 21:20, scratch185, 11:10); - s(EmcPmacroPadCfgCtrl, 25:24, scratch185, 13:12); - s(EmcPmacroPadCfgCtrl, 30:28, scratch185, 16:14); - s(EmcPmacroTxSelClkSrc5, 27:24, scratch185, 20:17); - s(EmcPmacroCmdPadTxCtrl, 1:0, scratch185, 22:21); - s(EmcPmacroCmdPadTxCtrl, 5:4, scratch185, 24:23); - s(EmcPmacroCmdPadTxCtrl, 9:8, scratch185, 26:25); - s(EmcPmacroCmdPadTxCtrl, 13:12, scratch185, 28:27); - s(EmcPmacroCmdPadTxCtrl, 16:16, scratch185, 29:29); - s(EmcPmacroCmdPadTxCtrl, 21:20, scratch185, 31:30); - s(EmcRefresh, 15:0, scratch186, 15:0); - s(EmcCmdQ, 4:0, scratch186, 20:16); - s(EmcCmdQ, 10:8, scratch186, 23:21); - s(EmcCmdQ, 14:12, scratch186, 26:24); - s(EmcCmdQ, 28:24, scratch186, 31:27); - s(EmcAcpdControl, 15:0, scratch187, 15:0); - s(EmcAutoCalVrefSel1, 15:0, scratch187, 31:16); - s(EmcXm2CompPadCtrl, 1:0, scratch188, 1:0); - s(EmcXm2CompPadCtrl, 6:3, scratch188, 5:2); - s(EmcXm2CompPadCtrl, 9:9, scratch188, 6:6); - s(EmcXm2CompPadCtrl, 19:11, scratch188, 15:7); - s(EmcCfgDigDllPeriod, 15:0, scratch188, 31:16); - s(EmcCfgDigDll_1, 15:0, scratch189, 15:0); - s(EmcPreRefreshReqCnt, 15:0, scratch189, 31:16); - s(EmcPmacroCmdPadTxCtrl, 27:24, scratch190, 19:16); - s(EmcPmacroDataPadTxCtrl, 1:0, scratch190, 21:20); - s(EmcPmacroDataPadTxCtrl, 5:4, scratch190, 23:22); - s(EmcPmacroDataPadTxCtrl, 9:8, scratch190, 25:24); - s(EmcPmacroDataPadTxCtrl, 13:12, scratch190, 27:26); - s(EmcPmacroDataPadTxCtrl, 16:16, scratch190, 28:28); - s(EmcPmacroDataPadTxCtrl, 21:20, scratch190, 30:29); - s(EmcPmacroDataPadTxCtrl, 24:24, scratch190, 31:31); - s(EmcPmacroDataPadTxCtrl, 27:25, scratch191, 2:0); + static const struct sdram_param parameters_0[] = { + s(EmcClockSource, 7:0, scratch6, 15:8), + s(EmcClockSourceDll, 7:0, scratch6, 23:16), + s(EmcClockSource, 31:29, scratch6, 26:24), + s(EmcClockSourceDll, 31:29, scratch6, 29:27), + s(EmcClockSourceDll, 11:10, scratch6, 31:30), + s(ClkRstControllerPllmMisc2Override, 9:8, scratch7, 1:0), + s(ClkRstControllerPllmMisc2Override, 2:1, scratch7, 3:2), + s(EmcZqCalLpDdr4WarmBoot, 31:30, scratch7, 5:4), + s(EmcClockSource, 15:15, scratch7, 6:6), + s(EmcClockSource, 26:26, scratch7, 7:7), + s(EmcClockSource, 20:20, scratch7, 8:8), + s(EmcClockSource, 19:19, scratch7, 9:9), + s(ClkRstControllerPllmMisc2Override, 13:13, scratch7, 10:10), + s(ClkRstControllerPllmMisc2Override, 12:12, scratch7, 11:11), + s(ClkRstControllerPllmMisc2Override, 11:11, scratch7, 12:12), + s(ClkRstControllerPllmMisc2Override, 10:10, scratch7, 13:13), + s(ClkRstControllerPllmMisc2Override, 5:5, scratch7, 14:14), + s(ClkRstControllerPllmMisc2Override, 4:4, scratch7, 15:15), + s(ClkRstControllerPllmMisc2Override, 3:3, scratch7, 16:16), + s(ClkRstControllerPllmMisc2Override, 0:0, scratch7, 17:17), + s(EmcZqCalLpDdr4WarmBoot, 1:0, scratch7, 19:18), + s(EmcZqCalLpDdr4WarmBoot, 4:4, scratch7, 20:20), + s(EmcOdtWrite, 5:0, scratch7, 26:21), + s(EmcOdtWrite, 11:8, scratch7, 30:27), + s(EmcOdtWrite, 31:31, scratch7, 31:31), + s(EmcFdpdCtrlCmdNoRamp, 0:0, scratch13, 30:30), + s(EmcCfgPipeClk, 0:0, scratch13, 31:31), + s(McEmemArbMisc2, 0:0, scratch14, 30:30), + s(McDaCfg0, 0:0, scratch14, 31:31), + s(EmcQRst, 6:0, scratch15, 26:20), + s(EmcQRst, 20:16, scratch15, 31:27), + s(EmcPmacroCmdTxDrv, 5:0, scratch16, 25:20), + s(EmcPmacroCmdTxDrv, 13:8, scratch16, 31:26), + s(EmcPmacroAutocalCfg0, 2:0, scratch17, 22:20), + s(EmcPmacroAutocalCfg0, 10:8, scratch17, 25:23), + s(EmcPmacroAutocalCfg0, 18:16, scratch17, 28:26), + s(EmcPmacroAutocalCfg0, 26:24, scratch17, 31:29), + s(EmcPmacroAutocalCfg1, 2:0, scratch18, 22:20), + s(EmcPmacroAutocalCfg1, 10:8, scratch18, 25:23), + s(EmcPmacroAutocalCfg1, 18:16, scratch18, 28:26), + s(EmcPmacroAutocalCfg1, 26:24, scratch18, 31:29), + s(EmcPmacroAutocalCfg2, 2:0, scratch19, 22:20), + s(EmcPmacroAutocalCfg2, 10:8, scratch19, 25:23), + s(EmcPmacroAutocalCfg2, 18:16, scratch19, 28:26), + s(EmcPmacroAutocalCfg2, 26:24, scratch19, 31:29), + s32(EmcCfgRsv,scratch22), + s32(EmcAutoCalConfig, scratch23), + s32(EmcAutoCalVrefSel0, scratch24), + s32(EmcPmacroBrickCtrlRfu1, scratch25), + s32(EmcPmacroBrickCtrlRfu2, scratch26), + s32(EmcPmcScratch1, scratch27), + s32(EmcPmcScratch2, scratch28), + s32(EmcPmcScratch3, scratch29), + s32(McEmemArbDaTurns, scratch30), + s(EmcFbioSpare, 31:24, scratch58, 7:0), + s(EmcFbioSpare, 23:16, scratch58, 15:8), + s(EmcFbioSpare, 15:8, scratch58, 23:16), + s(EmcFbioSpare, 7:2, scratch58, 29:24), + s(EmcFbioSpare, 0:0, scratch58, 30:30), + s(EmcDllCfg0, 29:0, scratch59, 29:0), + s(EmcPmacroDdllBypass, 11:0, scratch60, 11:0), + s(EmcPmacroDdllBypass, 27:13, scratch60, 26:12), + s(EmcPmacroDdllBypass, 31:29, scratch60, 29:27), + s(McEmemArbMisc0, 14:0, scratch61, 14:0), + s(McEmemArbMisc0, 30:16, scratch61, 29:15), + s(EmcFdpdCtrlCmd, 16:0, scratch62, 16:0), + s(EmcFdpdCtrlCmd, 31:20, scratch62, 28:17), + s(EmcAutoCalConfig2, 27:0, scratch63, 27:0), + s(EmcBurstRefreshNum, 3:0, scratch63, 31:28), + s(EmcPmacroZctrl, 27:0, scratch64, 27:0), + s(EmcTppd, 3:0, scratch64, 31:28), + s(EmcCfgDigDll, 10:0, scratch65, 10:0), + s(EmcCfgDigDll, 25:12, scratch65, 24:11), + s(EmcCfgDigDll, 27:27, scratch65, 25:25), + s(EmcCfgDigDll, 31:30, scratch65, 27:26), + s(EmcR2r, 3:0, scratch65, 31:28), + s(EmcFdpdCtrlDq, 16:0, scratch66, 16:0), + s(EmcFdpdCtrlDq, 28:20, scratch66, 25:17), + s(EmcFdpdCtrlDq, 31:30, scratch66, 27:26), + s(EmcW2w, 3:0, scratch66, 31:28), + s(EmcPmacroTxPwrd4, 13:0, scratch67, 13:0), + s(EmcPmacroTxPwrd4, 29:16, scratch67, 27:14), + s(EmcPmacroCommonPadTxCtrl, 3:0, scratch67, 31:28), + s(EmcPmacroTxPwrd5, 13:0, scratch68, 13:0), + s(EmcPmacroTxPwrd5, 29:16, scratch68, 27:14), + s(EmcPmacroDdllPwrd0, 4:0, scratch69, 4:0), + s(EmcPmacroDdllPwrd0, 12:6, scratch69, 11:5), + s(EmcPmacroDdllPwrd0, 20:14, scratch69, 18:12), + s(EmcPmacroDdllPwrd0, 28:22, scratch69, 25:19), + s(EmcPmacroDdllPwrd0, 31:30, scratch69, 27:26), + s(EmcCfg, 4:4, scratch69, 31:31), + s(EmcPmacroDdllPwrd1, 4:0, scratch70, 4:0), + s(EmcPmacroDdllPwrd1, 12:6, scratch70, 11:5), + s(EmcPmacroDdllPwrd1, 20:14, scratch70, 18:12), + s(EmcPmacroDdllPwrd1, 28:22, scratch70, 25:19), + s(EmcPmacroDdllPwrd1, 31:30, scratch70, 27:26), + s(EmcCfg, 5:5, scratch70, 31:31), + s(EmcPmacroDdllPwrd2, 4:0, scratch71, 4:0), + s(EmcPmacroDdllPwrd2, 12:6, scratch71, 11:5), + s(EmcPmacroDdllPwrd2, 20:14, scratch71, 18:12), + s(EmcPmacroDdllPwrd2, 28:22, scratch71, 25:19), + s(EmcPmacroDdllPwrd2, 31:30, scratch71, 27:26), + s(EmcFbioCfg5, 23:20, scratch71, 31:28), + s(EmcPmacroIbVrefDq_0, 6:0, scratch72, 6:0), + s(EmcPmacroIbVrefDq_0, 14:8, scratch72, 13:7), + s(EmcPmacroIbVrefDq_0, 22:16, scratch72, 20:14), + s(EmcPmacroIbVrefDq_0, 30:24, scratch72, 27:21), + s(EmcFbioCfg5, 15:13, scratch72, 30:28), + s(EmcCfg, 6:6, scratch72, 31:31), + s(EmcPmacroIbVrefDq_1, 6:0, scratch73, 6:0), + s(EmcPmacroIbVrefDq_1, 14:8, scratch73, 13:7), + s(EmcPmacroIbVrefDq_1, 22:16, scratch73, 20:14), + s(EmcPmacroIbVrefDq_1, 30:24, scratch73, 27:21), + s(EmcCfg2, 5:3, scratch73, 30:28), + s(EmcCfg, 7:7, scratch73, 31:31), + s(EmcPmacroIbVrefDqs_0, 6:0, scratch74, 6:0), + s(EmcPmacroIbVrefDqs_0, 14:8, scratch74, 13:7), + s(EmcPmacroIbVrefDqs_0, 22:16, scratch74, 20:14), + s(EmcPmacroIbVrefDqs_0, 30:24, scratch74, 27:21), + s(EmcCfg, 17:16, scratch74, 29:28), + s(EmcFbioCfg5, 1:0, scratch74, 31:30), + s(EmcPmacroIbVrefDqs_1, 6:0, scratch75, 6:0), + s(EmcPmacroIbVrefDqs_1, 14:8, scratch75, 13:7), + s(EmcPmacroIbVrefDqs_1, 22:16, scratch75, 20:14), + s(EmcPmacroIbVrefDqs_1, 30:24, scratch75, 27:21), + s(EmcFbioCfg5, 3:2, scratch75, 29:28), + s(EmcCfg2, 27:26, scratch75, 31:30), + s(EmcPmacroDdllShortCmd_0, 6:0, scratch76, 6:0), + s(EmcPmacroDdllShortCmd_0, 14:8, scratch76, 13:7), + s(EmcPmacroDdllShortCmd_0, 22:16, scratch76, 20:14), + s(EmcPmacroDdllShortCmd_0, 30:24, scratch76, 27:21), + s(EmcPmacroCmdPadTxCtrl, 3:2, scratch76, 29:28), + s(EmcPmacroCmdPadTxCtrl, 7:6, scratch76, 31:30), + s(EmcPmacroDdllShortCmd_1, 6:0, scratch77, 6:0), + s(EmcPmacroDdllShortCmd_1, 14:8, scratch77, 13:7), + s(EmcPmacroDdllShortCmd_1, 22:16, scratch77, 20:14), + s(EmcPmacroDdllShortCmd_1, 30:24, scratch77, 27:21), + s(EmcPmacroCmdPadTxCtrl, 11:10, scratch77, 29:28), + s(EmcPmacroCmdPadTxCtrl, 15:14, scratch77, 31:30), + s(EmcAutoCalChannel, 5:0, scratch78, 5:0), + s(EmcAutoCalChannel, 11:8, scratch78, 9:6), + s(EmcAutoCalChannel, 27:16, scratch78, 21:10), + s(EmcAutoCalChannel, 31:29, scratch78, 24:22), + s(EmcConfigSampleDelay, 6:0, scratch78, 31:25), + s(EmcPmacroRxTerm, 5:0, scratch79, 5:0), + s(EmcPmacroRxTerm, 13:8, scratch79, 11:6), + s(EmcPmacroRxTerm, 21:16, scratch79, 17:12), + s(EmcPmacroRxTerm, 29:24, scratch79, 23:18), + s(EmcRc, 7:0, scratch79, 31:24), + s(EmcPmacroDqTxDrv, 5:0, scratch80, 5:0), + s(EmcPmacroDqTxDrv, 13:8, scratch80, 11:6), + s(EmcPmacroDqTxDrv, 21:16, scratch80, 17:12), + s(EmcPmacroDqTxDrv, 29:24, scratch80, 23:18), + s(EmcSelDpdCtrl, 5:2, scratch80, 27:24), + s(EmcSelDpdCtrl, 8:8, scratch80, 28:28), + s(EmcSelDpdCtrl, 18:16, scratch80, 31:29), + s(EmcPmacroCaTxDrv, 5:0, scratch81, 5:0), + s(EmcPmacroCaTxDrv, 13:8, scratch81, 11:6), + s(EmcPmacroCaTxDrv, 21:16, scratch81, 17:12), + s(EmcPmacroCaTxDrv, 29:24, scratch81, 23:18), + s(EmcObdly, 5:0, scratch81, 29:24), + s(EmcObdly, 29:28, scratch81, 31:30), + s(EmcZcalInterval, 23:10, scratch82, 13:0), + s(EmcZcalInterval, 9:0, scratch82, 23:14), + s(EmcPmacroCmdRxTermMode, 1:0, scratch82, 25:24), + s(EmcPmacroCmdRxTermMode, 5:4, scratch82, 27:26), + s(EmcPmacroCmdRxTermMode, 9:8, scratch82, 29:28), + s(EmcPmacroCmdRxTermMode, 13:12, scratch82, 31:30), + s(EmcDataBrlshft0, 23:0, scratch83, 23:0), + s(EmcPmacroDataRxTermMode, 1:0, scratch83, 25:24), + s(EmcPmacroDataRxTermMode, 5:4, scratch83, 27:26), + s(EmcPmacroDataRxTermMode, 9:8, scratch83, 29:28), + s(EmcPmacroDataRxTermMode, 13:12, scratch83, 31:30), + s(EmcDataBrlshft1, 23:0, scratch84, 23:0), + s(McEmemArbTimingRc, 7:0, scratch84, 31:24), + s(EmcDqsBrlshft0, 23:0, scratch85, 23:0), + s(McEmemArbRsv, 7:0, scratch85, 31:24), + s(EmcDqsBrlshft1, 23:0, scratch86, 23:0), + s(EmcCfgPipe2, 11:0, scratch87, 11:0), + s(EmcCfgPipe2, 27:16, scratch87, 23:12), + s(EmcCfgPipe1, 11:0, scratch88, 11:0), + s(EmcCfgPipe1, 27:16, scratch88, 23:12), + s(EmcPmacroCmdCtrl0, 5:0, scratch89, 5:0), + s(EmcPmacroCmdCtrl0, 13:8, scratch89, 11:6), + s(EmcPmacroCmdCtrl0, 21:16, scratch89, 17:12), + s(EmcPmacroCmdCtrl0, 29:24, scratch89, 23:18), + s(EmcPmacroCmdCtrl1, 5:0, scratch90, 5:0), + s(EmcPmacroCmdCtrl1, 13:8, scratch90, 11:6), + s(EmcPmacroCmdCtrl1, 21:16, scratch90, 17:12), + s(EmcPmacroCmdCtrl1, 29:24, scratch90, 23:18), + s(EmcRas, 6:0, scratch90, 30:24), + s(EmcCfg, 8:8, scratch90, 31:31), + s(EmcPmacroVttgenCtrl2, 23:0, scratch91, 23:0), + s(EmcW2p, 6:0, scratch91, 30:24), + s(EmcCfg, 9:9, scratch91, 31:31), + s(EmcPmacroCmdPadRxCtrl, 2:0, scratch92, 2:0), + s(EmcPmacroCmdPadRxCtrl, 5:4, scratch92, 4:3), + s(EmcPmacroCmdPadRxCtrl, 10:8, scratch92, 7:5), + s(EmcPmacroCmdPadRxCtrl, 22:12, scratch92, 18:8), + s(EmcPmacroCmdPadRxCtrl, 28:24, scratch92, 23:19), + s(EmcQSafe, 6:0, scratch92, 30:24), + s(EmcCfg, 18:18, scratch92, 31:31), + s(EmcPmacroDataPadRxCtrl, 2:0, scratch93, 2:0), + s(EmcPmacroDataPadRxCtrl, 5:4, scratch93, 4:3), + s(EmcPmacroDataPadRxCtrl, 10:8, scratch93, 7:5), + s(EmcPmacroDataPadRxCtrl, 22:12, scratch93, 18:8), + s(EmcPmacroDataPadRxCtrl, 28:24, scratch93, 23:19), + s(EmcRdv, 6:0, scratch93, 30:24), + s(EmcCfg, 21:21, scratch93, 31:31), + s(McEmemArbDaCovers, 23:0, scratch94, 23:0), + s(EmcRw2Pden, 6:0, scratch94, 30:24), + s(EmcCfg, 22:22, scratch94, 31:31), + s(EmcPmacroCmdCtrl2, 5:0, scratch95, 5:0), + s(EmcPmacroCmdCtrl2, 13:9, scratch95, 10:6), + s(EmcPmacroCmdCtrl2, 21:16, scratch95, 16:11), + s(EmcPmacroCmdCtrl2, 29:24, scratch95, 22:17), + s(EmcRfcPb, 8:0, scratch95, 31:23), + s(EmcPmacroQuseDdllRank0_0, 10:0, scratch96, 10:0), + s(EmcPmacroQuseDdllRank0_0, 26:16, scratch96, 21:11), + s(EmcCfgUpdate, 2:0, scratch96, 24:22), + s(EmcCfgUpdate, 10:8, scratch96, 27:25), + s(EmcCfgUpdate, 31:28, scratch96, 31:28), + s(EmcPmacroQuseDdllRank0_1, 10:0, scratch97, 10:0), + s(EmcPmacroQuseDdllRank0_1, 26:16, scratch97, 21:11), + s(EmcRfc, 9:0, scratch97, 31:22), + s(EmcPmacroQuseDdllRank0_2, 10:0, scratch98, 10:0), + s(EmcPmacroQuseDdllRank0_2, 26:16, scratch98, 21:11), + s(EmcTxsr, 9:0, scratch98, 31:22), + s(EmcPmacroQuseDdllRank0_3, 10:0, scratch99, 10:0), + s(EmcPmacroQuseDdllRank0_3, 26:16, scratch99, 21:11), + s(EmcMc2EmcQ, 2:0, scratch99, 24:22), + s(EmcMc2EmcQ, 10:8, scratch99, 27:25), + s(EmcMc2EmcQ, 27:24, scratch99, 31:28), + s(EmcPmacroQuseDdllRank0_4, 10:0, scratch100, 10:0), + s(EmcPmacroQuseDdllRank0_4, 26:16, scratch100, 21:11), + s(McEmemArbRing1Throttle, 4:0, scratch100, 26:22), + s(McEmemArbRing1Throttle, 20:16, scratch100, 31:27), + s(EmcPmacroQuseDdllRank0_5, 10:0, scratch101, 10:0), + s(EmcPmacroQuseDdllRank0_5, 26:16, scratch101, 21:11), + s(EmcPmacroQuseDdllRank1_0, 10:0, scratch102, 10:0), + s(EmcPmacroQuseDdllRank1_0, 26:16, scratch102, 21:11), + s(EmcAr2Pden, 8:0, scratch102, 30:22), + s(EmcCfg, 23:23, scratch102, 31:31), + s(EmcPmacroQuseDdllRank1_1, 10:0, scratch103, 10:0), + s(EmcPmacroQuseDdllRank1_1, 26:16, scratch103, 21:11), + s(EmcRfcSlr, 8:0, scratch103, 30:22), + s(EmcCfg, 24:24, scratch103, 31:31), + s(EmcPmacroQuseDdllRank1_2, 10:0, scratch104, 10:0), + s(EmcPmacroQuseDdllRank1_2, 26:16, scratch104, 21:11), + s(EmcIbdly, 6:0, scratch104, 28:22), + s(EmcIbdly, 29:28, scratch104, 30:29), + s(EmcCfg, 25:25, scratch104, 31:31), + s(EmcPmacroQuseDdllRank1_3, 10:0, scratch105, 10:0), + s(EmcPmacroQuseDdllRank1_3, 26:16, scratch105, 21:11), + s(McEmemArbTimingRFCPB, 8:0, scratch105, 30:22), + s(EmcCfg, 26:26, scratch105, 31:31), + s(EmcPmacroQuseDdllRank1_4, 10:0, scratch106, 10:0), + s(EmcPmacroQuseDdllRank1_4, 26:16, scratch106, 21:11), + s(EmcTfaw, 6:0, scratch106, 28:22), + s(EmcPmacroDataPadTxCtrl, 3:2, scratch106, 30:29), + s(EmcCfg, 28:28, scratch106, 31:31), + s(EmcPmacroQuseDdllRank1_5, 10:0, scratch107, 10:0), + s(EmcPmacroQuseDdllRank1_5, 26:16, scratch107, 21:11), + s(EmcTClkStable, 6:0, scratch107, 28:22), + s(EmcPmacroDataPadTxCtrl, 7:6, scratch107, 30:29), + s(EmcCfg, 29:29, scratch107, 31:31), + s(EmcPmacroObDdllLongDqRank0_0, 10:0, scratch108, 10:0), + s(EmcPmacroObDdllLongDqRank0_0, 26:16, scratch108, 21:11), + s(EmcPdex2Mrr, 6:0, scratch108, 28:22), + s(EmcPmacroDataPadTxCtrl, 11:10, scratch108, 30:29), + s(EmcCfg, 30:30, scratch108, 31:31), + s(EmcPmacroObDdllLongDqRank0_1, 10:0, scratch109, 10:0), + s(EmcPmacroObDdllLongDqRank0_1, 26:16, scratch109, 21:11), + s(EmcRdvMask, 6:0, scratch109, 28:22), + s(EmcPmacroDataPadTxCtrl, 15:14, scratch109, 30:29), + s(EmcCfg, 31:31, scratch109, 31:31), + s(EmcPmacroObDdllLongDqRank0_2, 10:0, scratch110, 10:0), + s(EmcPmacroObDdllLongDqRank0_2, 26:16, scratch110, 21:11), + s(EmcRdvEarlyMask, 6:0, scratch110, 28:22), + s(EmcFbioCfg5, 4:4, scratch110, 29:29), + s(EmcFbioCfg5, 8:8, scratch110, 30:30), + s(EmcFbioCfg5, 10:10, scratch110, 31:31), + s(EmcPmacroObDdllLongDqRank0_3, 10:0, scratch111, 10:0), + s(EmcPmacroObDdllLongDqRank0_3, 26:16, scratch111, 21:11), + s(EmcRdvEarly, 6:0, scratch111, 28:22), + s(EmcFbioCfg5, 12:12, scratch111, 29:29), + s(EmcFbioCfg5, 25:24, scratch111, 31:30), + s(EmcPmacroObDdllLongDqRank0_4, 10:0, scratch112, 10:0), + s(EmcPmacroObDdllLongDqRank0_4, 26:16, scratch112, 21:11), + s(EmcPmacroDdllShortCmd_2, 6:0, scratch112, 28:22), + s(EmcFbioCfg5, 28:26, scratch112, 31:29), + s(EmcPmacroObDdllLongDqRank0_5, 10:0, scratch113, 10:0), + s(EmcPmacroObDdllLongDqRank0_5, 26:16, scratch113, 21:11), + s(McEmemArbTimingRp, 6:0, scratch113, 28:22), + s(EmcFbioCfg5, 31:30, scratch113, 30:29), + s(EmcCfg2, 0:0, scratch113, 31:31), + s(EmcPmacroObDdllLongDqRank1_0, 10:0, scratch114, 10:0), + s(EmcPmacroObDdllLongDqRank1_0, 26:16, scratch114, 21:11), + s(McEmemArbTimingRas, 6:0, scratch114, 28:22), + s(EmcCfg2, 2:1, scratch114, 30:29), + s(EmcCfg2, 7:7, scratch114, 31:31), + s(EmcPmacroObDdllLongDqRank1_1, 10:0, scratch115, 10:0), + s(EmcPmacroObDdllLongDqRank1_1, 26:16, scratch115, 21:11), + s(McEmemArbTimingFaw, 6:0, scratch115, 28:22), + s(EmcCfg2, 11:10, scratch115, 30:29), + s(EmcCfg2, 14:14, scratch115, 31:31), + s(EmcPmacroObDdllLongDqRank1_2, 10:0, scratch123, 10:0), + s(EmcPmacroObDdllLongDqRank1_2, 26:16, scratch123, 21:11), + s(McEmemArbTimingRap2Pre, 6:0, scratch123, 28:22), + s(EmcCfg2, 16:15, scratch123, 30:29), + s(EmcCfg2, 20:20, scratch123, 31:31), + s(EmcPmacroObDdllLongDqRank1_3, 10:0, scratch124, 10:0), + s(EmcPmacroObDdllLongDqRank1_3, 26:16, scratch124, 21:11), + s(McEmemArbTimingWap2Pre, 6:0, scratch124, 28:22), + s(EmcCfg2, 24:22, scratch124, 31:29), + s(EmcPmacroObDdllLongDqRank1_4, 10:0, scratch125, 10:0), + s(EmcPmacroObDdllLongDqRank1_4, 26:16, scratch125, 21:11), + s(McEmemArbTimingR2W, 6:0, scratch125, 28:22), + s(EmcCfg2, 25:25, scratch125, 29:29), + s(EmcCfg2, 29:28, scratch125, 31:30), + s(EmcPmacroObDdllLongDqRank1_5, 10:0, scratch126, 10:0), + s(EmcPmacroObDdllLongDqRank1_5, 26:16, scratch126, 21:11), + s(McEmemArbTimingW2R, 6:0, scratch126, 28:22), + s(EmcCfg2, 31:30, scratch126, 30:29), + s(EmcCfgPipe, 0:0, scratch126, 31:31), + s(EmcPmacroObDdllLongDqsRank0_0, 10:0, scratch127, 10:0), + s(EmcPmacroObDdllLongDqsRank0_0, 26:16, scratch127, 21:11), + s(EmcRp, 5:0, scratch127, 27:22), + s(EmcCfgPipe, 4:1, scratch127, 31:28), + s(EmcPmacroObDdllLongDqsRank0_1, 10:0, scratch128, 10:0), + s(EmcPmacroObDdllLongDqsRank0_1, 26:16, scratch128, 21:11), + s(EmcR2w, 5:0, scratch128, 27:22), + s(EmcCfgPipe, 8:5, scratch128, 31:28), + s(EmcPmacroObDdllLongDqsRank0_2, 10:0, scratch129, 10:0), + s(EmcPmacroObDdllLongDqsRank0_2, 26:16, scratch129, 21:11), + s(EmcW2r, 5:0, scratch129, 27:22), + s(EmcCfgPipe, 11:9, scratch129, 30:28), + s(EmcCfgPipe, 16:16, scratch129, 31:31), + s(EmcPmacroObDdllLongDqsRank0_3, 10:0, scratch130, 10:0), + s(EmcPmacroObDdllLongDqsRank0_3, 26:16, scratch130, 21:11), + s(EmcR2p, 5:0, scratch130, 27:22), + s(EmcCfgPipe, 20:17, scratch130, 31:28), + s(EmcPmacroObDdllLongDqsRank0_4, 10:0, scratch131, 10:0), + s(EmcPmacroObDdllLongDqsRank0_4, 26:16, scratch131, 21:11), + s(EmcCcdmw, 5:0, scratch131, 27:22), + s(EmcCfgPipe, 24:21, scratch131, 31:28), + s(EmcPmacroObDdllLongDqsRank0_5, 10:0, scratch132, 10:0), + s(EmcPmacroObDdllLongDqsRank0_5, 26:16, scratch132, 21:11), + s(EmcRdRcd, 5:0, scratch132, 27:22), + s(EmcCfgPipe, 27:25, scratch132, 30:28), + s(EmcPmacroTxPwrd0, 0:0, scratch132, 31:31), + s(EmcPmacroObDdllLongDqsRank1_0, 10:0, scratch133, 10:0), + s(EmcPmacroObDdllLongDqsRank1_0, 26:16, scratch133, 21:11), + s(EmcWrRcd, 5:0, scratch133, 27:22), + s(EmcPmacroTxPwrd0, 4:1, scratch133, 31:28), + s(EmcPmacroObDdllLongDqsRank1_1, 10:0, scratch134, 10:0), + s(EmcPmacroObDdllLongDqsRank1_1, 26:16, scratch134, 21:11), + s(EmcWdv, 5:0, scratch134, 27:22), + s(EmcPmacroTxPwrd0, 8:5, scratch134, 31:28), + s(EmcPmacroObDdllLongDqsRank1_2, 10:0, scratch135, 10:0), + s(EmcPmacroObDdllLongDqsRank1_2, 26:16, scratch135, 21:11), + s(EmcQUse, 5:0, scratch135, 27:22), + s(EmcPmacroTxPwrd0, 12:9, scratch135, 31:28), + s(EmcPmacroObDdllLongDqsRank1_3, 10:0, scratch136, 10:0), + s(EmcPmacroObDdllLongDqsRank1_3, 26:16, scratch136, 21:11), + s(EmcPdEx2Wr, 5:0, scratch136, 27:22), + s(EmcPmacroTxPwrd0, 13:13, scratch136, 28:28), + s(EmcPmacroTxPwrd0, 18:16, scratch136, 31:29), + s(EmcPmacroObDdllLongDqsRank1_4, 10:0, scratch137, 10:0), + s(EmcPmacroObDdllLongDqsRank1_4, 26:16, scratch137, 21:11), + s(EmcPdEx2Rd, 5:0, scratch137, 27:22), + s(EmcPmacroTxPwrd0, 22:19, scratch137, 31:28), + s(EmcPmacroObDdllLongDqsRank1_5, 10:0, scratch138, 10:0), + s(EmcPmacroObDdllLongDqsRank1_5, 26:16, scratch138, 21:11), + s(EmcPdex2Cke, 5:0, scratch138, 27:22), + s(EmcPmacroTxPwrd0, 26:23, scratch138, 31:28), + s(EmcPmacroIbDdllLongDqsRank0_0, 10:0, scratch139, 10:0), + s(EmcPmacroIbDdllLongDqsRank0_0, 26:16, scratch139, 21:11), + s(EmcPChg2Pden, 5:0, scratch139, 27:22), + s(EmcPmacroTxPwrd0, 29:27, scratch139, 30:28), + s(EmcPmacroTxPwrd1, 0:0, scratch139, 31:31), + s(EmcPmacroIbDdllLongDqsRank0_1, 10:0, scratch140, 10:0), + s(EmcPmacroIbDdllLongDqsRank0_1, 26:16, scratch140, 21:11), + s(EmcAct2Pden, 5:0, scratch140, 27:22), + s(EmcPmacroTxPwrd1, 4:1, scratch140, 31:28), + s(EmcPmacroIbDdllLongDqsRank0_2, 10:0, scratch141, 10:0), + s(EmcPmacroIbDdllLongDqsRank0_2, 26:16, scratch141, 21:11), + s(EmcCke2Pden, 5:0, scratch141, 27:22), + s(EmcPmacroTxPwrd1, 8:5, scratch141, 31:28), + s(EmcPmacroIbDdllLongDqsRank0_3, 10:0, scratch142, 10:0), + s(EmcPmacroIbDdllLongDqsRank0_3, 26:16, scratch142, 21:11), + s(EmcTcke, 5:0, scratch142, 27:22), + s(EmcPmacroTxPwrd1, 12:9, scratch142, 31:28), + s(EmcPmacroIbDdllLongDqsRank1_0, 10:0, scratch143, 10:0), + s(EmcPmacroIbDdllLongDqsRank1_0, 26:16, scratch143, 21:11), + s(EmcTrpab, 5:0, scratch143, 27:22), + s(EmcPmacroTxPwrd1, 13:13, scratch143, 28:28), + s(EmcPmacroTxPwrd1, 18:16, scratch143, 31:29), + s(EmcPmacroIbDdllLongDqsRank1_1, 10:0, scratch144, 10:0), + s(EmcPmacroIbDdllLongDqsRank1_1, 26:16, scratch144, 21:11), + s(EmcClkenOverride, 3:1, scratch144, 24:22), + s(EmcClkenOverride, 8:6, scratch144, 27:25), + s(EmcPmacroTxPwrd1, 22:19, scratch144, 31:28), + s(EmcPmacroIbDdllLongDqsRank1_2, 10:0, scratch145, 10:0), + s(EmcPmacroIbDdllLongDqsRank1_2, 26:16, scratch145, 21:11), + s(EmcEInput, 5:0, scratch145, 27:22), + s(EmcPmacroTxPwrd1, 26:23, scratch145, 31:28), + s(EmcPmacroIbDdllLongDqsRank1_3, 10:0, scratch146, 10:0), + s(EmcPmacroIbDdllLongDqsRank1_3, 26:16, scratch146, 21:11), + s(EmcEInputDuration, 5:0, scratch146, 27:22), + s(EmcPmacroTxPwrd1, 29:27, scratch146, 30:28), + s(EmcPmacroTxPwrd2, 0:0, scratch146, 31:31), + s(EmcPmacroDdllLongCmd_0, 10:0, scratch147, 10:0), + s(EmcPmacroDdllLongCmd_0, 26:16, scratch147, 21:11), + s(EmcPutermExtra, 5:0, scratch147, 27:22), + s(EmcPmacroTxPwrd2, 4:1, scratch147, 31:28), + s(EmcPmacroDdllLongCmd_1, 10:0, scratch148, 10:0), + s(EmcPmacroDdllLongCmd_1, 26:16, scratch148, 21:11), + s(EmcTckesr, 5:0, scratch148, 27:22), + s(EmcPmacroTxPwrd2, 8:5, scratch148, 31:28), + s(EmcPmacroDdllLongCmd_2, 10:0, scratch149, 10:0), + s(EmcPmacroDdllLongCmd_2, 26:16, scratch149, 21:11), + s(EmcTpd, 5:0, scratch149, 27:22), + s(EmcPmacroTxPwrd2, 12:9, scratch149, 31:28), + s(EmcPmacroDdllLongCmd_3, 10:0, scratch150, 10:0), + s(EmcPmacroDdllLongCmd_3, 26:16, scratch150, 21:11), + s(EmcWdvMask, 5:0, scratch150, 27:22), + s(EmcPmacroTxPwrd2, 13:13, scratch150, 28:28), + s(EmcPmacroTxPwrd2, 18:16, scratch150, 31:29), + s(McEmemArbCfg, 8:0, scratch151, 8:0), + s(McEmemArbCfg, 20:16, scratch151, 13:9), + s(McEmemArbCfg, 31:24, scratch151, 21:14), + s(EmcWdvChk, 5:0, scratch151, 27:22), + s(EmcPmacroTxPwrd2, 22:19, scratch151, 31:28), + s(McEmemArbMisc1, 12:0, scratch152, 12:0), + s(McEmemArbMisc1, 25:21, scratch152, 17:13), + s(McEmemArbMisc1, 31:28, scratch152, 21:18), + s(EmcCmdBrlshft0, 5:0, scratch152, 27:22), + s(EmcPmacroTxPwrd2, 26:23, scratch152, 31:28), + s(EmcMrsWaitCnt2, 9:0, scratch153, 9:0), + s(EmcMrsWaitCnt2, 26:16, scratch153, 20:10), + s(EmcPmacroIbRxrt, 10:0, scratch153, 31:21), + s(EmcMrsWaitCnt, 9:0, scratch154, 9:0), + s(EmcMrsWaitCnt, 26:16, scratch154, 20:10), + s(EmcPmacroDdllLongCmd_4, 10:0, scratch154, 31:21), + s(EmcAutoCalInterval, 20:0, scratch155, 20:0), + s(McEmemArbOutstandingReq, 8:0, scratch155, 29:21), + s(McEmemArbOutstandingReq, 31:30, scratch155, 31:30), + s(McEmemArbRefpbHpCtrl, 6:0, scratch156, 6:0), + s(McEmemArbRefpbHpCtrl, 14:8, scratch156, 13:7), + s(McEmemArbRefpbHpCtrl, 22:16, scratch156, 20:14), + s(EmcCmdBrlshft1, 5:0, scratch156, 26:21), + s(EmcRrd, 4:0, scratch156, 31:27), + s(EmcQuseBrlshft0, 19:0, scratch157, 19:0), + s(EmcFbioCfg8, 27:16, scratch157, 31:20), + s(EmcQuseBrlshft1, 19:0, scratch158, 19:0), + s(EmcTxsrDll, 11:0, scratch158, 31:20), + s(EmcQuseBrlshft2, 19:0, scratch159, 19:0), + s(EmcTxdsrvttgen, 11:0, scratch159, 31:20), + s(EmcQuseBrlshft3, 19:0, scratch160, 19:0), + s(EmcPmacroVttgenCtrl0, 3:0, scratch160, 23:20), + s(EmcPmacroVttgenCtrl0, 11:8, scratch160, 27:24), + s(EmcPmacroVttgenCtrl0, 19:16, scratch160, 31:28), + s(EmcPmacroVttgenCtrl1, 19:0, scratch161, 19:0), + s(EmcCmdBrlshft2, 5:0, scratch161, 25:20), + s(EmcCmdBrlshft3, 5:0, scratch161, 31:26), + s(EmcAutoCalConfig3, 5:0, scratch162, 5:0), + s(EmcAutoCalConfig3, 13:8, scratch162, 11:6), + s(EmcAutoCalConfig3, 18:16, scratch162, 14:12), + s(EmcAutoCalConfig3, 22:20, scratch162, 17:15), + s(EmcTRefBw, 13:0, scratch162, 31:18), + s(EmcAutoCalConfig4, 5:0, scratch163, 5:0), + s(EmcAutoCalConfig4, 13:8, scratch163, 11:6), + s(EmcAutoCalConfig4, 18:16, scratch163, 14:12), + s(EmcAutoCalConfig4, 22:20, scratch163, 17:15), + s(EmcQpop, 6:0, scratch163, 24:18), + s(EmcQpop, 22:16, scratch163, 31:25), + s(EmcAutoCalConfig5, 5:0, scratch164, 5:0), + s(EmcAutoCalConfig5, 13:8, scratch164, 11:6), + s(EmcAutoCalConfig5, 18:16, scratch164, 14:12), + s(EmcAutoCalConfig5, 22:20, scratch164, 17:15), + s(EmcPmacroAutocalCfgCommon, 5:0, scratch164, 23:18), + s(EmcPmacroAutocalCfgCommon, 13:8, scratch164, 29:24), + s(EmcPmacroAutocalCfgCommon, 16:16, scratch164, 30:30), + s(EmcPmacroTxPwrd2, 27:27, scratch164, 31:31), + s(EmcAutoCalConfig6, 5:0, scratch165, 5:0), + s(EmcAutoCalConfig6, 13:8, scratch165, 11:6), + s(EmcAutoCalConfig6, 18:16, scratch165, 14:12), + s(EmcAutoCalConfig6, 22:20, scratch165, 17:15), + s(EmcWev, 5:0, scratch165, 23:18), + s(EmcWsv, 5:0, scratch165, 29:24), + s(EmcPmacroTxPwrd2, 29:28, scratch165, 31:30), + s(EmcAutoCalConfig7, 5:0, scratch166, 5:0), + s(EmcAutoCalConfig7, 13:8, scratch166, 11:6), + s(EmcAutoCalConfig7, 18:16, scratch166, 14:12), + s(EmcAutoCalConfig7, 22:20, scratch166, 17:15), + s(EmcCfg3, 2:0, scratch166, 20:18), + s(EmcCfg3, 6:4, scratch166, 23:21), + s(EmcQuseWidth, 3:0, scratch166, 27:24), + s(EmcQuseWidth, 29:28, scratch166, 29:28), + s(EmcPmacroTxPwrd3, 1:0, scratch166, 31:30), + s(EmcAutoCalConfig8, 5:0, scratch167, 5:0), + s(EmcAutoCalConfig8, 13:8, scratch167, 11:6), + s(EmcAutoCalConfig8, 18:16, scratch167, 14:12), + s(EmcAutoCalConfig8, 22:20, scratch167, 17:15), + s(EmcPmacroBgBiasCtrl0, 2:0, scratch167, 20:18), + s(EmcPmacroBgBiasCtrl0, 6:4, scratch167, 23:21), + s(McEmemArbTimingRcd, 5:0, scratch167, 29:24), + s(EmcPmacroTxPwrd3, 3:2, scratch167, 31:30), + s(EmcXm2CompPadCtrl2, 17:0, scratch168, 17:0), + s(McEmemArbTimingCcdmw, 5:0, scratch168, 23:18), + s(McEmemArbOverride, 27:27, scratch168, 24:24), + s(McEmemArbOverride, 26:26, scratch168, 25:25), + s(McEmemArbOverride, 16:16, scratch168, 26:26), + s(McEmemArbOverride, 10:10, scratch168, 27:27), + s(McEmemArbOverride, 4:4, scratch168, 28:28), + s(McEmemArbOverride, 3:3, scratch168, 29:29), + s(EmcPmacroTxPwrd3, 5:4, scratch168, 31:30), + s(EmcXm2CompPadCtrl3, 17:0, scratch169, 17:0), + s(EmcRext, 4:0, scratch169, 22:18), + s(EmcTClkStop, 4:0, scratch169, 27:23), + s(EmcPmacroTxPwrd3, 9:6, scratch169, 31:28), + s(EmcZcalWaitCnt, 10:0, scratch170, 10:0), + s(EmcZcalWaitCnt, 21:16, scratch170, 16:11), + s(EmcZcalWaitCnt, 31:31, scratch170, 17:17), + s(EmcWext, 4:0, scratch170, 22:18), + s(EmcRefctrl2, 0:0, scratch170, 23:23), + s(EmcRefctrl2, 26:24, scratch170, 26:24), + s(EmcRefctrl2, 31:31, scratch170, 27:27), + s(EmcPmacroTxPwrd3, 13:10, scratch170, 31:28), + s(EmcZcalMrwCmd, 7:0, scratch171, 7:0), + s(EmcZcalMrwCmd, 23:16, scratch171, 15:8), + s(EmcZcalMrwCmd, 31:30, scratch171, 17:16), + s(EmcWeDuration, 4:0, scratch171, 22:18), + s(EmcWsDuration, 4:0, scratch171, 27:23), + s(EmcPmacroTxPwrd3, 19:16, scratch171, 31:28), + s(EmcSwizzleRank0Byte0, 2:0, scratch172, 2:0), + s(EmcSwizzleRank0Byte0, 6:4, scratch172, 5:3), + s(EmcSwizzleRank0Byte0, 10:8, scratch172, 8:6), + s(EmcSwizzleRank0Byte0, 14:12, scratch172, 11:9), + s(EmcSwizzleRank0Byte0, 18:16, scratch172, 14:12), + s(EmcSwizzleRank0Byte0, 22:20, scratch172, 17:15), + s(EmcPutermWidth, 31:31, scratch172, 18:18), + s(EmcPutermWidth, 3:0, scratch172, 22:19), + s(McEmemArbTimingRrd, 4:0, scratch172, 27:23), + s(EmcPmacroTxPwrd3, 23:20, scratch172, 31:28), + s(EmcSwizzleRank0Byte1, 2:0, scratch173, 2:0), + s(EmcSwizzleRank0Byte1, 6:4, scratch173, 5:3), + s(EmcSwizzleRank0Byte1, 10:8, scratch173, 8:6), + s(EmcSwizzleRank0Byte1, 14:12, scratch173, 11:9), + s(EmcSwizzleRank0Byte1, 18:16, scratch173, 14:12), + s(EmcSwizzleRank0Byte1, 22:20, scratch173, 17:15), + s(McEmemArbTimingR2R, 4:0, scratch173, 22:18), + s(McEmemArbTimingW2W, 4:0, scratch173, 27:23), + s(EmcPmacroTxPwrd3, 27:24, scratch173, 31:28), + s(EmcSwizzleRank0Byte2, 2:0, scratch174, 2:0), + s(EmcSwizzleRank0Byte2, 6:4, scratch174, 5:3), + s(EmcSwizzleRank0Byte2, 10:8, scratch174, 8:6), + s(EmcSwizzleRank0Byte2, 14:12, scratch174, 11:9), + s(EmcSwizzleRank0Byte2, 18:16, scratch174, 14:12), + s(EmcSwizzleRank0Byte2, 22:20, scratch174, 17:15), + s(EmcPmacroTxPwrd3, 29:28, scratch174, 19:18), + s(EmcPmacroTxSelClkSrc0, 11:0, scratch174, 31:20), + s(EmcSwizzleRank0Byte3, 2:0, scratch175, 2:0), + s(EmcSwizzleRank0Byte3, 6:4, scratch175, 5:3), + s(EmcSwizzleRank0Byte3, 10:8, scratch175, 8:6), + s(EmcSwizzleRank0Byte3, 14:12, scratch175, 11:9), + s(EmcSwizzleRank0Byte3, 18:16, scratch175, 14:12), + s(EmcSwizzleRank0Byte3, 22:20, scratch175, 17:15), + s(EmcPmacroTxSelClkSrc0, 27:16, scratch175, 29:18), + s(EmcPmacroTxSelClkSrc1, 1:0, scratch175, 31:30), + s(EmcSwizzleRank1Byte0, 2:0, scratch176, 2:0), + s(EmcSwizzleRank1Byte0, 6:4, scratch176, 5:3), + s(EmcSwizzleRank1Byte0, 10:8, scratch176, 8:6), + s(EmcSwizzleRank1Byte0, 14:12, scratch176, 11:9), + s(EmcSwizzleRank1Byte0, 18:16, scratch176, 14:12), + s(EmcSwizzleRank1Byte0, 22:20, scratch176, 17:15), + s(EmcPmacroTxSelClkSrc1, 11:2, scratch176, 27:18), + s(EmcPmacroTxSelClkSrc1, 19:16, scratch176, 31:28), + s(EmcSwizzleRank1Byte1, 2:0, scratch177, 2:0), + s(EmcSwizzleRank1Byte1, 6:4, scratch177, 5:3), + s(EmcSwizzleRank1Byte1, 10:8, scratch177, 8:6), + s(EmcSwizzleRank1Byte1, 14:12, scratch177, 11:9), + s(EmcSwizzleRank1Byte1, 18:16, scratch177, 14:12), + s(EmcSwizzleRank1Byte1, 22:20, scratch177, 17:15), + s(EmcPmacroTxSelClkSrc1, 27:20, scratch177, 25:18), + s(EmcPmacroTxSelClkSrc3, 5:0, scratch177, 31:26), + s(EmcSwizzleRank1Byte2, 2:0, scratch178, 2:0), + s(EmcSwizzleRank1Byte2, 6:4, scratch178, 5:3), + s(EmcSwizzleRank1Byte2, 10:8, scratch178, 8:6), + s(EmcSwizzleRank1Byte2, 14:12, scratch178, 11:9), + s(EmcSwizzleRank1Byte2, 18:16, scratch178, 14:12), + s(EmcSwizzleRank1Byte2, 22:20, scratch178, 17:15), + s(EmcPmacroTxSelClkSrc3, 11:6, scratch178, 23:18), + s(EmcPmacroTxSelClkSrc3, 23:16, scratch178, 31:24), + s(EmcSwizzleRank1Byte3, 2:0, scratch179, 2:0), + s(EmcSwizzleRank1Byte3, 6:4, scratch179, 5:3), + s(EmcSwizzleRank1Byte3, 10:8, scratch179, 8:6), + s(EmcSwizzleRank1Byte3, 14:12, scratch179, 11:9), + s(EmcSwizzleRank1Byte3, 18:16, scratch179, 14:12), + s(EmcSwizzleRank1Byte3, 22:20, scratch179, 17:15), + s(EmcPmacroTxSelClkSrc3, 27:24, scratch179, 21:18), + s(EmcPmacroTxSelClkSrc2, 9:0, scratch179, 31:22), + s(EmcPmacroCmdBrickCtrlFdpd, 17:0, scratch180, 17:0), + s(EmcPmacroTxSelClkSrc2, 11:10, scratch180, 19:18), + s(EmcPmacroTxSelClkSrc2, 27:16, scratch180, 31:20), + s(EmcPmacroDataBrickCtrlFdpd, 17:0, scratch181, 17:0), + s(EmcPmacroTxSelClkSrc4, 11:0, scratch181, 29:18), + s(EmcPmacroTxSelClkSrc4, 17:16, scratch181, 31:30), + s(EmcFbioCfg7, 16:0, scratch182, 16:0), + s(McEmemArbRefpbBankCtrl, 6:0, scratch182, 23:17), + s(McEmemArbRefpbBankCtrl, 14:8, scratch182, 30:24), + s(McEmemArbRefpbBankCtrl, 31:31, scratch182, 31:31), + s(EmcDynSelfRefControl, 15:0, scratch183, 15:0), + s(EmcDynSelfRefControl, 31:31, scratch183, 16:16), + s(EmcPmacroTxSelClkSrc4, 27:18, scratch183, 26:17), + s(EmcPmacroTxSelClkSrc5, 4:0, scratch183, 31:27), + s(EmcDllCfg1, 16:0, scratch184, 16:0), + s(EmcPmacroTxSelClkSrc5, 11:5, scratch184, 23:17), + s(EmcPmacroTxSelClkSrc5, 23:16, scratch184, 31:24), + s(EmcPmacroPadCfgCtrl, 1:0, scratch185, 1:0), + s(EmcPmacroPadCfgCtrl, 6:5, scratch185, 3:2), + s(EmcPmacroPadCfgCtrl, 11:9, scratch185, 6:4), + s(EmcPmacroPadCfgCtrl, 13:13, scratch185, 7:7), + s(EmcPmacroPadCfgCtrl, 17:16, scratch185, 9:8), + s(EmcPmacroPadCfgCtrl, 21:20, scratch185, 11:10), + s(EmcPmacroPadCfgCtrl, 25:24, scratch185, 13:12), + s(EmcPmacroPadCfgCtrl, 30:28, scratch185, 16:14), + s(EmcPmacroTxSelClkSrc5, 27:24, scratch185, 20:17), + s(EmcPmacroCmdPadTxCtrl, 1:0, scratch185, 22:21), + s(EmcPmacroCmdPadTxCtrl, 5:4, scratch185, 24:23), + s(EmcPmacroCmdPadTxCtrl, 9:8, scratch185, 26:25), + s(EmcPmacroCmdPadTxCtrl, 13:12, scratch185, 28:27), + s(EmcPmacroCmdPadTxCtrl, 16:16, scratch185, 29:29), + s(EmcPmacroCmdPadTxCtrl, 21:20, scratch185, 31:30), + s(EmcRefresh, 15:0, scratch186, 15:0), + s(EmcCmdQ, 4:0, scratch186, 20:16), + s(EmcCmdQ, 10:8, scratch186, 23:21), + s(EmcCmdQ, 14:12, scratch186, 26:24), + s(EmcCmdQ, 28:24, scratch186, 31:27), + s(EmcAcpdControl, 15:0, scratch187, 15:0), + s(EmcAutoCalVrefSel1, 15:0, scratch187, 31:16), + s(EmcXm2CompPadCtrl, 1:0, scratch188, 1:0), + s(EmcXm2CompPadCtrl, 6:3, scratch188, 5:2), + s(EmcXm2CompPadCtrl, 9:9, scratch188, 6:6), + s(EmcXm2CompPadCtrl, 19:11, scratch188, 15:7), + s(EmcCfgDigDllPeriod, 15:0, scratch188, 31:16), + s(EmcCfgDigDll_1, 15:0, scratch189, 15:0), + s(EmcPreRefreshReqCnt, 15:0, scratch189, 31:16), + s(EmcPmacroCmdPadTxCtrl, 27:24, scratch190, 19:16), + s(EmcPmacroDataPadTxCtrl, 1:0, scratch190, 21:20), + s(EmcPmacroDataPadTxCtrl, 5:4, scratch190, 23:22), + s(EmcPmacroDataPadTxCtrl, 9:8, scratch190, 25:24), + s(EmcPmacroDataPadTxCtrl, 13:12, scratch190, 27:26), + s(EmcPmacroDataPadTxCtrl, 16:16, scratch190, 28:28), + s(EmcPmacroDataPadTxCtrl, 21:20, scratch190, 30:29), + s(EmcPmacroDataPadTxCtrl, 24:24, scratch190, 31:31), + s(EmcPmacroDataPadTxCtrl, 27:25, scratch191, 2:0), - s(EmcPinGpio, 1:0, scratch8, 31:30); - s(EmcPinGpioEn, 1:0, scratch9, 31:30); - s(EmcDevSelect, 1:0, scratch10, 31:30); - s(EmcZcalWarmColdBootEnables, 1:0, scratch11, 31:30); - s(EmcCfgDigDllPeriodWarmBoot, 1:0, scratch12, 31:30); - s32(EmcBctSpare13, scratch31); - s32(EmcBctSpare12, scratch32); - s32(EmcBctSpare7, scratch33); - s32(EmcBctSpare6, scratch40); - s32(EmcBctSpare5, scratch42); - s32(EmcBctSpare4, scratch44); - s32(EmcBctSpare3, scratch45); - s32(EmcBctSpare2, scratch46); - s32(EmcBctSpare1, scratch47); - s32(EmcBctSpare0, scratch48); - s32(EmcBctSpare9, scratch50); - s32(EmcBctSpare8, scratch51); - s32(BootRomPatchData, scratch56); - s32(BootRomPatchControl, scratch57); - s(McClkenOverrideAllWarmBoot, 0:0, scratch58, 31:31); - s(EmcClkenOverrideAllWarmBoot, 0:0, scratch59, 30:30); - s(EmcMrsWarmBootEnable, 0:0, scratch59, 31:31); - s(ClearClk2Mc1, 0:0, scratch60, 30:30); - s(EmcWarmBootExtraModeRegWriteEnable, 0:0, scratch60, 31:31); - s(ClkRstControllerPllmMisc2OverrideEnable, 0:0, scratch61, 30:30); - s(EmcDbgWriteMux, 0:0, scratch61, 31:31); - s(EmcExtraRefreshNum, 2:0, scratch62, 31:29); - s(PmcIoDpd3ReqWait, 2:0, scratch68, 30:28); - s(AhbArbitrationXbarCtrlMemInitDone, 0:0, scratch68, 31:31); - s(MemoryType, 2:0, scratch69, 30:28); - s(PmcIoDpd4ReqWait, 2:0, scratch70, 30:28); - s(EmcTimingControlWait, 7:0, scratch86, 31:24); - s(EmcZcalWarmBootWait, 7:0, scratch87, 31:24); - s(WarmBootWait, 7:0, scratch88, 31:24); - s(EmcPinProgramWait, 7:0, scratch89, 31:24); - s(EmcAutoCalWait, 9:0, scratch101, 31:22); - s(SwizzleRankByteEncode, 15:0, scratch190, 15:0); + s(EmcPinGpio, 1:0, scratch8, 31:30), + s(EmcPinGpioEn, 1:0, scratch9, 31:30), + s(EmcDevSelect, 1:0, scratch10, 31:30), + s(EmcZcalWarmColdBootEnables, 1:0, scratch11, 31:30), + s(EmcCfgDigDllPeriodWarmBoot, 1:0, scratch12, 31:30), + s32(EmcBctSpare13, scratch31), + s32(EmcBctSpare12, scratch32), + s32(EmcBctSpare7, scratch33), + s32(EmcBctSpare6, scratch40), + s32(EmcBctSpare5, scratch42), + s32(EmcBctSpare4, scratch44), + s32(EmcBctSpare3, scratch45), + s32(EmcBctSpare2, scratch46), + s32(EmcBctSpare1, scratch47), + s32(EmcBctSpare0, scratch48), + s32(EmcBctSpare9, scratch50), + s32(EmcBctSpare8, scratch51), + s32(BootRomPatchData, scratch56), + s32(BootRomPatchControl, scratch57), + s(McClkenOverrideAllWarmBoot, 0:0, scratch58, 31:31), + s(EmcClkenOverrideAllWarmBoot, 0:0, scratch59, 30:30), + s(EmcMrsWarmBootEnable, 0:0, scratch59, 31:31), + s(ClearClk2Mc1, 0:0, scratch60, 30:30), + s(EmcWarmBootExtraModeRegWriteEnable, 0:0, scratch60, 31:31), + s(ClkRstControllerPllmMisc2OverrideEnable, 0:0, scratch61, 30:30), + s(EmcDbgWriteMux, 0:0, scratch61, 31:31), + s(EmcExtraRefreshNum, 2:0, scratch62, 31:29), + s(PmcIoDpd3ReqWait, 2:0, scratch68, 30:28), + s(AhbArbitrationXbarCtrlMemInitDone, 0:0, scratch68, 31:31), + s(MemoryType, 2:0, scratch69, 30:28), + s(PmcIoDpd4ReqWait, 2:0, scratch70, 30:28), + s(EmcTimingControlWait, 7:0, scratch86, 31:24), + s(EmcZcalWarmBootWait, 7:0, scratch87, 31:24), + s(WarmBootWait, 7:0, scratch88, 31:24), + s(EmcPinProgramWait, 7:0, scratch89, 31:24), + s(EmcAutoCalWait, 9:0, scratch101, 31:22), + s(SwizzleRankByteEncode, 15:0, scratch190, 15:0), + }; + + sdram_lp0_save_parameter_array(sdram, pmc, parameters_0, sizeof(parameters_0)/sizeof(struct sdram_param)); switch (sdram->MemoryType) { case NvBootMemoryType_LpDdr2: - case NvBootMemoryType_LpDdr4: - s(EmcMrwLpddr2ZcalWarmBoot, 23:16, scratch5, 7:0); - s(EmcMrwLpddr2ZcalWarmBoot, 7:0, scratch5, 15:8); - s(EmcWarmBootMrwExtra, 23:16, scratch5, 23:16); - s(EmcWarmBootMrwExtra, 7:0, scratch5, 31:24); - s(EmcMrwLpddr2ZcalWarmBoot, 31:30, scratch6, 1:0); - s(EmcWarmBootMrwExtra, 31:30, scratch6, 3:2); - s(EmcMrwLpddr2ZcalWarmBoot, 27:26, scratch6, 5:4); - s(EmcWarmBootMrwExtra, 27:26, scratch6, 7:6); - s(EmcMrw6, 27:0, scratch8, 27:0); - s(EmcMrw6, 31:30, scratch8, 29:28); - s(EmcMrw8, 27:0, scratch9, 27:0); - s(EmcMrw8, 31:30, scratch9, 29:28); - s(EmcMrw9, 27:0, scratch10, 27:0); - s(EmcMrw9, 31:30, scratch10, 29:28); - s(EmcMrw10, 27:0, scratch11, 27:0); - s(EmcMrw10, 31:30, scratch11, 29:28); - s(EmcMrw12, 27:0, scratch12, 27:0); - s(EmcMrw12, 31:30, scratch12, 29:28); - s(EmcMrw13, 27:0, scratch13, 27:0); - s(EmcMrw13, 31:30, scratch13, 29:28); - s(EmcMrw14, 27:0, scratch14, 27:0); - s(EmcMrw14, 31:30, scratch14, 29:28); - s(EmcMrw1, 7:0, scratch15, 7:0); - s(EmcMrw1, 23:16, scratch15, 15:8); - s(EmcMrw1, 27:26, scratch15, 17:16); - s(EmcMrw1, 31:30, scratch15, 19:18); - s(EmcWarmBootMrwExtra, 7:0, scratch16, 7:0); - s(EmcWarmBootMrwExtra, 23:16, scratch16, 15:8); - s(EmcWarmBootMrwExtra, 27:26, scratch16, 17:16); - s(EmcWarmBootMrwExtra, 31:30, scratch16, 19:18); - s(EmcMrw2, 7:0, scratch17, 7:0); - s(EmcMrw2, 23:16, scratch17, 15:8); - s(EmcMrw2, 27:26, scratch17, 17:16); - s(EmcMrw2, 31:30, scratch17, 19:18); - s(EmcMrw3, 7:0, scratch18, 7:0); - s(EmcMrw3, 23:16, scratch18, 15:8); - s(EmcMrw3, 27:26, scratch18, 17:16); - s(EmcMrw3, 31:30, scratch18, 19:18); - s(EmcMrw4, 7:0, scratch19, 7:0); - s(EmcMrw4, 23:16, scratch19, 15:8); - s(EmcMrw4, 27:26, scratch19, 17:16); - s(EmcMrw4, 31:30, scratch19, 19:18); - break; - case NvBootMemoryType_Ddr3: - s(EmcMrs, 13:0, scratch5, 13:0); - s(EmcEmrs, 13:0, scratch5, 27:14); - s(EmcMrs, 21:20, scratch5, 29:28); - s(EmcMrs, 31:30, scratch5, 31:30); - s(EmcEmrs2, 13:0, scratch8, 13:0); - s(EmcEmrs3, 13:0, scratch8, 27:14); - s(EmcEmrs, 21:20, scratch8, 29:28); - s(EmcWarmBootMrsExtra, 13:0, scratch9, 13:0); - s(EmcEmrs, 31:30, scratch9, 15:14); - s(EmcEmrs2, 21:20, scratch9, 17:16); - s(EmcEmrs2, 31:30, scratch9, 19:18); - s(EmcEmrs3, 21:20, scratch9, 21:20); - s(EmcEmrs3, 31:30, scratch9, 23:22); - s(EmcWarmBootMrsExtra, 31:30, scratch9, 25:24); - s(EmcWarmBootMrsExtra, 21:20, scratch9, 27:26); - s(EmcZqCalDdr3WarmBoot, 31:30, scratch9, 29:28); - s(EmcMrs, 27:26, scratch10, 1:0); - s(EmcEmrs, 27:26, scratch10, 3:2); - s(EmcEmrs2, 27:26, scratch10, 5:4); - s(EmcEmrs3, 27:26, scratch10, 7:6); - s(EmcWarmBootMrsExtra, 27:27, scratch10, 8:8); - s(EmcWarmBootMrsExtra, 26:26, scratch10, 9:9); - s(EmcZqCalDdr3WarmBoot, 0:0, scratch10, 10:10); - s(EmcZqCalDdr3WarmBoot, 4:4, scratch10, 11:11); - break; + case NvBootMemoryType_LpDdr4: { + static const struct sdram_param parameters_1[] = { + s(EmcMrwLpddr2ZcalWarmBoot, 23:16, scratch5, 7:0), + s(EmcMrwLpddr2ZcalWarmBoot, 7:0, scratch5, 15:8), + s(EmcWarmBootMrwExtra, 23:16, scratch5, 23:16), + s(EmcWarmBootMrwExtra, 7:0, scratch5, 31:24), + s(EmcMrwLpddr2ZcalWarmBoot, 31:30, scratch6, 1:0), + s(EmcWarmBootMrwExtra, 31:30, scratch6, 3:2), + s(EmcMrwLpddr2ZcalWarmBoot, 27:26, scratch6, 5:4), + s(EmcWarmBootMrwExtra, 27:26, scratch6, 7:6), + s(EmcMrw6, 27:0, scratch8, 27:0), + s(EmcMrw6, 31:30, scratch8, 29:28), + s(EmcMrw8, 27:0, scratch9, 27:0), + s(EmcMrw8, 31:30, scratch9, 29:28), + s(EmcMrw9, 27:0, scratch10, 27:0), + s(EmcMrw9, 31:30, scratch10, 29:28), + s(EmcMrw10, 27:0, scratch11, 27:0), + s(EmcMrw10, 31:30, scratch11, 29:28), + s(EmcMrw12, 27:0, scratch12, 27:0), + s(EmcMrw12, 31:30, scratch12, 29:28), + s(EmcMrw13, 27:0, scratch13, 27:0), + s(EmcMrw13, 31:30, scratch13, 29:28), + s(EmcMrw14, 27:0, scratch14, 27:0), + s(EmcMrw14, 31:30, scratch14, 29:28), + s(EmcMrw1, 7:0, scratch15, 7:0), + s(EmcMrw1, 23:16, scratch15, 15:8), + s(EmcMrw1, 27:26, scratch15, 17:16), + s(EmcMrw1, 31:30, scratch15, 19:18), + s(EmcWarmBootMrwExtra, 7:0, scratch16, 7:0), + s(EmcWarmBootMrwExtra, 23:16, scratch16, 15:8), + s(EmcWarmBootMrwExtra, 27:26, scratch16, 17:16), + s(EmcWarmBootMrwExtra, 31:30, scratch16, 19:18), + s(EmcMrw2, 7:0, scratch17, 7:0), + s(EmcMrw2, 23:16, scratch17, 15:8), + s(EmcMrw2, 27:26, scratch17, 17:16), + s(EmcMrw2, 31:30, scratch17, 19:18), + s(EmcMrw3, 7:0, scratch18, 7:0), + s(EmcMrw3, 23:16, scratch18, 15:8), + s(EmcMrw3, 27:26, scratch18, 17:16), + s(EmcMrw3, 31:30, scratch18, 19:18), + s(EmcMrw4, 7:0, scratch19, 7:0), + s(EmcMrw4, 23:16, scratch19, 15:8), + s(EmcMrw4, 27:26, scratch19, 17:16), + s(EmcMrw4, 31:30, scratch19, 19:18), + }; + + sdram_lp0_save_parameter_array(sdram, pmc, parameters_1, sizeof(parameters_1)/sizeof(struct sdram_param)); + + break; } + case NvBootMemoryType_Ddr3: { + static const struct sdram_param parameters_1[] = { + s(EmcMrs, 13:0, scratch5, 13:0), + s(EmcEmrs, 13:0, scratch5, 27:14), + s(EmcMrs, 21:20, scratch5, 29:28), + s(EmcMrs, 31:30, scratch5, 31:30), + s(EmcEmrs2, 13:0, scratch8, 13:0), + s(EmcEmrs3, 13:0, scratch8, 27:14), + s(EmcEmrs, 21:20, scratch8, 29:28), + s(EmcWarmBootMrsExtra, 13:0, scratch9, 13:0), + s(EmcEmrs, 31:30, scratch9, 15:14), + s(EmcEmrs2, 21:20, scratch9, 17:16), + s(EmcEmrs2, 31:30, scratch9, 19:18), + s(EmcEmrs3, 21:20, scratch9, 21:20), + s(EmcEmrs3, 31:30, scratch9, 23:22), + s(EmcWarmBootMrsExtra, 31:30, scratch9, 25:24), + s(EmcWarmBootMrsExtra, 21:20, scratch9, 27:26), + s(EmcZqCalDdr3WarmBoot, 31:30, scratch9, 29:28), + s(EmcMrs, 27:26, scratch10, 1:0), + s(EmcEmrs, 27:26, scratch10, 3:2), + s(EmcEmrs2, 27:26, scratch10, 5:4), + s(EmcEmrs3, 27:26, scratch10, 7:6), + s(EmcWarmBootMrsExtra, 27:27, scratch10, 8:8), + s(EmcWarmBootMrsExtra, 26:26, scratch10, 9:9), + s(EmcZqCalDdr3WarmBoot, 0:0, scratch10, 10:10), + s(EmcZqCalDdr3WarmBoot, 4:4, scratch10, 11:11), + }; + + sdram_lp0_save_parameter_array(sdram, pmc, parameters_1, sizeof(parameters_1)/sizeof(struct sdram_param)); + + break; } } - s32(EmcCmdMappingByte, secure_scratch8); - s32(EmcPmacroBrickMapping0, secure_scratch9); - s32(EmcPmacroBrickMapping1, secure_scratch10); - s32(EmcPmacroBrickMapping2, secure_scratch11); - s32(McVideoProtectGpuOverride0, secure_scratch12); - s(EmcCmdMappingCmd0_0, 6:0, secure_scratch13, 6:0); - s(EmcCmdMappingCmd0_0, 14:8, secure_scratch13, 13:7); - s(EmcCmdMappingCmd0_0, 22:16, secure_scratch13, 20:14); - s(EmcCmdMappingCmd0_0, 30:24, secure_scratch13, 27:21); - s(McVideoProtectBomAdrHi, 1:0, secure_scratch13, 29:28); - s(McVideoProtectWriteAccess, 1:0, secure_scratch13, 31:30); - s(EmcCmdMappingCmd0_1, 6:0, secure_scratch14, 6:0); - s(EmcCmdMappingCmd0_1, 14:8, secure_scratch14, 13:7); - s(EmcCmdMappingCmd0_1, 22:16, secure_scratch14, 20:14); - s(EmcCmdMappingCmd0_1, 30:24, secure_scratch14, 27:21); - s(McSecCarveoutAdrHi, 1:0, secure_scratch14, 29:28); - s(McMtsCarveoutAdrHi, 1:0, secure_scratch14, 31:30); - s(EmcCmdMappingCmd1_0, 6:0, secure_scratch15, 6:0); - s(EmcCmdMappingCmd1_0, 14:8, secure_scratch15, 13:7); - s(EmcCmdMappingCmd1_0, 22:16, secure_scratch15, 20:14); - s(EmcCmdMappingCmd1_0, 30:24, secure_scratch15, 27:21); - s(McGeneralizedCarveout5BomHi, 1:0, secure_scratch15, 29:28); - s(McGeneralizedCarveout3BomHi, 1:0, secure_scratch15, 31:30); - s(EmcCmdMappingCmd1_1, 6:0, secure_scratch16, 6:0); - s(EmcCmdMappingCmd1_1, 14:8, secure_scratch16, 13:7); - s(EmcCmdMappingCmd1_1, 22:16, secure_scratch16, 20:14); - s(EmcCmdMappingCmd1_1, 30:24, secure_scratch16, 27:21); - s(McGeneralizedCarveout2BomHi, 1:0, secure_scratch16, 29:28); - s(McGeneralizedCarveout4BomHi, 1:0, secure_scratch16, 31:30); - s(EmcCmdMappingCmd2_0, 6:0, secure_scratch17, 6:0); - s(EmcCmdMappingCmd2_0, 14:8, secure_scratch17, 13:7); - s(EmcCmdMappingCmd2_0, 22:16, secure_scratch17, 20:14); - s(EmcCmdMappingCmd2_0, 30:24, secure_scratch17, 27:21); - s(McGeneralizedCarveout1BomHi, 1:0, secure_scratch17, 29:28); - s(EmcAdrCfg, 0:0, secure_scratch17, 30:30); - s(EmcFbioSpare, 1:1, secure_scratch17, 31:31); - s(EmcCmdMappingCmd2_1, 6:0, secure_scratch18, 6:0); - s(EmcCmdMappingCmd2_1, 14:8, secure_scratch18, 13:7); - s(EmcCmdMappingCmd2_1, 22:16, secure_scratch18, 20:14); - s(EmcCmdMappingCmd2_1, 30:24, secure_scratch18, 27:21); - s(EmcFbioCfg8, 15:15, secure_scratch18, 28:28); - s(McEmemAdrCfg, 0:0, secure_scratch18, 29:29); - s(McSecCarveoutProtectWriteAccess, 0:0, secure_scratch18, 30:30); - s(McMtsCarveoutRegCtrl, 0:0, secure_scratch18, 31:31); - s(EmcCmdMappingCmd3_0, 6:0, secure_scratch19, 6:0); - s(EmcCmdMappingCmd3_0, 14:8, secure_scratch19, 13:7); - s(EmcCmdMappingCmd3_0, 22:16, secure_scratch19, 20:14); - s(EmcCmdMappingCmd3_0, 30:24, secure_scratch19, 27:21); - s(McGeneralizedCarveout2Cfg0, 6:3, secure_scratch19, 31:28); - s(EmcCmdMappingCmd3_1, 6:0, secure_scratch20, 6:0); - s(EmcCmdMappingCmd3_1, 14:8, secure_scratch20, 13:7); - s(EmcCmdMappingCmd3_1, 22:16, secure_scratch20, 20:14); - s(EmcCmdMappingCmd3_1, 30:24, secure_scratch20, 27:21); - s(McGeneralizedCarveout2Cfg0, 10:7, secure_scratch20, 31:28); - s(McGeneralizedCarveout4Cfg0, 26:0, secure_scratch39, 26:0); - s(McGeneralizedCarveout2Cfg0, 17:14, secure_scratch39, 30:27); - s(McVideoProtectVprOverride, 0:0, secure_scratch39, 31:31); - s(McGeneralizedCarveout5Cfg0, 26:0, secure_scratch40, 26:0); - s(McGeneralizedCarveout2Cfg0, 21:18, secure_scratch40, 30:27); - s(McVideoProtectVprOverride, 1:1, secure_scratch40, 31:31); - s(EmcCmdMappingCmd0_2, 6:0, secure_scratch41, 6:0); - s(EmcCmdMappingCmd0_2, 14:8, secure_scratch41, 13:7); - s(EmcCmdMappingCmd0_2, 22:16, secure_scratch41, 20:14); - s(EmcCmdMappingCmd0_2, 27:24, secure_scratch41, 24:21); - s(McGeneralizedCarveout1Cfg0, 6:3, secure_scratch41, 28:25); - s(McGeneralizedCarveout2Cfg0, 13:11, secure_scratch41, 31:29); - s(EmcCmdMappingCmd1_2, 6:0, secure_scratch42, 6:0); - s(EmcCmdMappingCmd1_2, 14:8, secure_scratch42, 13:7); - s(EmcCmdMappingCmd1_2, 22:16, secure_scratch42, 20:14); - s(EmcCmdMappingCmd1_2, 27:24, secure_scratch42, 24:21); - s(McGeneralizedCarveout1Cfg0, 13:7, secure_scratch42, 31:25); - s(EmcCmdMappingCmd2_2, 6:0, secure_scratch43, 6:0); - s(EmcCmdMappingCmd2_2, 14:8, secure_scratch43, 13:7); - s(EmcCmdMappingCmd2_2, 22:16, secure_scratch43, 20:14); - s(EmcCmdMappingCmd2_2, 27:24, secure_scratch43, 24:21); - s(McGeneralizedCarveout1Cfg0, 17:14, secure_scratch43, 28:25); - s(McGeneralizedCarveout3Cfg0, 13:11, secure_scratch43, 31:29); - s(EmcCmdMappingCmd3_2, 6:0, secure_scratch44, 6:0); - s(EmcCmdMappingCmd3_2, 14:8, secure_scratch44, 13:7); - s(EmcCmdMappingCmd3_2, 22:16, secure_scratch44, 20:14); - s(EmcCmdMappingCmd3_2, 27:24, secure_scratch44, 24:21); - s(McGeneralizedCarveout1Cfg0, 21:18, secure_scratch44, 28:25); - s(McVideoProtectVprOverride, 3:2, secure_scratch44, 30:29); - s(McVideoProtectVprOverride, 6:6, secure_scratch44, 31:31); - s(McEmemAdrCfgChannelMask, 31:9, secure_scratch45, 22:0); - s(McEmemAdrCfgDev0, 2:0, secure_scratch45, 25:23); - s(McEmemAdrCfgDev0, 9:8, secure_scratch45, 27:26); - s(McEmemAdrCfgDev0, 19:16, secure_scratch45, 31:28); - s(McEmemAdrCfgBankMask0, 31:10, secure_scratch46, 21:0); - s(McEmemAdrCfgDev1, 2:0, secure_scratch46, 24:22); - s(McEmemAdrCfgDev1, 9:8, secure_scratch46, 26:25); - s(McEmemAdrCfgDev1, 19:16, secure_scratch46, 30:27); - s(McVideoProtectVprOverride, 7:7, secure_scratch46, 31:31); - s(McEmemAdrCfgBankMask1, 31:10, secure_scratch47, 21:0); - s(McGeneralizedCarveout3Cfg0, 10:3, secure_scratch47, 29:22); - s(McVideoProtectVprOverride, 9:8, secure_scratch47, 31:30); - s(McEmemAdrCfgBankMask2, 31:10, secure_scratch48, 21:0); - s(McGeneralizedCarveout3Cfg0, 21:14, secure_scratch48, 29:22); - s(McVideoProtectVprOverride, 11:11, secure_scratch48, 30:30); - s(McVideoProtectVprOverride, 14:14, secure_scratch48, 31:31); - s(McVideoProtectGpuOverride1, 15:0, secure_scratch49, 15:0); - s(McEmemCfg, 13:0, secure_scratch49, 29:16); - s(McEmemCfg, 31:31, secure_scratch49, 30:30); - s(McVideoProtectVprOverride, 15:15, secure_scratch49, 31:31); - s(McGeneralizedCarveout3Bom, 31:17, secure_scratch50, 14:0); - s(McGeneralizedCarveout1Bom, 31:17, secure_scratch50, 29:15); - s(McVideoProtectVprOverride, 18:17, secure_scratch50, 31:30); - s(McGeneralizedCarveout4Bom, 31:17, secure_scratch51, 14:0); - s(McGeneralizedCarveout2Bom, 31:17, secure_scratch51, 29:15); - s(McVideoProtectVprOverride, 20:19, secure_scratch51, 31:30); - s(McGeneralizedCarveout5Bom, 31:17, secure_scratch52, 14:0); - s(McVideoProtectBom, 31:20, secure_scratch52, 26:15); - s(McVideoProtectVprOverride, 23:21, secure_scratch52, 29:27); - s(McVideoProtectVprOverride, 26:26, secure_scratch52, 30:30); - s(McVideoProtectVprOverride, 29:29, secure_scratch52, 31:31); - s(McVideoProtectSizeMb, 11:0, secure_scratch53, 11:0); - s(McSecCarveoutBom, 31:20, secure_scratch53, 23:12); - s(McVideoProtectVprOverride, 31:30, secure_scratch53, 25:24); - s(McVideoProtectVprOverride1, 1:0, secure_scratch53, 27:26); - s(McVideoProtectVprOverride1, 7:4, secure_scratch53, 31:28); - s(McSecCarveoutSizeMb, 11:0, secure_scratch54, 11:0); - s(McMtsCarveoutBom, 31:20, secure_scratch54, 23:12); - s(McVideoProtectVprOverride1, 15:8, secure_scratch54, 31:24); - s(McMtsCarveoutSizeMb, 11:0, secure_scratch55, 11:0); - s(McGeneralizedCarveout4Size128kb, 11:0, secure_scratch55, 23:12); - s(McVideoProtectVprOverride1, 16:16, secure_scratch55, 24:24); - s(McGeneralizedCarveout2Cfg0, 2:0, secure_scratch55, 27:25); - s(McGeneralizedCarveout2Cfg0, 25:22, secure_scratch55, 31:28); - s(McGeneralizedCarveout3Size128kb, 11:0, secure_scratch56, 11:0); - s(McGeneralizedCarveout2Size128kb, 11:0, secure_scratch56, 23:12); - s(McGeneralizedCarveout2Cfg0, 26:26, secure_scratch56, 24:24); - s(McGeneralizedCarveout1Cfg0, 2:0, secure_scratch56, 27:25); - s(McGeneralizedCarveout1Cfg0, 25:22, secure_scratch56, 31:28); - s(McGeneralizedCarveout1Size128kb, 11:0, secure_scratch57, 11:0); - s(McGeneralizedCarveout5Size128kb, 11:0, secure_scratch57, 23:12); - s(McGeneralizedCarveout1Cfg0, 26:26, secure_scratch57, 24:24); - s(McGeneralizedCarveout3Cfg0, 2:0, secure_scratch57, 27:25); - s(McGeneralizedCarveout3Cfg0, 25:22, secure_scratch57, 31:28); - s(McGeneralizedCarveout3Cfg0, 26:26, secure_scratch58, 0:0); + static const struct sdram_param parameters_2[] = { + s32(EmcCmdMappingByte, secure_scratch8), + s32(EmcPmacroBrickMapping0, secure_scratch9), + s32(EmcPmacroBrickMapping1, secure_scratch10), + s32(EmcPmacroBrickMapping2, secure_scratch11), + s32(McVideoProtectGpuOverride0, secure_scratch12), + s(EmcCmdMappingCmd0_0, 6:0, secure_scratch13, 6:0), + s(EmcCmdMappingCmd0_0, 14:8, secure_scratch13, 13:7), + s(EmcCmdMappingCmd0_0, 22:16, secure_scratch13, 20:14), + s(EmcCmdMappingCmd0_0, 30:24, secure_scratch13, 27:21), + s(McVideoProtectBomAdrHi, 1:0, secure_scratch13, 29:28), + s(McVideoProtectWriteAccess, 1:0, secure_scratch13, 31:30), + s(EmcCmdMappingCmd0_1, 6:0, secure_scratch14, 6:0), + s(EmcCmdMappingCmd0_1, 14:8, secure_scratch14, 13:7), + s(EmcCmdMappingCmd0_1, 22:16, secure_scratch14, 20:14), + s(EmcCmdMappingCmd0_1, 30:24, secure_scratch14, 27:21), + s(McSecCarveoutAdrHi, 1:0, secure_scratch14, 29:28), + s(McMtsCarveoutAdrHi, 1:0, secure_scratch14, 31:30), + s(EmcCmdMappingCmd1_0, 6:0, secure_scratch15, 6:0), + s(EmcCmdMappingCmd1_0, 14:8, secure_scratch15, 13:7), + s(EmcCmdMappingCmd1_0, 22:16, secure_scratch15, 20:14), + s(EmcCmdMappingCmd1_0, 30:24, secure_scratch15, 27:21), + s(McGeneralizedCarveout5BomHi, 1:0, secure_scratch15, 29:28), + s(McGeneralizedCarveout3BomHi, 1:0, secure_scratch15, 31:30), + s(EmcCmdMappingCmd1_1, 6:0, secure_scratch16, 6:0), + s(EmcCmdMappingCmd1_1, 14:8, secure_scratch16, 13:7), + s(EmcCmdMappingCmd1_1, 22:16, secure_scratch16, 20:14), + s(EmcCmdMappingCmd1_1, 30:24, secure_scratch16, 27:21), + s(McGeneralizedCarveout2BomHi, 1:0, secure_scratch16, 29:28), + s(McGeneralizedCarveout4BomHi, 1:0, secure_scratch16, 31:30), + s(EmcCmdMappingCmd2_0, 6:0, secure_scratch17, 6:0), + s(EmcCmdMappingCmd2_0, 14:8, secure_scratch17, 13:7), + s(EmcCmdMappingCmd2_0, 22:16, secure_scratch17, 20:14), + s(EmcCmdMappingCmd2_0, 30:24, secure_scratch17, 27:21), + s(McGeneralizedCarveout1BomHi, 1:0, secure_scratch17, 29:28), + s(EmcAdrCfg, 0:0, secure_scratch17, 30:30), + s(EmcFbioSpare, 1:1, secure_scratch17, 31:31), + s(EmcCmdMappingCmd2_1, 6:0, secure_scratch18, 6:0), + s(EmcCmdMappingCmd2_1, 14:8, secure_scratch18, 13:7), + s(EmcCmdMappingCmd2_1, 22:16, secure_scratch18, 20:14), + s(EmcCmdMappingCmd2_1, 30:24, secure_scratch18, 27:21), + s(EmcFbioCfg8, 15:15, secure_scratch18, 28:28), + s(McEmemAdrCfg, 0:0, secure_scratch18, 29:29), + s(McSecCarveoutProtectWriteAccess, 0:0, secure_scratch18, 30:30), + s(McMtsCarveoutRegCtrl, 0:0, secure_scratch18, 31:31), + s(EmcCmdMappingCmd3_0, 6:0, secure_scratch19, 6:0), + s(EmcCmdMappingCmd3_0, 14:8, secure_scratch19, 13:7), + s(EmcCmdMappingCmd3_0, 22:16, secure_scratch19, 20:14), + s(EmcCmdMappingCmd3_0, 30:24, secure_scratch19, 27:21), + s(McGeneralizedCarveout2Cfg0, 6:3, secure_scratch19, 31:28), + s(EmcCmdMappingCmd3_1, 6:0, secure_scratch20, 6:0), + s(EmcCmdMappingCmd3_1, 14:8, secure_scratch20, 13:7), + s(EmcCmdMappingCmd3_1, 22:16, secure_scratch20, 20:14), + s(EmcCmdMappingCmd3_1, 30:24, secure_scratch20, 27:21), + s(McGeneralizedCarveout2Cfg0, 10:7, secure_scratch20, 31:28), + s(McGeneralizedCarveout4Cfg0, 26:0, secure_scratch39, 26:0), + s(McGeneralizedCarveout2Cfg0, 17:14, secure_scratch39, 30:27), + s(McVideoProtectVprOverride, 0:0, secure_scratch39, 31:31), + s(McGeneralizedCarveout5Cfg0, 26:0, secure_scratch40, 26:0), + s(McGeneralizedCarveout2Cfg0, 21:18, secure_scratch40, 30:27), + s(McVideoProtectVprOverride, 1:1, secure_scratch40, 31:31), + s(EmcCmdMappingCmd0_2, 6:0, secure_scratch41, 6:0), + s(EmcCmdMappingCmd0_2, 14:8, secure_scratch41, 13:7), + s(EmcCmdMappingCmd0_2, 22:16, secure_scratch41, 20:14), + s(EmcCmdMappingCmd0_2, 27:24, secure_scratch41, 24:21), + s(McGeneralizedCarveout1Cfg0, 6:3, secure_scratch41, 28:25), + s(McGeneralizedCarveout2Cfg0, 13:11, secure_scratch41, 31:29), + s(EmcCmdMappingCmd1_2, 6:0, secure_scratch42, 6:0), + s(EmcCmdMappingCmd1_2, 14:8, secure_scratch42, 13:7), + s(EmcCmdMappingCmd1_2, 22:16, secure_scratch42, 20:14), + s(EmcCmdMappingCmd1_2, 27:24, secure_scratch42, 24:21), + s(McGeneralizedCarveout1Cfg0, 13:7, secure_scratch42, 31:25), + s(EmcCmdMappingCmd2_2, 6:0, secure_scratch43, 6:0), + s(EmcCmdMappingCmd2_2, 14:8, secure_scratch43, 13:7), + s(EmcCmdMappingCmd2_2, 22:16, secure_scratch43, 20:14), + s(EmcCmdMappingCmd2_2, 27:24, secure_scratch43, 24:21), + s(McGeneralizedCarveout1Cfg0, 17:14, secure_scratch43, 28:25), + s(McGeneralizedCarveout3Cfg0, 13:11, secure_scratch43, 31:29), + s(EmcCmdMappingCmd3_2, 6:0, secure_scratch44, 6:0), + s(EmcCmdMappingCmd3_2, 14:8, secure_scratch44, 13:7), + s(EmcCmdMappingCmd3_2, 22:16, secure_scratch44, 20:14), + s(EmcCmdMappingCmd3_2, 27:24, secure_scratch44, 24:21), + s(McGeneralizedCarveout1Cfg0, 21:18, secure_scratch44, 28:25), + s(McVideoProtectVprOverride, 3:2, secure_scratch44, 30:29), + s(McVideoProtectVprOverride, 6:6, secure_scratch44, 31:31), + s(McEmemAdrCfgChannelMask, 31:9, secure_scratch45, 22:0), + s(McEmemAdrCfgDev0, 2:0, secure_scratch45, 25:23), + s(McEmemAdrCfgDev0, 9:8, secure_scratch45, 27:26), + s(McEmemAdrCfgDev0, 19:16, secure_scratch45, 31:28), + s(McEmemAdrCfgBankMask0, 31:10, secure_scratch46, 21:0), + s(McEmemAdrCfgDev1, 2:0, secure_scratch46, 24:22), + s(McEmemAdrCfgDev1, 9:8, secure_scratch46, 26:25), + s(McEmemAdrCfgDev1, 19:16, secure_scratch46, 30:27), + s(McVideoProtectVprOverride, 7:7, secure_scratch46, 31:31), + s(McEmemAdrCfgBankMask1, 31:10, secure_scratch47, 21:0), + s(McGeneralizedCarveout3Cfg0, 10:3, secure_scratch47, 29:22), + s(McVideoProtectVprOverride, 9:8, secure_scratch47, 31:30), + s(McEmemAdrCfgBankMask2, 31:10, secure_scratch48, 21:0), + s(McGeneralizedCarveout3Cfg0, 21:14, secure_scratch48, 29:22), + s(McVideoProtectVprOverride, 11:11, secure_scratch48, 30:30), + s(McVideoProtectVprOverride, 14:14, secure_scratch48, 31:31), + s(McVideoProtectGpuOverride1, 15:0, secure_scratch49, 15:0), + s(McEmemCfg, 13:0, secure_scratch49, 29:16), + s(McEmemCfg, 31:31, secure_scratch49, 30:30), + s(McVideoProtectVprOverride, 15:15, secure_scratch49, 31:31), + s(McGeneralizedCarveout3Bom, 31:17, secure_scratch50, 14:0), + s(McGeneralizedCarveout1Bom, 31:17, secure_scratch50, 29:15), + s(McVideoProtectVprOverride, 18:17, secure_scratch50, 31:30), + s(McGeneralizedCarveout4Bom, 31:17, secure_scratch51, 14:0), + s(McGeneralizedCarveout2Bom, 31:17, secure_scratch51, 29:15), + s(McVideoProtectVprOverride, 20:19, secure_scratch51, 31:30), + s(McGeneralizedCarveout5Bom, 31:17, secure_scratch52, 14:0), + s(McVideoProtectBom, 31:20, secure_scratch52, 26:15), + s(McVideoProtectVprOverride, 23:21, secure_scratch52, 29:27), + s(McVideoProtectVprOverride, 26:26, secure_scratch52, 30:30), + s(McVideoProtectVprOverride, 29:29, secure_scratch52, 31:31), + s(McVideoProtectSizeMb, 11:0, secure_scratch53, 11:0), + s(McSecCarveoutBom, 31:20, secure_scratch53, 23:12), + s(McVideoProtectVprOverride, 31:30, secure_scratch53, 25:24), + s(McVideoProtectVprOverride1, 1:0, secure_scratch53, 27:26), + s(McVideoProtectVprOverride1, 7:4, secure_scratch53, 31:28), + s(McSecCarveoutSizeMb, 11:0, secure_scratch54, 11:0), + s(McMtsCarveoutBom, 31:20, secure_scratch54, 23:12), + s(McVideoProtectVprOverride1, 15:8, secure_scratch54, 31:24), + s(McMtsCarveoutSizeMb, 11:0, secure_scratch55, 11:0), + s(McGeneralizedCarveout4Size128kb, 11:0, secure_scratch55, 23:12), + s(McVideoProtectVprOverride1, 16:16, secure_scratch55, 24:24), + s(McGeneralizedCarveout2Cfg0, 2:0, secure_scratch55, 27:25), + s(McGeneralizedCarveout2Cfg0, 25:22, secure_scratch55, 31:28), + s(McGeneralizedCarveout3Size128kb, 11:0, secure_scratch56, 11:0), + s(McGeneralizedCarveout2Size128kb, 11:0, secure_scratch56, 23:12), + s(McGeneralizedCarveout2Cfg0, 26:26, secure_scratch56, 24:24), + s(McGeneralizedCarveout1Cfg0, 2:0, secure_scratch56, 27:25), + s(McGeneralizedCarveout1Cfg0, 25:22, secure_scratch56, 31:28), + s(McGeneralizedCarveout1Size128kb, 11:0, secure_scratch57, 11:0), + s(McGeneralizedCarveout5Size128kb, 11:0, secure_scratch57, 23:12), + s(McGeneralizedCarveout1Cfg0, 26:26, secure_scratch57, 24:24), + s(McGeneralizedCarveout3Cfg0, 2:0, secure_scratch57, 27:25), + s(McGeneralizedCarveout3Cfg0, 25:22, secure_scratch57, 31:28), + s(McGeneralizedCarveout3Cfg0, 26:26, secure_scratch58, 0:0), - s32(McGeneralizedCarveout1Access0, secure_scratch59); - s32(McGeneralizedCarveout1Access1, secure_scratch60); - s32(McGeneralizedCarveout1Access2, secure_scratch61); - s32(McGeneralizedCarveout1Access3, secure_scratch62); - s32(McGeneralizedCarveout1Access4, secure_scratch63); - s32(McGeneralizedCarveout2Access0, secure_scratch64); - s32(McGeneralizedCarveout2Access1, secure_scratch65); - s32(McGeneralizedCarveout2Access2, secure_scratch66); - s32(McGeneralizedCarveout2Access3, secure_scratch67); - s32(McGeneralizedCarveout2Access4, secure_scratch68); - s32(McGeneralizedCarveout3Access0, secure_scratch69); - s32(McGeneralizedCarveout3Access1, secure_scratch70); - s32(McGeneralizedCarveout3Access2, secure_scratch71); - s32(McGeneralizedCarveout3Access3, secure_scratch72); - s32(McGeneralizedCarveout3Access4, secure_scratch73); - s32(McGeneralizedCarveout4Access0, secure_scratch74); - s32(McGeneralizedCarveout4Access1, secure_scratch75); - s32(McGeneralizedCarveout4Access2, secure_scratch76); - s32(McGeneralizedCarveout4Access3, secure_scratch77); - s32(McGeneralizedCarveout4Access4, secure_scratch78); - s32(McGeneralizedCarveout5Access0, secure_scratch79); - s32(McGeneralizedCarveout5Access1, secure_scratch80); - s32(McGeneralizedCarveout5Access2, secure_scratch81); - s32(McGeneralizedCarveout5Access3, secure_scratch82); - s32(McGeneralizedCarveout1ForceInternalAccess0, secure_scratch84); - s32(McGeneralizedCarveout1ForceInternalAccess1, secure_scratch85); - s32(McGeneralizedCarveout1ForceInternalAccess2, secure_scratch86); - s32(McGeneralizedCarveout1ForceInternalAccess3, secure_scratch87); - s32(McGeneralizedCarveout1ForceInternalAccess4, secure_scratch88); - s32(McGeneralizedCarveout2ForceInternalAccess0, secure_scratch89); - s32(McGeneralizedCarveout2ForceInternalAccess1, secure_scratch90); - s32(McGeneralizedCarveout2ForceInternalAccess2, secure_scratch91); - s32(McGeneralizedCarveout2ForceInternalAccess3, secure_scratch92); - s32(McGeneralizedCarveout2ForceInternalAccess4, secure_scratch93); - s32(McGeneralizedCarveout3ForceInternalAccess0, secure_scratch94); - s32(McGeneralizedCarveout3ForceInternalAccess1, secure_scratch95); - s32(McGeneralizedCarveout3ForceInternalAccess2, secure_scratch96); - s32(McGeneralizedCarveout3ForceInternalAccess3, secure_scratch97); - s32(McGeneralizedCarveout3ForceInternalAccess4, secure_scratch98); - s32(McGeneralizedCarveout4ForceInternalAccess0, secure_scratch99); - s32(McGeneralizedCarveout4ForceInternalAccess1, secure_scratch100); - s32(McGeneralizedCarveout4ForceInternalAccess2, secure_scratch101); - s32(McGeneralizedCarveout4ForceInternalAccess3, secure_scratch102); - s32(McGeneralizedCarveout4ForceInternalAccess4, secure_scratch103); - s32(McGeneralizedCarveout5ForceInternalAccess0, secure_scratch104); - s32(McGeneralizedCarveout5ForceInternalAccess1, secure_scratch105); - s32(McGeneralizedCarveout5ForceInternalAccess2, secure_scratch106); - s32(McGeneralizedCarveout5ForceInternalAccess3, secure_scratch107); + s32(McGeneralizedCarveout1Access0, secure_scratch59), + s32(McGeneralizedCarveout1Access1, secure_scratch60), + s32(McGeneralizedCarveout1Access2, secure_scratch61), + s32(McGeneralizedCarveout1Access3, secure_scratch62), + s32(McGeneralizedCarveout1Access4, secure_scratch63), + s32(McGeneralizedCarveout2Access0, secure_scratch64), + s32(McGeneralizedCarveout2Access1, secure_scratch65), + s32(McGeneralizedCarveout2Access2, secure_scratch66), + s32(McGeneralizedCarveout2Access3, secure_scratch67), + s32(McGeneralizedCarveout2Access4, secure_scratch68), + s32(McGeneralizedCarveout3Access0, secure_scratch69), + s32(McGeneralizedCarveout3Access1, secure_scratch70), + s32(McGeneralizedCarveout3Access2, secure_scratch71), + s32(McGeneralizedCarveout3Access3, secure_scratch72), + s32(McGeneralizedCarveout3Access4, secure_scratch73), + s32(McGeneralizedCarveout4Access0, secure_scratch74), + s32(McGeneralizedCarveout4Access1, secure_scratch75), + s32(McGeneralizedCarveout4Access2, secure_scratch76), + s32(McGeneralizedCarveout4Access3, secure_scratch77), + s32(McGeneralizedCarveout4Access4, secure_scratch78), + s32(McGeneralizedCarveout5Access0, secure_scratch79), + s32(McGeneralizedCarveout5Access1, secure_scratch80), + s32(McGeneralizedCarveout5Access2, secure_scratch81), + s32(McGeneralizedCarveout5Access3, secure_scratch82), + s32(McGeneralizedCarveout1ForceInternalAccess0, secure_scratch84), + s32(McGeneralizedCarveout1ForceInternalAccess1, secure_scratch85), + s32(McGeneralizedCarveout1ForceInternalAccess2, secure_scratch86), + s32(McGeneralizedCarveout1ForceInternalAccess3, secure_scratch87), + s32(McGeneralizedCarveout1ForceInternalAccess4, secure_scratch88), + s32(McGeneralizedCarveout2ForceInternalAccess0, secure_scratch89), + s32(McGeneralizedCarveout2ForceInternalAccess1, secure_scratch90), + s32(McGeneralizedCarveout2ForceInternalAccess2, secure_scratch91), + s32(McGeneralizedCarveout2ForceInternalAccess3, secure_scratch92), + s32(McGeneralizedCarveout2ForceInternalAccess4, secure_scratch93), + s32(McGeneralizedCarveout3ForceInternalAccess0, secure_scratch94), + s32(McGeneralizedCarveout3ForceInternalAccess1, secure_scratch95), + s32(McGeneralizedCarveout3ForceInternalAccess2, secure_scratch96), + s32(McGeneralizedCarveout3ForceInternalAccess3, secure_scratch97), + s32(McGeneralizedCarveout3ForceInternalAccess4, secure_scratch98), + s32(McGeneralizedCarveout4ForceInternalAccess0, secure_scratch99), + s32(McGeneralizedCarveout4ForceInternalAccess1, secure_scratch100), + s32(McGeneralizedCarveout4ForceInternalAccess2, secure_scratch101), + s32(McGeneralizedCarveout4ForceInternalAccess3, secure_scratch102), + s32(McGeneralizedCarveout4ForceInternalAccess4, secure_scratch103), + s32(McGeneralizedCarveout5ForceInternalAccess0, secure_scratch104), + s32(McGeneralizedCarveout5ForceInternalAccess1, secure_scratch105), + s32(McGeneralizedCarveout5ForceInternalAccess2, secure_scratch106), + s32(McGeneralizedCarveout5ForceInternalAccess3, secure_scratch107), - c32(0, scratch2); - s(PllMInputDivider, 7:0, scratch2, 7:0); - s(PllMFeedbackDivider, 7:0, scratch2, 15:8); - s(PllMPostDivider, 4:0, scratch2, 20:16); - s(PllMKVCO, 0:0, scratch2, 21:21); - s(PllMKCP, 1:0, scratch2, 23:22); + c32(0, scratch2), + s(PllMInputDivider, 7:0, scratch2, 7:0), + s(PllMFeedbackDivider, 7:0, scratch2, 15:8), + s(PllMPostDivider, 4:0, scratch2, 20:16), + s(PllMKVCO, 0:0, scratch2, 21:21), + s(PllMKCP, 1:0, scratch2, 23:22), - c32(0, scratch35); - s(PllMSetupControl, 15:0, scratch35, 15:0); + c32(0, scratch35), + s(PllMSetupControl, 15:0, scratch35, 15:0), - c32(0, scratch3); - s(PllMInputDivider, 7:0, scratch3, 7:0); - c(0x3e, scratch3, 15:8); - c(0, scratch3, 20:16); - s(PllMKVCO, 0:0, scratch3, 21:21); - s(PllMKCP, 1:0, scratch3, 23:22); + c32(0, scratch3), + s(PllMInputDivider, 7:0, scratch3, 7:0), + c(0x3e, scratch3, 15:8), + c(0, scratch3, 20:16), + s(PllMKVCO, 0:0, scratch3, 21:21), + s(PllMKCP, 1:0, scratch3, 23:22), - c32(0, scratch36); - s(PllMSetupControl, 23:0, scratch36, 23:0); + c32(0, scratch36), + s(PllMSetupControl, 23:0, scratch36, 23:0), - c32(0, scratch4); - s(PllMStableTime, 9:0, scratch4, 9:0); + c32(0, scratch4), + s(PllMStableTime, 9:0, scratch4, 9:0), + }; + + sdram_lp0_save_parameter_array(sdram, pmc, parameters_2, sizeof(parameters_2)/sizeof(struct sdram_param)); } From d29baa337e495c724b56cbb3dd6b76524de7a3f9 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Wed, 28 Oct 2020 00:29:52 -0700 Subject: [PATCH 08/14] fusee-primary: deduplicate display initialization code --- fusee/fusee-primary/src/lib/log.c | 35 +++++++++++++++++++++++++++++++ fusee/fusee-primary/src/lib/log.h | 4 ++++ fusee/fusee-primary/src/main.c | 31 +++------------------------ fusee/fusee-primary/src/utils.c | 19 ++--------------- 4 files changed, 44 insertions(+), 45 deletions(-) diff --git a/fusee/fusee-primary/src/lib/log.c b/fusee/fusee-primary/src/lib/log.c index 26e0cb8a3..c4bcd5cb5 100644 --- a/fusee/fusee-primary/src/lib/log.c +++ b/fusee/fusee-primary/src/lib/log.c @@ -17,6 +17,7 @@ #include "log.h" #include "../display/video_fb.h" +#include "../di.h" #include "../uart.h" #include "vsprintf.h" @@ -31,6 +32,40 @@ ScreenLogLevel log_get_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) { uart_send(UART_B, message, strlen(message)); } diff --git a/fusee/fusee-primary/src/lib/log.h b/fusee/fusee-primary/src/lib/log.h index eea293e33..fc830c0d2 100644 --- a/fusee/fusee-primary/src/lib/log.h +++ b/fusee/fusee-primary/src/lib/log.h @@ -36,6 +36,10 @@ extern ScreenLogLevel g_screen_log_level; void log_set_log_level(ScreenLogLevel screen_log_level); ScreenLogLevel log_get_log_level(); +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 print(ScreenLogLevel screen_log_level, const char* fmt, ...); diff --git a/fusee/fusee-primary/src/main.c b/fusee/fusee-primary/src/main.c index ee983c66c..d1ec3df03 100644 --- a/fusee/fusee-primary/src/main.c +++ b/fusee/fusee-primary/src/main.c @@ -18,7 +18,6 @@ #include "exception_handlers.h" #include "panic.h" #include "hwinit.h" -#include "di.h" #include "timers.h" #include "fs_utils.h" #include "stage2.h" @@ -31,7 +30,6 @@ extern void (*__program_exit_callback)(int rc); -static uint32_t g_framebuffer[1280*768] __attribute__((section(".framebuffer"))) = {0}; static char g_bct0_buffer[BCTO_MAX_SIZE] __attribute__((section(".dram"))) = {0}; #define DEFAULT_BCT0 \ @@ -71,29 +69,6 @@ static const char *load_config(void) { return bct0; } -static void setup_display(void) { - /* 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) { /* Initialize hardware. */ nx_hwinit(); @@ -140,12 +115,12 @@ int main(void) { if (bct0.log_level != SCREEN_LOG_LEVEL_NONE) { /* Initialize the display for debugging. */ - setup_display(); + 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", g_framebuffer); + print(SCREEN_LOG_LEVEL_DEBUG, "Using color linear framebuffer at 0x%p!\n", log_get_display_framebuffer()); /* Run the MTC binary. */ if (!stage2_run_mtc(&bct0)) { @@ -174,7 +149,7 @@ int main(void) { mdelay(1000); /* Terminate the display for debugging. */ - cleanup_display(); + log_cleanup_display(); } /* Finally, after the cleanup routines (__libc_fini_array, etc.) are called, jump to Stage2. */ diff --git a/fusee/fusee-primary/src/utils.c b/fusee/fusee-primary/src/utils.c index 51033eed7..7e4914233 100644 --- a/fusee/fusee-primary/src/utils.c +++ b/fusee/fusee-primary/src/utils.c @@ -17,7 +17,6 @@ #include #include #include "utils.h" -#include "di.h" #include "se.h" #include "fuse.h" #include "pmc.h" @@ -27,7 +26,6 @@ #include "btn.h" #include "lib/log.h" #include "lib/vsprintf.h" -#include "display/video_fb.h" #include @@ -99,22 +97,9 @@ __attribute__ ((noreturn)) void generic_panic(void) { } __attribute__((noreturn)) void fatal_error(const char *fmt, ...) { - /* Forcefully initialize the screen if logging is disabled. */ - if (log_get_log_level() == SCREEN_LOG_LEVEL_NONE) { - /* Zero-fill the framebuffer and register it as printk provider. */ - video_init((void *)0xC0000000); + /* Forcefully initialize the screen if not already initialized. */ + log_setup_display(); - /* 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. */ log_set_log_level(SCREEN_LOG_LEVEL_ERROR); From ebc3de045a4d6488d98fdbbbba0ab1bf02a265b0 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sun, 18 Oct 2020 15:26:22 -0700 Subject: [PATCH 09/14] fusee-primary: add fastboot usb gadget --- config_templates/BCT.ini | 4 + fusee/fusee-primary/Makefile | 7 +- fusee/fusee-primary/src/bct0.c | 20 +- fusee/fusee-primary/src/bct0.h | 4 + fusee/fusee-primary/src/fastboot/fastboot.cpp | 76 +++ fusee/fusee-primary/src/fastboot/fastboot.h | 36 ++ .../src/fastboot/fastboot_descriptors.inc | 192 ++++++ .../src/fastboot/fastboot_gadget.cpp | 402 ++++++++++++ .../src/fastboot/fastboot_gadget.h | 116 ++++ .../src/fastboot/fastboot_impl.cpp | 229 +++++++ .../src/fastboot/fastboot_impl.h | 60 ++ .../src/fastboot/fastboot_interface.h | 31 + fusee/fusee-primary/src/fastboot/usb_types.h | 489 ++++++++++++++ fusee/fusee-primary/src/fastboot/xusb.cpp | 600 ++++++++++++++++++ fusee/fusee-primary/src/fastboot/xusb.h | 57 ++ .../src/fastboot/xusb_control.cpp | 414 ++++++++++++ .../fusee-primary/src/fastboot/xusb_control.h | 48 ++ .../src/fastboot/xusb_endpoint.cpp | 368 +++++++++++ .../src/fastboot/xusb_endpoint.h | 346 ++++++++++ .../src/fastboot/xusb_event_ring.cpp | 120 ++++ .../src/fastboot/xusb_event_ring.h | 38 ++ .../src/fastboot/xusb_test_gadget.cpp | 287 +++++++++ .../src/fastboot/xusb_test_gadget.h | 29 + fusee/fusee-primary/src/fastboot/xusb_trb.h | 185 ++++++ fusee/fusee-primary/src/main.c | 20 +- fusee/fusee-primary/src/reg/reg_apbdev_pmc.h | 33 + fusee/fusee-primary/src/reg/reg_car.h | 221 +++++++ fusee/fusee-primary/src/reg/reg_fuse.h | 38 ++ fusee/fusee-primary/src/reg/reg_util.h | 495 +++++++++++++++ fusee/fusee-primary/src/reg/reg_xusb_dev.h | 222 +++++++ fusee/fusee-primary/src/reg/reg_xusb_padctl.h | 211 ++++++ fusee/fusee-primary/src/utils.h | 7 +- .../libvapours/include/vapours/results.hpp | 1 + .../vapours/results/xusb_gadget_results.hpp | 47 ++ 34 files changed, 5444 insertions(+), 9 deletions(-) create mode 100644 fusee/fusee-primary/src/fastboot/fastboot.cpp create mode 100644 fusee/fusee-primary/src/fastboot/fastboot.h create mode 100644 fusee/fusee-primary/src/fastboot/fastboot_descriptors.inc create mode 100644 fusee/fusee-primary/src/fastboot/fastboot_gadget.cpp create mode 100644 fusee/fusee-primary/src/fastboot/fastboot_gadget.h create mode 100644 fusee/fusee-primary/src/fastboot/fastboot_impl.cpp create mode 100644 fusee/fusee-primary/src/fastboot/fastboot_impl.h create mode 100644 fusee/fusee-primary/src/fastboot/fastboot_interface.h create mode 100644 fusee/fusee-primary/src/fastboot/usb_types.h create mode 100644 fusee/fusee-primary/src/fastboot/xusb.cpp create mode 100644 fusee/fusee-primary/src/fastboot/xusb.h create mode 100644 fusee/fusee-primary/src/fastboot/xusb_control.cpp create mode 100644 fusee/fusee-primary/src/fastboot/xusb_control.h create mode 100644 fusee/fusee-primary/src/fastboot/xusb_endpoint.cpp create mode 100644 fusee/fusee-primary/src/fastboot/xusb_endpoint.h create mode 100644 fusee/fusee-primary/src/fastboot/xusb_event_ring.cpp create mode 100644 fusee/fusee-primary/src/fastboot/xusb_event_ring.h create mode 100644 fusee/fusee-primary/src/fastboot/xusb_test_gadget.cpp create mode 100644 fusee/fusee-primary/src/fastboot/xusb_test_gadget.h create mode 100644 fusee/fusee-primary/src/fastboot/xusb_trb.h create mode 100644 fusee/fusee-primary/src/reg/reg_apbdev_pmc.h create mode 100644 fusee/fusee-primary/src/reg/reg_car.h create mode 100644 fusee/fusee-primary/src/reg/reg_fuse.h create mode 100644 fusee/fusee-primary/src/reg/reg_util.h create mode 100644 fusee/fusee-primary/src/reg/reg_xusb_dev.h create mode 100644 fusee/fusee-primary/src/reg/reg_xusb_padctl.h create mode 100644 libraries/libvapours/include/vapours/results/xusb_gadget_results.hpp diff --git a/config_templates/BCT.ini b/config_templates/BCT.ini index 74dd6f648..b6193b9f4 100644 --- a/config_templates/BCT.ini +++ b/config_templates/BCT.ini @@ -10,3 +10,7 @@ stage2_entrypoint = 0xF0000000 ; To force-disable nogc, add nogc = 0 ; To opt out of using Atmosphere's NCM reimplementation, add disable_ncm = 1 + +[fastboot] +force_enable = 0 +button_timeout_ms = 0 diff --git a/fusee/fusee-primary/Makefile b/fusee/fusee-primary/Makefile index c471da0d4..4a764e7db 100644 --- a/fusee/fusee-primary/Makefile +++ b/fusee/fusee-primary/Makefile @@ -27,7 +27,7 @@ endif #--------------------------------------------------------------------------------- TARGET := $(notdir $(CURDIR)) 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 INCLUDES := include ../../libraries/libvapours/include @@ -39,11 +39,10 @@ DEFINES := -D__BPMP__ -DFUSEE_STAGE1_SRC -DATMOSPHERE_GIT_BRANCH=\"$(AMSBRANCH)\ CFLAGS := \ -g \ - -O2 \ + -Os \ -fomit-frame-pointer \ -ffunction-sections \ -fdata-sections \ - -std=gnu11 \ -Werror \ -Wall \ -fstrict-volatile-bitfields \ @@ -51,7 +50,7 @@ CFLAGS := \ CFLAGS += $(INCLUDE) -CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11 +CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=c++2a ASFLAGS := -g $(ARCH) LDFLAGS = -specs=$(TOPDIR)/linker.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) diff --git a/fusee/fusee-primary/src/bct0.c b/fusee/fusee-primary/src/bct0.c index 523071685..2746a1d3f 100644 --- a/fusee/fusee-primary/src/bct0.c +++ b/fusee/fusee-primary/src/bct0.c @@ -20,12 +20,15 @@ #include +#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 CONFIG_LOG_LEVEL_KEY "log_level" +#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; @@ -61,6 +64,18 @@ static int bct0_ini_handler(void *user, const char *section, const char *name, c } 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; } @@ -77,5 +92,8 @@ int bct0_parse(const char *ini, bct0_t *out) { 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); } diff --git a/fusee/fusee-primary/src/bct0.h b/fusee/fusee-primary/src/bct0.h index ebb86e2ee..948a49746 100644 --- a/fusee/fusee-primary/src/bct0.h +++ b/fusee/fusee-primary/src/bct0.h @@ -33,6 +33,10 @@ typedef struct { 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); diff --git a/fusee/fusee-primary/src/fastboot/fastboot.cpp b/fusee/fusee-primary/src/fastboot/fastboot.cpp new file mode 100644 index 000000000..4795452be --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot.cpp @@ -0,0 +1,76 @@ +/* + * 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 . + */ + +#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 should_enter = bct0->fastboot_force_enable; + + log_setup_display(); + + if (!should_enter) { + if (bct0->fastboot_button_timeout > 0) { + 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; + } + + print(SCREEN_LOG_LEVEL_DEBUG, "Entering fastboot.\n"); + 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; +} diff --git a/fusee/fusee-primary/src/fastboot/fastboot.h b/fusee/fusee-primary/src/fastboot/fastboot.h new file mode 100644 index 000000000..5c79444e1 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot.h @@ -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 . + */ + +#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); + +#ifdef __cplusplus +} +#endif diff --git a/fusee/fusee-primary/src/fastboot/fastboot_descriptors.inc b/fusee/fusee-primary/src/fastboot/fastboot_descriptors.inc new file mode 100644 index 000000000..3a0d988dc --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot_descriptors.inc @@ -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 . + */ + +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_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 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 diff --git a/fusee/fusee-primary/src/fastboot/fastboot_gadget.cpp b/fusee/fusee-primary/src/fastboot/fastboot_gadget.cpp new file mode 100644 index 000000000..a81616b56 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot_gadget.cpp @@ -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 . + */ + +#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 +#include +#include + +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 diff --git a/fusee/fusee-primary/src/fastboot/fastboot_gadget.h b/fusee/fusee-primary/src/fastboot/fastboot_gadget.h new file mode 100644 index 000000000..d1f6c535b --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot_gadget.h @@ -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 . + */ + +#pragma once + +#include "xusb.h" +#include "fastboot.h" +#include "fastboot_impl.h" + +#include + +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 diff --git a/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp b/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp new file mode 100644 index 000000000..29c82427c --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp @@ -0,0 +1,229 @@ +/* + * 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 . + */ + +#include "fastboot.h" +#include "fastboot_gadget.h" + +extern "C" { +#include "../lib/log.h" +#include "../utils.h" +#include "../chainloader.h" +#include "../lib/fatfs/ff.h" +} + +#include +#include + +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)); + +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) { + 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"); + } + } + + } // namespace fastboot + +} // namespace ams diff --git a/fusee/fusee-primary/src/fastboot/fastboot_impl.h b/fusee/fusee-primary/src/fastboot/fastboot_impl.h new file mode 100644 index 000000000..c9013965d --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot_impl.h @@ -0,0 +1,60 @@ +/* + * 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 . + */ + +#pragma once + +#include + +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, + } current_action; + + union { + /* Actions */ + }; + + /* 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 */ + }; + + } // namespace fastboot + +} // namespace ams diff --git a/fusee/fusee-primary/src/fastboot/fastboot_interface.h b/fusee/fusee-primary/src/fastboot/fastboot_interface.h new file mode 100644 index 000000000..3eed60f36 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/fastboot_interface.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/fastboot/usb_types.h b/fusee/fusee-primary/src/fastboot/usb_types.h new file mode 100644 index 000000000..21d484015 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/usb_types.h @@ -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 . + */ + +#pragma once + +#include +#include +#include + +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 + 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 FixedString(char16_t const (&)[N]) -> FixedString; + + } // namespace detail + + template + 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 + struct StringDescriptorIndexer : public First::template WithIndex, public StringDescriptorIndexer { + using ThisDescriptor = First::template WithIndex; + using NextIndexer = StringDescriptorIndexer; + + 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 + struct StringDescriptorIndexer : public First::template WithIndex { + using ThisDescriptor = First::template WithIndex; + + 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 + 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 \ + struct WithIndex { \ + static constexpr ::usb::StringDescriptor _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 + 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 + constexpr PLATFORM make_platform_capability(T cap) { + return PLATFORM(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 + 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 + struct PackedTuple { + First first; + PackedTuple remaining; + + constexpr PackedTuple(First first, T... remaining) : + first(first), + remaining(remaining...) { + } + } __attribute__((packed)); + + template + struct PackedTuple { + First first; + + constexpr PackedTuple(First first) : first(first) { + } + } __attribute__((packed)); + } // namespace detail + + template + struct BOSDescriptorContainer { + BOSDescriptor bos_descriptor; + detail::PackedTuple tuple; + + constexpr BOSDescriptorContainer(T... members) : bos_descriptor { + { + .bLength = sizeof(BOSDescriptor), + .bDescriptorType = DescriptorType::BOS, + }, + { + .wTotalLength = sizeof(*this), + .bNumDeviceCaps = sizeof...(T), + } + }, tuple(members...) { + } + } __attribute__((packed)); + + template + constexpr BOSDescriptorContainer make_bos_descriptor_container(T... members) { + return BOSDescriptorContainer(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 diff --git a/fusee/fusee-primary/src/fastboot/xusb.cpp b/fusee/fusee-primary/src/fastboot/xusb.cpp new file mode 100644 index 000000000..801c35069 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb.cpp @@ -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 . + */ + +#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 + +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 diff --git a/fusee/fusee-primary/src/fastboot/xusb.h b/fusee/fusee-primary/src/fastboot/xusb.h new file mode 100644 index 000000000..7b4edeb34 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb.h @@ -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 . + */ + +#pragma once + +#include "usb_types.h" +#include "xusb_trb.h" +#include "xusb_endpoint.h" + +#include + +#include + +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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_control.cpp b/fusee/fusee-primary/src/fastboot/xusb_control.cpp new file mode 100644 index 000000000..cad345a70 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_control.cpp @@ -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 . + */ + +#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 + +#include + +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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_control.h b/fusee/fusee-primary/src/fastboot/xusb_control.h new file mode 100644 index 000000000..e7fc75934 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_control.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_endpoint.cpp b/fusee/fusee-primary/src/fastboot/xusb_endpoint.cpp new file mode 100644 index 000000000..6b48e0844 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_endpoint.cpp @@ -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 . + */ + +#include "xusb_endpoint.h" + +#include "xusb.h" +#include "xusb_control.h" + +extern "C" { +#include "../lib/log.h" +} + +#include + +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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_endpoint.h b/fusee/fusee-primary/src/fastboot/xusb_endpoint.h new file mode 100644 index 000000000..6402f8be4 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_endpoint.h @@ -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 . + */ + +#pragma once + +#include "xusb_trb.h" +#include "../reg/reg_xusb_dev.h" + +#include + +#include + +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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_event_ring.cpp b/fusee/fusee-primary/src/fastboot/xusb_event_ring.cpp new file mode 100644 index 000000000..dbd6e33c8 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_event_ring.cpp @@ -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 . + */ + +#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 +#include + +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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_event_ring.h b/fusee/fusee-primary/src/fastboot/xusb_event_ring.h new file mode 100644 index 000000000..341cb6276 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_event_ring.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_test_gadget.cpp b/fusee/fusee-primary/src/fastboot/xusb_test_gadget.cpp new file mode 100644 index 000000000..74d8329f7 --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_test_gadget.cpp @@ -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 . + */ + +#include "xusb.h" +#include "xusb_control.h" +#include "xusb_endpoint.h" + +#include + +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_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 diff --git a/fusee/fusee-primary/src/fastboot/xusb_test_gadget.h b/fusee/fusee-primary/src/fastboot/xusb_test_gadget.h new file mode 100644 index 000000000..c0571f48f --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_test_gadget.h @@ -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 . + */ + +#pragma once + +#include "xusb.h" + +namespace xusb { + + namespace test { + + Gadget &GetTestGadget(); + + } // namespace test + +} // namespace xusb diff --git a/fusee/fusee-primary/src/fastboot/xusb_trb.h b/fusee/fusee-primary/src/fastboot/xusb_trb.h new file mode 100644 index 000000000..97692709e --- /dev/null +++ b/fusee/fusee-primary/src/fastboot/xusb_trb.h @@ -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 . + */ + +#pragma once + +#include "usb_types.h" + +#include +#include + +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 diff --git a/fusee/fusee-primary/src/main.c b/fusee/fusee-primary/src/main.c index d1ec3df03..7263f9eee 100644 --- a/fusee/fusee-primary/src/main.c +++ b/fusee/fusee-primary/src/main.c @@ -27,6 +27,7 @@ #include "lib/log.h" #include "lib/vsprintf.h" #include "display/video_fb.h" +#include "fastboot/fastboot.h" extern void (*__program_exit_callback)(int rc); @@ -43,7 +44,10 @@ static char g_bct0_buffer[BCTO_MAX_SIZE] __attribute__((section(".dram"))) = {0} "debugmode = 1\n"\ "debugmode_user = 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) { if (!read_from_file(g_bct0_buffer, BCTO_MAX_SIZE, "atmosphere/config/BCT.ini")) { @@ -130,8 +134,18 @@ int main(void) { /* Assert that our configuration is sane. */ stage2_validate_config(&bct0); - /* Load the loader payload into DRAM. */ - stage2_load(&bct0); + /* Try to enter fastboot, if we are configured to. */ + switch(fastboot_enter(&bct0)) { + case FASTBOOT_INVALID: + case FASTBOOT_SKIPPED: + case FASTBOOT_LOAD_STAGE2: + /* Load the loader payload into DRAM. */ + stage2_load(&bct0); + break; + case FASTBOOT_CHAINLOAD: + print(SCREEN_LOG_LEVEL_DEBUG, "fastboot: chainloading\n"); + break; + } /* Setup argument data. */ strcpy(g_chainloader_arg_data, bct0.stage2_path); diff --git a/fusee/fusee-primary/src/reg/reg_apbdev_pmc.h b/fusee/fusee-primary/src/reg/reg_apbdev_pmc.h new file mode 100644 index 000000000..bae6007e9 --- /dev/null +++ b/fusee/fusee-primary/src/reg/reg_apbdev_pmc.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/reg/reg_car.h b/fusee/fusee-primary/src/reg/reg_car.h new file mode 100644 index 000000000..23e63aeff --- /dev/null +++ b/fusee/fusee-primary/src/reg/reg_car.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/reg/reg_fuse.h b/fusee/fusee-primary/src/reg/reg_fuse.h new file mode 100644 index 000000000..19cfe5135 --- /dev/null +++ b/fusee/fusee-primary/src/reg/reg_fuse.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/reg/reg_util.h b/fusee/fusee-primary/src/reg/reg_util.h new file mode 100644 index 000000000..5071e99a8 --- /dev/null +++ b/fusee/fusee-primary/src/reg/reg_util.h @@ -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 . + */ + +#pragma once + +#include + +template +class RegisterAccessor { + public: + using Base = _Base; + static const uintptr_t offset = _offset; + + __attribute__((always_inline)) RegisterAccessor(const Peripheral &p) : + peripheral(p), + ptr(reinterpret_cast(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(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 +class BitArrayRegisterAccessor { + public: + using Base = _Base; + + __attribute__((always_inline)) BitArrayRegisterAccessor(const Peripheral &p, uintptr_t offset) : + peripheral(p), + ptr(reinterpret_cast(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(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(p.base_addr + offset)), + read_value(*ptr), + write_value(0) { + } + + class BitAccessor { + public: + __attribute__((always_inline)) BitAccessor(BitArrayRegisterAccessor ®, 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 ® + 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 +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 +class RegisterRWFieldAccessorBase : public RegisterFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterRWFieldAccessorBase(RegAcc &acc) : RegisterFieldAccessorBase(acc) { + } + + __attribute__((always_inline)) Type Get() { + return RegisterFieldAccessorBase::Get(); + } + + __attribute__((always_inline)) explicit operator Type() { + return Get(); + } + + __attribute__((always_inline)) RegAcc &Set(Type value) { + return RegisterFieldAccessorBase::Set(value); + } +}; + +template +class RegisterROFieldAccessorBase : public RegisterFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterROFieldAccessorBase(RegAcc &acc) : RegisterFieldAccessorBase(acc) { + } + + __attribute__((always_inline)) Type Get() { + return RegisterFieldAccessorBase::Get(); + } + + __attribute__((always_inline)) explicit operator Type() { + return Get(); + } +}; + +template +class RegisterWOFieldAccessorBase : public RegisterFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterWOFieldAccessorBase(RegAcc &acc) : RegisterFieldAccessorBase(acc) { + } + + __attribute__((always_inline)) RegAcc &Set(Type value) { + return RegisterFieldAccessorBase::Set(value); + } +}; + +// generic accessors + +template +class RegisterRWFieldAccessor : public RegisterRWFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterRWFieldAccessor(RegAcc &acc) : RegisterRWFieldAccessorBase(acc) { + } +}; + +template +class RegisterROFieldAccessor : public RegisterROFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterROFieldAccessor(RegAcc &acc) : RegisterROFieldAccessorBase(acc) { + } +}; + +template +class RegisterWOFieldAccessor : public RegisterWOFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterWOFieldAccessor(RegAcc &acc) : RegisterWOFieldAccessorBase(acc) { + } +}; + +// unusual accessors + +template +class RegisterRW1CFieldAccessor : public RegisterFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterRW1CFieldAccessor(RegAcc &acc) : RegisterFieldAccessorBase(acc) { + acc.write_value&= ~RegisterFieldAccessorBase::mask; + } + + __attribute__((always_inline)) bool Get() { + return RegisterFieldAccessorBase::Get(); + } + + __attribute__((always_inline)) operator bool() { + return RegisterFieldAccessorBase::Get(); + } + + __attribute__((always_inline)) RegAcc &Clear() { + return RegisterFieldAccessorBase::Set(true); + } +}; + +// templated-specialized accessors + +template +class RegisterRWFieldAccessor : public RegisterRWFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterRWFieldAccessor(RegAcc &acc) : RegisterRWFieldAccessorBase(acc) { + } + + __attribute__((always_inline)) RegAcc &Disable() { + return RegisterFieldAccessorBase::Set(false); + } + + __attribute__((always_inline)) RegAcc &Enable() { + return RegisterFieldAccessorBase::Set(true); + } + + __attribute__((always_inline)) operator bool() { + return RegisterFieldAccessorBase::Get(); + } +}; + +template +class RegisterROFieldAccessor : public RegisterROFieldAccessorBase { + public: + __attribute__((always_inline)) RegisterROFieldAccessor(RegAcc &acc) : RegisterROFieldAccessorBase(acc) { + } + + __attribute__((always_inline)) operator bool() { + return RegisterROFieldAccessorBase::Get(); + } +}; + +#define BEGIN_DEFINE_REGISTER(name, type, offset) \ + class name##_Accessor : public RegisterAccessor { \ + 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 { \ + public: \ + using RegSelf = name##_Accessor; \ + __attribute__((always_inline)) name##_Accessor(const Peripheral &p) : RegisterAccessor(p, 0) {} + +#define DEFINE_RW_FIELD(name, ...) \ + RegisterRWFieldAccessor name = RegisterRWFieldAccessor(*this); + +#define DEFINE_RO_FIELD(name, ...) \ + RegisterROFieldAccessor name = RegisterROFieldAccessor(*this); + +#define DEFINE_WO_FIELD(name, ...) \ + RegisterWOFieldAccessor name = RegisterWOFieldAccessor(*this); + +#define DEFINE_RW1C_FIELD(name, ...) \ + RegisterRW1CFieldAccessor name = RegisterRW1CFieldAccessor(*this); + + +#define BEGIN_DEFINE_RO_SYMBOLIC_FIELD(name, low, high) \ + struct name##_Accessor : public RegisterROFieldAccessor {\ + 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 {\ + 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 name() const { \ + return BitArrayRegisterAccessor(*this, offset); \ + } \ + __attribute__((always_inline)) BitArrayRegisterAccessor name(type value) const { \ + return BitArrayRegisterAccessor(*this, offset, value); \ + } + +#define DEFINE_RW1C_BIT_ARRAY_REGISTER(name, type, offset) \ + __attribute__((always_inline)) BitArrayRegisterAccessor name() const { \ + return BitArrayRegisterAccessor(*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 diff --git a/fusee/fusee-primary/src/reg/reg_xusb_dev.h b/fusee/fusee-primary/src/reg/reg_xusb_dev.h new file mode 100644 index 000000000..0df58679d --- /dev/null +++ b/fusee/fusee-primary/src/reg/reg_xusb_dev.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/reg/reg_xusb_padctl.h b/fusee/fusee-primary/src/reg/reg_xusb_padctl.h new file mode 100644 index 000000000..d0781f171 --- /dev/null +++ b/fusee/fusee-primary/src/reg/reg_xusb_padctl.h @@ -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 . + */ + +#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 diff --git a/fusee/fusee-primary/src/utils.h b/fusee/fusee-primary/src/utils.h index d3eaea88e..ef3c6cede 100644 --- a/fusee/fusee-primary/src/utils.h +++ b/fusee/fusee-primary/src/utils.h @@ -22,6 +22,8 @@ #include #include +#ifndef BIT + #define BIT(n) (1u << (n)) #define BITL(n) (1ull << (n)) #define MASK(n) (BIT(n) - 1) @@ -29,6 +31,8 @@ #define MASK2(a,b) (MASK(a) & ~MASK(b)) #define MASK2L(a,b) (MASKL(a) & ~MASKL(b)) +#endif + #define MAKE_REG32(a) (*(volatile uint32_t *)(a)) #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) { extern uint8_t __chainloader_start__[], __chainloader_end__[]; extern uint8_t __stack_bottom__[], __stack_top__[]; + extern uint8_t __dram_start__[], __dram_end__[]; extern uint8_t __start__[], __end__[]; uint8_t *start = (uint8_t *)addr, *end = start + size; return overlaps_a(start, end, __chainloader_start__, __chainloader_end__) || 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__); } diff --git a/libraries/libvapours/include/vapours/results.hpp b/libraries/libvapours/include/vapours/results.hpp index f10e5af32..6aa2a283a 100644 --- a/libraries/libvapours/include/vapours/results.hpp +++ b/libraries/libvapours/include/vapours/results.hpp @@ -63,3 +63,4 @@ /* Unofficial. */ #include +#include diff --git a/libraries/libvapours/include/vapours/results/xusb_gadget_results.hpp b/libraries/libvapours/include/vapours/results/xusb_gadget_results.hpp new file mode 100644 index 000000000..61ee4e025 --- /dev/null +++ b/libraries/libvapours/include/vapours/results/xusb_gadget_results.hpp @@ -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 . + */ + +#pragma once +#include + +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); + +} From bd5ec4be4e9cd7a26986c31076f16fe5454978a4 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Wed, 28 Oct 2020 21:25:54 -0700 Subject: [PATCH 10/14] fastboot: add 'flash ams' command, for extracting a zip file to SD --- .../src/fastboot/fastboot_impl.cpp | 127 +- .../src/fastboot/fastboot_impl.h | 11 +- fusee/fusee-primary/src/lib/miniz.c | 4038 +++++++++++++++++ fusee/fusee-primary/src/lib/miniz.h | 889 ++++ 4 files changed, 5063 insertions(+), 2 deletions(-) create mode 100644 fusee/fusee-primary/src/lib/miniz.c create mode 100644 fusee/fusee-primary/src/lib/miniz.h diff --git a/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp b/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp index 29c82427c..85476e8f2 100644 --- a/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp +++ b/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp @@ -17,6 +17,7 @@ #include "fastboot.h" #include "fastboot_gadget.h" +#include "../lib/miniz.h" extern "C" { #include "../lib/log.h" #include "../utils.h" @@ -74,6 +75,39 @@ struct android_boot_image_v2 { 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 { @@ -157,7 +191,28 @@ namespace ams { } Result FastbootImpl::Flash(const char *argument) { - return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "unknown partition"); + 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"); + } + + 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 { + return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, "unknown partition"); + } } Result FastbootImpl::Reboot(const char *argment) { @@ -221,8 +276,78 @@ namespace ams { 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) { + return this->gadget.SendResponse(ResponseDisposition::ReadHostCommand, ResponseToken::FAIL, this->flash_ams.error); + } + + if (this->flash_ams.file_index == this->flash_ams.num_files) { + 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 diff --git a/fusee/fusee-primary/src/fastboot/fastboot_impl.h b/fusee/fusee-primary/src/fastboot/fastboot_impl.h index c9013965d..803d1439b 100644 --- a/fusee/fusee-primary/src/fastboot/fastboot_impl.h +++ b/fusee/fusee-primary/src/fastboot/fastboot_impl.h @@ -18,6 +18,8 @@ #include +#include "../lib/miniz.h" + namespace ams { namespace fastboot { @@ -38,10 +40,16 @@ namespace ams { enum class Action { Invalid, + FlashAms, } current_action; union { - /* Actions */ + struct { + mz_zip_archive zip; + mz_uint num_files; + mz_uint file_index; + const char *error; + } flash_ams; }; /* Commands */ @@ -53,6 +61,7 @@ namespace ams { Result OemCRC32(const char *arg); /* Continuations */ + Result ContinueFlashAms(); }; } // namespace fastboot diff --git a/fusee/fusee-primary/src/lib/miniz.c b/fusee/fusee-primary/src/lib/miniz.c new file mode 100644 index 000000000..e17fa6658 --- /dev/null +++ b/fusee/fusee-primary/src/lib/miniz.c @@ -0,0 +1,4038 @@ +/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Change History + 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): + - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug + would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() + (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). + - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size + - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. + Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). + - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes + - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed + - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. + - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti + - Merged MZ_FORCEINLINE fix from hdeanclark + - Fix include before config #ifdef, thanks emil.brink + - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can + set it to 1 for real-time compression). + - Merged in some compiler fixes from paulharris's github repro. + - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. + - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. + - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. + - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled + - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch + 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). + 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. + - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. + - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. + - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly + "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). + - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. + - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. + - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. + - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) + - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). + 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. + level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. + 5/28/11 v1.11 - Added statement from unlicense.org + 5/27/11 v1.10 - Substantial compressor optimizations: + - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a + - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). + - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. + - Refactored the compression code for better readability and maintainability. + - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large + drop in throughput on some files). + 5/15/11 v1.09 - Initial stable release. + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + 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); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ + +#include "miniz.h" + +#ifndef MINIZ_HEADER_FILE_ONLY + +#pragma GCC optimize ("Os") + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; + +#include +#include + +#include "log.h" + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC + #define MZ_MALLOC(x) NULL + #define MZ_FREE(x) (void)x, ((void)0) + #define MZ_REALLOC(p, x) NULL +#else + #define MZ_MALLOC(x) malloc(x) + #define MZ_FREE(x) free(x) + #define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) +#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) + #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else + #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) + #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#ifdef _MSC_VER + #define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) + #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) +#else + #define MZ_FORCEINLINE inline +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +// ------------------- zlib-style API's + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; + if (!ptr) return MZ_ADLER32_INIT; + while (buf_len) { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + return (s2 << 16) + s1; +} + +// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) return MZ_CRC32_INIT; + crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } + return ~crcu32; +} + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +#ifndef MINIZ_NO_ZLIB_APIS + +static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } +static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } +static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; + if (!pStream->avail_out) return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; + for ( ; ; ) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; // Can't make forward progress without some input. + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state* pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + + pState = (inflate_state*)pStream->state; + if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; pState->m_first_call = 0; + if (pState->m_last_status < 0) return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + // flush != MZ_FINISH then we must assume there's more input. + if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for ( ; ; ) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. + else if (flush == MZ_FINISH) + { + // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +const char *mz_error(int err) +{ + static struct { int m_err; const char *m_pDesc; } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, + { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif //MINIZ_NO_ZLIB_APIS + +// ------------------- Low-level Decompression (completely independent from all compression API's) + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN switch(r->m_state) { case 0: +#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END +#define TINFL_CR_FINISH } + +// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never +// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. +#define TINFL_GET_BYTE(state_index, c) do { \ + if (pIn_buf_cur >= pIn_buf_end) { \ + for ( ; ; ) { \ + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ + TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ + if (pIn_buf_cur < pIn_buf_end) { \ + c = *pIn_buf_cur++; \ + break; \ + } \ + } else { \ + c = 0; \ + break; \ + } \ + } \ + } else c = *pIn_buf_cur++; } MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END + +// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. +// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a +// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the +// bit buffer contains >=15 bits (deflate's max. Huffman code size). +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ + } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ + } while (num_bits < 15); + +// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read +// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully +// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. +// The slow path is only executed at the very end of the input buffer. +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ + int temp; mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ + } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END + +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) +{ + static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; + static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } + + num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } + while (pIn_buf_cur >= pIn_buf_end) + { + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) + { + TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); + } + else + { + TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); + } + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; + r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for ( i = 0; i <= 143; ++i) *p++ = 8; + for ( ; i <= 255; ++i) *p++ = 9; + for ( ; i <= 279; ++i) *p++ = 7; + for ( ; i <= 287; ++i) *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } + r->m_table_sizes[2] = 19; + } + for ( ; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; + cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) + { + mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for ( ; ; ) + { + mz_uint8 *pSrc; + for ( ; ; ) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } +#else + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + counter = sym2; bit_buf >>= code_len; num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + bit_buf >>= code_len; num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) break; + + num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; pSrc += 3; + } while ((int)(counter -= 3) > 2); + if ((int)counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int)counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + TINFL_CR_FINISH + +common_exit: + r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +// Higher level helper functions. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) break; + new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +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_decompressor decomp; tinfl_status status; tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +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) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +// ------------------- Low-level Compression (independent from all decompression API's) + +// Purposely making these tables static for faster init and thread safety. +static const mz_uint16 s_tdefl_len_sym[256] = { + 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, + 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, + 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, + 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, + 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, + 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, + 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, + 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; + +static const mz_uint8 s_tdefl_len_extra[256] = { + 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, + 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = { + 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, + 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, + 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = { + 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7 }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = { + 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, + 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, + 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = { + 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, + 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; + +// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. +typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; +static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32* pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } + for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } + } + return pCur_syms; +} + +// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } + A[0].m_key += A[1].m_key; root = 0; leaf = 2; + for (next=1; next < n-1; next++) + { + if (leaf>=n || A[root].m_key=n || (root=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; + avbl = 1; used = dpth = 0; root = n-2; next = n-1; + while (avbl>0) + { + while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } + while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } + avbl = 2*used; dpth++; used = 0; + } +} + +// Limits canonical Huffman code table's max code size. +enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; mz_uint32 total = 0; if (code_list_len <= 1) return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; + code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) do { \ + mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ + while (d->m_bits_in >= 8) { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ +} MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ + if (rle_repeat_count < 3) { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } else { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ +} rle_repeat_count = 0; } } + +#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ + if (rle_z_count < 3) { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ + } else if (rle_z_count <= 10) { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } else { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ +} rle_z_count = 0; } } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) *p++ = 8; + for ( ; i <= 255; ++i) *p++ = 9; + for ( ; i <= 279; ++i) *p++ = 7; + for ( ; i <= 287; ++i) *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + // This sequence coaxes MSVC into using cmov's vs. jmp's. + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64*)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. + if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) + { + mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } + } + else + { + mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + if (!probe_len) + { + *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; + if (probe_len > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; + c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + // Simple lazy/greedy parsing state machine. + len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + // Move the lookahead forward by len_to_move bytes. + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); + // Check if it's time to flush the current LZ codes to the internal output buffer. + if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) + { + int n; + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +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) +{ + if (!d) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; + d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +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) +{ + tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; + pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; + do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); + pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; + p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; + } + memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; + *pOut_len = out_buf.m_size; return out_buf.m_pBuf; +} + +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) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) return 0; + out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; + return out_buf.m_size; +} + +#ifndef MINIZ_NO_ZLIB_APIS +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} +#endif //MINIZ_NO_ZLIB_APIS + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) +#endif + +// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at +// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. +// This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. +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) +{ + // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; + if (!pComp) return NULL; + MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } + // write dummy header + for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); + // compress image data + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + // write real header + *pLen_out = out_buf.m_size-41; + { + static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; + mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, + 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0, + (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54}; + c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + // write footer (IDAT CRC-32, followed by IEND chunk) + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); + // compute final size of file, grab compressed data buffer and return + *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; +} +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +} + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// ------------------- .ZIP archive reading + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. +enum +{ + // ZIP archive identifiers and record sizes + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + // Central directory header record offsets + MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + // Local directory header offsets + MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + // End of central directory offsets + MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, +}; + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; + if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; + pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; + memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif + +#ifndef MINIZ_NO_STDIO +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef MINIZ_NO_TIME + (void)pFilename; *pDOS_date = *pDOS_time = 0; +#else + struct MZ_FILE_STAT_STRUCT file_stat; + // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); +#endif // #ifdef MINIZ_NO_TIME + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) +{ + struct utimbuf t; t.actime = access_time; t.modtime = modified_time; + return !utime(pFilename, &t); +} +#endif // #ifndef MINIZ_NO_TIME +#endif // #ifndef MINIZ_NO_STDIO + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) { + print(SCREEN_LOG_LEVEL_DEBUG, "failing init early\n"); + return MZ_FALSE; + } + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + pZip->m_pState = &pZip->m_State; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END + +// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + int start = (size - 2) >> 1, end; + while (start >= 0) + { + int child, root = start; + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= size) + break; + child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + start--; + } + + end = size - 1; + while (end > 0) + { + int child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= end) + break; + child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) +{ + mz_uint cdir_size, num_this_disk, cdir_disk_index; + mz_uint64 cdir_ofs; + mz_int64 cur_file_ofs; + const mz_uint8 *p; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + // Find the end of central directory record by scanning the file from the end towards the beginning. + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for ( ; ; ) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + for (i = n - 4; i >= 0; --i) + if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + break; + if (i >= 0) + { + cur_file_ofs += i; + break; + } + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return MZ_FALSE; + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + // Read and verify the end of central directory record. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || + ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) + return MZ_FALSE; + + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return MZ_FALSE; + + if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return MZ_FALSE; + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + + // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return MZ_FALSE; + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return MZ_FALSE; + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return MZ_FALSE; + + // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, comp_size, decomp_size, disk_index; + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return MZ_FALSE; + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) + return MZ_FALSE; + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index != num_this_disk) && (disk_index != 1)) + return MZ_FALSE; + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return MZ_FALSE; + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return MZ_FALSE; + n -= total_header_size; p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return MZ_FALSE; + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) +{ + if (!mz_zip_reader_init_internal(pZip, flags)) { + print(SCREEN_LOG_LEVEL_DEBUG, "failed to init internal\n"); + return MZ_FALSE; + } + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + pZip->m_pState->m_mem_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + print(SCREEN_LOG_LEVEL_DEBUG, "failed to read central dir\n"); + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + mz_uint64 file_size; + MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return MZ_FALSE; + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + file_size = MZ_FTELL64(pFile); + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & 1); +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, external_attr; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + + // First see if the filename ends with a '/' character. + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. + // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. + // FIXME: Remove this check? Is it necessary - we already check the filename. + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & 0x10) != 0) + return MZ_TRUE; + + return MZ_FALSE; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if ((!p) || (!pStat)) + return MZ_FALSE; + + // Unpack the central directory record. + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + // Copy as much of the filename and comment as possible. + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; + + return MZ_TRUE; +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + int l = 0, h = size - 1; + while (l <= h) + { + int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + return file_index; + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + return -1; +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint file_index; size_t name_len, comment_len; + if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return -1; + if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + return mz_zip_reader_locate_file_binary_search(pZip, pName); + name_len = strlen(pName); if (name_len > 0xFFFF) return -1; + comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) + return file_index; + } + return -1; +} + +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) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((buf_size) && (!pBuf)) + return MZ_FALSE; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). + // I'm torn how to handle this case - should it fail instead? + if (mz_zip_reader_is_file_a_directory(pZip, file_index)) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Ensure supplied output buffer is large enough. + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return MZ_FALSE; + return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); + } + + // Decompress the file either directly from memory or from a file input buffer. + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + // Read directly from the archive in memory. + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + // Use a user provided read buffer. + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + // Temporarily allocate a read buffer. + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#endif + return MZ_FALSE; + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +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) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +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) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +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) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + if (!p) + return NULL; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#endif + return NULL; + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + return NULL; + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + { + if (pSize) *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +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) +{ + int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). + // I'm torn how to handle this case - should it fail instead? + if (mz_zip_reader_is_file_a_directory(pZip, file_index)) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + // Decompress the file either directly from memory or from a file input buffer. + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pState->m_pMem) + { +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#endif + return MZ_FALSE; + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + status = TINFL_STATUS_FAILED; + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + status = TINFL_STATUS_FAILED; + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + status = TINFL_STATUS_FAILED; + break; + } + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +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) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); +} + +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 status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return MZ_FALSE; + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + if (MZ_FCLOSE(pFile) == EOF) + return MZ_FALSE; +#ifndef MINIZ_NO_TIME + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + return status; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} +#endif + +// ------------------- .ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } +static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (pZip->m_file_offset_alignment) + { + // Ensure user specified file offset alignment is a power of 2. + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return MZ_FALSE; + } + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return MZ_FALSE; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); +#ifdef _MSC_VER + if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#else + if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#endif + return 0; + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + return 0; + pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + MZ_FILE *pFile; + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_pFile = pFile; + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + cur_ofs += n; size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState; + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + // No sense in trying to write to an archive that's already at the support max size + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + pFilename; return MZ_FALSE; +#else + // Archive is being read from stdio - try to reopen as writable. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + if (!pFilename) + return MZ_FALSE; + pZip->m_pWrite = mz_zip_file_write_func; + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. + mz_zip_reader_end(pZip); + return MZ_FALSE; + } +#endif // #ifdef MINIZ_NO_STDIO + } + else if (pState->m_pMem) + { + // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + } + // Archive is being read via a user provided read function - make sure the user has specified a write function too. + else if (!pZip->m_pWrite) + return MZ_FALSE; + + // Start writing new files at the archive's current central directory location. + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_central_directory_file_ofs = 0; + + return MZ_TRUE; +} + +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) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + // No zip64 support yet + if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return MZ_FALSE; + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + // Try to push the central directory array back into its original state. + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. + if (*pArchive_name == '/') + return MZ_FALSE; + while (*pArchive_name) + { + if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + return MZ_FALSE; + pArchive_name++; + } + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return MZ_FALSE; + cur_file_ofs += s; n -= s; + } + return MZ_TRUE; +} + +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) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return MZ_FALSE; + // No zip64 support yet + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + +#ifndef MINIZ_NO_TIME + { + time_t cur_time; time(&cur_time); + mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif // #ifndef MINIZ_NO_TIME + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + // Set DOS Subdirectory attribute bit. + ext_attributes |= 0x10; + // Subdirectories cannot contain data. + if ((buf_size) || (uncomp_size)) + return MZ_FALSE; + } + + // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return MZ_FALSE; + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return MZ_FALSE; + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + method = MZ_DEFLATED; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +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) +{ + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + MZ_FILE *pSrc_file = NULL; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) + return MZ_FALSE; + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return MZ_FALSE; + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + if (uncomp_size > 0xFFFFFFFF) + { + // No zip64 support yet + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + for ( ; ; ) + { + size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + + if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) + break; + + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_remaining -= in_buf_size; + + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + break; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + MZ_FCLOSE(pSrc_file); pSrc_file = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes; + mz_uint64 comp_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; const mz_uint8 *pSrc_central_header; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) + return MZ_FALSE; + pState = pZip->m_pState; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + cur_dst_file_ofs = pZip->m_archive_size; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + cur_dst_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) + return MZ_FALSE; + + while (comp_bytes_remaining) + { + n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_dst_file_ofs += n; + + comp_bytes_remaining -= n; + } + + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + // Copy data descriptor + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + // no zip64 support yet + if (cur_dst_file_ofs > 0xFFFFFFFF) + return MZ_FALSE; + + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return MZ_FALSE; + + n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + if (pState->m_central_dir.m_size > 0xFFFFFFFF) + return MZ_FALSE; + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + + pState = pZip->m_pState; + + // no zip64 support yet + if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + // Write central directory + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return MZ_FALSE; + pZip->m_archive_size += central_dir_size; + } + + // Write end of central directory record + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) + return MZ_FALSE; +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return MZ_FALSE; +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_archive_size += sizeof(hdr); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) + return MZ_FALSE; + if (pZip->m_pWrite != mz_zip_heap_write_func) + return MZ_FALSE; + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *pBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + return MZ_FALSE; + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +#ifndef MINIZ_NO_STDIO +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) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + MZ_CLEAR_OBJ(zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + // Create a new archive. + if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) + return MZ_FALSE; + created_new_archive = MZ_TRUE; + } + else + { + // Append to an existing archive. + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return MZ_FALSE; + if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) + { + mz_zip_reader_end(&zip_archive); + return MZ_FALSE; + } + } + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) + if (!mz_zip_writer_finalize_archive(&zip_archive)) + status = MZ_FALSE; + if (!mz_zip_writer_end(&zip_archive)) + status = MZ_FALSE; + if ((!status) && (created_new_archive)) + { + // It's a new archive and something went wrong, so just delete it. + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + return status; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + int file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + return NULL; + + MZ_CLEAR_OBJ(zip_archive); + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return NULL; + + if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + + mz_zip_reader_end(&zip_archive); + return p; +} + +#endif // #ifndef MINIZ_NO_STDIO + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_FILE_ONLY + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/fusee/fusee-primary/src/lib/miniz.h b/fusee/fusee-primary/src/lib/miniz.h new file mode 100644 index 000000000..90e4899cb --- /dev/null +++ b/fusee/fusee-primary/src/lib/miniz.h @@ -0,0 +1,889 @@ +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include + +// 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 +#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 + #include + + #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 + #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 + #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 + #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 + #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 + #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 From 5c73dd145321a2638c8c4c59fcd022af26696d99 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sat, 7 Nov 2020 14:36:28 -0800 Subject: [PATCH 11/14] fusee-primary: use reference counting for sd device/filesystem --- fusee/fusee-primary/src/fs_utils.c | 107 ++++++++++++++++++++--------- fusee/fusee-primary/src/fs_utils.h | 6 ++ fusee/fusee-primary/src/main.c | 4 +- 3 files changed, 83 insertions(+), 34 deletions(-) diff --git a/fusee/fusee-primary/src/fs_utils.c b/fusee/fusee-primary/src/fs_utils.c index ff5a18bb5..9c773e06c 100644 --- a/fusee/fusee-primary/src/fs_utils.c +++ b/fusee/fusee-primary/src/fs_utils.c @@ -20,57 +20,98 @@ #include "lib/log.h" FATFS sd_fs; -static bool g_sd_mounted = false; -static bool g_sd_initialized = false; +static int g_sd_device_rc = 0; +static int g_sd_fs_rc = 0; sdmmc_t g_sd_sdmmc; 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) { /* Already mounted. */ - if (g_sd_mounted) + if (g_sd_fs_rc++ > 0) return true; - /* Enable AHB redirection if necessary. */ - mc_acquire_ahb_redirect(); - - if (!g_sd_initialized) { - /* Initialize SD. */ - if (sdmmc_device_sd_init(&g_sd_device, &g_sd_sdmmc, SDMMC_BUS_WIDTH_4BIT, SDMMC_SPEED_UHS_SDR104)) - { - 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"); + /* Make sure SD device is initialized. */ + if (!acquire_sd_device()) { + g_sd_fs_rc--; + return false; + } + + /* Mount SD filesystem. */ + if (f_mount(&sd_fs, "", 1) == FR_OK) { + print(SCREEN_LOG_LEVEL_INFO, "Mounted SD card!\n"); + return true; } - return g_sd_mounted; + release_sd_device(); + + g_sd_fs_rc--; + + return false; } void unmount_sd(void) { - if (g_sd_mounted) - { - f_mount(NULL, "", 1); - sdmmc_device_finish(&g_sd_device); - g_sd_mounted = false; - } + if (--g_sd_fs_rc > 0) + return; + + f_mount(NULL, "", 1); - /* Disable AHB redirection if necessary. */ - mc_release_ahb_redirect(); + release_sd_device(); +} + +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) { /* SD card hasn't been mounted yet. */ - if (!g_sd_mounted) + if (g_sd_fs_rc == 0) return 0; /* Open the file for reading. */ @@ -90,7 +131,7 @@ uint32_t get_file_size(const char *filename) int read_from_file(void *dst, uint32_t dst_size, const char *filename) { /* SD card hasn't been mounted yet. */ - if (!g_sd_mounted) + if (g_sd_fs_rc == 0) return 0; /* Open the file for reading. */ @@ -112,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) { /* SD card hasn't been mounted yet. */ - if (!g_sd_mounted) + if (g_sd_fs_rc == 0) return 0; /* Open the file for writing. */ @@ -129,4 +170,4 @@ int write_to_file(void *src, uint32_t src_size, const char *filename) f_close(&f); return (res == FR_OK) ? (int)bw : 0; -} \ No newline at end of file +} diff --git a/fusee/fusee-primary/src/fs_utils.h b/fusee/fusee-primary/src/fs_utils.h index 1e25b2b82..f33ebc851 100644 --- a/fusee/fusee-primary/src/fs_utils.h +++ b/fusee/fusee-primary/src/fs_utils.h @@ -26,8 +26,14 @@ extern sdmmc_t g_sd_sdmmc; extern sdmmc_device_t g_sd_device; +bool acquire_sd_device(void); +void release_sd_device(void); bool mount_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); 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); diff --git a/fusee/fusee-primary/src/main.c b/fusee/fusee-primary/src/main.c index 7263f9eee..1c8cf169d 100644 --- a/fusee/fusee-primary/src/main.c +++ b/fusee/fusee-primary/src/main.c @@ -81,7 +81,9 @@ static void setup_env(void) { setup_exception_handlers(); /* Mount the SD card. */ - mount_sd(); + if (!mount_sd()) { + fatal_error("Failed to mount SD card!\n"); + } } static void cleanup_env(void) { From d1078b5c820520ba74793ae245ce9461a0aefef2 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sat, 7 Nov 2020 14:37:07 -0800 Subject: [PATCH 12/14] fastboot: add support for flashing sd directly --- .../src/fastboot/fastboot_impl.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp b/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp index 85476e8f2..e0f855907 100644 --- a/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp +++ b/fusee/fusee-primary/src/fastboot/fastboot_impl.cpp @@ -21,6 +21,8 @@ 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" } @@ -28,6 +30,8 @@ extern "C" { #include #include +#include + uint32_t crc32(uint32_t crc, const uint8_t *buf, size_t len) { int k; @@ -203,6 +207,10 @@ namespace ams { 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; @@ -210,6 +218,32 @@ namespace ams { 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"); } @@ -300,10 +334,14 @@ namespace ams { 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, ""); } From 182b45b604a068b099d1901a6636173b2c5681bd Mon Sep 17 00:00:00 2001 From: misson20000 Date: Sat, 7 Nov 2020 14:37:57 -0800 Subject: [PATCH 13/14] Makefile: add rules for generating and flashing an SD card image directly --- .gitignore | 1 + Makefile | 166 ++++++++++++++++++++++++++++------------------------- 2 files changed, 90 insertions(+), 77 deletions(-) diff --git a/.gitignore b/.gitignore index 78f859ac8..1a2ff87e3 100644 --- a/.gitignore +++ b/.gitignore @@ -95,3 +95,4 @@ sept/sept-secondary/KEYS.py **/build_nintendo_nx_arm **/build_nintendo_nx_x64 **/build_nintendo_nx_x86 +extras \ No newline at end of file diff --git a/Makefile b/Makefile index 38848b5f9..efa554dbe 100644 --- a/Makefile +++ b/Makefile @@ -39,87 +39,79 @@ clean: $(MAKE) -C fusee clean rm -rf out -dist-no-debug: all - $(eval MAJORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MAJOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \ +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:] \ - | cut -d' ' -f3)) - $(eval MINORVER = $(shell grep 'define ATMOSPHERE_RELEASE_VERSION_MINOR\b' libraries/libvapours/include/vapours/ams/ams_api_version.h \ + | cut -d' ' -f3) +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 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) - rm -rf out - mkdir atmosphere-$(AMSVER) - mkdir atmosphere-$(AMSVER)/atmosphere - mkdir atmosphere-$(AMSVER)/sept - mkdir atmosphere-$(AMSVER)/switch - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008 - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032 - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034 - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036 - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037 - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042 - mkdir -p atmosphere-$(AMSVER)/atmosphere/fatal_errors - mkdir -p atmosphere-$(AMSVER)/atmosphere/config_templates - mkdir -p atmosphere-$(AMSVER)/atmosphere/config - cp fusee/fusee-primary/fusee-primary.bin atmosphere-$(AMSVER)/atmosphere/reboot_payload.bin - cp fusee/fusee-mtc/fusee-mtc.bin atmosphere-$(AMSVER)/atmosphere/fusee-mtc.bin - cp fusee/fusee-secondary/fusee-secondary-experimental.bin atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin - cp fusee/fusee-secondary/fusee-secondary-experimental.bin atmosphere-$(AMSVER)/sept/payload.bin - cp sept/sept-primary/sept-primary.bin atmosphere-$(AMSVER)/sept/sept-primary.bin - cp sept/sept-secondary/sept-secondary.bin atmosphere-$(AMSVER)/sept/sept-secondary.bin || true - cp sept/sept-secondary/sept-secondary_00.enc atmosphere-$(AMSVER)/sept/sept-secondary_00.enc - cp sept/sept-secondary/sept-secondary_01.enc atmosphere-$(AMSVER)/sept/sept-secondary_01.enc - cp sept/sept-secondary/sept-secondary_dev_00.enc atmosphere-$(AMSVER)/sept/sept-secondary_dev_00.enc - cp sept/sept-secondary/sept-secondary_dev_01.enc atmosphere-$(AMSVER)/sept/sept-secondary_dev_01.enc - cp config_templates/BCT.ini atmosphere-$(AMSVER)/atmosphere/config/BCT.ini - cp config_templates/override_config.ini atmosphere-$(AMSVER)/atmosphere/config_templates/override_config.ini - cp config_templates/system_settings.ini atmosphere-$(AMSVER)/atmosphere/config_templates/system_settings.ini - cp config_templates/exosphere.ini atmosphere-$(AMSVER)/atmosphere/config_templates/exosphere.ini - cp -r config_templates/kip_patches atmosphere-$(AMSVER)/atmosphere/kip_patches - cp -r config_templates/hbl_html atmosphere-$(AMSVER)/atmosphere/hbl_html - cp stratosphere/boot2/boot2.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008/exefs.nsp - cp stratosphere/dmnt/dmnt.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D/exefs.nsp - cp stratosphere/erpt/erpt.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B/exefs.nsp - cp stratosphere/eclct.stub/eclct.stub.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/exefs.nsp - cp stratosphere/fatal/fatal.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034/exefs.nsp - cp stratosphere/creport/creport.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036/exefs.nsp - cp stratosphere/ro/ro.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/exefs.nsp - cp stratosphere/jpegdec/jpegdec.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C/exefs.nsp - cp stratosphere/pgl/pgl.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042/exefs.nsp - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags - touch atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags/boot2.flag - mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags - touch atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags/boot2.flag - 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 - cd atmosphere-$(AMSVER); zip -r ../atmosphere-EXPERIMENTAL-$(AMSVER).zip ./*; cd ../; - cp fusee/fusee-secondary/fusee-secondary.bin atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin - cp fusee/fusee-secondary/fusee-secondary.bin atmosphere-$(AMSVER)/sept/payload.bin - cd atmosphere-$(AMSVER); zip -r ../atmosphere-$(AMSVER).zip ./*; cd ../; - rm -r atmosphere-$(AMSVER) - mkdir out - mv atmosphere-EXPERIMENTAL-$(AMSVER).zip out/atmosphere-EXPERIMENTAL-$(AMSVER).zip - mv atmosphere-$(AMSVER).zip out/atmosphere-$(AMSVER).zip + | cut -d' ' -f3) +AMSVER = $(MAJORVER).$(MINORVER).$(MICROVER)-$(AMSREV) + +out/atmosphere-$(AMSVER): all + rm -rf out/atmosphere-$(AMSVER) + mkdir -p out/atmosphere-$(AMSVER) + mkdir -p out/atmosphere-$(AMSVER)/atmosphere + mkdir -p out/atmosphere-$(AMSVER)/sept + mkdir -p out/atmosphere-$(AMSVER)/switch + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008 + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032 + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034 + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036 + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037 + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042 + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/fatal_errors + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/config_templates + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/config + cp fusee/fusee-primary/fusee-primary.bin out/atmosphere-$(AMSVER)/atmosphere/reboot_payload.bin + cp fusee/fusee-mtc/fusee-mtc.bin out/atmosphere-$(AMSVER)/atmosphere/fusee-mtc.bin + cp fusee/fusee-secondary/fusee-secondary-experimental.bin out/atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin + cp fusee/fusee-secondary/fusee-secondary-experimental.bin out/atmosphere-$(AMSVER)/sept/payload.bin + cp sept/sept-primary/sept-primary.bin out/atmosphere-$(AMSVER)/sept/sept-primary.bin + cp sept/sept-secondary/sept-secondary.bin out/atmosphere-$(AMSVER)/sept/sept-secondary.bin || true + cp sept/sept-secondary/sept-secondary_00.enc out/atmosphere-$(AMSVER)/sept/sept-secondary_00.enc + cp sept/sept-secondary/sept-secondary_01.enc out/atmosphere-$(AMSVER)/sept/sept-secondary_01.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_dev_01.enc out/atmosphere-$(AMSVER)/sept/sept-secondary_dev_01.enc + cp config_templates/BCT.ini out/atmosphere-$(AMSVER)/atmosphere/config/BCT.ini + cp config_templates/override_config.ini out/atmosphere-$(AMSVER)/atmosphere/config_templates/override_config.ini + cp config_templates/system_settings.ini out/atmosphere-$(AMSVER)/atmosphere/config_templates/system_settings.ini + cp config_templates/exosphere.ini out/atmosphere-$(AMSVER)/atmosphere/config_templates/exosphere.ini + cp -r config_templates/kip_patches out/atmosphere-$(AMSVER)/atmosphere/kip_patches + cp -r config_templates/hbl_html out/atmosphere-$(AMSVER)/atmosphere/hbl_html + cp stratosphere/boot2/boot2.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000008/exefs.nsp + cp stratosphere/dmnt/dmnt.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000000D/exefs.nsp + cp stratosphere/erpt/erpt.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000002B/exefs.nsp + cp stratosphere/eclct.stub/eclct.stub.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/exefs.nsp + cp stratosphere/fatal/fatal.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034/exefs.nsp + cp stratosphere/creport/creport.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036/exefs.nsp + cp stratosphere/ro/ro.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/exefs.nsp + cp stratosphere/jpegdec/jpegdec.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C/exefs.nsp + cp stratosphere/pgl/pgl.nsp out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000042/exefs.nsp + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags + touch out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags/boot2.flag + mkdir -p out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags + touch out/atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags/boot2.flag + cp troposphere/reboot_to_payload/reboot_to_payload.nro out/atmosphere-$(AMSVER)/switch/reboot_to_payload.nro + cp troposphere/daybreak/daybreak.nro out/atmosphere-$(AMSVER)/switch/daybreak.nro + +out/atmosphere-EXPERIMENTAL-$(AMSVER): out/atmosphere-$(AMSVER) + rm -rf out/atmosphere-EXPERIMENTAL-$(AMSVER) + cp -r out/atmosphere-$(AMSVER) out/atmosphere-EXPERIMENTAL-$(AMSVER) + cp fusee/fusee-secondary/fusee-secondary.bin out/atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin + cp fusee/fusee-secondary/fusee-secondary.bin out/atmosphere-$(AMSVER)/sept/payload.bin + +dist-no-debug: out/atmosphere-$(AMSVER) out/atmosphere-EXPERIMENTAL-$(AMSVER) + cd out/atmosphere-EXPERIMENTAL-$(AMSVER); zip -r ../atmosphere-EXPERIMENTAL-$(AMSVER).zip ./*; cd ../; + cd out/atmosphere-$(AMSVER); zip -r ../atmosphere-$(AMSVER).zip ./*; cd ../; cp fusee/fusee-primary/fusee-primary.bin out/fusee-primary.bin 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 mkdir atmosphere-$(AMSVER)-debug cp fusee/fusee-primary/fusee-primary.elf atmosphere-$(AMSVER)-debug/fusee-primary.elf @@ -154,5 +146,25 @@ dist: dist-no-debug rm -r atmosphere-$(AMSVER)-debug 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 From 5be26c6c9205793bae1617c6b170704f4f680e19 Mon Sep 17 00:00:00 2001 From: misson20000 Date: Fri, 20 Nov 2020 17:09:28 -0800 Subject: [PATCH 14/14] fusee-primary: reorganize main to give some options when SD mount fails --- fusee/fusee-primary/src/fastboot/fastboot.cpp | 34 ++-- fusee/fusee-primary/src/fastboot/fastboot.h | 2 +- fusee/fusee-primary/src/main.c | 177 +++++++++++++----- fusee/fusee-primary/src/panic.c | 6 +- fusee/fusee-primary/src/stage2.c | 7 + 5 files changed, 160 insertions(+), 66 deletions(-) diff --git a/fusee/fusee-primary/src/fastboot/fastboot.cpp b/fusee/fusee-primary/src/fastboot/fastboot.cpp index 4795452be..c89ee74e9 100644 --- a/fusee/fusee-primary/src/fastboot/fastboot.cpp +++ b/fusee/fusee-primary/src/fastboot/fastboot.cpp @@ -26,16 +26,19 @@ extern "C" { 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 should_enter = bct0->fastboot_force_enable; +extern "C" fastboot_return fastboot_enter(const bct0_t *bct0, bool force) { + bool should_enter = force || bct0->fastboot_force_enable; - log_setup_display(); - - if (!should_enter) { + 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) { @@ -48,20 +51,25 @@ extern "C" fastboot_return fastboot_enter(const bct0_t *bct0) { 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; } } - if (!should_enter) { - log_cleanup_display(); - return FASTBOOT_SKIPPED; - } - - print(SCREEN_LOG_LEVEL_DEBUG, "Entering fastboot.\n"); + 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"); @@ -71,6 +79,6 @@ extern "C" fastboot_return fastboot_enter(const bct0_t *bct0) { fastboot_return r = fastboot_gadget.Run(); log_cleanup_display(); - + return r; } diff --git a/fusee/fusee-primary/src/fastboot/fastboot.h b/fusee/fusee-primary/src/fastboot/fastboot.h index 5c79444e1..2c3792e19 100644 --- a/fusee/fusee-primary/src/fastboot/fastboot.h +++ b/fusee/fusee-primary/src/fastboot/fastboot.h @@ -29,7 +29,7 @@ enum fastboot_return { FASTBOOT_CHAINLOAD, }; -enum fastboot_return fastboot_enter(const bct0_t *bct0); +enum fastboot_return fastboot_enter(const bct0_t *bct0, bool force); #ifdef __cplusplus } diff --git a/fusee/fusee-primary/src/main.c b/fusee/fusee-primary/src/main.c index 1c8cf169d..5d6fd7f86 100644 --- a/fusee/fusee-primary/src/main.c +++ b/fusee/fusee-primary/src/main.c @@ -28,6 +28,7 @@ #include "lib/vsprintf.h" #include "display/video_fb.h" #include "fastboot/fastboot.h" +#include "btn.h" extern void (*__program_exit_callback)(int rc); @@ -79,16 +80,6 @@ static void setup_env(void) { /* Set up the exception handlers. */ setup_exception_handlers(); - - /* Mount the SD card. */ - if (!mount_sd()) { - fatal_error("Failed to mount SD card!\n"); - } -} - -static void cleanup_env(void) { - /* Unmount the SD card. */ - unmount_sd(); } static void exit_callback(int rc) { @@ -96,8 +87,8 @@ static void exit_callback(int rc) { relocate_and_chainload(); } -int main(void) { - const char *bct0_string; +int main(void) { + const char *bct0_string = DEFAULT_BCT0; stage2_args_t *stage2_args; uint32_t stage2_version = 0; bct0_t bct0; @@ -108,46 +99,126 @@ int main(void) { /* Check for panics. */ check_and_display_panic(); - /* Load the BCT0 configuration ini off of the SD. */ - bct0_string = load_config(); + bool should_greet = true; + bool skip_fastboot = false; + bool stage2_loaded = false; + bool has_sd_card = false; - /* Parse the BCT0 configuration ini. */ - if (bct0_parse(bct0_string, &bct0) < 0) { - fatal_error("Failed to parse BCT.ini!\n"); + while (!stage2_loaded) { + + /* 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. */ - log_set_log_level(bct0.log_level); - - if (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()); - - /* Run the MTC binary. */ - 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); - - /* Try to enter fastboot, if we are configured to. */ - switch(fastboot_enter(&bct0)) { - case FASTBOOT_INVALID: - case FASTBOOT_SKIPPED: - case FASTBOOT_LOAD_STAGE2: - /* Load the loader payload into DRAM. */ - stage2_load(&bct0); - break; - case FASTBOOT_CHAINLOAD: - print(SCREEN_LOG_LEVEL_DEBUG, "fastboot: chainloading\n"); - break; - } + print(SCREEN_LOG_LEVEL_DEBUG, "Continuing to stage2...\n"); /* Setup argument data. */ strcpy(g_chainloader_arg_data, bct0.stage2_path); @@ -157,8 +228,10 @@ int main(void) { strcpy(stage2_args->bct0, bct0_string); g_chainloader_argc = 2; - /* Terminate the boot environment. */ - cleanup_env(); + /* Cleanup environment. */ + if (has_sd_card) { + unmount_sd(); + } if (bct0.log_level != SCREEN_LOG_LEVEL_NONE) { /* Wait a while for debugging. */ @@ -168,6 +241,8 @@ int main(void) { log_cleanup_display(); } + print(SCREEN_LOG_LEVEL_DEBUG, "Exiting...\n"); + /* Finally, after the cleanup routines (__libc_fini_array, etc.) are called, jump to Stage2. */ __program_exit_callback = exit_callback; return 0; diff --git a/fusee/fusee-primary/src/panic.c b/fusee/fusee-primary/src/panic.c index e4cd19e06..0906ede83 100644 --- a/fusee/fusee-primary/src/panic.c +++ b/fusee/fusee-primary/src/panic.c @@ -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); /* Save context to the SD card. */ - { + if (mount_sd()) { char filepath[0x40]; snprintf(filepath, sizeof(filepath) - 1, "/atmosphere/fatal_errors/report_%016llx.bin", ctx.report_identifier); filepath[sizeof(filepath)-1] = 0; @@ -157,6 +157,10 @@ static void _check_and_display_atmosphere_fatal_error(void) { } else { 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. */ diff --git a/fusee/fusee-primary/src/stage2.c b/fusee/fusee-primary/src/stage2.c index b0cfa85cc..97d09809e 100644 --- a/fusee/fusee-primary/src/stage2.c +++ b/fusee/fusee-primary/src/stage2.c @@ -20,8 +20,13 @@ #include "utils.h" bool stage2_run_mtc(const bct0_t *bct0) { + static bool has_run_mtc = false; FILINFO info; size_t size; + + if (has_run_mtc) { + return true; + } /* Check if the MTC binary is present. */ if (f_stat(bct0->stage2_mtc_path, &info) != FR_OK) { @@ -51,6 +56,8 @@ bool stage2_run_mtc(const bct0_t *bct0) { /* Cleanup right away. */ memset((void *)bct0->stage2_load_address, 0, size); + + has_run_mtc = true; return mtc_res; }