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..9346fec4 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,18 @@ def load_devices(root=ROOT): BOARDS = {name: v[3] for name, v in _DEVICES.items()} +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. + The key belongs to the SoC (its soc///shim/soc_hooks.c implements the hooks), so a board.json may not set it; + any value but a JSON boolean is refused. Absent = False: the shim builds exactly as without the key.""" + if "shim_hooks" in _load(os.path.join(_DEVICES[board][0], "board.json")): + raise ValueError(f"{board}: shim_hooks 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("shim_hooks", False) + if not isinstance(v, bool): + raise ValueError(f"{board}: soc.json shim_hooks must be true or false, got {v!r}") + return v + + def device_dir(board): return os.path.relpath(_DEVICES[board][0], ROOT) @@ -565,6 +577,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: @@ -675,6 +689,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/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()