diff --git a/device/husky/BATTERY-NOTES.md b/device/husky/BATTERY-NOTES.md index e2dde7058..cb1b16f76 100644 --- a/device/husky/BATTERY-NOTES.md +++ b/device/husky/BATTERY-NOTES.md @@ -1,7 +1,7 @@ # Pixel 8 Pro (husky) battery, charging and USB-C: bring-up notes and results -Last updated: 2026-11-01. One phone, one person (Lef), one day of hands-on tests, written up in full so that others can check it and reuse it. Everything here is tagged: +Last updated: 2026-11-02. One phone, one person (Lef), one day of hands-on tests, written up in full so that others can check it and reuse it. Everything here is tagged: - **Verified** means it was read from a file, a log or the phone and the source is named. - **Not verified** means it is an inference, or comes from memory of a datasheet, and says what would settle it. @@ -17,7 +17,7 @@ Nothing in this document contains a serial number, IMEI, MAC address, IP address | Gauge battery model | Google's ATL model (the pack's real ID, read from its EEPROM), loaded through an overlay. The temperature reads about 35 C and moves; replacing the fallback model with the right one dropped the reported level by 10 points (section 5.6). | | MFD core (PMIC at 0x66, `max77759`) | Binds, no interrupt storm, loads at boot. | | Charger (0x69, `max77759_charger`) | Loaded by hand under a dead-man tool, three runs: 500 mA and 900 mA on a desktop USB port, and a wall charger. The driver charges the battery, slowly (see section 7). | -| Type-C controller (0x25, `tcpci_maxim`) | No driver loaded: it stays disabled and blocked. The only access to the chip is its USB data switch register (0x25:0x93), read and written by the rescue service (section 8). | +| Type-C controller (0x25, `tcpci_maxim`) | Blocked at boot; loaded by hand under the dead-man tool (`b4-tcpm`, section 7.2): the port registers as a sink, 3.0 A from the desktop port, the driver closes the data switch on a replug itself, and with the charger loaded the charger follows TCPM's current limit. Three boots on 2026-11-01. Without the driver the only access to the chip is its USB data switch register (0x25:0x93), read and written by the rescue service (section 8). Sourcing VBUS (host mode) is not done: [HOST-MODE-RUNBOOK.md](HOST-MODE-RUNBOOK.md). | | USB link across an unplug | Lost until a reboot, because the Type-C chip opens the USB data switch. Fixed with `omamobile-usb-rescue`. | | Slot B boot retries | A hazard: each boot of slot B uses one retry (3 after a flash or `set_active`), and when they run out the bootloader falls back to GrapheneOS, whose first boot wiped `userdata`. How slot B gets marked successful is on hold until the maintainer decides (#252); until then, flash a known-good image set before the last try (sections 3 and 9). | | PCA9468 direct charger (0x57) | No mainline driver. Not touched. | @@ -177,6 +177,18 @@ Not verified, and not claimed: how much current the charger actually draws from A note for UI authors: the charger power supply says `Charging` (fast charge) while the gauge's own power supply says `Discharging` whenever the net current is negative, so the status-bar icon (charger) and the fetch widget (gauge) can disagree. Both are telling the truth. +### 7.2 The Type-C driver (`b4-tcpm`) and the USB role switch: three boots on 2026-11-01 + +Kernel `7.3.0-rc6-omamobile-push1-g5899fec2bd28` (the e1 kernel: the shared base plus our eight battery and EEPROM commits) for all three. Plan: [TYPEC-FAST-CHARGE-PLAN.md](TYPEC-FAST-CHARGE-PLAN.md) stages 3 and 4, [HOST-MODE-PLAN.md](HOST-MODE-PLAN.md) stage 1. The dead-man step `b4-tcpm` stops `omamobile-usb-rescue`, loads `tcpci_maxim` (which pulls `tcpci` and `tcpm`; the device tree keeps `pd-disable`, so Rp sensing only, no PD), soaks under its guard (the battery limits of section 6, hard-reset or contaminant states in the tcpm log, `USBSW_CTRL` 0x93 not 0x09 with VBUS valid, both links dead) and undoes itself unless confirmed over a new SSH login. Control over Wi-Fi in every case. Each flash refilled slot B's tries to three and each boot used one. Logs kept locally. + +**Boot 1, 20:06-20:13: the node enabled, the driver loaded charger-less.** Overlay `overlays/typec-test.dtso` sets `usb-typec@25` to `okay`. After boot: the I2C client `1-0025` present and unbound, only the MFD core loaded, Wi-Fi up, the rescue active, `tcpci_maxim` blocked, `USBSW_CTRL` 0x09. `b4-tcpm` at 20:09:06-20:11:20 with the USB cable on the desktop's front USB-C port: the driver bound (`maxtcpc 1-0025`), `tcpm` registered `typec/port0` with `power_role [sink]`, `data_role host [device]`, `port_type [sink]`, `power_operation_mode 3.0A`; partner `type not_dfp`, no PD (a USB source advertising 3.0 A on CC); power supply `tcpm-source-psy-1-0025` `online 1`, `current_max 3,000,000 uA`, `voltage_now 5,000,000 uV`. TCPC after the load: `CC_STATUS` 0x1c, `POWER_STATUS` 0x0d, `USBSW_CTRL` 0x09 (left closed by the driver), `FAULT_STATUS` 0x00 (0x80, "all registers reset", before the load). USB gadget `configured` and `usb0` up throughout, Wi-Fi up, **0 hard resets**, confirmed and soaked 120 s clean, no trip, no reset. The battery charged at +0.4..+0.5 A with the charger driver not loaded (input limit 0xc2 unchanged at 0x13). Kernel messages `maxtcpc 1-0025: dummy supplies not allowed for exclusive requests (id=vbus)` and `Failed to get vbus regulator handle`: the connector has no VBUS source in the device tree, so the port is a sink only (HOST-MODE-PLAN section 0). The tcpm debugfs log printed nothing in the dump: unknown why; to check before any PD stage, since the hard-reset stop reads that log. Replug at 20:12-20:13 with the rescue stopped: unplug gave `USBSW_CTRL` 0x00 (data switch open), CHGIN 0x00; replug 12 s later gave `USBSW_CTRL` 0x09 **written by the driver, not the rescue**, the phone back on the USB address in seconds, `typec/port0` and the partner back, the tcpm supply online at 3 A. With the driver loaded the rescue is redundant; without it, still required. + +**Boot 2, 20:19-20:26: charger and Type-C together.** Flash, `b3-charger --ilim 500000 --soak 120`, then `b4-tcpm --soak 300` in the same boot. `b3-charger` soaked clean (the driver probed `mode 0x5, float 4200 mV, fast charge 1533400 uA`, capped 1485000 in the 20-42 C band, input limit 500000 uA; the bootloader had left float 4350 mV and fast charge 1933420 uA). `b4-tcpm` with the charger loaded: soak clean, **0 hard resets**, `USBSW_CTRL` 0x09 throughout, USB and Wi-Fi up. **The charger followed TCPM:** `current_max 3,000,000 uA` and the input-limit register 0xc2 went 0x13 (500 mA) to **0x77 (3 A)** and stayed there (the log line every 10 s read `0xc2 0x77 0xb9 0x05`): the TCPM-to-charger path of `max77759_charger.c` on hardware. Battery current in the soak +0.33..+0.52 A, 4.148 to 4.164 V, 35.6-35.8 C, 78 %; not 1.5 A because the pack was near the 4.2 V float where the current tapers (an earlier +1.49 A reading was at 4.0 V and 52-55 %) [I: a repeat at about 65 % settles it]. No trips, no resets. The `b4-tcpm` undo also undoes `b3-charger` in this case (charging ends off). + +**Boot 3, 20:56-21:03: the USB role switch, no VBUS (HOST-MODE-PLAN stage 1).** Overlays `typec-test` and `usb-role-test` (dwc3 `dr_mode = "otg"`, `usb-role-switch`, default peripheral, a graph to the connector). After boot: `dr_mode otg` in the live DT, `/sys/class/usb_role/11210000.usb-role-switch/role` = `device`, UDC `configured`, USB SSH up on the first boot (dwc3 does not wait for the Type-C driver), `typec/port0` absent until the driver loads. `b4-tcpm` charger-less (soak 120 s) over Wi-Fi: clean, port0 sink, 3.0 A, **no hard resets**, `USBSW_CTRL` 0x09. Then, by hand over Wi-Fi with the desktop cable out and a restore-to-device trap: `echo host > .../role` (no VBUS, the connector still sink-only) took the gadget away and two xHCI root hubs appeared, `usb1` at 480 Mbit/s and `usb2` at 10000 Mbit/s; `typec/port0/data_role` still read `host [device]` (the userspace write bypasses TCPM). `echo device` 5 s later: UDC `configured`, `usb0` carrier 1, the USB address answered in 4 ms. No hang, no oops, no kernel message in host mode. Conclusion: zuma's dwc3 runs as a host with the in-tree `dwc3` and `xhci-plat`, no stock glue driver, and the PHY survives the switch with nothing attached. Not shown: enumeration of a real device (no VBUS, so nothing could attach), and TCPM setting the role itself on an attach. + +Not recorded in these notes because the source files do not have them: the exact battery level and temperature at each boot's start beyond what is quoted, and the tcpm debugfs log's contents (empty in the dump). + ### 7.1 What stock does, decoded, and a first safe step (a proposal, nothing implemented) Read-only research on Google's stock husky device tree (the MP overlay, capacity 0x1356 = 4950 mAh) and Google's GPL charger sources (shusky `bms` repository). The decoded tables were recomputed independently and match. @@ -229,7 +241,7 @@ So the layout is consistent with husky's [verified, read-only, on files]: the ma - The bring-up used a modprobe block by hand and an overlay each time, not the package. Once the package ships `omamobile-max77759.conf`, delete the local `/etc/modprobe.d/omamobile-battery-test.conf`: a file in `/etc` of the same name would replace the package's and its later changes would not apply. - `modprobe -r max77759_charger` was used four times (by the tool's undo). CONTRIBUTING warns about unloading bring-up modules; for this driver the unload worked every time, but note that the driver has no remove function and leaves charging on when unloaded, which is why the undo forces the mode to 0x4 explicitly. -- No Type-C work, no charger limits above the conservative ones, no JEITA, no PCA9468, no wireless, no OTG. +- No charger limits above the conservative ones, no JEITA, no PCA9468, no wireless, no PD. The Type-C driver ran under the dead-man tool (section 7.2). OTG (sourcing 5 V on the port from the external boost) has a draft runbook, [HOST-MODE-RUNBOOK.md](HOST-MODE-RUNBOOK.md), with the `b5-host` and `baseline` steps of the dead-man tool; nothing in it runs until the maintainer says go. ## 10a. Charger baseline, plugged and done (2026-11-06, kernel 7.3.0-rc6-omamobile-push1-g904a64931327) @@ -261,7 +273,7 @@ When the charger driver binds with today's device tree it sets 4.20 V on purpose ## 12. Files -In this repository: `device/husky/overlays/battery-clk-test.dtso`, `battery-i2c-test.dtso`, `gauge-model.dtso`, `gauge-model-atl.dtso`, `pack-eeprom-test.dtso` (all under `device/husky/overlays/`), `tools/gen-gauge-overlay.py` (reads Google's public `zuma-husky-battery-data.dtsi`, section 5.7), `tools/husky-deadman`, `tools/husky-deadman-phone`, and the package changes (USB rescue, blocklist) in #250. Kernel side: kernel #163 (the bus) and #154 (panel size, which the on-screen keyboard needs). +In this repository: `device/husky/overlays/battery-clk-test.dtso`, `battery-i2c-test.dtso`, `gauge-model.dtso`, `gauge-model-atl.dtso`, `pack-eeprom-test.dtso`, `typec-test.dtso`, `usb-role-test.dtso` (all under `device/husky/overlays/`), `tools/gen-gauge-overlay.py` (reads Google's public `zuma-husky-battery-data.dtsi`, section 5.7), `tools/husky-deadman`, `tools/husky-deadman-phone` (with `tests/husky-deadman`), [HOST-MODE-RUNBOOK.md](HOST-MODE-RUNBOOK.md), and the package changes (USB rescue, blocklist) in #250. Kernel side: kernel #163 (the bus) and #154 (panel size, which the on-screen keyboard needs). Kept locally, available on request, no serials: the dead-man tool's per-run kernel logs, the gauge test logs (including the interrupt log for #170), the charge-watch logs, and the `tools/phone-smoke` report from this kernel. diff --git a/device/husky/HOST-MODE-PLAN.md b/device/husky/HOST-MODE-PLAN.md new file mode 100644 index 000000000..02513887e --- /dev/null +++ b/device/husky/HOST-MODE-PLAN.md @@ -0,0 +1,73 @@ + +# Pixel 8 Pro (husky): USB host (OTG), plan + +Last updated: 2026-11-02. Written 2026-11-01 from source reading; stage 1 has run (section 4), stage 2 is the gated [HOST-MODE-RUNBOOK.md](HOST-MODE-RUNBOOK.md) and runs only on the maintainer's go. Paths: `L/` = our kernel tree (linux-omarchy-mobile); `G/` = Google's GPL sources, branch `android-gs-shusky-6.1-android16`: `kernel/devices/google/shusky` (`dts/zuma-shusky-usecases.dtsi`), `kernel/google-modules/bms` (`max77759_usecase.c`, `max77759_charger.c`, `max77759_A1_regs.h`) and `kernel/google-modules/usbc` (`tcpci_max77759.c`, `tcpci_max77759_vendor_reg.h`). Claims: **[V]** read in the file:line given; **[I]** inferred, with what settles it; **[U]** unknown. + +## 0. Where we stand + +- `tcpci_maxim` binds on husky, `typec/port0` is `power_role [sink]`, `data_role host [device]`, `port_type [sink]`, 3.0 A from the desktop port, a replug handled by the driver ([BATTERY-NOTES.md](BATTERY-NOTES.md) 7.2). **[V]** +- Kernel messages `dummy supplies not allowed for exclusive requests (id=vbus)` / `Failed to get vbus regulator handle`: `max_tcpci_set_vbus()` asks for an exclusive regulator named `vbus`, the TCPC node has no `vbus-supply`, and for a sink-only port it then returns success. **[V: L/drivers/usb/typec/tcpm/tcpci_maxim_core.c:210-251]** + +## 1. What is missing + +### 1.1 The data role never becomes host without a power role change + +- Without PD, TCPM sets the data role from the power role at attach: a source becomes `TYPEC_HOST`, a sink `TYPEC_DEVICE` (`tcpm_data_role_for_source/sink`; only `data-role = "host"`/`"device"` overrides). **[V: L/drivers/usb/typec/tcpm/tcpm.c:786-792, 5059, 5227]** +- Our connector is `power-role = "sink"`, so the phone is always Rd/UFP and can only be a device; `data-role = "dual"` alone changes nothing; PD is disabled (`pd-disable`), so no DR_Swap. **[V: L/arch/arm64/boot/dts/exynos/google/zuma-husky.dts:446-477; tcpm.c:8324]** +- So host mode = a DRP port (`power-role = "dual"`, `try-power-role = "sink"` so chargers still win) and Type-C toggling attaching as source (Rp) to a device that presents Rd. PD is not needed for 5 V host mode. **[V: tcpm.c:778-784 (try-sink needs DRP); 5030-5062 (`tcpm_src_attach` sets VBUS, then the roles)]** +- `tcpm_src_attach()` calls `tcpm_set_vbus(port, true)` and bails on error, so a DRP port without `vbus-supply` would fail every source attach (`max_tcpci_set_vbus` returns -ENODEV for `source`). **[V: tcpci_maxim_core.c:235-240; tcpm.c:5055-5057]** + +### 1.2 The VBUS source is an EXTERNAL boost, not the MAX77759's reverse boost + +- Google's husky use-case node: `max77759,ext-otg-only`, `max77759,bst-on = <&max777x9_gpio 4>` (GPIO5), `max77759,extbst-ctl = <&max77759_tcpc_gpio 0>` (the TCPC's `VENDOR_EXTBST_CTRL`), `max77759,extbst-mode = <&s2mpg14_gpio 4>`, `max77759,bst-lsw-sequence`; no `max77759,usb-otg-mv`. **[V: G/shusky dts/zuma-shusky-usecases.dtsi:10-34]** +- Google's OTG path with `ext_otg_only`: `gs101_otg_enable()` default branch: the bypass registers (`gs101_otg_bypass_enable`), `gs101_ext_mode(EXT_MODE_OTG_5_0V)` = `bst_on` high, 5 ms, `gs101_ls_mode(1)` = TCPC vendor register `EXTBST_CTRL` 0x92 bit 0 `EXT_BST_EN` (the load switch LSW1), then 30 ms. `MODE` (0xb9) stays off: `gs101_otg_mode()` returns early. **[V: G/bms max77759_usecase.c:144-160, 220-250, 370-389, 729-737, 789-875; G/usbc tcpci_max77759_vendor_reg.h:91-92; tcpci_max77759.c:611-618]** The functions are listed line by line in HOST-MODE-RUNBOOK section 1. +- `ext_bst_mode` (s2mpg14 GPIO4) is set after enable when `ext_otg_only && !wlc_otg_extbst_en`; Google's code calls it "extbst mode" (FCCM). Whether 5 V appears without it: **[I: the runbook's stage (a) meter]**. **[V: usecase.c:920-940, 985-996]** +- Google's TCPC driver clears `EXTBST_CTRL` on every toggle restart. **[V: tcpci_max77759.c:2021-2022]** +- The internal reverse boost (`MODE = 0xA`, `CHG_CNFG_05` OTG_ILIM, `CHG_CNFG_11` OTG_VBYP) is what Google uses on boards WITHOUT `ext-otg-only`; the comment in Google's zuma TCPC include says the external boost does about 1 A, the internal 1.5 A, and the source PDO is 5 V / 900 mA. **[V: G/ zuma `max777x9-tcpc.dtsi`:38-49]** Whether husky's internal boost is even wired to the connector: **[U]**; never test `MODE = 0xA` first. + +### 1.3 What our tree already has + +- `max77759_charger.c` registers a `chgin-otg` regulator (fixed 5 V, enable = `MODE 0xA`), DT child `chgin-otg-regulator`; this is the INTERNAL boost, not husky's path, and has no ILIM/VBYP handling. **[V: L/drivers/power/supply/max77759_charger.c:513-548, 1026-1033; L/include/linux/mfd/max77759.h:207-210]** +- `maxim,max33359.yaml` has `vbus-supply` on the TCPC node. **[V: L/Documentation/devicetree/bindings/usb/maxim,max33359.yaml:36-37, 60]** +- `gpio-max77759` exposes two lines, "GPIO5" (offset 0) and "GPIO6" (offset 1); the gpio cell is in husky's `pmic@66`. GPIO6 is the VBUS input switch (active low), left alone. **[V: L/drivers/gpio/gpio-max77759.c:23-24; zuma-husky.dts:457-459, 501-507]** +- No driver exposes TCPC 0x92: mainline `tcpci_maxim_core.c` only knows 0x93 `USBSW_CTRL`. **[V: tcpci_maxim_core.c:25-27]** +- dwc3: `dr_mode = "peripheral"`, no `usb-role-switch`, no graph port. dwc3 registers a role switch when `usb-role-switch` is present, with `role-switch-default-mode`; TCPM finds it through the connector's graph. **[V: L/arch/arm64/boot/dts/exynos/google/zuma.dtsi:953-963; L/drivers/usb/dwc3/drd.c:498-540; tcpm.c:8924-8926; L/drivers/usb/roles/class.c:126-136, 190-197]** +- Config: `USB_DWC3_DUAL_ROLE=y`, `USB_ROLE_SWITCH=y`, `USB_XHCI_HCD/PLATFORM=y`, `USB_HID=y`, `HID_GENERIC=y`, `USB_STORAGE=y`, `USB_USBNET/CDCETHER/AX8817X/AX88179/RTL8152=m`, `TYPEC_DP_ALTMODE=m`. **[V: the e1 build's .config]** +- The PHY (`phy-exynos5-usbdrd.c`, `zuma_usb32drd_phy`) has no `set_mode`; it forces VBUS valid unless it has an orientation switch. **[V: phy-exynos5-usbdrd.c:2114-2124, 547-566]** Stage 1 showed it survives a role switch with nothing attached (section 4). +- The eUSB2 repeater at 0x3e has no driver; high speed as a device works without it. Host HS with it untuned: **[U; stage 3 devices]**. + +## 2. Patch outlines (kernel, later) + +### 2.1 External-boost VBUS regulator + +Option A (preferred, no new driver): a `regulator-fixed` with `gpio = <&max77759_gpio 0 GPIO_ACTIVE_HIGH>` (bst_on), `enable-active-high`, `regulator-name = "usb-otg-vbus"`, 5 V, `startup-delay-us = <5000>`, never `regulator-boot-on` or `regulator-always-on`; plus `tcpci_maxim_core.c` setting and clearing `TCPC_VENDOR_EXTBST_CTRL` (0x92) bit 0 around `regulator_enable/disable` in `max_tcpci_set_vbus()`, gated by a new TCPC DT property, with a `dt-bindings:` patch for `maxim,max33359.yaml`. Register and bit from Google's header and driver. **[V: vendor_reg.h:91-92; order from usecase.c:789-875]** The bypass registers (HOST-MODE-RUNBOOK section 5) then belong in the charger driver, through its regmap. Open question for the maintainers: a boolean or a GPIO-chip-like description as Google's `max77759_tcpc_gpio`. +Option B: a small regulator driver in the TCPC owning both the GPIO and 0x92. More code, same binding question. +Not in scope: `chgin-otg` (internal boost), OTG while charging, FRS, `ext_bst_mode` unless stage (a) shows no 5 V. + +### 2.2 DT (husky, upstream style, one commit each) + +1. `arm64: dts: exynos: google: zuma-husky: add the Type-C VBUS boost`: a label on the gpio node, `usb_otg_vbus: regulator-usb-otg-vbus` (regulator-fixed on GPIO5), `vbus-supply = <&usb_otg_vbus>` on `usb-typec@25`, the new TCPC property. +2. `arm64: dts: exynos: google: zuma-husky: make the Type-C port dual role`: `power-role = "dual"`, `try-power-role = "sink"`, `source-pdos = ` (Google's), `pd-disable` and the sink PDOs kept. +3. `arm64: dts: exynos: google: zuma-husky: wire the USB controller to the Type-C port`: `&usb_dwc3 { dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "peripheral"; port { ... } }` and the connector's port@0 endpoint; `maximum-speed = "high-speed"` kept. (This is what `overlays/usb-role-test.dtso` does for the test boot.) + +Sent to linux-omarchy-mobile as one branch with the prefixes `dt-bindings: usb: maxim,max33359:`, `usb: typec: tcpci_maxim:`, `arm64: dts: exynos: google: zuma-husky:`. Questions for the maintainers first: the binding shape, and whether zuma's dwc3 may switch to host without a glue driver (stock wraps it in `exynos9-dwusb`; stage 1 says yes for the switch itself). Cheetah has the same stock wiring and may want the same. + +## 3. Staged plan (overlays first, DT later; dead-man pattern from `tools/husky-deadman`) + +- **Stage 0** (no reboot): with `tcpci_maxim` loaded, read `/sys/class/usb_role/*` (expect none), `/sys/class/typec/port0/{data_role,power_role,port_type}`; dump TCPC 0x92, charger 0xb9/0xbe/0xc4. Rollback: none. +- **Stage 1** (role switch only, NO VBUS, one reboot): `overlays/usb-role-test.dtso` on top of `overlays/typec-test.dtso`: dwc3 `dr_mode = "otg"`, `usb-role-switch`, default peripheral, connector port@0 to dwc3; the connector stays sink-only. Load `tcpci_maxim` under `b4-tcpm`. Pass: `/sys/class/usb_role/11210000.usb-role-switch/role` = `device`, the `usb0` gadget still configured, Wi-Fi up. Hand test: `echo host > .../role` for a few seconds with nothing plugged in (no VBUS involved, the desktop cable out, control over Wi-Fi), then back to `device`. Pass: xHCI root hubs appear, dmesg clean, no PHY hang, the gadget returns. Stop: no `role` file, dwc3 "Configuration mismatch", an oops, the gadget never returns. Rollback: `echo device`, `undo b4-tcpm`, re-flash the known-good images. +- **Stage 2** (VBUS sourcing from userspace, nothing attached): [HOST-MODE-RUNBOOK.md](HOST-MODE-RUNBOOK.md) stage (a), under `b5-host`, with an independent USB-C meter, on the maintainer's go. Pass: about 5 V on the meter while sourcing, 0 V after the undo. No-go: any trip. If no 5 V: `ext_bst_mode` (s2mpg14 GPIO4) next, the internal boost last, each as its own reviewed step. +- **Stage 3** (attached devices): through the kernel path of section 2 (TCPM sources only after a sink attaches), with its own runbook alongside the kernel pull request: a keyboard (HID, about 100 mA), then a flash drive (200-400 mA), then an Ethernet dongle (300-500 mA), watching VBUS sag and pack current. Not from userspace. +- HDMI/DisplayPort dongles need DP alt mode (PD required), the SBU mux (`sbu-mux-sel-gpio` in Google's DT), the USB3/DP combo PHY at 0x11130000 and a DRM DP sink; mainline has none of this for zuma. Out of scope, far larger. **[V: zuma.dtsi:892-895; grep typec_mux in L/drivers/phy/samsung empty]** + +Retry cost: each stage with a reboot spends one slot B boot (three per flash); re-flash the known-good images before a stage to refill. Everything inside a stage (module loads, `echo host`) is live and costs nothing. + +## 4. Results + +**Stage 1, 2026-11-01 20:56-21:03, kernel `7.3.0-rc6-omamobile-push1-g5899fec2bd28`** (the e1 images with `typec-test` and `usb-role-test` applied; slot B read 2 tries before the flash, the flash refilled to 3, one boot used). **[V: BATTERY-NOTES.md 7.2 and the kernel logs kept locally]** +- After boot: `dr_mode otg` in the live DT, `/sys/class/usb_role/11210000.usb-role-switch/role` = `device`, UDC `configured`, USB SSH up on the first boot with the overlay (dwc3 does not wait for the Type-C driver), `typec/port0` absent until the Type-C driver loads. Then `b4-tcpm` (charger-less, soak 120 s) over Wi-Fi: clean, port0 sink, 3.0 A, no hard resets, USBSW 0x09. +- `echo host > .../role` (no VBUS, connector still sink-only), by hand over Wi-Fi with a restore-to-device trap: the gadget went away and two xHCI root hubs appeared, `usb1` at 480 Mbit/s and `usb2` at 10000 Mbit/s; `typec/port0/data_role` still read `host [device]` (the userspace write bypasses TCPM, as expected). `echo device`: UDC `configured`, `usb0` carrier 1, the USB address answered in 4 ms. No hang, no oops, no kernel message during the 5 s in host mode. +- Conclusion: zuma's dwc3 runs as a host with the in-tree `dwc3` + `xhci-plat` and no stock glue driver, and the PHY survives the role switch with nothing attached. Not shown: whether the eUSB2 PHY/repeater enumerates real devices (no VBUS, so nothing could attach); that TCPM sets the role switch by itself on an attach. +- A planned check for a sysfs link from `typec/port0` to the dwc3 role switch was wrong (TCPM keeps the switch as an internal pointer; there is no such link) and was dropped. + +**Stage 2:** not run. One earlier sourcing attempt (2026-11-01 21:33, before the maintainer's review, over Wi-Fi with nothing attached) used a first version of `b5-host` without the baseline-relative guard; it tripped at once on the charger's details (`CHG_DETAILS_01` 0xb1 with the bootloader's MODE 0x05) and the undo brought the TCPC's VBUS reading back under 0.8 V within a second. That is why the runbook writes MODE 0x00 first and defines the charger guard against a baseline. **[V: the tool's log, kept locally]** diff --git a/device/husky/HOST-MODE-RUNBOOK.md b/device/husky/HOST-MODE-RUNBOOK.md new file mode 100644 index 000000000..f497d46e4 --- /dev/null +++ b/device/husky/HOST-MODE-RUNBOOK.md @@ -0,0 +1,148 @@ + +# Pixel 8 Pro (husky): sourcing 5 V on the USB-C port from userspace, stage (a) runbook + +Last updated: 2026-11-02 (second revision, after the maintainer's review of the draft). Draft, for review. **Nothing in this document runs until the maintainer says go.** The one sourcing run that has happened (2026-11-01, before the review, over Wi-Fi with nothing attached; the undo brought the port to 0 V within a second) is described in [BATTERY-NOTES.md](BATTERY-NOTES.md) and in the pull request; it used an earlier version of the tool and is not a result of this runbook. + +Tags, on every claim: **[verified]** read in the file at the line given, or in a log; **[inferred]** follows from a verified fact, with what settles it; **[unknown]** in no file we have, with the test that answers it. + +Paths: `G/` = Google's GPL charger code, `kernel/google-modules/bms`, branch `android-gs-shusky-6.1-android16` (`max77759_usecase.c`, `max77759_charger.c`, the register headers `max77759_A1_regs.h` and `max77759_v0p65_121919_regs.h`); `D/` = Google's GPL device tree for husky, `kernel/devices/google/shusky`, same branch (`dts/zuma-shusky-usecases.dtsi`); `L/` = our kernel tree (linux-omarchy-mobile, the c6 base); `P/` = `tools/husky-deadman-phone` in this repository. + +## 0. Scope + +Stage (a) only: VBUS on, **nothing attached** but a passive inline USB-C meter, a 30 s soak under the 1 s guard, then the tool's own undo switches VBUS off **in the same run**: a hot port is never left standing without the guard (`P/run`, the `b5-host` case after the soak). The dwc3 controller stays in device role, so nothing could enumerate anyway, and the only overcurrent detection is the tool's 1 s voltage poll. Attached devices (a keyboard, a flash drive, an Ethernet dongle) are **not** done from userspace: they go through the kernel path in section 7, with its own runbook next to that kernel pull request. The `--device` mode of the earlier tool is removed; `husky-deadman-phone` refuses the option. + +What stage (a) answers: does Google's external-boost sequence, replayed from userspace with the bypass registers programmed, put about 5 V on the port, and does it go away on the undo. What it does not answer: anything about load, overcurrent behaviour, or the data path. + +## 1. Google's sequence, the functions to read + +Google's husky use-case node (`&max77759_chg`) has `max77759,bst-on = <&max777x9_gpio 4 GPIO_ACTIVE_HIGH>` ("MW: OTG_BOOST_EN", GPIO5), `max77759,extbst-ctl = <&max77759_tcpc_gpio 0 GPIO_ACTIVE_HIGH>` (the TCPC's `VENDOR_EXTBST_CTRL`), `max77759,extbst-mode = <&s2mpg14_gpio 4 GPIO_ACTIVE_HIGH>`, `max77759,ext-otg-only` ("use external OTG only") and `max77759,bst-lsw-sequence`; no `max77759,usb-otg-mv`, no `max77759,vin-is-valid`. **[verified: D/dts/zuma-shusky-usecases.dtsi:10-34 (lines 12, 13, 14, 31, 34)]** + +`G/max77759_usecase.c`, the on path: + +| Step | Function | What it does | Lines | +| --- | --- | --- | --- | +| 0 | `gs101_standby_to_otg()` | `mode = EXT_MODE_OTG_5_0V` (because `ext_otg_only`), calls `gs101_otg_enable(uc_data, mode)`, then `gs101_ext_bst_mode(uc_data, 1)` when `ext_otg_only && !wlc_otg_extbst_en`, then 5 ms | 985-996 | +| 1 | `gs101_otg_enable()` default branch (`vin_is_valid < 0`, as on husky) | `gs101_otg_bypass_enable(uc_data, uc_data->otg_value)`; `gs101_ext_mode(uc_data, mode)`; 5 ms; `gs101_ls_mode(uc_data, 1)`; 30 ms ("time for VBUS to be on") | 789-875, default branch 833-857 | +| 1a | `gs101_otg_bypass_enable()` | write `CHG_CNFG_11` = `vbyp`; set `OTG_V_PGM` in `CHG_CNFG_18` | 370-383 | +| 1b | `gs101_ext_mode(EXT_MODE_OTG_5_0V)` | `bst_on` GPIO high (no `bst_sel` on husky) | 220-250 | +| 1c | `gs101_ls_mode(1)` | `gpio_set_value_cansleep(ext_bst_ctl, 1)`: the TCPC's `EXTBST_CTRL` 0x92 bit 0 `EXT_BST_EN`, written as a whole byte by Google's TCPC driver (`ext_bst_en_gpio_set`); the load-switch readback is skipped because husky's node has no `lsw1-is-closed`/`lsw1-is-open` | 144-160; `tcpci_max77759.c:611-618`, `tcpci_max77759_vendor_reg.h:91-92` | +| 2 | `gs101_ext_bst_mode(1)` | s2mpg14 GPIO4 ("extbst mode", FCCM) high | 920-940 | +| – | `gs101_otg_mode()` | returns 0 at once with `ext_otg_only` ("no transition needed if only use external boost OTG"): the charger `MODE` register is **not** switched to the internal boost; the use-case comment for this path reads "5-1: mode=0x0 in MW, EXT_B=1, LS1=1" | 729-737; 945-955 | + +The off path (OTG to standby with `ext_otg_only`): `gs101_ext_bst_mode(0)`, `gs101_ls_mode(0)`, `gs101_ext_mode(0)`. **[verified: 1199-1204]** `gs101_otg_bypass_disable()` clears `OTG_V_PGM`. **[verified: 385-389]** Google's TCPC driver also clears 0x92 on every toggle restart. **[verified: tcpci_max77759.c:2021-2022]** + +What the tool does with this: steps 1a, 1b, 1c in that order with those delays, `MODE` = 0x00 before them (section 5), and step 2 **not done** (no mainline access to that s2mpg14 GPIO was checked). **[inferred: whether 5 V appears without step 2 is what the meter says in stage (a)]** + +## 2. The meter is the measurement + +Stage (a) is gated on an **independent** USB-C meter inline on the port, with nothing on its far side: it must read **0 V before** the run, **about 5 V during** (4.75 to 5.25 V is the pass window), and **0 V after** the undo. The TCPC's own `VBUS_VOLTAGE` register (0x70, 25 mV per LSB, **[verified: L/include/linux/usb/tcpci.h:159-161]**) is read and logged by the tool once a second, but it comes from the chip we are driving and is not the check. **[verified: this is the maintainer's review condition]** + +The tool refuses `b5-host` without `--meter`, which is the operator's statement that the meter is on and read 0 V. The tool cannot check the meter; the person can. + +The same meter answers the charging-current question of issue #1 (how much the charger draws from a source; the input limit register still reading 0x13 does not mean the chip draws only 500 mA, see the note in TYPEC-FAST-CHARGE-PLAN.md): one meter, both measurements. The meter must be passive on CC: if `husky-deadman-phone dump` shows a CC partner with only the meter plugged in, that meter presents a termination of its own and cannot be used for stage (a). **[inferred: the dump's CC line before the run settles it]** + +## 3. A hot port, and a reset that leaves it hot + +Sourcing from userspace skips Type-C's attach detection: VBUS is on whatever is plugged in. GPIO5 and 0x92 are registers of the MAX77759, not of the SoC (GPIO5 is a PMIC MaxQ register, **[verified: L/drivers/gpio/gpio-max77759.c:99-107, 198-216]**; 0x92 is a TCPC vendor register), so a SoC reset is expected to leave them as they were and the port hot through the reboot. **[inferred: no reset with the boost on has been observed on this phone; the a6 drill is the test]** Three lines of defence, in the order they act: + +**Rule (the person).** During a stage, **nothing that can source** is plugged into the port or the meter's far side: no charger, no desktop cable, no powered hub, no meter with its own power. On any trouble, **the load comes out first**, then the software undo. The desktop cable stays out for the whole stage; the way in is Wi-Fi. + +**Guard (the tool, once a second).** `CC_STATUS` (TCPC 0x1d): bit 5 `TOGGLING`, bit 4 `TERM` (1 = this port presents Rd, as a sink does), bits 3:2 CC2 and 1:0 CC1; with Rd presented, the values 1/2/3 mean the partner shows Rp default / 1.5 A / 3 A, 0 is open **[verified: L/include/linux/usb/tcpci.h:87-93, and the decode `tcpci_to_typec_cc()` at 246-261, as `tcpci_get_cc()` in tcpci.c uses it]**. A partner Rp is a source on the port; the tool refuses to start with one, and trips the undo at once if one appears while sourcing (`P/cc_partner`, `P/host_guard`). `TERM` = 0 (this port presenting Rp) or the toggling bit set are treated as "not valid": a refusal before the step, a trip after three such reads. Whether the MAX33359 reports a partner Rp in this register while it is itself the one putting 5 V on VBUS: **[inferred from the TCPCI layout; the register is logged every second during stage (a), and a check with a known Rp (a charger) is *not* part of stage (a), see the rule above]**. + +**Undo at the next boot (the tool, by itself).** Before its first register write, `b5-host` writes a marker (`/var/lib/husky-deadman/undo-pending`, holding the saved registers and the boot id) and installs `/etc/systemd/system/husky-deadman-undo.service`: `Type=oneshot`, `ConditionPathExists=` that marker, `DefaultDependencies=no`, `After=sysinit.target systemd-udev-settle.service`, `Before=basic.target`, `ExecStart=husky-deadman-phone boot-undo`, enabled for `basic.target`. The unit is written and enabled first, the marker last, so a failed install leaves no marker. It has `TimeoutStartSec=180` (boot-undo waits up to 60 s for the I2C bus and 10 s for the gpiochip) and `RequiresMountsFor=/var/lib/husky-deadman /usr/local/bin`. At the next boot it writes TCPC 0x92 = 0x00 and GPIO5 = 0 and reads both back: that is the port **cold**, and only then the marker and the unit go. Then it undoes only what still reads as b5-host's own write: MODE 0xb9 back to the saved value only if it reads 0x00 now, bit 3 of 0xcb cleared only if it was clear before and reads set now, 0xc4 back only if it was different before and reads 0x00 now; anything else was set by this boot's bootloader or a driver and stays, logged. One case cannot be told apart: a MODE that reads 0x00 after the reset is either b5-host's own write kept by the PMIC or this boot's bootloader choosing 0x00; the rule (write back only while it still reads 0x00) accepts that, and the consequence is that boot-undo may then switch charging on (the saved 0x05 is buck and charger on) over a bootloader that had left it off. **[inferred: whether husky's bootloader ever leaves MODE at 0x00 is unknown; every dump so far read 0x05]** If a write it had to make fails (or the charger driver is loaded, so it writes nothing there), the saved values go to `/var/lib/husky-deadman/registers-not-restored`, which `b5-host` refuses on until the person has restored them by hand, and the marker still goes (it exists for the hot port, not for the registers, and must not fire at every boot for writes it cannot make). If the port is **not** proven cold, the marker stays and the unit runs again at the following boot (`P/undo_unit_install`, `P/boot_undo`). A clean undo in the same boot removes both as well, and follows the same split: its return value is the port cold, a failed register restore leaves `registers-not-restored` and refuses the next run, and never makes `run` reset the phone (a reset costs a slot B try). `systemctl stop` of the run, or a reboot during it, sends TERM: the tool traps TERM, INT and HUP during b5-host and runs the undo first (the watchdog feeder ignores the signal until that undo has asked it to close, and the undo itself ignores a second signal). The undo takes about 5 s and the watchdog close up to 12 s, inside the transient unit's default `TimeoutStopSec` of 90 s, so no explicit value is set. A failed register restore after a clean soak shows in the result (`soaked: VBUS off, but ... not all restored`), which the desktop tool prints. The unit cannot run on a normal boot: without the marker the condition fails, and `boot-undo` itself exits at once without the marker. All of this is checked against stubs in `tests/husky-deadman`, not on the phone. **[verified against stubs only, tests/husky-deadman; not run on the phone]** A TERM, INT or HUP that arrives after the trap is set but before `b5-host` has saved the registers finds neither `host.saved` nor the marker: the undo then writes none of 0xb9, 0xc4 and 0xcb (the step had written nothing yet, so a set bit 3 in 0xcb is the bootloader's) and only switches the port off. **[verified: tests/husky-deadman 9e2]** + +Unverified about the boot undo: **[unknown]** whether `max77759`, the I2C host and `gpio-max77759` are up by `basic.target` on the phone (the unit waits up to 60 s for the bus, then loads `max77759` itself if it is not up and waits up to 10 s for it, then `gpio_max77759` and up to 10 s for the chip, and keeps the marker if any of them never shows up; its modprobe block is a `blacklist` line, which an explicit modprobe ignores **[verified: BATTERY-NOTES section 4, M3]**); **[unknown]** whether `libgpiod` is installed on the phone (the device package depends on bash, systemd and the keyring only **[verified: packages/omamobile-device-husky/PKGBUILD]**; `pacman -S libgpiod` first, and the preflight refuses without it). + +**Manual fallback (the person, second).** If the phone froze, no software undo ran at all. Then, in this order: + +1. Unplug anything on the port (the meter too). +2. Force a restart: hold Power + Volume Up for 15 to 30 s (Power alone does nothing under our kernel). This spends one of slot B's three boot tries: count them, and flash the known-good set first if only one is left (BATTERY-NOTES section 3). +3. First thing after the boot, over Wi-Fi, before anything is plugged in: + + ```sh + OMAMOBILE_SSH_HOST=root@ tools/husky-deadman boot-undo # runs husky-deadman-phone boot-undo + OMAMOBILE_SSH_HOST=root@ tools/husky-deadman dump # 0x92 must read 0x00, gpio5 0, no marker + ``` + + If the tool is not there or fails, by hand on the phone, as one script, so that nothing is deleted before every step has read back right (BUS is the adapter number of `10cb0000.i2c`, `ls -l /sys/bus/i2c/devices/ | grep 10cb0000`; CHIP is `/dev/gpiochipN` from `/sys/bus/platform/devices/max77759-gpio*/`; `max77759_charger` must NOT be loaded, `lsmod | grep max77759_charger` empty): + + ```sh + set -u; BUS=; CHIP=/dev/gpiochip; M=/var/lib/husky-deadman/undo-pending + lsmod | grep -q '^max77759_charger ' && { echo "charger driver loaded: stop"; exit 1; } + i2cset -f -y $BUS 0x25 0x92 0x00 || exit 1 + [ "$(i2cget -f -y $BUS 0x25 0x92)" = 0x00 ] || { echo "0x92 not 0x00"; exit 1; } + modprobe gpio_max77759; gpioset -c $CHIP GPIO5=0 & sleep 0.2; kill $! + [ "$(gpioget --as-is -c $CHIP GPIO5)" = '"GPIO5"=inactive' ] || { echo "GPIO5 not 0"; exit 1; } + # the port is cold. Now the registers, from the saved values in the marker + cb=$(i2cget -f -y $BUS 0x69 0xcb) || exit 1 + i2cset -f -y $BUS 0x69 0xcb $(printf '0x%02x' $(( cb & 0xf7 ))) || exit 1 # bit 3 OTG_V_PGM clear + [ $(( $(i2cget -f -y $BUS 0x69 0xcb) & 0x08 )) -eq 0 ] || { echo "0xcb bit 3 still set (CHGPROT 0xbf bits 3:2 = 11 unlocks; relock after)"; exit 1; } + c4=$(awk '$1=="0xc4"{print $2}' $M); b9=$(awk '$1=="0xb9"{print $2}' $M) + i2cset -f -y $BUS 0x69 0xc4 "$c4" && [ "$(i2cget -f -y $BUS 0x69 0xc4)" = "$c4" ] || { echo "0xc4"; exit 1; } + i2cset -f -y $BUS 0x69 0xb9 "$b9" && [ "$(i2cget -f -y $BUS 0x69 0xb9)" = "$b9" ] || { echo "0xb9"; exit 1; } + rm -f $M; systemctl disable husky-deadman-undo.service; rm -f /etc/systemd/system/husky-deadman-undo.service; systemctl daemon-reload + echo "undone" + ``` + + Any line that stops leaves the marker, so the unit tries again at the next boot. Only after "undone" plug the meter back in and read 0 V. **[verified against the tool's own stub test for the same sequence; the script itself has not been run anywhere]** + +## 4. The charger guard: baseline first + +`CHG_DETAILS_01` read 0xb1 in every dump taken while the pack was charging (`BAT_DTLS` 3 = battery okay, `CHG_DTLS` 1 = fast-charge constant current, bit 7 set) with the bootloader's `MODE` 0x05. That value means a source was charging the phone, so it cannot have been a dump with the cable out; with a cable in and the pack done it reads 0xb4 (`CHG_DTLS` 4, 2026-11-04 and 2026-11-06). A guard that trips on "CHG_DTLS says charging" therefore says nothing while a source is attached: it tripped the first run at once. **[verified: the 2026-11-01 run's log, and the maintainer's review]** + +Now: + +1. `husky-deadman-phone baseline` (`tools/husky-deadman baseline`) is a new **read-only** step: cable out, Wi-Fi only, the charger driver not loaded, no write anywhere. It reads `CHG_DETAILS_00` 0xb5, `_01` 0xb6 and `_02` 0xb7 five times a second apart and keeps the values for this boot (`/run/husky-deadman/baseline`, with the boot id). A register that does not read the same five times makes the baseline "unstable" and `b5-host` refuses until a stable one is taken. **[verified: P/baseline]** +2. `b5-host` refuses without a stable baseline from **this** boot, and its guard trips on a **change from the baseline** in the fields mainline names: 0xb5 `CHGIN_DTLS` bits 6:5, 0xb6 `BAT_DTLS` bits 6:4 and `CHG_DTLS` bits 3:0, 0xb7 `CHGIN_STS` bit 5 **[verified: L/include/linux/mfd/max77759.h:83-89]**. The other bits are logged and never compared. **[verified: P/chg_vs_baseline, P/host_guard]** +3. The `MODE` 0x00 write (section 5) comes before the boost. Right after it, and before GPIO5, the tool reads the details again and compares with the cable-out baseline: **if MODE 0x00 alone moves them, the run stops there, before any VBUS**, logs the MODE-0 reading, and undoes (MODE back). That is a legitimate end of a first run: it gives the reading the maintainer asked for. The guard then has to be **re-derived against what the registers read with MODE 0x00**, as its own reviewed change, before the next run. **[verified: P/apply b5-host; what MODE 0x00 does to CHG_DTLS is unknown until that run]** + +## 5. The bypass registers, and MODE + +Google programs the charger's OTG bypass before `bst_on` (section 1, step 1a). The tool now does the same, with these values: + +- `CHG_CNFG_11` 0xc4 = **0x00**. `otg_value` comes from `max77759,usb-otg-mv`, which stock husky's node does not have, so the default `GS101_OTG_DEFAULT_MV` = `MAX77759_OTG_5000_MV` = 5000 mV is used, and `max77759_otg_vbyp_mv_to_code()` gives `(5000 - 5000) / 50` = 0 (12000 mV and above gives 0x8c). **[verified: G/max77759_charger.c:40-41, 3331-3340; G/max77759_usecase.c:1281-1292; D/dts/zuma-shusky-usecases.dtsi:10-34 has no usb-otg-mv]** (The earlier design note's 5100 mV / code 0x2 is `GS101_OTG_VBYPASS_DEFAULT_MV`, used for `otg_vbyp`, the wireless path, usecase.c:1372; not this one.) The register's power-on default is 0x00 as well **[verified: G/max77759_v0p65_121919_regs.h:1993-1996]**, so on a fresh boot this write changes nothing; it is still done and read back, so the sequence is Google's. +- `CHG_CNFG_18` 0xcb bit 3 `OTG_V_PGM` set, by a read-modify-write of that bit only; the undo clears it (as `gs101_otg_bypass_disable()` does) and puts 0xc4 back, each only where it still reads as this step's own write (section 3). **[verified: `MAX77759_CHG_CNFG_18 0xCB` at G/max77759_A1_regs.h:2383 and `MAX77759_CHG_CNFG_18_OTG_V_PGM (0x1 << 3)` at 2386 (the register's comment block starts at 2380), fetched from the bms repository at that branch; the same in G/max77759_v0p65_121919_regs.h:2281-2303]** Google's shipping driver includes `max77759_regs.h`, which includes `max77759_A1_regs.h`; both headers give bit 3, so this is not a register-map version question. **[verified: G/max77759_regs.h:11]** The earlier design note said the bit's position was unknown; it was in these headers. Limit: the headers are machine-generated from a register-map CSV ("source MW_regmap_ds_v0p65_121919.csv"), and no datasheet was read; the bit is where Google's code writes it, which is what we replay. +- Whether 0xcb takes the write without the `CHGPROT` unlock (`CHG_CNFG_06` 0xbf bits 3:2 = 11, as mainline's probe does for `WDTEN` in the same register, **[verified: L/drivers/power/supply/max77759_charger.c:145-149, 642-657]**): **[unknown]**. The tool writes, reads back, and only if the readback disagrees unlocks `CHGPROT`, retries, and puts 0xbf back to what it was. 0xbf is saved before the step. (Google's `max77759_chgr_reg_update()` is not in the files we have, so whether Google unlocks here is **[unknown]** too.) +- Both registers are saved before the step (with 0xb9 and 0xbf) and put back by the undo and by the boot undo only where they still read as this step's own write; a register that cannot be read or written back counts as not restored and goes to `registers-not-restored`. **[verified: P/host.saved, P/restore_own_writes; tests/husky-deadman]** +- The tool refuses `b5-host` while `max77759_charger` is loaded (unchanged): the MFD registers the charger regmap with a flat cache that is volatile only for 0xb0-0xb1 and 0xb4-0xb8, so an `i2cset` to 0xc4/0xcb behind a loaded driver would be written back stale by its next `regmap_update_bits`. **[verified: L/drivers/mfd/max77759.c:154-186]** + +`MODE` (`CHG_CNFG_00` 0xb9): written to 0x00 for the duration and restored by the undo. Google keeps the charger mode at 0 on this path (section 1); the first run, with the bootloader's 0x05 left on, saw CHG_DTLS in "charging" at once (section 4). **[verified: G/max77759_usecase.c:729-737, 945-955; the 2026-11-01 log]** Whether the charger's CHGIN sees the self-sourced 5 V: with `MODE` 0x05 it does (the first run's CHG_DTLS moved to "charging" at once, section 4), so section 8 item 4 is answered for 0x05; it stays open only for `MODE` 0x00. **[verified for 0x05: the 2026-11-01 log; unknown for 0x00]** + +Writing 0x92 with `i2cset -f` while `tcpci_maxim` is bound is fine for research with the tool's "0x92 changed under us" guard (the maintainer's note): mainline's `tcpci_maxim` never touches 0x92 (its only vendor writes are to 0x93, and its regmap allows writes through 0x95), so nothing in our kernel races the byte. **[verified: L/drivers/usb/typec/tcpm/tcpci_maxim_core.c:25-27, 40-52]** The guard trips if 0x92 stops reading 0x01 while sourcing. This stays research: the kernel path (section 7) owns the byte for good. + +## 6. The runbook: stage (a) + +Preconditions the tool enforces (each a refusal, nothing applied): Pixel 8 Pro by compatible; Wi-Fi up; `max77759_charger` blocked in `modprobe.d` and not loaded; `max77759` loaded; `b4-tcpm` applied in this boot (`tcpci_maxim` bound, `typec/port0` with `power_role [sink]`); the `usb-role-test` overlay's dwc3 role file reading `device`; the USB gadget not configured (desktop cable out); `gpio-max77759` and libgpiod v2 (`gpioget --as-is`); GPIO5 reading 0; 0x92 reading 0x00; `POWER_CTRL` bit 6 clear (VBUS monitor on); `POWER_STATUS` bits 4/2/0 clear; TCPC VBUS reading at most 0.8 V; CHGIN not valid; `MODE` without a boost bit; no partner on CC; a stable baseline from this boot, and the details still matching it; no undo marker from an earlier boot; `--meter`; battery 3.0 to 4.15 V, 10 to 40 C and not exactly 22.0 C, 30 to 80 %; one `b5-host` per boot. **[verified: P/preflight, P/preflight_host]** + +What stays as the review approved it: the battery and temperature limits and the 1.7 A trips, one run per boot with the latch (`b5-done`) left alone, runs started by hand with the person watching the meter and the kernel log, and the slot B tries refilled with a flash before a stage that can reset the phone. + +| # | Step | Commands (desktop, over Wi-Fi) | Expect / pass | Stop | Rollback | Risk | +| --- | --- | --- | --- | --- | --- | --- | +| a0 | Image | `bin/omamobile flash` of the e1 images with `typec-test` and `usb-role-test` applied (refills slot B's tries) | boots, Wi-Fi up, `/sys/class/usb_role/11210000.usb-role-switch/role` reads `device` | no role file, no Wi-Fi | flash the known-good set | reboot (one try) | +| a1 | Read-only | `tools/husky-deadman dump` with the cable out and the meter in | 0x92 0x00, gpio5 0, CC partner none, VBUS at most 0.8 V, meter 0 V, no marker | CC partner shown with only the meter in (the meter is not passive) | none | none | +| a2 | Baseline | `tools/husky-deadman baseline` | `ok`, three registers each stable over 5 reads, written to the log | "unstable": wait, take it again | none (read-only) | none | +| a3 | Type-C driver | `tools/husky-deadman b4-tcpm` over Wi-Fi, charger-less, cable out (so no partner; its own preflight and 120 s soak), in the same boot as a4 | `tcpci_maxim`, `tcpci`, `tcpm` loaded, `maxtcpc` bound to `-0025`, `/sys/class/typec/port0` with `power_role [sink]`, `data_role host [device]`, no partner, 0 hard resets or contaminant states in the tcpm log, register 0x93 (`USBSW_CTRL`) reads 0x09, Wi-Fi up; the soak confirmed and finished clean (as on 2026-11-01, BATTERY-NOTES 7.2) | a hard reset or contaminant state in the tcpm log, the driver not bound, port0 missing, Wi-Fi gone, any battery trip (the step undoes itself on these) | `tools/husky-deadman undo b4-tcpm` (unloads the three modules, 0x93 = 0x09 only with VBUS valid, restarts the rescue) | no VBUS involved; USB is not the way in | +| a4 | Source | `tools/husky-deadman b5-host --meter` (soak 30 s, then the tool's own undo) | **four outcomes are possible; the most likely is (a4c), VBUS on and then a trip on CHGIN within 1 s, so have the meter reading real VBUS from the first run:** (a4c) the sequence runs to VBUS on, and within the first second of the 1 s guard the charger details (CHG_DETAILS_00/01/02, CHGIN seeing the self-sourced VBUS) leave the baseline: the log has a line with the three registers right after VBUS on, then the guard's own line naming that check as the one that ended the run ("tripped", exit 7), the undo runs, MODE 0xb9 is put back to the saved value, the **meter shows 5 V briefly and then 0 V after the undo**, and no undo marker is left behind (this is an expected result, not a fault; I have not seen it yet, so it is [inferred]); (a4') the run stops right after MODE 0x00 because the charger details moved off the baseline (the baseline was taken at the bootloader's MODE 0x05, so `CHG_DTLS` may change): the MODE-0 reading is in the log, MODE is restored, no VBUS was ever on; (a4'') the sequence completes and the TCPC reads under 4.5 V: "no 5 V from the external boost on this path" is logged and the undo runs; `gs101_ext_bst_mode` (s2mpg14 GPIO4) was skipped, so this is an allowed result, not a fault, and the next step is that GPIO as its own reviewed change; (a4) "VBUS up" 4500-5500 mV, **meter 4.75-5.25 V**, details unchanged, battery current up by tens of mA at most, CC no partner, then after 30 s "SOAKED and UNDONE" and the **meter at 0 V** | a trip, the meter disagreeing with 0x70 by more than 0.3 V (write both down), the meter not at 0 V after the undo, anything warm | automatic (the run ends in the undo in every outcome); if the meter still shows VBUS: unplug the meter, section 3 fallback | VBUS on the port with nothing attached; 1 s poll only; bst_on is high about 0.2 s before 0x92 (the tool's gpioset hold and readback), not Google's 5 ms, **[inferred: a longer settle in the same direction, logged]** | +| a5 | Check | `tools/husky-deadman dump` | 0x92 0x00, gpio5 0, 0xcb bit 3 clear, 0xc4 and 0xb9 as before, no marker, no `registers-not-restored`, **meter 0 V** | anything else: section 3 fallback | section 3 | none if a4 ended clean | +| a6 | Boot undo, drill | **a separate go from the maintainer, after a4's results, and only once a4 has answered section 8 item 4 (does the charger's CHGIN see the phone's own 5 V).** A later boot: run a4 with `--soak 120` and, during the soak, with the meter in and nothing else on the port, force a reset that skips shutdown: the tool's own watchdog path (`husky-deadman-phone` stops feeding when its deadline passes, so `kill -STOP` of the feeder or `echo $(( $(date +%s) ))` into `/run/husky-deadman/deadline`), or `echo b > /proc/sysrq-trigger`. NOT `reboot-to`, `reboot` or `systemctl stop`: those send TERM, the tool traps it and undoes first, so they test the trap, not the boot undo. Watch during the reboot: the meter (5 V is expected to stay until boot-undo runs), and after the boot `husky-deadman-phone dump` for `CHG_DETAILS_00` CHGIN valid and `CHG_DETAILS_01` CHG_DTLS 0..3 with the bootloader's MODE 0x05: that would be the bootloader charging the pack from the phone's own boost in the seconds before boot-undo (with `MODE` 0x05 left by the bootloader, expect exactly that: charging from the boost until boot-undo runs) | the meter reads 0 V after the boot; `journalctl -u husky-deadman-undo` shows it ran with "port cold: 1"; marker and unit gone; the charger details back at the baseline | the meter still at 5 V 60 s after the boot: unplug the meter, section 3 fallback; CHGIN valid or CHG_DTLS charging with the cable out after the boot: stop the stage, record the registers, no further a6 until the self-charging loop is understood (a reset mid-sourcing is then a charging event the bootloader controls) | section 3 | a hot port through one reboot; possibly the bootloader charging from the boost for seconds; one slot B try | + +Record in the pull request: the log lines of a3, a2, a4 (which outcome) and a5, the meter readings before/during/after, the kernel release, and the count of slot B tries left. + +## 7. Attached devices: the kernel path, later + +Not in this pull request, and not from userspace: a `regulator-fixed` on MAX77759 GPIO5 as the TCPC node's `vbus-supply` (never `regulator-boot-on` or `regulator-always-on`), the connector made dual role with `try-power-role = "sink"`, so that TCPM sources only after a sink (Rd) attaches and stops on detach, and `tcpci_maxim` taught to set and clear `EXTBST_CTRL` 0x92 bit 0 around the regulator enable and disable, with the register and bit cited from Google's driver in the same pull request (`tcpci_max77759_vendor_reg.h:91-92`, `tcpci_max77759.c:611-618, 2021-2022`) and a binding for it. The bypass registers of section 5 then belong in the charger driver, through its regmap. That pull request gets its own runbook alongside it (stage (b) with the meter and a 5 Ω test load question still open, then devices). Until then the connector stays sink-only and `b5-host` is the only thing that ever sources. **[verified: [HOST-MODE-PLAN.md](HOST-MODE-PLAN.md) sections 1.1, 2.1, 2.2; L/drivers/usb/typec/tcpm/tcpci_maxim_core.c:210-251 for why `vbus-supply` must not be set before the 0x92 change exists]** + +## 8. Unknowns in one place + +1. Whether 5 V appears without `ext_bst_mode` (s2mpg14 GPIO4): the meter in a4. +2. Whether the MAX33359's 0x70 reading agrees with the meter: a4, both written down. +3. What MODE 0x00 does to CHG_DETAILS with the cable out: a4' or a4c (a4c is the most likely outcome, a4' the other one that reads the MODE-0 details); the guard is then re-derived against the log. +4. Whether CHGIN sees the self-sourced VBUS with `MODE` 0x00 (answered for 0x05: it does): the baseline comparison in a4. +5. Whether 0xcb needs the CHGPROT unlock: the readback in a4. +6. VBUS fall time after the undo: a5, the meter. +7. Whether `basic.target` is late enough for the I2C bus and the gpiochip, and whether libgpiod is on the phone: a1 (`pacman -Q libgpiod`) and a6. +8. Whether `CC_STATUS` reports a partner Rp while this chip sources: not tested in stage (a) (the rule forbids a source on the port); the register is logged every second. +9. Whether GPIO5 and 0x92 keep their values across a SoC reset: a6. +10. Whether `VBUS_VOLTAGE` ever reports a non-zero TCPCI scale factor (bits 11:10) on this chip: the tool treats such a word as unreadable rather than scaling it; a4 shows whether it happens. + +Not in this runbook: the read-only Baseus 500 mA re-run the maintainer asked for on issue #1 (the same meter, a separate note). diff --git a/device/husky/TYPEC-FAST-CHARGE-PLAN.md b/device/husky/TYPEC-FAST-CHARGE-PLAN.md new file mode 100644 index 000000000..2399d050a --- /dev/null +++ b/device/husky/TYPEC-FAST-CHARGE-PLAN.md @@ -0,0 +1,36 @@ + +# Pixel 8 Pro (husky): Type-C and fast charging, plan + +Last updated: 2026-11-02. Written 2026-11-01 from source reading and that day's measurements; stages 0, 3 and 4 have run (results in [BATTERY-NOTES.md](BATTERY-NOTES.md) section 7.2). Claims: **[V]** checked in a file or on the phone, **[I]** inferred, with what settles it. + +## 1. Where things stood before the Type-C step (2026-11-01, kernel `7.3.0-rc6-omamobile-push1-g5899fec2bd28`) + +- Charging works: `max77759_charger` loaded under `tools/husky-deadman` (`b3-charger`, 500 mA), status `Charging`. On a USB-A wall charger with an A-to-C cable, screen off: net battery current +30..+70 mA, voltage rising, 35 C. On the desktop port: about -40..-80 mA. On a 30 W USB-PD charger with a C-to-C cable, screen off: +1.50 A, 4.004 V, 33 C, TCPC `CC_STATUS` 0x1c (CC2 at the 3.0 A level by the TCPCI layout **[I]**), charger input limit 0xc2 still 0x13, 0xbb 0x17 (the "500 mA" reading of 0x13 is not what the chip draws: bit 7 NO_AUTOIBUS is clear, so the charger's own source detection sets the input current; at about 49 mAh per percent, 23 % in 30 min is nearer 2.2 A than a 1.57 A mean, per the maintainer's reading on #282); no Type-C driver loaded. About 49 mAh per percent, so about 1 % per hour on the weak sources. **[V: the charge logs, kept locally]** +- With the USB-A sources the TCPC read `CC_STATUS` 0x11 (default Rp only) and `POWER_STATUS` 0x0c (VBUS present). No TCPM driver ran, so no PD messages were sent or seen. **[V]** +- `tcpci_maxim`: the DT node `usb-typec@25` is complete (sink-only, `pd-disable`, sink PDOs 5 V 3 A / 9 V 2.2 A / PPS) but `status = "disabled"`; the module is built and blocked by the device package. **[V: zuma-husky.dts, the package's modprobe file]** +- The earlier wall-charger run at 900 mA (input register 0x23 on all 180 samples) averaged only +22 mA, so 500 to 900 mA barely changed the battery current: either the phone's own draw takes most of it or the source limits. **[I: an inline meter settles it]** + +## 2. The limiter chain + +There is no single limiter to lift. In order: what the source advertises (CC Rp, or PD) -> the current TCPM hands to the charger -> the input limit register 0xc2 (500 mA = 0x13, 900 mA = 0x23; the driver clamps at 900 mA when TCPM reports 0 because Rp is default) -> the battery current cap (DT 1.485 A, float 4.2 V) -> the PCA9468 direct charger (no driver). A default-Rp source gives no reason to raise 0xc2 by hand. The float, the 1.485 A cap, the temperature table and the PCA9468 are the maintainer's call: keep 4.2 V and 1.485 A, raise nothing before the Type-C step and its temperature guard are reviewed. **[V: the maintainer on issue #1]** + +What "fast" could mean here: default Rp only, no gain; Rp 1.5/3 A, up to the 1.485 A battery cap inside the 1.7 A / 45 C trips; PD fixed 9 V without the direct charger, about 1.485 A at 4.2 V into the pack, about 6 W; stock-style fast charge needs PPS plus a PCA9468 driver that does not exist. + +## 3. Stages + +| # | Stage | Cost | State | +| --- | --- | --- | --- | +| 0 | Read-only 1 Hz log (`i2cget` only, no scans) of TCPC 0x10/0x11/0x1a/0x1d/0x1e/0x2f/0x93 and charger 0xb5-0xb9/0xc2, desktop port then charger. Stop on anything that needs a write. Rollback: unplug | none | done 2026-11-01 (section 1) | +| 1 | Idle-power check: charger loaded, 500 vs 900 mA on the same source, screen off, Wi-Fi on | one reboot between `b3` runs | not done; the inline meter answers it better (HOST-MODE-RUNBOOK section 2) | +| 2 | Wi-Fi-only drill: SSH over Wi-Fi with the USB cable out, replug, the rescue restores the data switch | none | done (BATTERY-NOTES section 8) | +| 3 | Enable the Type-C node, module still blocked: overlay `overlays/typec-test.dtso` sets `usb-typec@25` to `okay`. Pass: `/sys/bus/i2c/devices/-0025` exists with no driver, USB and the rescue fine | one reboot | done 2026-11-01 20:06 (BATTERY-NOTES 7.2) | +| 4 | Load `tcpci_maxim` with `pd-disable` under the dead-man (`b4-tcpm`, the port of cheetah's `b4a-tcpm`): desktop port first, Wi-Fi as the way in, rescue stopped first. Undo: `modprobe -r tcpci_maxim tcpci tcpm`, 0x93 = 0x09 if VBUS is valid, rescue restarted. Stop: a hard reset or contaminant state in the tcpm log, 0x93 not 0x09 with VBUS valid, both links dead, the battery guard | none by itself | done 2026-11-01 20:09, and with the charger loaded 20:21 (BATTERY-NOTES 7.2) | +| 5 | A charger on the Type-C stack: worthwhile only if it shows Rp 1.5/3 A; the input then follows TCPM inside the guard | none | the desktop port already showed 3.0 A and drove 0xc2 to 0x77 (BATTERY-NOTES 7.2); a wall charger not yet | +| 6 | PD on (drop `pd-disable`, fixed 9 V, the PPS APDO removed from the sink list), after the maintainers sign off (9 V into the MAX77759's default input OVP; float stays 4.2 V) | one reboot | not started | +| 7 | Not now: PCA9468, PPS direct charge, any limit above 4.2 V / 1.485 A, `devinfo` or boot-success writes | | each needs the maintainers | + +Host mode (sourcing VBUS) is its own plan: [HOST-MODE-PLAN.md](HOST-MODE-PLAN.md) and [HOST-MODE-RUNBOOK.md](HOST-MODE-RUNBOOK.md). + +## 4. Retry budget + +Every reboot of slot B spends one of its three tries, and at zero the bootloader falls back to slot A (BATTERY-NOTES section 9). Stages 1, 3 and 6 each cost a reboot; re-flash the known-good image set to refill to three before them. diff --git a/device/husky/overlays/typec-test.dtso b/device/husky/overlays/typec-test.dtso new file mode 100644 index 000000000..9a03113e0 --- /dev/null +++ b/device/husky/overlays/typec-test.dtso @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up probe, never default (TYPEC-FAST-CHARGE-PLAN.md stage 3): switches + * on the MAX77759 Type-C port controller node (usb-typec@25 on hsi2c_11), so + * the I2C client 0x25 exists and tcpci_maxim can bind to it. Nothing else + * changes: the bus, USI11 and CMU_PERIC1 come from battery-i2c-test, the + * interrupt (gpa8-3) and its pinctrl are in the board file, and the connector + * keeps pd-disable (sink only, Rp sensing, no PD messages). + * + * The driver stays blacklisted by the husky package (omamobile-max77759.conf) + * until the dead-man step loads it (tools/husky-deadman b4-tcpm): with this + * overlay alone the node is "okay" but unbound, and omamobile-usb-rescue still + * closes the data switch. The node has no label in zuma-husky.dts, so it is + * addressed through its parent bus. + */ +/dts-v1/; +/plugin/; + +&hsi2c_11 { + usb-typec@25 { + status = "okay"; + }; +}; diff --git a/device/husky/overlays/usb-role-test.dtso b/device/husky/overlays/usb-role-test.dtso new file mode 100644 index 000000000..b3ed0783f --- /dev/null +++ b/device/husky/overlays/usb-role-test.dtso @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up probe, never default (HOST-MODE-PLAN.md stage 1): wires the USB + * controller to the Type-C port so TCPM owns the data role. The dwc3 becomes + * OTG with a role switch (default peripheral, so the gadget comes up exactly + * as before), and an OF graph links its port to the connector's port@0 (the + * high-speed lines). No VBUS: there is no vbus-supply, the connector stays + * power-role = "sink" (pd-disable, Rp sensing), and nothing here can source + * power. Host mode is only reachable by hand through + * /sys/class/usb_role/11210000.usb-role-switch/role, over Wi-Fi, with the + * cable out. + * + * Needs typec-test (the usb-typec@25 node is "okay") and battery-i2c-test + * (the bus) applied first. The connector has no label in zuma-husky.dts, so + * it is addressed through its parent bus; both endpoint labels are defined + * here, in the same overlay, so dtc -@ records them as local fixups and + * fdtoverlay resolves the two remote-endpoint phandles when it applies this. + */ +/dts-v1/; +/plugin/; + +&usb_dwc3 { + dr_mode = "otg"; + usb-role-switch; + role-switch-default-mode = "peripheral"; + + port { + usb_dwc3_role: endpoint { + remote-endpoint = <&typec_role>; + }; + }; +}; + +&hsi2c_11 { + usb-typec@25 { + connector { + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + typec_role: endpoint { + remote-endpoint = <&usb_dwc3_role>; + }; + }; + }; + }; + }; +}; diff --git a/tests/all b/tests/all index 0f79edbb2..4b6a8751a 100755 --- a/tests/all +++ b/tests/all @@ -40,7 +40,7 @@ sh -n device/flame/initramfs/build bash -n tools/build-flame-probe echo "ok - scripts parse" python3 tests/bt-uart-gpio.py -for t in tests/pr-check tests/kernel-pr-check tests/phone-smoke tests/alarm-wake-test tests/install-phone tests/build-rootfs tests/rootfs-resolve tests/phone-provision tests/nv-backup tests/initramfs-grow tests/images-layout tests/boot-update-parity tests/stage-boot-files tests/initramfs-reproducible tests/device-overlays tests/simplefb-trigger tests/initramfs-steps tests/storage-guard tests/usb-product tests/boot-method tests/modules-push tests/make-bundle-keys tests/make-bundle tests/release-signing tests/pinned-packages tests/flame-probe packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all packages/omamobile-device-lynx/test/all packages/omamobile-device-panther/test/all tests/local-builds tests/phone-install-package tests/publish-kernel tests/fetch-toolchain tests/release-upload tests/extract-camera-data tests/release tests/lineage-ref tests/repo-publish tests/repo-publish-stage tests/extract-vendor-firmware; do +for t in tests/pr-check tests/kernel-pr-check tests/phone-smoke tests/alarm-wake-test tests/install-phone tests/build-rootfs tests/rootfs-resolve tests/phone-provision tests/nv-backup tests/initramfs-grow tests/images-layout tests/boot-update-parity tests/stage-boot-files tests/initramfs-reproducible tests/device-overlays tests/simplefb-trigger tests/initramfs-steps tests/storage-guard tests/usb-product tests/boot-method tests/modules-push tests/make-bundle-keys tests/make-bundle tests/release-signing tests/pinned-packages tests/flame-probe tests/husky-deadman packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all packages/omamobile-device-lynx/test/all packages/omamobile-device-panther/test/all tests/local-builds tests/phone-install-package tests/publish-kernel tests/fetch-toolchain tests/release-upload tests/extract-camera-data tests/release tests/lineage-ref tests/repo-publish tests/repo-publish-stage tests/extract-vendor-firmware; do echo "# $t" "$t" done diff --git a/tests/husky-deadman b/tests/husky-deadman new file mode 100755 index 000000000..fc867ebd2 --- /dev/null +++ b/tests/husky-deadman @@ -0,0 +1,417 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# tools/husky-deadman-phone's b5-host against stubs, no phone: in a user and +# mount namespace (unshare -Urm) /run, /sys, /proc, /var/lib, /var/log, +# /etc/modprobe.d and /etc/systemd/system are tmpfs with a fake Pixel 8 Pro +# in them, and /usr/local/sbin (first on the tool's own PATH) holds stub +# i2cget/i2cset/gpioset/gpioget/lsmod/systemctl/modprobe/ip. The stubs keep +# a register file and a write log, so the test checks: b5-host refuses +# without --meter, without a baseline, with a partner Rp on CC, with +# --no-watchdog, with a VBUS_VOLTAGE scale factor, with a leftover marker or +# registers-not-restored file; the boot-undo unit (oneshot, conditioned on +# its marker, TimeoutStartSec, RequiresMountsFor) is enabled before the first +# register write and armed through the soak; the soak ends in the undo, which +# restores 0xcb bit 3, 0xc4 and 0xb9 and removes unit and marker; the undo +# also runs when VBUS misses the window and when MODE 0x00 moves the details +# (a4'); 0xcb behind CHGPROT is unlocked and relocked; boot-undo does nothing +# without the marker, finishes the job with it, and with the charger driver +# loaded leaves the port cold and the registers for the person; a partner Rp +# mid-soak trips the undo. The SoC watchdog is a file bound over +# /dev/watchdog0. Skipped where unshare -Urm is refused. +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +fail() { printf 'not ok - %s\n' "$1" >&2; exit 1; } +pass() { printf 'ok - %s\n' "$1"; } + +if [[ -z ${HDT_INSIDE:-} ]]; then + if ! unshare -Urm --propagation private true 2>/dev/null; then + echo "ok - # skip: unshare -Urm not permitted here (tests/husky-deadman needs a user namespace)"; exit 0 + fi + HDT_INSIDE=1 exec unshare -Urm --propagation private "$0" "$@" +fi + +tool=$PWD/tools/husky-deadman-phone +t=$(mktemp -d); trap '[[ -n ${KEEP:-} ]] || rm -rf "$t"' EXIT +export HDT_STATE=$t/state +mkdir -p "$HDT_STATE" + +for m in /run /sys /proc /var/lib /var/log /etc/modprobe.d /etc/systemd/system /usr/local/sbin; do + mount -t tmpfs none "$m" || fail "tmpfs on $m" +done +# the SoC watchdog: a plain file the feeder writes 'k' and 'V' into +[[ -e /dev/watchdog0 ]] || { echo "ok - # skip: no /dev/watchdog0 to bind the fake watchdog over"; exit 0; } +: > "$t/wd"; mount --bind "$t/wd" /dev/watchdog0 || fail "bind over /dev/watchdog0" + +# ---- the fake phone ---- +mkdir -p /proc/device-tree; printf 'google,zuma-husky\0google,zuma\0' > /proc/device-tree/compatible +mkdir -p /proc/sys/kernel/random; echo "boot-1" > /proc/sys/kernel/random/boot_id +mkdir -p /sys/devices/platform/10cb0000.i2c/i2c-3 /sys/bus/i2c/devices +ln -s /sys/devices/platform/10cb0000.i2c/i2c-3 /sys/bus/i2c/devices/i2c-3 +mkdir -p /sys/bus/i2c/devices/3-0025 /sys/bus/i2c/drivers/tcpci_maxim +ln -s /sys/bus/i2c/drivers/tcpci_maxim /sys/bus/i2c/devices/3-0025/driver +p=/sys/class/power_supply/max170xx_battery; mkdir -p $p +echo 4000000 > $p/voltage_now; echo 340 > $p/temp; echo 60 > $p/capacity; echo -150000 > $p/current_now +mkdir -p /sys/class/udc/11210000.dwc3; echo "not attached" > /sys/class/udc/11210000.dwc3/state +mkdir -p /sys/class/net/wlp1s0; echo 1 > /sys/class/net/wlp1s0/carrier +mkdir -p /sys/class/typec/port0; echo "[sink]" > /sys/class/typec/port0/power_role +mkdir -p /sys/class/usb_role/11210000.usb-role-switch; echo device > /sys/class/usb_role/11210000.usb-role-switch/role +mkdir -p /sys/bus/platform/devices/max77759-gpio.2.auto/gpiochip7 +printf 'blacklist max77759_charger\nblacklist tcpci_maxim\n' > /etc/modprobe.d/omamobile-max77759.conf +mkdir -p /run/husky-deadman; touch /run/husky-deadman/b4-done + +# registers: "addr reg value"; VBUS (0x70, word) follows GPIO5 and 0x92 +cat > "$HDT_STATE/regs" <<'EOF' +0x25 0x92 0x00 +0x25 0x1c 0x00 +0x25 0x1d 0x10 +0x25 0x1e 0x00 +0x25 0x1f 0x00 +0x25 0x93 0x09 +0x69 0xb5 0x00 +0x69 0xb6 0xb1 +0x69 0xb7 0x00 +0x69 0xb9 0x05 +0x69 0xbb 0x1d +0x69 0xbd 0x23 +0x69 0xbf 0x00 +0x69 0xc2 0x13 +0x69 0xc4 0x00 +0x69 0xc5 0x6a +0x69 0xcb 0xc0 +EOF +echo 0 > "$HDT_STATE/gpio5" +: > "$HDT_STATE/writes" + +stub() { cat > "/usr/local/sbin/$1"; chmod 755 "/usr/local/sbin/$1"; } +stub i2cget <<'EOF' +#!/bin/bash +# i2cget -f -y BUS ADDR REG [w] +addr=$4 reg=$5 mode=${6:-b} +if [[ $mode == w ]]; then + if [[ $reg == 0x70 ]]; then + v92=$(awk '$1=="0x25" && $2=="0x92" {print $3}' "$HDT_STATE/regs") + [[ -e $HDT_STATE/scale ]] && { echo 0x0432; exit 0; } # scale bits 11:10 set + [[ -e $HDT_STATE/novbus ]] && { echo 0x0000; exit 0; } # the boost gives nothing + [[ $v92 == 0x01 && $(cat "$HDT_STATE/gpio5") == 1 ]] && echo 0x00c8 || echo 0x0000 + else echo 0x0000; fi + exit 0 +fi +[[ $reg == 0xb9 && -e $HDT_STATE/b9-unreadable ]] && exit 1 +awk -v a="$addr" -v r="$reg" '$1==a && $2==r {print $3; f=1} END {exit !f}' "$HDT_STATE/regs" +EOF +stub i2cset <<'EOF' +#!/bin/bash +# i2cset -f -y BUS ADDR REG VALUE +addr=$4 reg=$5 val=$(printf '0x%02x' "$6") +echo "i2cset $addr $reg $val" >> "$HDT_STATE/writes" +[[ $reg == 0xcb && -e $HDT_STATE/cb-stuck ]] && exit 0 # 0xcb never takes a write +# cb-locked: 0xcb takes a write only while CHGPROT (0xbf bits 3:2) is 11 +if [[ $reg == 0xcb && -e $HDT_STATE/cb-locked ]]; then + prot=$(awk '$1=="0x69" && $2=="0xbf" {print $3}' "$HDT_STATE/regs") + (( (prot & 0x0c) == 0x0c )) || exit 0 +fi +awk -v a="$addr" -v r="$reg" -v v="$val" '$1==a && $2==r {$3=v} {print}' "$HDT_STATE/regs" > "$HDT_STATE/regs.new" && mv "$HDT_STATE/regs.new" "$HDT_STATE/regs" +if [[ $reg == 0xb9 && $val == 0x00 && -e $HDT_STATE/mode0-moves ]]; then sed -i 's/^0x69 0xb6 .*/0x69 0xb6 0xb8/' "$HDT_STATE/regs"; fi +if [[ $reg == 0xb9 && $val == 0x05 && -e $HDT_STATE/mode0-moves ]]; then sed -i 's/^0x69 0xb6 .*/0x69 0xb6 0xb1/' "$HDT_STATE/regs"; fi +EOF +stub gpioset <<'EOF' +#!/bin/bash +# gpioset -c CHIP GPIO5=V (libgpiod v2: holds the line until killed) +for a; do [[ $a == GPIO5=* ]] && { echo "${a#GPIO5=}" > "$HDT_STATE/gpio5"; echo "gpioset $a" >> "$HDT_STATE/writes"; }; done +sleep 100 +EOF +stub gpioget <<'EOF' +#!/bin/bash +[[ $1 == --help ]] && { echo " --as-is do not change the line direction"; exit 0; } +v=$(cat "$HDT_STATE/gpio5"); echo "\"GPIO5\"=$([[ $v == 1 ]] && echo active || echo inactive)" +EOF +stub lsmod <<'EOF' +#!/bin/bash +printf 'Module Size Used by\n' +[[ -e $HDT_STATE/no-mfd ]] || printf 'max77759 16384 0\n' +printf 'gpio_max77759 16384 0\ntcpci_maxim 16384 0\ntcpci 16384 1\ntcpm 16384 1\nmax17042_battery 16384 0\n' +[[ -e $HDT_STATE/charger-loaded ]] && echo "max77759_charger 16384 0" +exit 0 +EOF +stub systemctl <<'EOF' +#!/bin/bash +echo "systemctl $*" >> "$HDT_STATE/writes"; exit 0 +EOF +stub modprobe <<'EOF' +#!/bin/bash +echo "modprobe $*" >> "$HDT_STATE/writes" +[[ $1 == max77759 && -e $HDT_STATE/mfd-loads ]] && rm -f "$HDT_STATE/no-mfd" +exit 0 +EOF +stub ip <<'EOF' +#!/bin/bash +echo "2: wlp1s0 inet 192.0.2.10/24 scope global wlp1s0" +EOF + +reg() { awk -v a="$1" -v r="$2" '$1==a && $2==r {print $3}' "$HDT_STATE/regs"; } +D=/run/husky-deadman MARK=/var/lib/husky-deadman/undo-pending UNIT=/etc/systemd/system/husky-deadman-undo.service +LOG=/var/log/husky-deadman.log +result() { cat $D/result 2>/dev/null || echo none; } +run_b5() { # run_b5 [opts]; confirms after 2 s; prints the result + : > "$HDT_STATE/writes" + "$tool" run b5-host --confirm 6 --grace 3 --soak "${SOAK:-3}" "$@" > "$t/run.out" 2>&1 & + local pid=$! + if [[ -z ${NOCONFIRM:-} ]]; then sleep 2; "$tool" confirm > /dev/null; fi + wait $pid || true + result +} + +# ---- 1. refusals ---- +"$tool" run b5-host --device >/dev/null 2>&1 && fail "--device is still accepted" +pass "--device is refused (stage (a) only)" + +r=$(run_b5); [[ $r == "refused: no --meter"* ]] || { cat "$t/run.out"; fail "no --meter refused (got '$r')"; } +[[ ! -s "$HDT_STATE/writes" ]] || fail "a refusal wrote something: $(cat "$HDT_STATE/writes")" +pass "b5-host refuses without --meter, nothing written" + +r=$(run_b5 --meter); [[ $r == "refused: no stable cable-out baseline"* ]] || { cat "$t/run.out"; fail "no baseline refused (got '$r')"; } +[[ ! -s "$HDT_STATE/writes" ]] || fail "a refusal wrote something" +[[ ! -e $UNIT && ! -e $MARK ]] || fail "a refusal installed the undo unit" +pass "b5-host refuses without a baseline of this boot, nothing written, no unit" + +: > "$HDT_STATE/writes" +"$tool" baseline > "$t/base.out" 2>&1 || { cat "$t/base.out"; fail "baseline"; } +[[ ! -s "$HDT_STATE/writes" ]] || fail "baseline wrote: $(cat "$HDT_STATE/writes")" +{ grep -q '^boot boot-1$' $D/baseline && grep -q '^0xb6 0xb1$' $D/baseline; } || { cat $D/baseline; fail "baseline file"; } +pass "baseline is read-only and records 0xb6 0xb1 for this boot" + +sed -i 's/^0x25 0x1d .*/0x25 0x1d 0x11/' "$HDT_STATE/regs" # Rp default on CC1 +r=$(run_b5 --meter); [[ $r == "refused: TCPC CC_STATUS"* ]] || { cat "$t/run.out"; fail "partner Rp refused (got '$r')"; } +[[ ! -s "$HDT_STATE/writes" ]] || fail "a refusal wrote something" +sed -i 's/^0x25 0x1d .*/0x25 0x1d 0x10/' "$HDT_STATE/regs" +pass "b5-host refuses with a partner Rp on CC" + +r=$(run_b5 --meter --no-watchdog); [[ $r == "refused: --no-watchdog is not allowed"* ]] || { cat "$t/run.out"; fail "--no-watchdog refused (got '$r')"; } +[[ ! -s "$HDT_STATE/writes" ]] || fail "a refusal wrote something" +pass "b5-host refuses --no-watchdog" + +touch "$HDT_STATE/scale" +r=$(run_b5 --meter); [[ $r == "refused: TCPC VBUS_VOLTAGE 0x70 unreadable"* ]] || { cat "$t/run.out"; fail "scale bits refused (got '$r')"; } +rm -f "$HDT_STATE/scale" +pass "a VBUS_VOLTAGE word with scale bits 11:10 set counts as unreadable and refuses" + +# ---- 2. a clean run: unit before the first write, armed through the soak, soak ends in the undo ---- +r=$(run_b5 --meter); [[ $r == soaked ]] || { cat "$t/run.out"; tail -30 $LOG; fail "clean run (got '$r')"; } +grep -q 'SOAKED and UNDONE' $LOG || fail "the soak ended in the undo" +# order: enable the unit, then MODE 0, 0xc4, 0xcb bit 3, GPIO5, 0x92; undo: 0x92, GPIO5, 0xcb bit 3 clear, 0xb9 back, disable +seq=$(grep -E '^(i2cset|gpioset|systemctl (enable|disable))' "$HDT_STATE/writes" | tr '\n' ';') +want='systemctl enable --quiet husky-deadman-undo.service;i2cset 0x69 0xb9 0x00;i2cset 0x69 0xc4 0x00;i2cset 0x69 0xcb 0xc8;gpioset GPIO5=1;i2cset 0x25 0x92 0x01;i2cset 0x25 0x92 0x00;gpioset GPIO5=0;i2cset 0x69 0xcb 0xc0;i2cset 0x69 0xb9 0x05;systemctl disable --quiet husky-deadman-undo.service;' +[[ $seq == "$want" ]] || { echo "$seq"; fail "apply then undo order"; } +grep -q 'VBUS up: 5000 mV' $LOG || fail "VBUS read 5000 mV from the stub" +grep -q 'bst_on high for [0-9]* ms before 0x92' $LOG || fail "the bst_on-to-0x92 time is logged" +[[ $(reg 0x69 0xcb) == 0xc0 && $(reg 0x69 0xc4) == 0x00 && $(reg 0x69 0xb9) == 0x05 && $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 ]] || fail "registers after the soak's undo" +[[ ! -e $UNIT && ! -e $MARK ]] || fail "unit or marker left after a clean soak" +{ grep -q 'k' "$t/wd" && grep -q 'V' "$t/wd"; } || fail "the watchdog was fed and closed with the magic character" +pass "clean run: unit enabled before the first write, Google's order, soak ends in the undo, registers back, unit and marker gone, watchdog fed then closed" + +# ---- 3. the unit's content, caught mid-soak ---- +rm -f $D/b5-done; : > "$HDT_STATE/writes" +SOAK=20 "$tool" run b5-host --meter --confirm 6 --grace 3 --soak 20 > "$t/run.out" 2>&1 & +pid=$! +sleep 2; "$tool" confirm > /dev/null; sleep 2 +[[ -e $UNIT && -e $MARK ]] || fail "unit or marker missing during the soak" +grep -q "^ConditionPathExists=$MARK$" $UNIT || { cat $UNIT; fail "unit is conditioned on the marker"; } +grep -q '^ExecStart=/usr/local/bin/husky-deadman-phone boot-undo$' $UNIT || fail "unit runs boot-undo" +{ grep -q '^Type=oneshot$' $UNIT && grep -q '^TimeoutStartSec=180$' $UNIT && grep -q "^RequiresMountsFor=$(dirname $MARK) /usr/local/bin$" $UNIT; } || { cat $UNIT; fail "unit: oneshot, TimeoutStartSec, RequiresMountsFor"; } +{ grep -q '^0xcb 0xc0$' $MARK && grep -q '^0xc4 0x00$' $MARK && grep -q '^0xb9 0x05$' $MARK; } || { cat $MARK; fail "marker carries the saved 0xcb/0xc4/0xb9"; } +[[ $(reg 0x25 0x92) == 0x01 && $(cat "$HDT_STATE/gpio5") == 1 ]] || fail "sourcing during the soak" +pass "mid-soak: unit (oneshot, ConditionPathExists= marker, TimeoutStartSec, RequiresMountsFor) and marker with the saved registers are armed" +# "a reset": the tool dies without a word, the PMIC keeps GPIO5 and 0x92, /run is gone +kill -9 $pid; wait $pid 2>/dev/null || true +pkill -9 -f 'husky-deadman-phone' 2>/dev/null || true; pkill -9 -x gpioset 2>/dev/null || true; sleep 1 +rm -rf $D; echo "boot-2" > /proc/sys/kernel/random/boot_id + +# ---- 4. boot-undo: nothing without the marker (kept aside); the whole job with it ---- +mv $MARK "$t/mark.saved"; : > "$HDT_STATE/writes" +"$tool" boot-undo > "$t/bu.out" 2>&1 || { cat "$t/bu.out"; fail "boot-undo without a marker exits 0"; } +[[ ! -s "$HDT_STATE/writes" ]] || fail "boot-undo without a marker wrote: $(cat "$HDT_STATE/writes")" +pass "boot-undo without the marker does nothing" +mv "$t/mark.saved" $MARK +[[ $(reg 0x25 0x92) == 0x01 && $(cat "$HDT_STATE/gpio5") == 1 && -e $MARK && -e $UNIT ]] || fail "state before boot-undo" +: > "$HDT_STATE/writes" +"$tool" boot-undo > "$t/bu.out" 2>&1 || { cat "$t/bu.out"; fail "boot-undo with the marker"; } +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && $(reg 0x69 0xcb) == 0xc0 && $(reg 0x69 0xb9) == 0x05 ]] || { cat "$HDT_STATE/writes"; fail "boot-undo restored"; } +# MODE read 0x00 (b5-host's own write, or a bootloader that left 0x00: the two cannot be told apart) and the saved value was 0x05: the rule writes it back +grep -q '^i2cset 0x69 0xb9 0x05$' "$HDT_STATE/writes" || fail "boot-undo wrote MODE 0x05 back over a 0x00" +[[ ! -e $UNIT && ! -e $MARK ]] || fail "boot-undo left the unit or marker" +grep -q 'boot-undo: marker from boot boot-1' $LOG || fail "boot-undo names the boot it came from" +pass "boot-undo with the marker: 0x92 off, GPIO5 low, registers back, unit and marker removed" + +# ---- 5. boot-undo with the charger driver loaded: port cold, marker gone, registers left for the person ---- +mkdir -p /run/husky-deadman; touch /run/husky-deadman/b4-done +"$tool" baseline > /dev/null 2>&1 || fail "baseline (boot 2)" +rm -f $D/b5-done +SOAK=20 "$tool" run b5-host --meter --confirm 6 --grace 3 --soak 20 > "$t/run.out" 2>&1 & +pid=$!; sleep 2; "$tool" confirm > /dev/null; sleep 2 +kill -9 $pid; wait $pid 2>/dev/null || true; pkill -9 -f 'husky-deadman-phone' 2>/dev/null || true; pkill -9 -x gpioset 2>/dev/null || true; sleep 1 +rm -rf $D; echo "boot-3" > /proc/sys/kernel/random/boot_id +touch "$HDT_STATE/charger-loaded"; : > "$HDT_STATE/writes" +"$tool" boot-undo > "$t/bu.out" 2>&1 && fail "boot-undo with the charger loaded must report rc 1" +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 ]] || fail "port not cold after boot-undo with the charger loaded" +[[ $(reg 0x69 0xcb) == 0xc8 ]] || fail "0xcb must be left alone with the charger loaded" +grep -q '^i2cset 0x69' "$HDT_STATE/writes" && fail "a charger write with the charger loaded" +[[ ! -e $UNIT && ! -e $MARK ]] || fail "marker or unit kept although the port is cold" +left=$(dirname $MARK)/registers-not-restored +{ [[ -e "$left" ]] && grep -q '^0xcb 0xc0$' "$left"; } || fail "the saved registers are left in $left" +rm -f "$HDT_STATE/charger-loaded" +pass "boot-undo with the charger loaded: port cold, unit and marker removed, charger registers left in registers-not-restored" +mkdir -p /run/husky-deadman; touch /run/husky-deadman/b4-done; "$tool" baseline > /dev/null 2>&1 || fail "baseline (boot 3)" +r=$(run_b5 --meter); [[ $r == "refused: $left exists"* ]] || { cat "$t/run.out"; fail "registers-not-restored refuses (got '$r')"; } +rm -f "$left"; sed -i -e 's/^0x69 0xcb .*/0x69 0xcb 0xc0/' -e 's/^0x69 0xb9 .*/0x69 0xb9 0x05/' "$HDT_STATE/regs" # the person restores them by hand +pass "a leftover registers-not-restored file refuses b5-host" + +# ---- 6. a marker from an unfinished undo blocks the next run ---- +mkdir -p "$(dirname $MARK)"; echo "boot boot-1" > $MARK +r=$(run_b5 --meter); [[ $r == "refused: $MARK exists"* ]] || { cat "$t/run.out"; fail "marker refusal (got '$r')"; } +rm -f $MARK +pass "a leftover marker refuses b5-host" + +# ---- 7. apply failures after GPIO5/0x92 are set: the undo runs ---- +touch "$HDT_STATE/novbus" +r=$(run_b5 --meter); [[ $r == "failed: step b5-host did not apply"* ]] || { cat "$t/run.out"; tail -20 $LOG; fail "no VBUS -> failed (got '$r')"; } +grep -q 'no 5 V from the external boost' $LOG || fail "the no-VBUS reason is logged" +seq=$(grep -E '^(i2cset 0x25|gpioset)' "$HDT_STATE/writes" | tr '\n' ';') +[[ $seq == 'gpioset GPIO5=1;i2cset 0x25 0x92 0x01;i2cset 0x25 0x92 0x00;gpioset GPIO5=0;' ]] || { echo "$seq"; fail "undo after the VBUS miss"; } +[[ $(reg 0x69 0xcb) == 0xc0 && $(reg 0x69 0xb9) == 0x05 && ! -e $UNIT && ! -e $MARK ]] || { echo "cb=$(reg 0x69 0xcb) b9=$(reg 0x69 0xb9) unit=$([[ -e $UNIT ]] && echo y) mark=$([[ -e $MARK ]] && echo y)"; cat "$HDT_STATE/writes"; tail -15 $LOG; fail "state after the VBUS miss"; } +rm -f "$HDT_STATE/novbus"; rm -f $D/b5-done +pass "VBUS missing the window after GPIO5/0x92: the undo runs, registers back, unit and marker removed" + +# ---- 8. a4': MODE 0x00 moves the details: stop before any VBUS ---- +touch "$HDT_STATE/mode0-moves" +r=$(run_b5 --meter); [[ $r == "failed: step b5-host did not apply"* ]] || { cat "$t/run.out"; fail "a4' (got '$r')"; } +grep -q 'MODE 0x00 alone moved CHG_DETAILS off the cable-out baseline: 0xb6 0xb8 vs baseline 0xb1' $LOG || fail "the MODE-0 reading is logged" +seq=$(grep -E '^(i2cset|gpioset)' "$HDT_STATE/writes" | tr '\n' ';') +[[ $seq == 'i2cset 0x69 0xb9 0x00;i2cset 0x25 0x92 0x00;gpioset GPIO5=0;i2cset 0x69 0xb9 0x05;' ]] || { echo "$seq"; fail "a4' writes: MODE 0, then the undo with MODE back, no 0xc4/0xcb/GPIO5 on, no 0x92 on"; } +[[ ! -e $UNIT && ! -e $MARK ]] || fail "unit or marker left after a4'" +rm -f "$HDT_STATE/mode0-moves"; rm -f $D/b5-done +pass "a4': MODE 0x00 moving the details stops the run before GPIO5/0x92 and restores MODE" + +# ---- 9. 0xcb behind CHGPROT: unlock, write, relock ---- +touch "$HDT_STATE/cb-locked" +r=$(run_b5 --meter); [[ $r == soaked ]] || { cat "$t/run.out"; tail -20 $LOG; fail "CHGPROT run (got '$r')"; } +seq=$(grep -E '^i2cset 0x69 (0xcb|0xbf)' "$HDT_STATE/writes" | tr '\n' ';') +want='i2cset 0x69 0xcb 0xc8;i2cset 0x69 0xbf 0x0c;i2cset 0x69 0xcb 0xc8;i2cset 0x69 0xbf 0x00;i2cset 0x69 0xcb 0xc0;i2cset 0x69 0xbf 0x0c;i2cset 0x69 0xcb 0xc0;i2cset 0x69 0xbf 0x00;' +[[ $seq == "$want" ]] || { echo "$seq"; fail "CHGPROT unlock/relock around the 0xcb writes, both ways"; } +[[ $(reg 0x69 0xbf) == 0x00 && $(reg 0x69 0xcb) == 0xc0 ]] || fail "0xbf relocked and 0xcb restored" +rm -f "$HDT_STATE/cb-locked"; rm -f $D/b5-done +pass "0xcb needing CHGPROT: unlocked, written, relocked, on the set and on the clear" + +# ---- 9b. the register restore fails but the port is cold: no reset, registers-not-restored, next run refused ---- +touch "$HDT_STATE/cb-stuck"; : > "$HDT_STATE/writes" +r=$(run_b5 --meter); [[ $r == "failed: step b5-host did not apply"* ]] || { cat "$t/run.out"; tail -20 $LOG; fail "cb-stuck apply (got '$r')"; } +# the apply itself fails at the 0xcb set (readback), so the undo runs with nothing to clear: that is the cold path +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && $(reg 0x69 0xb9) == 0x05 && ! -e $UNIT && ! -e $MARK ]] || fail "cold undo after a 0xcb set failure (MODE back to 0x05)" +grep -q 'resetting' $LOG && fail "a register failure reset the phone" +rm -f "$HDT_STATE/cb-stuck"; rm -f $D/b5-done +pass "0xcb refusing the set: the apply fails, the undo runs, no reset" +# a restore failure after a good run: 0xcb takes the set, then refuses the clear +: > "$HDT_STATE/writes" +"$tool" run b5-host --meter --confirm 6 --grace 3 --soak 4 > "$t/run.out" 2>&1 & +pid=$!; sleep 2; "$tool" confirm > /dev/null; sleep 1; touch "$HDT_STATE/cb-stuck" +wait $pid || true +r=$(result); [[ $r == "soaked: VBUS off, but 0xcb/0xc4/0xb9 were not all restored"* ]] || { cat "$t/run.out"; tail -20 $LOG; fail "cb-stuck at the undo: result must say so (got '$r')"; } +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && $(reg 0x69 0xcb) == 0xc8 && $(reg 0x69 0xb9) == 0x05 ]] || fail "state after the stuck restore" +[[ ! -e $UNIT && ! -e $MARK && -e $left ]] || fail "unit/marker removed and registers-not-restored written" +grep -q 'resetting' $LOG && fail "a register restore failure reset the phone" +grep -q 'port cold, but 0xcb/0xc4/0xb9 were NOT all restored' $LOG || fail "the restore failure is logged" +rm -f "$HDT_STATE/cb-stuck" "$left" $D/b5-done; sed -i 's/^0x69 0xcb .*/0x69 0xcb 0xc0/' "$HDT_STATE/regs" +pass "0xcb refusing the clear after a clean soak: port cold, no reset, saved values left in registers-not-restored" + +# ---- 9c. boot-undo writes back only b5-host's own writes ---- +rm -f $D/b5-done; : > "$HDT_STATE/writes" +"$tool" run b5-host --meter --confirm 6 --grace 3 --soak 20 > "$t/run.out" 2>&1 & +pid=$!; sleep 2; "$tool" confirm > /dev/null; sleep 2 +kill -9 $pid; wait $pid 2>/dev/null || true; pkill -9 -f 'husky-deadman-phone' 2>/dev/null || true; pkill -9 -x gpioset 2>/dev/null || true; sleep 1 +rm -rf $D; echo "boot-4" > /proc/sys/kernel/random/boot_id +# "the bootloader of the new boot" set MODE 0x05 and 0xc4 0x02 itself; 0xcb bit 3 still ours +sed -i -e 's/^0x69 0xb9 .*/0x69 0xb9 0x05/' -e 's/^0x69 0xc4 .*/0x69 0xc4 0x02/' "$HDT_STATE/regs" +: > "$HDT_STATE/writes" +"$tool" boot-undo > "$t/bu.out" 2>&1 || { cat "$t/bu.out"; fail "boot-undo (own writes)"; } +seq=$(grep -E '^i2cset 0x69' "$HDT_STATE/writes" | tr '\n' ';') +[[ $seq == 'i2cset 0x69 0xcb 0xc0;' ]] || { echo "$seq"; fail "boot-undo wrote more than its own 0xcb bit"; } +[[ $(reg 0x69 0xb9) == 0x05 && $(reg 0x69 0xc4) == 0x02 && ! -e $MARK && ! -e $UNIT ]] || fail "boot-undo left the bootloader's MODE and 0xc4 alone" +grep -q 'MODE 0xb9 0x05 (saved 0x05): not our 0x00, left as is' $LOG || fail "the left-alone MODE is logged" +sed -i 's/^0x69 0xc4 .*/0x69 0xc4 0x00/' "$HDT_STATE/regs" # cleanup for the next cases, after the assertions +pass "boot-undo: MODE not 0x00 and a 0xc4 that is not ours stay as the bootloader left them, only the OTG_V_PGM bit is cleared" + +# ---- 9d. boot-undo with the MFD not up: loads it, or keeps the marker ---- +mkdir -p /run/husky-deadman; touch /run/husky-deadman/b4-done; "$tool" baseline > /dev/null 2>&1 || fail "baseline (boot 4)" +rm -f $D/b5-done +"$tool" run b5-host --meter --confirm 6 --grace 3 --soak 20 > "$t/run.out" 2>&1 & +pid=$!; sleep 2; "$tool" confirm > /dev/null; sleep 2 +kill -9 $pid; wait $pid 2>/dev/null || true; pkill -9 -f 'husky-deadman-phone' 2>/dev/null || true; pkill -9 -x gpioset 2>/dev/null || true; sleep 1 +rm -rf $D; echo "boot-5" > /proc/sys/kernel/random/boot_id +touch "$HDT_STATE/no-mfd"; : > "$HDT_STATE/writes" +"$tool" boot-undo > "$t/bu.out" 2>&1 && fail "boot-undo without the MFD must fail" +grep -q '^modprobe max77759$' "$HDT_STATE/writes" || fail "boot-undo tried modprobe max77759" +grep -q '^i2cset' "$HDT_STATE/writes" && fail "boot-undo wrote registers without the MFD" +[[ -e $MARK && -e $UNIT && $(reg 0x25 0x92) == 0x01 ]] || fail "marker kept while the MFD is missing" +pass "boot-undo with max77759 missing: modprobe tried, nothing written, marker kept" +touch "$HDT_STATE/mfd-loads"; : > "$HDT_STATE/writes" +"$tool" boot-undo > "$t/bu.out" 2>&1 || { cat "$t/bu.out"; fail "boot-undo once modprobe max77759 works"; } +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && ! -e $MARK && ! -e $UNIT ]] || fail "boot-undo after loading the MFD" +rm -f "$HDT_STATE/no-mfd" "$HDT_STATE/mfd-loads" +pass "boot-undo loads max77759 itself when it can, then switches the port off" + +# ---- 9e. TERM during the soak: the undo runs, nothing stays hot ---- +mkdir -p /run/husky-deadman; touch /run/husky-deadman/b4-done; "$tool" baseline > /dev/null 2>&1 || fail "baseline (boot 5)" +rm -f $D/b5-done; : > "$HDT_STATE/writes" +"$tool" run b5-host --meter --confirm 6 --grace 3 --soak 20 > "$t/run.out" 2>&1 & +pid=$!; sleep 2; "$tool" confirm > /dev/null; sleep 2 +kill -TERM $pid; wait $pid 2>/dev/null || true +r=$(result); [[ $r == "interrupted: undone on a signal" ]] || { cat "$t/run.out"; tail -20 $LOG; fail "TERM mid-soak (got '$r')"; } +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && $(reg 0x69 0xcb) == 0xc0 && $(reg 0x69 0xb9) == 0x05 && ! -e $MARK && ! -e $UNIT ]] || fail "state after TERM" +grep -q 'V' "$t/wd" || fail "the watchdog was closed after the signal undo" +pkill -9 -f 'husky-deadman-phone' 2>/dev/null || true +rm -f $D/b5-done +pass "TERM during the soak: undo, registers back, unit and marker removed, watchdog closed" + +for sig in INT HUP; do + mkdir -p /run/husky-deadman; touch /run/husky-deadman/b4-done; "$tool" baseline > /dev/null 2>&1 || fail "baseline ($sig)" + rm -f $D/b5-done; : > "$HDT_STATE/writes" + # job control on: a non-interactive shell starts a background job with SIGINT + # ignored, and an ignored signal cannot be trapped (systemd-run does not do that) + set -m; "$tool" run b5-host --meter --confirm 6 --grace 3 --soak 20 > "$t/run.out" 2>&1 & set +m + pid=$!; sleep 2; "$tool" confirm > /dev/null; sleep 2 + kill -$sig $pid; wait $pid 2>/dev/null || true + r=$(result); [[ $r == "interrupted: undone on a signal" ]] || { cat "$t/run.out"; tail -20 $LOG; fail "$sig mid-soak (got '$r')"; } + [[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && $(reg 0x69 0xcb) == 0xc0 && $(reg 0x69 0xb9) == 0x05 && ! -e $MARK && ! -e $UNIT ]] || fail "state after $sig" + pkill -9 -f 'husky-deadman-phone' 2>/dev/null || true + pass "$sig during the soak: undo, registers back, unit and marker removed" +done + +# ---- 9e2. a signal before b5-host saved anything: no saved file, no marker, nothing to put back ---- +rm -f $D/host.saved $MARK $D/b5-done "$left"; sed -i 's/^0x69 0xcb .*/0x69 0xcb 0xc8/' "$HDT_STATE/regs"; : > "$HDT_STATE/writes" +"$tool" undo b5-host --meter > "$t/u.out" 2>&1 || { cat "$t/u.out"; tail -20 $LOG; fail "undo with nothing saved exits 0"; } +grep -qE '^i2cset 0x69 0x(cb|c4|b9) ' "$HDT_STATE/writes" && { cat "$HDT_STATE/writes"; fail "undo with nothing saved wrote a charger register"; } +[[ $(reg 0x69 0xcb) == 0xc8 && ! -e "$left" ]] || fail "0xcb bit 3 (the bootloader's) must stay, and no registers-not-restored" +grep -q 'no saved registers anywhere' $LOG || fail "the nothing-saved case is logged" +sed -i 's/^0x69 0xcb .*/0x69 0xcb 0xc0/' "$HDT_STATE/regs" +pass "a signal before the registers were saved: the undo writes no charger register and leaves 0xcb bit 3 alone" + +# ---- 9f. a register that cannot be read at the restore counts as not restored ---- +rm -f $D/b5-done; : > "$HDT_STATE/writes" +"$tool" run b5-host --meter --confirm 6 --grace 3 --soak 4 > "$t/run.out" 2>&1 & +pid=$!; sleep 2; "$tool" confirm > /dev/null; sleep 1; touch "$HDT_STATE/b9-unreadable" +wait $pid || true +r=$(result); [[ $r == "soaked: VBUS off, but 0xcb/0xc4/0xb9 were not all restored"* ]] || { cat "$t/run.out"; tail -20 $LOG; fail "unreadable 0xb9 at the restore (got '$r')"; } +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && -e "$left" && ! -e $MARK && ! -e $UNIT ]] || fail "state after an unreadable 0xb9" +grep -q 'cannot read 0xb9' $LOG || fail "the unreadable register is logged" +rm -f "$HDT_STATE/b9-unreadable" "$left" $D/b5-done; sed -i 's/^0x69 0xb9 .*/0x69 0xb9 0x05/' "$HDT_STATE/regs" +pass "an unreadable 0xb9 at the restore: port cold, registers-not-restored written, result says so" + +# ---- 10. a source plugged in mid-soak trips the undo ---- +: > "$HDT_STATE/writes" +"$tool" run b5-host --meter --confirm 6 --grace 3 --soak 8 > "$t/run.out" 2>&1 & +pid=$! +sleep 2; "$tool" confirm > /dev/null +sleep 1; sed -i 's/^0x25 0x1d .*/0x25 0x1d 0x13/' "$HDT_STATE/regs" # Rp 3 A on CC1 +wait $pid || true +r=$(result); [[ $r == "tripped: CC_STATUS"* ]] || { cat "$t/run.out"; tail -20 $LOG; fail "CC trip (got '$r')"; } +[[ $(reg 0x25 0x92) == 0x00 && $(cat "$HDT_STATE/gpio5") == 0 && ! -e $MARK && ! -e $UNIT ]] || fail "state after the CC trip" +pass "a partner Rp appearing mid-soak trips the undo, which disarms the unit" diff --git a/tools/husky-deadman b/tools/husky-deadman index 988e1cbf4..4f9abec6e 100755 --- a/tools/husky-deadman +++ b/tools/husky-deadman @@ -15,8 +15,40 @@ # tools/husky-deadman STEP [options] run STEP under the dead-man switch # tools/husky-deadman undo STEP revert a confirmed STEP by hand # tools/husky-deadman log the phone's /var/log/husky-deadman.log +# tools/husky-deadman baseline read-only: the charger's CHG_DETAILS +# with the cable out, kept for this boot +# (b5-host refuses without it) +# tools/husky-deadman boot-undo run the b5-host boot undo by hand (what +# husky-deadman-undo.service runs after +# a reset mid-step) # -# STEP: noop | wd-drill | b3-charger +# STEP: noop | wd-drill | b3-charger | b4-tcpm | b5-host +# b5-host (device/husky/HOST-MODE-RUNBOOK.md stage (a), NOT to be run until +# the maintainer says go) sources 5 V on VBUS from husky's external boost +# with nothing on the port but a passive USB-C meter: charger MODE 0xb9 = +# 0, the bypass registers (0xc4 = 0x00 for 5000 mV, 0xcb bit 3 OTG_V_PGM), +# MAX77759 GPIO5 bst_on high (libgpiod gpioset), 5 ms, TCPC EXTBST_CTRL +# 0x92 = 0x01, 30 ms; all saved first and restored by the undo. Wi-Fi only, +# desktop cable OUT, a 'baseline' and b4-tcpm in the same boot, charger NOT +# loaded, usb-role-test image, --meter (you state that an independent meter +# is on the port and reads 0 V). Soak 30 s unless --soak, and the soak ENDS +# IN THE UNDO (VBUS is never left on without the guard). --no-watchdog is +# refused. Undo: 0x92 = 0, +# GPIO5 low, registers back. A reset does NOT switch the boost off (the +# PMIC keeps GPIO5 and 0x92): the phone installs a oneshot unit that undoes +# it early in the next boot; after a freeze, unplug, force a restart and run +# 'tools/husky-deadman boot-undo' first. No --device: attached devices go +# through the kernel path later (see the runbook). +# b4-tcpm loads tcpci_maxim (Type-C, pd-disable) and may take the USB port +# away, so it must be run over Wi-Fi: OMAMOBILE_SSH_HOST=root@ +# tools/husky-deadman b4-tcpm. It spends +# no boot retry unless the watchdog fires (one of slot B's 3 per reset). +# Two cases: charger-less (max77759_charger not loaded), or AFTER b3-charger +# in the same boot (b3-charger soaked, then b4-tcpm): the charger then follows +# tcpm's current limit (Rp 3 A -> input limit 3 A, battery still capped at +# 1.485 A by the DT) and the b4 undo also undoes b3 (charging ends off). +# The phone refuses b4 if the charger was loaded any other way, or with +# default_ilim_ua 0. b3-charger refuses while a Type-C driver is loaded. # # Options: # --confirm SECS phone waits this long for our confirmation (default 90) @@ -28,6 +60,8 @@ # --no-watchdog phone falls back to a crash (panic=10) instead of the # watchdog if the undo fails too # --no-confirm do not confirm until the phone has undone the step +# --meter b5-host: an independent USB-C meter is on the port and +# reads 0 V now (required; the phone refuses without it) # # Exit codes: 0 confirmed (or undone on purpose with --no-confirm), # 3 undone (no confirmation in time), 4 no answer from the phone, @@ -69,6 +103,10 @@ Physical recovery, in order: battery temperature by hand. 4. Fastboot by hand: force a restart as in 2, then Power + Volume Down until "Fastboot Mode"; flash your known-good image set. + 5. After a reset mid b5-host the port may still be HOT (GPIO5 and 0x92 live + in the PMIC): plug nothing in; the phone's husky-deadman-undo.service + switches it off early in the boot. If it did not run (frozen phone, + forced restart): tools/husky-deadman boot-undo first thing. TXT } @@ -80,18 +118,28 @@ install_phone() { } cmd="${1:-}"; shift || true -step= confirm= grace=60 soak=600 ilim=500000 nowd= noconfirm=0 allowsoc= +step='' confirm='' grace=60 soak='' ilim=500000 nowd='' noconfirm=0 allowsoc='' meter='' case "$cmd" in ''|-h|--help) usage ;; install) install_phone; say "installed /usr/local/bin/husky-deadman-phone"; exit 0 ;; dump) install_phone; phone 'husky-deadman-phone dump'; exit $? ;; log) phone 'cat /var/log/husky-deadman.log'; exit $? ;; + baseline) install_phone; phone 'husky-deadman-phone baseline'; exit $? ;; + boot-undo) install_phone; phone 'husky-deadman-phone boot-undo'; rc=$? + if ((rc)); then warn "the boot undo did not finish: the port may still be hot, plug nothing in; read 'tools/husky-deadman dump' and finish by hand (gpioset GPIO5=0, i2cset -f -y BUS 0x25 0x92 0x00)"; fi + exit $rc ;; undo) install_phone; phone "husky-deadman-phone undo ${1:?STEP}"; rc=$? - if ((rc)); then warn "the undo did not finish cleanly (charger may still be loaded, with charging forced off): reboot the phone"; recovery; fi + # undo b4-tcpm after b3-charger also undoes b3 (charger unloaded, charging off) + if ((rc)); then warn "the undo did not finish cleanly (a module may still be loaded, with charging forced off): reboot the phone"; recovery; fi exit $rc ;; - noop|wd-drill|b3-charger) step="$cmd" ;; + noop|wd-drill|b3-charger|b4-tcpm|b5-host) step="$cmd" ;; *) usage 1 ;; esac +if [[ $step == b4-tcpm || $step == b5-host ]]; then + case "${OMAMOBILE_SSH_HOST:-}" in + ''|*172.16.42.1) die "$step must run over Wi-Fi (the step may take the USB port away): OMAMOBILE_SSH_HOST=root@ $0 $step" ;; + esac +fi while (($#)); do case "$1" in --confirm) confirm="${2:?}"; shift ;; @@ -101,14 +149,25 @@ while (($#)); do --allow-soc) allowsoc=--allow-soc ;; --no-watchdog) nowd=--no-watchdog ;; --no-confirm) noconfirm=1 ;; + --meter) meter=--meter ;; + --device|--no-device) die "$1 is gone: b5-host is stage (a) only (nothing attached); devices go through the kernel path, see device/husky/HOST-MODE-RUNBOOK.md" ;; *) usage 1 ;; esac shift done [[ -n "$confirm" ]] || confirm=90 +if [[ $step == b5-host ]]; then + [[ -n "$soak" ]] || soak=30 + [[ -n "$meter" ]] || die "b5-host needs --meter: an independent USB-C meter on the port, reading 0 V now (the phone refuses without it)" + [[ -z "$nowd" ]] || die "--no-watchdog is not allowed for b5-host (a dead tool must end in a reset, which runs boot-undo)" + warn "b5-host stage (a): the desktop cable must be OUT, nothing on the port but the passive meter (reading 0 V), nothing that can source anywhere near it; a 'baseline' must have been taken in this boot" +else + [[ -z "$meter" ]] || die "--meter only applies to b5-host" +fi +[[ -n "$soak" ]] || soak=600 [[ $ilim =~ ^[0-9]+$ ]] && (( ilim <= 900000 )) || die "--ilim must be a number up to 900000 (the driver clamps there)" -phone true || die "phone not reachable at 172.16.42.1: nothing started" +phone true || die "phone not reachable at ${OMAMOBILE_SSH_HOST:-root@172.16.42.1}: nothing started" install_phone if [[ $step == wd-drill ]]; then warn "wd-drill RESETS the phone and spends one of slot B's three boot tries (at zero the bootloader falls back to slot A, whose first boot wipes userdata; count the boots since your last bin/omamobile flash)" @@ -136,7 +195,7 @@ trap stop_logger EXIT sleep 2 unit="husky-deadman-$step-$stamp" -args="run $step --confirm $confirm --grace $grace --soak $soak --ilim $ilim $nowd $allowsoc" +args="run $step --confirm $confirm --grace $grace --soak $soak --ilim $ilim $nowd $allowsoc $meter" say "starting $step on the phone, detached (unit $unit): husky-deadman-phone $args" phone "if command -v systemd-run >/dev/null; then systemd-run --quiet --collect --unit=$unit /usr/local/bin/husky-deadman-phone $args @@ -161,13 +220,13 @@ while (( $(date +%s) < deadline )); do fi fi result=$(phone 'cat /run/husky-deadman/result 2>/dev/null' 2>/dev/null) - case "$result" in soaked|reverted|reset|refused*|failed*|tripped*|drill) break ;; esac + case "$result" in soaked*|reverted|reset|refused*|failed*|tripped*|drill) break ;; esac if [[ $result == confirmed ]]; then (( ++polls % 10 == 1 )) && { echo; say "soaking, guard: $(phone 'cat /run/husky-deadman/guard.last 2>/dev/null' 2>/dev/null)"; } fi else if [[ $step == wd-drill ]]; then result=drill; break; fi - ((dropped)) || { echo; warn "link down (not expected for these steps); waiting"; } + ((dropped)) || { echo; warn "link down (not expected for these steps over Wi-Fi; b4-tcpm over USB would, which is why it refuses USB); waiting"; } dropped=1 fi printf '.' @@ -177,10 +236,15 @@ echo rc=1 case "$result" in - soaked) + soaked*) rc=0 - say "step $step CONFIRMED and the soak finished clean; it stays applied. NOTHING guards it now (no watchdog, no guard): read the dump, then 'tools/husky-deadman undo $step' or watch the gauge by hand; reboot before another b3-charger. State:" - phone 'husky-deadman-phone dump; dmesg | grep -iE "max77759|max17042|charger|guard" | tail -25' + [[ $result == soaked:* ]] && warn "the phone says: ${result#soaked: } (the port is off; restore those registers by hand and remove that file before the next b5-host)" + if [[ $step == b5-host ]]; then + say "step b5-host CONFIRMED, soaked clean and UNDONE by the phone (stage (a) ends in the undo): the meter must read 0 V now, 0x92 0x00, gpio5 0, no marker. State:" + else + say "step $step CONFIRMED and the soak finished clean; it stays applied. NOTHING guards it now (no watchdog, no guard): read the dump, then 'tools/husky-deadman undo $step' or watch the gauge by hand; reboot before another $step. State:" + fi + phone 'husky-deadman-phone dump; dmesg | grep -iE "max77759|max17042|charger|guard|tcpci|tcpm|typec|xhci|usb [0-9]" | tail -30' ;; confirmed) rc=4 diff --git a/tools/husky-deadman-phone b/tools/husky-deadman-phone index 49530c3be..10b1df511 100755 --- a/tools/husky-deadman-phone +++ b/tools/husky-deadman-phone @@ -3,9 +3,10 @@ # # husky-deadman-phone: the phone half of tools/husky-deadman. Runs ONE charger # bring-up step on the Pixel 8 Pro detached from SSH, under a dead-man switch -# and a battery guard. Ported from tools/usbc-deadman-phone (cheetah); the -# Type-C / USB data-switch parts are left out on purpose: on husky the USB -# gadget is built in and nothing here loads tcpci_maxim (that is M6). +# and a battery guard. Ported from tools/usbc-deadman-phone (cheetah). The +# Type-C step (b4-tcpm, TYPEC-FAST-CHARGE-PLAN.md stage 4) is the port of +# cheetah's b4a-tcpm: it may take the USB port away, so Wi-Fi (wlp1s0) is the +# way in and the only precondition on the link. # # 1. refuse unless the preconditions hold (nothing is applied if not); # 2. arm the SoC watchdog (/dev/watchdog0 = 10060000.watchdog) with a feeder @@ -26,30 +27,129 @@ # # Usage (normally started by tools/husky-deadman): # husky-deadman-phone run STEP [--confirm S] [--grace S] [--ilim UA] [--soak S] -# [--no-watchdog] [--allow-soc] +# [--no-watchdog] [--allow-soc] [--meter] # husky-deadman-phone confirm | undo STEP | dump | status +# husky-deadman-phone baseline read-only: CHG_DETAILS_00/01/02 with the +# cable out, 5 reads, kept for this boot +# husky-deadman-phone boot-undo what husky-deadman-undo.service runs at +# the boot after a reset mid b5-host # -# STEP: noop | b3-charger | wd-drill +# STEP: noop | b3-charger | b4-tcpm | b5-host | wd-drill # noop applies nothing; exercises refuse/confirm/watchdog/undo. # wd-drill applies nothing and stops feeding the watchdog: the phone MUST # reset by itself within ~15-20 s. Needs the user present. # b3-charger modprobe max77759_charger default_ilim_ua=UA temp_guard=1 # guard_psy=max170xx_battery. +# b4-tcpm stop omamobile-usb-rescue, modprobe tcpci_maxim (pulls tcpci +# and tcpm; the DT keeps pd-disable: Rp sensing only, no PD). +# Needs Wi-Fi up, the Type-C node enabled (typec-test overlay) +# and unbound. Spends no boot retry by itself: only a watchdog +# reset does (one of slot B's 3). Two cases, see preflight_tcpm: +# charger-less (max77759_charger not loaded: tcpm only reports), +# or AFTER b3-charger in the same boot (b3-done present and +# default_ilim_ua > 0): the charger then follows the tcpm psy +# (online + current_max -> input limit 0xc2, offline -> mode OFF) +# and the guard logs tcpm/charger/battery every 10 s. +# Undo: modprobe -r tcpci_maxim tcpci tcpm, USBSW_CTRL 0x93 = +# 0x09 if VBUS is valid, start omamobile-usb-rescue; then, if the +# charger was loaded by b3-charger, the b3 undo too (modprobe -r +# max77759_charger, restore the limits, mode 0x4 = charging off), +# so nothing is left unguarded. Either unload failing -> reset. +# b5-host HOST-MODE-RUNBOOK.md stage (a), NOTHING ATTACHED but a passive +# USB-C meter: source 5 V on VBUS from husky's EXTERNAL boost in +# Google's order (kernel/google-modules/bms, branch +# android-gs-shusky-6.1-android16, max77759_usecase.c: +# gs101_standby_to_otg -> gs101_otg_enable default branch, the +# one stock husky's max77759,ext-otg-only takes): +# 1. charger MODE 0xb9 = 0x00 (Google's "mode=0x0 in MW" for +# this use case; gs101_otg_mode returns early). Then the +# CHG_DETAILS are compared with the cable-out baseline: +# a change STOPS the run before any VBUS (item 4 below). +# 2. gs101_otg_bypass_enable: CHG_CNFG_11 0xc4 = 0x00 (OTG_VBYP +# code for 5000 mV: stock husky has no max77759,usb-otg-mv, +# so GS101_OTG_DEFAULT_MV 5000 -> (5000-5000)/50 = 0), then +# CHG_CNFG_18 0xcb bit 3 OTG_V_PGM set (read-modify-write +# of that bit only; CHGPROT 0xbf unlocked and relocked only +# if the readback fails). +# 3. gs101_ext_mode(OTG_5_0V): MAX77759 GPIO5 "bst_on" high +# (gpio-max77759 line "GPIO5", libgpiod gpioset), 5 ms. +# 4. gs101_ls_mode(1): load switch LSW1 = TCPC vendor register +# EXTBST_CTRL 0x92 = 0x01 (whole byte), 30 ms, VBUS expected. +# gs101_ext_bst_mode (s2mpg14 GPIO4) is not done. Needs: Wi-Fi, +# a 'baseline' taken in this boot, b4-tcpm applied in this boot +# (tcpci_maxim bound, TCPM enabled the TCPC's VBUS monitor), the +# usb-role-test overlay (dwc3 role file, reads device), +# max77759_charger NOT loaded, the desktop cable OUT, CC_STATUS +# showing no partner Rp, 0x92 == 0, GPIO5 low, TCPC VBUS < 0.8 V, +# no undo marker from an earlier boot, libgpiod, and --meter: the +# operator's statement that an independent USB-C meter is on the +# port and read 0 V (the TCPC's 0x70 is the chip we drive, not +# an independent check). Guard, once a second: battery (as b3), +# VBUS outside 4.5..5.5 V (collapse below 4.0 V = short or +# overload; the 1 s poll is the ONLY overcurrent detection), +# battery discharge jump > 1 A over the pre-step value (a short), +# CC_STATUS 0x1d showing a source's Rp (something that can +# source got plugged in: undo at once), CHG_DETAILS_00/01/02 +# leaving the baseline in their known fields, 0x92 changed under +# us, FAULT_STATUS 0x1f (logged only: no VBUS OCP bit is known), +# Wi-Fi dead. Undo, reverse order: 0x92 = 0x00, 20 ms, GPIO5 +# low, readbacks, VBUS must fall below 0.8 V within 3 s (logged, +# not fatal), then 0xcb bit 3, 0xc4 and 0xb9 back to the saved +# values, but only where they still read as this step's own +# write (gs101_otg_bypass_disable clears the bit); the undo's +# return value is the PORT COLD (0x92 and GPIO5 read 0), a +# failed register restore goes to registers-not-restored and +# refuses the next run, it never resets the phone. The soak +# ENDS IN THE UNDO: VBUS is never left on without the guard. +# --no-watchdog is refused (a dead tool must end in a reset, +# which runs boot-undo). One b5 per +# boot. Attached devices (--device) are NOT in this tool: dwc3 +# stays in device role, nothing can enumerate; they go through +# the kernel path (regulator-fixed vbus-supply, TCPM) later. +# GPIO5 and 0x92 live in the PMIC and survive a SoC reset, so +# before its first write b5-host installs husky-deadman-undo +# .service (oneshot, ConditionPathExists= a marker in /var/lib) +# that runs boot-undo early in the NEXT boot and then removes +# itself; a clean undo removes it in this boot. TERM, INT and +# HUP (systemctl stop, a reboot) run the undo first. If the +# phone freezes nothing runs: unplug, force a restart, +# 'boot-undo'. # -# The only charger writes are in restore_charger (the undo path). +# The charger writes are in restore_charger (the b3 undo path) and in b5-host +# (0xb9, 0xc4, 0xcb bit 3, 0xbf only on a failed 0xcb readback, all saved +# first and written back by the undo); the TCPC writes are USBSW_CTRL 0x93 = +# 0x09 in the b4 undo path and EXTBST_CTRL 0x92 = 0x01 / 0x00 in b5-host. set -u PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin D=/run/husky-deadman LOG=/var/log/husky-deadman.log -CHG=0x69 +CHG=0x69 TCPC=0x25 PSY=/sys/class/power_supply/max170xx_battery WD=/dev/watchdog0 -confirm_s=90 grace_s=60 ilim=500000 use_wd=1 soak_s=600 allow_soc=0 +WIFI=wlp1s0 +RESCUE=omamobile-usb-rescue.service +confirm_s=90 grace_s=60 ilim=500000 use_wd=1 soak_s=600 allow_soc=0 meter=0 gpid= +REGS_LEFT=0 # set by the b5-host undo when the port is cold but a register restore failed +# b5-host: TCPC VBUS_VOLTAGE (mV) window while sourcing, the collapse level +# (short/overload), the most VBUS allowed before the step (nothing sourcing), +# and the discharge jump over the pre-step value that trips (a short). +VB_MIN=4500 VB_MAX=5500 VB_COLLAPSE=4000 VB_IDLE_MAX=800 I_JUMP=1000000 +ROLE=/sys/class/usb_role/11210000.usb-role-switch/role +# b5-host: the cable-out baseline of this boot (read-only 'baseline' command), +# the boot-undo marker (persistent: /run is gone after a reset) and its unit. +BASE=$D/baseline BASE_N=5 +MARK=/var/lib/husky-deadman/undo-pending +UNDO_UNIT=/etc/systemd/system/husky-deadman-undo.service +# OTG_VBYP code for 5000 mV (Google: max77759_otg_vbyp_mv_to_code, (mV-5000)/50) +VBYP_5000=0x00 # Guard limits (uV, uA, 0.1 C). The DT caps the float voltage at 4.2 V. V_TRIP=4300000 V_MIN=3000000 I_TRIP=1700000 T_MAX=450 T_MIN=50 +# b4-tcpm guard: consecutive 2 s reads (so 6 s) of USBSW_CTRL != 0x09 while +# VBUS is valid, or of both links dead, before the trip +SW_BAD_N=3 # Preconditions SOC_MIN=30 SOC_MAX=80 START_V_MAX=4150000 START_T_MIN=100 START_T_MAX=400 ILIM_MAX=900000 @@ -76,13 +176,325 @@ hexok() { [[ ${1:-} =~ ^0x[0-9a-fA-F]{1,2}$ ]]; } psy() { cat "$PSY/$1" 2>/dev/null; } # psy FILE udc_state() { cat /sys/class/udc/*/state 2>/dev/null || echo none; } charger_loaded() { lsmod | grep -q '^max77759_charger '; } +tcpc_loaded() { lsmod | grep -qE '^(tcpci_maxim|tcpci|tcpm) '; } +# usb0 keeps its carrier after an unplug, so the gadget state is the link test +usb_up() { [[ $(udc_state) == configured ]]; } +wifi_up() { + [[ $(cat /sys/class/net/$WIFI/carrier 2>/dev/null) == 1 ]] && + ip -4 -o addr show dev $WIFI 2>/dev/null | grep -q ' inet ' +} +# VBUS as the charger sees it: CHG_DETAILS_00.CHGIN_DTLS (bits 6:5) == 3 +vbus_valid() { + local v + v=$(rd $CHG 0xb5); hexok "$v" || return 1 + (( ((v >> 5) & 3) == 3 )) +} + +# ---- Type-C (b4-tcpm) ---- +# The I2C client of usb-typec@25 (needs the typec-test overlay), the tcpm +# debugfs log and the power supply tcpm registers for it (tcpm.c names them +# after the device: tcpm-source-psy--0025). +tcpc_dev() { echo "/sys/bus/i2c/devices/$BUS-0025"; } +tcpm_log() { echo "/sys/kernel/debug/usb/tcpm-$BUS-0025/log"; } +tcpm_psy() { echo "/sys/class/power_supply/tcpm-source-psy-$BUS-0025"; } +# tcpm logs "Received hard reset" but also the states HARD_RESET_SEND/_START, +# SNK_HARD_RESET_* (a VBUS dip during discovery) and CHECK_CONTAMINANT: all stop the step. +TCPM_BAD_RE='hard[ _]reset|contaminant' +tcpm_hard_resets() { local n; n=$(grep -ciE "$TCPM_BAD_RE" "$(tcpm_log)" 2>/dev/null); echo "${n:-0}"; } +rescue_active() { systemctl is-active --quiet $RESCUE; } + +# The MAX77759 opens its USB2 data switch (TCPC vendor USBSW_CTRL 0x93) on +# unplug and only a Type-C driver or the rescue service closes it; 0x09 +# connects D+/D-. Written only after the driver is gone, and only with VBUS. +usbsw_restore() { + local sw + if vbus_valid; then + sw=$(rd $TCPC 0x93) + log "VBUS valid, USBSW_CTRL was $sw" + [[ $sw == 0x09 ]] || wr $TCPC 0x93 0x09 + log "USBSW_CTRL now $(rd $TCPC 0x93) (0x09 = data connected)" + else + log "no valid VBUS (CHG_DETAILS_00 $(rd $CHG 0xb5)): USBSW_CTRL left as is" + fi +} + +# ---- host mode (b5-host) ---- +# TCPC VBUS_VOLTAGE 0x70/0x71: 10 bits, 25 mV per LSB (include/linux/usb/ +# tcpci.h:159-161); Google reads it on this chip (tcpci_max77759.c:1426). +# SMBus word reads are little-endian, so "w" gives the 16-bit value directly. +# Valid only while POWER_CTRL 0x1c bit 6 (VBUS voltage monitor disable) is 0; +# tcpci_maxim writes POWER_CTRL = 0 at init (tcpci_maxim_core.c:111-116). +# Bits 11:10 are the TCPCI scale factor (x1, x2, x4; the TCPCI spec, not in +# tcpci.h, which masks them off). A non-zero scale would under-read by 2 or +# 4, so the reading counts as unreadable (-1) rather than guessed. +vbus_mv() { + local w + w=$(i2cget -f -y "$BUS" $TCPC 0x70 w 2>/dev/null) + [[ $w =~ ^0x[0-9a-fA-F]{1,4}$ ]] || { echo -1; return 1; } + (( (w & 0xc00) == 0 )) || { echo -1; return 1; } + echo $(( (w & 0x3ff) * 25 )) +} +vbus_mon_on() { local p; p=$(rd $TCPC 0x1c); hexok "$p" && (( (p & 0x40) == 0 )); } +# POWER_STATUS 0x1e bits: 4 SOURCING_VBUS, 3 VBUS_DET, 2 VBUS_PRES, 0 SINKING_VBUS (tcpci.h:96-103) +pwr_status() { rd $TCPC 0x1e; } +extbst() { rd $TCPC 0x92; } +# The charger's detail registers and the fields mainline names in them +# (include/linux/mfd/max77759.h:83-89): CHG_DETAILS_00 0xb5 CHGIN_DTLS bits +# 6:5, CHG_DETAILS_01 0xb6 BAT_DTLS bits 6:4 and CHG_DTLS bits 3:0 (0..3 = +# prequal/CC/CV/top-off, 8 = off), CHG_DETAILS_02 0xb7 CHGIN_STS bit 5. The +# other bits are not named there and are logged, never compared. +DETAILS="0xb5 0xb6 0xb7" +det_mask() { case $1 in 0xb5) echo 0x60 ;; 0xb6) echo 0x7f ;; 0xb7) echo 0x20 ;; esac; } +boot_id() { cat /proc/sys/kernel/random/boot_id 2>/dev/null || echo unknown; } +base_val() { awk -v r="$1" '$1 == r && $2 != "unstable" {print $2}' $BASE 2>/dev/null; } +base_ok() { # a baseline from THIS boot, every register stable + [[ -f $BASE ]] && [[ $(awk '$1 == "boot" {print $2}' $BASE) == "$(boot_id)" ]] && + ! grep -q unstable $BASE +} +# Prints nothing while every named field still reads as in the baseline, +# else what moved. Derek (PR review): a guard tripping on an absolute value +# (0xb1 was in every dump of the day) says nothing; compare with the baseline. +chg_vs_baseline() { + local r m b v out= + for r in $DETAILS; do + m=$(det_mask "$r"); b=$(base_val "$r"); v=$(rd $CHG "$r") + if ! hexok "$b" || ! hexok "$v"; then out+="$r unreadable (now '$v', baseline '$b'); " + elif (( (v & m) != (b & m) )); then out+="$r $v vs baseline $b (fields $m); " + fi + done + echo "$out" +} +# Read-only. 5 reads of the details a second apart with the cable out, kept +# in $BASE for this boot (boot_id). No write anywhere. +baseline() { + local n r v rc=0 + [[ -n "$BUS" ]] || { echo "refused: no i2c bus for 10cb0000.i2c"; return 1; } + [[ $(udc_state) != configured ]] || { echo "refused: USB gadget is configured, the cable is in"; return 1; } + vbus_valid && { echo "refused: charger CHG_DETAILS_00 $(rd $CHG 0xb5) says CHGIN valid: a cable is in"; return 1; } + wifi_up || { echo "refused: Wi-Fi is not up (the baseline is for the Wi-Fi-only b5-host)"; return 1; } + charger_loaded && { echo "refused: max77759_charger is loaded; b5-host runs charger-less, so must the baseline"; return 1; } + mkdir -p $D; rm -f $BASE $BASE.reads + for n in $(seq 1 $BASE_N); do + for r in $DETAILS; do v=$(rd $CHG "$r"); hexok "$v" || v='?'; echo "$r $v" >> $BASE.reads; done + (( n < BASE_N )) && sleep 1 + done + { + echo "boot $(boot_id)"; echo "taken $(date '+%F %T')"; echo "mode $(rd $CHG 0xb9)"; echo "udc $(udc_state)" + for r in $DETAILS; do + v=$(awk -v r="$r" '$1 == r {print $2}' $BASE.reads | sort -u | tr '\n' ' ') + if [[ $v =~ ^0x[0-9a-fA-F]{2}\ $ ]]; then echo "$r ${v% }"; else echo "$r unstable $v"; rc=1; fi + done + } > $BASE.tmp + mv $BASE.tmp $BASE; rm -f $BASE.reads + log "baseline (read-only, cable out, charger-less, $BASE_N reads): $(tr '\n' ';' < $BASE)" + (( rc )) && log "baseline has an unstable register: b5-host will refuse until a stable one is taken" + return $rc +} + +# CC_STATUS 0x1d (include/linux/usb/tcpci.h:87-93): bit 5 TOGGLING (result +# not valid), bit 4 TERM (1 = this port presents Rd, as a sink does), bits +# 3:2 CC2 and 1:0 CC1. With Rd presented, 1/2/3 = the partner's Rp default / +# 1.5 A / 3 A, 0 = open (tcpci_to_typec_cc, tcpci.h:246-261, as tcpci.c's +# tcpci_get_cc decodes it). Prints nothing when both CCs are open, "?" when +# unreadable or toggling, else what is seen. A partner Rp is a SOURCE on the +# port: with our VBUS on that is two sources back to back. +cc_partner() { + local c c1 c2 out= + c=$(rd $TCPC 0x1d); hexok "$c" || { echo "?"; return; } + (( c & 0x20 )) && { echo "?"; return; } + (( (c & 0x10) == 0 )) && { echo "term=Rp($c)"; return; } + c1=$(( c & 0x3 )); c2=$(( (c >> 2) & 0x3 )) + (( c1 )) && out+="cc1=Rp$c1 " + (( c2 )) && out+="cc2=Rp$c2 " + echo "${out% }" +} + +# CHG_CNFG_18 0xcb bit 3 OTG_V_PGM (Google's max77759_A1_regs.h and +# max77759_v0p65_121919_regs.h, both (0x1 << 3); mainline's header names only +# WDTEN bit 0 there). Read-modify-write of that bit only. Whether 0xcb takes +# the write without the CHGPROT unlock (0xbf bits 3:2 = 11, mainline +# unlock_prot_regs, max77759_charger.c:145-149) is not known: the readback +# decides, and 0xbf goes back to what it was. +otg_v_pgm() { # otg_v_pgm 1|0 + local cur new p0 + cur=$(rd $CHG 0xcb); hexok "$cur" || { log "cannot read CHG_CNFG_18 0xcb (got '$cur')"; return 1; } + new=$(printf '0x%02x' $(( $1 ? (cur | 0x08) : (cur & 0xf7) ))) + [[ $new == "$cur" ]] && { log "CHG_CNFG_18 0xcb already $cur (OTG_V_PGM=$1)"; return 0; } + wr $CHG 0xcb "$new" || return 1 + [[ $(rd $CHG 0xcb) == "$new" ]] && return 0 + p0=$(rd $CHG 0xbf); hexok "$p0" || { log "0xcb readback failed and CHGPROT 0xbf unreadable"; return 1; } + log "0xcb readback $(rd $CHG 0xcb), not $new: CHGPROT unlock (0xbf $p0 -> bits 3:2 set), retry, relock to $p0" + wr $CHG 0xbf "$(printf '0x%02x' $(( p0 | 0x0c )))" || return 1 + wr $CHG 0xcb "$new" + wr $CHG 0xbf "$p0" + [[ $(rd $CHG 0xcb) == "$new" ]] || { log "0xcb still $(rd $CHG 0xcb) after the unlock"; return 1; } +} +# restore_own_writes FILE: put back only what still reads as b5-host's own +# write, from FILE's saved values: MODE 0xb9 only if it reads 0x00 now; 0xcb +# bit 3 only if it was clear before and reads set now; 0xc4 only if it was +# different before and reads 0x00 now. Anything else was written by someone +# else since (the bootloader of a new boot, a driver) and stays, logged. +# Returns 1 when a write it had to make failed or a saved value is missing. +restore_own_writes() { + local s cur rc=0 + s=$(awk '$1 == "0xcb" {print $2}' "$1"); cur=$(rd $CHG 0xcb) + if ! hexok "$s"; then log "no saved 0xcb in $1"; rc=1 + elif ! hexok "$cur"; then log "cannot read 0xcb"; rc=1 + elif (( (s & 0x08) == 0 && (cur & 0x08) != 0 )); then otg_v_pgm 0 || rc=1 + else log "0xcb $cur (saved $s): bit 3 not ours to clear, left as is"; fi + s=$(awk '$1 == "0xc4" {print $2}' "$1"); cur=$(rd $CHG 0xc4) + if ! hexok "$s"; then log "no saved 0xc4 in $1"; rc=1 + elif ! hexok "$cur"; then log "cannot read 0xc4"; rc=1 + elif [[ $s != "$VBYP_5000" && $cur == "$VBYP_5000" ]]; then wr $CHG 0xc4 "$s" || rc=1 + else log "0xc4 $cur (saved $s): not our write to undo, left as is"; fi + s=$(awk '$1 == "0xb9" {print $2}' "$1"); cur=$(rd $CHG 0xb9) + if ! hexok "$s"; then log "no saved 0xb9 in $1"; rc=1 + elif ! hexok "$cur"; then log "cannot read 0xb9"; rc=1 + elif [[ $cur == 0x00 && $s != 0x00 ]]; then log "restoring charger MODE 0xb9 to the saved $s"; wr $CHG 0xb9 "$s" || rc=1 + else log "MODE 0xb9 $cur (saved $s): not our 0x00, left as is"; fi + log "bypass/mode now vs saved: 0xc4 $(rd $CHG 0xc4) / $(awk '$1 == "0xc4" {print $2}' "$1"), 0xcb $(rd $CHG 0xcb) / $(awk '$1 == "0xcb" {print $2}' "$1"), 0xb9 $(rd $CHG 0xb9) / $(awk '$1 == "0xb9" {print $2}' "$1")" + return $rc +} + +# GPIO5 and 0x92 keep their values across a SoC reset (they live in the +# PMIC), so a crash mid-step leaves the port hot through the reboot. Before +# its first write b5-host installs a oneshot unit for the NEXT boot, gated on +# a persistent marker that also carries the saved registers; a clean undo +# removes both in this boot, boot-undo removes both after it ran. Without the +# marker the unit's ConditionPathExists= skips it, and boot-undo itself exits +# at once, so a normal boot never runs it. +undo_unit_install() { + # the unit first, the marker last: a failure here leaves no marker behind + mkdir -p "$(dirname $MARK)" || return 1 + cat > $UNDO_UNIT </dev/null + return 1 + fi + if ! { echo "boot $(boot_id)"; echo "installed $(date '+%F %T')"; cat $D/host.saved; } > $MARK.tmp || ! mv $MARK.tmp $MARK; then + log "cannot write $MARK: unit disabled and removed again" + rm -f $MARK.tmp; undo_unit_remove + return 1 + fi + sync + log "boot undo armed: $UNDO_UNIT runs boot-undo at the next boot while $MARK exists" +} +undo_unit_remove() { + rm -f $MARK + systemctl disable --quiet husky-deadman-undo.service 2>/dev/null + rm -f $UNDO_UNIT + systemctl daemon-reload 2>/dev/null + sync + log "boot undo disarmed: $MARK and $UNDO_UNIT removed" +} +boot_undo() { + local i rc=0 + [[ -f $MARK ]] || { log "boot-undo: no $MARK, nothing to do"; return 0; } + log "boot-undo: marker from boot $(awk '$1 == "boot" {print $2}' $MARK) (installed $(awk '$1 == "installed" {print $2, $3}' $MARK)), now boot $(boot_id): switching the external boost off" + for i in $(seq 1 30); do BUS=$(i2c_bus) && [[ -n $BUS ]] && break; sleep 2; done + [[ -n "$BUS" ]] || { log "boot-undo: no i2c bus after 60 s: marker kept, undo by hand"; return 1; } + # the MFD first (its blocklist is blacklist lines, an explicit modprobe + # loads it), then its GPIO cell's driver; both bounded, the marker stays + # if either never shows up + lsmod | grep -q '^max77759 ' || { log "boot-undo: modprobe max77759 (MFD not up yet)"; modprobe max77759 2>/dev/null; } + for i in $(seq 1 10); do lsmod | grep -q '^max77759 ' && break; sleep 1; done + lsmod | grep -q '^max77759 ' || { log "boot-undo: max77759 (MFD) is not loaded after 10 s: marker kept, undo by hand"; return 1; } + gpio_chip >/dev/null || modprobe gpio_max77759 2>/dev/null + for i in $(seq 1 10); do gpio_chip >/dev/null && break; sleep 1; done + log "boot-undo: before: 0x92 $(extbst), gpio5 $(command -v gpioget >/dev/null && gpio5_get || echo 'no gpioget'), 0xb9 $(rd $CHG 0xb9), 0xc4 $(rd $CHG 0xc4), 0xcb $(rd $CHG 0xcb), POWER_STATUS $(pwr_status), VBUS $(vbus_mv) mV$(vbus_mon_on || echo ' (monitor off: not valid)'), CC $(cc_partner)" + tcpc_loaded && log "boot-undo: WARNING a Type-C driver is loaded at boot (it is blocked, not expected); 0x92 is written anyway, mainline never touches it" + # Two outcomes kept apart: the port COLD (0x92 reads 0x00 and GPIO5 reads + # 0: the marker's job is done, it goes) and the charger registers restored + # (if not, they are left for the person in $LEFT, the marker does not stay + # for them, or the unit would fire at every boot for registers it cannot + # write, e.g. with the charger driver loaded). + local cold=1 LEFT + LEFT="$(dirname "$MARK")/registers-not-restored" + wr $TCPC 0x92 0x00 || cold=0 + [[ $(extbst) == 0x00 ]] || { log "boot-undo: 0x92 readback $(extbst), not 0x00"; cold=0; } + sleep 0.02 + if gpio_chip >/dev/null && command -v gpioset >/dev/null && command -v gpioget >/dev/null; then + gpio5_set 0 || { log "boot-undo: GPIO5 readback is not 0 (got $(gpio5_get))"; cold=0; } + else + log "boot-undo: no max77759 gpiochip or no libgpiod: GPIO5 NOT cleared"; cold=0 + fi + if charger_loaded; then + log "boot-undo: max77759_charger is loaded: 0xcb/0xc4/0xb9 left alone (its regmap cache would not see the writes)"; rc=1 + else + restore_own_writes $MARK || rc=1 + fi + log "boot-undo: after: 0x92 $(extbst), gpio5 $(command -v gpioget >/dev/null && gpio5_get || echo '?'), VBUS $(vbus_mv) mV, port cold: $cold, registers restored: $(( !rc ))" + if (( cold )); then + if (( rc )); then + cp $MARK "$LEFT" 2>/dev/null + log "boot-undo: port is cold but the charger registers were NOT all restored: the saved values are in $LEFT, restore them by hand (0xcb bit 3, 0xc4, 0xb9) with the charger driver unloaded" + fi + undo_unit_remove + else + log "boot-undo: the port is NOT proven cold: $MARK kept, the unit runs again at the next boot; finish by hand (i2cset 0x25 0x92 0x00, gpioset GPIO5=0) and then remove $MARK" + rc=1 + fi + return $rc +} +role_now() { cat $ROLE 2>/dev/null || echo none; } +# MAX77759 GPIO5 = gpio-max77759 line 0, named "GPIO5" (gpio-max77759.c:24); +# the chip is the "max77759-gpio" MFD cell's gpiochip. Lines are set through +# libgpiod's gpioset (v2: holds the line until killed); the output value lives +# in the PMIC's MaxQ GPIO control register and the driver has no .free hook, +# so the value stays after the request is released. gpioget must use --as-is: +# without it libgpiod turns the line into an input. +gpio_chip() { + local d + for d in /sys/bus/platform/devices/max77759-gpio*/gpiochip*; do + [[ -e $d ]] && { echo "/dev/$(basename "$d")"; return 0; } + done + return 1 +} +gpio5_get() { # prints 0/1, or "?" on failure + local v + v=$(gpioget --as-is -c "$(gpio_chip)" GPIO5 2>/dev/null | sed 's/.*=//; s/^inactive$/0/; s/^active$/1/') + [[ $v == 0 || $v == 1 ]] && echo "$v" || echo "?" +} +gpio5_set() { # gpio5_set 0|1; returns 1 when the readback disagrees + local chip + chip=$(gpio_chip) || { log "no max77759 gpiochip"; return 1; } + log "gpioset -c $chip GPIO5=$1 (bst_on)" + gpioset -c "$chip" GPIO5="$1" & + local p=$! + # gpioset v2 holds the line while it runs, and gpioget cannot read a held + # line, so: hold 0.2 s, release, read back. In b5-host this makes bst_on + # high for about 0.2 s (logged) before 0x92, not Google's 5 ms. + sleep 0.2 + kill "$p" 2>/dev/null; wait "$p" 2>/dev/null + [[ $(gpio5_get) == "$1" ]] +} # ---- charger registers: saved before the step, written back by the undo ---- # 0xbb CHG_CNFG_02 (fast-charge current), 0xbd CNFG_04 (float voltage), # 0xc2 CNFG_09 (input current limit): written back. 0xb9 CNFG_00 (mode): only # logged. 0xbf (CHGPROT), 0xc5 CNFG_12 and 0xcb CNFG_18 are also written by -# the driver's probe but need the CHGPROT unlock; they are recorded, never -# written, so a person can compare them (dump). +# the driver's probe but need the CHGPROT unlock; the b3 path records them, +# never writes them, so a person can compare them (dump). b5-host's own +# writes (0xb9, 0xc4, 0xcb bit 3) are saved in host.saved and the marker. SAVE_RESTORE="0xbb 0xbd 0xc2" SAVE_ONLY="0xb9 0xbf 0xc5 0xcb" save_charger() { @@ -128,9 +540,17 @@ preflight() { # preflight STEP [[ -n "$BUS" ]] || { refuse "no i2c bus for 10cb0000.i2c"; return 1; } command -v i2cget >/dev/null || { refuse "i2c-tools missing"; return 1; } [[ -d $PSY ]] || { refuse "no battery power supply $PSY (load max17042_battery)"; return 1; } - [[ $(udc_state) == configured ]] || { refuse "USB gadget not configured ($(udc_state))"; return 1; } + if [[ $1 == b4-tcpm || $1 == b5-host ]]; then + # the step may take the USB port away: Wi-Fi is the way in, USB is not required + wifi_up || { refuse "Wi-Fi is not up ($WIFI needs carrier and an IPv4 address): it is the only way in during $1"; return 1; } + else + [[ $(udc_state) == configured ]] || { refuse "USB gadget not configured ($(udc_state))"; return 1; } + fi [[ $ilim =~ ^[0-9]+$ ]] && (( ilim <= ILIM_MAX )) || { refuse "--ilim '$ilim' must be a number up to $ILIM_MAX"; return 1; } - charger_loaded && { refuse "max77759_charger is already loaded"; return 1; } + if [[ $1 == b5-host ]] && charger_loaded; then + refuse "max77759_charger is loaded: b5-host writes MODE 0xb9 (0x00 while sourcing, as Google does on the external boost) and the bypass registers 0xc4/0xcb, which the driver owns through a cached regmap that would not see the writes; the charger's CHGIN may also see the self-sourced 5 V. Not proven safe together: reboot without b3-charger first"; return 1 + fi + [[ $1 != b4-tcpm && $1 != b5-host ]] && charger_loaded && { refuse "max77759_charger is already loaded"; return 1; } # the recovery boot depends on the charger being blocked at boot (the drill proves it) if [[ $1 != noop ]]; then grep -qsE '^(install|blacklist) max77759_charger( |$)' /etc/modprobe.d/*.conf /usr/lib/modprobe.d/*.conf || @@ -138,8 +558,14 @@ preflight() { # preflight STEP fi [[ $1 == noop || $1 == wd-drill ]] && return 0 lsmod | grep -q '^max77759 ' || { refuse "max77759 (MFD) not loaded"; return 1; } - lsmod | grep -qE '^(tcpci_maxim|tcpci|tcpm) ' && { refuse "a Type-C driver is loaded (that is M6)"; return 1; } - [[ -e $D/b3-done ]] && { refuse "b3-charger already ran in this boot: reboot first (the MFD register cache no longer matches the chip)"; return 1; } + if [[ $1 == b3-charger ]]; then + tcpc_loaded && { refuse "a Type-C driver is loaded: run b3-charger before b4-tcpm"; return 1; } + [[ -e $D/b3-done ]] && { refuse "b3-charger already ran in this boot: reboot first (the MFD register cache no longer matches the chip)"; return 1; } + elif [[ $1 == b5-host ]]; then + preflight_host || return 1 + else + preflight_tcpm || return 1 + fi v=$(psy voltage_now); t=$(psy temp); s=$(psy capacity) [[ $v =~ ^[0-9]+$ && $t =~ ^-?[0-9]+$ && $s =~ ^[0-9]+$ ]] || { refuse "battery readings unreadable (v='$v' t='$t' soc='$s')"; return 1; } (( v >= V_MIN && v <= V_TRIP )) || { refuse "voltage_now $v uV is not sane"; return 1; } @@ -155,6 +581,93 @@ preflight() { # preflight STEP return 0 } +# b4-tcpm preconditions. The charger may be loaded or not (the plan allows +# charger + tcpm together): with it loaded, max77759_charger follows the +# tcpm-source power supply (psy_work_item): online and current_max 0 (default +# Rp, the only case with pd-disable on today's sources) -> its own +# default_ilim_ua; online and current_max > 0 (Rp 1.5/3 A) -> that value, +# up to the register range, NOT clamped at 900 mA; offline -> mode OFF (no +# charging, the phone runs from the battery). So default_ilim_ua must not be +# 0 (the charger would switch off on the desktop port), and the 1.7 A battery +# trip stays the limit on what an Rp 3 A source can push: the DT caps the +# battery current at 1.485 A anyway. +preflight_tcpm() { + local p + tcpc_loaded && { refuse "tcpci_maxim/tcpci/tcpm already loaded: b4-tcpm applies nothing (undo b4-tcpm to unload)"; return 1; } + [[ -e $D/b4-done ]] && { refuse "b4-tcpm already ran in this boot: reboot first (the TCPC was re-initialised by the driver)"; return 1; } + grep -qsE '^(install|blacklist) tcpci_maxim( |$)' /etc/modprobe.d/*.conf /usr/lib/modprobe.d/*.conf || + { refuse "tcpci_maxim is not blocked in modprobe.d: a reset would boot with the Type-C driver autoloading"; return 1; } + [[ -d $(tcpc_dev) ]] || { refuse "no I2C client $(tcpc_dev): the DTB lacks the typec-test overlay (usb-typec@25 is disabled)"; return 1; } + [[ -e $(tcpc_dev)/driver ]] && { refuse "$(tcpc_dev) is already bound to $(basename "$(readlink -f "$(tcpc_dev)/driver")")"; return 1; } + rescue_active || { refuse "$RESCUE is not active: start it first (the undo restarts it, and its state must be known)"; return 1; } + # Charger + tcpm together is allowed only when b3-charger loaded the charger + # in this boot (b3-done: the saved registers and the mode-off undo are ours) + # and default_ilim_ua > 0 (with 0, tcpm online + current_max 0 would switch + # the charger OFF). The b4 undo then also runs the b3 undo (see revert). + if charger_loaded; then + [[ -e $D/b3-done ]] || { refuse "max77759_charger is loaded but not by b3-charger in this boot (no b3-done): the undo does not own it; reboot, then b3-charger before b4-tcpm"; return 1; } + p=$(cat /sys/module/max77759_charger/parameters/default_ilim_ua 2>/dev/null) + { [[ $p =~ ^[0-9]+$ ]] && (( p > 0 )); } || { refuse "max77759_charger default_ilim_ua is '$p': with tcpm up and default Rp the charger would switch off"; return 1; } + log "case: charger + tcpm. max77759_charger loaded by b3-charger with default_ilim_ua=$p: tcpm online + current_max 0 keeps that limit; Rp 1.5/3 A raises 0xc2 to that value (battery trip $I_TRIP uA stays; the b4 undo also undoes b3)" + else + log "case: charger-less. tcpm only reports; input limit register 0xc2 stays as the bootloader left it" + fi + [[ $(rd $TCPC 0x93) == 0x09 ]] || { refuse "USBSW_CTRL 0x93 is $(rd $TCPC 0x93), not 0x09 before the step (rescue not done, or no VBUS)"; return 1; } + return 0 +} + +# b5-host preconditions. The Type-C driver must be up (b4-tcpm in this boot): +# TCPM initialised the TCPC (POWER_CTRL 0 = VBUS voltage monitor on, alerts +# unmasked, USBSW 0x93 handled) and its log shows what it makes of VBUS +# appearing on an unattached sink (tcpm.c _tcpm_pd_vbus_on has no case for +# SNK_UNATTACHED/TOGGLING: no state change expected). The dwc3 role file is +# the usb-role-test overlay. Nothing may be sourcing or sinking VBUS: the +# desktop cable is out. 0x92 must read 0 and GPIO5 low (no half-applied +# state from a crashed run: a watchdog reset does not clear either). +preflight_host() { + local v p + [[ -e $D/b5-done ]] && { refuse "b5-host already ran in this boot: reboot first"; return 1; } + ((use_wd)) || { refuse "--no-watchdog is not allowed for b5-host: a dead tool must end in a reset, which runs boot-undo"; return 1; } + ((meter)) || { refuse "no --meter: stage (a) is gated on an independent USB-C meter on the port reading 0 V now (the TCPC's 0x70 is the chip we drive); put it on, read it, and say so with --meter"; return 1; } + [[ -e $MARK ]] && { refuse "$MARK exists: an earlier b5-host did not finish its undo (or boot-undo failed); run 'husky-deadman-phone boot-undo' by hand, check the dump, then remove the marker"; return 1; } + [[ -e $(dirname $MARK)/registers-not-restored ]] && { refuse "$(dirname $MARK)/registers-not-restored exists: a boot-undo left 0xcb/0xc4/0xb9 unrestored; restore them by hand from that file, compare with the dump, then remove it"; return 1; } + base_ok || { refuse "no stable cable-out baseline from this boot ($BASE): run 'husky-deadman-phone baseline' (read-only) first; the charger guard is defined against it"; return 1; } + [[ -e $D/b4-done ]] && tcpc_loaded && [[ -e $(tcpc_dev)/driver ]] || + { refuse "b4-tcpm has not run in this boot (b4-done, tcpci_maxim bound): b5-host needs TCPM owning the TCPC"; return 1; } + [[ -d /sys/class/typec/port0 ]] || { refuse "no /sys/class/typec/port0"; return 1; } + [[ $(cat /sys/class/typec/port0/power_role 2>/dev/null) == "[sink]" ]] || + { refuse "typec port0 power_role is '$(cat /sys/class/typec/port0/power_role 2>/dev/null)', expected '[sink]' (the connector must still be sink-only; TCPM must not also drive VBUS)"; return 1; } + [[ -e $ROLE ]] || { refuse "no $ROLE: the DTB lacks the usb-role-test overlay"; return 1; } + [[ $(role_now) == device ]] || { refuse "dwc3 role is '$(role_now)', not device (a host toggle is still applied)"; return 1; } + [[ $(udc_state) != configured ]] || { refuse "USB gadget is configured: the desktop cable is still in. Unplug it (Wi-Fi is the way in)"; return 1; } + lsmod | grep -q '^gpio_max77759 ' || [[ -n $(gpio_chip) ]] || { refuse "gpio-max77759 is not loaded (modprobe gpio_max77759): GPIO5 bst_on is its line 0"; return 1; } + gpio_chip >/dev/null || { refuse "no gpiochip under /sys/bus/platform/devices/max77759-gpio*"; return 1; } + { command -v gpioset >/dev/null && command -v gpioget >/dev/null; } || + { refuse "libgpiod tools missing (pacman -S libgpiod): gpioset/gpioget drive GPIO5"; return 1; } + gpioget --help 2>&1 | grep -q -- '--as-is' || { refuse "gpioget has no --as-is (libgpiod v1?): v2 is required, or the readback would turn GPIO5 into an input"; return 1; } + v=$(gpio5_get) + [[ $v == 0 ]] || { refuse "GPIO5 (bst_on) reads '$v', expected 0 (inactive) before the step"; return 1; } + v=$(extbst); hexok "$v" || { refuse "cannot read TCPC EXTBST_CTRL 0x92 (got '$v')"; return 1; } + [[ $v == 0x00 ]] || { refuse "TCPC EXTBST_CTRL 0x92 is $v, expected 0x00 before the step"; return 1; } + vbus_mon_on || { refuse "TCPC POWER_CTRL 0x1c = $(rd $TCPC 0x1c): VBUS voltage monitor is disabled (bit 6), no VBUS reading possible"; return 1; } + p=$(pwr_status); hexok "$p" || { refuse "cannot read TCPC POWER_STATUS (got '$p')"; return 1; } + (( (p & 0x15) == 0 )) || { refuse "TCPC POWER_STATUS $p: VBUS present/sourcing/sinking (bits 4,2,0). Nothing may be on VBUS before the step"; return 1; } + v=$(vbus_mv) + [[ $v =~ ^[0-9]+$ ]] || { refuse "TCPC VBUS_VOLTAGE 0x70 unreadable"; return 1; } + (( v <= VB_IDLE_MAX )) || { refuse "TCPC VBUS_VOLTAGE reads $v mV with nothing attached (limit $VB_IDLE_MAX): something is sourcing, or the ADC is not trustworthy"; return 1; } + vbus_valid && { refuse "charger CHG_DETAILS_00 $(rd $CHG 0xb5) says CHGIN valid: a cable is in"; return 1; } + v=$(rd $CHG 0xb9); hexok "$v" || { refuse "cannot read charger MODE 0xb9"; return 1; } + (( (v & 0x8) == 0 )) || { refuse "charger MODE 0xb9 = $v has a boost bit set (0x8/0x9/0xa/0xc/0xd): the internal boost is on, not our path"; return 1; } + v=$(cc_partner) + [[ -z $v ]] || { refuse "TCPC CC_STATUS 0x1d = $(rd $TCPC 0x1d) ($v): a partner presents a source's Rp, or the reading is not valid. Nothing that can source may be on the port (the meter must be passive)"; return 1; } + v=$(chg_vs_baseline) + [[ -z $v ]] || { refuse "CHG_DETAILS differ from this boot's baseline before the step: $v. Take a new baseline (cable out) and compare"; return 1; } + v=$(rd $CHG 0xcb); hexok "$v" && (( v & 0x08 )) && log "note: CHG_CNFG_18 0xcb = $v already has OTG_V_PGM (bit 3) set before the step; it is saved and put back as is by the undo" + [[ $(rd $CHG 0xc4) == "$VBYP_5000" ]] || log "note: CHG_CNFG_11 0xc4 = $(rd $CHG 0xc4), not $VBYP_5000; it is saved and put back by the undo" + log "stage (a): nothing attached but the passive meter. VBUS is read from the TCPC once a second; a > $I_JUMP uA discharge jump, a partner Rp on CC, or the details leaving the baseline trip the undo" + return 0 +} + # ---- steps ---- apply() { case "$1" in @@ -167,6 +680,90 @@ apply() { sleep 2 charger_loaded || return 1 [[ -d /sys/class/power_supply/max77759-charger ]] || { log "max77759_charger loaded but no max77759-charger power_supply: the probe failed"; return 1; } ;; + b4-tcpm) + echo "0x93 $(rd $TCPC 0x93)" > $D/tcpc.saved + log "saved TCPC USBSW_CTRL: $(cat $D/tcpc.saved); tcpm log hard resets so far: n/a (no port yet)" + touch $D/b4-done + log "systemctl stop $RESCUE (so its 2 s poll cannot race the driver's first USBSW_CTRL write)" + systemctl stop $RESCUE || return 1 + # the package blocklist has blacklist lines only; --ignore-install is + # needed only if someone added an install ... /bin/false line + if grep -qsE '^install tcpci_maxim( |$)' /etc/modprobe.d/*.conf /usr/lib/modprobe.d/*.conf; then + log "modprobe --ignore-install tcpci_maxim (DT keeps pd-disable; TCPM takes the port, expect one USB re-enumeration)" + modprobe --ignore-install tcpci_maxim || return 1 + else + log "modprobe tcpci_maxim (DT keeps pd-disable; TCPM takes the port, expect one USB re-enumeration)" + modprobe tcpci_maxim || return 1 + fi + sleep 5 + tcpc_loaded || return 1 + [[ -e $(tcpc_dev)/driver ]] || { log "tcpci_maxim loaded but $(tcpc_dev) is unbound: the probe failed"; return 1; } + [[ -d /sys/class/typec/port0 ]] || { log "no /sys/class/typec/port0: tcpm did not register the port"; return 1; } + [[ -d $(tcpm_psy) ]] || { log "no $(tcpm_psy): the charger has nothing to follow"; return 1; } + log "typec port0: power_role '$(cat /sys/class/typec/port0/power_role 2>/dev/null)' data_role '$(cat /sys/class/typec/port0/data_role 2>/dev/null)' power_operation_mode '$(cat /sys/class/typec/port0/power_operation_mode 2>/dev/null)'" + log "tcpm psy: online $(cat "$(tcpm_psy)/online" 2>/dev/null) current_max $(cat "$(tcpm_psy)/current_max" 2>/dev/null) uA; USBSW_CTRL $(rd $TCPC 0x93); charger 0xc2 $(rd $CHG 0xc2); hard resets $(tcpm_hard_resets)" + (( $(tcpm_hard_resets) == 0 )) || { log "hard reset in the tcpm log right after the probe"; return 1; } ;; + b5-host) + # Google's order (max77759_usecase.c, gs101_standby_to_otg:985-996 -> + # gs101_otg_enable default branch 833-857): MODE stays 0 for this use + # case (gs101_otg_mode:729-737 returns early with ext_otg_only), the + # bypass registers (gs101_otg_bypass_enable:370-383), bst_on high + # (gs101_ext_mode:220-250), 5 ms, LSW1 closed through EXTBST_CTRL + # (gs101_ls_mode:144-160), 30 ms, then VBUS is expected. + local i0 v p n d t0 + i0=$(psy current_now) + [[ $i0 =~ ^-?[0-9]+$ ]] || { log "battery current unreadable ('$i0')"; return 1; } + echo "$i0" > $D/b5.ibase + { + echo "0x92 $(extbst)"; echo "0xc4 $(rd $CHG 0xc4)"; echo "0xcb $(rd $CHG 0xcb)" + echo "0xb9 $(rd $CHG 0xb9)"; echo "0xbf $(rd $CHG 0xbf)" + echo "0xb5 $(rd $CHG 0xb5)"; echo "0xb6 $(rd $CHG 0xb6)"; echo "0xb7 $(rd $CHG 0xb7)" + echo "0x1d $(rd $TCPC 0x1d)"; echo "0x1e $(pwr_status)"; echo "0x1c $(rd $TCPC 0x1c)" + echo "0x1f $(rd $TCPC 0x1f)"; echo "0x24 $(i2cget -f -y "$BUS" $TCPC 0x24 w 2>/dev/null)" + echo "vbus_mv $(vbus_mv)"; echo "gpio5 $(gpio5_get)"; echo "role $(role_now)"; echo "ibase $i0" + } > $D/host.saved + log "saved before b5-host: $(tr '\n' ' ' < $D/host.saved); baseline: $(tr '\n' ';' < $BASE)" + touch $D/b5-done + # the boot-undo unit goes in BEFORE the first write + undo_unit_install || { log "cannot arm the boot undo: nothing written"; return 1; } + # Step 1: MODE 0x00. With the bootloader's 0x05 (buck + charger on) the + # charger would charge the pack from our own 5 V (seen 2026-11-01 21:33, + # CHG_DTLS in 0xb1). Google runs the external boost with MODE 0 (the + # "5-1: mode=0x0 in MW, EXT_B=1, LS1=1" comment, usecase.c:945-955). + log "charger MODE 0xb9 $(rd $CHG 0xb9) -> 0x00 while the external boost sources VBUS; restored by the undo" + wr $CHG 0xb9 0x00 || { log "cannot write charger MODE"; return 1; } + [[ $(rd $CHG 0xb9) == 0x00 ]] || { log "charger MODE readback $(rd $CHG 0xb9), not 0x00"; return 1; } + sleep 0.2 + log "with MODE 0x00 (no VBUS yet): 0xb5 $(rd $CHG 0xb5) 0xb6 $(rd $CHG 0xb6) 0xb7 $(rd $CHG 0xb7)" + d=$(chg_vs_baseline) + if [[ -n $d ]]; then + log "MODE 0x00 alone moved CHG_DETAILS off the cable-out baseline: $d. Stopping BEFORE any VBUS: the guard is defined against the cable-out baseline and has to be re-derived against the MODE-0 reading above once that is reviewed (HOST-MODE-RUNBOOK.md, item 4)" + return 1 + fi + # Step 2: the bypass registers, Google's gs101_otg_bypass_enable + log "bypass: CHG_CNFG_11 0xc4 $(rd $CHG 0xc4) -> $VBYP_5000 (OTG_VBYP code for 5000 mV), then CHG_CNFG_18 0xcb bit 3 OTG_V_PGM set; both restored by the undo" + wr $CHG 0xc4 $VBYP_5000 || { log "cannot write 0xc4"; return 1; } + [[ $(rd $CHG 0xc4) == "$VBYP_5000" ]] || { log "0xc4 readback $(rd $CHG 0xc4), not $VBYP_5000"; return 1; } + otg_v_pgm 1 || { log "cannot set OTG_V_PGM in 0xcb"; return 1; } + # Step 3 and 4: bst_on, 5 ms, LSW1, 30 ms + t0=$(date +%s%N) + gpio5_set 1 || { log "GPIO5 readback is not 1 after gpioset (got $(gpio5_get))"; return 1; } + sleep 0.005 + log "bst_on high for $(( ($(date +%s%N) - t0) / 1000000 )) ms before 0x92 (Google: 5 ms; longer here because gpioset must hold, then release, then be read back)" + wr $TCPC 0x92 0x01 || return 1 + v=$(extbst); [[ $v == 0x01 ]] || { log "EXTBST_CTRL readback $v, not 0x01"; return 1; } + sleep 0.03 + # settle: up to 1 s for VBUS to enter the window + for n in 1 2 3 4 5; do + v=$(vbus_mv); p=$(pwr_status) + log "VBUS after ${n}00 ms: $v mV, POWER_STATUS $p, CC_STATUS $(rd $TCPC 0x1d), FAULT_STATUS $(rd $TCPC 0x1f), battery i=$(psy current_now) uA (before $i0)" + [[ $v =~ ^[0-9]+$ ]] && (( v >= VB_MIN && v <= VB_MAX )) && break + sleep 0.1 + done + { [[ $v =~ ^[0-9]+$ ]] && (( v >= VB_MIN && v <= VB_MAX )); } || { log "VBUS $v mV is outside $VB_MIN..$VB_MAX mV after the sequence: no 5 V from the external boost on this path"; return 1; } + d=$(cc_partner); [[ -z $d ]] || { log "CC_STATUS shows a partner ($d) right after VBUS came up"; return 1; } + d=$(chg_vs_baseline); [[ -z $d ]] || { log "CHG_DETAILS left the baseline right after VBUS came up: $d (the charger sees its own 5 V?)"; return 1; } + log "VBUS up: $v mV (the meter is the real reading: write it down); tcpm log tail: $(tail -3 "$(tcpm_log)" 2>/dev/null | tr '\n' '|')" ;; *) log "unknown step $1"; return 1 ;; esac } @@ -184,16 +781,174 @@ revert() { return 1 fi restore_charger || { log "charging is NOT confirmed off (mode readback is not 0x4)"; return 1; } ;; + b4-tcpm) + # Type-C first (the switch is written only once the driver is gone), then + # the charger if b3-charger loaded it in this boot: a loaded charger must + # not be left at a TCPM-derived input limit with nothing guarding it. + # A charger loaded some other way (no b3-done) is left alone and logged. + local rc=0 + log "modprobe -r tcpci_maxim tcpci tcpm (charger loaded: $(charger_loaded && echo yes || echo no), b3-done: $([[ -e $D/b3-done ]] && echo yes || echo no))" + modprobe -r tcpci_maxim tcpci tcpm + if tcpc_loaded; then + log "a Type-C module did NOT unload: $(lsmod | awk '/^(tcpci_maxim|tcpci|tcpm) / {printf "%s ", $1}')" + systemctl start $RESCUE + rc=1 + else + usbsw_restore + log "systemctl start $RESCUE" + systemctl start $RESCUE || log "WARNING: $RESCUE did not start" + fi + if charger_loaded && [[ -e $D/b3-done ]]; then + log "charger was loaded by b3-charger: running the b3-charger undo too (charging ends off)" + revert b3-charger || rc=1 + elif charger_loaded; then + log "WARNING: max77759_charger is loaded but not by b3-charger (no b3-done): left alone at its last input limit 0xc2 $(rd $CHG 0xc2), mode 0xb9 $(rd $CHG 0xb9)" + fi + log "undo done (rc $rc): USBSW_CTRL $(rd $TCPC 0x93), udc $(udc_state), wifi $(wifi_up && echo up || echo down), charger loaded: $(charger_loaded && echo yes || echo no)" + return $rc ;; + b5-host) + # Google's off order (usecase.c:1199-1204, ls_mode(0) then ext_mode(0); + # gs101_otg_bypass_disable:385-389 clears OTG_V_PGM): load switch open + # (0x92 = 0x00, also the TCPC driver's clear-on-toggle value), 20 ms, + # bst_on low, VBUS fall, then 0xcb bit 3, 0xc4 and 0xb9 back to the + # saved values. The dwc3 role is never changed by this version; if + # someone set it to host by hand it goes back first. + local v n saved=$D/host.saved + [[ -f $saved ]] || { saved=$MARK; log "no $D/host.saved (new boot?): restoring from $MARK"; } + if [[ $(role_now) == host ]]; then + log "echo device > $ROLE" + echo device > $ROLE || log "cannot set the dwc3 role back to device" + fi + wr $TCPC 0x92 0x00 || log "i2cset of 0x92 failed" + v=$(extbst); [[ $v == 0x00 ]] || log "EXTBST_CTRL readback $v, not 0x00" + sleep 0.02 + gpio5_set 0 || log "GPIO5 readback is not 0 after gpioset (got $(gpio5_get))" + for n in 1 2 3; do + sleep 1 + v=$(vbus_mv) + [[ $v =~ ^[0-9]+$ ]] && (( v <= VB_IDLE_MAX )) && break + done + log "VBUS ${n} s after the undo: $v mV (expected <= $VB_IDLE_MAX; bleed/discharge behaviour of this path is unknown, so this is logged, not fatal; the meter must read 0 V)" + # the port is cold when 0x92 and GPIO5 read back 0: only that decides + # the return value (a failed return makes run() reset the phone, which + # costs a slot B try and must not happen for a register restore) + local cold=1 regs=0 left + left="$(dirname "$MARK")/registers-not-restored" + # from here on a signal must not start a second undo on top of this one + trap '' TERM INT HUP + [[ $(extbst) == 0x00 && $(gpio5_get) == 0 ]] || cold=0 + if [[ -f $saved ]]; then + restore_own_writes "$saved" || regs=1 + else + # neither host.saved nor the marker: the signal came before b5-host saved + # anything, so it has written nothing; bit 3 of 0xcb, if set, is the + # bootloader's (rule 4 of the boot undo), and 0xc4 and 0xb9 stay too + log "no saved registers anywhere: b5-host had written none of 0xcb/0xc4/0xb9, all left as they are" + fi + log "undo done: port cold $cold, registers restored $(( !regs )); 0x92 $(extbst), gpio5 $(gpio5_get), CC $(cc_partner), role $(role_now), POWER_STATUS $(pwr_status), udc $(udc_state), wifi $(wifi_up && echo up || echo down)" + if (( cold )); then + if (( regs )); then + cp "$saved" "$left" 2>/dev/null # regs is only set from a saved file + REGS_LEFT=1 + log "port cold, but 0xcb/0xc4/0xb9 were NOT all restored: the saved values are in $left; restore them by hand and remove that file, b5-host refuses until then (no reset: the port is off)" + fi + undo_unit_remove + return 0 + fi + log "undo NOT complete, the port is not proven cold: $MARK stays, husky-deadman-undo.service runs boot-undo at the next boot" + return 1 ;; esac return 0 } +# b5-host guard, once a second: VBUS window and collapse, a partner Rp on CC +# (a source got plugged in), the discharge jump (a short), the charger +# details leaving the cable-out baseline, 0x92 changed under us, FAULT_STATUS +# logged (no VBUS OCP bit exists in tcpci.h or Google's vendor header for +# this chip), Wi-Fi dead SW_BAD_N reads in a row. +host_guard() { + local v p f i0 i c + c=$(cc_partner) + if [[ $c == "?" ]]; then + ccbad=$((ccbad + 1)) + (( ccbad >= SW_BAD_N )) && { echo "CC_STATUS 0x1d unreadable or toggling $ccbad times ($(rd $TCPC 0x1d))" > $D/trip; return 1; } + elif [[ -n $c ]]; then + echo "CC_STATUS 0x1d $(rd $TCPC 0x1d): a partner presents a source's Rp ($c) while we source: unplug it" > $D/trip; return 1 + else + ccbad=0 + fi + v=$(vbus_mv); p=$(pwr_status); f=$(rd $TCPC 0x1f) + if [[ $v =~ ^[0-9]+$ ]]; then + vbad=0 + if (( v < VB_COLLAPSE )); then echo "VBUS collapsed to $v mV (< $VB_COLLAPSE): short or overload" > $D/trip; return 1 + elif (( v < VB_MIN || v > VB_MAX )); then echo "VBUS $v mV outside $VB_MIN..$VB_MAX" > $D/trip; return 1 + fi + else + vbad=$((vbad + 1)) + (( vbad >= SW_BAD_N )) && { echo "TCPC VBUS_VOLTAGE unreadable $vbad times" > $D/trip; return 1; } + fi + [[ $(extbst) == 0x01 ]] || { echo "EXTBST_CTRL 0x92 is $(extbst), not 0x01: the load switch was changed under us" > $D/trip; return 1; } + c=$(chg_vs_baseline) + [[ -z $c ]] || { echo "charger details left the cable-out baseline while sourcing: $c" > $D/trip; return 1; } + i0=$(cat $D/b5.ibase 2>/dev/null); i=$(psy current_now) + if [[ $i0 =~ ^-?[0-9]+$ && $i =~ ^-?[0-9]+$ ]] && (( i0 - i > I_JUMP )); then + echo "battery discharge jumped $(( i0 - i )) uA over the pre-step value with nothing attached (short on VBUS?)" > $D/trip; return 1 + fi + [[ $f != 0x00 ]] && hexok "$f" && log "FAULT_STATUS 0x1f = $f (bit 1 VCONN_OC, bit 7 ALL_REG_RST_TO_DEFAULT are the known ones; logged, not a trip)" + if ! wifi_up; then + linkbad=$((linkbad + 1)) + (( linkbad >= SW_BAD_N )) && { echo "$WIFI dead $linkbad reads in a row" > $D/trip; return 1; } + else + linkbad=0 + fi + echo "vbus=${v}mV pwr=$p cc=$(rd $TCPC 0x1d) fault=$f 0x92=$(extbst) dtls=$(rd $CHG 0xb5)/$(rd $CHG 0xb6)/$(rd $CHG 0xb7) wifi=$(wifi_up && echo up || echo down)" > $D/guard.tcpc + return 0 +} + # ---- guard: reads the battery every 2 s while the step is applied ---- # A breach, or 3 failed reads in a row, writes $D/trip; the main loop undoes. -guard() { - local bad=0 v t i +# For b4-tcpm it also watches the TCPC: a hard reset in the tcpm log trips at +# once; USBSW_CTRL != 0x09 while VBUS is valid, or usb0 and wlp1s0 both dead, +# trip after SW_BAD_N reads in a row. +tcpc_guard() { # returns 1 and writes $D/trip on a breach + local sw + if (( $(tcpm_hard_resets) > 0 )); then + echo "hard reset in the tcpm log ($(grep -iE "$TCPM_BAD_RE" "$(tcpm_log)" 2>/dev/null | tail -1))" > $D/trip; return 1 + fi + sw=$(rd $TCPC 0x93) + # VBUS dropping must NOT reset the counter (a discovery hard reset is a VBUS dip): + # only a good switch value clears it. + if [[ $sw == 0x09 ]]; then + swbad=0 + elif vbus_valid; then + swbad=$((swbad + 1)) + if (( swbad >= SW_BAD_N )); then echo "USBSW_CTRL $sw != 0x09 with VBUS valid, $swbad reads in a row" > $D/trip; return 1; fi + fi + if ! usb_up && ! wifi_up; then + linkbad=$((linkbad + 1)) + if (( linkbad >= SW_BAD_N )); then echo "usb0 (udc $(udc_state)) and $WIFI both dead, $linkbad reads in a row" > $D/trip; return 1; fi + else + linkbad=0 + fi + echo "sw=$sw udc=$(udc_state) wifi=$(wifi_up && echo up || echo down) hr=$(tcpm_hard_resets)" > $D/guard.tcpc + return 0 +} + +guard() { # guard STEP + local bad=0 v t i swbad=0 linkbad=0 vbad=0 ccbad=0 n=0 period=2 + [[ $1 == b5-host ]] && period=1 while :; do + if [[ $1 == b4-tcpm ]]; then tcpc_guard || return 1; fi + if [[ $1 == b5-host ]]; then + host_guard || return 1 + (( n++ % 5 == 0 )) && log "b5: $(cat $D/guard.tcpc) battery i=$(psy current_now) uA v=$(psy voltage_now) uV t=$(psy temp)" + fi v=$(psy voltage_now); t=$(psy temp); i=$(psy current_now) + # b4 with the charger loaded: every 10 s (5 reads) a line of evidence in + # the log: what tcpm hands over, what the charger did with it, the battery + if [[ $1 == b4-tcpm ]] && charger_loaded && (( n++ % 5 == 0 )); then + log "b4+charger: tcpm psy online $(cat "$(tcpm_psy)/online" 2>/dev/null) current_max $(cat "$(tcpm_psy)/current_max" 2>/dev/null) uA; charger 0xc2 $(rd $CHG 0xc2) 0xb9 $(rd $CHG 0xb9); battery i=$i uA v=$v uV t=$t" + fi if [[ $v =~ ^[0-9]+$ && $t =~ ^-?[0-9]+$ && $i =~ ^-?[0-9]+$ ]]; then bad=0 if (( v > V_TRIP )); then echo "voltage $v uV > $V_TRIP" > $D/trip; return 1 @@ -207,8 +962,8 @@ guard() { bad=$((bad + 1)) if (( bad >= 3 )); then echo "battery unreadable 3 times (v='$v' t='$t' i='$i')" > $D/trip; return 1; fi fi - echo "$(date +%T) v=$v t=$t i=$i" > $D/guard.last - sleep 2 + echo "$(date +%T) v=$v t=$t i=$i $(cat $D/guard.tcpc 2>/dev/null)" > $D/guard.last + sleep $period done } @@ -228,6 +983,9 @@ wd_arm() { rm -f $D/disarm $D/wd ( exec 3>$WD || exit 1 + # a stop or reboot sends TERM to the whole unit: the feeder keeps feeding + # until the main shell's handler has undone the step and asks to disarm + trap '' TERM INT HUP echo armed > $D/wd said=0 while :; do @@ -300,7 +1058,7 @@ trip_undo() { # trip_undo STEP guard_kill wd_extend $(( grace_s + 20 )) if revert "$1"; then - echo "tripped: $why" > $D/result + echo "tripped: $why$( ((REGS_LEFT)) && echo '; registers not restored, see registers-not-restored')" > $D/result wd_disarm return 1 fi @@ -308,12 +1066,32 @@ trip_undo() { # trip_undo STEP return 1 } +# signal handler for b5-host: undo, then let the feeder close the watchdog +on_signal() { + trap '' TERM INT HUP + log "=== step $1: signal received (systemctl stop or a reboot): undoing now" + guard_kill + wd_extend $(( grace_s + 20 )) + if revert "$1"; then + echo "interrupted: undone on a signal" > $D/result + wd_disarm + exit 1 + fi + final_reset "$1" + exit 1 +} + run() { local step="$1" rc mkdir -p $D guard_kill - rm -f $D/confirm $D/result $D/trip $D/guard.last - log "=== step $step: confirm ${confirm_s}s, grace ${grace_s}s, soak ${soak_s}s, watchdog $use_wd, ilim $ilim; udc $(udc_state); battery v=$(psy voltage_now) t=$(psy temp) soc=$(psy capacity)" + rm -f $D/confirm $D/result $D/trip $D/guard.last $D/guard.tcpc + log "=== step $step: confirm ${confirm_s}s, grace ${grace_s}s, soak ${soak_s}s, watchdog $use_wd, ilim $ilim; udc $(udc_state); wifi $(wifi_up && echo up || echo down); battery v=$(psy voltage_now) t=$(psy temp) soc=$(psy capacity)" + if [[ $step == b4-tcpm ]]; then + log "b4-tcpm spends NO boot retry by itself (no reboot, no slot change); only a watchdog reset does, and each reset spends one of slot B's 3 boots. USB may drop: the confirmation must come over Wi-Fi ($WIFI)" + elif [[ $step == b5-host ]]; then + log "b5-host stage (a): sources 5 V on VBUS from the external boost (MODE 0, bypass 0xc4/0xcb, GPIO5 bst_on, TCPC 0x92 = 0x01) with NOTHING on the port but a passive meter. The desktop cable must be OUT; the confirmation comes over Wi-Fi ($WIFI). A reset does NOT switch the boost off (the PMIC keeps GPIO5 and 0x92): husky-deadman-undo.service runs boot-undo at the next boot; if the phone freezes, unplug first, force a restart, and run 'husky-deadman-phone boot-undo' first thing" + fi preflight "$step" || return 1 if ((use_wd)); then wd_arm || { refuse "cannot open $WD, held by: $(wd_holders) (stop that, or --no-watchdog)"; return 1; } @@ -327,6 +1105,12 @@ run() { wd_extend 60; wd_disarm return 1 fi + # (b5-host) a systemctl stop or a reboot during the run must not leave the + # port hot until the next boot: TERM/INT/HUP undo the step first + if [[ $step == b5-host ]]; then + # shellcheck disable=SC2064 + trap "on_signal $step" TERM INT HUP + fi if ! apply "$step"; then log "apply failed: reverting now" wd_extend $(( grace_s + 20 )) @@ -338,7 +1122,7 @@ run() { final_reset "$step" return 1 fi - guard & + guard "$step" & gpid=$! echo "$gpid" > $D/guard.pid wait_confirm "$confirm_s"; rc=$? @@ -357,6 +1141,17 @@ run() { done guard_kill if [[ -e $D/trip ]]; then trip_undo "$step"; return 1; fi + if [[ $step == b5-host ]]; then + # a hot port is never left without the 1 s poll: the soak ends in the undo + log "=== step $step SOAKED clean; switching VBUS off now (stage (a) ends in the undo, nothing stays applied)" + wd_extend $(( grace_s + 20 )) + if ! revert "$step"; then final_reset "$step"; return 1; fi + wd_disarm + log "=== step $step SOAKED and UNDONE: VBUS off" + if (( REGS_LEFT )); then echo "soaked: VBUS off, but 0xcb/0xc4/0xb9 were not all restored, see $(dirname "$MARK")/registers-not-restored" > $D/result + else echo soaked > $D/result; fi + return 0 + fi wd_disarm log "=== step $step SOAKED clean; left applied" echo soaked > $D/result @@ -377,12 +1172,20 @@ run() { dump() { local r - echo "i2c bus ${BUS:-none}; udc $(udc_state); modules: $(lsmod | awk '/max77759|tcpci|tcpm|max17042/ {printf "%s ", $1}')" + echo "i2c bus ${BUS:-none}; udc $(udc_state); wifi $WIFI $(wifi_up && echo up || echo down); $RESCUE $(systemctl is-active $RESCUE 2>/dev/null); modules: $(lsmod | awk '/max77759|tcpci|tcpm|max17042/ {printf "%s ", $1}')" echo "battery: v=$(psy voltage_now) uV i=$(psy current_now) uA t=$(psy temp) (0.1 C) soc=$(psy capacity) % status=$(psy status)" [[ -f $D/guard.last ]] && echo "guard last: $(cat $D/guard.last)" if [[ -n "$BUS" ]]; then echo "charger 0x69 (read only):" for r in 0xb5 0xb6 0xb9 0xbb 0xbd 0xbf 0xc2 0xc5 0xcb; do echo " $r = $(rd $CHG $r)"; done + echo "tcpc 0x25 (read only): 0x1d CC_STATUS = $(rd $TCPC 0x1d), 0x1e POWER_STATUS = $(rd $TCPC 0x1e), 0x93 USBSW_CTRL = $(rd $TCPC 0x93) (0x09 = data connected)" + echo "tcpc host (read only): 0x92 EXTBST_CTRL = $(rd $TCPC 0x92), 0x1c POWER_CTRL = $(rd $TCPC 0x1c), 0x1f FAULT_STATUS = $(rd $TCPC 0x1f), 0x70 VBUS = $(vbus_mv) mV$(vbus_mon_on || echo ' (monitor disabled: not valid)'), CC partner: $(v=$(cc_partner); echo "${v:-none}"); charger 0xc4 = $(rd $CHG 0xc4) 0xcb = $(rd $CHG 0xcb) (bit 3 OTG_V_PGM); gpio5 bst_on = $(command -v gpioget >/dev/null && gpio5_get || echo 'no gpioget'); dwc3 role $(role_now)" + echo "charger details 0xb5/0xb6/0xb7 = $(rd $CHG 0xb5)/$(rd $CHG 0xb6)/$(rd $CHG 0xb7); baseline this boot: $(base_ok && tr '\n' ';' < $BASE || echo none); boot-undo marker: $([[ -e $MARK ]] && echo "PRESENT ($MARK)" || echo none)" + [[ -d $(tcpc_dev) ]] && echo "typec client $(tcpc_dev): driver $(basename "$(readlink -f "$(tcpc_dev)/driver" 2>/dev/null)" 2>/dev/null || echo none)" + fi + if [[ -d /sys/class/typec/port0 ]]; then + echo "typec port0: power_role '$(cat /sys/class/typec/port0/power_role 2>/dev/null)' data_role '$(cat /sys/class/typec/port0/data_role 2>/dev/null)' power_operation_mode '$(cat /sys/class/typec/port0/power_operation_mode 2>/dev/null)'" + [[ -d $(tcpm_psy) ]] && echo "tcpm psy: online $(cat "$(tcpm_psy)/online" 2>/dev/null) current_max $(cat "$(tcpm_psy)/current_max" 2>/dev/null) uA voltage_now $(cat "$(tcpm_psy)/voltage_now" 2>/dev/null) uV; hard resets $(tcpm_hard_resets)" fi } @@ -399,6 +1202,8 @@ while (($#)); do --soak) soak_s="${2:?}"; shift ;; --no-watchdog) use_wd=0 ;; --allow-soc) allow_soc=1 ;; + --meter) meter=1 ;; + --device|--no-device) echo "$1 is gone: b5-host is stage (a) only, nothing attached; devices go through the kernel path (HOST-MODE-RUNBOOK.md)" >&2; exit 1 ;; *) echo "unknown option $1" >&2; exit 1 ;; esac shift @@ -411,5 +1216,7 @@ case "$cmd" in undo) revert "$step" ;; dump) dump ;; status) cat $D/result 2>/dev/null || echo none ;; - *) echo "usage: husky-deadman-phone run|confirm|undo|dump|status" >&2; exit 1 ;; + baseline) baseline ;; + boot-undo) boot_undo ;; + *) echo "usage: husky-deadman-phone run|confirm|undo|dump|status|baseline|boot-undo" >&2; exit 1 ;; esac