diff --git a/device/husky/BATTERY-NOTES.md b/device/husky/BATTERY-NOTES.md index 80d4e8dac..d84356131 100644 --- a/device/husky/BATTERY-NOTES.md +++ b/device/husky/BATTERY-NOTES.md @@ -25,7 +25,7 @@ Nothing in this document contains a serial number, IMEI, MAC address, IP address ## 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. +All of this is from Google's GPL kernel source and reads on the phone. The gauge model nodes come from Google's public, GPL-2.0-only `dts/zuma-husky-battery-data.dtsi` in the shusky device tree repository (`kernel/devices/google/shusky`, branch `android-gs-shusky-6.1-android16`, [source](https://android.googlesource.com/kernel/devices/google/shusky/+/refs/heads/android-gs-shusky-6.1-android16/dts/zuma-husky-battery-data.dtsi)). It is the husky file: the Pixel 8 has a smaller pack and its own model nodes, do not use those for husky. The clocks are from `android-gs-shusky-6.1-android16`, the gauge and charger drivers from the shusky `bms` repository. The bus, interrupt and pin facts below were read from the stock device tree (the husky `ov8` overlay, the retail MP one with the 4950 mAh pack) when this work was done; the gauge overlays no longer depend on it, they regenerate from the public file above (section 5.7). - **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. @@ -96,8 +96,8 @@ Evidence from a sibling: on a Pixel 7, nesmeck's kernel PR #171 reports the same 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.) +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 `maxim,default-a1-0k` node by `tools/gen-gauge-overlay.py` (today straight from the public `zuma-husky-battery-data.dtsi`, section 2, whose values are already u16 words; the first version read a decompiled stock overlay, where the table is u32 cells split into two u16, high half first, and the parameters a byte list read as big-endian u16 in the order of `struct max77759_fg_params`), so no number is typed by hand. Regenerated from the public file on 2026-11-01, the overlay came out the same apart from its header comment (section 5.7). +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 in husky's decompiled stock overlay (`ov8`) are `default-fake-batt` (ID 170, Google's dummy), `atl-a1-1k` and `cos-a1-2k`; `lsn-a1-3k` (ID 3) appears only in other entries of the stock dtbo image (`ov9` to `ov18`, other boards), and the public dtsi has the three real husky models only (5.7). (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. @@ -113,19 +113,36 @@ Result, verified: dmesg `max17042 0-0036: battery model loaded (DesignCap 0x994, **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. +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` (170 is in husky's `ov8` and ID 3 only in other boards' entries of the stock dtbo image, `ov9` to `ov18`; the public husky dtsi carries only IDs 0, 1 and 2, section 5.7). 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. +The overlay for this is `gauge-model-atl.dtso`, generated by `tools/gen-gauge-overlay.py` from Google's `maxim,atl-a1-1k` node (model version 5, DesignCap 0x09cf; from the public `zuma-husky-battery-data.dtsi`, section 2 and 5.7). 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. +### 5.7 The overlays regenerated from Google's public file, and the other model nodes + +Derek's review of #249 asked for a source anyone can fetch. `tools/gen-gauge-overlay.py` now reads Google's `dts/zuma-husky-battery-data.dtsi` (section 2) directly; it still accepts a decompiled stock overlay. Run on 2026-11-01 against the file fetched from the branch `android-gs-shusky-6.1-android16`: + +- `gen-gauge-overlay.py zuma-husky-battery-data.dtsi atl-a1-1k OUT` and `cmp` against `device/husky/overlays/gauge-model-atl.dtso` as committed in #249: identical, byte for byte. The same for `default-a1-0k` against `gauge-model.dtso` (`diff`): identical. Both overlays were then regenerated into the tree so their header comment names the public file; with comments stripped, the new and the old files are identical, so the properties the phone booted with did not change. +- `gen-gauge-overlay.py --compare zuma-husky-battery-data.dtsi gauge-model-atl.dtso gauge-model.dtso`: each model node of the file against each overlay in the tree, counting the table words (48) and the parameter words (27) that differ. + +The public file has three model nodes, `default-a1-0k`, `atl-a1-1k` and `cos-a1-2k`. It has no `default-fake-batt` (which husky's decompiled `ov8` has) and no `lsn-a1-3k` (which `ov8` does not have either; it is in other boards' entries of the stock dtbo image, `ov9` to `ov18`), so a pack with EEPROM ID 3 has no model in this source. The script's limits: it takes a node to end at the first line holding only `};`, and expects 48 table words and 27 or 28 parameters, else it stops with a message. + +| Node (`maxim,batt-id-kohm`) | vs `gauge-model-atl.dtso` | vs `gauge-model.dtso` | +| --- | --- | --- | +| `default-a1-0k` (0) | different: 48/48 table words, 16/27 parameters (RelaxCFG, FullCAPRep, DesignCap, dPacc, dQacc, FullCAPNom, the four QResidual, RCOMP0, TempCo, ICHGTerm, MiscCFG, AtRate, FilterCFG) | identical | +| `atl-a1-1k` (1) | identical | different: 48/48 table words, the same 16 parameters | +| `cos-a1-2k` (2) | different: 30/48 table words, 7/27 parameters (FullCAPRep, DesignCap, dQacc, FullCAPNom, QResidual00, QResidual10, TempCo); DesignCap 0x09c4 | different: 48/48 table words, the same 16 parameters | + +So of the 16 parameters where ATL differs from the generic model, ATL and COS share nine (RelaxCFG, dPacc, QResidual20, QResidual30, RCOMP0, ICHGTerm, MiscCFG, AtRate, FilterCFG) and differ in the other seven. `--compare` also prints each node's DesignCap and the table words the overlay and the node have in common: ATL and COS agree in words 0-1 (0xa500 0xb790) and 32-47 (all 0x0200); the generic model has 0x0100 in 32-47 and DesignCap 0x0994. The 11 parameters outside the 16 (IAvgEmpty, LearnCFG, Config, Config2, FullSOCthr, V_empty, TGain, TOff, Curve, convgcfg, TaskPeriod) are the same in all three nodes. The file also carries `maxim,batt-id-kohm`, `maxim,model-version`, `maxim,rc1-tempco`, `maxim,force-reset-model-data` and `maxim,fg-aafv` per node; the overlays carry only the table and the parameters. No COS overlay was generated or booted: this phone's pack is ATL. + ## 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. @@ -225,7 +242,7 @@ So the layout is consistent with husky's [verified, read-only, on files]: the ma ## 12. Files -In this repository: `device/husky/overlays/battery-clk-test.dtso`, `battery-i2c-test.dtso`, `gauge-model.dtso`, `gauge-model-atl.dtso`, `pack-eeprom-test.dtso` (all under `device/husky/overlays/`), `tools/gen-gauge-overlay.py`, `tools/husky-deadman`, `tools/husky-deadman-phone`, and the package changes (USB rescue, blocklist) in #250. Kernel side: kernel #163 (the bus) and #154 (panel size, which the on-screen keyboard needs). +In this repository: `device/husky/overlays/battery-clk-test.dtso`, `battery-i2c-test.dtso`, `gauge-model.dtso`, `gauge-model-atl.dtso`, `pack-eeprom-test.dtso` (all under `device/husky/overlays/`), `tools/gen-gauge-overlay.py` (reads Google's public `zuma-husky-battery-data.dtsi`, section 5.7), `tools/husky-deadman`, `tools/husky-deadman-phone`, and the package changes (USB rescue, blocklist) in #250. Kernel side: kernel #163 (the bus) and #154 (panel size, which the on-screen keyboard needs). Kept locally, available on request, no serials: the dead-man tool's per-run kernel logs, the gauge test logs (including the interrupt log for #170), the charge-watch logs, and the `tools/phone-smoke` report from this kernel. diff --git a/device/husky/overlays/gauge-model-atl.dtso b/device/husky/overlays/gauge-model-atl.dtso index 2a47850d7..a05eca462 100644 --- a/device/husky/overlays/gauge-model-atl.dtso +++ b/device/husky/overlays/gauge-model-atl.dtso @@ -3,11 +3,13 @@ * 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. + * an unknown pack), 1 atl-a1-1k, 2 cos-a1-2k. Generated by tools/gen-gauge-overlay.py + * from Google's public, GPL-2.0-only dts/zuma-husky-battery-data.dtsi (kernel/devices/ + * google/shusky, branch android-gs-shusky-6.1-android16, + * https://android.googlesource.com/kernel/devices/google/shusky/+/refs/heads/android-gs-shusky-6.1-android16/dts/zuma-husky-battery-data.dtsi): + * maxim,fg-model = that node's 48 u16 table words, maxim,fg-params = its parameter + * 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/; diff --git a/device/husky/overlays/gauge-model.dtso b/device/husky/overlays/gauge-model.dtso index 5bbf1cf31..cc4ce6f15 100644 --- a/device/husky/overlays/gauge-model.dtso +++ b/device/husky/overlays/gauge-model.dtso @@ -3,11 +3,13 @@ * 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. + * an unknown pack), 1 atl-a1-1k, 2 cos-a1-2k. Generated by tools/gen-gauge-overlay.py + * from Google's public, GPL-2.0-only dts/zuma-husky-battery-data.dtsi (kernel/devices/ + * google/shusky, branch android-gs-shusky-6.1-android16, + * https://android.googlesource.com/kernel/devices/google/shusky/+/refs/heads/android-gs-shusky-6.1-android16/dts/zuma-husky-battery-data.dtsi): + * maxim,fg-model = that node's 48 u16 table words, maxim,fg-params = its parameter + * 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/; diff --git a/tools/gen-gauge-overlay.py b/tools/gen-gauge-overlay.py index 0951e9a81..b18198574 100755 --- a/tools/gen-gauge-overlay.py +++ b/tools/gen-gauge-overlay.py @@ -1,41 +1,117 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: MIT -"""Generate device/husky/overlays/gauge-model.dtso from Google's stock husky devicetree. +"""Generate device/husky/overlays/gauge-model*.dtso from Google's husky battery 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 +Usage: gen-gauge-overlay.py SOURCE NODE OUT.dtso + gen-gauge-overlay.py --compare SOURCE OVERLAY.dtso... -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 + SOURCE Google's public, GPL-2.0-only dts/zuma-husky-battery-data.dtsi (kernel/devices/ + google/shusky, branch android-gs-shusky-6.1-android16), the file with the + "maxim, { maxim,fg-model ... maxim,fg-params ... }" nodes. A decompiled + stock overlay (dtc -I dtb -O dts of the factory dtbo, the husky ov8) still works: + there the table is 24 u32 cells and the parameters a byte list. + NODE the model node, e.g. default-a1-0k (Google's fallback for an unknown pack), + atl-a1-1k, cos-a1-2k + OVERLAY an overlay this tool wrote. --compare reads each model node of SOURCE and says, + per overlay, how many of the 48 table words and of the parameter words differ. + +Writes maxim,fg-model (48 u16) and maxim,fg-params (u16, 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 + +PARAM_NAMES = ["IAvgEmpty", "RelaxCFG", "LearnCFG", "Config", "Config2", "FullSOCthr", + "FullCAPRep", "DesignCap", "dPacc", "dQacc", "FullCAPNom", "V_empty", + "QResidual00", "QResidual10", "QResidual20", "QResidual30", "RCOMP0", "TempCo", + "ICHGTerm", "TGain", "TOff", "Curve", "MiscCFG", "AtRate", "convgcfg", + "FilterCFG", "TaskPeriod", "RSense"] + + +def strip_comments(text): + text = re.sub(r'/\*.*?\*/', ' ', text, flags=re.S) + return re.sub(r'//[^\n]*', '', text) + + +def config_block(text): + """The body of the maxim,config block (the model nodes live in it); the whole text when + there is none, as in a decompiled overlay. Limit: the block is taken to end at the first + line that is only '};' at its own indentation, which holds for Google's files.""" + m = re.search(r'maxim,config\s*\{(.*?)\n\};', text, re.S) + return m.group(1) if m else text + + +def node_names(text): + """The model nodes: every 'maxim, {' in the maxim,config block.""" + return re.findall(r'maxim,([\w-]+)\s*\{', config_block(strip_comments(text))) + + +def words(prop, body): + """The u16 words of one property: /bits/ 16 <...> as written; <...> without /bits/ taken + as u32 cells, each split into two u16 (high half first); [...] bytes paired big-endian.""" + m = re.search(r'maxim,' + prop + r'\s*=\s*(/bits/\s*16\s*)?(<([^>]*)>|\[([^\]]*)\])', body) + if not m: + sys.exit(f"no maxim,{prop} in the node") + if m.group(4) is not None: + b = [int(x, 16) for x in m.group(4).split()] + if len(b) % 2: + sys.exit(f"maxim,{prop}: odd byte list ({len(b)} bytes)") + return [(b[i] << 8) | b[i + 1] for i in range(0, len(b), 2)] + cells = [int(x, 16) for x in m.group(3).split()] + if m.group(1): + return cells + out = [] + for v in cells: + out += [(v >> 16) & 0xffff, v & 0xffff] + return out + + +def read_node(text, node): + text = strip_comments(text) + # Limit: the node body ends at the first line holding only '};' (no nested nodes). + m = re.search(r'maxim,' + re.escape(node) + r'\s*\{(.*?)\n\s*\};', text, re.S) + if not m: + sys.exit(f"no maxim,{node} node in the source") + model, params = words("fg-model", m.group(1)), words("fg-params", m.group(1)) + if len(model) != 48: + sys.exit(f"{node}: maxim,fg-model has {len(model)} words, expected 48") + if len(params) not in (27, 28): + sys.exit(f"{node}: maxim,fg-params has {len(params)} words, expected 27 or 28 (struct max77759_fg_params)") + return model, params + + +def ranges(idx): + """0 1 32-47 for [0, 1, 32, ..., 47].""" + out, i = [], 0 + while i < len(idx): + j = i + while j + 1 < len(idx) and idx[j + 1] == idx[j] + 1: + j += 1 + out.append(str(idx[i]) if i == j else f"{idx[i]}-{idx[j]}") + i = j + 1 + return " ".join(out) or "none" + + +def read_overlay(text): + text = strip_comments(text) + return words("fg-model", text), words("fg-params", text) + + +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)) + + +def render(node, model, pw): + return 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. + * an unknown pack), 1 atl-a1-1k, 2 cos-a1-2k. Generated by tools/gen-gauge-overlay.py + * from Google's public, GPL-2.0-only dts/zuma-husky-battery-data.dtsi (kernel/devices/ + * google/shusky, branch android-gs-shusky-6.1-android16, + * https://android.googlesource.com/kernel/devices/google/shusky/+/refs/heads/android-gs-shusky-6.1-android16/dts/zuma-husky-battery-data.dtsi): + * maxim,fg-model = that node's 48 u16 table words, maxim,fg-params = its parameter + * 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/; @@ -50,5 +126,44 @@ def fmt(ws): return "\n".join("\t\t\t" + " ".join("0x%04x" % w for w in ws[i:i + >; }}; }}; -""") +""" + + +def compare(src, overlays): + text = open(src).read() + nodes = node_names(text) + print("nodes in", src + ":", " ".join(nodes)) + for node in nodes: + model, params = read_node(text, node) + print(f"{node}: DesignCap {params[7]:#06x}, table words 0-1 {model[0]:#06x} {model[1]:#06x}," + f" words 32-47 {' '.join(f'{w:#06x}' for w in sorted(set(model[32:])))}") + for ov in overlays: + omodel, oparams = read_overlay(open(ov).read()) + for node in nodes: + model, params = read_node(text, node) + if len(omodel) != len(model) or len(oparams) != len(params): + print(f"{ov} vs {node}: different, lengths differ (overlay {len(omodel)} table and" + f" {len(oparams)} parameter words, node {len(model)} and {len(params)})") + continue + eq = [i for i, (a, b) in enumerate(zip(model, omodel)) if a == b] + dm = len(model) - len(eq) + dp = [PARAM_NAMES[i] for i in range(max(len(params), len(oparams))) + if i >= len(params) or i >= len(oparams) or params[i] != oparams[i]] + verdict = "identical" if not dm and not dp else "different" + line = f"{ov} vs {node}: {verdict}, model {dm}/{len(model)} words differ, params {len(dp)}/{len(params)}" + if dp: + line += " (" + " ".join(dp) + ")" + if dm: + line += f"; equal table words: {ranges(eq)}" + print(line) + + +if len(sys.argv) >= 3 and sys.argv[1] == "--compare": + compare(sys.argv[2], sys.argv[3:]) + sys.exit(0) +if len(sys.argv) != 4: + sys.exit(__doc__) +src, node, out = sys.argv[1], sys.argv[2], sys.argv[3] +model, pw = read_node(open(src).read(), node) +open(out, "w").write(render(node, model, 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]))