diff --git a/device/husky/BATTERY-NOTES.md b/device/husky/BATTERY-NOTES.md new file mode 100644 index 000000000..3bbe85815 --- /dev/null +++ b/device/husky/BATTERY-NOTES.md @@ -0,0 +1,234 @@ + +# 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: + +- **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. + +Nothing in this document contains a serial number, IMEI, MAC address, IP address of a person's network, or a Wi-Fi name. Raw partition backups exist locally and are never published. + +## 1. Where things stand + +| Item | State on 2026-11-01 | +| --- | --- | +| I2C bus hsi2c_11 (USI11, CMU_PERIC1) | Works. Needs kernel #163 and a bring-up overlay. | +| Fuel gauge (0x36, `max17042_battery`) | Works: percentage, voltage, current, temperature, in the status bar, the home widget and UPower. | +| 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). | +| 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`. A cure exists (section 9). | +| PCA9468 direct charger (0x57) | No mainline driver. Not touched. | +| Charge-limit step table, JEITA, a reset restoring the charger registers, why charging is so slow | Open. See section 11. | + +## 2. Hardware, as found + +All of this is from Google's stock device tree (the factory image's `dtbo` partition decompiled with `dtc`; we used the copy in the GrapheneOS husky images; the Pixel 8 Pro's own overlay is `ov8.dts`, the retail MP one with the 4950 mAh pack; `ov16.dts` is the Pixel 8 with a smaller pack and different ATL, COS and LSN model nodes, do not use it for husky), Google's GPL kernel source (`android-gs-shusky-6.1-android16` for the clocks, the shusky `bms` repository for the gauge) and reads on the phone. + +- **Bus:** hsi2c_11 at 0x10CB0000, GIC SPI 659, on USI11 at 0x10cb00c0. USI11 needs CMU_PERIC1 at 0x10c00000 and the PERIC1 sysreg at 0x10c21000 (SW_CONF at offset 0xc). Pins gpp21-0 and gpp21-1. +- **Devices on the bus:** fuel gauge 0x36 (`maxim,max77759-fg`, interrupt gpa7-7), PMIC 0x66 (`maxim,max77759`, interrupt gpa8-0), the charger's registers at 0x69 (a dummy I2C client created by the PMIC driver), the Type-C controller 0x25 (interrupt gpa8-3), and a PCA9468 direct charger at 0x57 with no driver. +- **Chip identity:** the PMIC driver binds only if `PMIC_ID` is 59 (0x3b). Read back on the phone: PMIC_ID 0x3b, PMIC_REVISION 0x02, OTP_REVISION 0x31. So the chip at 0x66 is a MAX77759, not the MAX77729 that Google's device tree names on the same interrupt. +- **Pack:** 4950 mAh in our device tree (`simple-battery`). The pack's EEPROM says ATL (section 5.6). Husky's ATL model carries a design capacity of 0x09cf, which the gauge reports as 5,022,000 uAh (2 mAh per unit: 1 mAh from the 5 mOhm shunt, doubled because the driver scales by TaskPeriod 0x2d00 over the default 0x1680, as in section 5.6), and its fallback model `default-a1-0k` 0x0994 (4,904,000 uAh). With the ATL model loaded the kernel reports `charge_full` 4,978,000 uAh and `charge_full_design` 5,022,000 uAh. +- **Bootloader state at boot (before any Linux driver):** charger mode 0x5 (charge and buck on), float voltage 4350 mV, fast charge 1,933,420 uA, input limit 500 mA. Read from the register dump and from the charger driver's own probe line. +- **Stock charging steps:** 4.20, 4.30, 4.35 and 4.48 V by temperature (`google,chg-cv-limits`, edges at 0, 10, 20, 42, 46, 48, 55 C). Our device tree is deliberately more conservative: 4.2 V and 0.3 C (1.485 A). Raising it needs a review (section 11). + +## 3. Safety model used + +These notes follow CONTRIBUTING sections 3.1 to 3.6. In short: back up first, read before write, one change per boot where possible, a way back at every step, and a person at the phone for anything that charges. + +- **Backups.** A read-only backup of ten partitions (`persist`, `modem_a`, `modem_b`, `efs`, `efs_backup`, `modem_userdata`, `devinfo`, `pinfo`, `trusty_persist`, `trusty_userdata`) was taken in the guarded initramfs before the battery work and again after the only Android boot of the day, each copy accepted only if its SHA-256 equalled one computed on the phone from the partition. Several partitions differ between the backups, as they do after any Android boot. They hold IMEI and serials and are never published. +- **Rollback.** Every flashed image set was copied to a `known-good` directory first, so any step can be undone with `omamobile flash` of the previous set. +- **Rule on userspace register access (AGENTS.md section 1).** The rule is about the SoC's own PMU registers, which are secure-only. This work never used `devmem` or `debugfs/regmap`. It did read and write registers of the external MAX77759 chips over I2C with `i2cget` and `i2cset`, for the dead-man tool, the USB rescue and the gauge tests in section 6. That is what cheetah's and raven's tools already do, and it is listed here so nobody has to find it. +- **One change per boot.** Mostly kept. The exceptions: the panel-size overlay (for the on-screen keyboard) rode along with the battery overlay in one boot, and the gauge-model overlay and the pull-up test overlay were separate boots. Said here for honesty, not as a recommendation. +- **Slot B boot tries.** Every reset or reboot of slot B spends one of its three tries, and nothing marks slot B successful (section 9). `wd-drill`, the final reset of each step and every reboot between steps all count. Count the boots since your last `bin/omamobile flash` (a flash gives B three again). Before any step that can reset the phone, make sure that reset cannot be the one that leaves B with none; with one try left, flash your known-good image set first. The tool prints this in `wd-drill`'s start message and in its recovery text. +- **Which kernel ran, and what changed since.** The battery commits booted for these notes are the branch `husky-battery-i2c-booted` on the author's fork (Brett's c6 plus four commits), with the hsi2c_11 pins at `PULL_NONE`. Kernel #163 has moved since: it has the bindings split in three commits, rewritten comments, and one functional change, the pins at `PULL_UP`, which is the final value in Google's tree. The pull-up was booted separately with a one-line overlay (`&hsi2c11_bus { samsung,pin-pud = <3>; }`, kept locally, not in this PR) on the same tree, and the gauge, PMIC and the dummy at 0x69 bound and the Type-C chip answered. The pack EEPROM overlay (`pack-eeprom-test.dtso`) and section 5.6 need kernel #175 (booted as `husky-pack-eeprom-booted`). +- **Hand writes are research, not runbook steps.** The writes to the gauge in sections 5.3 and 5.6 (TEMP, Config, TGAIN, TOFF, and 0x000F to register 0x60) were one-off research, each with read-backs. They are not part of any runbook, and repeating them waits for a go from the maintainers. The gauge has no non-volatile memory, so nothing permanent was at stake. + +## 4. Runbook and results, step by step + +Each step is: what, expected result, stop condition, rollback. Kernel: Brett's c6 plus the four battery commits of kernel #163, booted release `7.3.0-rc6-omamobile-push1-gc7a0b2ef2f66-dirty`. (`c7a0b2ef2` is Brett's c6 commit. The four commits were applied before the build and committed afterwards, hence "dirty". The same four commits are `husky-battery-i2c` in the published kernel branch.) + +**M1, read-only baseline.** Expected: no I2C devices, no power supply, no PERIC1 nodes. Result: as expected. + +**M2, boot the new kernel with the nodes disabled.** Expected: nothing changes. Result: booted first time, no failed units; `cmu_peric1`, sysreg and USI11 nodes present, disabled. + +**M2b, clocks only** (overlay enabling CMU_PERIC1 and the sysreg). Result: the PERIC1 clock tree comes up as Google's tables say (peric1_noc 532.992 MHz, divided to 66.624 MHz for the NoC-user, sysreg, GPIO and USI11 PCLK gates; USI11 source and IPCLK at 399.36 MHz); all consumers off. + +**M3, the bus** (overlay enabling USI11 and hsi2c_11; a `modprobe.d` file on the phone keeping `max77759`, `max77759_charger`, `tcpci_maxim`, `gpio_max77759`, `nvmem_max77759` and `max17042_battery` from loading). Result: `10cb0000.i2c` binds to `exynos5-hsi2c`, adapter `i2c-0`, clients 0x36 and 0x66 present and unbound. USI11's gates are enabled by the drivers (enable count 1), so the automatic gating works and no MANUAL bit is needed. No I2C probe tools were run in this step. + +**M4a, the gauge.** The driver's model load only runs with a `maxim,fg-model` property, so without one the probe writes only the alert-enable bit and the alert thresholds. Loaded by hand. Result: percentage, voltage, current and temperature appear, UPower shows the battery. It loads at boot once its block line is removed. + +**M4b, the MFD.** Read the driver first. It reads PMIC_ID, creates the dummy client at 0x69, and registers the PMIC, MaxQ, TOPSYS and charger interrupt chips with everything masked. Result: binds, five interrupt lines with counts of 0 or 1 that stay flat, no I2C timeouts or NACKs. Two kernel messages are not understood: `max77759-gpio: DMA mask not set` and `max77759-nvmem: Failed to locate of_node`; the GPIO and NVMEM drivers themselves stay blocked. + +**M4c, the gauge model** (section 5). + +**M5, the charger under a dead-man tool** (sections 6 to 8). + +## 5. The gauge model and the temperature + +### 5.1 The symptom + +After a reinstall the gauge's temperature read exactly 22.0 C (`TEMP` register 0x08 = 0x1600) and never moved, not even under a sustained load. Before that, the same gauge on the same kernel read 32 to 34 C and moved. The dead-man tool refuses to start if the temperature is exactly 22.0 C, and it caught this before any charge. + +### 5.2 What the gauge looked like + +Verified, read with `i2cget` on 0x36: `Status` 0x0002 (the power-on-reset bit set), `Config` 0x2354, `TGAIN` 0xeb8d, `TOFF` 0x20aa. Google's register header (`max_m5_reg.h`, shusky `bms`) gives the power-on defaults as `Config` 0x2350, `Status` 0x02, `TGAIN` 0xeb8d, `TOFF` 0x20aa. So the live gauge was the power-on defaults plus the one alert bit the Linux driver sets: Google's model load had never run. The Linux driver loads a model only while `Status` bit 1 is set and only if the device tree carries `maxim,fg-model` and `maxim,fg-params`. Ours had neither. + +What put the gauge back in that state is **not known**. Candidates: a 30-second power-key hold to reach the bootloader, or the GrapheneOS boot that preceded the reinstall. Neither was tested. + +### 5.3 Hand calibration, three tests + +All rolled back to the starting state each time (config, TGAIN, TOFF, and `TEMP` rewritten to 0x1600, because after restoring the config `TEMP` stays latched at the last measured value). + +| Test | Writes | Reading | +| --- | --- | --- | +| 1 | `Config` 0x4217 only | 66.5 C, 66.4 C: impossible | +| 2 | stock TGAIN 0xed51, TOFF 0x1eba, `Config` 0x2254 (TEX cleared) | 53.5 C: still impossible | +| 3 | Google's whole stock triple: `Config` 0x4217, TGAIN 0xed51, TOFF 0x1eba | **warm test**, after about 20 minutes of a guarded 6-core load at about 800 mA (phone "a bit hot" to the hand): 47.2 to 47.4 C at idle, then a smooth rise to 49.3 C over 3 minutes of load. **Cold test**, 15 minutes idle, the phone at room temperature to the hand ("a tiny bit warm"): 46.5 to 47.2 C, not falling. | + +Reading of test 3: the thermistor channel is alive and follows heating (it rose by about 2 C under load), but it sat about 20 C above what the hand felt at rest. A constant offset, not a dead sensor. Not verified: why. There is no second temperature sensor on the phone (the gauge's is the only thermal zone), so the reference was the hand. + +### 5.4 The fix: load the whole model + +Evidence from a sibling: on a Pixel 7, nesmeck's kernel PR #171 reports the same gauge reading a stuck 22.0 C without the model and 33.1 C once Google's model is loaded. The model load writes much more than the three registers above (the 48 table words and 27 parameter words, including config2, misc config and filter settings, then waits for the gauge's load bit). + +Done on husky: + +1. `device/husky/overlays/gauge-model.dtso` adds `maxim,fg-model` (48 u16) and `maxim,fg-params` (27 u16) to `fuel-gauge@36`. It is generated from Google's stock husky node by `tools/gen-gauge-overlay.py` (each stock u32 table cell split into two u16, high half first; the stock parameter bytes read as big-endian u16 in the order of `struct max77759_fg_params`), so no number is typed by hand. The leading words of the table and of the parameters matched an independently derived copy; the whole table was not re-compared by hand. +2. Model chosen: Google's `default-a1-0k`. In Google's driver the unknown-pack path sets the battery ID to 0 (`DEFAULT_BATTERY_ID`) and matches the node with `maxim,batt-id-kohm = 0`. The other nodes are `default-fake-batt` (ID 170, Google's dummy), `atl-a1-1k`, `cos-a1-2k` and `lsn-a1-3k`. (Replaced by the ATL model once the pack ID was read, section 5.6.) +3. Flashed through the images workflow (`DTB_OVERLAYS`), no kernel rebuild. + +Result, verified: dmesg `max17042 0-0036: battery model loaded (DesignCap 0x994, TaskPeriod 0x2d00)`; `Status` 0x0000 (power-on bit cleared); `Config`, `TGAIN`, `TOFF` at 0x4217, 0xed51, 0x1eba; **TEMP 34.4 C**, drifting down slowly as a freshly booted phone cools, matching the hand (a hair above room temperature). The model survives reboots (no reload, the power-on bit stays clear). The gauge interrupt bursts on every 1 % step with the stock module, as kernel #170 describes: a logger on the phone reads the gauge's line in `/proc/interrupts` (summed over the CPUs) and the battery level every 30 s, and with a CPU load forcing steps the count rose by 466 for 75 to 74 % (803 to 1,269) and by 402 for 74 to 73 % (1,269 to 1,671). With #170's patch (applied cleanly to this tree, only `max17042_battery.ko` rebuilt with the release name pinned, swapped on the running phone with `rmmod` and `insmod`, the model staying loaded) the 73 to 72 % and 72 to 71 % steps each added 1 interrupt (1,671 to 1,672 and 1,672 to 1,673). The log is kept locally. Not tested: another pack or model, more than two patched steps. + +### 5.5 Consequences, honestly + +- The model is **sticky** until the gauge is reset. Google's reset is writing 0x000F to the gauge's command register (0x60) (`max1720x_full_reset()`); not tried on husky. +- A wrong table moves the percentage (often several percent) and the gauge's own full threshold. It does not change the charger's voltage limit, which comes from the device tree. +- Google's driver, if Android ever boots again on this gauge, compares a version byte with the model for the pack ID it reads and reloads Google's own model on a mismatch. The Linux driver never writes that byte. Not verified on a phone. +- The pack ID was found afterwards and the model replaced, see 5.6. + +### 5.6 The pack ID, and switching to the ATL model + +**Reading the ID.** Google's pack EEPROM is an `at,24c08` at 0x50 on hsi2c_9 (USI9, on CMU_PERIC1 like the battery bus, base 0x10c90000, GIC SPI 657, pins gpp19-4 and gpp19-5). Four kernel commits describe it: the USI9 clock ids, the USI9 path in `clk-zuma.c` (mux 0x690, divider 0x1824 and gates 0x2070, 0x2074, 0x20a0 in CMU_PERIC1, each checked against Google's cmucal tables and next to the USI11 set that already works), the `usi9` and `hsi2c_9` nodes with their pins, and a read-only `atmel,24c08` node in the board file (stock calls it `at,24c08`). `CONFIG_EEPROM_AT24=m` was already on. A bring-up overlay (`pack-eeprom-test.dtso`) switches the bus on. At boot the log shows `at24 0-0050: 1024 byte 24c08 EEPROM, read-only` and the three extra addresses (0x51 to 0x53) of the 24c08 appear. With the new bus the I2C adapter numbers move (the EEPROM bus became `i2c-0` and the battery chips `i2c-1`): look the bus up by its device path, as the tools here do. + +Google's driver reads one byte at offset 0x17 (the battery ID, no checksum) and matches it exactly against `maxim,batt-id-kohm` of the model nodes: 170 is Google's dummy model, 0 `default-a1-0k`, 1 `atl-a1-1k`, 2 `cos-a1-2k`, 3 `lsn-a1-3k`. On this phone byte 0x17 is **1: an ATL pack** [verified: the byte read with `dd` from the nvmem file; the mapping is from Google's driver and the husky overlay]. An independent check: at the start of the day, before the gauge fell back to its power-on state, it reported a design capacity of 5,022,000 uAh, which is exactly the ATL model's 0x09cf times 2 mAh. The rest of the EEPROM holds the pack's part number, dates and history: only that one byte was ever read and printed, and nothing else of it is published. + +**Switching the model.** The model is sticky (the driver loads it only while the gauge's Status bit 1, power-on reset, is set, and clears the bit), so replacing it needs a reset. Reviewed before doing it: + +1. Set the power-on bit by hand: write 0x0002 to Status. The bit does **not** stick (read back 0x0000); the hardware owns it. Nothing changed. +2. Unload `max17042_battery`, write 0x000F to the gauge's register 0x60 (the `max1720x_full_reset()` code of Google's driver, which Google sends to this gauge itself when the model version changes; on this gauge's register map 0x60 is also the extra-config unlock, so this is not a documented command here), wait 0.4 s, read back, reload the driver. Read back right after the reset: Status 0x0002 (power-on set), Config 0x2350, TGAIN 0xeb8d, TOFF 0x20aa, DesignCap 0x0bb8, TEMP 0x1600: exactly the power-on defaults. After the reload: `battery model loaded (DesignCap 0x9cf, TaskPeriod 0x2d00)`; Status 0x0000, Config 0x4217, Config2 0x0090 (load bit clear), TGAIN 0xed51, TOFF 0x1eba, DesignCap and FullCapNom 0x09cf, TEMP about 35.3 C and steady. + +The overlay for this is `gauge-model-atl.dtso`, generated by `tools/gen-gauge-overlay.py` from the husky MP overlay's `atl-a1-1k` node (model version 5, DesignCap 0x09cf). It has to be in the booted device tree before the reset (the driver reads the model from it at probe), so the switch was: flash the images with the ATL overlay, boot, reset, reload. + +**What changed for the user.** The wrong table had been overstating the charge. At the same moment and about 3.95 V, the fallback model reported 70 % and the ATL model reports 60 %. The percentage after the load can jump (the driver writes RepCap to 0, loads, waits for it to become non-zero), and then settles. + +**Not verified.** Whether the Status write ever works on another gauge state, and what Android does on a later boot (Google's driver compares a version byte stored in `TAlrtTh` and reloads its own model on a mismatch; the Linux loader does not write it). The 0x000F reset is Google's own code path but is documented nowhere for this chip, so the first time on a phone was done with the driver unloaded, a read-back at every step and the stop conditions above; it behaved as the reviewers expected. + +## 6. The dead-man tool + +`tools/husky-deadman` (desktop half) and `tools/husky-deadman-phone`, ported from cheetah's `tools/usbc-deadman`. A step runs detached on the phone and undoes itself unless the desktop gets back in over a new SSH login and confirms; a guard watches the battery; the SoC watchdog resets the phone if even the undo fails, and the phone then boots with the charger driver blocked. + +- **Steps:** `noop`, `wd-drill` (stops feeding the watchdog on purpose), `b3-charger` (loads `max77759_charger` with `default_ilim_ua`, `temp_guard=1`, `guard_psy=max170xx_battery`). +- **Preflight (refuses otherwise):** gadget configured, MFD loaded, charger and Type-C driver not loaded, the charger blocked in `modprobe.d`, battery 30 to 80 %, at most 4.15 V, 10 to 40 C and not exactly 22.0 C, input limit at most 900 mA, no earlier `b3-charger` this boot (the MFD register cache goes stale after any `i2cset`). +- **Guard (every 2 s):** trips on more than 4.30 V or under 3.0 V, above 45 C or under 5 C, more than 1.7 A in either direction, or three bad reads. +- **Undo:** unload the module, restore registers 0xbb, 0xbd, 0xc2, set the mode to OFF and then 0x4 (system from USB, battery not charged), read the mode back. Registers 0xb9, 0xbf, 0xc5, 0xcb are recorded only (0xc5 and 0xcb need the CHGPROT unlock). +- **Reviews:** two review rounds before the first run (not by a maintainer), then a third on the final plan. They found: the driver's unload does not stop charging (it leaves mode 0x5), the desktop half exited at `confirmed` before the soak, the watchdog was off during the soak, an unchecked unload, stale state files, a race at the end of the soak, an undo that did not read back the mode, a dropped link not treated as the drill. All fixed before the first run. +- **Two bugs found only by running it on the phone:** (1) the block file's `install max77759_charger /bin/false` line made the tool's own `modprobe` run `/bin/false`; the load now uses `modprobe --ignore-install`. (2) After a load, the tool now also requires the `max77759-charger` power supply to exist, because a probe failure could otherwise leave charging on with no driver. +- **The temperature check earned its place:** it refused the first two real attempts because of the stuck 22.0 C. +- **Not verified:** whether a watchdog reset puts the charger registers back to the bootloader's values. The drill never changes them. A software reboot with the step applied would show it for the software path; the emergency watchdog path would need a combined drill. + +## 7. The charger runs + +Common setup: battery 76 to 78 %, 4.0 to 4.04 V, about 34 C, charger blocked at boot, MFD and gauge loaded, USB rescue running. Each run ended with the tool's own `undo` (after the extra watches described below), which unloaded the module, restored the registers (0xbb 0x1d, 0xbd 0x23, 0xc2 as at boot) and left mode 0x4. + +What the driver does on probe, from its own log: it finds what the bootloader left (`mode 0x5, float voltage 4350 mV, fast charge 1933420 uA, input limit 500000 uA`), then reprograms to the device-tree limits (`float voltage 4200 mV, fast charge 1533400 uA`) with the temperature guard on (`band 20-42 C, float 4200 mV, charge 1485000 uA`). So the Linux driver is more conservative than the bootloader. Registers seen: 0xbb 0x1d to 0x17 (fast charge), 0xbd 0x23 to 0x14 (float 4.2 V), 0xc2 0x13 to 0x23 for 900 mA. + +| Run | Source | Input limit | Duration | Voltage | Battery temperature | Net battery current | Result | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 1 | desktop USB port, screen on | 500 mA | 10 min soak | 4.03 to 4.04 V | 34.3 to 34.6 C | -17 to -240 mA | clean | +| 1b | same, screen off, idle | 500 mA | 5.5 min, 33 samples | 4.03 to 4.04 V | 34.3 to 34.5 C | average -119 mA | clean | +| 2 | desktop USB port, screen off | 900 mA | 10 min soak | 4.03 to 4.04 V | 34.2 to 34.3 C | -19 to -234 mA | clean | +| 3 | wall charger (the stock fast-charge brick of a OnePlus 13; the Pixel cannot negotiate its protocols, so presumably plain 5 V, not measured), screen off | 900 mA | 14 min, 84 samples (78 in the window) | 4.01 to 4.05 V (mostly 4.04, a few load dips to 4.01) | 33.8 to 34.3 C | positive in 70 of 78 samples, typically +30 to +80 mA, average +18 mA with a few load spikes down to -425 mA | clean | + +Run 4, after the model was corrected to ATL (battery 59 %, 3.95 V, 35 C), 900 mA, screen off, a 30-minute guard on the phone (180 samples, no trip), the cable moved from the desktop port to the wall charger at 15:37:46: on the desktop port the net battery current averaged -55 mA (23 samples, never positive); on the wall charger +38 mA (156 samples, positive in 146, median +40 mA, maximum +95 mA, none above +150 mA), the voltage went from 3.955 to 3.964 V (maximum 3.971 V), the battery temperature stayed 33.5 to 34.6 C, and the level went from 59 to 60 % in about 55 minutes on the charger. The charger's own registers were identical on both sources (fast charge, constant current; input limit 900 mA). So the wall charger gives about 90 mA more than the desktop port and still only a trickle: the net current is small however strong the source is. Not verified: why. The likely reason is that, with no Type-C driver, neither source is told it may deliver more than the default current, and the driver clamps the input limit at 900 mA anyway; that is for the Type-C step. + +Reading, verified from the logs: raising the input limit from 500 to 900 mA changed nothing on the desktop port, so the port, not the phone, was the limit. On the wall charger the net current turned positive and the voltage went from 4.038 to 4.045 V between the first and last samples (a few load dips down to 4.01 V in between). The percentage stayed at 76 %: +40 mA for 13 minutes is under 10 mAh, and 1 % is about 49 mAh. + +Not verified, and not claimed: how much current the charger actually draws from the input; the gauge says the battery's net current only. Without a Type-C driver the Pixel cannot negotiate USB-PD or the charger's own fast-charge protocols, so it presumably gets plain 5 V (not measured); that is for the Type-C step. + +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.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. + +Stock's profile (`google,chg-temp-limits`, `google,chg-cv-limits`, `google,chg-cc-limits`; the current limits are percent of the 4950 mAh capacity). Bands 0 to 10, 10 to 20, 20 to 42, 42 to 46, 46 to 48 and 48 to 55 C; voltage tiers 4.20, 4.30, 4.35 and 4.48 V (`fv-max-uv` is 4.48 V): + +| Band (C) | up to 4.20 V | 4.20 to 4.30 V | 4.30 to 4.35 V | 4.35 to 4.48 V | +| --- | --- | --- | --- | --- | +| 0 to 10 | 2475 mA (0.5 C) | 1485 mA (0.3 C) | no charge | no charge | +| 10 to 20 | 3465 mA (0.7 C) | 1485 mA | 1485 mA | 1485 mA | +| 20 to 42 | 5940 mA (1.2 C) | 5940 mA | 5940 mA | 2475 mA (0.5 C) | +| 42 to 46 | 4950 mA (1.0 C) | 4950 mA | 4950 mA | 2475 mA | +| 46 to 48 | 2475 mA | 2475 mA | 2475 mA | no charge | +| 48 to 55 | no charge | 1485 mA | no charge | no charge | + +Adaptive charging by cycle count lowers the 20 to 42 C row from 120 % to 110 % at 300 cycles and 100 % at 1000. The battery defender starts after 21,600 s at 35 C or more and above 4.270 V, drains to 80 %, recharges at 4.250 V and 79 %, and resumes at 29 C or below. + +What stock does not do, verified in the source: no JEITA registers are programmed in the charger chip (the hardware thermistor monitor THM2 is off on husky, and it is a USB-connector sensor in any case), and the fast-charge safety timer is disabled. All the bands are software, from the fuel gauge's temperature. Our driver's temperature guard already uses the same band edges (0, 10, 20, 42, 46, 48, 55 C); its tiers (4.20, 4.30 and 4.45 V) and percentages are from the Pixel 7 era and differ, and the log line `band 20-42 C, float 4200 mV, charge 1485000 uA` is its 100 % of 4950 mAh clamped by the device tree's 4.2 V and 1.485 A. + +The PCA9468 (0x57) is a 2:1 direct charger fed by USB-PD PPS (10.5 V maximum, 3 A at the adapter), chosen by stock's power manager between 3.4 and 4.35 V battery voltage; it carries the rows above about 3 A, and wireless DC. Without a driver there is no fast charge; the MAX77759's own buck is what stock itself uses above 4.35 V. Not verified: the part's power-on default and the state of its enable GPIO under Linux, so check that before relying on "unconfigured is safe". + +Input limit: the charger's `CHGIN_ILIM` code is 0x04 plus (uA minus 125,000) divided by 25,000. Stock votes 500 mA (USB 2) or 900 mA (USB 3) for a standard port and 1.5 A for a charging port after BC1.2 detection, and whatever the contract says for PD. Our 500 and 900 mA are the no-advertisement defaults; without BC1.2 or PD a higher limit on a plain 5 V source would be a guess. + +A proposal for review, not implemented: keep the 4.20 V float, and band the current by temperature, for example 0.3 C at 0 to 10 C, 0.5 C at 10 to 20 C, 0.5 C or at most 0.7 C at 20 to 42 C, 0.5 C at 42 to 46 C, 0.3 C at 46 to 48 C, and no charge outside 0 to 48 C. Not to be raised without a review: the float above 4.2 V (it needs the tier switching, full detection, recharge logic, adaptive charging and the defender), the current above 0.7 C, the input limit beyond what the port advertises, and stock's odd 48 to 55 C row. Putting such a table in the driver is a kernel change (its table is hard-coded) for a later PR. + +## 8. USB link lost after an unplug + +Symptom: after unplugging and replugging the cable the phone does not come back on the USB link until it is rebooted. The kernel log of that boot shows nothing at the unplug. Cause (read from the cheetah and raven notes, then confirmed on husky): on unplug the MAX77759's Type-C side opens its USB2 data switch (TCPC 0x25, vendor register 0x93; 0x09 is closed, 0x00 open), and with no Type-C driver nothing closes it again; the bootloader does at the next boot. + +Fix: `omamobile-usb-rescue`, the Pixel 7 Pro's service on husky's bus (`10cb0000.i2c`). While VBUS is valid (`CHG_DETAILS_00.CHGIN_DTLS` equal to 3) it writes 0x09 to 0x25:0x93 when the switch is not 0x09, and it logs each change of the switch, VBUS and the UDC state to the journal. It stands aside once a Type-C driver owns the chip. + +Test, verified from its journal: unplug at 11:37:08 (`usbsw=0x00 vbus=0`), replug at 11:37:26 (`vbus=1`, the service wrote 0x09), 11:37:28 `usbsw=0x09`, link back on the desktop, no reboot. The same worked when the cable was moved to a wall charger and back. Shipped as part of `omamobile-device-husky` 0.1.3 together with the MAX77759 blocklist. + +## 9. Slot B retries, and the cure that cheetah already has + +Omarchy never marks slot B's boot successful, so every boot of slot B uses one of its three bootloader retries. At zero the bootloader falls back to slot A (GrapheneOS), and its first boot reformatted `userdata`: the Omarchy install was gone. It happened after a set of drills and reboots in one session. Observed with `fastboot getvar` after the fallback: current slot a; slot A successful, retry 1; slot B not successful, retry 0, not unbootable. `fastboot set_active b` sets the counter back to 3. Reading the count in the bootloader changes nothing; whether `reboot-to bootloader` itself uses a retry is not established (two of my readings disagree). + +Recovery was a fresh read-only backup in the initramfs, then `tools/install-phone` (it asks for answers, so it has to run in a real terminal), then the keyring repair for the known clock issue (#188), then the battery images and modules. + +**The cure exists.** Cheetah's package ships `omamobile-boot-success` and `omamobile-bootctl`, which mark the booted slot successful after a healthy boot by updating the slot bytes in `devinfo`. The husky package leaves them out on purpose ("until each one has its own runbook"). A check that can be done read-only: husky's `devinfo` has magic `DEVI`, version 3.15, and slot bytes at 0x30 that decode with the layout of `omamobile-bootctl`'s source (retry count, then flags: unbootable, successful, active, fastboot-ok). All three backups of the partition, taken at different times, hold the same slot bytes: slot A retry 1, flags 0x0a (successful, fastboot-ok); slot B retry 1, flags 0x04 (active, not successful). + +What can and cannot be cross-checked against `fastboot getvar`: + +- The flags agree with every reading I took: slot A successful, slot B not successful, and slot B the active one. +- The retry count agrees with one reading only: on 2026-10-31 at 13:54, right after the 13:35 backup and with no boot in between, `getvar` said retry 1 on both slots, as the file does. The counter moves with each boot of slot B, and between the other backups and my other readings slot B booted and was reset with `set_active`, so the file's retry value cannot be compared with those readings, and I am not using them. + +So the layout is consistent with husky's [verified, read-only, on files]: the magic and version are right, the flags match every reading, and the retry counts match the one reading that can be compared. That is not proof that the marker works on husky. Marking the slot successful would write `devinfo`, which today is hidden by the storage guard and listed as never-touch in AGENTS.md, so that is a decision for the maintainer, with its own runbook and a test against a backup first. Dry run, read-only on files: cheetah's `omamobile-bootctl dump` run on all three backups of the partition prints `magic 0x49564544 "DEVI"`, `version: 3.15 (verified layout)` and the same slot bytes as above (slot A `01 0a 00 00`, slot B `01 04 00 00`). This document only reports that the layout looks the same. + +## 10. What was combined, and what we did not do + +- 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. + +## 11. Open questions, in the order they matter + +1. **The model in the board file, or from the pack ID.** The pack is ATL (section 5.6). A model fixed in the board file would be wrong on a phone with a COS or LSN pack, so reading the ID at runtime may be better; this waits for what mainline's gauge driver can take (kernel #175 discussion). +3. **Charge limits.** Our 4.2 V and 1.485 A are conservative on purpose; stock steps up to 4.48 V by temperature. Review before anything raises them. Also unknown: whether the charger chip's own thermistor and JEITA protection are armed by default (nothing in the Linux driver configures them; Google's driver disables the charger watchdog and the THM2 interrupt). +4. **Does a reset put the charger registers back?** The software-reboot case can be checked directly; the emergency watchdog case needs a combined drill. +5. **Type-C (the next step).** In this tree's `tcpci_maxim_core.c` the data switch is closed (0x09) on every attach (`max_tcpci_set_roles`) and a PD partner that is not USB-communications capable opens it again (`set_partner_usb_comm_capable`); nothing else in that file writes register 0x93. So the driver should end the replug problem, but it has not been run on husky. It also takes over the USB-C port we use for SSH, so do it under the dead-man tool, with a second way into the phone. +6. **The boot-success marker** (section 9). +7. **The two kernel messages in the MFD** (DMA mask, NVMEM `of_node`), and what UPower's charge-cycle count means. + +## 12. Files + +In this repository: `device/husky/overlays/battery-i2c-test.dtso`, `gauge-model.dtso`, `gauge-model-atl.dtso`, `hsi2c-pullup-test.dtso`, `pack-eeprom-test.dtso` (all under `device/husky/overlays/`), `tools/gen-gauge-overlay.py`, `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). + +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. + +## 13. Credits + +Derek Ross reviewed the kernel changes against Google's tables. Brett (greenbrettmichael) provided the c6 kernel the work booted on. nesmeck's Pixel 7 gauge PRs (#170, #171) showed what a missing model looks like and what the load fixes. The cheetah and raven tools (`usbc-deadman`, `omamobile-usb-rescue`) are the pattern the husky versions follow. diff --git a/device/husky/ROADMAP.md b/device/husky/ROADMAP.md index 847e42b25..fcd319fda 100644 --- a/device/husky/ROADMAP.md +++ b/device/husky/ROADMAP.md @@ -31,8 +31,8 @@ Status words as in DEVICES.md. "9a" is the Pixel 9a (`tegu`) work. "Needs" lists | USB net | testing | Brett (per his comments on #1) | done | USB host and Type-C are in Charging | none | | Wi-Fi | testing | [Brett](https://github.com/greenbrettmichael) | done | [#156](https://github.com/derekross/linux-omarchy-mobile/pull/156) (draft): zuma's PCIe PHY and the BCM4398 (NCI backplane) in brcmfmac, stacked on #153, #143 (BCM4389) and #56 (API9), which have to land first; firmware from the owner's image with [#214](https://github.com/derekross/omarchy-mobile/pull/214). Open: P2P, recovery after a firmware crash, joining 5 GHz ([NOTES](NOTES.md)) | Test #156 on a second phone: `tools/extract-vendor-firmware -d husky -s `, then check the scan and a join | | Bluetooth | no | unassigned | 9a [#122](https://github.com/derekross/linux-omarchy-mobile/pull/122) (open); cheetah [BLUETOOTH-PLAN](../cheetah/BLUETOOTH-PLAN.md) | The controller is probably the combo chip that does Wi-Fi [I]; its UART, power and wake lines [I: not known to me] | Find the Bluetooth node in Google's tree; write `BLUETOOTH-PLAN.md` | -| Battery | no | Lef | cheetah [POWER-PLAN](../cheetah/POWER-PLAN.md), [WIFI-BATTERY-PLAN](../cheetah/WIFI-BATTERY-PLAN.md); `gs201-cheetah.dts` has the same chip family. The 9a's [#119](https://github.com/derekross/linux-omarchy-mobile/pull/119) is the MAX77779 and does not apply as is | Stock overlay [V, same source as Display]: fuel gauge `maxim,max77759` @0x36, charger `max77759chrg` @0x69, Type-C `max77759tcpc` @0x25 and `max77729pmic` @0x66, all on `hsi2c_11`; also `nxp,pca9468` and the wireless charger `idt,p9412`. Zuma has no clock controller for that I2C block yet (CMU_PERIC, not in `clk-zuma.c`) and no I2C or USI nodes [V]. `tools/phone-smoke` reports "no battery power supply" [V] | Derive the PERIC clocks from Google's cmucal tables, add the I2C nodes, then probe the gauge read-only. **Do not poke the PMIC from userspace** (AGENTS.md §1) | -| Charging, USB-C | no | Lef | cheetah [USB-C-PLAN](../cheetah/USB-C-PLAN.md); 9a: [#97](https://github.com/derekross/linux-omarchy-mobile/pull/97) is `tcpci_maxim` for the MAX77779 (merged), so check what husky's MAX77759 needs [I] | Same I2C bus as Battery; the USB data switch closes on unplug (AGENTS.md gotcha) | As Battery | +| Battery | testing (bus, gauge and MFD on kernel #163; the gauge's model through an overlay) | Lef | cheetah [POWER-PLAN](../cheetah/POWER-PLAN.md), [WIFI-BATTERY-PLAN](../cheetah/WIFI-BATTERY-PLAN.md); `gs201-cheetah.dts` has the same chip family. The 9a's [#119](https://github.com/derekross/linux-omarchy-mobile/pull/119) is the MAX77779 and does not apply as is | Stock overlay [V, same source as Display]: fuel gauge `maxim,max77759` @0x36, charger `max77759chrg` @0x69, Type-C `max77759tcpc` @0x25 and `max77729pmic` @0x66, all on `hsi2c_11`; also `nxp,pca9468` and the wireless charger `idt,p9412`. Zuma had no clock controller for that I2C block (CMU_PERIC, not in `clk-zuma.c`), no I2C or USI nodes, and `tools/phone-smoke` reported "no battery power supply" [V, until kernel #163] | Done on one phone, see [BATTERY-NOTES](BATTERY-NOTES.md): the PERIC1 clocks and the I2C nodes are kernel #163, the gauge works with Google's model loaded by an overlay. The pack ID is read (section 5.6: ATL). Next: the model, from the board file or the pack ID at runtime. **No hand writes to the PMIC or the gauge outside a reviewed tool** (AGENTS.md §1; the notes list the ones made, and why) | +| Charging, USB-C | testing (the MAX77759 charger driver in guarded runs; no USB-C yet) | Lef | cheetah [USB-C-PLAN](../cheetah/USB-C-PLAN.md); 9a: [#97](https://github.com/derekross/linux-omarchy-mobile/pull/97) is `tcpci_maxim` for the MAX77779 (merged), so check what husky's MAX77759 needs [I] | Same I2C bus as Battery; the USB data switch closes on unplug (AGENTS.md gotcha) | The charger ran under the dead-man tool at 500 and 900 mA and on a wall charger (slow net charging, plain 5 V), see [BATTERY-NOTES](BATTERY-NOTES.md). USB-C (`tcpci_maxim`) is not started; the replug rescue in the device package keeps the USB link until it is | | Haptics, Torch | no | unassigned | 9a [#96](https://github.com/derekross/linux-omarchy-mobile/pull/96) (CS40L26 and LM3644, open); cheetah [HAPTICS-TORCH-PLAN](../cheetah/HAPTICS-TORCH-PLAN.md) | The parts on husky [I: not known to me] | Find them in Google's tree | | GNSS | no | unassigned | cheetah [GNSS-PLAN](../cheetah/GNSS-PLAN.md); the 9a's is parked | Google's userspace in a chroot built from the owner's own factory image; the regulator rule (PMIC modules must load after about 30 s of late init) | After the display and battery rows | | AoC, Speakers/mics, Sensors | no | unassigned | cheetah [AOC-PLAN](../cheetah/AOC-PLAN.md), [AUDIO-PLAN](../cheetah/AUDIO-PLAN.md); 9a WIP | The AoC starts only through Trusty; the amplifiers need the speaker-protection calibration; high risk (AGENTS.md gotchas) | Read AOC-PLAN to size it | diff --git a/device/husky/overlays/battery-clk-test.dtso b/device/husky/overlays/battery-clk-test.dtso new file mode 100644 index 000000000..827f46e14 --- /dev/null +++ b/device/husky/overlays/battery-clk-test.dtso @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up probe, never default (BATTERY-NOTES.md M2b): only CMU_PERIC1 and its + * sysreg, with USI11 and the bus still off. Read clk_summary afterwards; + * nothing consumes the USI11 gates yet. + */ +/dts-v1/; +/plugin/; + +&cmu_peric1 { + status = "okay"; +}; + +&sysreg_peric1 { + status = "okay"; +}; diff --git a/device/husky/overlays/battery-i2c-test.dtso b/device/husky/overlays/battery-i2c-test.dtso new file mode 100644 index 000000000..6ade8b4f1 --- /dev/null +++ b/device/husky/overlays/battery-i2c-test.dtso @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up probe, never default (BATTERY-NOTES.md M3): switches on CMU_PERIC1, + * its sysreg, USI11 and hsi2c_11, the bus of the MAX77759 gauge, charger, + * Type-C controller and PMIC. The charger and Type-C drivers are blacklisted by the husky package + * (omamobile-max77759.conf), so nothing talks to those chips until a step + * loads them by hand. The Type-C controller node stays disabled in the board file. + */ +/dts-v1/; +/plugin/; + +&cmu_peric1 { + status = "okay"; +}; + +&sysreg_peric1 { + status = "okay"; +}; + +&usi11 { + status = "okay"; +}; + +&hsi2c_11 { + status = "okay"; +}; diff --git a/device/husky/overlays/gauge-model-atl.dtso b/device/husky/overlays/gauge-model-atl.dtso new file mode 100644 index 000000000..2a47850d7 --- /dev/null +++ b/device/husky/overlays/gauge-model-atl.dtso @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up overlay, never default (BATTERY-NOTES.md M4c and 5.6): load Google's + * ModelGauge m5 model "atl-a1-1k" into the husky fuel gauge. The node is picked by the + * pack's ID, byte 0x17 of its EEPROM: 0 default-a1-0k (what Google falls back to for + * an unknown pack), 1 atl-a1-1k, 2 cos-a1-2k, 3 lsn-a1-3k. Generated from the husky + * stock overlay by tools/gen-gauge-overlay.py: maxim,fg-model = the 24 stock u32 cells + * split into 48 u16 (high half first), maxim,fg-params = the stock byte list as + * big-endian u16 words, in the order of struct max77759_fg_params. The driver loads it + * only while the gauge reports power-on reset (Status bit 1), then clears that bit. + */ +/dts-v1/; +/plugin/; + +&hsi2c_11 { + fuel-gauge@36 { + maxim,fg-model = /bits/ 16 < + 0xa500 0xb790 0xb920 0xba60 0xbc70 0xbe00 0xbea0 0xc0b0 + 0xc270 0xc5d0 0xc930 0xcc40 0xcf40 0xd340 0xd6b0 0xde40 + 0x01e0 0x0b00 0x0d00 0x1310 0x1710 0x1410 0x0f00 0x0b00 + 0x0910 0x0810 0x07b0 0x07e0 0x05b0 0x07f0 0x04f0 0x04f0 + 0x0200 0x0200 0x0200 0x0200 0x0200 0x0200 0x0200 0x0200 + 0x0200 0x0200 0x0200 0x0200 0x0200 0x0200 0x0200 0x0200 + >; + maxim,fg-params = /bits/ 16 < + 0xf060 0x1439 0x260e 0x4217 0x0090 0x5f00 0x09cf 0x09cf + 0x3200 0x0273 0x09cf 0xa561 0x2400 0x0f80 0x0580 0x0480 + 0x03b0 0x1402 0x0630 0xed51 0x1eba 0x0014 0x6070 0x1900 + 0x2241 0x0613 0x2d00 + >; + }; +}; diff --git a/device/husky/overlays/gauge-model.dtso b/device/husky/overlays/gauge-model.dtso new file mode 100644 index 000000000..5bbf1cf31 --- /dev/null +++ b/device/husky/overlays/gauge-model.dtso @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up overlay, never default (BATTERY-NOTES.md M4c and 5.6): load Google's + * ModelGauge m5 model "default-a1-0k" into the husky fuel gauge. The node is picked by the + * pack's ID, byte 0x17 of its EEPROM: 0 default-a1-0k (what Google falls back to for + * an unknown pack), 1 atl-a1-1k, 2 cos-a1-2k, 3 lsn-a1-3k. Generated from the husky + * stock overlay by tools/gen-gauge-overlay.py: maxim,fg-model = the 24 stock u32 cells + * split into 48 u16 (high half first), maxim,fg-params = the stock byte list as + * big-endian u16 words, in the order of struct max77759_fg_params. The driver loads it + * only while the gauge reports power-on reset (Status bit 1), then clears that bit. + */ +/dts-v1/; +/plugin/; + +&hsi2c_11 { + fuel-gauge@36 { + maxim,fg-model = /bits/ 16 < + 0x9760 0xa510 0xb100 0xb600 0xb7a0 0xb900 0xba70 0xbc70 + 0xbde0 0xbfc0 0xc250 0xc510 0xc990 0xcea0 0xd040 0xd750 + 0x0060 0x0120 0x0200 0x0710 0x0e80 0x0df0 0x1430 0x1bd0 + 0x1520 0x0d70 0x0950 0x08e0 0x0800 0x0780 0x06b0 0x01e0 + 0x0100 0x0100 0x0100 0x0100 0x0100 0x0100 0x0100 0x0100 + 0x0100 0x0100 0x0100 0x0100 0x0100 0x0100 0x0100 0x0100 + >; + maxim,fg-params = /bits/ 16 < + 0xf060 0x2038 0x260e 0x4217 0x0090 0x5f00 0x0994 0x0994 + 0x0c80 0x0099 0x0994 0xa561 0x1100 0x0800 0x0301 0x0302 + 0x0700 0x223e 0x0310 0xed51 0x1eba 0x0014 0x3870 0x0000 + 0x2241 0xc623 0x2d00 + >; + }; +}; diff --git a/device/husky/overlays/pack-eeprom-test.dtso b/device/husky/overlays/pack-eeprom-test.dtso new file mode 100644 index 000000000..296c2341d --- /dev/null +++ b/device/husky/overlays/pack-eeprom-test.dtso @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up probe, never default (BATTERY-NOTES.md, the pack ID): switches on + * USI9 and hsi2c_9, the bus of the battery pack's EEPROM, whose byte 0x17 is + * the battery ID that picks the fuel gauge model. CMU_PERIC1 and its sysreg are + * on already when battery-i2c-test is loaded; repeating them is harmless. The + * EEPROM node itself is in the board file (read-only). Needs the kernel with + * the USI9 clock path. + */ +/dts-v1/; +/plugin/; + +&cmu_peric1 { + status = "okay"; +}; + +&sysreg_peric1 { + status = "okay"; +}; + +&usi9 { + status = "okay"; +}; + +&hsi2c_9 { + status = "okay"; +}; diff --git a/docs/DEVICES.md b/docs/DEVICES.md index 16cc933ef..fb3391c86 100644 --- a/docs/DEVICES.md +++ b/docs/DEVICES.md @@ -26,7 +26,7 @@ The status of each device, as verified on real hardware. Rows in the matrix have | Pixel 4 | flame | SM8150 (Snapdragon 855) | testing (temporary RAM boot; [notes](../device/flame/BRINGUP-M1.md)) | testing (RAM probe; all UFS read-only) | testing (1080x2280 console; software desktop in separate Arch payload) | testing (separate Arch payload; FD640 contexts, llvmpipe desktop) | testing (separate Arch payload; events and PIN unlock verified) | no | testing (NCM + ACM + SSH; sustained transfers can disconnect) | testing (guarded RAM scan; association untested) | no | no | no | no | no | no | - | no | no | no | no | no | no | - | | Pixel 4 XL ([notes](../device/coral/NOTES.md)) | coral | SM8150 (Snapdragon 855) | WIP (direct ABL v2 boot on the test handset's slot A; slot-B install and §3.1 entry pending; [notes](../device/coral/BRINGUP-M1.md)) | testing (read-only `blockdev` guard + RAM `overlayfs`) | testing (1440x3040@60Hz S6E3HC2 DSC 1.1 KMS, DPMS, brightness) | testing (Adreno 640 / FD640 Mesa Freedreno, Hyprland) | testing (FTS SPI multitouch + read-only flash guard) | testing (power via `qcom-pon` + volume via `gpio-keys`) | testing (CDC ECM + ACM + SSH; stays up with host USB switched off) | testing (`WCN3990` `ath10k_snoc` + `rmtfs -r`, WPA2/DHCP/HTTPS; radio sessions ran before the modem baseline) | WIP (`WCN3990` `hci_qca` `hci0` up + BLE scan; audio/pairing open) | WIP (PM8150B ADC `VBAT_SNS` voltage + FG temp; aftermarket pack on test unit: no reply from `1-0036`) | testing (PM8150B SMB5 charger with `4.20 V` / `500 mA` kernel clamp) | testing (`CS40L25A` I2C click waveform) | testing (PM8150L flash LEDs + quick-settings tile) | no | - | testing (QDSP6 + dual `CS35L36` amps capped at `-26 dB` + `IA8508` SPI mic DSP) | testing (`SLPI` + `fastrpc` + RAM-backed `hexagonrpcd` + QMI SSC: 7 sensors + Soli radar) | WIP (`MPSS` boots with `rmtfs -r` + patched `tqftpserv`, SIM detected; no IPA/voice yet; radio sessions ran before the modem baseline) | no | testing (`CAMSS` + `IMX363`, `IMX481`, `IMX520`, dual `OV7251` NIR; `libcamera` softISP) | no | - | | Pixel 9a ([notes](../device/tegu/NOTES.md)) | tegu | zumapro (Tensor G4) | works ([#28](https://github.com/derekross/omarchy-mobile/issues/28): native boot from slot B, the Arch root on `userdata`, `omamobile-device-tegu`; slot B was marked successful by hand on 2026-10-28 with the `devinfo` write approved on 2026-10-22, now on hold ([#125](https://github.com/derekross/omarchy-mobile/pull/125)), and the package does not mark it; unpublished kernel: the SoC and board device tree is [kernel #81](https://github.com/derekross/linux-omarchy-mobile/pull/81), merged; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (UFS behind the read-only guard; unpublished kernel; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (120 Hz through gs-decon; the panel driver [kernel #89](https://github.com/derekross/linux-omarchy-mobile/pull/89), 120 Hz [kernel #88](https://github.com/derekross/linux-omarchy-mobile/pull/88), merged, the display DT [kernel #90](https://github.com/derekross/linux-omarchy-mobile/pull/90) in review; brightness and the panel's sleep are not claimed until they have a dated record; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (Panthor, the desktop renders, runtime suspend when idle; this boot runs at a fixed 160 MHz, so frequency scaling and the GPU thermal zone count as in review, [kernel #85](https://github.com/derekross/linux-omarchy-mobile/pull/85) in review, [kernel #87](https://github.com/derekross/linux-omarchy-mobile/pull/87) in review; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (Synaptics S3908 over SPI, [kernel #81](https://github.com/derekross/linux-omarchy-mobile/pull/81), merged; survives sleep, [kernel #82](https://github.com/derekross/linux-omarchy-mobile/pull/82), merged; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (gpio-keys: power and volume; the power key wakes from sleep; unpublished kernel; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (CDC NCM and SSH; reconnects after a replug, `omamobile-tegu-usb-rescue` ([the replug record](../device/tegu/NOTES.md#2026-10-28-what-the-device-tables-claims-rest-on)); [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | testing (BCM4383 on PCIe through brcmfmac, WPA2 with iwd, kept loaded across sleep by the package's sleep hook; started by hand, not by the package; [kernel #56](https://github.com/derekross/linux-omarchy-mobile/pull/56) in review; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (hci_uart on the bootloader's address, BlueZ, A2DP; [kernel #94](https://github.com/derekross/linux-omarchy-mobile/pull/94); unpublished kernel; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (MAX77779 gauge with temperature, current and time estimates through UPower; [kernel #66](https://github.com/derekross/linux-omarchy-mobile/pull/66); unpublished kernel; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | testing (the chip charges on its own; the charger driver with its charge limit and inhibit is loaded by hand, [kernel #92](https://github.com/derekross/linux-omarchy-mobile/pull/92); [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (CS40L26A through feedbackd, with brownout prevention, [kernel #95](https://github.com/derekross/linux-omarchy-mobile/pull/95); its DT [kernel #96](https://github.com/derekross/linux-omarchy-mobile/pull/96) in review; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | works (LM3644, 25 steps to 75 mA, quick-settings tile; its DT [kernel #96](https://github.com/derekross/linux-omarchy-mobile/pull/96) in review; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | WIP (a position fix on 2026-10-30 and Omarchy's Location switch serving it on 2026-10-31, started by hand: 46 of 52 GGA sentences fixed, 9-13 satellites, first fix about 80 s after a client connects; needs [kernel #150](https://github.com/derekross/linux-omarchy-mobile/pull/150) and [#114](https://github.com/derekross/omarchy-mobile/pull/114), and a session lasts as long as the modem's PCIe link, one to five minutes, which is the open item; [plan](../device/tegu/MODEM-PLAN.md), record with [#202](https://github.com/derekross/omarchy-mobile/pull/202)) | testing (audio and sensor DSP through the GSA and Trusty, 93 services; the package ships its start disabled until a kernel enables the nodes, so it is started by hand; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | testing (speakers at a -10 dB ceiling, microphone, through the AoC card and PipeWire; by hand, as the AoC; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | testing (accelerometer, light, proximity through the AoC; by hand, as the AoC; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | WIP (ONLINE with IPC on an unpublished kernel, no SIM yet; [plan](../device/tegu/MODEM-PLAN.md)) | testing (NXP ST54L through nxp-nci: polls and read a payment card on 2026-10-29 with [kernel #131](https://github.com/derekross/linux-omarchy-mobile/pull/131), merged ([kernel #100](https://github.com/derekross/linux-omarchy-mobile/pull/100) closed into it), [kernel #104](https://github.com/derekross/linux-omarchy-mobile/pull/104) in review; started by hand; polling stops before sleep; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | testing (three cameras stream through libcamera; by hand; [kernel #63](https://github.com/derekross/linux-omarchy-mobile/pull/63) in review, [kernel #103](https://github.com/derekross/linux-omarchy-mobile/pull/103) in review; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | WIP (s2idle when asked for, or through the shell's auto-sleep with the `omamobile-sleep` toggle on, which ships off; the power key or the RTC wakes it, but three test sleeps have not woken, so sleep tests stay attended ([plan](../device/tegu/SLEEP-PLAN.md) S1); the drain is about 300 mA asleep, the same as awake with the screen off, because nothing below the CPUs sleeps yet; [record](../device/tegu/NOTES.md#2026-10-29-the-device-package-boot-and-what-this-row-rests-on)) | testing (enrolls, matches, refuses other fingers and unlocks the lock screen through Trusty and `omamobile-fingerprint`, 2026-10-29; the service ships disabled; [kernel #126](https://github.com/derekross/linux-omarchy-mobile/pull/126), merged; [plan](../device/tegu/FINGERPRINT-PLAN.md)) | -| Pixel 8 Pro ([notes](../device/husky/NOTES.md)) | husky | zuma (Tensor G3) | WIP ([#1](https://github.com/derekross/omarchy-mobile/issues/1): slot B, not marked successful; Omarchy's image from the signed repository boots to the lock screen; the zuma device tree is merged ([kernel #13](https://github.com/derekross/linux-omarchy-mobile/pull/13), [#53](https://github.com/derekross/linux-omarchy-mobile/pull/53))) | testing (UFS at HS-G4 behind the read-only guard; Arch on `userdata`; [UFS-PLAN](../device/husky/UFS-PLAN.md)) | WIP (simple-framebuffer: console and Omarchy's lock screen) | no | testing (ST FTM5 over SPI, merged, [kernel #153](https://github.com/derekross/linux-omarchy-mobile/pull/153); [NOTES](../device/husky/NOTES.md)) | testing (power and volume through `gpio-keys`, merged, [kernel #148](https://github.com/derekross/linux-omarchy-mobile/pull/148); [NOTES](../device/husky/NOTES.md)) | testing (USB and SSH) | testing (BCM4398 on a test kernel, [kernel #156](https://github.com/derekross/linux-omarchy-mobile/pull/156); firmware from the owner's image, [#214](https://github.com/derekross/omarchy-mobile/pull/214); [NOTES](../device/husky/NOTES.md)) | no | no | no | no | no | no | no | no | no | no | no | no | no | no | +| Pixel 8 Pro ([notes](../device/husky/NOTES.md)) | husky | zuma (Tensor G3) | WIP ([#1](https://github.com/derekross/omarchy-mobile/issues/1): slot B, not marked successful; Omarchy's image from the signed repository boots to the lock screen; the zuma device tree is merged ([kernel #13](https://github.com/derekross/linux-omarchy-mobile/pull/13), [#53](https://github.com/derekross/linux-omarchy-mobile/pull/53))) | testing (UFS at HS-G4 behind the read-only guard; Arch on `userdata`; [UFS-PLAN](../device/husky/UFS-PLAN.md)) | WIP (simple-framebuffer: console and Omarchy's lock screen) | no | testing (ST FTM5 over SPI, merged, [kernel #153](https://github.com/derekross/linux-omarchy-mobile/pull/153); [NOTES](../device/husky/NOTES.md)) | testing (power and volume through `gpio-keys`, merged, [kernel #148](https://github.com/derekross/linux-omarchy-mobile/pull/148); [NOTES](../device/husky/NOTES.md)) | testing (USB and SSH) | testing (BCM4398 on a test kernel, [kernel #156](https://github.com/derekross/linux-omarchy-mobile/pull/156); firmware from the owner's image, [#214](https://github.com/derekross/omarchy-mobile/pull/214); [NOTES](../device/husky/NOTES.md)) | no | testing (gauge with Google's ATL model through a bring-up overlay, temperature, MFD, on a test kernel, [kernel #163](https://github.com/derekross/linux-omarchy-mobile/pull/163); [notes](../device/husky/BATTERY-NOTES.md)) | testing (the charger driver by hand under a dead-man tool, slow on plain 5 V, on a test kernel, [kernel #163](https://github.com/derekross/linux-omarchy-mobile/pull/163); [notes](../device/husky/BATTERY-NOTES.md)) | no | no | no | no | no | no | no | no | no | no | no | | Pixel 7 ([notes](../device/panther/NOTES.md)) | panther | gs201 (Tensor G2) | WIP (slot B, not marked successful; Arch and Hyprland boot; [BRINGUP-M1](../device/panther/BRINGUP-M1.md); board file merged, [kernel #108](https://github.com/derekross/linux-omarchy-mobile/pull/108)) | testing (UFS behind the read-only guard; Arch on `userdata`; merged, [kernel #108](https://github.com/derekross/linux-omarchy-mobile/pull/108)) | WIP (simple-framebuffer: console and the Hyprland lock screen) | testing (Panthor on the Mali-G710; Hyprland renders on it; merged through [kernel #134](https://github.com/derekross/linux-omarchy-mobile/pull/134), with the always-on rule in device-panther 0.1.1, [#145](https://github.com/derekross/omarchy-mobile/pull/145); [notes](../device/panther/NOTES.md#2026-10-28-the-gpu-and-the-haptics-power-off-and-usb-after-a-replug)) | WIP (FocalTech FT3658: touches drive Hyprland and unlock the PIN screen on a test kernel; the driver, [kernel #109](https://github.com/derekross/linux-omarchy-mobile/pull/109), and the touch node, [kernel #134](https://github.com/derekross/linux-omarchy-mobile/pull/134), are merged; stock's interrupt pull-up and CS delay, [kernel #166](https://github.com/derekross/linux-omarchy-mobile/pull/166), the driver's review fixes, [kernel #133](https://github.com/derekross/linux-omarchy-mobile/pull/133), and the kernel option with the touch notes, [#149](https://github.com/derekross/omarchy-mobile/pull/149), are merged) | testing (gpio-keys: power, volume; merged, [kernel #108](https://github.com/derekross/linux-omarchy-mobile/pull/108)) | testing (USB and SSH; merged, [kernel #108](https://github.com/derekross/linux-omarchy-mobile/pull/108); a replug comes back through `omamobile-usb-rescue` in device-panther 0.1.3, on the MAX77759's I2C bus, merged, [kernel #167](https://github.com/derekross/linux-omarchy-mobile/pull/167); [notes](../device/panther/NOTES.md#2026-10-29-usb-comes-back-after-a-replug-u1)) | no | no | WIP (MAX77759 fuel gauge with stock's battery model on a test kernel: percentage, capacity and temperature in upower and the bar; in review, [kernel #171](https://github.com/derekross/linux-omarchy-mobile/pull/171) and the driver fix [#170](https://github.com/derekross/linux-omarchy-mobile/pull/170); [BATTERY-PLAN](../device/panther/BATTERY-PLAN.md)) | no | testing (CS40L26 with the phone's own firmware, `tools/extract-vendor-firmware -d panther`; merged through [kernel #134](https://github.com/derekross/linux-omarchy-mobile/pull/134), with the feedbackd rule in device-panther 0.1.1, [#145](https://github.com/derekross/omarchy-mobile/pull/145); [notes](../device/panther/NOTES.md#2026-10-28-the-gpu-and-the-haptics-power-off-and-usb-after-a-replug)) | no | no | no | no | no | no | no | no | no (s2idle by default since [kernel #134](https://github.com/derekross/linux-omarchy-mobile/pull/134) and device-panther 0.1.1; not run yet) | no | | OnePlus 13 ([notes](../device/dodge/NOTES.md)) | dodge | sm8750 (Snapdragon 8 Elite) | testing (kernel in review, [kernel #115](https://github.com/derekross/linux-omarchy-mobile/pull/115); [BRINGUP](../device/dodge/BRINGUP-M1.md), [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing ([notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (msm/dpu; warm-boot drop fixed; [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (Adreno 830 / gpu2; Vulkan untested; [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing ([notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing ([notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (CDC NCM + SSH; gadget stuck after replug until reboot; kernel in review, [kernel #115](https://github.com/derekross/linux-omarchy-mobile/pull/115); [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (WCN7860 / ath12k; [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (pairing; A2DP untested; kernel in review, [kernel #115](https://github.com/derekross/linux-omarchy-mobile/pull/115); [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (gauge; charging path not claimed; kernel in review, [kernel #115](https://github.com/derekross/linux-omarchy-mobile/pull/115); [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | no | no | no | no | - | testing (speakers, earpiece, mics; headset plug untested; [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (accel, prox, compass; autorotate; [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | testing (LTE data; calls/SMS untested; opt-in flag; [modem](../device/dodge/modem/README.md), [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | no | no | WIP (s2idle not default; [notes](../device/dodge/NOTES.md#2026-10-28-matrix-evidence)) | no | | *Template* | *codename* | *SoC* | | | | | | | | | | | | | | | | | | | | | | | diff --git a/tools/gen-gauge-overlay.py b/tools/gen-gauge-overlay.py new file mode 100755 index 000000000..0951e9a81 --- /dev/null +++ b/tools/gen-gauge-overlay.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Generate device/husky/overlays/gauge-model.dtso from Google's stock husky devicetree. + +Usage: gen-gauge-overlay.py STOCK.dts NODE OUT.dtso + STOCK.dts the husky MP stock overlay source (ov8: dtc -I dtb -O dts of the factory image's dtbo; not the Pixel 8's ov16, its models differ), the one + with the "maxim, { maxim,fg-model ... maxim,fg-params ... }" nodes + NODE the model node, e.g. default-a1-0k (Google's fallback for an unknown pack), + atl-a1-1k, cos-a1-2k, lsn-a1-3k, default-fake-batt + +Writes maxim,fg-model (48 u16 from the 24 stock u32 cells, high halfword first) and +maxim,fg-params (u16 from the stock big-endian byte pairs, in the order of +struct max77759_fg_params). Nothing is typed by hand.""" +import re, sys +src, node, out = sys.argv[1], sys.argv[2], sys.argv[3] +text = open(src).read() +m = re.search(r'maxim,' + re.escape(node) + r' \{(.*?)\n\t*\};', text, re.S) +body = m.group(1) +cells = re.search(r'maxim,fg-model = <([^>]*)>', body).group(1).split() +params = re.search(r'maxim,fg-params = \[([^\]]*)\]', body).group(1).split() +model = [] +for c in cells: + v = int(c, 16) + model += [(v >> 16) & 0xffff, v & 0xffff] +pw = [(int(params[i], 16) << 8) | int(params[i + 1], 16) for i in range(0, len(params), 2)] +assert len(model) == 48, len(model) +assert len(pw) in (27, 28), len(pw) +def fmt(ws): return "\n".join("\t\t\t" + " ".join("0x%04x" % w for w in ws[i:i + 8]) for i in range(0, len(ws), 8)) +open(out, "w").write(f"""// SPDX-License-Identifier: GPL-2.0-only +/* + * Bring-up overlay, never default (BATTERY-NOTES.md M4c and 5.6): load Google's + * ModelGauge m5 model "{node}" into the husky fuel gauge. The node is picked by the + * pack's ID, byte 0x17 of its EEPROM: 0 default-a1-0k (what Google falls back to for + * an unknown pack), 1 atl-a1-1k, 2 cos-a1-2k, 3 lsn-a1-3k. Generated from the husky + * stock overlay by tools/gen-gauge-overlay.py: maxim,fg-model = the 24 stock u32 cells + * split into 48 u16 (high half first), maxim,fg-params = the stock byte list as + * big-endian u16 words, in the order of struct max77759_fg_params. The driver loads it + * only while the gauge reports power-on reset (Status bit 1), then clears that bit. + */ +/dts-v1/; +/plugin/; + +&hsi2c_11 {{ + fuel-gauge@36 {{ + maxim,fg-model = /bits/ 16 < +{fmt(model)} + >; + maxim,fg-params = /bits/ 16 < +{fmt(pw)} + >; + }}; +}}; +""") +print("model words", len(model), "param words", len(pw), "design cap word", hex(pw[7]), "config", hex(pw[3]), "tgain/toff", hex(pw[19]), hex(pw[20])) diff --git a/tools/husky-deadman b/tools/husky-deadman new file mode 100755 index 000000000..e1119f4df --- /dev/null +++ b/tools/husky-deadman @@ -0,0 +1,246 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# +# husky-deadman: run one MAX77759 charger bring-up step on the Pixel 8 Pro +# under a dead-man switch and a battery guard (device/husky/BATTERY-NOTES.md, M5). Ported from +# tools/usbc-deadman (cheetah). The step runs DETACHED on the phone +# (tools/husky-deadman-phone, started with systemd-run) and undoes itself +# unless this script gets back in over a NEW SSH login and confirms, or when +# the guard sees the battery leave its limits. If even that does not settle, +# the SoC watchdog resets the phone, which boots with the charger blocked. +# +# Usage: +# tools/husky-deadman install copy the phone half to /usr/local/bin +# tools/husky-deadman dump read-only battery / charger dump +# 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 +# +# STEP: noop | wd-drill | b3-charger +# +# Options: +# --confirm SECS phone waits this long for our confirmation (default 90) +# --grace SECS after its undo, wait this long again (default 60) +# --soak SECS keep guarding after the confirmation (default 600) +# --ilim UA b3-charger: default_ilim_ua (default 500000, max 900000) +# (the confirmation is only 'SSH still works': the soak is the gate) +# --allow-soc run b3-charger outside 30..80 % battery +# --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 +# +# Exit codes: 0 confirmed (or undone on purpose with --no-confirm), +# 3 undone (no confirmation in time), 4 no answer from the phone, +# 5 refused before applying anything (reason printed), 6 apply failed, undone, +# 7 the guard tripped and the step was undone, 8 wd-drill failed. 4 also means +# the soak never finished or the phone did not come back after wd-drill. + +set -uo pipefail + +ROOT=$(cd "$(dirname "$0")/.." && pwd) +SSH="$ROOT/tools/phone-ssh" +LOGDIR="$ROOT/logs" + +say() { printf '\e[1m==> %s\e[0m\n' "$*"; } +warn() { printf '\e[33m==> %s\e[0m\n' "$*"; } +die() { printf '\e[31merror:\e[0m %s\n' "$*" >&2; exit 1; } +usage() { sed -n '/^# Usage:/,/^# 5 refused/p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; } +# Every call gets its own stdin and a hard time limit, so a stuck SSH can +# neither eat our terminal nor hang the loop. +# --fresh: a shared connection (OMAMOBILE_SSH_SHARE) would outlive the very +# loss of new logins this tool must notice. +phone() { timeout 30 "$SSH" --fresh "$@" < /dev/null; } +phone_in() { timeout 30 "$SSH" --fresh "$@"; } # with our stdin (file uploads) + +recovery() { + cat <<'TXT' +Physical recovery, in order: + 1. Wait 2 minutes: the phone undoes the step, then its watchdog resets it + (the screen goes black and the boot logo returns). Linux on slot B boots + with max77759_charger blocked in /etc/modprobe.d. + 2. Unplug the cable. Force a restart: hold Power + Volume Up for 15 to 30 s + (Power alone does nothing on the 8 Pro under our kernel). It boots slot B + again. EVERY reset spends one of slot B's three boot tries; at zero the + bootloader falls back to slot A and its first boot wipes userdata. Count + the boots since your last "bin/omamobile flash" (it gives B three again), + and when one is left, flash your known-good image set instead of resetting. + 3. Whether a reset puts the charger registers back is NOT known for husky: + keep the phone on a cable only while you watch it, and check the + 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. +TXT +} + +install_phone() { + phone 'command -v i2cget >/dev/null' || + die "i2c-tools missing on the phone: tools/phone-ssh 'pacman -S --needed --noconfirm i2c-tools'" + phone_in 'cat > /usr/local/bin/husky-deadman-phone && chmod 755 /usr/local/bin/husky-deadman-phone' \ + < "$ROOT/tools/husky-deadman-phone" || die "could not install the phone half" +} + +cmd="${1:-}"; shift || true +step= confirm= grace=60 soak=600 ilim=500000 nowd= noconfirm=0 allowsoc= +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 $? ;; + 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 + exit $rc ;; + noop|wd-drill|b3-charger) step="$cmd" ;; + *) usage 1 ;; +esac +while (($#)); do + case "$1" in + --confirm) confirm="${2:?}"; shift ;; + --grace) grace="${2:?}"; shift ;; + --ilim) ilim="${2:?}"; shift ;; + --soak) soak="${2:?}"; shift ;; + --allow-soc) allowsoc=--allow-soc ;; + --no-watchdog) nowd=--no-watchdog ;; + --no-confirm) noconfirm=1 ;; + *) usage 1 ;; + esac + shift +done +[[ -n "$confirm" ]] || confirm=90 +[[ $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" +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)" +fi +mkdir -p "$LOGDIR" +stamp=$(date +%Y%m%d-%H%M%S) +log="$LOGDIR/husky-$step-$stamp.log" + +# Kernel log on the desktop while the link lasts; reconnects after a drop. +# Its own session (setsid), with every fd pointed at the log, so stopping it +# kills the whole group (loop, ssh, reader) and nothing keeps our stdout or +# stderr open after we exit. +say "streaming the phone's kernel log to $log" +export SSH +setsid bash -c ' + while :; do + "$SSH" --fresh -T -o ServerAliveInterval=1 -o ServerAliveCountMax=3 \ + "exec cat /dev/kmsg" | + while IFS= read -r line; do printf "%s %s\n" "$(date +%T.%3N)" "$line"; done + echo "# $(date +%T.%3N) log stream ended"; sleep 2 + done' < /dev/null >> "$log" 2>&1 & +logger=$! +stop_logger() { kill -- -"$logger" 2>/dev/null || kill "$logger" 2>/dev/null; } +trap stop_logger EXIT +sleep 2 + +unit="husky-deadman-$step-$stamp" +args="run $step --confirm $confirm --grace $grace --soak $soak --ilim $ilim $nowd $allowsoc" +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 + else + setsid nohup /usr/local/bin/husky-deadman-phone $args >/dev/null 2>&1 < /dev/null & + fi" || die "could not start the step (nothing applied)" + +if ((noconfirm)); then + warn "--no-confirm: not confirming for ${confirm}s, so the phone undoes the step; confirming after that" +fi + +start=$(date +%s) +deadline=$(( start + confirm + grace + soak + 90 )) +dropped=0 confirmed=0 result= polls=0 +sleep 5 +while (( $(date +%s) < deadline )); do + if phone true 2>/dev/null; then + if ((!confirmed)) && { ((!noconfirm)) || (( $(date +%s) > start + confirm + 10 )); }; then + if out=$(phone 'husky-deadman-phone confirm' 2>/dev/null); then + confirmed=1 + echo; say "confirmed over a new SSH login after $(( $(date +%s) - start ))s ($out)" + 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 + 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=1 + fi + printf '.' + sleep 2 +done +echo + +rc=1 +case "$result" in + 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' + ;; + confirmed) + rc=4 + warn "the phone still says 'confirmed' but never finished the soak (deadline passed); check by hand" + phone 'husky-deadman-phone dump' || recovery + ;; + reverted) + rc=$(( noconfirm ? 0 : 3 )) + warn "step $step was UNDONE by the phone (no confirmation in time); the link is back" + phone 'tail -20 /var/log/husky-deadman.log' + ;; + refused*) + rc=5 + warn "the phone REFUSED to start $step, nothing was applied: ${result#refused: }" + ;; + tripped*) + rc=7 + warn "the GUARD tripped and the phone undid $step: ${result#tripped: }" + phone 'tail -20 /var/log/husky-deadman.log' + ;; + drill) + # the phone stopped feeding the watchdog: it must drop off and come back by itself + warn "wd-drill: waiting for the phone to go down (about 15 to 20 s)" + down=0 + t0=$(date +%s); while (( $(date +%s) < t0 + 120 )); do phone true 2>/dev/null || { down=1; break; }; sleep 2; done + if ((!down)); then + rc=8; warn "wd-drill FAILED: the phone never went down, the watchdog did not reset it" + else + say "the phone went down; waiting for it to come back" + up=0 + t0=$(date +%s); while (( $(date +%s) < t0 + 180 )); do phone true 2>/dev/null && { up=1; break; }; sleep 2; done + if ((!up)); then rc=4; warn "the phone did not come back in 3 minutes"; recovery + else + sleep 20 + say "back. uptime and modules:" + phone 'cut -d" " -f1 /proc/uptime; lsmod | grep -E "max77759|max17042" ; husky-deadman-phone dump' + upt=$(phone 'cut -d. -f1 /proc/uptime' 2>/dev/null) + if phone 'lsmod | grep -q "^max77759_charger "'; then rc=8; warn "max77759_charger is loaded after the reset" + elif ! [[ $upt =~ ^[0-9]+$ ]] || (( upt > 300 )); then rc=8; warn "uptime '$upt' s: the phone did not reboot, the link only dropped" + else rc=0; say "wd-drill OK: the watchdog reset the phone (uptime $upt s) and the charger stayed unloaded"; fi + fi + fi + ;; + reset) + rc=4 + warn "the phone is resetting itself (undo did not settle). Wait 2 minutes:" + recovery + ;; + failed*) + rc=6 + warn "step $step FAILED to apply on the phone and was undone; the link is fine" + phone 'tail -20 /var/log/husky-deadman.log' + ;; + *) + rc=4 + warn "no result from the phone (result='${result}'). If it does not answer within 2 minutes:" + recovery + ;; +esac +stop_logger +trap - EXIT +say "kernel log: $log" +exit $rc diff --git a/tools/husky-deadman-phone b/tools/husky-deadman-phone new file mode 100755 index 000000000..49530c3be --- /dev/null +++ b/tools/husky-deadman-phone @@ -0,0 +1,415 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# +# 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). +# +# 1. refuse unless the preconditions hold (nothing is applied if not); +# 2. arm the SoC watchdog (/dev/watchdog0 = 10060000.watchdog) with a feeder +# that stops feeding at a deadline; it stays armed through the soak; +# 3. save the charger registers, apply the step, log everything to /dev/kmsg +# and /var/log/husky-deadman.log first; +# 4. the guard reads the battery every 2 s and undoes the step on a breach; +# 5. no confirmation (a NEW SSH login on the desktop): undo, wait --grace for a +# confirmation; still nothing, or the module will not unload: stop feeding +# the watchdog, so the phone resets and boots with the charger blocked. +# +# THE UNDO ENDS WITH CHARGING OFF. Unloading max77759_charger does not stop +# charging (the driver has no .remove and leaves mode 0x5 on), so the undo +# restores the saved current/voltage/input limits and then sets the mode to +# 0x4 (BUCK_ON: the phone runs from USB, the battery is not charged), through +# OFF. The mode that was saved is only logged. After an undo reboot before +# another b3-charger: the MFD's register cache no longer matches the chip. +# +# Usage (normally started by tools/husky-deadman): +# husky-deadman-phone run STEP [--confirm S] [--grace S] [--ilim UA] [--soak S] +# [--no-watchdog] [--allow-soc] +# husky-deadman-phone confirm | undo STEP | dump | status +# +# STEP: noop | b3-charger | 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. +# +# The only charger writes are in restore_charger (the undo path). +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 +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 +gpid= + +# 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 +# Preconditions +SOC_MIN=30 SOC_MAX=80 START_V_MAX=4150000 START_T_MIN=100 START_T_MAX=400 +ILIM_MAX=900000 + +log() { + local m="husky-deadman: $*" + echo "$m" > /dev/kmsg 2>/dev/null + echo "$(date '+%F %T') $m" >> "$LOG" 2>/dev/null + echo "$m" +} + +i2c_bus() { + local d + for d in /sys/bus/i2c/devices/i2c-*; do + if readlink -f "$d" | grep -q 10cb0000.i2c; then echo "${d##*-}"; return 0; fi + done + return 1 +} +BUS=$(i2c_bus) || BUS= +rd() { i2cget -f -y "$BUS" "$1" "$2" 2>/dev/null; } # rd ADDR REG +wr() { log "i2cset $1 reg $2 = $3"; i2cset -f -y "$BUS" "$1" "$2" "$3"; } +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 '; } + +# ---- 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). +SAVE_RESTORE="0xbb 0xbd 0xc2" +SAVE_ONLY="0xb9 0xbf 0xc5 0xcb" +save_charger() { + local r v + rm -f $D/charger.saved + for r in $SAVE_RESTORE $SAVE_ONLY; do + v=$(rd $CHG $r) + hexok "$v" || { log "cannot read charger register $r (got '$v')"; rm -f $D/charger.saved.tmp; return 1; } + echo "$r $v" >> $D/charger.saved.tmp + done + mv $D/charger.saved.tmp $D/charger.saved + log "saved charger registers: $(tr '\n' ' ' < $D/charger.saved)" +} + +# limits first, then the mode through OFF to BUCK_ON (0x4): the system runs +# from USB and the battery is not charged +restore_charger() { + local r v cur + if [[ -f $D/charger.saved ]]; then + while read -r r v; do + case " $SAVE_RESTORE " in *" $r "*) hexok "$v" && wr $CHG "$r" "$v" ;; esac + done < $D/charger.saved + log "saved mode was $(awk '$1 == "0xb9" {print $2}' $D/charger.saved) (not restored: undo leaves charging off)" + else + log "no saved charger registers: only the mode is set" + fi + cur=$(rd $CHG 0xb9) + hexok "$cur" || { log "cannot read mode (got '$cur'); writing 0x04 blind"; cur=0x00; } + wr $CHG 0xb9 $(printf '0x%02x' $(( cur & 0xf0 ))) + wr $CHG 0xb9 $(printf '0x%02x' $(( (cur & 0xf0) | 0x4 ))) + cur=$(rd $CHG 0xb9) + log "charger mode now $cur (0x4 = system from USB, no charging)" + hexok "$cur" && (( (cur & 0xf) == 4 )) +} + +# ---- preconditions: any failure means nothing is applied ---- +refuse() { log "refusing: $*"; echo "refused: $*" > $D/result; } + +preflight() { # preflight STEP + local v t s + tr '\0' '\n' < /proc/device-tree/compatible 2>/dev/null | grep -qx 'google,zuma-husky' || + { refuse "this is not a Pixel 8 Pro (device tree compatible is not google,zuma-husky)"; return 1; } + [[ -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; } + [[ $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; } + # 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 || + { refuse "max77759_charger is not blocked in modprobe.d (blacklist, or install ... /bin/false): a reset would not boot with the charger blocked"; return 1; } + 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; } + 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; } + (( v <= START_V_MAX )) || { refuse "voltage_now $v uV is above $START_V_MAX uV: too full to start"; return 1; } + (( t >= START_T_MIN && t <= START_T_MAX )) || { refuse "temp $t (0.1 C) outside $START_T_MIN..$START_T_MAX"; return 1; } + # a sensor stuck at the 22.0 C default would let the temperature guard pass blind + if [[ $t == 220 && -z ${ALLOW_STUCK_TEMP:-} ]]; then + refuse "temp is exactly 22.0 C: treated as a stuck sensor (set ALLOW_STUCK_TEMP=1 to accept)"; return 1 + fi + if ((!allow_soc)) && (( s < SOC_MIN || s > SOC_MAX )); then + refuse "capacity $s % outside $SOC_MIN..$SOC_MAX % (--allow-soc to override)"; return 1 + fi + return 0 +} + +# ---- steps ---- +apply() { + case "$1" in + noop|wd-drill) log "step $1: nothing to apply" ;; + b3-charger) + save_charger || return 1 + touch $D/b3-done + log "modprobe max77759_charger default_ilim_ua=$ilim temp_guard=1 guard_psy=max170xx_battery" + modprobe --ignore-install max77759_charger default_ilim_ua="$ilim" temp_guard=1 guard_psy=max170xx_battery || return 1 + 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; } ;; + *) log "unknown step $1"; return 1 ;; + esac +} + +# revert STEP; returns 1 if the module would not unload (caller must reset) +revert() { + log "reverting step $1 (udc $(udc_state))" + case "$1" in + b3-charger) + log "modprobe -r max77759_charger" + modprobe -r max77759_charger + if charger_loaded; then + log "max77759_charger did NOT unload; forcing charging off anyway" + restore_charger + return 1 + fi + restore_charger || { log "charging is NOT confirmed off (mode readback is not 0x4)"; return 1; } ;; + esac + 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 + while :; do + v=$(psy voltage_now); t=$(psy temp); i=$(psy current_now) + 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 + elif (( v < V_MIN )); then echo "voltage $v uV < $V_MIN (not sane)" > $D/trip; return 1 + elif (( t > T_MAX )); then echo "temp $t > $T_MAX (0.1 C)" > $D/trip; return 1 + elif (( t < T_MIN )); then echo "temp $t < $T_MIN (0.1 C)" > $D/trip; return 1 + elif (( i > I_TRIP )); then echo "charging current $i uA > $I_TRIP" > $D/trip; return 1 + elif (( i < -I_TRIP )); then echo "discharge current $i uA < -$I_TRIP" > $D/trip; return 1 + fi + else + 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 + done +} + +# kill the guard so it can neither trip a later run nor outlive this one +guard_kill() { + [[ -n "$gpid" ]] && { kill "$gpid" 2>/dev/null; wait "$gpid" 2>/dev/null; } + gpid= + if [[ -f $D/guard.pid ]]; then + kill "$(cat $D/guard.pid)" 2>/dev/null + rm -f $D/guard.pid + fi +} + +# ---- watchdog (feeder as in usbc-deadman-phone) ---- +wd_arm() { + echo $(( $(date +%s) + confirm_s + 30 )) > $D/deadline + rm -f $D/disarm $D/wd + ( + exec 3>$WD || exit 1 + echo armed > $D/wd + said=0 + while :; do + if [[ -e $D/disarm ]]; then printf V >&3; echo disarmed > $D/wd; exit 0; fi + if (( $(date +%s) >= $(cat $D/deadline 2>/dev/null || echo 0) )); then + if ((!said)); then + echo "husky-deadman: watchdog deadline passed, no longer feeding: reset in ~15 s" > /dev/kmsg + sync; said=1 + fi + sleep 2; continue # still looks for disarm, but does not feed + fi + said=0 + printf k >&3 + sleep 2 + done + ) & + sleep 1 + [[ $(cat $D/wd 2>/dev/null) == armed ]] +} +wd_extend() { ((use_wd)) && echo $(( $(date +%s) + $1 )) > $D/deadline; } +wd_disarm() { # waits (bounded) until the feeder wrote the magic close + ((use_wd)) || return 0 + touch $D/disarm + local i + for i in $(seq 1 12); do + [[ $(cat $D/wd 2>/dev/null) == disarmed ]] && break + sleep 1 + done + [[ $(cat $D/wd 2>/dev/null) == disarmed ]] && log "watchdog: disarmed" || + log "WARNING: the watchdog feeder did not confirm the magic close (state '$(cat $D/wd 2>/dev/null)'); a reset may follow" +} +wd_holders() { + local f p out= + for f in /proc/[0-9]*/fd/*; do + [[ $(readlink "$f" 2>/dev/null) == /dev/watchdog* ]] || continue + p=${f#/proc/}; p=${p%%/*} + out+="$(cat /proc/$p/comm 2>/dev/null)[$p]; " + done + echo "${out:-nobody visible}" +} + +final_reset() { + log "=== step $1: could not settle (udc $(udc_state), charger loaded: $(charger_loaded && echo yes || echo no)); resetting" + echo reset > $D/result + sync + if ((use_wd)); then wd_extend 0; sleep 40; fi + log "still alive: crashing (panic=10 reboots)" + sync + echo c > /proc/sysrq-trigger +} + +wait_confirm() { # wait_confirm SECS; 0 confirmed, 1 timeout, 2 guard trip + local end=$(( $(date +%s) + $1 )) + while (( $(date +%s) < end )); do + [[ -e $D/confirm ]] && return 0 + [[ -e $D/trip ]] && return 2 + if [[ -n "$gpid" ]] && ! kill -0 "$gpid" 2>/dev/null; then + echo "guard process died" > $D/trip; return 2 + fi + sleep 1 + done + return 1 +} + +# undo after a trip; always ends with a result and the watchdog settled +trip_undo() { # trip_undo STEP + local why + why=$(cat $D/trip 2>/dev/null) + log "GUARD TRIP: $why; undoing $1" + guard_kill + wd_extend $(( grace_s + 20 )) + if revert "$1"; then + echo "tripped: $why" > $D/result + wd_disarm + return 1 + fi + final_reset "$1" + return 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)" + 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; } + log "watchdog armed" + fi + if [[ $step == wd-drill ]]; then + log "wd-drill: no longer feeding the watchdog on purpose; the phone must reset in about 15-20 s" + echo drill > $D/result; sync; wd_extend 0; sleep 90 + log "wd-drill: STILL ALIVE after 90 s, the watchdog did not reset the phone" + echo "failed: watchdog did not reset the phone" > $D/result + wd_extend 60; wd_disarm + return 1 + fi + if ! apply "$step"; then + log "apply failed: reverting now" + wd_extend $(( grace_s + 20 )) + if revert "$step"; then + echo "failed: step $step did not apply and was undone; see $LOG" > $D/result + wd_disarm + return 1 + fi + final_reset "$step" + return 1 + fi + guard & + gpid=$! + echo "$gpid" > $D/guard.pid + wait_confirm "$confirm_s"; rc=$? + if (( rc == 2 )); then trip_undo "$step"; return 1; fi + if (( rc == 0 )); then + log "step $step confirmed; the guard and the watchdog keep running for ${soak_s}s" + echo confirmed > $D/result + local end=$(( $(date +%s) + soak_s )) + while (( $(date +%s) < end )); do + if [[ -e $D/trip ]]; then trip_undo "$step"; return 1; fi + if ! kill -0 "$gpid" 2>/dev/null; then + echo "guard process died" > $D/trip; trip_undo "$step"; return 1 + fi + wd_extend 60 # the feeder only runs out if this loop dies + sleep 2 + done + guard_kill + if [[ -e $D/trip ]]; then trip_undo "$step"; return 1; fi + wd_disarm + log "=== step $step SOAKED clean; left applied" + echo soaked > $D/result + return 0 + fi + log "no confirmation within ${confirm_s}s" + guard_kill + wd_extend $(( grace_s + 20 )) + if ! revert "$step"; then final_reset "$step"; return 1; fi + if wait_confirm "$grace_s"; then + wd_disarm + log "=== step $step REVERTED, link back (udc $(udc_state))" + echo reverted > $D/result + return 1 + fi + final_reset "$step" +} + +dump() { + local r + echo "i2c bus ${BUS:-none}; udc $(udc_state); 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 + fi +} + +cmd="${1:-}"; shift || true +step= +case "$cmd" in + run|undo) step="${1:?STEP}"; shift ;; +esac +while (($#)); do + case "$1" in + --confirm) confirm_s="${2:?}"; shift ;; + --grace) grace_s="${2:?}"; shift ;; + --ilim) ilim="${2:?}"; shift ;; + --soak) soak_s="${2:?}"; shift ;; + --no-watchdog) use_wd=0 ;; + --allow-soc) allow_soc=1 ;; + *) echo "unknown option $1" >&2; exit 1 ;; + esac + shift +done + +mkdir -p $D +case "$cmd" in + run) run "$step" ;; + confirm) touch $D/confirm; echo "confirmed $(date +%T)" ;; + 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 ;; +esac