diff --git a/shim/build.sh b/shim/build.sh index 619aa97d..84d6d7a4 100755 --- a/shim/build.sh +++ b/shim/build.sh @@ -344,6 +344,14 @@ socshim=../$("$PYTHON" ../tools/boards.py "$board" --get soc_dir)/shim for f in ufsdiag ufsinit; do "$CC" $CFLAGS -I"$socshim" -I. -c "$socshim/$f.c" -o "$O/$f.o" done +# Board hooks (soc_hooks.h): only a SoC whose soc.json sets "shim_hooks": true has a soc_hooks.c, compiled and +# linked here; boards.py emits SOC_SHIM_HOOKS 1 for it. Without the key nothing is compiled or linked. +shim_hooks=$("$PYTHON" ../tools/boards.py "$board" --get shim_hooks) || exit 2 +hook_objs= +if [ "$shim_hooks" = 1 ]; then + "$CC" $CFLAGS -I"$socshim" -I. -c "$socshim/soc_hooks.c" -o "$O/soc_hooks.o" + hook_objs=$O/soc_hooks.o +fi # Gate honesty: usbproto.c and usbgadget.c are # cross-compiled with the shim CFLAGS on EVERY build so the object # audits in tools/test-bluejay-boot.py always see them; they are only @@ -508,10 +516,10 @@ if [ "$touch_rails" = 1 ] || [ "$touch_dvfs" = 1 ] || [ "$gpu_clk" = 1 ] || [ "$ usb_objs="$usb_objs $O/acpm.o" fi clr_obj=""; [ "$pmic_src_clear" != 1 ] || clr_obj="$O/pmicsrc_clear.o" # SC2046: no unquoted $(...) in the readelf list -abs=$("$READELF" -r $O/shim.o $O/shim_assert.o $O/console.o $O/ramlog.o $O/mmu.o $O/fdt.o $O/pstore.o $O/pr3marker.o $O/pr3run.o $O/loader.o $O/payload.o $O/ufs.o $O/ufsdiag.o $O/ufsinit.o $O/usbprobe.o $O/usbproto.o $O/usbgadget.o $O/usbpool.o $O/udump.o $O/wlanprobe.o $O/wlanrails.o $O/pmicsrc.o ${clr_obj:+"$clr_obj"} $O/wlanen.o $O/wlansmc.o $O/wlansmc_iso.o $O/wlansmc_link.o $O/wlanlink.o $O/gpuprobe.o $O/gpupower.o $O/gpupower_stack.o $O/gpupower_job.o $O/gpujob.o $O/gpuclk.o $O/mifclk.o $O/mifclk_audit.o $O/sweetprobe.o $O/sweetprobe_smc.o $O/sweetprobe_audit.o $O/sweetprobe_smc_audit.o $O/gpus2mpu.o $O/wlanh1.o $O/gpurails.o $O/gpurailon.o $O/acpm_railon.o $O/touchprobe.o $O/acpm.o $qr_objs $el2_objs | grep -c ABS64 || { rc=$?; [ $rc = 1 ] || { echo "error: build GAP: grep -c ABS64 failed rc=$rc" >&2; exit 1; }; }) +abs=$("$READELF" -r $O/shim.o $O/shim_assert.o $O/console.o $O/ramlog.o $O/mmu.o $O/fdt.o $O/pstore.o $O/pr3marker.o $O/pr3run.o $O/loader.o $O/payload.o $O/ufs.o $O/ufsdiag.o $O/ufsinit.o $hook_objs $O/usbprobe.o $O/usbproto.o $O/usbgadget.o $O/usbpool.o $O/udump.o $O/wlanprobe.o $O/wlanrails.o $O/pmicsrc.o ${clr_obj:+"$clr_obj"} $O/wlanen.o $O/wlansmc.o $O/wlansmc_iso.o $O/wlansmc_link.o $O/wlanlink.o $O/gpuprobe.o $O/gpupower.o $O/gpupower_stack.o $O/gpupower_job.o $O/gpujob.o $O/gpuclk.o $O/mifclk.o $O/mifclk_audit.o $O/sweetprobe.o $O/sweetprobe_smc.o $O/sweetprobe_audit.o $O/sweetprobe_smc_audit.o $O/gpus2mpu.o $O/wlanh1.o $O/gpurails.o $O/gpurailon.o $O/acpm_railon.o $O/touchprobe.o $O/acpm.o $qr_objs $el2_objs | grep -c ABS64 || { rc=$?; [ $rc = 1 ] || { echo "error: build GAP: grep -c ABS64 failed rc=$rc" >&2; exit 1; }; }) [ "$abs" = 0 ] || { echo "error: $abs absolute relocations in C objects" >&2; exit 1; } "$CC" $CFLAGS -static -T shim.ld -Wl,--build-id=none -Wl,--no-warn-rwx-segments -Wl,-N \ - $O/start.o $O/shim.o $O/shim_assert.o $O/console.o $O/ramlog.o $O/mmu.o $O/fdt.o $O/pstore.o $O/loader.o $O/payload.o $O/ufs.o $O/ufsdiag.o $O/ufsinit.o $O/usbprobe.o $O/usbpool.o $usb_objs $qr_objs $el2_objs -o $O/shim.elf + $O/start.o $O/shim.o $O/shim_assert.o $O/console.o $O/ramlog.o $O/mmu.o $O/fdt.o $O/pstore.o $O/loader.o $O/payload.o $O/ufs.o $O/ufsdiag.o $O/ufsinit.o $hook_objs $O/usbprobe.o $O/usbpool.o $usb_objs $qr_objs $el2_objs -o $O/shim.elf "$OBJCOPY" -O binary $O/shim.elf $O/Image size_hex=$("$NM" $O/shim.elf | awk '$3=="_end"{print $1}') size=$((16#$size_hex)) @@ -567,6 +575,15 @@ else chk "wlan: every xnu/patches/*.patch ends with a newline" bash -c 'for p in ../xnu/patches/[0-9]*.patch; do [ "$(tail -c1 "$p" | od -An -c | tr -d " ")" = "\n" ] || { echo "no final newline: $p"; exit 1; }; done' chk "host_test (compile)" gcc -O1 -Wall -o $O/host_test console.c ramlog.c host_test.c chk "host_test" $O/host_test $O/host.ppm + # Board hooks: no SoC on trunk sets shim_hooks, so the `#if SOC_SHIM_HOOKS` call sites in shim.c/loader.c are + # compiled here for a hook SoC that is not gs101 (this board's header with SOC_GS101 0 + SOC_SHIM_HOOKS 1) + mkdir -p "$O/hookcheck" + sed -e 's/^#define SOC_GS101 1$/#define SOC_GS101 0/' "$O/board_config.h" >"$O/hookcheck/board_config.h" + echo '#define SOC_SHIM_HOOKS 1' >>"$O/hookcheck/board_config.h" + hk_cflags=${CFLAGS/"-include $O/board_config.h"/"-include $O/hookcheck/board_config.h"} + chk "soc_hooks call sites (shim.c, hook SoC)" "$CC" $hk_cflags -c shim.c -o "$O/hookcheck/shim.o" + chk "soc_hooks call sites (loader.c, hook SoC)" "$CC" $hk_cflags -c loader.c -o "$O/hookcheck/loader.o" + chk "soc_hooks call sites reference every always-built hook" sh -c 'u=$("$1" -u "$2/shim.o" "$2/loader.o") || exit 1; for h in entry video console pstore_fallback probes payload bootflags before_jump; do echo "$u" | grep -q " U soc_hook_$h\$" || { echo "no call of soc_hook_$h"; exit 1; }; done' sh "$NM" "$O/hookcheck" chk "ramlog_host_test (compile)" gcc -O1 -Wall -Wextra -o $O/ramlog_host_test ramlog.c ramlog_host_test.c chk "ramlog_host_test" $O/ramlog_host_test # ASan/UBSan catch a 1-byte overflow of the report buffer (review T-98a7-assert F3); if the host gcc has no sanitizer runtime the test still runs, loudly without them diff --git a/shim/loader.c b/shim/loader.c index 28396ffe..a6ea4e74 100644 --- a/shim/loader.c +++ b/shim/loader.c @@ -166,7 +166,7 @@ const char *loader_boot(uintptr_t dtb) tail_hit = payload_addr != 0; #endif if (!payload_addr) - payload_addr = shim_find_magic(rd_start, rd_end, "SWEETXNU", 8); + payload_addr = SOC_HOOK_FIND_PAYLOAD(rd_start, rd_end, "SWEETXNU", 8); /* soc_hooks.h */ __asm__ volatile("isb; mrs %0, cntpct_el0" : "=r"(t_scan1)); __asm__ volatile("mrs %0, cntfrq_el0" : "=r"(frq)); uint32_t scan_ms = (uint32_t)(frq >= 1000 ? (t_scan1 - t_scan0) / (frq / 1000) : 0); @@ -219,9 +219,9 @@ const char *loader_boot(uintptr_t dtb) zero64(ba_pa, PAGE_16K); volatile struct boot_args *ba = (volatile struct boot_args *)ba_pa; #ifdef EL2_RESIDENT - uint64_t bootflags = payload_bootflags(1, el2_s2_on); + uint64_t bootflags = SOC_HOOK_BOOTFLAGS(payload_bootflags(1, el2_s2_on)); #else - uint64_t bootflags = 0; + uint64_t bootflags = SOC_HOOK_BOOTFLAGS(0); /* soc_hooks.h */ #endif payload_fill_boot_args(ba, p, top, adt_pa - pa_of_va_base, bootflags); /* xnu reads deviceTreeP with the MMU on: a VA */ /* --mif-clk (T-5030): MIF/INT GET + one MIF request, sweetmif* tokens; no-op otherwise */ @@ -258,7 +258,7 @@ const char *loader_boot(uintptr_t dtb) uintptr_t entry_pa = p->entry_va + pa_of_va_base; con_hex("JUMP", entry_pa); con_str("XNU", "jumping (fbcon clears screen)"); - + SOC_HOOK_BEFORE_JUMP(); /* soc_hooks.h: the last SoC step before the jump */ /* Everything was written with the MMU and caches off; drop any stale I-cache lines too. */ __asm__ volatile("dsb sy; ic iallu; dsb sy; isb" ::: "memory"); ((xnu_entry_t)entry_pa)(ba_pa); diff --git a/shim/loader.h b/shim/loader.h index 49493ae6..59c28b06 100644 --- a/shim/loader.h +++ b/shim/loader.h @@ -3,3 +3,5 @@ /* Boot the SWEETXNU payload found in the ABL ramdisk; returns only on error. */ const char *loader_boot(uintptr_t dtb); +/* loader.c board hooks (SOC_HOOK_*): included here so loader.c keeps its line numbers (SHIM_ASSERT logs __LINE__) */ +#include "soc_hooks.h" diff --git a/shim/shim.c b/shim/shim.c index a8a3c6c7..dd087944 100644 --- a/shim/shim.c +++ b/shim/shim.c @@ -31,6 +31,7 @@ #include "gpus2mpu.h" #include "gpujob.h" #include "touchprobe.h" +#include "soc_hooks.h" #ifdef EL2_TRAP #include "el2.h" #endif @@ -111,7 +112,11 @@ static inline void wr32(uintptr_t a, uint32_t v) { *(volatile uint32_t *)a = v; static inline void wr8(uintptr_t a, uint8_t v) { *(volatile uint8_t *)a = v; } extern char secondary_entry[]; -#if SOC_GS101 +/* The probe flow (bluejay_probe, the fault-guarded accessors, the exception skip) runs on gs101 and + * on every SoC that opts into the board hooks (soc_hooks.h). Its gs101-only register steps keep + * their own SOC_GS101 guards: DECON re-arm, PMU CPU prep, the REBOOT_BL words. */ +#define SHIM_PROBE (SOC_GS101 || SOC_SHIM_HOOKS) +#if SHIM_PROBE static const uint64_t board_mpidrs[NR_CPUS] = { BOARD_MPIDR_0, BOARD_MPIDR_1, BOARD_MPIDR_2, BOARD_MPIDR_3, BOARD_MPIDR_4, BOARD_MPIDR_5, BOARD_MPIDR_6, BOARD_MPIDR_7, @@ -121,7 +126,7 @@ static const uint64_t board_mpidrs[NR_CPUS] = { static const char *stage; /* set at runtime: no absolute pointers in data */ volatile uint64_t probe_entry_el; static volatile uint32_t probe_guard, probe_fault; -#if SOC_GS101 +#if SHIM_PROBE static volatile uintptr_t probe_fault_address; #endif static volatile uint64_t sec_mpidr[NR_CPUS]; @@ -162,9 +167,9 @@ static uint64_t smc(uint64_t fn, uint64_t a1, uint64_t a2, uint64_t a3) * usbprobe.h): sets probe_guard around the load so a data abort or * SError from a gated clock/power domain lands in exc_handler's * probe_guard skip and the caller prints "unreadable" instead of - * panicking. That skip is compiled in only for SOC_GS101, so on - * other boards try_read32 is only as guarded as a raw read (and - * nothing calls it there). + * panicking. That skip is compiled in only for the probe SoCs + * (SHIM_PROBE), so on other boards try_read32 is only as guarded as + * a raw read (and nothing calls it there). */ int try_read32(uintptr_t address, uint32_t *value) { @@ -178,8 +183,8 @@ int try_read32(uintptr_t address, uint32_t *value) return !probe_fault; } -#if SOC_GS101 -/* Defined for SOC_GS101 only; declared (with try_read32) in +#if SHIM_PROBE +/* Defined for the probe SoCs only (SHIM_PROBE); declared (with try_read32) in * shim/usbgadget.h, whose only caller is usbgadget.c - linked into the * shim only when build.sh runs with --usb-gadget. */ int try_write32(uintptr_t address, uint32_t value) @@ -236,6 +241,9 @@ static void report_bluejay_watchdog(const char *label, const struct wdt_state *s * reset. ponytail: the WDT path assumes the s3c2410 layout and an unmasked * PMU reset source (UNSURE on gs101); it only runs after both PSCI calls * returned, i.e. already failed. */ +#if defined(REBOOT_BL) && !SOC_GS101 +#error "REBOOT_BL: the bootloader-reset words below are gs101 PMU registers" +#endif #ifdef REBOOT_BL /* Reset INTO THE BOOTLOADER without a button press (docs/research/10): ABL reads the volatile PMU register * SYSIP_DAT0 (0x17460810) after reset; 0xfc = "reboot bootloader". Only EL3 can write it: the PMU SMC @@ -305,6 +313,7 @@ static void __attribute__((noreturn)) bluejay_reset_chain(void) } /* WTCON/WTCNT layout and ENABLE/RSTEN bits: https://github.com/torvalds/linux/blob/master/drivers/watchdog/s3c2410_wdt.c */ +#if SOC_GS101 /* gs101 display block; a hook SoC arms its display in soc_hook_video() */ /* Linaro reports ABL disables DECON HW trigger: https://patchew.org/linux/20241216-gs101-simplefb-v1-0-8ccad1830281%40linaro.org/ */ /* DECON0 is 0x1c300000 in GS101 DTS; TRIG_CON is 0x30 and HW_TRIG_EN is bit 0: https://android.googlesource.com/kernel/google-modules/display/+/661047c0c1c4939aa81fcc822bb21dc5a484f913/samsung/cal_9845/regs-decon.h */ /* Whole-word command-mode trigger value 0x3061: https://gitlab.com/postmarketOS/pmaports/-/blob/v26.06/device/testing/soc-google-gs101/00-enable-fb.sh */ @@ -324,6 +333,7 @@ static void decon_rearm_trigger(void) } con_hex2("DECON TRIG", "before=", before, "after=", after); } +#endif /* SOC_GS101 */ static void report_cpu(unsigned cpu) { @@ -342,6 +352,7 @@ static void report_cpu(unsigned cpu) con_hex("timer freq used", counter_freq()); } +#if SOC_GS101 /* gs101 PMU words and SMC; no other SoC has a derived CPU prep */ static int prepare_bluejay_cpu(unsigned cpu) { uint64_t caller = rsr("mpidr_el1"); @@ -362,6 +373,7 @@ static int prepare_bluejay_cpu(unsigned cpu) con_hex("PMU intr-gen success", ok); return ok; } +#endif /* SOC_GS101 */ #ifdef USB_GADGET /* ---- stage-2 USB CDC-ACM log gadget (build flag --usb-gadget, default OFF) ---- @@ -571,6 +583,15 @@ static void udump_dump(void) static void __attribute__((noreturn)) bluejay_probe(uintptr_t dtb) { stage = "bluejay probe"; +#if SOC_SHIM_HOOKS + uint32_t soc_entry = soc_hook_entry(dtb); /* first: before anything can hang */ +#ifdef USB_GADGET + if (soc_entry & SOC_ENTRY_USB_EARLY) + usb_gadget_start(dtb); +#else + (void)soc_entry; +#endif +#endif struct wdt_state wdt_cl0 = {0}, wdt_cl1 = {0}; disable_bluejay_watchdog(WDT_CL0_BASE, &wdt_cl0); disable_bluejay_watchdog(WDT_CL1_BASE, &wdt_cl1); @@ -585,19 +606,35 @@ static void __attribute__((noreturn)) bluejay_probe(uintptr_t dtb) } else { video = (struct fdt_video){ FB_BASE, FB_SIZE, FB_W, FB_H, FB_STRIDE }; } +#if SOC_SHIM_HOOKS + soc_hook_video(&video); +#endif con_set_video(video.base, video.width, video.height, video.stride); con_clear(0xff000000U); con_str("FB", live_framebuffer ? "from live FDT" : "board fallback"); +#if SOC_SHIM_HOOKS + soc_hook_console(&video); +#endif con_hex("ENTRY EL", probe_entry_el); pr3_marker_run(); /* style-allow: func-len legacy */ /* style-allow: sized-types legacy */ /* Locate the ramoops console zone before anything can crash: from * here on every checkpoint save (and the panic path) hands the log * to Android through pstore. */ +#if SOC_SHIM_HOOKS + if (!pstore_init(dtb)) + soc_hook_pstore_fallback(); +#else pstore_init(dtb); +#endif pstore_save(); /* checkpoint 1: earliest log */ +#if SOC_SHIM_HOOKS + soc_hook_probes(); +#endif report_bluejay_watchdog("WDT CL0", &wdt_cl0); report_bluejay_watchdog("WDT CL1", &wdt_cl1); +#if SOC_GS101 decon_rearm_trigger(); +#endif pstore_save(); /* checkpoint 2: watchdog + DECON */ #ifdef PMIC_SRC /* READ-ONLY (--pmic-src, pmicsrc.c, docs/research/139): the PMIC reset-source latches through @@ -617,6 +654,9 @@ static void __attribute__((noreturn)) bluejay_probe(uintptr_t dtb) * probe (and the USB log, if built in), so a failure still yields * data. The probe sections never run on the success path. */ con_str("SECTION", "boot XNU"); +#if SOC_SHIM_HOOKS + soc_hook_pre_xnu(); +#endif #ifdef XNU_UFS /* ABL shut the UFS host down; XNU's sweet_ufs driver (patch 0080) expects HCE + link up. */ con_hex("UFS cold init rc", (uint32_t)ufs_cold_init()); @@ -693,6 +733,9 @@ static void __attribute__((noreturn)) bluejay_probe(uintptr_t dtb) } #endif #ifdef USB_GADGET +#if SOC_SHIM_HOOKS + if (!(soc_entry & SOC_ENTRY_USB_EARLY)) /* else soc_hook_entry() asked for it at the top */ +#endif usb_gadget_start(dtb); /* live log from here on */ #endif #if defined(EL2_TRAP) && !defined(EL2_RESIDENT) /* EL2_RESIDENT (SPEC 3.4 (b) design item 1 (ii)): the T1/T2 test reads are compiled out, there is no trap page */ @@ -741,12 +784,16 @@ static void __attribute__((noreturn)) bluejay_probe(uintptr_t dtb) /* ALREADY_ON / ON_PENDING: the core is coming; just wait. */ con_str("CPU path", "already on / on pending; wait"); } else { +#if SOC_GS101 con_str("CPU path", "error: PMU prep, then one retry"); prepare_bluejay_cpu(cpu); ret = (int32_t)smc(PSCI_CPU_ON, board_mpidrs[cpu], (uintptr_t)secondary_entry, cpu); con_hex2("CPU_ON 2nd", "cpu=", cpu, "ret=", (uint32_t)ret); retried = 1; +#else + con_str("CPU path", "error: no CPU prep for this SoC; not retried"); +#endif } /* 2 s: A76s can take ~300 ms to reach secondary_entry. */ uint64_t deadline = now() + counter_freq() * 2; @@ -1022,7 +1069,7 @@ static void __attribute__((noreturn)) bluejay_probe(uintptr_t dtb) bluejay_reset_chain(); #endif } -#endif +#endif /* SHIM_PROBE */ static uint64_t now(void) { @@ -1044,8 +1091,9 @@ uint64_t touch_ticks(void) /* touchprobe.c / gpupower.c: bounded waits (CNTPCT) } #endif -static void __attribute__((noreturn)) reset(unsigned after_s) +static void __attribute__((noreturn)) reset(uint32_t after_s) { + /* style-allow: assert on the stop path (STYLE-C rule 4: no assertion in reset) */ (void)after_s; /* unused under --pstore-fast */ #if SOC_GS101 #ifdef PSTORE_FAST @@ -1059,6 +1107,20 @@ static void __attribute__((noreturn)) reset(unsigned after_s) pager_replay(); bluejay_reset_chain(); #endif +#elif SOC_SHIM_HOOKS + /* A hook SoC: PSCI only. The branch below writes sweet's Qualcomm restart-reason and PSHOLD + * words, which are not this SoC's. */ + con_skip(); +#ifdef PSTORE_FAST + after_s = 5; +#endif + con_hex("RESET PSCI SYSTEM_RESET in s", after_s); + wait_ticks(counter_freq() * after_s); + __asm__ volatile("dsb sy" ::: "memory"); + smc(PSCI_SYSTEM_RESET, 0, 0, 0); + /* bounded: halt on purpose: the reset was requested, wait for it to take effect */ + for (;;) + __asm__ volatile("wfe"); #else con_skip(); con_str("RESET", after_s > 20 ? "in 40s" : "in 20s"); @@ -1101,6 +1163,8 @@ void __attribute__((noreturn)) shim_halt(void) (void)try_write32(WDT_CL0_BASE + 8, 1); (void)try_write32(WDT_CL0_BASE, (3U << 3) | (1U << 5) | 1U); } +#elif SOC_SHIM_HOOKS + (void)smc(PSCI_SYSTEM_RESET, 0, 0, 0); /* a hook SoC: PSCI only (no sweet words) */ #else wr32(IMEM_RESTART_REASON, RESTART_BOOTLOADER); __asm__ volatile("dsb sy" ::: "memory"); @@ -1145,11 +1209,12 @@ static void irq_handler(void) void exc_handler(uint64_t slot, uint64_t *regs) { + /* style-allow: assert on the stop path (STYLE-C rule 4: no assertion in exc_handler) */ if (slot == 5) { /* IRQ from current EL */ irq_handler(); return; } -#if SOC_GS101 +#if SHIM_PROBE if (probe_guard) { if (slot == 4) { uint64_t esr = rsr("esr_el1"); @@ -1435,7 +1500,8 @@ static uint32_t to_us(uint64_t ticks) void shim_main(uint64_t dtb) { -#if SOC_GS101 + /* style-allow: assert stage dispatch only; the checks live in the stages it calls (loader.c) */ +#if SHIM_PROBE bluejay_probe(dtb); #endif struct mmu_info mi = { 0 }; /* mmu_enable can bail before n_l3/sctlr_* are set */ @@ -1463,7 +1529,7 @@ void shim_main(uint64_t dtb) uint64_t mem_off = ticks_mem(); stage = "mmu enable"; - int rc = mmu_enable(&mi, dtb); + int32_t rc = mmu_enable(&mi, dtb); stage = "fill on"; uint64_t fill_on = rc ? 0 : ticks_fill(RED); diff --git a/shim/soc_hooks.h b/shim/soc_hooks.h new file mode 100644 index 00000000..7b51ed0e --- /dev/null +++ b/shim/soc_hooks.h @@ -0,0 +1,89 @@ +#pragma once +#include + +/* + * soc_hooks.h - board hooks: the points where the shared shim flow hands control to SoC code. + * + * Opt-in per SoC: `"shim_hooks": true` in soc///soc.json. tools/boards.py then emits + * `#define SOC_SHIM_HOOKS 1` into board_config.h and shim/build.sh compiles and links + * soc///shim/soc_hooks.c, which must define every hook below. Without the key + * nothing changes: SOC_SHIM_HOOKS is 0, every call site in shim/ is compiled out + * (`#if SOC_SHIM_HOOKS`), no SoC file is linked, and the loader macros at the end expand to + * exactly the code they replace. No SoC on trunk sets the key today. + * + * SOC_SHIM_HOOKS is a capability, not a SoC name: shared code keys on it, never on the SoC. + * A hook SoC also runs the probe flow (shim.c bluejay_probe, SHIM_PROBE) like gs101: watchdog, + * FDT video and pstore, the opt-in probe sections, --boot-xnu. Its gs101-only steps (DECON re-arm, + * PMU CPU prep, REBOOT_BL) stay compiled out there. + * + * Rules for every hook (shim/AGENTS.md, docs/SAFETY.md, docs/STYLE-C.md): + * - Read-only unless the write is audited: a register write goes through an allowlisted helper, + * cites its source, and extends the SoC's own audit module (never an exception in an existing + * audit, CONTRIBUTING.md). UFS stays read-only; nothing here may reach the UFS doorbell. + * - Every wait is bounded (a counter or a CNTPCT deadline) and logs what it waited for; the + * watchdogs may be disabled, so a hang stays a hang. + * - Log through console.h (con_*); the log reaches the screen, the RAM log, pstore and USB. + * - A hook may not assume an order other than the one documented here, and may not keep the + * MMU, caches or interrupts in a state other than the one it was called in. + * - The stop path (reset(), shim_stop(), shim_halt()) calls no hook: on a hook SoC it ends in + * PSCI SYSTEM_RESET only, never in another SoC's restart words. + */ + +#ifndef SOC_SHIM_HOOKS +#define SOC_SHIM_HOOKS 0 +#endif + +#if SOC_SHIM_HOOKS +struct fdt_video; + +/* soc_hook_entry() result bits */ +#define SOC_ENTRY_USB_EARLY (1u << 0) /* --usb-gadget: start the live log now, not after the probes */ + +/* First call of the probe flow, before the watchdog step and before any FDT parse or console use + * beyond the RAM log. For what must be recorded before anything else can hang: an early pstore + * checkpoint at a zone the SoC knows, a read-only look at the watchdogs as the bootloader left + * them. Returns SOC_ENTRY_* bits. */ +uint32_t soc_hook_entry(uintptr_t dtb); + +/* After the framebuffer was chosen (live FDT node or board.json fallback), before + * con_set_video(). The SoC may arm its display pipe here, or set video->base = 0 to keep the + * console off a panel nobody scans out (the log still goes to RAM, pstore and USB). */ +void soc_hook_video(struct fdt_video *video); + +/* Right after the console is up ("FB" line): report what the console uses. Read-only. */ +void soc_hook_console(const struct fdt_video *video); + +/* pstore_init(dtb) found no usable ramoops zone in the FDT: the SoC may arm a zone it knows + * (board.json values with a cited source) so the checkpoints still land. Logs what it did. */ +void soc_hook_pstore_fallback(void); + +/* After checkpoint 1 (pstore armed, console up), before the watchdog report and the generic + * probe sections: the SoC's own opt-in probe sections (each behind its own build flag) and + * read-only reports. Saves pstore itself after a step that may hang. */ +void soc_hook_probes(void); + +/* --boot-xnu: first step of the handover section, before the UFS cold init and the rail/link + * steps: a read-only survey of what the bootloader left behind. */ +void soc_hook_pre_xnu(void); + +/* loader_boot(): the payload address the SoC found itself (e.g. carried inside the kernel Image), + * or 0 to scan the initrd [rd_lo, rd_hi) as usual. Consulted where the scan would run. */ +uintptr_t soc_hook_payload(uintptr_t rd_lo, uintptr_t rd_hi); + +/* loader_boot(): the boot-args flags XNU gets; returns flags plus the SoC's own bits. */ +uint64_t soc_hook_bootflags(uint64_t flags); + +/* loader_boot(): after every check and copy, immediately before the jump to XNU. Bounded; after + * it nothing in the shim runs again (no console service, no USB poll). */ +void soc_hook_before_jump(void); + +#define SOC_HOOK_FIND_PAYLOAD(lo, hi, magic, n) \ + (soc_hook_payload((lo), (hi)) ?: shim_find_magic((lo), (hi), (magic), (n))) +#define SOC_HOOK_BOOTFLAGS(f) soc_hook_bootflags(f) +#define SOC_HOOK_BEFORE_JUMP() soc_hook_before_jump() +#else +/* Without hooks the loader macros are the code they stand in for (loader.c keeps its lines). */ +#define SOC_HOOK_FIND_PAYLOAD(lo, hi, magic, n) shim_find_magic((lo), (hi), (magic), (n)) +#define SOC_HOOK_BOOTFLAGS(f) (f) +#define SOC_HOOK_BEFORE_JUMP() ((void)0) +#endif diff --git a/tools/boards.py b/tools/boards.py index 97255618..a8163b07 100644 --- a/tools/boards.py +++ b/tools/boards.py @@ -11,7 +11,7 @@ written as "0x..." strings. Run `tools/pix devices` to list them. boards.py BOARD OUT.h write the generated C header - boards.py BOARD --get KEY print one value (shell use), e.g. soc_dir + boards.py BOARD --get KEY print one value (shell use), e.g. soc_dir; shim_hooks prints 1 or 0 """ import glob import json @@ -57,6 +57,28 @@ def load_devices(root=ROOT): BOARDS = {name: v[3] for name, v in _DEVICES.items()} +def soc_flag(board, key): + """A SoC opt-in flag of soc.json (shim_hooks, adt_hooks): the key belongs to the SoC (its own code implements what it enables), so a board.json + may not set it; any value but a JSON boolean is refused. Absent = False: the board builds exactly as without the key.""" + if key in _load(os.path.join(_DEVICES[board][0], "board.json")): + raise ValueError(f"{board}: {key} is a soc.json key (the SoC implements the hooks), not a board.json key") + v = _load(os.path.join(_DEVICES[board][1], "soc.json")).get(key, False) + if not isinstance(v, bool): + raise ValueError(f"{board}: soc.json {key} must be true or false, got {v!r}") + return v + + +def shim_hooks(board): + """True when the board's SoC opts into the shim board hooks (shim/soc_hooks.h): soc.json "shim_hooks": true + (its soc///shim/soc_hooks.c implements the hooks; soc_flag rules).""" + return soc_flag(board, "shim_hooks") + + +def device_name(board): + """Marketing name from board.json "name" (e.g. "Pixel 6a"): the About page's Model Name (tools/mkadt.py product_overrides).""" + return _DEVICES[board][2]["name"] + + def device_dir(board): return os.path.relpath(_DEVICES[board][0], ROOT) @@ -537,6 +559,24 @@ def _el2_macros(v): return out +_PSTORE_KEYS = (("PSTORE_BASE", "pstore_base"), ("PSTORE_SIZE", "pstore_size"), ("PSTORE_CONSOLE_SIZE", "pstore_console_size")) + + +def _pstore_macros(board, values): + """Optional fixed ramoops window of a board whose bootloader hands the probe its pstore zone at a known address (board.json pstore_base, + pstore_size, pstore_console_size, each cited to the device's reserved-memory node). Used before the FDT is parsed (shim/soc_hooks.h + soc_hook_pstore_fallback). All three or none; a board without them gets the same header as before.""" + have = [k for _, k in _PSTORE_KEYS if k in values] + if not have: + return [] + if len(have) != len(_PSTORE_KEYS): + raise ValueError(f"{board}: pstore_base, pstore_size and pstore_console_size go together (got {have})") + base, size, con = (values[k] for _, k in _PSTORE_KEYS) + if not all(isinstance(x, int) and x > 0 for x in (base, size, con)) or con > size or base % 0x1000: + raise ValueError(f"{board}: pstore window must be positive integers, page-aligned base, console_size <= size") + return [f"#define {macro} {values[key]:#x}UL" for macro, key in _PSTORE_KEYS] + + def c_header(board: str) -> str: values = BOARDS[board] names = { @@ -554,6 +594,7 @@ def c_header(board: str) -> str: for macro, key in names.items(): value = 8 if key == "cpu_count" else values[key] lines.append(f"#define {macro} {value}" if key == "cpu_count" else f"#define {macro} {value:#x}UL") + lines += _pstore_macros(board, values) for i, mpidr in enumerate(values["cpu_mpidrs"]): lines.append(f"#define BOARD_MPIDR_{i} {mpidr:#x}UL") watchdogs = values["watchdog_bases"] + (0, 0) @@ -565,6 +606,8 @@ def c_header(board: str) -> str: for name in sorted({os.path.basename(os.path.dirname(p)).upper() for p in glob.glob(os.path.join(ROOT, "soc", "*", "*", "soc.json"))}): lines.append(f"#define SOC_{name} {1 if name == this_soc else 0}") + if shim_hooks(board): # only when set: a board without the key gets the same header as before (shim/soc_hooks.h defaults it to 0) + lines.append("#define SOC_SHIM_HOOKS 1") for key, addr in sorted(values.get("wlan", {}).items()): lines.append(f"#define WLAN_{key.upper()} {int(addr, 0):#x}UL") if "gpu" in values: @@ -622,7 +665,8 @@ def cell(r, step): blk = "WLB_NONE" if r["blk"] is None else "WLB_" + r["blk"] return f"\t{{ {step}u, WLK_{r['kind'].upper()}, {blk}, {r['off']:#x}u, {r['mask']:#x}u, {r['value']:#x}u, {a}u, {b}u }}," - out = ["/* Generated from soc/google/gs101/wlan_seq.json by tools/boards.py; do not edit. Plain integers only (no pointers). */", "#pragma once", "#include ", "", + src = os.path.relpath(path, ROOT) if os.path.isabs(path) else "soc/google/gs101/wlan_seq.json" # the SoC's own table (gs101 text unchanged) + out = [f"/* Generated from {src} by tools/boards.py; do not edit. Plain integers only (no pointers). */", "#pragma once", "#include ", "", f'#define WLAN_SEQ_SHA256 "{sha}"', f"#define WLAN_SEQ_NROWS {len(rows)}u", f"#define WLAN_SEQ_NTEAR {len(tear)}u", f"#define WLAN_SEQ_LAST {last}u", f"#define WLAN_SEQ_DEFAULT_N {int(doc['default_last_step'])}u", "", "enum { " + ", ".join(f"WLK_{k.upper()}" for k in _WLAN_SEQ_KINDS) + " };", @@ -675,6 +719,11 @@ def cell(r, step): print(soc_dir(args.board)) elif args.get == "soc": print(_DEVICES[args.board][2]["soc"]) + elif args.get == "shim_hooks": + try: + print(1 if shim_hooks(args.board) else 0) + except ValueError as exc: + raise SystemExit(f"error: {exc}") else: print(BOARDS[args.board][args.get]) elif args.wlan_seq: diff --git a/tools/mkadt.py b/tools/mkadt.py index 001ce2b9..523e3880 100644 --- a/tools/mkadt.py +++ b/tools/mkadt.py @@ -146,20 +146,47 @@ def audio_node(ph, mode, path=D22AP_ADT): return node('audio', props) +# /sweet-wlan compatible per SoC: the string the PCIe Wi-Fi driver matches (xnu patch 0124 for gs101). A SoC without a row gets no /sweet-wlan node and no +# launchd /wlan node; a new SoC adds its row together with the driver patch that accepts it. +SWEET_WLAN_COMPAT = {'google/gs101': 'google,gs101-bcm4389-pcie'} + + +def sweet_wlan_compat(board): + """The /sweet-wlan compatible of the board's SoC (SWEET_WLAN_COMPAT), or None.""" + return SWEET_WLAN_COMPAT.get(boards._DEVICES[board][2]['soc']) + + def wlan_node_default(board, qemu): - """The iOS-root boot (tools/xrun runs mkadt.py with no flag) carries the wlan node on a board that is not sweet (its tree stays unchanged) and not on a qemu tree.""" - return board != 'sweet' and not qemu + """The iOS-root boot (tools/xrun runs mkadt.py with no flag) carries the wlan node on a board whose SoC has a Wi-Fi driver row (SWEET_WLAN_COMPAT; not + sweet, whose tree stays unchanged) and not on a qemu tree.""" + return sweet_wlan_compat(board) is not None and not qemu -def product_overrides(props, config): - """/product edits of the Pixel boards: product-description (About > Model Name, MG ArtworkTraits) and, from soc.json wifi_chipset, wifi-chipset (MobileGestalt WifiChipset, - research 110 s.7 row WifiChipset 0x19c56d18c; SPEC-WIFI Part F W2). The D22AP tree says 4357 (iPhone X); a board without the soc.json key keeps it (nothing invented).""" - out = [(k, v) for k, v in props if k != 'product-description'] + [('product-description', cstr('Pixel 6a'))] +def product_overrides(props, config, board='bluejay'): + """/product edits of the Pixel boards: product-description (About > Model Name, MG ArtworkTraits) = board.json "name" (sweet keeps 'Pixel 6a', its tree stays + unchanged), from soc.json wifi_chipset, wifi-chipset (MobileGestalt WifiChipset, research 110 s.7 row WifiChipset 0x19c56d18c; SPEC-WIFI Part F W2; the D22AP + tree says 4357 (iPhone X); a board without the soc.json key keeps it, nothing invented), and artwork-display-gamut (display_gamut).""" + out = [(k, v) for k, v in props if k != 'product-description'] + [('product-description', cstr('Pixel 6a' if board == 'sweet' else boards.device_name(board)))] if config.get('wifi_chipset'): out = [(k, v) for k, v in out if k != 'wifi-chipset'] + [('wifi-chipset', cstr(str(config['wifi_chipset'])))] + gamut = display_gamut(config) + if gamut: + out = [(k, v) for k, v in out if k != 'artwork-display-gamut'] + [('artwork-display-gamut', cstr(gamut))] + print(f'ADT GAP: /product artwork-display-gamut set to {gamut} (board.json artwork_display_gamut / PIXOS_ADT_GAMUT; D22AP says P3) [mkadt]', file=sys.stderr) return out +def display_gamut(config, env=None): + """/product artwork-display-gamut replacement, or None = the D22AP value ('P3') unchanged. board.json artwork_display_gamut sets a board's default; env + PIXOS_ADT_GAMUT overrides it for one build. [guess] MobileGestalt derives HasExtendedColorDisplay from it, which makes WebKit and CoreAnimation pick 10-bit + IOSurface formats; a port whose GPU path does not render those sets sRGB. Only 'sRGB' and 'P3' are accepted.""" + env = os.environ if env is None else env + gamut = env.get('PIXOS_ADT_GAMUT') or config.get('artwork_display_gamut') + if gamut and gamut not in ('sRGB', 'P3'): + raise SystemExit(f'artwork-display-gamut {gamut!r} (board.json artwork_display_gamut / PIXOS_ADT_GAMUT): sRGB or P3 only') + return gamut or None + + def add_wdt_node(root, board='sweet', qemu=False): """bsd/dev/sweet_wdt.c (patch 0278 = port of 0193, docs/specs/SPEC-WDT.md SQ2): gs101 cluster-0 watchdog block (reg, 0x100 bytes; oracle R01) and the three PMU offsets it reads (R08: reset mask 0x1244 bit 2, counter enable 0x1220 bit 8; RST_STAT 0x3b44). Read-only except WTCON/WTDAT/WTCNT. The PMU @@ -186,6 +213,40 @@ def phandles(n): return wdt +def add_backlight_node(root, board='sweet', qemu=False, path=D22AP_ADT): + """board.json adt_d22ap_backlight: true -> IODeviceTree:/backlight (backboardd looks it up for the brightness slider), copied from the D22AP tree + (research/ipsw-x/d22ap.adt: DBVMin/DBVMax, max-nit-value, calibration tables) without its function-* properties (iBoot/kernel function references to hardware + the phone does not have). The calibration is the iPhone X panel's, said in an ADT GAP line. Added after build() like add_wdt_node (phandle = the tree's + largest + 1, appended last). A board without the key, a qemu tree or a missing D22AP tree: no node.""" + if qemu or BOARDS[board].get('adt_d22ap_backlight') is not True or not os.path.exists(path): + return None + with open(path, 'rb') as f: + src, _ = adt.parse(f.read()) + bl = [c for c in src.children if dict((k, v) for k, f, v in c.props).get('name') == b'backlight\0'] + if not bl: + sys.exit(f'mkadt: GAP: {path} has no /backlight node') + props = [(k, v) for k, f, v in bl[0].props if not f and k not in ('name', 'AAPL,phandle') and not k.startswith('function-')] + def phandles(nd): + out = [struct.unpack('.py, e.g. tools/mkadt_gs201.py) when its soc.json sets "adt_hooks": true, else None. The module provides + add_nodes(root, board, qemu) (nodes of that SoC's drivers, each gated on its own board/soc table) and may provide + product_required(board, qemu, d22ap_path, allow_no_product) -> None or the reason to refuse the build. No SoC on trunk sets the key.""" + if not boards.soc_flag(board, 'adt_hooks'): + return None + import importlib + return importlib.import_module('tools.mkadt_' + os.path.basename(boards.soc_dir(board))) + + def add_chg_node(root, board='sweet', qemu=False): """bsd/dev/sweet_chg.c (xnu patch 0283, charger phase 1, docs/research/charger-max77759-gs101.md section 8 steps 1-2): the READ windows of the MAX77759 I2C bus bring-up (HSI2C12/USI12, sysreg_peric1, CMU_PERIC1, CMU_TOP, pad bank gpp23) and the register offsets read in each. soc.json "chg_probe" is the only table (sources @@ -373,7 +434,7 @@ def build(seed=None, qemu=False, highmem=False, board='sweet', no_ufs=False, wla ufs = node('sweet-ufs', [ ph(), ('compatible', cstr('qcom,ufshc' if board == 'sweet' else 'google,gs101-ufs')), - ('reg', u64(config['ufs_base'], config['ufs_size'])), + ('reg', u64(config['ufs_base'], config.get('ufs_map_size', config['ufs_size']))), # ufs_map_size: an SoC whose HCI window is larger than ufs_size ]) # pmap_compute_max_asids requires the node even when no overrides are set. @@ -394,7 +455,7 @@ def build(seed=None, qemu=False, highmem=False, board='sweet', no_ufs=False, wla product_props = d22ap_product() # About > Model Name reads /product product-description (MG ArtworkTraits, docs about-identity report) if product_props: - product_props = product_overrides(product_props, config) + product_props = product_overrides(product_props, config, board) product = [node('product', [ph()] + product_props)] if product_props else [] # bsd/dev/sweet_usb.c (patch 0082): the gs101 DWC3 and the DRAM range ABL keeps its event @@ -483,7 +544,7 @@ def cmu_props(): w = config.get('wlan') wlan = node('sweet-wlan', [ ph(), - ('compatible', cstr('google,gs101-bcm4389-pcie')), + ('compatible', cstr(sweet_wlan_compat(board))), ('reg', u64(int(w['mem'], 0), 0x10000)), ('cfg', u64(int(w['cfg'], 0), 0x1000)), ('atu', u64(int(w['atu'], 0), 0x1000)), @@ -496,7 +557,7 @@ def cmu_props(): if all(k in w for k in ('tcm', 'tcm_bytes', 'atu_r2_off')) else []) + ( # xnu patch 0174 (Wi-Fi G2, docs/research/107 #3): RC DBI for the Command store, pinned by the driver. [('dbi', u64(int(w['dbi'], 0), 0x1000))] if 'dbi' in w else []) - ) if w and all(k in w for k in ('mem', 'cfg', 'atu', 'elbi', 'pmu_pcie1_iso')) and not qemu else None + ) if w and all(k in w for k in ('mem', 'cfg', 'atu', 'elbi', 'pmu_pcie1_iso')) and not qemu and sweet_wlan_compat(board) else None # Identity of the iPhone X whose userland runs here: compatible[0] is # hw.model/hw.target (D22AP), model is hw.machine/hw.product @@ -508,7 +569,7 @@ def cmu_props(): # About > Serial Number / Model Number: IOPlatformExpert serial-number -> IOPlatformSerialNumber, # MG ModelNumber = root model-number (region-info stays absent so the row is exactly this text). Fake serial, never a real one. ('serial-number', cstr('PixOS-Project/pixelios')), - ('model-number', cstr('bluejay')), + ('model-number', cstr('bluejay' if board == 'sweet' else board)), # the board codename (sweet keeps its tree) ('target-type', cstr('D22')), ('target-sub-type', cstr('D22AP')), ('manufacturer', cstr('Apple Inc.')), @@ -535,11 +596,19 @@ def cmu_props(): parser.add_argument('--cpu-order', help='comma list of physical core numbers in /cpus DT order (a permutation starting with 0 = boot CPU); ' 'only the child order changes, every property keeps its value. --intent gpu passes 0,6,7,4,5,1,2,3 (sprint-gpu nav19+: with cpus=5 the kernel picks ' 'the boot A55 + the two A76 + the two X1 first)') + parser.add_argument('--allow-no-product', action='store_true', help="build without /product although the SoC's ADT hooks refuse that (soc_adt_hooks product_required)") args = parser.parse_args() + hooks = soc_adt_hooks(args.board) + why = hooks.product_required(args.board, args.qemu, D22AP_ADT, args.allow_no_product) if hasattr(hooks, 'product_required') else None + if why: + sys.exit(why) root = build(qemu=args.qemu, highmem=args.highmem, board=args.board, no_ufs=args.no_ufs, wlan_node=wlan_node_default(args.board, args.qemu) and not args.no_wlan_node, bt_node=not args.no_bt_node, audio=audio_mode()) add_wdt_node(root, args.board, args.qemu) add_chg_node(root, args.board, args.qemu) + add_backlight_node(root, args.board, args.qemu) + if hooks: + hooks.add_nodes(root, args.board, args.qemu) for line in bt_gap_lines(not args.no_bt_node) + audio_gap_lines(audio_mode()): print(line) if args.cpu_order: diff --git a/tools/mkpayload.py b/tools/mkpayload.py index 331c1cc7..cec302d7 100644 --- a/tools/mkpayload.py +++ b/tools/mkpayload.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Pack an xnu kernel Mach-O + ADT into the payload the sweet shim boots. - mkpayload.py KERNEL ADT OUT [--cmdline "..."] [--ramdisk IMAGE] [--wlanfw CONTAINER] [--wlancred BLOB] + mkpayload.py KERNEL ADT OUT [--cmdline "..."] [--ramdisk IMAGE] [--wlanfw CONTAINER] [--wlancred BLOB] [--board NAME] The kernel is linked as a PIE with LC_DYLD_CHAINED_FIXUPS. Nobody else (no kmutil, no iBoot) resolves those for us, and xnu only rebases static @@ -28,6 +28,7 @@ property WLANFW (page-rounded placement, ), which nothing turns into a disk; the container is validated (magic, CRCs) before it is packed. --wlancred (tools/mkwlancred.py, 128 bytes) is placed the same way as property WLANCRED ; it is validated (magic, crc) and only `wlancred: present` is reported, never a phys address or any value. +The ADT's RAM range must lie in one board.json dram_bank, or in banks that are physically adjacent (banks_cover). """ import argparse, os, struct, sys @@ -188,6 +189,16 @@ def walk(n, path): return found +def banks_cover(banks, phys, size): + """True when [phys, phys + size) lies in physically contiguous DRAM banks: a window spanning several adjacent banks (e.g. two 2 GiB banks listed + separately in board.json) is one contiguous range. Asked only after the single-bank check failed, so a window one bank holds is judged as before.""" + covered = phys + for base, bsize in sorted(banks): + if base <= covered < base + bsize: + covered = base + bsize + return phys + size <= covered + + def build(kernel_path, adt_path, cmdline, ramdisk_path=None, board='sweet', wlanfw_path=None, wlancred_path=None, lab=False): buf = bytearray(open(kernel_path, 'rb').read()) if KERNEL_TAG not in buf: @@ -213,7 +224,7 @@ def build(kernel_path, adt_path, cmdline, ramdisk_path=None, board='sweet', wlan # The ADT decides where the kernel's RAM is (mkadt.py --highmem). PHYS_BASE, MEM_SIZE = adt_dram(adt_blob) if not any(PHYS_BASE >= base and PHYS_BASE + MEM_SIZE <= base + size - for base, size in boards.BOARDS[board]['dram_banks']): + for base, size in boards.BOARDS[board]['dram_banks']) and not banks_cover(boards.BOARDS[board]['dram_banks'], PHYS_BASE, MEM_SIZE): raise SystemExit(f'ADT RAM range does not fit board {board}') pieces = [(s['vmaddr'], s['vmsize'], buf[s['fileoff']:s['fileoff'] + s['filesize']]) for s in segs] ramdisk = None @@ -287,7 +298,7 @@ def build(kernel_path, adt_path, cmdline, ramdisk_path=None, board='sweet', wlan ap.add_argument('--ramdisk', help='root image for md0 (boot with rd=md0)') ap.add_argument('--wlanfw', help='BCM4389 firmware container (tools/pack_wlanfw.py) -> /chosen/memory-map WLANFW') ap.add_argument('--wlancred', help='credential blob (tools/mkwlancred.py) -> /chosen/memory-map WLANCRED') - ap.add_argument('--board', choices=('sweet', 'bluejay'), default='sweet') + ap.add_argument('--board', choices=sorted(boards.BOARDS), default='sweet') a = ap.parse_args() blob, info = build(a.kernel, a.adt, a.cmdline, a.ramdisk, a.board, a.wlanfw, a.wlancred) open(a.out, 'wb').write(blob) diff --git a/tools/test_boards_board_inputs.py b/tools/test_boards_board_inputs.py new file mode 100644 index 00000000..c219e131 --- /dev/null +++ b/tools/test_boards_board_inputs.py @@ -0,0 +1,105 @@ +"""New board inputs of tools/boards.py for a second Pixel SoC (split step A3): the optional fixed pstore window (board.json pstore_*), device_name, +the generic soc.json opt-in flags (soc_flag) and the wlan_seq.h source line. Every trunk header stays as it was; the opt-in cases run on a private copy +of the device/ and soc/ JSON (no file of the checkout is written).""" +import os +import shutil +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from tools import boards # noqa: E402 +from tools.test_boards_shim_hooks import boards_at, copy_tree, edit_json, gs101_soc_json # noqa: E402 + +PSTORE = {"pstore_base": "0xfd3ff000", "pstore_size": "0x400000", "pstore_console_size": "0x200000"} +PSTORE_LINES = ["#define PSTORE_BASE 0xfd3ff000UL", "#define PSTORE_SIZE 0x400000UL", "#define PSTORE_CONSOLE_SIZE 0x200000UL"] + + +def read(path): + with open(path) as f: + return f.read() + + +class BoardInputs(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="board-inputs-") + copy_tree(self.tmp) + self.bluejay_json = os.path.join(self.tmp, "device", "google", "bluejay", "board.json") + + def tearDown(self): + shutil.rmtree(self.tmp) + + def test_trunk_headers_have_no_pstore_window(self): + for board in boards.BOARDS: + self.assertNotIn("PSTORE_", boards.c_header(board), board) + + def test_pstore_window_adds_three_lines_before_the_mpidrs(self): + real = boards.c_header("bluejay").splitlines() + edit_json(self.bluejay_json, **PSTORE) + with boards_at(self.tmp): + got = boards.c_header("bluejay").splitlines() + for b in boards.BOARDS: + if b != "bluejay": + self.assertNotIn("PSTORE_", boards.c_header(b), b) + i = got.index(PSTORE_LINES[0]) + self.assertEqual(got[i:i + 3], PSTORE_LINES) + self.assertEqual(got[:i] + got[i + 3:], real) + self.assertTrue(got[i + 3].startswith("#define BOARD_MPIDR_0 "), got[i + 3]) + + def test_pstore_window_refusals(self): + bad = ({"pstore_base": "0xfd3ff000"}, # not all three + dict(PSTORE, pstore_console_size="0x800000"), # console larger than the window + dict(PSTORE, pstore_base="0xfd3ff800"), # not page-aligned + dict(PSTORE, pstore_size=0)) + for kv in bad: + saved = read(self.bluejay_json) + edit_json(self.bluejay_json, **kv) + with boards_at(self.tmp): + with self.assertRaisesRegex(ValueError, "pstore"): + boards.c_header("bluejay") + with open(self.bluejay_json, "w") as f: + f.write(saved) + + def test_device_name_is_board_json_name(self): + self.assertEqual(boards.device_name("bluejay"), "Pixel 6a") + edit_json(self.bluejay_json, name="Test Phone") + with boards_at(self.tmp): + self.assertEqual(boards.device_name("bluejay"), "Test Phone") + + def test_soc_flags_follow_the_shim_hooks_rules(self): + saved = {p: read(p) for p in (gs101_soc_json(self.tmp), self.bluejay_json)} + for key in ("shim_hooks", "adt_hooks"): + for p, text in saved.items(): # back to the checkout's JSON + with open(p, "w") as f: + f.write(text) + for board in boards.BOARDS: + self.assertIs(boards.soc_flag(board, key), False, (board, key)) + edit_json(gs101_soc_json(self.tmp), **{key: True}) + with boards_at(self.tmp): + self.assertIs(boards.soc_flag("bluejay", key), True, key) + self.assertIs(boards.soc_flag("sweet", key), False, key) + edit_json(gs101_soc_json(self.tmp), **{key: 1}) + with boards_at(self.tmp): + with self.assertRaisesRegex(ValueError, "must be true or false"): + boards.soc_flag("bluejay", key) + edit_json(gs101_soc_json(self.tmp), **{key: False}) + edit_json(self.bluejay_json, **{key: True}) + with boards_at(self.tmp): + with self.assertRaisesRegex(ValueError, "soc.json key"): + boards.soc_flag("bluejay", key) + + def test_wlan_seq_source_line(self): + path = os.path.join(ROOT, boards.soc_dir("bluejay"), "wlan_seq.json") + import json + with open(path) as f: + doc = json.load(f) + first = boards.wlan_seq_header("bluejay").splitlines()[0] + self.assertEqual(first, "/* Generated from soc/google/gs101/wlan_seq.json by tools/boards.py; do not edit. Plain integers only (no pointers). */") + self.assertEqual(boards.wlan_seq_render(doc), boards.wlan_seq_header("bluejay")) # the audit's relative-path call: same text + other = os.path.join(ROOT, "soc", "google", "gs999", "wlan_seq.json") + self.assertIn("Generated from soc/google/gs999/wlan_seq.json ", boards.wlan_seq_render(doc, other).splitlines()[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_boards_shim_hooks.py b/tools/test_boards_shim_hooks.py new file mode 100644 index 00000000..1a82af0a --- /dev/null +++ b/tools/test_boards_shim_hooks.py @@ -0,0 +1,135 @@ +"""The board-hooks opt-in (shim/soc_hooks.h): tools/boards.py emits `#define SOC_SHIM_HOOKS 1` into board_config.h and +`--get shim_hooks` prints 1 only for a board whose soc.json sets "shim_hooks": true; every other header stays as it was. +The opt-in cases run on a private copy of the device/ and soc/ JSON (no file of the checkout is written).""" +import contextlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from tools import boards # noqa: E402 + +HOOK_LINE = "#define SOC_SHIM_HOOKS 1" + + +def copy_tree(dst): + """device/*/*/board.json, soc/*/*/soc.json and tools/boards.py of the checkout, at the same paths under dst.""" + for rel in ("device", "soc"): + for d, _, files in os.walk(os.path.join(ROOT, rel)): + for f in files: + if f in ("board.json", "soc.json"): + out = os.path.join(dst, os.path.relpath(d, ROOT)) + os.makedirs(out, exist_ok=True) + shutil.copy2(os.path.join(d, f), out) + os.makedirs(os.path.join(dst, "tools")) + shutil.copy2(os.path.join(ROOT, "tools", "boards.py"), os.path.join(dst, "tools")) + + +def edit_json(path, **kv): + with open(path) as f: + doc = json.load(f) + doc.update(kv) + with open(path, "w") as f: + json.dump(doc, f, indent=2) + + +@contextlib.contextmanager +def boards_at(root): + """boards.py's module state pointed at root for the duration, restored after.""" + saved = (boards.ROOT, boards._DEVICES, boards.BOARDS) + try: + boards.ROOT = root + boards._DEVICES = boards.load_devices(root) + boards.BOARDS = {name: v[3] for name, v in boards._DEVICES.items()} + yield + finally: + boards.ROOT, boards._DEVICES, boards.BOARDS = saved + + +def gs101_soc_json(root): + return os.path.join(root, "soc", "google", "gs101", "soc.json") + + +class ShimHooksFlag(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="shim-hooks-") + copy_tree(self.tmp) + + def tearDown(self): + shutil.rmtree(self.tmp) + + def test_trunk_boards_have_no_hooks(self): + # no SoC on trunk opts in: no header carries the macro and --get prints 0 + for board in boards.BOARDS: + self.assertFalse(boards.shim_hooks(board), board) + self.assertNotIn("SOC_SHIM_HOOKS", boards.c_header(board), board) + out = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "boards.py"), "bluejay", "--get", "shim_hooks"], + capture_output=True, text=True, cwd=self.tmp) + self.assertEqual((out.returncode, out.stdout), (0, "0\n"), out.stderr) + + def test_copy_without_key_is_byte_identical(self): + # the copied tree (no key anywhere) renders exactly the checkout's headers + real = {b: boards.c_header(b) for b in boards.BOARDS} + with boards_at(self.tmp): + self.assertEqual({b: boards.c_header(b) for b in boards.BOARDS}, real) + + def test_opt_in_adds_one_line_after_the_soc_macros(self): + real = boards.c_header("bluejay").splitlines() + edit_json(gs101_soc_json(self.tmp), shim_hooks=True) + with boards_at(self.tmp): + self.assertTrue(boards.shim_hooks("bluejay")) + hooked = boards.c_header("bluejay").splitlines() + other = [b for b in boards.BOARDS if boards._DEVICES[b][2]["soc"] != "google/gs101"] + for b in other: + self.assertNotIn("SOC_SHIM_HOOKS", boards.c_header(b), b) + self.assertEqual(hooked.count(HOOK_LINE), 1) + i = hooked.index(HOOK_LINE) + self.assertEqual(hooked[:i] + hooked[i + 1:], real) + self.assertTrue(hooked[i - 1].startswith("#define SOC_"), hooked[i - 1]) + self.assertFalse(hooked[i + 1].startswith("#define SOC_"), hooked[i + 1]) + out = subprocess.run([sys.executable, "-I", os.path.join(self.tmp, "tools", "boards.py"), "bluejay", "--get", "shim_hooks"], + capture_output=True, text=True, cwd=ROOT) + self.assertEqual((out.returncode, out.stdout), (0, "1\n"), out.stderr) + + def test_false_is_the_same_as_absent(self): + real = boards.c_header("bluejay") + edit_json(gs101_soc_json(self.tmp), shim_hooks=False) + with boards_at(self.tmp): + self.assertFalse(boards.shim_hooks("bluejay")) + self.assertEqual(boards.c_header("bluejay"), real) + + def test_non_bool_values_are_refused(self): + for bad in ("true", 1, 0, "1", None, [True], {"on": True}): + edit_json(gs101_soc_json(self.tmp), shim_hooks=bad) + with boards_at(self.tmp): + with self.assertRaisesRegex(ValueError, "must be true or false"): + boards.shim_hooks("bluejay") + with self.assertRaisesRegex(ValueError, "must be true or false"): + boards.c_header("bluejay") + out = subprocess.run([sys.executable, "-I", os.path.join(self.tmp, "tools", "boards.py"), "bluejay", "--get", "shim_hooks"], + capture_output=True, text=True, cwd=self.tmp) + self.assertNotEqual(out.returncode, 0, bad) + self.assertIn("must be true or false", out.stderr) + self.assertEqual(out.stdout, "") + + def test_board_json_may_not_set_it(self): + for v in (True, False): + edit_json(os.path.join(self.tmp, "device", "google", "bluejay", "board.json"), shim_hooks=v) + with boards_at(self.tmp): + with self.assertRaisesRegex(ValueError, "soc.json key"): + boards.shim_hooks("bluejay") + with self.assertRaisesRegex(ValueError, "soc.json key"): + boards.c_header("bluejay") + out = subprocess.run([sys.executable, "-I", os.path.join(self.tmp, "tools", "boards.py"), "bluejay", "--get", "shim_hooks"], + capture_output=True, text=True, cwd=self.tmp) + self.assertNotEqual(out.returncode, 0) + self.assertIn("soc.json key", out.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_mkadt_board_inputs.py b/tools/test_mkadt_board_inputs.py new file mode 100644 index 00000000..181054ee --- /dev/null +++ b/tools/test_mkadt_board_inputs.py @@ -0,0 +1,198 @@ +"""New board inputs of tools/mkadt.py for a second Pixel SoC (split step A3), on a private copy of the device/ and soc/ JSON with a made-up board +"testphone" (no file of the checkout is written): the /product and root identity from board.json, soc.json ufs_map_size, board.json +artwork_display_gamut (+ PIXOS_ADT_GAMUT), board.json adt_d22ap_backlight, the per-SoC /sweet-wlan compatible table and the soc.json adt_hooks +opt-in (tools/mkadt_.py). The trunk boards keep their trees (the byte-identical bluejay/sweet ADTs are shown in the PR).""" +import contextlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from tools import adt, boards, mkadt # noqa: E402 +from tools.test_boards_shim_hooks import boards_at, copy_tree, edit_json # noqa: E402 + +SEED = b"\0" * 64 +HOOK_MODULE = '''from tools.mkadt import cstr, node + + +def add_nodes(root, board, qemu=False): + root.children.append(node("test-hook-node", [("compatible", cstr("test," + board))])) + + +def product_required(board, qemu, d22ap_path, allow_no_product): + return None if allow_no_product else "test hook: refused without --allow-no-product" +''' + + +def props(n): + return dict((k, v) for k, _f, v in n.props) + + +def child(root, name): + return next((c for c in root.children if c.name == name), None) + + +def add_board(tmp, codename="testphone", soc="google/gs101", **kv): + """device/google//board.json = bluejay's with another codename, name and SoC (plus kv).""" + with open(os.path.join(tmp, "device", "google", "bluejay", "board.json")) as f: + doc = json.load(f) + doc.update(codename=codename, name="Test Phone", soc=soc, **kv) + d = os.path.join(tmp, "device", "google", codename) + os.makedirs(d) + with open(os.path.join(d, "board.json"), "w") as f: + json.dump(doc, f, indent=2) + + +def add_soc(tmp, name="gs999"): + """soc/google//soc.json = gs101's under another name: a SoC with no /sweet-wlan row.""" + d = os.path.join(tmp, "soc", "google", name) + shutil.copytree(os.path.join(tmp, "soc", "google", "gs101"), d) + edit_json(os.path.join(d, "soc.json"), name=name) + + +@contextlib.contextmanager +def tree(tmp): + """boards.py and mkadt.py pointed at the copied tree for the duration.""" + with boards_at(tmp): + saved = mkadt.BOARDS + mkadt.BOARDS = boards.BOARDS + try: + yield + finally: + mkadt.BOARDS = saved + + +class MkadtBoardInputs(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="mkadt-inputs-") + copy_tree(self.tmp) + + def tearDown(self): + shutil.rmtree(self.tmp) + + def root(self, board, **kw): + return adt.parse(adt.serialize(mkadt.build(seed=SEED, board=board, **kw)))[0] + + def test_identity_follows_the_board(self): + add_board(self.tmp) + with tree(self.tmp): + r = self.root("testphone") + self.assertEqual(props(r)["model-number"], b"testphone\0") + prod = child(r, "product") + if prod is not None: # /product needs the D22AP tree (research/ipsw-x/d22ap.adt) + self.assertEqual(props(prod)["product-description"], b"Test Phone\0") + for board in ("bluejay", "sweet"): # the trunk values: bluejay's own, sweet keeps bluejay's text (its tree stays unchanged) + r = self.root(board) + self.assertEqual(props(r)["model-number"], b"bluejay\0", board) + prod = child(r, "product") + if prod is not None: + self.assertEqual(props(prod)["product-description"], b"Pixel 6a\0", board) + + def test_product_overrides_directly(self): + base = [("product-description", b"iPhone X\0"), ("artwork-display-gamut", b"P3\0")] + out = dict(mkadt.product_overrides(base, {}, "bluejay")) + self.assertEqual((out["product-description"], out["artwork-display-gamut"]), (b"Pixel 6a\0", b"P3\0")) + self.assertEqual(dict(mkadt.product_overrides(base, {}, "sweet"))["product-description"], b"Pixel 6a\0") + + def test_display_gamut(self): + self.assertIsNone(mkadt.display_gamut({}, env={})) + self.assertEqual(mkadt.display_gamut({"artwork_display_gamut": "sRGB"}, env={}), "sRGB") + self.assertEqual(mkadt.display_gamut({"artwork_display_gamut": "sRGB"}, env={"PIXOS_ADT_GAMUT": "P3"}), "P3") + self.assertEqual(mkadt.display_gamut({}, env={"PIXOS_ADT_GAMUT": "sRGB"}), "sRGB") + for bad in ({"artwork_display_gamut": "srgb"}, {"artwork_display_gamut": "Display P3"}): + with self.assertRaises(SystemExit): + mkadt.display_gamut(bad, env={}) + with self.assertRaises(SystemExit): + mkadt.display_gamut({}, env={"PIXOS_ADT_GAMUT": "rec2020"}) + base = [("artwork-display-gamut", b"P3\0")] + old = os.environ.pop("PIXOS_ADT_GAMUT", None) + try: + self.assertEqual(dict(mkadt.product_overrides(base, {"artwork_display_gamut": "sRGB"}, "bluejay"))["artwork-display-gamut"], b"sRGB\0") + self.assertEqual(dict(mkadt.product_overrides(base, {}, "bluejay"))["artwork-display-gamut"], b"P3\0") + finally: + if old is not None: + os.environ["PIXOS_ADT_GAMUT"] = old + + def test_ufs_map_size(self): + add_board(self.tmp, ufs_map_size="0x1300") + with tree(self.tmp): + reg = props(child(self.root("testphone"), "sweet-ufs"))["reg"] + ufs_base = boards.BOARDS["testphone"]["ufs_base"] + self.assertEqual(reg, mkadt.u64(ufs_base, 0x1300)) + b = boards.BOARDS["bluejay"] + self.assertEqual(props(child(self.root("bluejay"), "sweet-ufs"))["reg"], mkadt.u64(b["ufs_base"], b["ufs_size"])) + + def test_sweet_wlan_compat_table(self): + self.assertEqual(mkadt.sweet_wlan_compat("bluejay"), "google,gs101-bcm4389-pcie") + self.assertIsNone(mkadt.sweet_wlan_compat("sweet")) + self.assertTrue(mkadt.wlan_node_default("bluejay", False)) + self.assertFalse(mkadt.wlan_node_default("bluejay", True)) + self.assertFalse(mkadt.wlan_node_default("sweet", False)) + add_soc(self.tmp) + add_board(self.tmp, soc="google/gs999") + with tree(self.tmp): + self.assertIsNone(mkadt.sweet_wlan_compat("testphone")) # a SoC without a driver row: no node, no launchd /wlan node + self.assertFalse(mkadt.wlan_node_default("testphone", False)) + self.assertIsNone(child(self.root("testphone"), "sweet-wlan")) + self.assertEqual(props(child(self.root("bluejay"), "sweet-wlan"))["compatible"], b"google,gs101-bcm4389-pcie\0") + + def test_backlight_node(self): + root = mkadt.build(seed=SEED, board="bluejay") + self.assertIsNone(mkadt.add_backlight_node(root, "bluejay")) # trunk boards: no key, no node + add_board(self.tmp, adt_d22ap_backlight=True) + with tree(self.tmp): + root = mkadt.build(seed=SEED, board="testphone") + self.assertIsNone(mkadt.add_backlight_node(root, "testphone", qemu=True)) + self.assertIsNone(mkadt.add_backlight_node(root, "testphone", path=os.path.join(self.tmp, "no-such.adt"))) + n = mkadt.add_backlight_node(root, "testphone", path=self.fake_d22ap()) + self.assertIs(root.children[-1], n) + p = props(n) + self.assertEqual(p["name"], b"backlight\0") + self.assertEqual(p["max-nit-value"], mkadt.u32(500)) + self.assertFalse([k for k in p if k.startswith("function-")]) + phs = [int.from_bytes(props(c).get("AAPL,phandle", b"\0\0\0\0")[:4], "little") for c in root.children[:-1]] + self.assertGreater(int.from_bytes(p["AAPL,phandle"], "little"), max(phs)) + + def fake_d22ap(self): + """A stand-in for research/ipsw-x/d22ap.adt (not in git): a root with a /backlight node carrying a phandle, a value and a function-* reference.""" + bl = mkadt.node("backlight", [("AAPL,phandle", mkadt.u32(7)), ("max-nit-value", mkadt.u32(500)), ("function-backlight", mkadt.u32(1))]) + path = os.path.join(self.tmp, "d22ap.adt") + with open(path, "wb") as f: + f.write(adt.serialize(mkadt.node("device-tree", [], [bl]))) + return path + + def test_adt_hooks_opt_in(self): + for board in boards.BOARDS: + self.assertIsNone(mkadt.soc_adt_hooks(board), board) + tools = os.path.join(self.tmp, "tools") + for f in ("mkadt.py", "adt.py"): + shutil.copy2(os.path.join(ROOT, "tools", f), tools) + with open(os.path.join(tools, "mkadt_gs101.py"), "w") as f: + f.write(HOOK_MODULE) + out = os.path.join(self.tmp, "A.adt") + + def run(*extra): + return subprocess.run([sys.executable, "-I", os.path.join(tools, "mkadt.py"), out, "--board", "bluejay", *extra], + capture_output=True, text=True, cwd=self.tmp, timeout=120) + r = run() # key absent: the module file is never loaded + self.assertEqual(r.returncode, 0, r.stderr) + with open(out, "rb") as f: + self.assertIsNone(child(adt.parse(f.read())[0], "test-hook-node")) + edit_json(os.path.join(self.tmp, "soc", "google", "gs101", "soc.json"), adt_hooks=True) + r = run() + self.assertNotEqual(r.returncode, 0) + self.assertIn("refused without --allow-no-product", r.stderr) + r = run("--allow-no-product") + self.assertEqual(r.returncode, 0, r.stderr) + with open(out, "rb") as f: + n = child(adt.parse(f.read())[0], "test-hook-node") + self.assertEqual(props(n)["compatible"], b"test,bluejay\0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_mkpayload_board_inputs.py b/tools/test_mkpayload_board_inputs.py new file mode 100644 index 00000000..fbfc7b59 --- /dev/null +++ b/tools/test_mkpayload_board_inputs.py @@ -0,0 +1,84 @@ +"""New board inputs of tools/mkpayload.py for a second Pixel SoC (split step A3): --board takes every board of tools/boards.py, and the ADT RAM range may +span physically adjacent board.json dram_banks (banks_cover). The board.json case runs on a private copy of the device/ and soc/ JSON (no file of the +checkout is written).""" +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from tools import adt, boards, mkadt, mkpayload # noqa: E402 +from tools.test_boards_shim_hooks import boards_at, copy_tree, edit_json # noqa: E402 + +GIB = 1 << 30 + + +def synthetic_kernel(path): + """Smallest Mach-O mkpayload accepts (as tools/test_mkwlancred.py): one __TEXT segment, LC_UNIXTHREAD, the boot-line tag, no chained fixups.""" + vm = 0xfffffff007004000 + seg = struct.pack("