diff --git a/device/cheetah/MODEM-PLAN.md b/device/cheetah/MODEM-PLAN.md index 608b9caa4..0d5bcf201 100644 --- a/device/cheetah/MODEM-PLAN.md +++ b/device/cheetah/MODEM-PLAN.md @@ -12,10 +12,13 @@ carrier manifest, the APNs and the bearer order chosen from the SIM (`omamobile-modem-sit` 0.3.30, `omamobile-device-cheetah` 0.1.44), and `omamobile-modem-boot.target` on by default from `omamobile-device-cheetah` 0.1.43 (M4.6b, B6-B9b passed, #398). Kernel `7.3.0-rc6-omamobile-g2219cc6cda77`, the release kernel. -Open: suspend with the modem up (section 6.3; the stack holds a sleep -inhibitor), other networks, cpif's `oem_ipc0` "is not opened" lines after -sitd starts (nothing opens the OEM IPC channel), and the UFS error-handler -pass at a modem power-off (M2.6). The day's evidence: [NOTES](NOTES.md), +Open: suspend with the modem up (section 7, M6: M6.0-M6.3 run on a second +Pixel 7 Pro with an SMS wake; the call half, M6.4 and M6.5 open; the stack +holds a sleep inhibitor unless `/etc/omamobile/modem-suspend-enable` exists +beside device-cheetah's `/usr/lib/omamobile-modem/suspend-runbook`), other +networks, cpif's `oem_ipc0` "is not opened" lines after sitd starts +(nothing opens the OEM IPC channel), and the UFS error-handler pass at a +modem power-off (M2.6). The day's evidence: [NOTES](NOTES.md), 2026-11-03. Earlier status (2026-10-13): **IPC works: the CP serves SIT (M4.1h passed).** @@ -3512,3 +3515,300 @@ coherency on before DMA (`cp_set_iocc()` at `link_up`); write-back mappings of the cacheable regions; no CPU mapping of AoC voice SRAM; no `remove()` for cpif; panics turned into errors. + +## 7. M6: suspend with the modem online (plan and first runs, 2026-11-09) + +Status: **M6.0-M6.3 run on a second Pixel 7 Pro (a contributor's, not the +maintainer's phone), on an LTE SIM with data and SMS but no voice (7.4): +the phone freezes with the modem up and wakes for an SMS, with K1-K1c. +Open: the call half of M6.3, M6.4, M6.5, and all of it on the maintainer's +phone. The screen state is off by default; the runbook turns it on +(`[control] follow_screen = yes`, M6.1b). Each step in 7.3 says who runs +it; M6.4 on the contributor's phone waits for the maintainer.** +Android sleeps with the modem up: the CP keeps +its registration and wakes the AP for a call, an SMS or data. Ours holds +`omamobile-modem-inhibit` from the modem's start to the reboot, so a phone +with the stack on (the default since device-cheetah 0.1.43) never sleeps +and runs warm. This section is the way to lift that, staged. + +### 7.1 What is already there + +- **CPIF's side is stock's** (gs-6.1, imported in `610ba27d9`), in + `drivers/soc/google/cpif/` on `omamobile`: + - `modem_suspend`/`modem_resume` as noirq sleep ops (`modem_main.c` + :942-973), and `suspend_cp()` refuses with -EBUSY while CP2AP_WAKEUP is + high (`modem_ctrl_s5100.c` :2007-2021; section 6.3); + - at suspend it writes `ap2cp_kerneltime` and drives AP2CP_PDA_ACTIVE low, + at resume high again (:2024-2061); + - the PM notifier and the deferred cp2ap work across the suspend window + (:2064-2104, :329-344); + - CP2AP_WAKEUP (gpa8-3) is a level IRQ with `enable_irq_wake()` + (`modem_utils.c` :530, :569), from `gpiod_to_irq()`, armed at + `complete_normal_boot`; gpa8 is a far-alive wakeup EINT bank, so no DT + `wakeup-source` is needed. Keep the bootloader's pull-up (section 6.3); + - a wake lock held while the PCIe link is up (:1889-1893, released at + the idle power-down :1819-1820), so s2idle can only begin with the link + down, as stock: stock does no link-down at suspend either, it happens + at runtime when the CP drops CP2AP_WAKEUP (M4.1h). +- **The modem's reports with the screen off** (omamobile-modem-sit, only + with `[control] follow_screen = yes`, off by default): sitd sends + SET_SCREEN_STATE and SET_IND_CMD_FILTER when the panel goes off or on. On + the contributor's phone (2026-11-09, idle, registered): 47 indications a + minute with the screen state on (all 0x0906), none with it off. Each one + wakes the AP and the link. + +### 7.2 What is missing + +| What | Where | For | Note | +|---|---|---|---| +| K1: noirq sleep ops in the link driver ([linux-omarchy-mobile#232](https://github.com/derekross/linux-omarchy-mobile/pull/232), with K1b and K1c) | `drivers/pci/controller/dwc/pcie-gs201-cp.c` (none today, driver struct :1975-1985) | M6.2 | `suspend_noirq`: refuse with -EBUSY and a log line if the link is up or the PHY isn't isolated (PMU 0x3ec0, through the SMC regmap); otherwise nothing. `resume_noirq`: a log line. Stock's RC only isolates a down link there (`pcie-exynos-rc.c` :5823-5935), which ours already does at every `link_down`. Without it the PCI core may put the root port in D3hot on a live link: our endpoint driver has no PM ops (inferred from `pci-driver.c` :917-950). K1b and K1c, found in M6.2 and M6.3 (7.4): the root port is `PCI_DEV_FLAGS_NO_D3` and the modem's `d3cold_delay` 0, or a sleep with the link down leaves the modem disconnected | +| K2: power-down pin states for the AP2CP outputs | the cpif overlay (`modem-cpif-test.dtso`) | only if needed | stock: gph0-2/3, gph1-1/2/3/6 with `pin-con-pdn` 3 (keep the level), no pull. Needed only if HSI1's pads lose their state in s2idle: check first (M6.0) | +| U1: a conditional inhibitor | `omamobile-modem-inhibit.service` | M6.2 | Skipped only when `/etc/omamobile/modem-suspend-enable` exists beside `/usr/lib/omamobile-modem/suspend-runbook`, which only device-cheetah ships (two triggering `ConditionPathExists=|!` lines); the start script's check that the lock is held follows the same two files, so on the 9a or the 6 Pro the owner's file alone changes nothing. Calls keep `omamobile-call-watch`'s inhibitor | +| U2: the screen state told before a sleep | `omamobile-modem-sit`'s systemd-sleep hook | M6.4 | found in M6.3 (7.4): `systemctl suspend` with the panel lit froze before sitd's 2 s backlight check told the modem "off". With `follow_screen = yes`, the hook asks sitd for "off" with a 10 s hold before every sleep; after the wake sitd's own check restores "on" if the panel is lit. A call refuses it, and the sleep goes ahead either way | +| Later | | | the AP-suspend-during-call path (section 2, not ported), MSI as a wake source (only if the link ever stays up in sleep), ACPM's pcieon sleep mode (deep sleep only) | + +Never power the CP off for sleep: every CP power-off costs a UFS +error-handler pass (M2.5), and stock doesn't either. + +### 7.3 Runbook (attended, on the charger, one change per boot) + +Who runs it: a sleep with the modem up on a 7 Pro is the maintainer's +attended test until M6 is qualified (AGENTS.md). M6.0 is read-only and +anyone's; M6.1 is a push the human approves; M6.1b to M6.5 are the +maintainer's. The contributor's runs in 7.4 came before that rule. + +Before each step: the NV checksum check (AGENTS section 1), `spm_lvl` 5, +the modem registered (`omamobile-sit status`), and after each wake +`dmesg | grep -cE 'ufshcd_err_handler|I/O error'` (stop on any new line). +NFC polling stopped for M6.2-M6.3 (`systemctl stop neard`), so a hang can't +be the 9a's NFC case again. + +**M6.0, read-only (low).** On the current kernel, modem up: +`grep -i cp2ap /proc/interrupts`, then `/sys/kernel/irq//wakeup` must +read `enabled`; `cat /sys/power/wakeup_count`; the link's idle cycles in +the log over 10 minutes with the screen off (0.3.32's filter on); HSI1's +gph0/gph1 CON and PUD read once, one controller (AGENTS gs201 pinctrl +note), to decide K2. Stop: a read error or an abort. + +**M6.1, K1 (medium).** Build `omamobile-modem-suspend` (off `omamobile`), +`W=1` and checkpatch clean; the human pushes it. Expect: nothing changes +awake (the stack comes up, registers, idle cycles as before). Rollback: +`omamobile-boot-update write` or the saved slot B. Stop: the modem doesn't +reach ONLINE. + +**M6.1b, the screen state on (low, the maintainer).** M6.2 to M6.5 need +it: every result in 7.4 was taken with sitd following the screen. Add +`[control]` `follow_screen = yes` to `/etc/omamobile/modem-sit.conf`, and +reboot. Expect: with the panel off, `journalctl -u omamobile-sitd` shows +SET_SCREEN_STATE off, and the modem's indications stop (none a minute, +against about 47 with it on). Undo: remove the line, reboot. Stop: a +refused request, or a call missed with the screen dark. + +**M6.2, the first freeze with the modem up (high, attended, the maintainer).** +`touch /etc/omamobile/modem-suspend-enable`, reboot, wait for +registration, screen off. Then a detached RTC freeze logged to UFS +(SUSPEND-PLAN "Common setup", `freeze_cmd m6-2 30`). +- Pass: woke at 30 s; `suspend_stats/fail` unchanged; the log has + "Suspend prepare", AP2CP_PDA_ACTIVE 0 then 1; `cpif` still ONLINE, + `omamobile-sit status` registered, a ping over `rmnet` works; no UFS line. +- A refused suspend (-EBUSY from CPIF or K1) is a pass for safety and a + finding: record which and why, then stop. +- Stop: no wake in 2 minutes. Don't send commands; the human holds Power + about 30 s, then Power. Then `rm /etc/omamobile/modem-suspend-enable` + and reboot. + +**M6.3, the network wakes the phone (high, the maintainer).** As M6.2 with a 300 s RTC +alarm; from another phone, an SMS at about 60 s, then (next cycle) a call. +Pass: the wake comes before the alarm, from the cp2ap IRQ (`omamobile-sleep`'s +wake IRQ line), the SMS reaches the inbox, the call rings in the Phone app. + +**M6.4, a loop (medium, the maintainer; on hold on the contributor's +phone).** 20 RTC cycles of 30 s, then an hour asleep with +the link's idle cycles; UFS clean throughout, the registration kept. + +**M6.5, a day (the maintainer).** With the shell's auto-sleep toggle on, as +SUSPEND-PLAN P6. After that the default (the enable file shipped, or the +condition dropped) is the maintainer's call. + +Rollback at any step: `rm /etc/omamobile/modem-suspend-enable` and reboot +(the inhibitor is back from the next modem start). + +### 7.4 Results + +All of M6.0-M6.3 ran on a second Pixel 7 Pro (a contributor's), attended +and on the charger, NFC polling stopped, with an LTE SIM that has data and +SMS but no voice. Every freeze below went straight to `/sys/power/state` +(`rtcwake -m freeze`), which skips the `system-sleep` hooks and systemd's +inhibitors, so these runs exercised neither U1's inhibitor change nor U2's +hook: M6.4 runs some cycles through `systemctl suspend` for that, refused +without the enable file and allowed with it. + +**M6.0, 2026-11-09** (`7.3.0-rc6-omamobile-push1-g0e3da55c9e9f`, modem up): +cp2ap_wakeup is a gpa8-3 level IRQ with `wakeup` enabled; the MSIs +(`mif_cp2ap_msg`, `mif_cp2ap_status`) are not wake-armed. `mem_sleep` +s2idle, `spm_lvl` 5, no UFS line. The pinctrl debugfs lists no pin +configurations for HSI1, so K2 stays open until a freeze shows a need. + +**M6.1, 2026-11-09** (`…-g2f2f0b979337`, K1 on the RTC power-off commit): +the stack came up, registered on LTE with IMS voice and SMS, idle cycles as +before. + +**M6.2 run 1, 2026-11-09** (`…-g2f2f0b979337`): the freeze was taken with +the link down (`sleep: link down, PMU 0x3ec0 = 0x0`) and woke on the RTC at +30 s, `suspend_stats` success 1, fail 0, no UFS line. But the modem was lost +after the wake. The PCI core had tried the root port into D3hot with its +configuration space unreachable: + +``` +pcieport 0001:00:00.0: Unable to change power state from D0 to D3hot, device inaccessible +pcieport 0001:00:00.0: Unable to change power state from D3cold to D0, device inaccessible +pcieport 0001:00:00.0: Data Link Layer Link Active not set in 100 msec +``` + +The failed D3hot left the port marked D3cold, so resume waited 100 ms for a +link that only comes back when CPIF asks for it, then marked the modem +disconnected (`pci_pm_bridge_power_up_actions()`). CPIF raised the link 3 s +later, but every kernel config read of the modem returned 0xffff (a read +from user space still saw the vendor ID), so no doorbell went through +(`BME is not set`, `LINK_DOWN … retry pcie poweron`) and sitd timed out. +The unit's clean stop worked (`modem-up` removed, no UFS line). Fix, +K1b: the root port gets `PCI_DEV_FLAGS_NO_D3` at the first scan, so it +stays in D0 and the core skips its bus PM in s2idle (`skip_bus_pm`). + +**M6.2 run 2, 2026-11-09** (`…-g75876b951a19`, K1 + K1b): pass, with one +finding. Before: a ping over `rmnet0` 3/3. The freeze was taken with the +link down and ended early, about 7 s in, on the cp2ap_wakeup IRQ +(`pm_wakeup_irq`; `ap_wakeup_handler: cp2ap_wakeup work pending`), with +sitd's screen state off since well before. After: `suspend_stats` success +1, fail 0, the link up again on CPIF's request, a ping over `rmnet0` 3/3 at +10 s and at 30 s, sitd's polls answered, no UFS line. The modem itself can +wake the phone, which is what M6.3 needs; what it had to say 7 s in isn't +logged yet. Left over: resume still prints "Unable to change power state +from D3hot to D0" for the modem and "from D3cold to D0" for the root port, +without consequence this time; read where that state comes from before +M6.4. + +**M6.3 run 1, 2026-11-09** (`…-g75876b951a19`): failed at the wake. The +freeze (a 300 s alarm) ended after 24 s on cp2ap_wakeup, and the modem +was disconnected again: run 2's resume had left the root port marked +D3cold (a failed power-up read with the link down: "Unable to change +power state from D3cold to D0"), so this resume waited for the link +("Data Link Layer Link Active not set in 100 msec") and dropped the modem, +as in M6.2 run 1. K1b alone only covers the first sleep of a boot. Fix, +K1c: the devices below the root port get a zero `d3cold_delay`, so +`pci_bridge_wait_for_secondary_bus()` returns at once. Lesson: a sleep +test with the modem runs at least two cycles per boot. + +**M6.2 again, 2026-11-09** (`…-g80f9610feb26`, K1 + K1b + K1c): two 30 s +cycles in a row, a ping over `rmnet0` 3/3 after each. Cycle 1 woke at 14 s +on cp2ap_wakeup, cycle 2 on the RTC alarm (the PMIC IRQ) at 32 s. No +"Link Active" or "BME" line, no UFS line. The power-state lines at resume +remain and are harmless now. + +**M6.3, 2026-11-09** (same kernel), SMS: pass. A 4-minute loop that +freezes again 3 s after every wake, screen off. An SMS sent from another +phone about a minute in woke the phone on cp2ap_wakeup and was stored and +acknowledged in the same second (sitd, ModemManager, omatel). One more +modem wake 38 s later, then 2 min 27 s asleep until the alarm. A second +4-minute loop: one modem wake at 94 s, then 2 min 23 s asleep until the +alarm. Over the boot (M6.2 again and M6.3), the journal holds eight +`PM: suspend entry (s2idle)` lines, each followed by `PM: suspend exit`, +and no failed suspend (an earlier count here said seven: one short); a ping over +`rmnet0` 3/3 at the end; no UFS line. The call half is open: the test SIM +has data and SMS only. What the modem's own wakes (no SMS) carry isn't +logged yet. + +**Between runs, and the NV checks** (read back on 2026-11-11 from the +phone's journal). Each M6 boot started the modem once: after M6.2 run 1 and +M6.3 run 1, which lost the modem, the phone was rebooted with the unit's +stop (`CP OFFLINE`, `modem-up` removed), never restarted within the boot. +The UFS check of those two boots is that boot's own kernel log, which runs +on past the stop (to 855 s and 1387 s): no `ufshcd_err_handler` or +`I/O error` line in either, the stop's CP power-off included. NV: no +`tools/nv-backup --check` ran at each boot. What each modem start checked +instead (its RAM copies of `modem_a`, `efs`, `efs_backup`, +`modem_userdata` and `persist` against `/etc/omamobile/modem-nv.sha256`, +which holds the backup's sums, and the three NV files' stock checksums): + +| Boot | Kernel | RAM copies against the backup | NV file checksums | +|---|---|---|---| +| M6.0 | `…-g0e3da55c9e9f` | 5 of 5 match | 3 of 3 | +| M6.1, M6.2 run 1 | `…-g2f2f0b979337` | 5 of 5 match | 3 of 3 | +| M6.2 run 2, M6.3 run 1 | `…-g75876b951a19` | 5 of 5 match | 3 of 3 | +| M6.2 again, M6.3 | `…-g80f9610feb26` | 5 of 5 match | 3 of 3 | + +After all of them, `tools/nv-backup --check` against the 2026-10-30 backup +(2026-11-11): `efs`, `efs_backup`, `modem_userdata`, `persist`, `modem_a` +and `modem_b` the same, `devinfo` different as expected. From M6.4 the +`--check` runs before each boot's first step, as 7.3 says. + +**Registration on the newer kernel base: a race with sitd, and the fix** +(2026-11-12, the same second Pixel 7 Pro, on the charger, no sleep). #232 +rebased onto the newer `omamobile` (`7.3.0-rc6-omamobile-push1-g33179249011e`) +never registered: sitd's start-up ran as before, the radio came on, and +GET_PS_REG_STATE read state 20, reject 0, RAT 14, no data calls, until the +300 s deadline (5 of 5 boots). The first sign is before radio on: with the +radio off the modem accepted SET_NR_MODE (error 0, reading 0 already) +where it normally refuses it (error 2, and sitd sets it right after radio +on); at radio on it put the mode back to 1 itself, and setting 0 again by +hand later changed nothing. NV was the same every boot (RAM copies 5 of 5, +NV files 3 of 3), and the package versions didn't matter (0.1.18 and +0.1.21 started and stopped either way registered on the older kernel). + +- Bisected on the kernel base, judged by the radio-off SET_NR_MODE reply + at about 34 s: the first bad commit is a353a0190 ("arm64: dts: exynos: + google: gs201: give the CPU levels a power model"), whose energy model + turns on energy-aware scheduling. On that kernel, `kernel.sched_energy_aware` + set to 0 just before the modem starts: refused, so good; the modem's + daemons pinned to CPUs 4-7: still accepted; sitd pinned to CPUs 4-7: + refused, so good. So it is a race between sitd's start-up and the + modem's: on the little cores sitd reaches the request later, when the + modem takes it. The older kernel lost it now and then too (3 of about + 12 boots on `…-g80f9610feb26` on 2026-11-11). +- Fix: sitd sets the mode only right after radio on, still before + registration. It is its own pull request, + [#701](https://github.com/derekross/omarchy-mobile/pull/701) (`[network] + nr_after_radio_on`, off by default), since the reference 7 Pro, on the + same `kernel-2026.11.08`, gets the refusal and registers with today's + order. With it on, this phone registered on `…-ga353a0190151` with EAS + on, and twice on `…-g33179249011e` (packet registration 7.5 and 8.5 s + after radio on, then IMS voice and SMS; a ping over `rmnet0` 3/3; no UFS + line). The runs below used it. +- Which boots each count covers: 5 of 5 are the boots of + `…-g33179249011e` on 2026-11-12 with the old order (before the fix); + 3 of about 12 are the boots of `…-g80f9610feb26` on 2026-11-11. +- The merged option, 2026-11-14 (`omamobile-modem-sit` 0.3.37 from this + pull request, which carries #701's 0.3.36; `…-gd2983420874d-dirty`, + `omamobile` at `82f31d3a7` with #232). Off (the package's default): the + modem accepted SET_NR_MODE with the radio off ("verified NR mode 0" before + radio on) and never registered, 1 of 1 boot. On, 4 of 4 boots + registered: + + ``` + omamobile-sitd: NR mode: set right after radio on (nr_after_radio_on) + omamobile-sitd: Registration: packet registered 7.5 s after radio on, RAT 14 + ``` + + (the other three: 6.4 s RAT 14, 7.4 s RAT 20, 6.4 s RAT 14). + +**Sleep on the rebased #232, through `systemctl suspend`** (2026-11-12, +this phone, on the charger, unattended at 80 % on the owner's word, before +the rule in 7.3; a loop that sets an RTC alarm, runs `systemctl suspend` +and pings over `rmnet0` after each wake; each `systemctl suspend` made two +kernel attempts when the first failed). + +- `…-gb857fd28dd36` (#232's first three commits): cycle 1 slept and woke + on cp2ap_wakeup, ping fine. Cycle 2: the link came up 8 ms after + `PM: suspend entry` (CPIF's doorbell), so the first attempt was refused + with the link fully up ("sleep refused: link up, PHY out of isolation"). + The second attempt 30 ms later found the link down, and CPIF refused it + (`suspend_cp: abort suspend`). Its resume printed "s51xx … Unable to + change power state from D3hot to D0" and "pcieport … from D3cold to D0". + From then on CPIF kept bringing the link up, but sitd's polls timed out + until the reboot. +- `…-g1668d1e8d1b0` (#232's head, adding the fourth commit; `git + hash-object drivers/pci/controller/dwc/pcie-gs201-cp.c` `1d12db51af20`): + with a ping every second, 30 cycles and 60 attempts, all refused by the + link driver, and a ping over `rmnet0` after each one. Quiet: 8 of 8 + cycles slept and woke on cp2ap_wakeup, with a ping after each. No + s51xx power-state line, and no UFS, I/O or BME line. diff --git a/packages/omamobile-device-cheetah/test/all b/packages/omamobile-device-cheetah/test/all index b7879111a..b2697ab37 100755 --- a/packages/omamobile-device-cheetah/test/all +++ b/packages/omamobile-device-cheetah/test/all @@ -211,6 +211,14 @@ pass "sitd waits for the CP; the modem stack is on by default through the target || fail "the device sitd policy is staged" grep -q 'omamobile-sitd-policy' PKGBUILD || fail "the package provides its sitd policy capability" pass "the device sitd policy is staged and provided" + +# MODEM-PLAN section 7 (M6): the owner's modem-suspend-enable lifts +# omamobile-modem's sleep inhibitor only beside this marker, which only the +# Pixel 7 Pro ships; a plain data file, never a script. +runbook=$tmp/root/usr/lib/omamobile-modem/suspend-runbook +[[ -f $runbook && ! -x $runbook ]] || fail "the M6 runbook marker is staged as a plain file" +[[ $(grep -cv '^#' "$runbook") == 0 ]] || fail "the M6 runbook marker holds comments only" +pass "the M6 runbook marker is staged, so modem-suspend-enable can take effect on this phone" # The USB gadget's MAC addresses stay the same across boots (omamobile-usb-mac), # against a fake gadget: plain directories and files stand in for configfs. for f in usr/bin/omamobile-usb-mac usr/lib/systemd/system/omamobile-usb-mac.service; do diff --git a/packages/omamobile-device-cheetah/vendor/omamobile-modem/suspend-runbook b/packages/omamobile-device-cheetah/vendor/omamobile-modem/suspend-runbook new file mode 100644 index 000000000..f0db93011 --- /dev/null +++ b/packages/omamobile-device-cheetah/vendor/omamobile-modem/suspend-runbook @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: MIT +# The Pixel 7 Pro's modem plan has a runbook for suspend with the modem up +# (device/cheetah/MODEM-PLAN.md section 7, M6). omamobile-modem lets the +# owner's /etc/omamobile/modem-suspend-enable lift its sleep inhibitor only +# beside this file, so the owner's file alone changes nothing on a phone +# whose device package doesn't ship it. Attended runs only, until M6 passes. diff --git a/packages/omamobile-device-cheetah/version b/packages/omamobile-device-cheetah/version index 8893a8e14..c52af3e24 100644 --- a/packages/omamobile-device-cheetah/version +++ b/packages/omamobile-device-cheetah/version @@ -1 +1 @@ -0.1.55 +0.1.56 diff --git a/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf b/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf index 843b0b89e..d3f91938d 100644 --- a/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf +++ b/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf @@ -129,6 +129,11 @@ roaming = yes [control] # Members of this group may use the calls/SMS socket (root always can). group = wheel +# Tell the modem when the screen goes off and on, as stock's RIL does: with +# the screen off it stops its optional signal and dormancy reports, so it +# wakes the phone less (MODEM-PLAN 7.4, M6). Off until calls with the screen +# dark have been tested on this phone; yes turns it on, from sitd's next start. +#follow_screen = no [audio] # The AoC sound card for call audio: "none" connects calls without routing diff --git a/packages/omamobile-modem-sit/install b/packages/omamobile-modem-sit/install index c0db4b484..8d749425a 100755 --- a/packages/omamobile-modem-sit/install +++ b/packages/omamobile-modem-sit/install @@ -14,6 +14,7 @@ install -Dm755 lib/omamobile-sit-config "$d/usr/lib/omamobile-sit/omamobile-sit- install -Dm644 polkit/org.omamobile.modem-sit.policy "$d/usr/share/polkit-1/actions/org.omamobile.modem-sit.policy" install -Dm644 share/apn-overrides.conf "$d/usr/share/omamobile/modem-sit/apn-overrides.conf" for f in systemd/*.service; do install -Dm644 "$f" "$d/usr/lib/systemd/system/${f#systemd/}"; done +install -Dm755 systemd/system-sleep/omamobile-modem-sit "$d/usr/lib/systemd/system-sleep/omamobile-modem-sit" install -Dm644 networkmanager/90-omamobile-rmnet.conf "$d/usr/lib/NetworkManager/conf.d/90-omamobile-rmnet.conf" install -Dm644 etc/omamobile/modem-sit.conf "$d/etc/omamobile/modem-sit.conf" install -Dm644 LICENSE "$d/usr/share/licenses/omamobile-modem-sit/LICENSE" diff --git a/packages/omamobile-modem-sit/lib/data_network.py b/packages/omamobile-modem-sit/lib/data_network.py index be7b4fd35..55c49c56d 100644 --- a/packages/omamobile-modem-sit/lib/data_network.py +++ b/packages/omamobile-modem-sit/lib/data_network.py @@ -23,12 +23,18 @@ dead bearer's route plus its DNS can outlive a short Wi-Fi outage, make NetworkManager's connectivity check fail through it and keep the phone offline with Wi-Fi up. + +Around a system sleep the default route is taken away (SleepHold): at +logind's announcement NetworkManager takes Wi-Fi down, and a route through +the bearer would carry everything that had been talking over Wi-Fi, bring +the modem's link up and make the kernel refuse the sleep. """ import fcntl import ipaddress import json import os from pathlib import Path +import select import signal import struct import subprocess @@ -257,6 +263,130 @@ def wait_for_bearer(seconds): time.sleep(1) +# How long after a sleep the cellular default route waits for Wi-Fi. +RETURN_GRACE = 10 +SLEEP_MATCH = ("type='signal',interface='org.freedesktop.login1.Manager'," + "member='PrepareForSleep'") + + +def sleep_signal(line): + """True or False for a logind PrepareForSleep line of busctl's JSON + monitor (a sleep is starting, or is over), None for anything else.""" + try: + message = json.loads(line) + except ValueError: + return None + if not isinstance(message, dict) or message.get('member') != 'PrepareForSleep': + return None + data = (message.get('payload') or {}).get('data') + if isinstance(data, list) and len(data) == 1 and isinstance(data[0], bool): + return data[0] + return None + + +class SleepWatch: + """logind's sleep announcements, read without blocking. Without busctl + nothing is heard, and the route simply stays as it was.""" + + def __init__(self): + self.buffer = b'' + try: + self.process = subprocess.Popen( + ['busctl', 'monitor', '--system', '--json=short', '--match', SLEEP_MATCH], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + os.set_blocking(self.process.stdout.fileno(), False) + except OSError: + self.process = None + + def wait(self, seconds): + """Sleep up to seconds; return the announcements heard, in order.""" + if not self.process: + time.sleep(seconds) + return [] + heard = [] + ready, _, _ = select.select([self.process.stdout], [], [], seconds) + if ready: + chunk = os.read(self.process.stdout.fileno(), 65536) + if not chunk: # the monitor ended: go on without it + self.close() + return heard + self.buffer += chunk + *lines, self.buffer = self.buffer.split(b'\n') + for line in lines: + state = sleep_signal(line.decode(errors='replace')) + if state is not None: + heard.append(state) + return heard + + def close(self): + if self.process: + self.process.terminate() + try: + self.process.wait(timeout=2) + except subprocess.TimeoutExpired: + self.process.kill() + self.process = None + + +class SleepHold: + """The cellular default route around a system sleep. + + When the system goes to sleep NetworkManager takes Wi-Fi down first, and + the bearer's default route is then the only one: whatever was talking + over Wi-Fi sends through the bearer in that moment, the modem's link + comes up, and the kernel refuses the sleep because of it. So the route + goes at logind's announcement. After the sleep it waits for something + else to lead out again, or for RETURN_GRACE without that: put back at + once, it carried a few seconds of traffic at every wake, and the answers + to that traffic ended the next sleeps early. + """ + + def __init__(self, grace=RETURN_GRACE): + self.grace = grace + self.sleeping = False + self.held = False # the route is ours to bring back + self.back_at = None # when it returns if nothing else leads out + + @property + def active(self): + """True while the route's presence is this class's business.""" + return self.sleeping or self.back_at is not None + + def announced(self, routed): + """A sleep is starting. True when the route has to go now.""" + if self.sleeping: + return False + self.sleeping = True + # Still waiting to return after the last sleep counts as held. + self.held = routed or self.back_at is not None + self.back_at = None + return routed + + def over(self, now, allowed=True): + """The sleep is over; allowed is False when roaming forbids data.""" + if not self.sleeping: + return + self.sleeping = False + if self.held and allowed: + self.back_at = now + self.grace + self.held = False + + def returns(self, others, now): + """True once: the route comes back now (others: another default + route exists).""" + if self.sleeping or self.back_at is None: + return False + if others or now >= self.back_at: + self.back_at = None + return True + return False + + def cancel(self): + """Roaming took the route away for good: nothing to bring back.""" + self.held = False + self.back_at = None + + def main(): os.umask(0o077) lock = os.open(paths.RUN / 'data-network.lock', os.O_CREAT | os.O_RDWR, 0o600) @@ -275,6 +405,7 @@ def stop(*_): signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) resolver = None + sleeps = None try: dev = find_device(address, data[2], stopped=lambda: stopping) addressed = True @@ -286,6 +417,7 @@ def stop(*_): last = None seen = counters(json.loads(run('ip', '-j', '-s', 'link', 'show', 'dev', dev))) check_at = time.monotonic() + 30 + hold = SleepHold() def watch(): nonlocal last, seen, check_at @@ -297,6 +429,7 @@ def watch(): run('ip', 'route', 'del', 'default', 'dev', dev, 'metric', '700') print('Roaming with data roaming off; the cellular default route is removed', flush=True) resolver.update(False, dns) + hold.cancel() last = None return # With Wi-Fi up but rated limited, the carrier's DNS would keep @@ -306,6 +439,13 @@ def watch(): if cellular != last: print('Default internet path', 'cellular' if cellular else 'Wi-Fi/other', flush=True) last = cellular + if hold.active: + if hold.returns(bool(others), time.monotonic()): + if not routed: + run('ip', 'route', 'add', 'default', 'dev', dev, 'src', address, 'metric', '700') + print('The cellular default route is back', 'behind Wi-Fi' if others else 'as the only way out', flush=True) + last = None + return if not routed and not others: run('ip', 'route', 'add', 'default', 'dev', dev, 'src', address, 'metric', '700') print('Nothing else leads out; the cellular default route is back', flush=True) @@ -317,6 +457,16 @@ def watch(): now = counters(json.loads(run('ip', '-j', '-s', 'link', 'show', 'dev', dev))) seen = now check_at = time.monotonic() + 30 + def announced(state): + if not state: + hold.over(time.monotonic(), not roaming_blocked()) + return + routes = json.loads(run('ip', '-j', 'route', 'show', 'default')) + routed = any(r.get('dev') == dev and r.get('metric') == 700 for r in routes) + if hold.announced(routed): + run('ip', 'route', 'del', 'default', 'dev', dev, 'metric', '700') + print('Sleep announced; the cellular default route is away until it is over', flush=True) + sleeps = SleepWatch() failing = None while not stopping and cp.online() and RESPONSE.exists(): error = guarded(watch) @@ -325,11 +475,14 @@ def watch(): elif failing and not error: print('Network checks work again', flush=True) failing = error - time.sleep(2 if error else .5) + for state in sleeps.wait(2 if error else .5): + guarded(lambda state=state: announced(state)) except InterruptedError: # Stopped while probing: find_device has put the candidate back. pass finally: + if sleeps: + sleeps.close() if resolver: resolver.restore() if dev: diff --git a/packages/omamobile-modem-sit/lib/paths.py b/packages/omamobile-modem-sit/lib/paths.py index a5f5db50a..31138a78f 100644 --- a/packages/omamobile-modem-sit/lib/paths.py +++ b/packages/omamobile-modem-sit/lib/paths.py @@ -43,7 +43,7 @@ # Extra modem-managed data profiles, one per line (data_call.parse_profile). 'profiles': {}, 'data': {'route': 'yes', 'metric': '700', 'roaming': 'yes'}, - 'control': {'group': 'wheel'}, + 'control': {'group': 'wheel', 'follow_screen': 'no'}, 'audio': {'card': 'none', 'mic_boost_db': '6', 'earpiece': 'yes'}, } diff --git a/packages/omamobile-modem-sit/lib/service.py b/packages/omamobile-modem-sit/lib/service.py index cacfc0508..502a1dc0f 100644 --- a/packages/omamobile-modem-sit/lib/service.py +++ b/packages/omamobile-modem-sit/lib/service.py @@ -39,6 +39,7 @@ import struct import subprocess import time +from pathlib import Path import cp import paths @@ -58,6 +59,8 @@ RATS = {0: '', 1: 'GPRS', 2: 'EDGE', 3: 'UMTS', 9: 'HSDPA', 10: 'HSUPA', 11: 'HSPA', 14: 'LTE', 15: 'HSPA+', 16: 'GSM', 20: 'LTE-CA', 21: 'NR', 22: 'NR'} SOCKET = paths.RUN / 'socket' +# The panel's power, which the shell drives (bl_power 4 = off, 0 = on). +BACKLIGHT = Path(os.environ.get('OMAMOBILE_SIT_BACKLIGHT', '/sys/class/backlight')) # GET_RADIO_POWER / IND_RADIO_STATE_CHANGED (MODEM-SIT-RESEARCH 3.1): # INITIALIZED and STOP_NETWORK are off, START_NETWORK on, POWER_OFF is the # state without a SIM (M4.1i), RESET is unavailable. GET_RADIO_POWER answers @@ -219,6 +222,13 @@ def __init__(self, client, db, settings=None): self.hangup_deadline = None self.release_unconfirmed = False self.screen_on = None + self.next_screen_check = 0 + # [control] follow_screen: off by default until calls with the + # screen dark are tested (MODEM-PLAN 7.4). + try: + self.follow = self.settings['control'].getboolean('follow_screen', False) + except ValueError: + self.follow = False self.indication_counts = {} self.net = dict(reg='unknown', rat='', operator='', plmn='') self.last_registration = None @@ -642,12 +652,50 @@ def publish(self): tmp.chmod(0o644) tmp.replace(path) + def follow_screen(self, now=None): + """Tell the modem when the panel goes off or on, as stock's RIL does: + with the screen off it sends the optional signal and dormancy reports + no more (calls, SMS and registration changes still come), so it wakes + the AP less. Off only when a backlight positively reads off; never + during a call (stock keeps the reports then, and screen-state refuses + it), and a failed request waits 30 s before the next try. Only with + [control] follow_screen = yes in modem-sit.conf.""" + if not self.follow: + return + now = time.monotonic() if now is None else now + if now < self.next_screen_check: + return + self.next_screen_check = now + 2 + states = [] + for power in sorted(BACKLIGHT.glob('*/bl_power')): + try: + states.append(power.read_text().strip() != '0') + except OSError: + pass + if not states: + return + on = not any(states) + if on == self.screen_on or (not on and self.live()): + return + try: + self.dispatch(dict(action='screen-state', on=on)) + print('Screen', 'on' if on else 'off', 'told to the modem', flush=True) + except (OSError, RuntimeError, ValueError) as e: + print('Screen state not sent:', e, flush=True) + self.next_screen_check = now + 30 + def dispatch(self, request): action = request.get('action') if action == 'screen-state': on = request.get('on') if type(on) is not bool: raise ValueError('Screen state must be boolean') + hold = request.get('hold', 0) + if type(hold) is not int or not 0 <= hold <= 60: + raise ValueError('Screen hold must be 0 to 60 s') + if hold and not self.follow: + # The sleep hook, on a phone that doesn't follow the screen. + return dict(screen_on=self.screen_on, following=False) if not on and self.live(): raise RuntimeError('Call in progress') if on != self.screen_on: @@ -661,6 +709,10 @@ def dispatch(self, request): # reporting. Cache only after both replies succeed. self.client.request(0x0928, struct.pack('= next_cp_check: if not cp.online(): raise RuntimeError('CP left ONLINE; the modem unit keeps its crash record') diff --git a/packages/omamobile-modem-sit/systemd/system-sleep/omamobile-modem-sit b/packages/omamobile-modem-sit/systemd/system-sleep/omamobile-modem-sit new file mode 100755 index 000000000..5a0a939e2 --- /dev/null +++ b/packages/omamobile-modem-sit/systemd/system-sleep/omamobile-modem-sit @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""systemd-sleep hook: tell the modem the screen is off before the AP sleeps. + +omamobile-sitd follows the backlight every 2 s, so a sleep that starts +sooner (systemctl suspend with the panel lit, or within 2 s of it going +dark) left the modem on its screen-on reports, each one a wake +(MODEM-PLAN 7.4). The request holds sitd's own check off for 10 s; after +the wake that check tells the modem "on" again if the panel is lit. The +hold counts on CLOCK_MONOTONIC, which stops during the freeze, so after a +short sleep the modem can stay on "screen off" for the rest of the 10 s +with the panel lit. A +refusal (a call in progress) or a missing sitd is fine: the sleep goes +ahead either way, and so does a phone without [control] follow_screen = yes +in modem-sit.conf, where sitd sends nothing. +""" +import json +import os +import socket +import sys + +RUN = os.environ.get('OMAMOBILE_SIT_RUN', '/run/omamobile-sit') + + +def main(argv): + if len(argv) < 2 or argv[1] != 'pre': + return 0 + path = os.path.join(RUN, 'socket') + if not os.path.exists(path): + return 0 + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(6) + client.connect(path) + client.sendall(json.dumps(dict(action='screen-state', on=False, hold=10)).encode() + b'\n') + data = b'' + while b'\n' not in data: + chunk = client.recv(4096) + if not chunk: + break + data += chunk + reply = json.loads(data or b'{}') + if not reply.get('ok'): + result = 'not told: ' + str(reply.get('error') or 'no reply') + elif (reply.get('result') or {}).get('following') is False: + result = 'not told: follow_screen is off in modem-sit.conf' + else: + result = 'told' + except (OSError, ValueError) as e: + result = 'not told: ' + type(e).__name__ + print('omamobile-modem-sit: screen off before sleep', result, flush=True) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/packages/omamobile-modem-sit/test/all b/packages/omamobile-modem-sit/test/all index 231ef6a10..c4d89443c 100755 --- a/packages/omamobile-modem-sit/test/all +++ b/packages/omamobile-modem-sit/test/all @@ -13,7 +13,7 @@ pass() { printf 'ok - %s\n' "$1"; } export PYTHONDONTWRITEBYTECODE=1 bash -n install || fail "install parses" -for f in bin/* lib/*.py lib/omamobile-sit-config test/*.py; do +for f in bin/* lib/*.py lib/omamobile-sit-config systemd/system-sleep/* test/*.py; do python3 -c 'import ast, sys; ast.parse(open(sys.argv[1]).read(), sys.argv[1])' "$f" || fail "$f parses" done pass "scripts parse" @@ -33,9 +33,42 @@ for f in usr/bin/omamobile-sitd usr/bin/omamobile-sit usr/bin/omamobile-sit-data usr/lib/omamobile-sit/omamobile-sit-config usr/lib/omamobile-sit/carrier_apn.py \ usr/share/polkit-1/actions/org.omamobile.modem-sit.policy \ usr/share/omamobile/modem-sit/apn-overrides.conf \ - usr/share/licenses/omamobile-modem-sit/LICENSE; do + usr/share/licenses/omamobile-modem-sit/LICENSE \ + usr/lib/systemd/system-sleep/omamobile-modem-sit; do [[ -e $stage/$f ]] || fail "staged $f" done +[[ -x $stage/usr/lib/systemd/system-sleep/omamobile-modem-sit ]] || fail "the sleep hook is executable" +# The sleep hook asks sitd for "screen off" with a hold, only before a sleep, +# and never stops the sleep (no sitd, or a refusal). +hook=$stage/usr/lib/systemd/system-sleep/omamobile-modem-sit +python3 - "$hook" <<'PY' || fail "sleep hook" +import json, os, socket, subprocess, sys, tempfile, threading +hook = sys.argv[1] +with tempfile.TemporaryDirectory() as run: + env = dict(os.environ, OMAMOBILE_SIT_RUN=run) + r = subprocess.run([hook, 'pre', 'suspend'], env=env, capture_output=True, text=True) + assert r.returncode == 0 and r.stdout == '', r + server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + server.bind(os.path.join(run, 'socket')); server.listen(2) + seen = [] + def serve(reply): + c, _ = server.accept() + seen.append(json.loads(c.recv(4096))) + c.sendall(json.dumps(reply).encode() + b'\n'); c.close() + t = threading.Thread(target=serve, args=(dict(ok=True, result=dict(screen_on=False)),)); t.start() + r = subprocess.run([hook, 'pre', 'suspend'], env=env, capture_output=True, text=True); t.join() + assert r.returncode == 0 and 'told' in r.stdout and 'not told' not in r.stdout, r + assert seen == [dict(action='screen-state', on=False, hold=10)], seen + t = threading.Thread(target=serve, args=(dict(ok=False, error='Call in progress'),)); t.start() + r = subprocess.run([hook, 'pre', 'suspend'], env=env, capture_output=True, text=True); t.join() + assert r.returncode == 0 and 'not told: Call in progress' in r.stdout, r + t = threading.Thread(target=serve, args=(dict(ok=True, result=dict(screen_on=None, following=False)),)); t.start() + r = subprocess.run([hook, 'pre', 'suspend'], env=env, capture_output=True, text=True); t.join() + assert r.returncode == 0 and 'not told: follow_screen is off' in r.stdout, r + r = subprocess.run([hook, 'post', 'suspend'], env=env, capture_output=True, text=True) + assert r.returncode == 0 and r.stdout == '' and len(seen) == 3, r +PY +pass "sleep hook: screen off before a sleep (follow_screen only), never blocking it" # the installed launchers find the installed library python3 "$stage/usr/bin/omamobile-sitd" --help >/dev/null || fail "the staged daemon imports its library" python3 "$stage/usr/bin/omamobile-sit" --help >/dev/null || fail "the staged CLI runs" diff --git a/packages/omamobile-modem-sit/test/env.py b/packages/omamobile-modem-sit/test/env.py index 584eee1aa..3c89ad36d 100644 --- a/packages/omamobile-modem-sit/test/env.py +++ b/packages/omamobile-modem-sit/test/env.py @@ -19,6 +19,7 @@ 'OMAMOBILE_SIT_DEVICE': 'unix:' + os.path.join(TMP, 'ipc0'), 'OMAMOBILE_SIT_ROUTER': 'unix:' + os.path.join(TMP, 'router'), 'OMAMOBILE_SIT_BOOT': 'none', + 'OMAMOBILE_SIT_BACKLIGHT': os.path.join(TMP, 'backlight'), # never the host's panel }) os.makedirs(os.path.join(TMP, 'run'), mode=0o700) if LIB not in sys.path: diff --git a/packages/omamobile-modem-sit/test/test_data_network.py b/packages/omamobile-modem-sit/test/test_data_network.py index cab69046b..0c9895afc 100644 --- a/packages/omamobile-modem-sit/test/test_data_network.py +++ b/packages/omamobile-modem-sit/test/test_data_network.py @@ -6,7 +6,7 @@ import unittest from unittest.mock import patch import data_network -from data_network import Resolver, configuration, counters, guarded, looks_silent +from data_network import Resolver, SleepHold, configuration, counters, guarded, looks_silent, sleep_signal class ResolverTests(unittest.TestCase): def test_fallback_restoration_preserves_new_wifi_dns(self): @@ -21,6 +21,61 @@ def test_rejects_inactive_or_wrong_bearer(self): with self.assertRaises(ValueError): configuration(data) class RouteTests(unittest.TestCase): + def test_only_logind_sleep_announcements_count(self): + line = '{"type":"signal","member":"PrepareForSleep","payload":{"type":"b","data":[%s]}}' + self.assertIs(sleep_signal(line % 'true'), True) + self.assertIs(sleep_signal(line % 'false'), False) + self.assertIsNone(sleep_signal(line.replace('PrepareForSleep', 'PrepareForShutdown') % 'true')) + self.assertIsNone(sleep_signal('{"member":"PrepareForSleep","payload":{"data":["yes"]}}')) + self.assertIsNone(sleep_signal('not json')) + self.assertIsNone(sleep_signal('[]')) + + def test_the_route_goes_at_the_announcement_and_waits_for_wifi_after(self): + hold = SleepHold(grace=10) + self.assertFalse(hold.active) + self.assertTrue(hold.announced(routed=True)) # remove it now + self.assertFalse(hold.announced(routed=False)) # a second announcement changes nothing + self.assertTrue(hold.active) + self.assertFalse(hold.returns(others=True, now=0)) # not while asleep + hold.over(now=100) + self.assertTrue(hold.active) + self.assertFalse(hold.returns(others=False, now=105)) # Wi-Fi not back, grace not over + self.assertTrue(hold.returns(others=True, now=106)) # Wi-Fi leads out again + self.assertFalse(hold.active) + self.assertFalse(hold.returns(others=True, now=107)) # once + + def test_without_wifi_the_route_returns_after_the_grace(self): + hold = SleepHold(grace=10) + hold.announced(routed=True) + hold.over(now=100) + self.assertFalse(hold.returns(others=False, now=109.9)) + self.assertTrue(hold.returns(others=False, now=110)) + + def test_a_route_that_was_not_there_is_not_brought_back(self): + hold = SleepHold(grace=10) + self.assertFalse(hold.announced(routed=False)) # removed earlier: silent bearer, roaming + hold.over(now=100) + self.assertFalse(hold.active) + self.assertFalse(hold.returns(others=True, now=200)) + + def test_a_sleep_during_the_wait_keeps_the_route_owed(self): + hold = SleepHold(grace=10) + hold.announced(routed=True) + hold.over(now=100) + self.assertFalse(hold.announced(routed=False)) # asleep again before it came back + hold.over(now=200) + self.assertTrue(hold.returns(others=True, now=201)) + + def test_roaming_ends_the_wait(self): + hold = SleepHold(grace=10) + hold.announced(routed=True) + hold.over(now=100, allowed=False) + self.assertFalse(hold.active) + hold.announced(routed=True) + hold.over(now=300) + hold.cancel() + self.assertFalse(hold.returns(others=True, now=301)) + def test_counters_read_ip_json(self): stats=[{'stats64':{'rx':{'bytes':0,'packets':0},'tx':{'bytes':900,'packets':12}}}] self.assertEqual(counters(stats),(0,12)) diff --git a/packages/omamobile-modem-sit/test/test_service.py b/packages/omamobile-modem-sit/test/test_service.py index 5cd82e4d5..742ab50f4 100644 --- a/packages/omamobile-modem-sit/test/test_service.py +++ b/packages/omamobile-modem-sit/test/test_service.py @@ -156,6 +156,56 @@ def test_failed_filter_does_not_hide_partial_screen_change(self): self.assertTrue(self.service.screen_on) self.client.request.assert_called_with(0x0928,b'\xff'*4,timeout=5) + def test_the_modem_follows_the_panel(self): + light=self.root/'backlight'/'panel'; light.mkdir(parents=True) + power=light/'bl_power' + def at(t, value=None): + if value is not None: power.write_text(value+'\n') + self.client.request.reset_mock() + self.service.follow_screen(now=t) + return [c.args for c in self.client.request.call_args_list] + with patch.object(app_service,'BACKLIGHT',self.root/'backlight'), patch('builtins.print'): + # Off by default: nothing is sent, and the sleep hook's request + # is answered without a word to the modem. + self.assertFalse(app_service.Service(self.client,self.db,paths.config(self.root/'none.conf')).follow) + self.service.follow=False + power.write_text('4\n') + self.assertEqual(at(0),[]) + self.assertEqual(self.service.dispatch(dict(action='screen-state',on=False,hold=10)), + dict(screen_on=None,following=False)) + self.client.request.assert_not_called() + self.service.follow=True + self.assertEqual(at(0,'0'),[(0x0902,b'\x01\0\0\0'),(0x0928,b'\xff'*4)]) + self.assertEqual(at(1,'4'),[]) # checked every 2 s + self.assertEqual(at(2),[(0x0902,bytes(4)),(0x0928,bytes(4))]) + self.assertEqual(at(4),[]) # no change, no request + self.assertEqual(at(6,'0'),[(0x0902,b'\x01\0\0\0'),(0x0928,b'\xff'*4)]) + # During a call the reports stay on. + call=self.service.new_call('+12025550123','incoming','ringing-in',7) + self.assertEqual(at(8,'4'),[]) + call['state']='terminated' + self.assertEqual(at(10),[(0x0902,bytes(4)),(0x0928,bytes(4))]) + # A failed request waits 30 s. + self.client.request.side_effect=TimeoutError() + at(12,'0'); self.assertIsNone(self.service.screen_on) + self.client.request.side_effect=None + self.assertEqual(at(20),[]) + self.assertEqual(at(42),[(0x0902,b'\x01\0\0\0'),(0x0928,b'\xff'*4)]) + # No backlight that reads: nothing is guessed. + power.unlink() + self.assertEqual(at(50),[]) + self.assertTrue(self.service.screen_on) + # The sleep hook's "off" holds against a lit panel, then lapses. + power.write_text('0\n') + with patch.object(app_service.time,'monotonic',return_value=100): + self.service.dispatch(dict(action='screen-state',on=False,hold=10)) + self.assertFalse(self.service.screen_on) + self.assertEqual(at(105),[]) + self.assertEqual(at(110),[(0x0902,b'\x01\0\0\0'),(0x0928,b'\xff'*4)]) + for bad in (-1, 61, True, '5'): + with self.assertRaises(ValueError): + self.service.dispatch(dict(action='screen-state',on=False,hold=bad)) + def test_public_state_has_no_numbers(self): self.service.new_call('+12025550123','incoming','ringing-in',7) state=json.loads((self.root/'state.json').read_text()) diff --git a/packages/omamobile-modem-sit/test/test_sim.py b/packages/omamobile-modem-sit/test/test_sim.py index f7aac1e7f..8f520527c 100644 --- a/packages/omamobile-modem-sit/test/test_sim.py +++ b/packages/omamobile-modem-sit/test/test_sim.py @@ -31,7 +31,8 @@ def setUp(self): OMAMOBILE_SIT_CONFIG=str(self.dir / 'modem-sit.conf'), OMAMOBILE_SIT_DEVICE='unix:' + str(self.dir / 'ipc0'), OMAMOBILE_SIT_ROUTER='unix:' + str(self.dir / 'router'), - OMAMOBILE_SIT_BOOT='none', PYTHONDONTWRITEBYTECODE='1') + OMAMOBILE_SIT_BOOT='none', PYTHONDONTWRITEBYTECODE='1', + OMAMOBILE_SIT_BACKLIGHT=str(self.dir / 'backlight')) (self.dir / 'modem-sit.conf').write_text( '[network]\napn = internet.example\nsim_timeout = 20\nregister_timeout = 30\n' '[audio]\ncard = none\n') diff --git a/packages/omamobile-modem-sit/version b/packages/omamobile-modem-sit/version index 851786c85..ba61ff307 100644 --- a/packages/omamobile-modem-sit/version +++ b/packages/omamobile-modem-sit/version @@ -1 +1 @@ -0.3.36 +0.3.37 diff --git a/packages/omamobile-modem/lib/omamobile-modem-start b/packages/omamobile-modem/lib/omamobile-modem-start index 43f4d9989..40aeab038 100755 --- a/packages/omamobile-modem/lib/omamobile-modem-start +++ b/packages/omamobile-modem/lib/omamobile-modem-start @@ -80,6 +80,15 @@ INHIBITOR=omamobile-modem # inhibitor (overridden by the test). SYSMODULE=${OMAMOBILE_MODEM_SYSMODULE:-/sys/module} SYSTEMCTL=${OMAMOBILE_MODEM_SYSTEMCTL:-systemctl} +# MODEM-PLAN section 7 (M6): with this file, the modem starts without the +# inhibitor (its unit is skipped by the same pair of files) and the phone +# may sleep with it up. Attended runbook only, until M6 passes. It takes +# effect only beside SUSPEND_RUNBOOK, which a device package ships for a +# phone whose plan has an M6 runbook (device-cheetah, the Pixel 7 Pro): +# suspend with the modem up is unqualified on the 9a and the 6 Pro, so the +# owner's file alone changes nothing there. +SUSPEND_ENABLE=${OMAMOBILE_MODEM_SUSPEND_ENABLE:-/etc/omamobile/modem-suspend-enable} +SUSPEND_RUNBOOK=${OMAMOBILE_MODEM_SUSPEND_RUNBOOK:-/usr/lib/omamobile-modem/suspend-runbook} say() { printf 'omamobile-modem: %s\n' "$*" >&2; } boot_id() { cat /proc/sys/kernel/random/boot_id; } @@ -247,12 +256,18 @@ done # The sleep inhibitor before the drivers: the unit requires and orders after # omamobile-modem-inhibit.service, but a Type=simple unit is "started" at # its fork, so give the lock a moment to appear, and refuse without it. -for _ in $(seq 25); do - systemd-inhibit --list --no-legend 2>/dev/null | grep -c "^$INHIBITOR " >/dev/null && break - sleep 0.2 -done -systemd-inhibit --list --no-legend 2>/dev/null | grep -c "^$INHIBITOR " >/dev/null || - { say "no sleep inhibitor held by $INHIBITOR (systemctl start omamobile-modem-inhibit): not loading the modem's drivers"; refuse "Off: no sleep inhibitor"; } +if [[ -e $SUSPEND_ENABLE && -e $SUSPEND_RUNBOOK ]]; then + say "$SUSPEND_ENABLE: the phone may sleep with the modem up (MODEM-PLAN section 7, M6)" +else + [[ -e $SUSPEND_ENABLE ]] && + say "$SUSPEND_ENABLE ignored: this phone has no M6 runbook ($SUSPEND_RUNBOOK); the sleep inhibitor stays" + for _ in $(seq 25); do + systemd-inhibit --list --no-legend 2>/dev/null | grep -c "^$INHIBITOR " >/dev/null && break + sleep 0.2 + done + systemd-inhibit --list --no-legend 2>/dev/null | grep -c "^$INHIBITOR " >/dev/null || + { say "no sleep inhibitor held by $INHIBITOR (systemctl start omamobile-modem-inhibit): not loading the modem's drivers"; refuse "Off: no sleep inhibitor"; } +fi # Past every refusal: an earlier one's reason no longer describes this boot. rm -f "$REFUSED" diff --git a/packages/omamobile-modem/systemd/omamobile-modem-inhibit.service b/packages/omamobile-modem/systemd/omamobile-modem-inhibit.service index ad2ff841b..cc46f0aa2 100644 --- a/packages/omamobile-modem/systemd/omamobile-modem-inhibit.service +++ b/packages/omamobile-modem/systemd/omamobile-modem-inhibit.service @@ -15,6 +15,14 @@ # Requires= pulls this in even when that unit's own conditions skip it, so # the same three conditions are here: a phone that isn't provisioned (no # modem files, checksums or board id) keeps sleeping. +# /etc/omamobile/modem-suspend-enable lifts it from the next modem start, for +# MODEM-PLAN section 7 (M6: suspend with the modem up, attended runbook +# only until M6 passes); the start script follows the same files. It is for +# the Pixel 7 Pro's M6 runbook only, so it takes effect only beside +# /usr/lib/omamobile-modem/suspend-runbook, which device-cheetah ships: +# suspend with the modem up is unqualified on the 9a and the 6 Pro, and +# there the owner's file alone keeps the lock (the two triggering +# conditions below: the unit runs unless both files exist). [Unit] Description=Omarchy Mobile modem: block system sleep until the reboot Before=omamobile-modem.service @@ -22,6 +30,8 @@ RefuseManualStop=yes ConditionPathExists=/usr/lib/omamobile-vendor/modem/root ConditionPathExists=/etc/omamobile/modem-nv.sha256 ConditionPathExists=/var/lib/omamobile-vendor/modem/props.conf +ConditionPathExists=|!/etc/omamobile/modem-suspend-enable +ConditionPathExists=|!/usr/lib/omamobile-modem/suspend-runbook [Service] ExecStart=/usr/bin/systemd-inhibit --what=sleep:idle --who=omamobile-modem --why="suspend with the modem up is not qualified on this phone (MODEM-PLAN 6.3)" --mode=block /usr/bin/sleep infinity diff --git a/packages/omamobile-modem/test/all b/packages/omamobile-modem/test/all index 4b0f8abb4..fdd9640ed 100755 --- a/packages/omamobile-modem/test/all +++ b/packages/omamobile-modem/test/all @@ -279,6 +279,34 @@ done grep -q 'CHROOT=\${OMAMOBILE_MODEM_CHROOT:-\$LIB/modem/root}' $s && grep -q 'NV_SUMS=\${OMAMOBILE_MODEM_NV_SUMS:-/etc/omamobile/modem-nv.sha256}' $s && grep -q 'PROPS=\${OMAMOBILE_MODEM_PROPS:-/var/lib/omamobile-vendor/modem/props.conf}' $s || fail "the script checks the same three paths as the units" pass "a phone that isn't provisioned is refused quietly, by the units' conditions and by the script" +# M6 (MODEM-PLAN section 7): the owner's file lifts the inhibitor only beside +# the device's runbook marker (device-cheetah ships it), in the unit and in +# the script alike; the script's behaviour is in test_link.py. The unit's +# conditions are evaluated by systemd itself, with the two paths moved +# under $m: it runs (holds the lock) unless both files exist. +unit=systemd/omamobile-modem-inhibit.service +[[ $(grep -c '^ConditionPathExists=|!' $unit) == 2 ]] && + grep -qx 'ConditionPathExists=|!/etc/omamobile/modem-suspend-enable' $unit && + grep -qx 'ConditionPathExists=|!/usr/lib/omamobile-modem/suspend-runbook' $unit || + fail "the inhibitor unit is skipped only with modem-suspend-enable and suspend-runbook" +if command -v systemd-analyze >/dev/null && systemd-analyze condition 'ConditionPathExists=/' >/dev/null 2>&1; then + mapfile -t conds < <(grep '^ConditionPathExists=|!' $unit | + sed -e "s|/etc/omamobile/modem-suspend-enable|$m/m6-enable|" -e "s|/usr/lib/omamobile-modem/suspend-runbook|$m/m6-runbook|") + rm -f "$m/m6-enable" "$m/m6-runbook" + systemd-analyze condition "${conds[@]}" >/dev/null 2>&1 || fail "neither file: the inhibitor runs" + touch "$m/m6-enable" + systemd-analyze condition "${conds[@]}" >/dev/null 2>&1 || fail "the enable file alone: the inhibitor still runs" + touch "$m/m6-runbook"; rm "$m/m6-enable" + systemd-analyze condition "${conds[@]}" >/dev/null 2>&1 || fail "the runbook marker alone: the inhibitor runs" + touch "$m/m6-enable" + systemd-analyze condition "${conds[@]}" >/dev/null 2>&1 && fail "both files: the inhibitor is skipped" + rm -f "$m/m6-enable" "$m/m6-runbook" +fi +grep -q 'SUSPEND_ENABLE=\${OMAMOBILE_MODEM_SUSPEND_ENABLE:-/etc/omamobile/modem-suspend-enable}' $s && + grep -q 'SUSPEND_RUNBOOK=\${OMAMOBILE_MODEM_SUSPEND_RUNBOOK:-/usr/lib/omamobile-modem/suspend-runbook}' $s || + fail "the script follows the same two files" +[[ $(lineof 'if \[\[ -e \$SUSPEND_ENABLE && -e \$SUSPEND_RUNBOOK \]\]') -lt $l_inhibit ]] || fail "the files are checked before the inhibitor refusal" +pass "modem-suspend-enable lifts the sleep inhibitor only beside the device's M6 runbook, in the unit and the script alike" # The bring-up latch: refused until --retry (a hang in the bring-up never repeats on its own). printf '%s boot %s\n' 2026-01-01T00:00:00+00:00 00000000-0000-0000-0000-000000000000 > "$m/latch" out=$(start) && fail "a bring-up latch is refused" diff --git a/packages/omamobile-modem/test/test_link.py b/packages/omamobile-modem/test/test_link.py index b43446ccc..778a43608 100644 --- a/packages/omamobile-modem/test/test_link.py +++ b/packages/omamobile-modem/test/test_link.py @@ -61,7 +61,8 @@ def test_loaded_module_mismatch_refuses_before_loading(self): self.assertEqual(result.returncode, 0 if value == 'Y' else 7) self.assertEqual('load-reached' in result.stdout, value == 'Y') - def run_starter(self, config, loaded=None, fail_module=None, inhibitor=False): + def run_starter(self, config, loaded=None, fail_module=None, inhibitor=False, + lock=True, suspend_enable=False, runbook=True): """Run actual starter with only paths redirected and inert external tools.""" config_path = self.root / 'link.conf' if config is not None: @@ -84,7 +85,8 @@ def run_starter(self, config, loaded=None, fail_module=None, inhibitor=False): tools = self.root / 'bin' tools.mkdir() for name, body in { - 'systemd-inhibit': 'echo inhibitor >> "$TRACE"; echo "omamobile-modem held"', + 'systemd-inhibit': 'echo inhibitor >> "$TRACE"; [[ -n ${NO_LOCK:-} ]] || echo "omamobile-modem held"', + 'sleep': ':', 'sync': ':', 'modprobe': 'test -f "$OMAMOBILE_MODEM_LATCH" || exit 23; echo "load:$*" >> "$TRACE"; ' '[[ $1 != "${FAIL_MODULE:-}" ]] || exit 1; mkdir -p "$SYSMODULE/${1//-/_}"', @@ -110,7 +112,16 @@ def run_starter(self, config, loaded=None, fail_module=None, inhibitor=False): OMAMOBILE_MODEM_REFUSED=str(self.root / 'refused'), OMAMOBILE_MODEM_CHROOT=str(provision), OMAMOBILE_MODEM_NV_SUMS=str(provision), - OMAMOBILE_MODEM_PROPS=str(provision)) + OMAMOBILE_MODEM_PROPS=str(provision), + # Never the machine's own file: on a phone running the M6 + # runbook it exists, and the starter would skip the lock. + OMAMOBILE_MODEM_SUSPEND_ENABLE=str(self.root / 'suspend-enable'), + OMAMOBILE_MODEM_SUSPEND_RUNBOOK=str(self.root / 'suspend-runbook'), + NO_LOCK='' if lock else '1') + if suspend_enable: + (self.root / 'suspend-enable').touch() + if runbook: + (self.root / 'suspend-runbook').touch() modules = self.root / 'loaded' modules.mkdir() if inhibitor: @@ -148,6 +159,42 @@ def test_later_module_failing_keeps_the_sleep_block(self): 'load:second cpif=1']) self.assertEqual((self.root / 'refused').read_text().strip(), "Off: second didn't load") + def test_no_enable_file_and_no_lock_refuses_before_loading(self): + result, trace = self.run_starter('first allow_hw=1\nsecond cpif=1\n', 'Y', lock=False) + self.assertEqual(result.returncode, 1) + self.assertNotIn('load:first allow_hw=1', trace) + self.assertEqual(trace[-1], 'inhibitor') + self.assertEqual((self.root / 'refused').read_text().strip(), 'Off: no sleep inhibitor') + self.assertFalse((self.root / 'latch').exists()) + + def test_enable_file_and_no_lock_loads_without_waiting(self): + result, trace = self.run_starter('first allow_hw=1\nsecond cpif=1\n', 'Y', lock=False, + suspend_enable=True) + self.assertEqual(result.returncode, 1) # inert profile check deliberately refuses + self.assertNotIn('inhibitor', trace) + self.assertEqual(trace, ['load:first allow_hw=1', 'load:second cpif=1', + 'load:shm_ipc', 'load:cpif', 'profile-check']) + self.assertIn('the phone may sleep with the modem up', result.stderr) + + def test_enable_file_without_runbook_keeps_the_inhibitor(self): + # A phone whose device package ships no M6 runbook (the 9a, the 6 Pro): + # the owner's file alone changes nothing, and no lock still refuses. + result, trace = self.run_starter('first allow_hw=1\nsecond cpif=1\n', 'Y', lock=False, + suspend_enable=True, runbook=False) + self.assertEqual(result.returncode, 1) + self.assertNotIn('load:first allow_hw=1', trace) + self.assertEqual(trace[-1], 'inhibitor') + self.assertEqual((self.root / 'refused').read_text().strip(), 'Off: no sleep inhibitor') + self.assertFalse((self.root / 'latch').exists()) + self.assertIn('ignored: this phone has no M6 runbook', result.stderr) + + def test_enable_file_without_runbook_with_lock_loads_as_before(self): + result, trace = self.run_starter('first allow_hw=1\nsecond cpif=1\n', 'Y', + suspend_enable=True, runbook=False) + self.assertEqual(result.returncode, 1) # inert profile check deliberately refuses + self.assertEqual(trace, ['inhibitor', 'inhibitor', 'load:first allow_hw=1', + 'load:second cpif=1', 'load:shm_ipc', 'load:cpif', 'profile-check']) + def test_no_config_preserves_real_default_load(self): result, trace = self.run_starter(None) self.assertEqual(result.returncode, 1) diff --git a/packages/omamobile-modem/version b/packages/omamobile-modem/version index 790629964..0e7400f18 100644 --- a/packages/omamobile-modem/version +++ b/packages/omamobile-modem/version @@ -1 +1 @@ -0.1.21 +0.1.25