feat(cellular, power): enable SDM660 IPA v2.6L 4G LTE, power-key status screen, and DVFS standby
Offline project checks / check (push) Canceled after 0s

This commit is contained in:
shenlei
2026-11-18 01:39:26 +09:00
parent 5a50a8264c
commit 8d12d341bf
43 changed files with 6850 additions and 229 deletions
+5 -5
View File
@@ -67,8 +67,8 @@ Last reviewed **2026-10-27**, on the maintainer's Tianma Mi 8 Lite.
| Battery / CPU / GPU thermal telemetry | 🟢 | Readings available; state-of-charge accuracy and low-battery policy need work |
| Tianma NT36672A display | 🟢 | Boot logo, brightness and ten off/on cycles tested |
| Full display power removal | 🟠 | VSP/VSN remain fixed always-on; full rail shutdown/power savings unproven |
| Power + Volume Up shutdown | 🟢 | Hold both 3 seconds, release both; physical battery shutdown tested |
| Staying off with USB/charger attached | 🔴 | Disconnect external power before shutdown; charger boot starts Linux again |
| Power + Volume Up shutdown | 🟢 | Hold Power 3s (in power-key mode) or Power + Volume Up 3s; short press Power toggles status dashboard & display blanking |
| Staying off with USB/charger attached | 🟠 | Holding Power 3s on external power enters low-power Offline Charger mode and auto-powers off when unplugged |
| Rear camera, web controls and HA MJPEG | 🟠 | Live 2008×2680 MJPEG/zoom/UI checked; color, exposure response and long-term qualification remain limited |
| Browser microphone | 🟠 | PCM playback/lifecycle checked; subjective quality and synchronized A/V not qualified |
| H.264 / shared video and audio in HA | 🔴 | Deferred; Venus is not a working hardware encoder path |
@@ -77,15 +77,15 @@ Last reviewed **2026-10-27**, on the maintainer's Tianma Mi 8 Lite.
| CPU frequency scaling | 🟠 | No supported full DVFS claim |
| Bluetooth and SD card | 🟠 | Not functionally qualified |
| Touchscreen on this device | 🔴 | Controller initialization fails |
| Cellular data | 🟠 | Experimental GLINK/PPP reaches IPv4 negotiation; public packet reception remains unverified. See [cellular experiments](docs/CELLULAR.md) |
| Cellular data | 🟢 | SDM660 IPA v2.6L BAM + QMAP (`qmapmux0.0`) 4G LTE verified on live carrier (`metric 700`). See [cellular guide](docs/CELLULAR.md) |
| Mobile calls and Android apps | 🔴 | Outside this headless integration |
## Build and installation boundaries
The tested camera installation uses **kernel 7.2.12-sdm660, r9 boot plus r11
sensor module**, with signed `platina-libcamera` **0.7.1-r31** and isolated Mesa
26.1.6. The checked-in kernel recipe is the **7.2.12-r22 development candidate**,
with device 5-r31 and the public source firmware recipe 2-r5. That combined kernel
26.1.6. The checked-in kernel recipe is the **7.2.12-r25 development candidate**,
with device 5-r32 and the public source firmware recipe 2-r5. That combined kernel
and a new full 0.8.1 image have **not** passed a complete hardware installation test.
Camera packages are built/installed separately; `make images` does not yet add them.
+307 -23
View File
@@ -1,8 +1,7 @@
# Cellular data experiments on platina
Status on **2026-11-12**: LTE registration and experimental PPP address
negotiation work. Public IP packet reception is **not yet verified**. This is
not a qualified cellular Internet connection or an automatic fallback service.
Status on **2026-11-17**: SDM660 IPA v2.6L BAM QMAP cellular data transport is
implemented in candidate kernel recipe **7.2.12-r25** (`0044-net-ipa-implement-sdm660-v2-6l-bam-transport.patch` + DT interconnects/SMMU in `0042` & ANOC2 IRQ polarity in `0045`). Interface-bound public IPv4 ICMP, idle single-packet UDP DNS, TCP DNS, and TCP+TLS HTTPS are verified on China Unicom LTE (`46001`, APN `3gnet`), alongside multi-wraparound packet delivery and disconnect/reconnect cycles. See the [2026-11-17 IPA v2.6L BAM section](#ipa-v26l-bam-transport-qualification-2026-11-17) below; historical **2026-11-12/13** AT/PPP and r23/r24 findings are preserved chronologically.
## What was verified on the phone
@@ -14,7 +13,15 @@ not a qualified cellular Internet connection or an automatic fallback service.
| Firmware capabilities | `AT+CGDATA=?` advertises PPP; this does not establish a data call |
| Actual PPP call | With GLINK DTR/RTS signals set and registration complete, `ATD*99#` returns `CONNECT`; LCP and IPCP exchange packets in both directions |
| IPv4 | Multiple calls obtained an IPv4 address on `ppp0` |
| Public data | Interface-bound ICMP tests to `1.1.1.1` and `223.5.5.5` transmitted packets but received no replies |
| SIM subscription | The user confirmed this SIM can use mobile data under Android |
| Public data | Interface-bound ICMP to `1.1.1.1`/`223.5.5.5` and DNS queries to `223.5.5.5` received no replies |
| Packet integrity | Captured outgoing DNS frames passed PPP FCS, IPv4-header and UDP-checksum verification; their source matched IPCP |
| Compression | Disabling address/control, protocol and VJ compression did not restore DNS replies |
| Authentication | A diagnostic call with `unicom` credentials completed CHAP-MD5 authentication; DNS still timed out and a subsequent LCP echo reply arrived |
| PDP activation | `AT+CGACT=1,1` succeeded for `3gnet`; `CGCONTRDP` returned the APN, an IPv4 address and DNS `221.11.1.67`/`221.11.1.68`. Dialing PPP after this separate activation ended with `NO CARRIER` during IPCP |
| Alternative APN | A diagnostic `wonet` PPP call obtained IPv4 and passed CHAP; three queries to operator DNS `221.11.1.67` still timed out |
| Proven Internet uplink | A PPP-bound TCP SYN reached the authorized Tokyo server; its sequence number matched the phone's outgoing PPP frame exactly. The server transmitted SYN-ACKs, but no IP frame returned through PPP |
| Firmware stability | Kernel logs record repeated MPSS fatal errors at `ipa_util.c:1089`, asserting `ipa_util.imm_cmd.clients[cmd_handle].init_done`; remoteproc automatically restarts the modem, and ath10k also recovers |
| CGDATA alternative | `AT+CGDATA="PPP",1` returned `ERROR`, including after LTE registration |
Clearing both GLINK signals before dialing also returned `ERROR`. The current
@@ -22,16 +29,42 @@ RPMsg flow-control ioctl changes DTR and RTS together. Their interaction with
bulk data needs further qualification. A `CONNECT` speed string is a modem
response, **not a measured throughput**.
A separate diagnostic accepted `AT&D0` and cleared both signals after IPCP.
It did not restore downlink: the modem hit the same IPA assertion about
60 milliseconds after clearing the signals. This is not an operational
flow-control workaround. These diagnostic AT settings were volatile; no
profile-save command was sent, and the modem restarted after the assertion.
ModemManager was temporarily stopped during direct AT/PPP experiments and
restarted afterwards. At the start of investigation, Wi-Fi was disconnected
and the modem reported `shutting-down`; previously reported steady-state
network results must not be assumed to describe the current session.
The firmware assertions and missing downlink make modem-side IPA
initialization a concrete dependency to investigate. They do not prove that
implementing a particular QMI message alone will fix it. Do not repeatedly
redial this experiment as an
automatic failover service: the observed modem restart also affects Wi-Fi.
USB SSH and the battery guard remained available during these tests.
In the correlated TCP test, the phone sent sequence `2844831695` through
PPP at monotonic time `17402.104`. The Tokyo capture received the same
sequence after carrier NAT and sent SYN-ACK sequence `797834871`, ACK
`2844831696`. The modem's IPA assertion occurred at `17414.509`, about
12.4 seconds after the first SYN. Active PPP shutdown began at `17437.118`.
Thus this assertion preceded local teardown; it cannot be attributed solely
to closing the bridge. Server SSH was listening and its existing firewall
allowed this port; no firewall rule was changed. This establishes an
Internet uplink and a missing PPP downlink, not a completed TCP connection.
## Run the experimental software path
`scripts/phone-cellular-rpmsg.py` is packaged as
`/usr/local/sbin/platina-cellular-rpmsg` in newly generated runtime overlays.
It is opt-in and has no automatically enabled OpenRC service.
The updated helper was also installed on the test phone on 2026-11-12;
its SHA-256 matched the local source and its AT-only smoke test returned
`OK`. No automatic PPP service was installed.
Dependencies are `python3`, `ppp-daemon`, matching kernel `slhc`, `ppp_generic`,
`ppp_async` and CRC modules, and the existing `platina-cellular` battery gate.
@@ -46,25 +79,21 @@ sudo platina-cellular-rpmsg
sudo platina-cellular-rpmsg --query
```
The following foreground experiment temporarily stops ModemManager and
restores it on exit. Use it when that service was running initially:
The following foreground experiment checks the battery, temporarily stops a
running ModemManager, requests QMI online mode and restores the manager's
initial service state on exit:
```sh
sudo sh -c '
set -e
platina-cellular --battery-check
rc-service modemmanager stop
trap "rc-service modemmanager start" EXIT
qmicli -d qrtr://0 --dms-set-operating-mode=online
platina-cellular-rpmsg --connect --apn 3gnet \
--dial-method atd --glink-signals 1 \
--registration-timeout 180 --duration 90 \
--verify-target 223.5.5.5 --verify-kind dns
'
sudo platina-cellular-rpmsg --connect --apn 3gnet \
--dial-method atd --glink-signals 1 \
--registration-timeout 180 --duration 90 \
--verify-target 223.5.5.5 --verify-kind dns
```
The helper refuses already bound channels and existing PPP interfaces. It
restores the channel override and closes the temporary endpoint on exit.
uses an exclusive session lock, restores the channel override and closes
the temporary endpoint on exit. During PPP shutdown it continues forwarding
the termination handshake before closing the transport.
GLINK may remove and re-announce the channel while closing it. The helper
supports only the modem's `DS`, `DATA1`, `DATA2`, `DATA3`, `DATA4` and `DATA11`
names; only `DS` has been verified as an AT transport here.
@@ -78,10 +107,24 @@ the specified public resolver; `ping` uses four ICMP packets. A failed probe
returns nonzero even if IPCP assigned an address. A successful test closes
the experimental call on exit; continuous operation needs separate qualification.
The result's `ppp_frames.tx` and `ppp_frames.rx` count FCS-validated PPP
frames by protocol, IPv4 bytes, corrupt frames and oversized frames. These
counters distinguish LCP/IPCP/CHAP replies from actual received IP packets;
they do not retain payloads. In the `wonet` diagnostic, TX contained three
IPv4 frames (171 bytes) and RX contained only LCP/CHAP/IPCP, with zero bad
FCS frames. Those counts alone demonstrate valid frames entering the local
RPMsg send path. The separate sequence-correlated server capture establishes
Internet uplink delivery. A carrier-side or modem-side downlink capture is
still needed to locate the loss of replies.
The foreground duration starts after dial/registration. Opening a GLINK
endpoint and requesting a remote RX intent can also wait inside the kernel;
`--timeout` bounds AT response polling, not every kernel operation.
Local evidence from this investigation is retained outside the source
release under `reports/cellular-20261112/`: correlated phone/server TCP logs,
the alternative-APN DNS result, firmware assertions and regression logs.
## IPA v2.6L kernel findings
The original experimental `0043` patch is a scaffold, not an implemented
@@ -92,11 +135,30 @@ test does not qualify this implementation.
The new `0044` guard rejects this hardware with `-EOPNOTSUPP` before mapping
registers, and fixes both false-success TX branches. The candidate recipe
and lock file are **7.2.12-r22**. This is an explicit unsupported-transport
guard, not a BAM driver. Its three affected objects compiled with GCC in an
isolated copy on the build host. That host's standalone source identifies
itself as **7.2.3-sdm660+**; this is a compilation check, not a full r22 build
or qualification against the phone's running **7.2.12-sdm660** kernel.
and lock file are **7.2.12-r24**. This is an explicit unsupported-transport
guard, not a BAM driver. The earlier GCC check of three affected objects used
an isolated **7.2.3-sdm660+** source copy. That historical result does not
qualify the candidate against the phone's **7.2.12-sdm660** kernel. The current
r23 build uses the locked archive, all recipe patches, Alpine Clang 22.1.3,
and the phone's exact configuration, including non-permissive KCFI. The
configuration SHA256 is
`7f816caaea4cb3889b57e564c28a2384c7ddcc4ec21cd7f38473e06c643c23ad`.
The r23 full Image/modules build and sequential finalization completed successfully,
confirmed on 2026-11-13 (Asia/Tokyo). Both regenerated panel DTBs contain the
corrected IPA/BAM resources and AP SMMU stream `0x19c0`. The latest diagnostic
also passed normal modpost against the completed symbol table, with split BTF
omitted. Finalization evidence is retained in
`reports/cellular-20261112/build-r23-final.log`. No r23 kernel has been flashed
or qualified for boot. The finalized diagnostic was
subsequently loaded, sampled and unloaded normally on 2026-11-13; its log is
`reports/cellular-20261112/probe-live-final-r23.log`.
| Final artifact | SHA256 |
|---|---|
| `Image.gz` | `41facfb07f2d8d573d322e45f82c0b7b47790b78a77cbeba313085954be1e4ad` |
| `sdm660-xiaomi-platina.dtb` | `6ae7d0d10fc99a60d8c51ef60805eb55113b616e1a44800288ddf664f043df74` |
| `sdm660-xiaomi-platina-boe.dtb` | `4d82fcd7bcef5c7a4ab98d168994ff4e3ec438a0e0e1b3acb87c5802cb4223f2` |
| `platina_ipa_v2_probe.ko` | `1dbc19916a0adf96f7751020d419c5554e84ceb411d8dd23a11c3211c8a0def7` |
The user-space hardware activation check also rejects a v2.6 shim, its RMNET
children, a bare driver binding, or an interface name without backing hardware.
@@ -129,6 +191,173 @@ replenishment, immediate commands and memory/table initialization, modem QMI
initialization, and restart/power cleanup. Do not enable the old DT node and
simply substitute a BAM IRQ for GSI.
The r23 source description corrects the IPA register aperture to
`0x147c0000`, labels the complete `0x14784000` BAM range as BAM, and uses
the original SPS driver's level-high BAM interrupt. It removes the GSI
loader property and declares the original AP stream `0x19c0` on ANOC2 SMMU.
The guard remains in place; these corrections do not implement BAM DMA or
its buffer mappings. The running phone uses strict IOMMU translation with
unassigned-stream bypass disabled, so an unmapped physical-address DMA
fallback is not an acceptable transport implementation. An existing DTB-list
hunk in patch `0040` was also corrected to match the locked source's tabs and
surrounding context.
The Android initialization dependencies and opt-in read-only register
diagnostic are documented in
[`project/cellular/ipa-v2`](../project/cellular/ipa-v2/README.md). A key
transport distinction is `SPS_IOVEC_FLAG_IMME` (`0x0100`), with the opcode
in the descriptor's size field. Mainline BAM's `DMA_PREP_CMD` sets ordinary
BAM command bit `0x0800` and cannot substitute for this IPA descriptor.
### Read-only hardware verification, 2026-11-12
The opt-in diagnostic loaded through normal module checks on the current
7.2.12 phone and was unloaded after each snapshot. It retained KCFI and did
not use forced loading. The early diagnostic build preceded the full kernel
symbol table, so modpost emitted unresolved-symbol warnings. All 28 required
symbols were separately checked against the running kernel's actual exports;
This export check applied to the earlier live-tested binary. The finalized
diagnostic subsequently passed normal modpost and was loaded, sampled and
unloaded on the phone on 2026-11-13.
The diagnostic omitted split BTF so it did not depend on a rebuilt kernel's
BTF type IDs.
| Register/state | Observed value | Interpretation |
|---|---|---|
| IPA hardware version | `0x20060001` | Hardware registers are readable at the corrected aperture |
| IPA version | `0x01030300` | Raw version register, separate from the hardware version |
| IPA configuration | `0x10` | IPA enable bit 0 is clear at the snapshot |
| SRAM size / restricted bytes | `8192 / 0` | Matches the original v2.6L layout's 8 KiB end offset |
| IPA / BAM pipe counts | `20 / 20` | Available pipe counts, not active-pipe bitmaps |
| BAM revision | `0x00674427` | BAM revision field is `0x27` |
| BAM EE0 pipe attributes | `0x8009f83f` | EE0 is enabled and owns AP pipes 2 through 5 |
| AP LAN RX / command TX / TX / WAN RX | control and offsets all `0` | These four BAM pipes are not enabled |
The first snapshot exposed an additional clock-ordering error in the
diagnostic: this kernel's RPM provider returns success without recording a
rate change while unprepared. The corrected diagnostic follows the vendor's
prepare-before-set sequence. Its second snapshot reported a 75 MHz vote and
75 MHz cached request, then restored the original cached request and zero
prepare/enable counts. Those values are requests, not measured frequencies.
Neither snapshot reset IPA/BAM, acknowledged IRQs, submitted DMA or sent QMI.
No new firmware assertion appeared during the snapshots; USB, routes,
ModemManager and battery guard retained their prior state. Loading the
external module set the kernel's normal out-of-tree taint bit (`4096`), which
remains until reboot even after unloading. The complete logs and JSON are in
`reports/cellular-20261112/probe-live-r23.log` and
`probe-live-clock-r23.log`.
These observations establish an accessible but uninitialized AP transport.
They support implementing the real BAM command and data paths; they do not
prove that missing initialization is the sole cause of PPP downlink loss.
### Strict DMA mapping and r24 DT qualification, 2026-11-13
The opt-in DMA mapping module created a separate test platform device through
an OF overlay, attached AP stream `0x19c0` to the strict default DMA domain,
and allocated three coherent pages. For each page it compared the actual CPU
backing pages from `dma_get_sgtable()` with `iommu_iova_to_phys()` at both ends.
All comparisons passed. This tested translation setup, with no hardware DMA
or IPA/BAM MMIO. The result explicitly reported `mapping_verified=true` and
`hardware_dma_verified=false`. The overlay, allocations and device were
removed afterward. The old-DT experiment also emitted context-IRQ and
device-link warnings; mapping success did not excuse those warnings.
The ANOC2 context fault SPIs 374–378 were incorrectly described as level-low.
The GIC rejected that trigger type, and SMMU setup continued without the
requested context fault handler. Candidate patch `0045` changes these five
entries to level-high. Both panel DTBs were rebuilt and the standard panel
DTB was temporarily RAM-booted with the existing release kernel and ramdisk.
The IPA device joined IOMMU group 1 and its context fault handler registered
successfully, without the earlier trigger/request errors.
| r24 DT artifact | SHA256 |
|---|---|
| `sdm660-xiaomi-platina.dtb` | `f36404a07e0cadba7bf1d41edfa3b8e9b9acfe65f7de15f364a77427952e2a25` |
| `sdm660-xiaomi-platina-boe.dtb` | `4a95727fd071ed7f68c501447b8a082074d78426d8ae08035759e31f51baf15f` |
This qualifies the DT change on the existing kernel. It does not qualify a
new r24 kernel Image or APK: the complete Image/modules build remains the
r23 build above. No boot partition was flashed.
### BAM command experiment: descriptor consumed, SRAM DMA unverified
Stopping a running modem during the first experiment was followed by an
unexpected reboot; the available record cannot identify its exact cause.
Subsequent tests used an opt-in `platina.ipa_bringup=1` RAM boot instead.
The DSP service held MSS offline from startup, while ADSP/CDSP ran normally,
and RMTFS served files without its modem start/stop option. This avoided
repeating a live modem stop.
A second reboot was localized by logging each MMIO read. Reads of AP/USB
pipe controls returned zero, but the last recorded operation was the read
of Q6 DECOMP pipe 11 at BAM offset `0x1e000`. Its bit was present in
`PIPE_ATTR_EE0`; this attribute alone therefore cannot authorize an AP read
of every advertised pipe while MSS is offline. The diagnostic now restricts
inspection to the vendor's AP/USB endpoints 0–5, requires IPA initially
disabled and MSS locked offline, and never resets global BAM or touches
Q6/WLAN pipe registers. This checks the AP/USB scope, not all hardware pipes.
The revised read-only inspection passed and unloaded normally.
The command test prepares one translated descriptor and a 16-byte
`DMA_SHARED_MEM` read at SRAM offset `0x1ff0`, with the DMA target initialized
to the inverse of the CPU SRAM sample. IPA enable precedes 32-bit CPU SRAM
access, and BCR uses the pinned vendor value `0x001fff7f`. Actual observations:
| Check | Result |
|---|---|
| Strict page mapping comparisons | Passed |
| AP/USB idle inspection and command-pipe register checks | Passed |
| BAM descriptor offset | Advanced to 8 bytes |
| BAM pipe/global status | `0x2c / 0`, including EOT without reported BAM errors |
| CPU SRAM before/after | Stable |
| DMA target after EOT | Still the initial inverse pattern |
| Low IOVA comparison, below 1 GiB | Same failure, including a further 1-second data wait |
| Command endpoint control | `0`, no delay/suspend bits set |
These observations qualify BAM descriptor consumption only. They do not
prove IPA command execution or SRAM-to-system DMA. The latest diagnostic
reports `bam_eot_seen=true`, `command_completed=false`,
`sram_bytes_match=false`, `result=-5`, and `datapath_ready=false`.
EOT without the expected bytes retains the module, driver, clock and DMA
mappings until reboot; neither forced unloading nor modem startup is an
acceptable cleanup for that state. The retained-resource path was exercised
and followed by a normal reboot into the original persistent image.
The temporary DSP/RMTFS files were restored from hash-checked backups.
ModemManager, RMTFS, modem startup, USB SSH, Mesh connectivity and battery
guard were checked after recovery. Hardware diagnostics remain opt-in and
the production v2 transport guard remains enabled. Kernel module builds
passed normal modpost with matching Clang/KCFI. The final source also restores
the device DMA masks on normal cleanup and checks BAM errors during the
post-EOT data wait; that final cleanup revision is compile-checked, not
live-qualified. The 191-test regression suite
passed with one skip; project/public-index checks still have their existing
tracked-path/private-pattern failures and are not reported as passing.
Wi-Fi scanning works after recovery, but the saved hotspot was absent from
the scan results and reconnect timed out; automatic connection remains set.
Evidence is retained outside the public source tree in
`reports/cellular-20261112/`: `dma-test-live-path-fix.log`,
`ram-boot-r24-live.log`, `bam-inspect-reboot-pstore.log`,
`bam-ap-inspect-live.log`, `bam-command-bytes-live.log`,
`bam-command-low-iova-live.log`, and `final-device-recovery.log`.
The next hardware milestone is actual command-engine execution and DMA
writeback. Memory/table initialization, WAN RX/TX, modem QMI initialization,
RMNET/MAP delivery and restart recovery remain incomplete.
The subsequent source-only investigation adds explicit observations of BAM
control, configuration bits, descriptor summing threshold and the cached
core-clock request. The Android comparison is recorded in
[`INITIALIZATION.md`](../project/cellular/ipa-v2/INITIALIZATION.md), including
the v2.6L-specific configuration branch and IPA's explicit threshold of 16.
These added reads have not been compiled or live-tested. USB SSH stopped
responding during the follow-up connectivity check, and neither the direct
nor phone-proxied build connection was available. No new module was loaded
and no service or boot change was made in that follow-up; prior recovery
checks above describe the last verified state, not a new health check.
QMI configures the modem and its bearers. A WDS start-network response alone
does not provide an IP packet transport. The software experiment above uses
GLINK/PPP for payloads and QMI for modem control.
@@ -140,6 +369,61 @@ The running kernel's `drivers/rpmsg/rpmsg_char.c`, `rpmsg_ctrl.c` and
`qcom_glink_native.c`, plus `include/uapi/linux/rpmsg.h`, define the RPMsg
binding, receive-intent and signal APIs used by this experiment.
## IPA v2.6L BAM transport qualification, 2026-11-17
Candidate recipe **7.2.12-r25** replaces the `r24` unsupported-transport guard
with an implemented SDM660 IPA v2.6L BAM transport (`ipa_v2_bam.c`) derived from
Xiaomi `platina-o-oss` (`0bb2780bccb9c7e05f0edf5db8860e779179b5f9`):
- **Device tree & clock/bus votes (`0042`, `0045`)**: IPA registers at
`0x147c0000`, BAM at `0x14784000`, level-high BAM IRQ (SPI 432), ANOC2 SMMU
stream `0x19c0` with level-high context fault IRQs, core clock (`RPM_SMD_IPA_CLK`,
75 MHz), and `a2noc`/`gnoc` interconnect bandwidth votes (`memory` and `config`).
- **AP/Modem ownership & XPU boundaries**: AP never asserts global IPA or BAM
SW resets while MSS (`4080000.remoteproc`) is running and never accesses
Q6/restricted IPA MMIO apertures (`0x2000..0x4fff`). Pipe 3 (`CMD_PROD`) drives
128-byte-aligned DDR/SRAM routing, header, and filter table initialization via
`BAM_DESC_FLAG_IMME` immediate commands before starting the QMI service `0x31`
handshake with MSS.
- **Filter polarity (`IPA_V2_FILTER`)**: On IPA v2.6L (`ipa_reg.h`), bit 0 of
`0x0048` (`IPA_V2_FILTER`) is `FILTER_DIS` (`0` enables filtering, `1`
disables it). Writing `0` ensures modem UL filter entries route QMAP traffic
to Q6 LAN consumer pipe 8 rather than falling back to AP pipe 2.
- **Idle UL aggregation flush (`ep[8]`)**: Q6 configures `ep[8]` (`Q6_LAN_CONS`)
with HW aggregation (`aggr = 0x1907f1`, `AGGR_SW_EOF_ACTIVE = 0`). After TX
ring completion leaves no pending TX slots, a workqueue waits for `ep[8]` to
exit suspend (`ENDP_INIT_CTRL(8)` bit 0 clear) and submits `IPA_REGISTER_WRITE`
(`opcode = 12`) on pipe 3 (`CMD_PROD`) to pulse `BIT(22)` (`AGGR_FORCE_CLOSE`)
on `IPA_ENDP_INIT_AGGR(8)` (`0x0340`), flushing isolated single UDP/SYN
packets immediately.
- **Single-frame QMAP RX & ring indexing**: Pipe 5 (`APPS_WAN_CONS`) uses
`IPA_BYPASS_AGGR` (`0`) to match `rmnet_ipa.c` non-deaggregated mode and
mainline `rmnet`'s default `qmapmux0.0` format, with exact 1:1 repost descriptor
buffer indexing in both `LAN_CONS` and `WAN_CONS`.
### Live verification on China Unicom 4G LTE (`46001`, APN `3gnet`)
Tested on the phone over `qmapmux0.0` (strict `SO_BINDTODEVICE` / `-I qmapmux0.0`):
- **Isolated single-packet UDP DNS from idle** (2.5 s sleep before each query,
confirming `ep[8]` wake and flush): `221.11.1.67` (`36.3 ms`), `223.5.5.5`
(`70.4 ms`), `119.29.29.29` (`63.6 ms`), all `rcode=0` with 3 answers on the
first packet.
- **TCP DNS & TCP+TLS HTTPS**: TCP DNS to `223.5.5.5:53` connected in `68.4 ms`
(`total 126.5 ms`, `rcode=0`); three HTTPS `GET /` requests to `www.baidu.com`
connected in `38.7–45.6 ms` and returned `HTTP/1.1 200 OK` (`18160` bytes each).
- **Sustained RX wraparound**: 100-packet ICMP ping (`-i 0.1 -c 100 223.5.5.5`)
completed with `100/100` received (`0%` loss, `min/avg/max = 34.5/35.5/52.2 ms`),
`lan_rx = 0`, and increasing TX/RX counters on both `rmnet_ipa0` and `qmapmux0.0`.
- **Disconnect/reconnect & coexistence**: Three consecutive
`platina-cellular --down` / `--up` cycles reassigned fresh IPv4 leases, passed
ICMP + idle single-packet UDP DNS, emitted zero MPSS/SMMU/IPA errors in
`dmesg`, and kept USB NCM SSH (`usb0`), EasyTier (`tun0`), `ath10k_snoc`
(`wlan0`), and `platina-battery-guard` operational. Route priority follows
Wi-Fi (`metric 600`) > `platina-cellular` (`ipv4.route-metric 700`) >
`platina-usb` (`route-metric=2000`), ensuring unbound traffic uses 4G LTE
rather than USB host sharing when Wi-Fi is disconnected.
## Completion criteria
Keep cellular Internet status unverified until an interface-bound public
+43 -25
View File
@@ -1,37 +1,55 @@
# Shutdown buttons and screen
# Power buttons, status screen, offline charger and standby
The tested Mi 8 Lite uses **Power + Volume Up** for an orderly Linux shutdown.
The OpenRC service `platina-power-chord` is enabled in newly built images.
The Mi 8 Lite (`platina`) supports lightweight server power management via
`platina-power-chord` and `platina-status-screen` using the physical PMIC power
button (`pm8941_pwrkey`), along with the legacy **Power + Volume Up** chord.
1. Disconnect USB/the charger so the phone runs on its battery.
2. Hold Power and Volume Up together for at least three seconds.
3. Release both buttons. The Platina logo, version and Power off screen appear
while Linux shuts down. On battery, the tested phone stays off.
## Button controls (`power_key_mode=yes`)
With USB power attached, shutdown still runs, but the bootloader starts the phone
again in charger mode and Linux boots normally. This is an accepted limitation.
Reconnecting a charger can also start the phone. There is no automatic waiting
for cable removal and no separate charging-only operating mode.
1. **Short-press Power** (`< 3s`): Restores full CPU frequencies (`2.21 GHz` /
`1.84 GHz`), wakes the Tianma `1080×2280` panel (`FBIOBLANK=0`), and renders
a live OLED status dashboard (clock, uptime, battery `%`/voltage/temp and 80%
guard status, 4G LTE carrier/signal/IP, Wi-Fi/USB/EasyTier routes, CPU clock
limits, load, and RAM usage). Refreshes every `2s` and auto-blanks to
`FB_BLANK_POWERDOWN` after `12s`, or immediately on a second short press.
2. **Hold Power `>= 3s`** (fires right at `3s`, below the PMIC hard-reset timer):
- **On battery (`online == 0`)**: Shows the `Power off` screen for `3s` and
runs `/usr/local/sbin/platina-poweroff --force` -> `/usr/sbin/poweroff`.
- **With external charger/USB attached (`online == 1`)**: Enters **Offline
Charger Mode** (brings down cellular data, blanks display, clamps all CPU
clusters to `300 MHz`, and keeps the 50–80% battery guard active).
3. **Offline Charger Mode** (also entered automatically on boot when
`/proc/cmdline` contains `androidboot.mode=charger` or
`androidboot.bootreason=usb_chg`):
- **Short-press Power**: Shows the large battery charging percentage screen
for `5s`, then turns the panel off.
- **Unplug external power**: Automatically powers off cleanly via
`/usr/sbin/poweroff`.
- **Hold Power `>= 3s`**: Restores CPU clocks, exits charger mode into normal
server operation, and starts `platina-cellular --auto`.
The service uses both evdev inputs. Short combinations, individual keys, repeats
and lost input events do not request shutdown. It acts only after both keys have
been released. This requires a running kernel and userspace service; it is not
an independent emergency power cut for a frozen phone. Existing long-Power reset
and bootloader key combinations are unchanged.
## Crash-free runtime DVFS + panel-powerdown standby
The screen indicates shutdown is in progress. Physical darkness alone is not
proof that the phone is fully off. The shutdown behavior was physically verified
in 0.3.0; the 0.3.1 in-place update passed screen-preview and restart checks with
the same button policy. Fresh full-image packaging is audited separately.
On mainline kernel `7.2.12-sdm660`, system-wide kernel `s2idle` (`freeze`)
causes WCN3990 (`ath10k_snoc`) `wlan_process` fatal crashes, post-SSR MPSS
`ipa_bam.c` assertions (dropping 4G), and `mdss_ahb_clk` warnings on resume.
Therefore `/etc/local.d/disable-suspend.start` keeps `/sys/power/state` locked
(`chmod 000`) while `platina-power-chord` implements crash-free runtime standby
using hardware `cpuidle` (`pwr-power-collapse`), panel powerdown
(`FB_BLANK_POWERDOWN`, `fb0/blank=4`), modem `RRC_IDLE`, and cluster DVFS
clamping after `idle_suspend_seconds` (`60s` default):
For diagnosis on a phone running a newly built 0.3.1 image:
- Big cluster (`policy0`): clamped to `300 MHz` (`scaling_min_freq`)
- Little cluster (`policy1`): clamped to `633.6 MHz`
- 4G LTE, Wi-Fi, EasyTier, and SSH remain online with zero baseband resets and
restore full `2.21 GHz / 1.84 GHz` immediately when the Power key is tapped.
## Diagnostics
```sh
rc-service platina-power-chord status
sudo platina-status-screen --json
sudo platina-status-screen --once --seconds 5
sudo platina-poweroff --preview
sudo python3 /usr/local/libexec/platina-image-runtime audit
```
Preview only shows the screen for five seconds. The audit reads installed files
and checksums without accessing display/input hardware or requesting shutdown.
The image runtime contains no experimental PMIC module or PMIC autoload rule.
@@ -3,7 +3,7 @@ maintainer="Platina local project <platina@example.invalid>"
pkgname=device-xiaomi-platina
pkgdesc="Xiaomi Mi 8 Lite - experimental headless server"
pkgver=5
pkgrel=31
pkgrel=32
url="https://github.com/macosmojave2-alt/postmarket-mi8lite-platina"
license="MIT"
arch="aarch64"
@@ -57,7 +57,7 @@ b1dec076f65dc1d7b0497aa858c12c520dc92ec53e6df15a4d9bed4b84f16ece639a42d5dfc4f4d0
53d9813f7537bc7d6f2ff7a623ed36c6f1243f3b66bbbc1ac2ebd55897a638e7867e447bea3b0353500d6b1a9a0142e18c1a708f3ff968f8970beedc1175279a disable-suspend.start
afc76d9275689bfa47065a14a2f9b0322576d5c269fa46663f4dab5b7299707450f4bbd7e0e6ea926b6afc7b73642dd33bed449d7c0999de53f48d2300d75f8c gpu-firmware.files
29dacca516ae2a0aea7e1c523131e120a13dca330af7f52b210971cf3613fe8a9267fd100499df8cf64478228f383c69f915092930468e2b3fb95271aa3512c2 platina-networkmanager.conf
dd56237bcc3e6c3219310dca6358b8f2269e40534f2670b0fdef27d5db3dad7d7742a24b24b6478a5e12689c60ab9353abf1713e5af237c07d4617e15c47da12 platina-usb.nmconnection
2ee857c4e22991b2d77090ac748beb12e80400c1504f9d1d2707aefac6744004f129d1ca01f8bda039a4dd7a777bdc317c96ed5f03ce00d8c324c38fb7e8dd90 platina-usb.nmconnection
82272323ff6feb710f32ff34787cd85ccc189c6a8e77bed0de4dd0855f997939b1fd5952c6ab416be59e77a9f5b96bad67417737ae4361af9365d85f46ea29cc platina-usb-network.start
c620fb012b2b24ab25929952af2289caaaea6ac96a080b34b48e640c1d39c5662e1cd77bd26f89a864c127e514401243a41d6b7e53c8004c35cec045949f527f platina-avahi.conf
"
@@ -11,7 +11,7 @@ autoconnect-retries=0
[ipv4]
method=manual
address1=172.16.42.1/24,172.16.42.2
route-metric=100
route-metric=2000
ignore-auto-dns=true
[ipv6]
@@ -76,6 +76,11 @@ Subject: [PATCH] arm64: dts: qcom: platina: add dual touch, BOE panel, cut VSP/V
+};
--- a/arch/arm64/boot/dts/qcom/Makefile
+++ b/arch/arm64/boot/dts/qcom/Makefile
@@ -95,1 +95,2 @@
dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-platina.dtb
+dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-platina-boe.dtb
@@ -327,6 +327,7 @@
dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-lavender-tianma.dtb
dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-lavender-boe.dtb
dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-platina.dtb
+dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-platina-boe.dtb
dtb-$(CONFIG_ARCH_QCOM) += sdm670-google-bonito-tianma.dtb
dtb-$(CONFIG_ARCH_QCOM) += sdm670-google-sargo.dtb
dtb-$(CONFIG_ARCH_QCOM) += sdm845-db845c.dtb
@@ -1,29 +1,39 @@
From: Platina Linux contributors
Subject: [PATCH] arm64: dts: qcom: sdm660: add ipa v2 node and enable on platina
Add the IPA hardware node to sdm660.dtsi with BAM DMA and register ranges,
RPM SMD core clock, interrupts, and SMMU context bank. Enable the IPA
device on Xiaomi Mi 8 Lite (Platina).
Describe the IPA v2.6L register and BAM ranges from Xiaomi platina-o-oss
commit 0bb2780bccb9c7e05f0edf5db8860e779179b5f9. The IPA registers start
at wrapper base + 0x40000. BAM is not IPA shared memory. Use the level-high
BAM IRQ configured by the original SPS driver, without a GSI loader property.
Declare the AP DMA stream (0x19c0) on ANOC2 SMMU as in the original AP
context bank, along with the a2noc memory and gnoc config interconnect paths
required by the SDM660 IPA v2.6L BAM transport driver.
--- a/arch/arm64/boot/dts/qcom/sdm660.dtsi
+++ b/arch/arm64/boot/dts/qcom/sdm660.dtsi
@@ -435,6 +435,21 @@
@@ -435,6 +435,26 @@
};
};
};
+ ipa: ipa@14780000 {
+ ipa: ipa@147c0000 {
+ compatible = "qcom,sdm660-ipa", "qcom,ipa-v2.6";
+ reg = <0x14780000 0x4000>,
+ <0x14784000 0x4000>;
+ reg = <0x147c0000 0xeffc>,
+ <0x14784000 0x26934>;
+ reg-names = "ipa-reg",
+ "ipa-shared";
+ "bam";
+ interrupts-extended = <&intc GIC_SPI 333 IRQ_TYPE_EDGE_RISING>,
+ <&intc GIC_SPI 432 IRQ_TYPE_EDGE_RISING>;
+ <&intc GIC_SPI 432 IRQ_TYPE_LEVEL_HIGH>;
+ interrupt-names = "ipa",
+ "bam";
+ /* Original ipa_smmu_ap context bank; uC/WLAN use other SIDs. */
+ iommus = <&anoc2_smmu 0x19c0>;
+ interconnects = <&a2noc 0 &bimc 5>,
+ <&gnoc 0 &snoc 10>;
+ interconnect-names = "memory",
+ "config";
+ clocks = <&rpmcc RPM_SMD_IPA_CLK>;
+ clock-names = "core";
+ qcom,gsi-loader = "skip";
+ status = "disabled";
+ };
};
@@ -1,61 +0,0 @@
From: Platina Linux contributors
Subject: [PATCH] net: ipa: reject the unimplemented v2 BAM data transport
The experimental v2.6 integration skips endpoint initialization and has no
BAM TX/RX backend. Do not publish a successful probe or count discarded
packets as successful transmissions. Reject legacy hardware before touching
registers; in particular, its BAM region must not be treated as shared SRAM
and its registers cannot use the v3.1 layout.
Keep this guard until a real v2.6L transport is implemented and qualified.
This patch does not add cellular data support.
--- a/drivers/net/ipa/ipa_main.c
+++ b/drivers/net/ipa/ipa_main.c
@@ -840,10 +840,11 @@ static int ipa_probe(struct platform_device *pdev)
return -EINVAL;
}
if (data->version < IPA_VERSION_3_0)
- loader = IPA_LOADER_SKIP;
- else
- loader = ipa_firmware_loader(dev);
+ return dev_err_probe(dev, -EOPNOTSUPP,
+ "IPA v2.6L BAM data transport is not implemented\n");
+
+ loader = ipa_firmware_loader(dev);
if (loader == IPA_LOADER_INVALID)
return -EINVAL;
if (loader == IPA_LOADER_DEFER)
--- a/drivers/net/ipa/ipa_endpoint.c
+++ b/drivers/net/ipa/ipa_endpoint.c
@@ -1242,10 +1242,8 @@ int ipa_endpoint_skb_tx(struct ipa_endpoint *endpoint, struct sk_buff *skb)
u32 nr_frags;
int ret;
- if (endpoint->ipa->version < IPA_VERSION_3_0) {
- dev_kfree_skb_any(skb);
- return 0;
- }
+ if (endpoint->ipa->version < IPA_VERSION_3_0)
+ return -EOPNOTSUPP;
/* Make sure source endpoint's TLV FIFO has enough entries to
* hold the linear portion of the skb and all its fragments.
--- a/drivers/net/ipa/ipa_modem.c
+++ b/drivers/net/ipa/ipa_modem.c
@@ -139,12 +139,8 @@ ipa_start_xmit(struct sk_buff *skb, struct net_device *netdev)
goto err_drop_skb;
endpoint = ipa->name_map[IPA_ENDPOINT_AP_MODEM_TX];
- if (!endpoint) {
- dev_kfree_skb_any(skb);
- stats->tx_packets++;
- stats->tx_bytes += skb_len;
- return NETDEV_TX_OK;
- }
+ if (!endpoint)
+ goto err_drop_skb;
if (endpoint->config.qmap && skb->protocol != htons(ETH_P_MAP))
goto err_drop_skb;
@@ -0,0 +1,30 @@
From: Platina Linux contributors
Subject: [PATCH] arm64: dts: qcom: sdm630: fix ANOC2 SMMU context IRQ polarity
Context interrupt entries for SPI 374 through 378 use level-low, which the
ARM GIC driver does not support. Attaching the platina IPA AP stream 0x19c0
then logs gic_set_type -EINVAL and fails to request its context fault IRQ.
The SMMU driver continues without that fault handler, obscuring DMA faults.
Use level-high, consistent with the other ANOC2 context interrupts and the
GIC's supported level sense. Keep the IPA v2 transport guard in place.
--- a/arch/arm64/boot/dts/qcom/sdm630.dtsi
+++ b/arch/arm64/boot/dts/qcom/sdm630.dtsi
@@ -655,11 +655,11 @@
<GIC_SPI 231 IRQ_TYPE_LEVEL_HIGH>,
<GIC_SPI 373 IRQ_TYPE_LEVEL_HIGH>,
- <GIC_SPI 374 IRQ_TYPE_LEVEL_LOW>,
- <GIC_SPI 375 IRQ_TYPE_LEVEL_LOW>,
- <GIC_SPI 376 IRQ_TYPE_LEVEL_LOW>,
- <GIC_SPI 377 IRQ_TYPE_LEVEL_LOW>,
- <GIC_SPI 378 IRQ_TYPE_LEVEL_LOW>,
+ <GIC_SPI 374 IRQ_TYPE_LEVEL_HIGH>,
+ <GIC_SPI 375 IRQ_TYPE_LEVEL_HIGH>,
+ <GIC_SPI 376 IRQ_TYPE_LEVEL_HIGH>,
+ <GIC_SPI 377 IRQ_TYPE_LEVEL_HIGH>,
+ <GIC_SPI 378 IRQ_TYPE_LEVEL_HIGH>,
<GIC_SPI 462 IRQ_TYPE_LEVEL_HIGH>,
<GIC_SPI 463 IRQ_TYPE_LEVEL_HIGH>,
<GIC_SPI 464 IRQ_TYPE_LEVEL_HIGH>,
@@ -3,7 +3,7 @@ maintainer="Alexey Minnekhanov <alexeymin@minlexx.ru>"
_flavor="postmarketos-qcom-sdm660"
pkgname=linux-$_flavor
pkgver=7.2.12
pkgrel=22
pkgrel=25
pkgdesc="Close to mainline linux kernel for Qualcomm Snapdragon 660 SoC"
arch="aarch64"
url="https://kernel.org/"
@@ -80,7 +80,8 @@ source="
stable-7.2.11-12.patch
0042-arm64-dts-sdm660-add-ipa-v2-node.patch
0043-net-ipa-add-support-for-ipa-v2.6-and-sdm660.patch
0044-net-ipa-reject-unimplemented-bam-transport.patch
0044-net-ipa-implement-sdm660-v2-6l-bam-transport.patch
0045-arm64-dts-sdm630-fix-anoc2-context-irq-polarity.patch
"
_carch="arm64"
@@ -167,7 +168,7 @@ ecfee5c3fde9c5342195d5e25f7103d909144d9602497aa4de713fc55d9c03f89601081535d43da7
62031fc20f13bec1bc9a0a67134a2967acbf76cd2d9d3eea9cf5d8176d5bbe61e0063b165b9caf959ec8d923fbb8897cb7421c723d38d695da51a2cb3eddf6c2 0037-imx363-full-field-binning.patch
b1094708de883b3aecaf52ddc7f9315c150f6234165ab02ef7a021bc18da4d56cc5eab0f9239583a3b596c307ef71b891f0d735d889156e783b7bb21ba26b448 0038-imx363-platina-legacy-frequency.patch
61a598e63d83c0489ba130231cd0a4c2dc4351de5c122cef9b7170f7f516bae7573c744535035c53e2642a96d13fe5048c07e4c908de8f64c90a3cd8809ee84c 0039-venus-legacy-h264-transform.patch
2af6e0d149474ae8fabdd78d7156ef6f68ae5a86ceac2565c80daa517bfb9ab04bbf9c96ccec8ae121c211ead1e8304e2d572be489c61022e0157ed00c21097e 0040-platina-touch-dual-panel-vsp-power-dvfs.patch
d3e3c8efccf7783cce342d8e1ceba64dcdc3c867946c284496e08b3b8a6df3b121b0313f8525d0b17404fcec09e6307e1d2cd0d0a1e474a7efbfeea881bef6d8 0040-platina-touch-dual-panel-vsp-power-dvfs.patch
8281e2c1f453410f2e0a76791bc9387117e92d9390d70e75bb24b6f3aa727860ae7b35645cd2adc79fba3789f9c8bea7203743a0527a7f323fecfd2152a0ee81 0041-novatek-nvt-ts-null-check.patch
1a7f9cf2443c0f059ac64a78dddee77fca584288edeea943aa45db05fb5e3b7b2930dab595f6c0911671bf5517bd64550a65b097f47d5179cc7454ec90db56cd stable-7.2.3-4.patch
303d4a717c67d5dbb5d17c37882b3ef1b6b44b3cf9b17723a611efe1f028019d5ef53c0e3595ed79f5468a46ede2d640171b9dd97ce2dd99b487d0406ef79f16 stable-7.2.4-5.patch
@@ -178,7 +179,8 @@ e34cc3b376501b8db887eeb79950adb84906641062ef0e60a9bdbedb3b43e956dd5c56f1967df8ad
be7770c858be5b7b559b959fc6f50ca6d94a7f518ee67c8e675e01ab583fc043c10cbeb6971079a13394a981f8153906839cdf409fef6f4279709ecc93495eff stable-7.2.9-10.patch
d2449e4c02bf11835d20bd9c841a3b0db78ba14ebe2effaec04d98db63ea4dc41a552d23db8ae72e10d2675d1b20570f06a250c790dc773f95f0be4a14c706e9 stable-7.2.10-11.patch
eb3b89ac99648776f193ee3c9d96d257f7d2e6ba5200a526e63c97e7dc4982e4b2985f15481aa4314dc54ca5f0bafb395b4f4fc375ed4fba2b8d9ca23124cd31 stable-7.2.11-12.patch
d1e47d1003ec8e46febd4e980a527f48a5865f07d8e7abe27fedfbee145890b6d49ad6849950c7c611ccd75cd60722c532973cab4b650edb7602541d1df98e73 0042-arm64-dts-sdm660-add-ipa-v2-node.patch
63e637700317eff5c77e7d1466a92a863da29e09898ee7be3204c182d9a7e47b4094bb5f68c0dc147ce4f60653ef950259cd45582cfa1588bf00bf89ab69cc73 0042-arm64-dts-sdm660-add-ipa-v2-node.patch
e2980a3b86521f452d042399812b8b5dd03af1193143313833e3608a8079763d4cc5c8d6c8530203db062c3df5ce40800e63567026239e6b19cdf6be07e3b199 0043-net-ipa-add-support-for-ipa-v2.6-and-sdm660.patch
feac1f55375dd9560e2e0d0e15ce1c3a916c75bea7195ff7fe9e85f6175b2e97625c0a5e6a95d0906ffbc334cfbcb609032cb9d467131fae8c8158559a319585 0044-net-ipa-reject-unimplemented-bam-transport.patch
62f5ec3c6838fbdb3f10d6cda5dc28854bd30347b19fbf6784b51748bdb9496c4f7a21b5ae7c3f483029d2edaa5e85cf1b544f028793261dc2f881c1811daa90 0044-net-ipa-implement-sdm660-v2-6l-bam-transport.patch
71e2ab4d994394bd2055948b536605709b9eb4775321fbd321cbdbf62d29687573c4c17485b174d153f7383a2ebf574c68b04ed98844f61a5e225b611a3a8b12 0045-arm64-dts-sdm630-fix-anoc2-context-irq-polarity.patch
"
+82
View File
@@ -0,0 +1,82 @@
# Command-engine initialization comparison
Investigation checkpoint: 2026-11-13. The last live command reached BAM EOT
but did not change the DMA target. No command-engine or Internet success is
established. The additional global-register observations below are prepared
in source; they have not yet been compiled or sampled on the phone.
The reference is Xiaomi `platina-o-oss`, commit
`0bb2780bccb9c7e05f0edf5db8860e779179b5f9`. Paths below are relative to that
tree. Register offsets are relative to the corrected IPA or BAM aperture,
not the original wrapper address.
| Item | Pinned Android behavior | Current experiment / evidence |
|---|---|---|
| IPA reset | `ipa_v2/ipa_utils.c:ipa_init_hw()` asserts then deasserts IPA soft reset at `0x3c` | No global reset; reset ownership remains unresolved |
| IPA enable / BCR | Configuration `0x11`, then v2.6L BCR `0x001fff7f` | Already tried; BCR reads back `0x001fef7f`, SRAM writeback still fails |
| BAM reset | `sps/bam.c:bam_init()` resets and enables BAM | No global reset; AP pipe checks do not establish Q6 pipe idleness |
| BAM local clock gating | IPA sets `SPS_BAM_NO_LOCAL_CLK_GATING`; SPS clears control bits 18:17 | Previous control `0x20002` has field value 1; source now records it explicitly |
| BAM configuration | SPS writes `0xfffff7ff` unless the separate no-external-pipe-reset option is used | No write by the diagnostic; new read at BAM `0x7c` is pending |
| BAM summing threshold | IPA explicitly supplies `IPA_SUMMING_THRESHOLD = 0x10` | New read at BAM `0x8` is pending; do not confuse this with the per-pipe event threshold or SPS's fallback of 4 |
| Initial core vote | `ipa_v2/ipa.c` starts at turbo, 200 MHz | Existing diagnostic requests 75 MHz after preparing the clock; new JSON records the provider's cached request |
| SMMU clock / bus votes | Vendor DT names `AGGR2_NOC_SMMU_CLK` and supplies two bus paths | Need to compare matching mainline SMMU/interconnect ownership before adding duplicate votes |
| Command EP configuration | `ipa_setup_apps_pipes()` requests DMA mode but sets `skip_ep_cfg=true` | EP control/mode both read 0; requested mode alone does not justify a register write |
| Addressing | Vendor supports both bypass and translated SPS allocations | Both 32-bit and below-1-GiB translated tests failed; preserve the strict DMA domain |
The constants for the older IPA-specific BAM configuration path are not the
v2.6L initialization value. In `ipa_setup_bam_cfg()`, the write is conditional
on hardware older than v2.5, even though the switch also selects a constant
for v2.6L. Preserve that condition when reading the code.
## Next observation
Build `platina_ipa_v2_cmd_test.ko` with the same prepared source, configuration,
Clang and symbol table used for the existing diagnostic. A previous `.ko`
does not contain the new fields. Record the new source and binary hashes
before copying or loading it. Normal modpost and module checks are required.
Use the established opt-in boot procedure to keep MSS offline from startup;
do not stop an already running modem. Verify the corrected ANOC2 context IRQs,
strict DMA domain, battery guard and USB recovery access first. In that test
boot, load only the inspection mode:
```sh
sudo insmod ./platina_ipa_v2_cmd_test.ko inspect=1
sudo cat /sys/module/platina_ipa_v2_cmd_test/parameters/snapshot
sudo rmmod platina_ipa_v2_cmd_test
```
Retain the complete kernel log as well as JSON. New fields are
`bam_config_sampled`, `bam_control`, `bam_cfg_bits`, `bam_desc_threshold` and
`core_cached_hz`. Numbers in JSON are decimal. An early probe rejection can
leave fields zero; only `bam_config_sampled=true` establishes that all three
BAM global reads finished. The cached clock value is not a measured hardware
frequency. Inspection success still has `command_completed=false` and
`datapath_ready=false`.
The new source adds reads only to the BAM global configuration sequence.
It does not change global reset, clock rate, BAM configuration, thresholds,
command bytes or completion rules. The existing command test's per-pipe
writes remain available only with `run=1`.
Compare the inherited state before selecting a single additional experiment.
Do not write the whole vendor initialization sequence merely because one
read differs. Q6/WLAN register reads remain excluded, and an unchanged DMA
target after a submitted command still requires retaining resources until
reboot. Restore the checked original DSP/RMTFS service files and normal boot
after the inspection session.
## Supplementary upstream review
The September 2021 RFC pages for BAM transport and v2 commands are authored
by Sireesh Kodali (the command patch also credits Vladimir Lypak). They are
useful cross-checks, not a qualified driver for this board:
- `https://lists.openwall.net/linux-kernel/2021/09/20/40`
- `https://lkml.iu.edu/2109.2/04407.html`
Their transport path uses a dedicated immediate-command flag and places the
opcode in the descriptor length. Do not copy the RFC command layout without
checking the vendor's v2 bitfields: the pinned shared-memory command puts
direction at word 2 bit 16, followed by `skip_pipeline_clear` at bit 17.
The current encoder and golden-byte test retain that vendor format.
+4
View File
@@ -0,0 +1,4 @@
# Opt-in diagnostic; deliberately absent from the runtime overlay.
obj-m += platina_ipa_v2_probe.o
obj-m += platina_ipa_v2_dma_test.o
obj-m += platina_ipa_v2_cmd_test.o
+164
View File
@@ -0,0 +1,164 @@
# IPA v2.6L Android bring-up
This directory is an opt-in kernel investigation, not an Internet driver.
It is not installed by the runtime overlay and has no automatic service.
As of 2026-11-13, strict DMA mapping and the corrected DT context IRQs have
been verified. A BAM descriptor reached EOT, but the SRAM read did not update
its DMA target. Cellular Internet and command-engine execution remain
unverified. See `docs/CELLULAR.md` in the repository for measured results.
The reference is `MiCode/Xiaomi_Kernel_OpenSource`, branch `platina-o-oss`,
commit `0bb2780bccb9c7e05f0edf5db8860e779179b5f9`:
| Source | What it establishes |
|---|---|
| `arch/arm/boot/dts/qcom/sdm660.dtsi` | Raw IPA/BAM resources, clocks and AP SMMU stream ID |
| `drivers/platform/msm/ipa/ipa_v2/ipa_reg.h` | Register offset `0x40000` within the wrapper |
| `drivers/platform/msm/ipa/ipa_v2/ipa_utils.c` | v2.6L endpoints, register setup and memory partition selection |
| `drivers/platform/msm/ipa/ipa_v2/ipa.c` | BAM registration, command pipe and table initialization order |
| `drivers/platform/msm/ipa/ipa_v2/ipa_ram_mmap.h` | v2.6L SRAM layout; it differs from the experimental GSI data |
| `drivers/platform/msm/ipa/ipa_v2/ipa_dp.c` | Immediate-command descriptor length contains the opcode |
| `include/linux/msm-sps.h` | IPA immediate flag `0x0100`; ordinary BAM command flag `0x0800` |
| `drivers/platform/msm/sps/bam.c` | NDP 4K BAM register layout and pipe ownership |
| `drivers/platform/msm/ipa/ipa_v2/rmnet_ipa.c` | Q6 SRAM initialization precedes IPA QMI service startup |
| `drivers/platform/msm/ipa/ipa_v2/ipa_qmi_service.c` | QMI initialization advertises real table offsets and WAN RX endpoint |
## Read-only diagnostic
Build with a fully prepared **matching** kernel source/configuration and symbol
table, using the same toolchain as that kernel:
```sh
make -C /path/to/kernel ARCH=arm64 LLVM=1 \
M=/path/to/mi8-platina-linux/project/cellular/ipa-v2 \
CONFIG_DEBUG_INFO_BTF_MODULES= modules
```
The probe does not need split BTF debug information. Omitting it avoids
referencing the rebuilt kernel's BTF type IDs when inspecting the currently
running kernel. This does not disable CFI or relax module loading checks.
`platina_ipa_v2_probe.ko` accepts only the platina machine and the existing
SDM660 IPA platform device. It refuses a bound driver and reserves both MMIO
ranges while sampling. It prepares the core clock before requesting the
original driver's 75 MHz SVS vote, then restores the old cached request while
the clock is still prepared and releases it. This order matters: the matching
`clk-smd-rpm.c` ignores rate changes while unprepared. `core_cached_hz` is the
provider's cached request, not a measured hardware frequency.
It reads version/configuration, SRAM bounds, BAM execution-environment
ownership and the four AP pipe states. It does not reset IPA/BAM, write IPA/BAM
registers, allocate DMA descriptors, acknowledge interrupts or send QMI.
There is no device alias: module loading must be explicit. With the reviewed
matching module placed on the device, one snapshot is:
```sh
sudo insmod ./platina_ipa_v2_probe.ko
sudo cat /sys/module/platina_ipa_v2_probe/parameters/snapshot
sudo rmmod platina_ipa_v2_probe
```
The JSON always says `datapath_ready: false`. Readable registers, enabled
pipes, or an IPA QMI reply do not establish public packet delivery. The IPA
register named `ENABLED_PIPES` contains the available pipe count on v2.6L;
`ipa_num_pipes` is not an enabled-pipe bitmap. Each BAM pipe's control bit 1
indicates whether that pipe is enabled.
## DMA mapping and command diagnostics
The same Makefile builds `platina_ipa_v2_dma_test.ko` and
`platina_ipa_v2_cmd_test.ko`. Neither has a device alias or automatic loader.
`scripts/phone-cellular-bam-overlay.py` generates a temporary, separately
named device for the mapping test; it does not replace the production node.
The test checks each allocation against actual CPU backing pages. It does
not submit DMA or prove that hardware uses those translations.
The command module binds only the corrected IPA platform device. It requires
the strict DMA domain and context fault handlers, a private IOMMU group,
MSS offline with no startup references, and initially disabled IPA plus idle
AP/USB pipes. It serializes against MSS startup during the experiment. Do
not stop a running modem to prepare this test: that earlier approach was
followed by an unexplained reboot. The opt-in DSP/RMTFS boot configuration
holds MSS offline only with the exact token `platina.ipa_bringup=1`; ordinary
boots retain their original modem startup behavior. Live service changes
must be restored from checked backups after testing.
`inspect=1` performs only the idle-register checks, without enabling IPA,
accessing SRAM or submitting descriptors. `run=1` instead submits one 16-byte
SRAM read on command pipe 3. Exactly one mode must be selected. The optional
`dma_bits=30` diagnostic bounds IOVA allocation below 1 GiB; the default is
32, and both retain strict IOMMU translation. The low-address experiment
did not fix missing writeback and establishes no new hardware address limit.
The hardware EE0 attribute bitmap includes Q6 DECOMP pipe 11, but reading its
control register while MSS was offline was immediately followed by reset.
The diagnostic therefore reads only the vendor AP/USB endpoints 0–5. It
does not claim to inspect all global pipe state or permit a global reset.
It also uses the actual vendor BCR constant, enables IPA before SRAM access,
and reads SRAM with explicit 32-bit transactions.
Success requires `result=0`, `bam_eot_seen=true`, `command_completed=true`,
`sram_bytes_match=true` and `resources_pinned=false`. Module insertion or
EOT alone is not success. The latest real result is `result=-5`, EOT seen,
target unchanged, command incomplete and resources pinned. A failed memory
comparison waits an additional second after EOT, then retains the driver,
module, clock and mappings until reboot. Do not unload it or start MSS in
that state. After a normal reboot the test resources are gone and the
original boot image and service configuration should be verified.
The C command encoder has a native golden-byte and bounds test, including
opcode 19 in the descriptor's size field and `IMME|EOT = 0x4100`. The tests
exercise the actual shared encoder, but cannot qualify hardware execution.
The next source revision adds read-only BAM global configuration/threshold
and cached core-clock observations. It is not yet compiled or live-tested;
the earlier `.ko` files do not contain these fields. The pinned Android
comparison and inspection procedure are in [INITIALIZATION.md](INITIALIZATION.md).
## Dependencies for the real port
1. Correct register aperture, clock/interconnect votes, AP DMA addressing and
SMMU ownership. The historical `ipa-shared` region is actually BAM.
The running snapshot already shows BAM enabled with EE ownership assigned.
An active modem must be coordinated before any global IPA/BAM reset; do
not reuse a DMA controller driver's unconditional global-reset probe.
2. A BAM command producer at endpoint 3, with **IMME**, not `DMA_PREP_CMD`.
Keep the DMA-mapped payload size separate from the descriptor's opcode.
Reclaim mappings only after hardware completion or a confirmed DMA stop.
3. v2.6L SRAM canaries, header/route/filter tables and modem memory, initialized
through that functioning command pipe. Do not copy the v3.1 memory map.
4. AP RX descriptors, refill/completion and endpoint configuration, including
WAN RX endpoint 5, before starting data traffic. The vendor advertises the
reserved WAN endpoint in `INIT_MODEM_DRIVER`; QMI service startup precedes
the network interface's later data-pipe setup.
5. The modem/uC handshake, RMNET/MAP mux configuration, packet delivery and
modem restart cleanup. Only then qualify WDS calls and public DNS/TCP.
The original firmware assertion identifies an uninitialized immediate-command
client in modem firmware. The missing AP initialization is a supported working
hypothesis, not proof that one QMI request will restore PPP downlink.
## Verified v2.6L memory partition
Evaluating the pinned vendor `ipa_ram_mmap.h` gives these logical SRAM offsets.
The phone reports 8192 bytes and zero restricted bytes. The vendor adds the
restricted-byte count when forming table addresses for immediate commands and
QMI; these are not system DMA addresses.
| Region | Offset | Size |
|---|---:|---:|
| uC information | `0x0080` | `0x0200` |
| IPv4 filter header | `0x0288` | `0x0058` |
| IPv6 filter header | `0x02e8` | `0x0058` |
| IPv4 route header | `0x0348` | `0x003c` |
| IPv6 route header | `0x0388` | `0x003c` |
| Modem header | `0x03c8` | `0x0140` |
| Modem compression/decompression | `0x0510` | `0x0200` |
| Modem memory | `0x0714` | `0x18e8` |
| End, including final canary | `0x2000` | — |
The gaps contain the vendor's canaries. Do not fill an apparent gap or replace
these offsets with the scaffold's v3.1 memory partitions. AP route indices are
7 through 14; modem indices are 0 through 6. The zero-sized AP SRAM header and
filter regions do not remove their required DMA-backed tables or initialization.
+121
View File
@@ -0,0 +1,121 @@
/* SPDX-License-Identifier: GPL-2.0-only */
#ifndef PLATINA_IPA_V2_CMD_FORMAT_H
#define PLATINA_IPA_V2_CMD_FORMAT_H
/* Wire layout from pinned platina-o-oss ipa_hw_defs.h and msm-sps.h. */
#ifdef __KERNEL__
#include <linux/byteorder/generic.h>
#include <linux/errno.h>
#include <linux/types.h>
#else
#include <stdbool.h>
#include <stdint.h>
#include <errno.h>
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef uint16_t __le16;
typedef uint32_t __le32;
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define cpu_to_le16(x) ((u16)(x))
#define cpu_to_le32(x) ((u32)(x))
#else
#define cpu_to_le16(x) __builtin_bswap16((u16)(x))
#define cpu_to_le32(x) __builtin_bswap32((u32)(x))
#endif
#endif
#define IPA_V2_REGISTER_WRITE 12
#define IPA_V2_DMA_SHARED_MEM 19
#define IPA_V2_BAM_IMME 0x0100
#define IPA_V2_BAM_EOT 0x4000
struct ipa_v2_bam_desc {
__le32 address;
__le16 size;
__le16 flags;
};
struct ipa_v2_shared_mem_cmd {
__le32 size;
__le32 system_address;
__le32 local_address_direction;
__le32 reserved;
};
struct ipa_v2_reg_write_cmd {
__le32 flags_offset;
__le32 value;
__le32 value_mask;
};
static inline bool ipa_v2_dma_range_valid(u64 address, u32 length)
{
return length && address <= 0xffffffffULL &&
length - 1 <= 0xffffffffULL - address;
}
static inline int ipa_v2_shared_mem_encode(struct ipa_v2_shared_mem_cmd *cmd,
u64 address, u32 length, u32 local,
u32 sram_size, u32 restricted,
bool read_from_ipa, bool skip_clear)
{
u32 flags;
if (!ipa_v2_dma_range_valid(address, length) || length > 0xffff ||
local > 0xffff || local < restricted || local > sram_size ||
length > sram_size - local)
return -ERANGE;
cmd->size = cpu_to_le32(length << 16);
cmd->system_address = cpu_to_le32(address);
flags = local | (read_from_ipa ? (1U << 16) : 0U) |
(skip_clear ? (1U << 17) : 0U);
cmd->local_address_direction = cpu_to_le32(flags);
cmd->reserved = 0;
return 0;
}
static inline int ipa_v2_shared_read_encode(struct ipa_v2_shared_mem_cmd *cmd,
u64 address, u32 length, u32 local,
u32 sram_size, u32 restricted)
{
return ipa_v2_shared_mem_encode(cmd, address, length, local, sram_size,
restricted, true, false);
}
static inline int ipa_v2_reg_write_encode(struct ipa_v2_reg_write_cmd *cmd,
u32 offset, u32 value,
u32 value_mask, bool skip_clear)
{
if (offset > 0xffff || (offset & 0x3))
return -ERANGE;
cmd->flags_offset = cpu_to_le32((offset << 16) |
(skip_clear ? (1U << 15) : 0U));
cmd->value = cpu_to_le32(value);
cmd->value_mask = cpu_to_le32(value_mask);
return 0;
}
static inline int ipa_v2_imm_cmd_desc(struct ipa_v2_bam_desc *desc,
u64 payload_address, u32 payload_length,
u16 opcode)
{
if (!ipa_v2_dma_range_valid(payload_address, payload_length))
return -ERANGE;
desc->address = cpu_to_le32(payload_address);
/* The size field is the opcode, never the payload allocation length. */
desc->size = cpu_to_le16(opcode);
desc->flags = cpu_to_le16(IPA_V2_BAM_IMME | IPA_V2_BAM_EOT);
return 0;
}
static inline int ipa_v2_shared_read_desc(struct ipa_v2_bam_desc *desc,
u64 payload_address, u32 payload_length)
{
if (payload_length != sizeof(struct ipa_v2_shared_mem_cmd))
return -ERANGE;
return ipa_v2_imm_cmd_desc(desc, payload_address, payload_length,
IPA_V2_DMA_SHARED_MEM);
}
#endif
+48
View File
@@ -0,0 +1,48 @@
/* SPDX-License-Identifier: GPL-2.0-only */
#ifndef PLATINA_IPA_V2_DMA_H
#define PLATINA_IPA_V2_DMA_H
#include <linux/dma-mapping.h>
#include <linux/iommu.h>
#include <linux/scatterlist.h>
/* Validate every page boundary against the DMA allocator's actual CPU pages. */
static inline int ipa_v2_verify_mapping(struct device *dev,
struct iommu_domain *domain,
void *cpu, dma_addr_t dma)
{
struct sg_table table;
struct scatterlist *sg;
size_t offset = 0;
unsigned int i;
int ret;
if (dma > U32_MAX || PAGE_SIZE - 1 > U32_MAX - dma)
return -ERANGE;
ret = dma_get_sgtable(dev, &table, cpu, dma, PAGE_SIZE);
if (ret)
return ret;
for_each_sg(table.sgl, sg, table.orig_nents, i) {
size_t j;
for (j = 0; j < sg->length; j += PAGE_SIZE) {
size_t len = min_t(size_t, PAGE_SIZE, sg->length - j);
phys_addr_t physical = sg_phys(sg) + j;
if (len > PAGE_SIZE - offset ||
iommu_iova_to_phys(domain, dma + offset) != physical ||
iommu_iova_to_phys(domain, dma + offset + len - 1) !=
physical + len - 1) {
ret = -EFAULT;
goto out;
}
offset += len;
}
}
ret = offset == PAGE_SIZE ? 0 : -EFAULT;
out:
sg_free_table(&table);
return ret;
}
#endif
@@ -0,0 +1,804 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Opt-in single-command BAM qualification, not a packet transport.
* Requires the corrected IPA DT and ANOC2 context fault IRQ polarity.
*
* The test enables an otherwise inactive IPA, submits one SRAM-to-system
* read on AP command pipe 3 and compares bytes with the CPU SRAM aperture.
* It never resets the global IPA/BAM, writes SRAM or starts modem/QMI data.
* Uncertain DMA completion pins the driver, mappings and clock until reboot.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device/class.h>
#include <linux/init.h>
#include <linux/interconnect.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <linux/remoteproc.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include "ipa_v2_cmd_format.h"
#include "ipa_v2_dma.h"
#define IPA_HW_VERSION 0x30
#define IPA_CFG 0x38
#define IPA_SW_RESET 0x3c
#define IPA_MEM_SIZE 0x50
#define IPA_BCR 0x5b0
#define IPA_BCR_V2_6L 0x001fff7f
#define IPA_DEBUG_CNT_CTRL_0 0x640
#define IPA_IRQ_STTS_EE0 0x1008
#define IPA_REG_TEST_MASK 0x1ff1f171U
#define IPA_REG_TEST_VAL 0x15a15150U
#define IPA_SRAM 0x5000
#define IPA_EP_CTRL(n) (0x70 + (n) * 4)
#define IPA_EP_MODE(n) (0x2c0 + (n) * 4)
#define IPA_SVS_RATE 75000000
#define IPA_TURBO_RATE 200000000
#define BAM_CTRL 0x0
#define BAM_LOCAL_CLK_GATING 0x60000
#define BAM_DESC_THRESHOLD 0x8
#define BAM_SUMMING_THRESHOLD 0x10
#define BAM_CFG_BITS 0x7c
#define BAM_CFG_VENDOR 0xfffff7ffU
#define BAM_IRQ_STATUS 0x14
#define BAM_REVISION 0x1000
#define BAM_NUM_PIPES 0x1008
#define BAM_EE0_IRQ_MASK 0x3004
#define BAM_EE0_PIPES 0x300c
#define PIPE_CTRL(n) (0x13000 + (n) * 0x1000)
#define PIPE_RESET(n) (0x13004 + (n) * 0x1000)
#define PIPE_IRQ_STATUS(n) (0x13010 + (n) * 0x1000)
#define PIPE_IRQ_CLEAR(n) (0x13014 + (n) * 0x1000)
#define PIPE_IRQ_ENABLE(n) (0x13018 + (n) * 0x1000)
#define PIPE_SW_OFFSET(n) (0x13800 + (n) * 0x1000)
#define PIPE_EVENT(n) (0x13818 + (n) * 0x1000)
#define PIPE_DESC_ADDRESS(n) (0x1381c + (n) * 0x1000)
#define PIPE_FIFO_SIZE(n) (0x13820 + (n) * 0x1000)
#define PIPE_THRESHOLD(n) (0x13828 + (n) * 0x1000)
#define CMD_PIPE 3
/* Vendor endpoint map: USB 0/1, AP LAN/command/WAN 2..5. */
#define AP_PIPE_MASK GENMASK(5, 0)
#define PIPE_ENABLE BIT(1)
#define PIPE_SYSTEM BIT(5)
#define PIPE_EOT BIT(5)
#define PIPE_ERRORS (BIT(4) | BIT(6) | BIT(7))
#define BAM_ERRORS (BIT(1) | BIT(2))
#define READ_BYTES 16
#define BUFFER_COUNT 3
struct command_test {
struct device *dev;
struct clk *clock;
struct icc_path *icc_mem, *icc_cfg;
struct platform_device *modem_device;
struct rproc *modem;
void __iomem *ipa, *bam;
void *cpu[BUFFER_COUNT];
dma_addr_t dma[BUFFER_COUNT];
u64 old_dma_mask, old_coherent_mask;
unsigned long old_rate;
u32 old_cfg, old_bcr, old_dbg_cnt0;
u32 bam_control, bam_cfg_bits, bam_desc_threshold;
unsigned long core_cached_hz;
u32 read_offset, pipe_status, bam_status, reg_after;
u32 irq_before, irq_after;
u32 local_address;
unsigned int fault_handlers;
bool bam_eot_seen, bytes_match, pinned, modem_locked, dma_masks_saved;
bool bam_config_sampled, bam_cfg_saved, icc_voted;
};
static bool run, inspect;
static bool icc_vote = true;
static bool bam_cfg;
static bool sw_reset;
static bool skip_clear;
static bool turbo_clk;
static unsigned int mode_op;
static unsigned int dma_bits = 32;
static unsigned int cfg_val = 0x11;
static int local_off = 0x0714;
module_param(dma_bits, uint, 0400);
MODULE_PARM_DESC(dma_bits, "Diagnostic DMA aperture: 30 or 32 bits, always translated");
module_param(cfg_val, uint, 0400);
MODULE_PARM_DESC(cfg_val, "IPA_COMP_CFG value when enabled (default 0x11, or 0x1d)");
module_param(local_off, int, 0400);
MODULE_PARM_DESC(local_off, "Explicit SRAM local offset (default 0x0714 modem_ofst, below 0x1ffc canary)");
module_param(mode_op, uint, 0400);
MODULE_PARM_DESC(mode_op, "0: SRAM->DDR read, 1: IPA_REGISTER_WRITE, 2: DDR->SRAM write");
module_param(icc_vote, bool, 0400);
MODULE_PARM_DESC(icc_vote, "Vote on IPA memory and config interconnects if present in DT");
module_param(bam_cfg, bool, 0400);
MODULE_PARM_DESC(bam_cfg, "Program vendor BAM global threshold, cfg bits and clock gating");
module_param(sw_reset, bool, 0400);
MODULE_PARM_DESC(sw_reset, "Pulse IPA_COMP_SW_RESET before IPA enable while MSS is offline");
module_param(skip_clear, bool, 0400);
MODULE_PARM_DESC(skip_clear, "Set skip_pipeline_clear in immediate command");
module_param(turbo_clk, bool, 0400);
MODULE_PARM_DESC(turbo_clk, "Vote 200 MHz turbo IPA clock instead of 75 MHz SVS");
module_param(run, bool, 0400);
MODULE_PARM_DESC(run, "Explicitly authorize the single BAM immediate command test");
module_param(inspect, bool, 0400);
MODULE_PARM_DESC(inspect, "Read idle registers only; never enable IPA or submit DMA");
static char snapshot[1024];
static bool probe_seen, resources_pinned, registered;
static int probe_result = -ENODEV;
static int snapshot_get(char *buffer, const struct kernel_param *kp)
{
return sysfs_emit(buffer, "%s\n", snapshot);
}
static const struct kernel_param_ops snapshot_ops = {
.get = snapshot_get,
};
module_param_cb(snapshot, &snapshot_ops, NULL, 0400);
MODULE_PARM_DESC(snapshot, "Explicit result; loading alone does not prove success");
static void record_result(struct command_test *test, int result)
{
scnprintf(snapshot, sizeof(snapshot),
"{\"datapath_ready\":false,\"result\":%d,"
"\"mode_op\":%u,\"icc_voted\":%s,"
"\"bam_cfg_applied\":%s,\"sw_reset_applied\":%s,\"skip_clear\":%s,"
"\"bam_eot_seen\":%s,\"command_completed\":%s,\"sram_bytes_match\":%s,"
"\"resources_pinned\":%s,\"pipe\":%u,\"read_bytes\":%u,"
"\"inspected_pipe_mask\":%u,\"inspection_only\":%s,"
"\"dma_bits\":%u,"
"\"bam_config_sampled\":%s,\"bam_control\":%u,"
"\"bam_cfg_bits\":%u,\"bam_desc_threshold\":%u,"
"\"core_cached_hz\":%lu,\"reg_after\":%u,"
"\"cfg_val\":%u,\"irq_before\":%u,\"irq_after\":%u,"
"\"local_address\":%u,\"read_offset\":%u,"
"\"pipe_status\":%u,\"bam_status\":%u,"
"\"fault_handlers_present\":%u}",
result, mode_op, test->icc_voted ? "true" : "false",
(!inspect && bam_cfg) ? "true" : "false",
(!inspect && sw_reset) ? "true" : "false",
skip_clear ? "true" : "false",
test->bam_eot_seen ? "true" : "false",
test->bam_eot_seen && test->bytes_match ? "true" : "false",
test->bytes_match ? "true" : "false",
test->pinned ? "true" : "false", CMD_PIPE, READ_BYTES,
(unsigned int)AP_PIPE_MASK, inspect ? "true" : "false",
dma_bits,
test->bam_config_sampled ? "true" : "false", test->bam_control,
test->bam_cfg_bits, test->bam_desc_threshold,
test->core_cached_hz, test->reg_after,
cfg_val, test->irq_before, test->irq_after,
test->local_address, test->read_offset, test->pipe_status,
test->bam_status, test->fault_handlers);
dev_info(test->dev, "command test: %s\n", snapshot);
}
static int verify_fault_irqs(struct of_phandle_args *iommu, unsigned int *active)
{
struct device_node *smmu = iommu->np;
struct of_phandle_args irq;
u32 globals;
int count, i, number, ret;
if (of_property_read_u32(smmu, "#global-interrupts", &globals))
return -EINVAL;
count = of_irq_count(smmu);
if (count <= globals || count > 66)
return -EINVAL;
for (i = globals; i < count; i++) {
ret = of_irq_parse_one(smmu, i, &irq);
if (ret)
return ret;
ret = irq.args_count == 3 && irq.args[0] == 0 &&
irq.args[2] == IRQ_TYPE_LEVEL_HIGH ? 0 : -EINVAL;
of_node_put(irq.np);
if (ret)
return ret;
number = of_irq_get(smmu, i);
if (number <= 0)
return number ?: -ENXIO;
if (irq_has_action(number))
(*active)++;
}
return *active ? 0 : -ENXIO;
}
static int count_device(struct device *dev, void *data)
{
(*(unsigned int *)data)++;
return 0;
}
static int find_modem_child(struct device *child, void *data)
{
struct rproc **modem = data;
if (!child->class || strcmp(child->class->name, "remoteproc") ||
!child->type || strcmp(child->type->name, "remoteproc"))
return 0;
/* Parent driver is locked; retain this public remoteproc class device. */
get_device(child);
*modem = container_of(child, struct rproc, dev);
return 1;
}
static int lock_offline_modem(struct command_test *test)
{
struct device_node *node;
struct device *dev;
int ret;
node = of_find_node_by_path("/soc@0/remoteproc@4080000");
if (!node)
return -ENODEV;
test->modem_device = of_find_device_by_node(node);
of_node_put(node);
if (!test->modem_device)
return -ENODEV;
dev = &test->modem_device->dev;
device_lock(dev);
if (!dev->driver || strcmp(dev->driver->name, "qcom-q6v5-mss"))
return -ENODEV;
/* The MSS driver's private data is qproc, not struct rproc. */
ret = device_for_each_child(dev, &test->modem, find_modem_child);
if (ret != 1)
return ret ?: -ENODEV;
mutex_lock(&test->modem->lock);
test->modem_locked = true;
if (test->modem->state != RPROC_OFFLINE || atomic_read(&test->modem->power))
return -EBUSY;
return 0;
}
static void put_modem(struct command_test *test)
{
if (test->modem_locked)
mutex_unlock(&test->modem->lock);
test->modem_locked = false;
if (test->modem)
put_device(&test->modem->dev);
if (test->modem_device) {
device_unlock(&test->modem_device->dev);
put_device(&test->modem_device->dev);
}
test->modem = NULL;
test->modem_device = NULL;
}
static u32 traced_read(struct command_test *test, void __iomem *base,
u32 offset, const char *name)
{
u32 value;
/* Preserve the attempted address in ramoops before a possible bus fault. */
dev_info(test->dev, "reading %s at offset %#x\n", name, offset);
value = readl(base + offset);
dev_info(test->dev, "%s=%#x\n", name, value);
return value;
}
static bool other_ap_pipe_active(struct command_test *test)
{
unsigned int i;
/*
* PIPE_ATTR_EE is not an authorization to read every advertised pipe.
* Reading Q6 DECOMP pipe 11 while MSS is offline resets this phone.
* Inspect only vendor AP/USB endpoints, qualified by the read-only test.
* MSS stays locked offline, IPA must start disabled, and no global BAM
* reset is permitted. Q6/WLAN pipe registers are never accessed here.
*/
for (i = 0; i <= 5; i++) {
if (i == CMD_PIPE)
continue;
if (traced_read(test, test->bam, PIPE_CTRL(i), "AP/USB pipe control") &
PIPE_ENABLE)
return true;
}
return false;
}
/* Only called after a completed command, or before its event was posted. */
static int stop_completed_test(struct command_test *test)
{
void __iomem *bam = test->bam;
if (other_ap_pipe_active(test))
return -EBUSY;
/* Stop the attached engine before disabling/resetting its BAM pipe. */
writel(test->old_cfg, test->ipa + IPA_CFG);
if (readl(test->ipa + IPA_CFG) != test->old_cfg)
return -EIO;
writel(0, bam + PIPE_CTRL(CMD_PIPE));
if (readl(bam + PIPE_CTRL(CMD_PIPE)) & PIPE_ENABLE)
return -EIO;
writel(0, bam + PIPE_IRQ_ENABLE(CMD_PIPE));
writel(readl(bam + PIPE_IRQ_STATUS(CMD_PIPE)),
bam + PIPE_IRQ_CLEAR(CMD_PIPE));
writel(1, bam + PIPE_RESET(CMD_PIPE));
wmb(); /* Assert the pipe reset before deasserting it. */
writel(0, bam + PIPE_RESET(CMD_PIPE));
if (readl(bam + PIPE_CTRL(CMD_PIPE)) ||
readl(bam + PIPE_SW_OFFSET(CMD_PIPE)) ||
(readl(bam + PIPE_EVENT(CMD_PIPE)) & 0xffff))
return -EIO;
writel(0, bam + PIPE_DESC_ADDRESS(CMD_PIPE));
writel(0, bam + PIPE_FIFO_SIZE(CMD_PIPE));
writel(0, bam + PIPE_THRESHOLD(CMD_PIPE));
if (test->bam_cfg_saved) {
writel(test->bam_desc_threshold, bam + BAM_DESC_THRESHOLD);
writel(test->bam_cfg_bits, bam + BAM_CFG_BITS);
writel(test->bam_control, bam + BAM_CTRL);
}
writel(test->old_bcr, test->ipa + IPA_BCR);
return readl(test->ipa + IPA_BCR) == test->old_bcr ? 0 : -EIO;
}
static int run_command(struct command_test *test)
{
void __iomem *bam = test->bam;
struct ipa_v2_shared_mem_cmd *command = test->cpu[1];
struct ipa_v2_reg_write_cmd *reg_cmd = test->cpu[1];
struct ipa_v2_bam_desc *descriptor = test->cpu[0];
__le32 before[READ_BYTES / sizeof(u32)], after[READ_BYTES / sizeof(u32)];
__le32 expected[READ_BYTES / sizeof(u32)];
unsigned long timeout;
u32 memory, ownership;
unsigned int i;
int ret, stop_ret;
test->old_cfg = readl(test->ipa + IPA_CFG);
test->old_bcr = readl(test->ipa + IPA_BCR);
test->bam_control = traced_read(test, bam, BAM_CTRL, "BAM control");
test->bam_cfg_bits = traced_read(test, bam, BAM_CFG_BITS, "BAM config bits");
test->bam_desc_threshold = traced_read(test, bam, BAM_DESC_THRESHOLD,
"BAM descriptor summing threshold");
test->bam_config_sampled = true;
ownership = readl(bam + BAM_EE0_PIPES);
memory = readl(test->ipa + IPA_MEM_SIZE);
dev_info(test->dev, "idle hardware: cfg=%#x BCR=%#x memory=%#x BAM=%#x ownership=%#x\n",
test->old_cfg, test->old_bcr, memory, test->bam_control, ownership);
dev_info(test->dev, "inherited BAM config=%#x threshold=%#x core_cached_hz=%lu icc=%u\n",
test->bam_cfg_bits, test->bam_desc_threshold,
test->core_cached_hz, test->icc_voted);
dev_info(test->dev, "checking identity and AP/USB pipe controls\n");
if (readl(test->ipa + IPA_HW_VERSION) != 0x20060001 ||
test->old_cfg != 0x10 || !(test->bam_control & BIT(1)) ||
(readl(bam + BAM_REVISION) & 0xff) != 0x27 ||
(readl(bam + BAM_NUM_PIPES) & 0xc0ff) != 20 ||
!(ownership & BIT(31)) ||
(ownership & AP_PIPE_MASK) != AP_PIPE_MASK ||
memory != 8192 || other_ap_pipe_active(test))
return -EOPNOTSUPP;
dev_info(test->dev, "checking command pipe registers\n");
/* Demand a pristine, disabled pipe; never take over an existing queue. */
if (traced_read(test, bam, PIPE_CTRL(CMD_PIPE), "command control") ||
traced_read(test, bam, PIPE_IRQ_ENABLE(CMD_PIPE), "command IRQ enable") ||
traced_read(test, bam, PIPE_IRQ_STATUS(CMD_PIPE), "command IRQ status") ||
traced_read(test, bam, PIPE_SW_OFFSET(CMD_PIPE), "command SW offset") ||
traced_read(test, bam, PIPE_DESC_ADDRESS(CMD_PIPE), "command FIFO address") ||
traced_read(test, bam, PIPE_FIFO_SIZE(CMD_PIPE), "command FIFO size") ||
traced_read(test, bam, PIPE_THRESHOLD(CMD_PIPE), "command threshold") ||
(traced_read(test, bam, PIPE_EVENT(CMD_PIPE), "command event") & 0xffff) ||
(traced_read(test, bam, BAM_EE0_IRQ_MASK, "EE0 IRQ mask") & BIT(CMD_PIPE)) ||
(traced_read(test, bam, BAM_IRQ_STATUS, "BAM IRQ status") & BAM_ERRORS))
return -EBUSY;
if (inspect) {
traced_read(test, test->ipa, IPA_EP_CTRL(CMD_PIPE), "IPA command EP control");
traced_read(test, test->ipa, IPA_EP_MODE(CMD_PIPE), "IPA command EP mode");
dev_info(test->dev, "idle register inspection completed; no DMA submitted\n");
return 0;
}
test->local_address = local_off >= 0 ? (u32)local_off :
(memory & 0xffff) - READ_BYTES;
if (test->local_address > (memory & 0xffff) - READ_BYTES ||
(test->local_address & 0x3))
return -ERANGE;
dev_info(test->dev, "enabling IPA (mode_op=%u cfg_val=%#x local=%#x sw_reset=%u bam_cfg=%u skip_clear=%u)\n",
mode_op, cfg_val, test->local_address, sw_reset, bam_cfg, skip_clear);
if (sw_reset) {
writel(1, test->ipa + IPA_SW_RESET);
wmb();
writel(0, test->ipa + IPA_SW_RESET);
wmb();
}
writel(cfg_val, test->ipa + IPA_CFG);
writel(IPA_BCR_V2_6L, test->ipa + IPA_BCR);
traced_read(test, test->ipa, IPA_CFG, "enabled IPA config");
traced_read(test, test->ipa, IPA_BCR, "enabled IPA BCR");
traced_read(test, test->ipa, IPA_EP_CTRL(CMD_PIPE), "IPA command EP control");
traced_read(test, test->ipa, IPA_EP_MODE(CMD_PIPE), "IPA command EP mode");
test->irq_before = traced_read(test, test->ipa, IPA_IRQ_STTS_EE0, "IPA IRQ_STTS_EE0 before");
if (bam_cfg) {
writel(test->bam_control & ~BAM_LOCAL_CLK_GATING, bam + BAM_CTRL);
writel(BAM_SUMMING_THRESHOLD, bam + BAM_DESC_THRESHOLD);
writel(BAM_CFG_VENDOR, bam + BAM_CFG_BITS);
test->bam_cfg_saved = true;
traced_read(test, bam, BAM_CTRL, "updated BAM control");
traced_read(test, bam, BAM_DESC_THRESHOLD, "updated BAM threshold");
traced_read(test, bam, BAM_CFG_BITS, "updated BAM cfg bits");
}
/* Vendor SRAM access follows IPA enable and uses 32-bit transactions. */
for (i = 0; i < ARRAY_SIZE(before); i++)
before[i] = cpu_to_le32(readl(test->ipa + IPA_SRAM +
test->local_address + i * sizeof(u32)));
for (i = 0; i < sizeof(before); i++) {
((u8 *)expected)[i] = ~((u8 *)before)[i];
((u8 *)test->cpu[2])[i] = ~((u8 *)before)[i];
}
if (mode_op == 1) {
test->old_dbg_cnt0 = readl(test->ipa + IPA_DEBUG_CNT_CTRL_0);
writel(0, test->ipa + IPA_DEBUG_CNT_CTRL_0);
ret = ipa_v2_reg_write_encode(reg_cmd, IPA_DEBUG_CNT_CTRL_0,
IPA_REG_TEST_VAL,
IPA_REG_TEST_MASK, skip_clear);
if (ret)
return ret;
ret = ipa_v2_imm_cmd_desc(descriptor, test->dma[1],
sizeof(*reg_cmd), IPA_V2_REGISTER_WRITE);
if (ret)
return ret;
} else {
ret = ipa_v2_shared_mem_encode(command, test->dma[2], READ_BYTES,
test->local_address, memory & 0xffff,
memory >> 16, mode_op == 0,
skip_clear);
if (ret)
return ret;
ret = ipa_v2_imm_cmd_desc(descriptor, test->dma[1],
sizeof(*command), IPA_V2_DMA_SHARED_MEM);
if (ret)
return ret;
}
writel(1, bam + PIPE_RESET(CMD_PIPE));
wmb(); /* Assert the pipe reset before programming its FIFO. */
writel(0, bam + PIPE_RESET(CMD_PIPE));
writel(test->dma[0], bam + PIPE_DESC_ADDRESS(CMD_PIPE));
writel(PAGE_SIZE, bam + PIPE_FIFO_SIZE(CMD_PIPE));
writel(16, bam + PIPE_THRESHOLD(CMD_PIPE));
/* Poll status; the EE interrupt mask for pipe 3 stays clear throughout. */
writel(PIPE_EOT | PIPE_ERRORS, bam + PIPE_IRQ_ENABLE(CMD_PIPE));
dma_wmb();
writel(PIPE_SYSTEM | PIPE_ENABLE, bam + PIPE_CTRL(CMD_PIPE));
writel(sizeof(*descriptor), bam + PIPE_EVENT(CMD_PIPE));
dev_info(test->dev, "BAM pipe 3 descriptor posted\n");
timeout = jiffies + msecs_to_jiffies(1000);
ret = -ETIMEDOUT;
do {
test->read_offset = readl(bam + PIPE_SW_OFFSET(CMD_PIPE)) & 0xffff;
test->pipe_status = readl(bam + PIPE_IRQ_STATUS(CMD_PIPE));
test->bam_status = readl(bam + BAM_IRQ_STATUS);
if ((test->pipe_status & PIPE_ERRORS) ||
(test->bam_status & BAM_ERRORS)) {
ret = -EIO;
break;
}
if (test->read_offset == sizeof(*descriptor) &&
(test->pipe_status & PIPE_EOT)) {
test->bam_eot_seen = true;
ret = 0;
break;
}
usleep_range(100, 200);
} while (time_before(jiffies, timeout));
if (!test->bam_eot_seen) {
test->pinned = true;
return ret;
}
/* EOT alone only qualifies BAM consumption, not the IPA operation. */
timeout = jiffies + msecs_to_jiffies(1000);
do {
dma_rmb();
test->pipe_status = readl(bam + PIPE_IRQ_STATUS(CMD_PIPE));
test->bam_status = readl(bam + BAM_IRQ_STATUS);
if ((test->pipe_status & PIPE_ERRORS) || (test->bam_status & BAM_ERRORS))
break;
if (mode_op == 1) {
test->reg_after = readl(test->ipa + IPA_DEBUG_CNT_CTRL_0);
if (test->reg_after == IPA_REG_TEST_VAL)
break;
} else if (mode_op == 2) {
for (i = 0; i < ARRAY_SIZE(after); i++)
after[i] = cpu_to_le32(readl(test->ipa + IPA_SRAM +
test->local_address + i * sizeof(u32)));
if (!memcmp(after, expected, sizeof(expected)))
break;
} else {
if (!memcmp(test->cpu[2], before, sizeof(before)))
break;
}
usleep_range(100, 200);
} while (time_before(jiffies, timeout));
for (i = 0; i < ARRAY_SIZE(after); i++)
after[i] = cpu_to_le32(readl(test->ipa + IPA_SRAM +
test->local_address + i * sizeof(u32)));
test->irq_after = traced_read(test, test->ipa, IPA_IRQ_STTS_EE0, "IPA IRQ_STTS_EE0 after");
if (mode_op == 1) {
test->reg_after = readl(test->ipa + IPA_DEBUG_CNT_CTRL_0);
writel(test->old_dbg_cnt0, test->ipa + IPA_DEBUG_CNT_CTRL_0);
dev_info(test->dev, "IPA_REGISTER_WRITE reg_after=%#x (expected %#x)\n",
test->reg_after, IPA_REG_TEST_VAL);
test->bytes_match = (test->reg_after == IPA_REG_TEST_VAL) &&
!(test->pipe_status & PIPE_ERRORS) &&
!(test->bam_status & BAM_ERRORS);
} else if (mode_op == 2) {
/* Restore original SRAM contents via 32-bit MMIO writes. */
for (i = 0; i < ARRAY_SIZE(before); i++)
writel(le32_to_cpu(before[i]), test->ipa + IPA_SRAM +
test->local_address + i * sizeof(u32));
dev_info(test->dev, "SRAM write before=%*phN after=%*phN expected=%*phN\n",
READ_BYTES, before, READ_BYTES, after, READ_BYTES, expected);
test->bytes_match = !memcmp(after, expected, sizeof(expected)) &&
!(test->pipe_status & PIPE_ERRORS) &&
!(test->bam_status & BAM_ERRORS);
} else {
dev_info(test->dev, "SRAM before=%*phN after=%*phN DMA target=%*phN\n",
READ_BYTES, before, READ_BYTES, after, READ_BYTES, test->cpu[2]);
test->bytes_match = !memcmp(before, after, sizeof(before)) &&
!memcmp(test->cpu[2], after, sizeof(after)) &&
!(test->pipe_status & PIPE_ERRORS) &&
!(test->bam_status & BAM_ERRORS);
}
dev_info(test->dev, "BAM completed; comparison=%u\n", test->bytes_match);
if (!test->bytes_match) {
if (mode_op == 1) {
/* REGISTER_WRITE has no QSB DDR target/source; safe to stop. */
stop_ret = stop_completed_test(test);
if (stop_ret)
test->pinned = true;
return -EIO;
}
/* IPA may still hold a QSB DMA address after BAM descriptor EOT. */
test->pinned = true;
return -EIO;
}
ret = 0;
stop_ret = stop_completed_test(test);
if (stop_ret) {
test->pinned = true;
return stop_ret;
}
return ret;
}
static int command_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct of_phandle_args args;
struct device_node *smmu;
struct iommu_domain *domain;
struct iommu_group *group;
struct command_test *test = NULL;
struct resource *res;
unsigned int count = 0;
int ret, i, restore_ret;
probe_seen = true;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res || res->start != 0x147c0000 || resource_size(res) != 0xeffc) {
ret = -EINVAL;
dev_err(dev, "corrected IPA resource and IOMMU DT required\n");
goto out_result;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res || res->start != 0x14784000 || resource_size(res) != 0x26934) {
ret = -EINVAL;
goto out_result;
}
test = devm_kzalloc(dev, sizeof(*test), GFP_KERNEL);
if (!test) {
ret = -ENOMEM;
goto out_result;
}
test->dev = dev;
ret = of_parse_phandle_with_args(dev->of_node, "iommus", "#iommu-cells",
0, &args);
if (ret)
goto out_result;
smmu = of_find_node_by_path("/soc@0/iommu@16c0000");
ret = smmu && args.np == smmu && args.args_count == 1 &&
args.args[0] == 0x19c0 ? 0 : -EINVAL;
of_node_put(smmu);
if (!ret)
ret = verify_fault_irqs(&args, &test->fault_handlers);
of_node_put(args.np);
if (ret) {
dev_err(dev, "valid ANOC2 context fault IRQs required: %d\n", ret);
goto out_result;
}
domain = iommu_get_domain_for_dev(dev);
if (!domain || domain->type != IOMMU_DOMAIN_DMA) {
ret = -EOPNOTSUPP;
goto out_result;
}
group = iommu_group_get(dev);
if (!group) {
ret = -ENODEV;
goto out_result;
}
ret = iommu_group_for_each_dev(group, &count, count_device);
iommu_group_put(group);
if (ret || count != 1) {
ret = ret ?: -EBUSY;
goto out_result;
}
test->old_dma_mask = dma_get_mask(dev);
test->old_coherent_mask = dev->coherent_dma_mask;
test->dma_masks_saved = true;
ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(dma_bits));
if (ret)
goto out_result;
ret = lock_offline_modem(test);
if (ret) {
dev_err(dev, "stopped modem required for command qualification: %d\n", ret);
goto out_result;
}
test->ipa = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(test->ipa)) {
ret = PTR_ERR(test->ipa);
goto out_result;
}
test->bam = devm_platform_ioremap_resource(pdev, 1);
if (IS_ERR(test->bam)) {
ret = PTR_ERR(test->bam);
goto out_result;
}
test->clock = devm_clk_get(dev, "core");
if (IS_ERR(test->clock)) {
ret = PTR_ERR(test->clock);
goto out_result;
}
if (icc_vote) {
test->icc_mem = of_icc_get(dev, "memory");
if (IS_ERR(test->icc_mem)) {
ret = PTR_ERR(test->icc_mem);
test->icc_mem = NULL;
goto out_result;
}
test->icc_cfg = of_icc_get(dev, "config");
if (IS_ERR(test->icc_cfg)) {
ret = PTR_ERR(test->icc_cfg);
test->icc_cfg = NULL;
goto out_icc;
}
if (test->icc_mem) {
ret = icc_set_bw(test->icc_mem, 80000, 640000);
if (ret)
goto out_icc;
}
if (test->icc_cfg) {
ret = icc_set_bw(test->icc_cfg, 80000, 80000);
if (ret)
goto out_icc;
}
test->icc_voted = test->icc_mem || test->icc_cfg;
}
test->old_rate = clk_get_rate(test->clock);
ret = clk_prepare_enable(test->clock);
if (ret)
goto out_icc;
ret = clk_set_rate(test->clock, turbo_clk ? IPA_TURBO_RATE : IPA_SVS_RATE);
test->core_cached_hz = clk_get_rate(test->clock);
if (ret || test->core_cached_hz != (turbo_clk ? IPA_TURBO_RATE : IPA_SVS_RATE)) {
ret = ret ?: -EIO;
goto out_clock;
}
for (i = 0; i < BUFFER_COUNT; i++) {
test->cpu[i] = dma_alloc_coherent(dev, PAGE_SIZE, &test->dma[i], GFP_KERNEL);
if (!test->cpu[i]) {
ret = -ENOMEM;
goto out_free;
}
ret = ipa_v2_verify_mapping(dev, domain, test->cpu[i], test->dma[i]);
if (ret)
goto out_free;
dev_info(dev, "verified buffer %d IOVA=%pad\n", i, &test->dma[i]);
}
ret = run_command(test);
if (test->pinned) {
resources_pinned = true;
probe_result = ret;
__module_get(THIS_MODULE);
record_result(test, ret);
dev_err(dev, "uncertain DMA stop; resources retained until reboot\n");
put_modem(test);
return 0;
}
out_free:
for (i = BUFFER_COUNT - 1; i >= 0; i--)
if (test->cpu[i])
dma_free_coherent(dev, PAGE_SIZE, test->cpu[i], test->dma[i]);
out_clock:
restore_ret = clk_set_rate(test->clock, test->old_rate);
if (restore_ret)
ret = restore_ret;
clk_disable_unprepare(test->clock);
out_icc:
if (test->icc_cfg) {
icc_set_bw(test->icc_cfg, 0, 0);
icc_put(test->icc_cfg);
test->icc_cfg = NULL;
}
if (test->icc_mem) {
icc_set_bw(test->icc_mem, 0, 0);
icc_put(test->icc_mem);
test->icc_mem = NULL;
}
out_result:
if (test) {
if (test->dma_masks_saved) {
restore_ret = dma_set_mask(dev, test->old_dma_mask);
if (restore_ret)
ret = restore_ret;
restore_ret = dma_set_coherent_mask(dev, test->old_coherent_mask);
if (restore_ret)
ret = restore_ret;
}
record_result(test, ret);
put_modem(test);
}
probe_result = ret;
if (ret)
dev_err(dev, "command test failed: %d\n", ret);
return ret;
}
static const struct of_device_id command_match[] = {
{ .compatible = "qcom,sdm660-ipa" },
{ }
};
static struct platform_driver command_driver = {
.probe = command_probe,
.driver = {
.name = "platina-ipa-v2-cmd-test",
.of_match_table = command_match,
.probe_type = PROBE_FORCE_SYNCHRONOUS,
.suppress_bind_attrs = true,
},
};
static int __init command_init(void)
{
int ret;
if (run == inspect || mode_op > 2 || (dma_bits != 30 && dma_bits != 32) ||
!(cfg_val & 0x1) || (cfg_val & ~0x1fU) ||
PAGE_SIZE != 4096 || !of_machine_is_compatible("xiaomi,platina"))
return -ENODEV;
ret = platform_driver_register(&command_driver);
if (ret)
return ret;
registered = true;
if (resources_pinned)
return 0;
platform_driver_unregister(&command_driver);
registered = false;
return probe_seen ? probe_result : -ENODEV;
}
static void __exit command_exit(void)
{
if (registered)
platform_driver_unregister(&command_driver);
}
module_init(command_init);
module_exit(command_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Platina IPA v2.6L opt-in BAM immediate SRAM read test");
@@ -0,0 +1,269 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Temporary AP DMA mapping qualification for the IPA v2.6L BAM port.
*
* The old platina DT omits the AP IOMMU stream. A generated overlay adds
* one temporary test device using the vendor AP stream (ANOC2, 0x19c0).
* The platform/IOMMU core attaches its default DMA domain. We do not
* manufacture physical DMA addresses or attach an identity domain.
*
* No IPA/BAM MMIO, clock change, IRQ, DMA submission, reset, QMI or netdev.
* All allocations and the overlay are removed before successful init.
*/
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/firmware.h>
#include <linux/init.h>
#include <linux/iommu.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
#include <linux/sysfs.h>
#include "ipa_v2_dma.h"
#define AP_STREAM_ID 0x19c0
#define ANOC2_PATH "/soc@0/iommu@16c0000"
#define TEST_PATH "/soc@0/platina-ipa-dma-test@147c0000"
#define TEST_COMPAT "xiaomi,platina-ipa-v2-dma-test"
#define TEST_BUFFERS 3
static char *overlay_firmware = "platina/ipa-v2-dma-test.dtbo";
module_param(overlay_firmware, charp, 0400);
MODULE_PARM_DESC(overlay_firmware, "Overlay generated from this boot's live DT");
static char snapshot[512];
static bool probe_seen;
static int probe_result = -ENODEV;
static int overlay_id;
static int snapshot_get(char *buffer, const struct kernel_param *kp)
{
return sysfs_emit(buffer, "%s\n", snapshot);
}
static const struct kernel_param_ops snapshot_ops = {
.get = snapshot_get,
};
module_param_cb(snapshot, &snapshot_ops, NULL, 0400);
MODULE_PARM_DESC(snapshot, "Mapping test result; no hardware DMA was submitted");
static int count_device(struct device *dev, void *data)
{
unsigned int *count = data;
(*count)++;
return 0;
}
static bool node_at_path(struct device_node *node, const char *path)
{
struct device_node *expected = of_find_node_by_path(path);
bool match = expected && node == expected;
of_node_put(expected);
return match;
}
/* Reject another declaration of the AP stream before adding a test device. */
static int ap_stream_unused(void)
{
struct of_phandle_args args;
struct device_node *node;
int i, ret;
for_each_node_with_property(node, "iommus") {
for (i = 0; ; i++) {
bool conflict;
ret = of_parse_phandle_with_args(node, "iommus",
"#iommu-cells", i, &args);
if (ret == -ENOENT)
break;
if (ret) {
of_node_put(node);
return ret;
}
conflict = node_at_path(args.np, ANOC2_PATH) &&
args.args_count && args.args[0] == AP_STREAM_ID;
of_node_put(args.np);
if (conflict) {
pr_err("%s: AP stream already declared by %pOF\n",
KBUILD_MODNAME, node);
of_node_put(node);
return -EBUSY;
}
}
}
return 0;
}
static int dma_test_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct of_phandle_args args;
struct iommu_domain *domain;
struct iommu_group *group;
struct resource *res;
void *cpu[TEST_BUFFERS] = { };
dma_addr_t dma[TEST_BUFFERS] = { };
unsigned int count = 0;
int ret, i, group_id;
probe_seen = true;
ret = -EINVAL;
if (!node_at_path(dev->of_node, TEST_PATH))
goto out_result;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res || res->start != 0x147c0000 || resource_size(res) != 0x1000)
goto out_result;
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res || res->start != 0x14784000 || resource_size(res) != 0x26934)
goto out_result;
ret = of_parse_phandle_with_args(dev->of_node, "iommus", "#iommu-cells",
0, &args);
if (ret)
goto out_result;
ret = args.args_count == 1 && args.args[0] == AP_STREAM_ID &&
node_at_path(args.np, ANOC2_PATH) ? 0 : -EINVAL;
of_node_put(args.np);
if (ret)
goto out_result;
domain = iommu_get_domain_for_dev(dev);
if (!domain || domain->type != IOMMU_DOMAIN_DMA) {
ret = -EOPNOTSUPP;
dev_err(dev, "strict translated DMA domain required\n");
goto out_result;
}
group = iommu_group_get(dev);
if (!group) {
ret = -ENODEV;
goto out_result;
}
ret = iommu_group_for_each_dev(group, &count, count_device);
group_id = iommu_group_id(group);
iommu_group_put(group);
if (ret || count != 1) {
ret = ret ?: -EBUSY;
goto out_result;
}
ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
if (ret)
goto out_result;
for (i = 0; i < TEST_BUFFERS; i++) {
cpu[i] = dma_alloc_coherent(dev, PAGE_SIZE, &dma[i], GFP_KERNEL);
if (!cpu[i]) {
ret = -ENOMEM;
goto out_free;
}
ret = ipa_v2_verify_mapping(dev, domain, cpu[i], dma[i]);
if (ret)
goto out_free;
}
scnprintf(snapshot, sizeof(snapshot),
"{\"datapath_ready\":false,\"mapping_verified\":true,"
"\"hardware_dma_verified\":false,\"stream_id\":%u,"
"\"iommu_group\":%d,\"domain_type\":%u,\"dma_bits\":32,"
"\"page_size\":%lu,\"buffers\":%u,"
"\"iovas\":[%llu,%llu,%llu]}",
AP_STREAM_ID, group_id, domain->type, PAGE_SIZE, TEST_BUFFERS,
(unsigned long long)dma[0], (unsigned long long)dma[1],
(unsigned long long)dma[2]);
dev_info(dev, "mapping verified: %s\n", snapshot);
out_free:
for (i = TEST_BUFFERS - 1; i >= 0; i--)
if (cpu[i])
dma_free_coherent(dev, PAGE_SIZE, cpu[i], dma[i]);
out_result:
probe_result = ret;
if (ret)
dev_err(dev, "DMA mapping test failed: %d\n", ret);
return ret;
}
static const struct of_device_id dma_test_match[] = {
{ .compatible = TEST_COMPAT },
{ }
};
/* No MODULE_DEVICE_TABLE: explicit loading only, never an automatic service. */
static struct platform_driver dma_test_driver = {
.probe = dma_test_probe,
.driver = {
.name = "platina-ipa-v2-dma-test",
.of_match_table = dma_test_match,
.probe_type = PROBE_FORCE_SYNCHRONOUS,
.suppress_bind_attrs = true,
},
};
static int __init dma_test_init(void)
{
const struct firmware *firmware;
struct platform_device *original;
struct device_node *node;
int ret, remove_ret;
if (!of_machine_is_compatible("xiaomi,platina"))
return -ENODEV;
node = of_find_compatible_node(NULL, NULL, "qcom,sdm660-ipa");
if (!node)
return -ENODEV;
original = of_find_device_by_node(node);
of_node_put(node);
if (!original)
return -ENODEV;
device_lock(&original->dev);
if (original->dev.driver || iommu_get_domain_for_dev(&original->dev)) {
ret = -EBUSY;
goto out_device;
}
ret = ap_stream_unused();
if (ret)
goto out_device;
ret = request_firmware_direct(&firmware, overlay_firmware, &original->dev);
if (ret)
goto out_device;
if (!firmware->size || firmware->size > 4096) {
ret = -EINVAL;
goto out_firmware;
}
ret = platform_driver_register(&dma_test_driver);
if (ret)
goto out_firmware;
ret = of_overlay_fdt_apply(firmware->data, firmware->size, &overlay_id, NULL);
if (!ret)
ret = probe_seen ? probe_result : -ENODEV;
platform_driver_unregister(&dma_test_driver);
if (overlay_id > 0) {
remove_ret = of_overlay_remove(&overlay_id);
if (remove_ret) {
pr_err("%s: overlay cleanup failed: %d\n",
KBUILD_MODNAME, remove_ret);
ret = remove_ret;
}
}
if (!ret)
pr_info("%s: buffers freed, test device and overlay removed\n",
KBUILD_MODNAME);
out_firmware:
release_firmware(firmware);
out_device:
device_unlock(&original->dev);
put_device(&original->dev);
return ret;
}
static void __exit dma_test_exit(void)
{
}
module_init(dma_test_init);
module_exit(dma_test_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Platina IPA v2.6L temporary strict IOMMU mapping test");
@@ -0,0 +1,214 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Read-only register snapshot for the platina IPA v2.6L port.
*
* Register locations: Xiaomi platina-o-oss commit
* 0bb2780bccb9c7e05f0edf5db8860e779179b5f9, ipa_v2/ipa_reg.h and
* drivers/platform/msm/sps/bam.c (SPS_BAM_NDP_4K).
*
* No device alias, driver binding, reset, DMA, IRQ acknowledgement, or QMI
* messages. Clock references and MMIO reservations exist only during init.
*/
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <linux/sysfs.h>
#define IPA_WRAPPER_BASE 0x14780000
#define IPA_REG_OFFSET 0x40000
#define IPA_REG_BASE (IPA_WRAPPER_BASE + IPA_REG_OFFSET)
#define IPA_REG_SIZE 0x1000
#define IPA_BAM_BASE 0x14784000
#define IPA_BAM_SIZE 0x26934
/* Original driver's SVS vote; RPM does not expose a measured frequency. */
#define IPA_SVS_RATE 75000000
#define IPA_COMP_HW_VERSION 0x30
#define IPA_VERSION 0x34
#define IPA_COMP_CFG 0x38
#define IPA_SHARED_MEM_SIZE 0x50
#define IPA_ENABLED_PIPES 0x5dc
#define BAM_CTRL 0x0
#define BAM_DESC_THRESHOLD 0x8
#define BAM_IRQ_STATUS 0x14
#define BAM_CNFG_BITS 0x7c
#define BAM_REVISION 0x1000
#define BAM_NUM_PIPES 0x1008
#define BAM_AHB_ERR_CTRL 0x1024
#define BAM_AHB_ERR_ADDR 0x1028
#define BAM_PIPE_ATTR_EE0 0x300c
#define BAM_PIPE_CTRL(n) (0x13000 + 0x1000 * (n))
#define BAM_PIPE_SW_OFSTS(n) (0x13800 + 0x1000 * (n))
static char snapshot[1024];
static int snapshot_get(char *buffer, const struct kernel_param *kp)
{
return sysfs_emit(buffer, "%s\n", snapshot);
}
static const struct kernel_param_ops snapshot_ops = {
.get = snapshot_get,
};
module_param_cb(snapshot, &snapshot_ops, NULL, 0400);
MODULE_PARM_DESC(snapshot, "Read-only IPA/BAM snapshot; does not prove datapath readiness");
static int __init platina_ipa_v2_probe_init(void)
{
struct platform_device *pdev;
struct device_node *node;
struct resource *resource;
struct clk *clock;
void __iomem *ipa, *bam;
u32 version, hardware, memory, bam_revision, bam_info, num_pipes;
unsigned long clock_rate, old_rate;
int ret, restore_ret;
if (!of_machine_is_compatible("xiaomi,platina"))
return -ENODEV;
node = of_find_compatible_node(NULL, NULL, "qcom,sdm660-ipa");
if (!node)
return -ENODEV;
pdev = of_find_device_by_node(node);
of_node_put(node);
if (!pdev)
return -EPROBE_DEFER;
/* Serialize against driver binding for the entire snapshot. */
device_lock(&pdev->dev);
if (pdev->dev.driver) {
ret = -EBUSY;
goto out_device;
}
resource = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!resource || (resource->start != IPA_WRAPPER_BASE &&
resource->start != IPA_REG_BASE)) {
ret = -EINVAL;
goto out_device;
}
/* The old DT maps the wrapper, not the actual IPA register aperture. */
if (!request_mem_region(IPA_REG_BASE, IPA_REG_SIZE, KBUILD_MODNAME)) {
ret = -EBUSY;
goto out_device;
}
if (!request_mem_region(IPA_BAM_BASE, IPA_BAM_SIZE, KBUILD_MODNAME)) {
ret = -EBUSY;
goto out_ipa_region;
}
clock = clk_get(&pdev->dev, "core");
if (IS_ERR(clock)) {
ret = PTR_ERR(clock);
goto out_bam_region;
}
old_rate = clk_get_rate(clock);
/*
* Follow the vendor prepare-before-set order. This RPM provider ignores
* set_rate while unprepared, so an earlier successful call is no vote.
*/
ret = clk_prepare_enable(clock);
if (ret)
goto out_clock;
ret = clk_set_rate(clock, IPA_SVS_RATE);
if (ret)
goto out_restore_rate;
clock_rate = clk_get_rate(clock);
if (clock_rate != IPA_SVS_RATE) {
ret = -ENODEV;
goto out_restore_rate;
}
ipa = ioremap(IPA_REG_BASE, IPA_REG_SIZE);
if (!ipa) {
ret = -ENOMEM;
goto out_restore_rate;
}
bam = ioremap(IPA_BAM_BASE, IPA_BAM_SIZE);
if (!bam) {
ret = -ENOMEM;
goto out_unmap_ipa;
}
version = readl(ipa + IPA_VERSION);
hardware = readl(ipa + IPA_COMP_HW_VERSION);
memory = readl(ipa + IPA_SHARED_MEM_SIZE);
bam_revision = readl(bam + BAM_REVISION);
bam_info = readl(bam + BAM_NUM_PIPES);
num_pipes = bam_info & 0xff;
if (!version || version == U32_MAX || !bam_revision ||
bam_revision == U32_MAX || num_pipes < 10 || num_pipes > 20) {
dev_err(&pdev->dev,
"invalid snapshot: version=%#x hardware=%#x BAM=%#x pipes=%u\n",
version, hardware, bam_revision, num_pipes);
ret = -ENODEV;
goto out_unmap_bam;
}
scnprintf(snapshot, sizeof(snapshot),
"{\"datapath_ready\":false,\"core_vote_hz\":%u,"
"\"core_cached_hz\":%lu,"
"\"ipa_version\":%u,\"ipa_hw_version\":%u,\"ipa_cfg\":%u,"
"\"sram_size\":%u,\"sram_restricted\":%u,\"ipa_num_pipes\":%u,"
"\"bam_revision\":%u,\"bam_pipes\":%u,\"bam_ctrl\":%u,"
"\"bam_cfg_bits\":%u,\"bam_desc_threshold\":%u,"
"\"bam_ahb_err_ctrl\":%u,\"bam_ahb_err_addr\":%u,"
"\"bam_num_pipes_raw\":%u,"
"\"bam_irq_status\":%u,\"bam_ee0_pipes\":%u,"
"\"ap_lan_rx\":{\"pipe\":2,\"ctrl\":%u,\"offsets\":%u},"
"\"ap_command_tx\":{\"pipe\":3,\"ctrl\":%u,\"offsets\":%u},"
"\"ap_tx\":{\"pipe\":4,\"ctrl\":%u,\"offsets\":%u},"
"\"ap_wan_rx\":{\"pipe\":5,\"ctrl\":%u,\"offsets\":%u}}",
IPA_SVS_RATE, clock_rate, version, hardware, readl(ipa + IPA_COMP_CFG),
memory & 0xffff, memory >> 16, readl(ipa + IPA_ENABLED_PIPES),
bam_revision, num_pipes, readl(bam + BAM_CTRL),
readl(bam + BAM_CNFG_BITS), readl(bam + BAM_DESC_THRESHOLD),
readl(bam + BAM_AHB_ERR_CTRL), readl(bam + BAM_AHB_ERR_ADDR),
bam_info,
readl(bam + BAM_IRQ_STATUS), readl(bam + BAM_PIPE_ATTR_EE0),
readl(bam + BAM_PIPE_CTRL(2)), readl(bam + BAM_PIPE_SW_OFSTS(2)),
readl(bam + BAM_PIPE_CTRL(3)), readl(bam + BAM_PIPE_SW_OFSTS(3)),
readl(bam + BAM_PIPE_CTRL(4)), readl(bam + BAM_PIPE_SW_OFSTS(4)),
readl(bam + BAM_PIPE_CTRL(5)), readl(bam + BAM_PIPE_SW_OFSTS(5)));
dev_info(&pdev->dev, "read-only snapshot: %s\n", snapshot);
ret = 0;
out_unmap_bam:
iounmap(bam);
out_unmap_ipa:
iounmap(ipa);
out_restore_rate:
/* Restore while prepared: the RPM provider ignores an unprepared set. */
restore_ret = clk_set_rate(clock, old_rate);
if (restore_ret) {
dev_err(&pdev->dev, "could not restore IPA clock rate: %d\n",
restore_ret);
if (!ret)
ret = restore_ret;
}
clk_disable_unprepare(clock);
out_clock:
clk_put(clock);
out_bam_region:
release_mem_region(IPA_BAM_BASE, IPA_BAM_SIZE);
out_ipa_region:
release_mem_region(IPA_REG_BASE, IPA_REG_SIZE);
out_device:
device_unlock(&pdev->dev);
put_device(&pdev->dev);
return ret;
}
static void __exit platina_ipa_v2_probe_exit(void)
{
}
module_init(platina_ipa_v2_probe_init);
module_exit(platina_ipa_v2_probe_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Platina IPA v2.6L read-only bring-up diagnostic");
+5
View File
@@ -0,0 +1,5 @@
# Append only for opt-in IPA hardware qualification, alongside phone-dsp.openrc.
# Without -s, rmtfs serves files without starting/stopping the modem rproc.
case " $(cat /proc/cmdline 2>/dev/null) " in
*" platina.ipa_bringup=1 "*) command_args="-P -r -v" ;;
esac
+2 -2
View File
@@ -16,8 +16,8 @@
"candidate": {
"ports": "ports/candidate",
"kernel": "7.2.12",
"kernel_package": "7.2.12-r22",
"device_package": "5-r31",
"kernel_package": "7.2.12-r25",
"device_package": "5-r32",
"firmware_package": "2-r5"
}
},
+11 -4
View File
@@ -5,11 +5,18 @@
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RELEASE_DIR="$SCRIPT_DIR/artifacts/release-v0.8.1-bulletproof"
RELEASE_DIR="$SCRIPT_DIR/artifacts/release-v0.8.2-cellular"
ARCHIVE="$SCRIPT_DIR/release/platina-linux-v0.8.2-cellular-release.tar.xz"
if [[ ! -d "$RELEASE_DIR" ]]; then
echo "ERROR: Release directory '$RELEASE_DIR' not found!"
exit 1
if [[ ! -f "$RELEASE_DIR/flash.sh" ]]; then
if [[ -f "$ARCHIVE" ]]; then
echo "Extracting $ARCHIVE into $RELEASE_DIR ..."
mkdir -p "$RELEASE_DIR"
tar -xJf "$ARCHIVE" -C "$RELEASE_DIR"
else
echo "ERROR: Release directory '$RELEASE_DIR' and archive '$ARCHIVE' not found!"
exit 1
fi
fi
exec "$RELEASE_DIR/flash.sh" "$@"
+1
View File
@@ -18,6 +18,7 @@ HELPERS = {
'scripts/phone-splash.py': 'usr/local/sbin/platina-splash',
'scripts/phone-display.py': 'usr/local/sbin/platina-display',
'scripts/phone-display-session.py': 'usr/local/sbin/platina-display-session',
'scripts/phone-status-screen.py': 'usr/local/sbin/platina-status-screen',
'scripts/phone-poweroff.py': 'usr/local/sbin/platina-poweroff',
'scripts/phone-power-chord.py': 'usr/local/sbin/platina-power-chord',
'scripts/phone-power-chord.openrc': 'etc/init.d/platina-power-chord',
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Generate a temporary AP DMA test overlay from this boot's live device tree.
No DT change, module loading or compilation is performed by this program.
The generated phandles are valid only for the inspected tree/boot.
"""
import argparse
from pathlib import Path
import struct
import sys
def cells(path):
data = path.read_bytes()
if not data or len(data) % 4:
raise ValueError(f"invalid cells: {path}")
return struct.unpack(f">{len(data) // 4}I", data)
def generate(root):
if b"xiaomi,platina" not in (root / "compatible").read_bytes().split(b"\0"):
raise ValueError("the device is not xiaomi,platina")
soc = root / "soc@0"
if cells(soc / "#address-cells") != (1,) or cells(soc / "#size-cells") != (1,):
raise ValueError("unsupported SoC address/size cells")
providers = {}
for prop in root.rglob("phandle"):
value, = cells(prop)
if not value or value in providers:
raise ValueError("invalid or duplicate phandle")
providers[value] = prop.parent
smmu = soc / "iommu@16c0000"
if b"qcom,smmu-v2" not in (smmu / "compatible").read_bytes().split(b"\0"):
raise ValueError("ANOC2 SMMU is not the expected controller")
if cells(smmu / "#iommu-cells") != (1,):
raise ValueError("unsupported ANOC2 IOMMU argument layout")
smmu_id, = cells(smmu / "phandle")
for prop in root.rglob("iommus"):
values = cells(prop)
offset = 0
while offset < len(values):
provider = providers.get(values[offset])
if provider is None:
raise ValueError(f"unresolved IOMMU provider: {prop}")
nargs, = cells(provider / "#iommu-cells")
if nargs < 1 or offset + nargs >= len(values):
raise ValueError(f"invalid IOMMU arguments: {prop}")
if provider == smmu and values[offset + 1] == 0x19C0:
raise ValueError(f"AP stream 0x19c0 already declared: {prop.parent}")
offset += nargs + 1
ipa_nodes = [p.parent for p in soc.glob("*/compatible")
if b"qcom,sdm660-ipa" in p.read_bytes().split(b"\0")]
if len(ipa_nodes) != 1:
raise ValueError("expected exactly one original IPA node")
ipa = ipa_nodes[0]
if (ipa / "clock-names").read_bytes() != b"core\0":
raise ValueError("unsupported IPA clocks")
clock = cells(ipa / "clocks")
if len(clock) != 2 or clock[1] != 0x44:
raise ValueError("expected RPM IPA core clock 0x44")
if clock[0] not in providers or cells(providers[clock[0]] / "#clock-cells") != (1,):
raise ValueError("invalid IPA clock provider")
if (soc / "platina-ipa-dma-test@147c0000").exists():
raise ValueError("the temporary test node already exists")
return f'''/dts-v1/;
/plugin/;
/* Generated from the inspected live DT. Do not reuse across different DTBs. */
/ {{
fragment@0 {{
target-path = "/soc@0";
__overlay__ {{
platina-ipa-dma-test@147c0000 {{
compatible = "xiaomi,platina-ipa-v2-dma-test";
reg = <0x147c0000 0x1000>, <0x14784000 0x26934>;
reg-names = "ipa", "bam";
iommus = <0x{smmu_id:x} 0x19c0>;
clocks = <0x{clock[0]:x} 0x44>;
clock-names = "core";
status = "okay";
}};
}};
}};
}};
'''
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dt-root", type=Path, default=Path("/sys/firmware/devicetree/base"))
args = parser.parse_args()
try:
sys.stdout.write(generate(args.dt_root))
except (OSError, ValueError, struct.error) as error:
parser.exit(1, f"overlay generation refused: {error}\n")
if __name__ == "__main__":
main()
+118 -6
View File
@@ -27,6 +27,71 @@ import time
import tty
class PPPFrameStats:
"""Count validated async PPP frames without retaining packet contents."""
def __init__(self):
self.frame = None
self.escaped = False
self.protocols = {}
self.invalid_fcs = 0
self.oversized = 0
self.ipv4_bytes = 0
@staticmethod
def fcs(data):
value = 0xffff
for byte in data:
value ^= byte
for _ in range(8):
value = (value >> 1) ^ (0x8408 if value & 1 else 0)
return value
def feed(self, data):
for byte in data:
if byte == 0x7e:
if self.frame and not self.escaped:
self.record(bytes(self.frame))
self.frame = bytearray()
self.escaped = False
elif self.frame is not None:
if self.escaped:
self.frame.append(byte ^ 0x20)
self.escaped = False
elif byte == 0x7d:
self.escaped = True
else:
self.frame.append(byte)
if len(self.frame) > 65536:
self.oversized += 1
self.frame = None
self.escaped = False
def record(self, frame):
if len(frame) < 3 or self.fcs(frame) != 0xf0b8:
self.invalid_fcs += 1
return
payload = frame[:-2]
if payload.startswith(b'\xff\x03'):
payload = payload[2:]
if not payload:
return
size = 1 if payload[0] & 1 else 2
if len(payload) < size:
return
protocol = int.from_bytes(payload[:size], 'big')
name = {0x21: 'ipv4', 0x57: 'ipv6', 0xc021: 'lcp',
0x8021: 'ipcp', 0xc023: 'pap', 0xc223: 'chap'}.get(
protocol, f'0x{protocol:04x}')
self.protocols[name] = self.protocols.get(name, 0) + 1
if protocol == 0x21:
self.ipv4_bytes += len(payload) - size
def summary(self):
return {'protocol_frames': dict(self.protocols), 'ipv4_bytes': self.ipv4_bytes,
'invalid_fcs': self.invalid_fcs, 'oversized_frames': self.oversized}
@contextmanager
def exclusive_session(path='/run/lock/platina-cellular-rpmsg.lock'):
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
@@ -142,6 +207,7 @@ def query(fd, timeout=5):
results = []
for command in ('AT', 'AT+CFUN?', 'AT+CPIN?', 'AT+CSQ', 'AT+COPS?',
'AT+CEREG?', 'AT+CGREG?', 'AT+CGATT?', 'AT+CGDCONT?',
'AT+CGACT?', 'AT+CGPADDR', 'AT+CGCONTRDP',
'AT+CGDATA=?', 'AT+CEER'):
result = at_command(fd, command, timeout)
result.pop('trailing')
@@ -170,6 +236,52 @@ def interface_ipv4(interface):
return None
def stop_ppp(proc, fd, master, timeout=5):
"""Keep the transport alive while pppd sends its termination handshake."""
if proc.poll() is not None:
return
proc.terminate()
deadline = time.monotonic() + timeout
pending = bytearray()
try:
while proc.poll() is None and time.monotonic() < deadline:
readable, writable, _ = select.select(
[fd, master], [master] if pending else [], [],
min(0.1, max(0, deadline - time.monotonic())))
if master in writable:
try:
count = os.write(master, pending)
del pending[:count]
except BlockingIOError:
pass
if fd in readable:
try:
data = os.read(fd, 65536)
except BlockingIOError:
data = None
if data == b'':
break
if data:
pending.extend(data)
if len(pending) > 1024 * 1024:
break
if master in readable:
try:
data = os.read(master, 1024)
except BlockingIOError:
continue
if data:
send_message(fd, data)
except (OSError, RuntimeError):
# Remote modem teardown can remove the endpoint before pppd exits.
# Process cleanup must still finish, and must not hide the main error.
pass
finally:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=5)
def probe_dns(interface, target):
"""Query a public resolver over a socket explicitly bound to the PPP device."""
transaction = os.urandom(2)
@@ -278,6 +390,8 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
local_ip = None
verification = None
tx_bytes = rx_bytes = 0
tx_frames, rx_frames = PPPFrameStats(), PPPFrameStats()
rx_frames.feed(trailing)
try:
tty.setraw(slave)
os.set_blocking(master, False)
@@ -326,6 +440,7 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
if data:
to_pty.extend(data)
rx_bytes += len(data)
rx_frames.feed(data)
if len(to_pty) > 1024 * 1024:
raise RuntimeError('PPP receive queue exceeded 1 MiB')
if master in readable:
@@ -340,9 +455,11 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
if data:
send_message(fd, data)
tx_bytes += len(data)
tx_frames.feed(data)
return {'interface': interface, 'local_ip': local_ip,
'bridge_tx_bytes': tx_bytes,
'bridge_rx_bytes': rx_bytes, 'pppd_exit': proc.poll(),
'ppp_frames': {'tx': tx_frames.summary(), 'rx': rx_frames.summary()},
'verification': verification,
'ip_connectivity': bool(verification and verification['exit_code'] == 0)}
finally:
@@ -358,12 +475,7 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
if dns_pool is not None:
dns_pool.shutdown(wait=True, cancel_futures=True)
if proc is not None and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
stop_ppp(proc, fd, master)
os.close(master)
os.close(slave)
+28 -11
View File
@@ -102,11 +102,10 @@ def parse_mmcli_modem_info(raw_text):
def cellular_datapath_status(sys_path='/sys'):
"""Inspect transport backing; a driver binding or interface name is insufficient.
"""Inspect cellular hardware transport readiness under sysfs.
The current IPA v2.6 shim has no BAM TX/RX implementation. Reject it even
when it exposes rmnet_ipa0. A future real backend must explicitly expose
modem/datapath_ready=1 before this integration permits activation.
Legacy IPA v2.6L hardware must expose modem/datapath_ready=1 before
NetworkManager activation is permitted.
"""
root = Path(sys_path)
rows = []
@@ -133,8 +132,10 @@ def cellular_datapath_status(sys_path='/sys'):
compatible = read(device / 'of_node/compatible').split('\0')
legacy = (version.startswith('2.') or
any(value in ('qcom,sdm660-ipa', 'qcom,ipa-v2.6') for value in compatible))
if legacy and read(device / 'modem/datapath_ready') != '1':
return False, 'IPA v2.6 shim: BAM TX/RX not implemented'
if legacy:
if read(device / 'modem/datapath_ready') != '1':
return False, 'IPA v2.6 shim: BAM TX/RX not implemented'
return True, 'bound hardware transport (datapath_ready=1)'
return True, 'bound hardware transport (IP connectivity unverified)'
for iface in sorted((root / 'class/net').glob('*')):
@@ -260,6 +261,7 @@ def build_nmcli_setup_commands(con_name=CONNECTION_NAME, apn='cmnet', ifname='*'
'gsm.apn', apn,
'gsm.auto-config', 'yes',
'connection.autoconnect', 'no',
'ipv4.route-metric', '700',
'connection.interface-name', ifname if ifname != '*' else ''])
else:
cmd = ['nmcli', 'connection', 'add',
@@ -268,7 +270,8 @@ def build_nmcli_setup_commands(con_name=CONNECTION_NAME, apn='cmnet', ifname='*'
'ifname', ifname,
'apn', apn,
'gsm.auto-config', 'yes',
'connection.autoconnect', 'no']
'connection.autoconnect', 'no',
'ipv4.route-metric', '700']
commands.append(cmd)
return commands
@@ -423,10 +426,6 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
"""
logger("Starting Platina cellular auto-connect...")
if not datapath_checker():
logger("No hardware IPA or rmnet cellular data path detected in kernel; dialing skipped to maintain modem and Wi-Fi stability.")
return False
attempts = 0
last_operator = None
last_state = None
@@ -438,6 +437,15 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
logger(f"Reached maximum attempts ({max_attempts}), stopping.")
return False
if not datapath_checker():
if last_state != 'no_datapath':
logger("No hardware IPA or rmnet cellular data path detected in kernel; dialing skipped to maintain modem and Wi-Fi stability.")
last_state = 'no_datapath'
if not daemon:
return False
sleeper(poll_interval)
continue
# Battery gate check: do not allow RF transmit if battery voltage/capacity is low
bat_ok, bat_msg = battery_checker()
if not bat_ok:
@@ -492,6 +500,15 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
sleeper(poll_interval)
continue
if state in ('searching', 'initializing', 'enabling') and not operator_code:
if daemon or (max_attempts is None or attempts < max_attempts):
wait_key = f'waiting_{state}'
if last_state != wait_key:
logger(f"Modem state is {state} without operator PLMN; waiting for registration...")
last_state = wait_key
sleeper(poll_interval)
continue
# Determine APN for current operator
apn = detect_apn_for_operator(
operator_code,
+49 -12
View File
@@ -6,25 +6,66 @@ depend() {
before networkmanager
}
ipa_bringup_mode() {
case " $(cat "${1:-/proc/cmdline}" 2>/dev/null) " in
*" platina.ipa_bringup=1 "*) return 0 ;;
esac
return 1
}
start_remoteprocs() {
local root="$1" hold_modem="$2" rproc
for rproc in "$root"/remoteproc*; do
if [ -d "$rproc" ] && [ -f "$rproc/state" ]; then
if [ "$hold_modem" = 1 ] &&
[ "$(cat "$rproc/name" 2>/dev/null)" = "4080000.remoteproc" ]; then
continue
fi
if [ "$(cat "$rproc/state" 2>/dev/null)" = "offline" ]; then
echo start > "$rproc/state" 2>/dev/null || true
fi
fi
done
}
start() {
local hold_modem=0
if ipa_bringup_mode; then
hold_modem=1
fi
ebegin "Initializing Platina DSP and WCN3990 Wi-Fi"
# 1. Un-blacklist modem driver from initramfs disarm
sed -i "/qcom_q6v5_mss/d" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null
if ! grep -q "blacklist ipa" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null; then
echo -e "install ipa /bin/true\nblacklist ipa" > /etc/modprobe.d/modem-blacklist.conf
# 1. Manage initramfs modem/IPA blacklists for normal vs early bringup mode
sed -i "/qcom_q6v5_mss/d" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null || true
if [ "$hold_modem" = 1 ]; then
if ! grep -q "blacklist ipa" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null; then
printf "install ipa /bin/true\nblacklist ipa\n" > /etc/modprobe.d/modem-blacklist.conf
fi
else
sed -i "/ipa/d" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null || true
if [ -f /etc/modprobe.d/modem-blacklist.conf ] &&
[ ! -s /etc/modprobe.d/modem-blacklist.conf ]; then
rm -f /etc/modprobe.d/modem-blacklist.conf
fi
fi
# 2. Ensure kernel modules are loaded
modprobe qcom_rmtfs_mem 2>/dev/null || true
modprobe qcom_q6v5_pas 2>/dev/null || true
modprobe qcom_q6v5_mss 2>/dev/null || true
if [ "$hold_modem" = 0 ]; then
modprobe ipa 2>/dev/null || true
fi
# 3. Ensure tqftpserv and rmtfs daemons are running
if ! pidof tqftpserv >/dev/null 2>&1; then
rc-service tqftpserv restart 2>/dev/null || /usr/bin/tqftpserv &
fi
if ! pidof rmtfs >/dev/null 2>&1; then
rc-service rmtfs restart 2>/dev/null || /usr/bin/rmtfs -s -P -r -v &
if [ "$hold_modem" = 1 ]; then
rc-service rmtfs restart 2>/dev/null || /usr/bin/rmtfs -P -r -v &
else
rc-service rmtfs restart 2>/dev/null || /usr/bin/rmtfs -s -P -r -v &
fi
fi
# Wait up to 3s for remoteproc nodes to register
@@ -36,13 +77,7 @@ start() {
done
# 4. Start any offline remoteproc instance (modem/ADSP/CDSP)
for rproc in /sys/class/remoteproc/remoteproc*; do
if [ -d "$rproc" ] && [ -f "$rproc/state" ]; then
if [ "$(cat "$rproc/state" 2>/dev/null)" = "offline" ]; then
echo start > "$rproc/state" 2>/dev/null || true
fi
fi
done
start_remoteprocs /sys/class/remoteproc "$hold_modem"
# 5. Ensure pd-mapper is running
if ! pidof pd-mapper >/dev/null 2>&1; then
@@ -50,6 +85,7 @@ start() {
fi
# Wait for modem remoteproc to be running before probing ath10k
if [ "$hold_modem" = 0 ]; then
for i in 1 2 3 4 5; do
for rproc in /sys/class/remoteproc/remoteproc*; do
if [ -f "$rproc/name" ] && grep -q "4080000" "$rproc/name" 2>/dev/null; then
@@ -60,6 +96,7 @@ start() {
done
sleep 1
done
fi
# 6. Load ath10k_snoc Wi-Fi driver cleanly
if ! lsmod | grep -q ath10k_snoc; then
+20 -1
View File
@@ -1,8 +1,27 @@
#!/bin/sh
# Always start dark. Display the installed release briefly in the background.
# Always start dark. Display charger UI in charger boot mode, or release logo briefly.
for path in /sys/class/backlight/*/brightness; do
[ -w "$path" ] && printf '0\n' > "$path"
done
CMDLINE=$(cat /proc/cmdline 2>/dev/null || true)
CHARGER_MODE=0
case " $CMDLINE " in
*" androidboot.mode=charger "*|*" androidboot.bootreason=usb_chg "*)
CHARGER_MODE=1
;;
esac
if [ "$CHARGER_MODE" = 1 ]; then
if [ -x /usr/local/sbin/platina-status-screen ]; then
umask 027
(
timeout -s TERM -k 3 10 /usr/local/sbin/platina-status-screen --once --mode charger --seconds 5 || true
if [ -x /usr/local/sbin/platina-display ]; then
/usr/local/sbin/platina-display off || true
fi
) >> /var/log/platina-splash.log 2>&1 &
fi
exit 0
fi
if [ -x /usr/local/sbin/platina-splash ] && [ -r /usr/local/share/platina/current/release.json ]; then
umask 027
(
+4 -1
View File
@@ -1,4 +1,7 @@
# Physical Power + Volume Up only. PMIC emergency reset remains unchanged.
# Physical Power button / chord policy. PMIC emergency reset remains unchanged.
hold_seconds=3
# Start in observation mode until the physical gesture has been checked.
dry_run=yes
power_key_mode=yes
screen_seconds=12
idle_suspend_seconds=60
+5 -2
View File
@@ -1,8 +1,8 @@
#!/sbin/openrc-run
description="Platina Power + Volume Up: hold together, release both to shut down"
description="Platina Power button, status screen, offline charger & standby daemon"
command="/usr/local/sbin/platina-power-chord"
command_user="root:root"
command_args="--hold-seconds ${hold_seconds:-3}"
command_args="--hold-seconds ${hold_seconds:-3} --screen-seconds ${screen_seconds:-12} --idle-suspend-seconds ${idle_suspend_seconds:-60}"
supervisor="supervise-daemon"
pidfile="/run/platina-power-chord.pid"
respawn_delay=5
@@ -18,6 +18,9 @@ depend() {
start_pre() {
checkpath --file --mode 0640 --owner root:root "$output_log"
if yesno "${power_key_mode:-yes}"; then
command_args="$command_args --power-key-mode"
fi
if yesno "${dry_run:-yes}"; then
command_args="$command_args --dry-run"
fi
+402 -19
View File
@@ -1,15 +1,18 @@
#!/usr/bin/env python3
"""Power + Volume Up, held together and fully released, requests orderly shutdown."""
"""Physical Power button, status screen toggle, offline charger & standby daemon."""
import argparse
import errno
import fcntl
import os
from pathlib import Path
import runpy
import select
import signal
import stat
import struct
import subprocess
import sys
import time
KEY_POWER, KEY_VOLUMEUP = 116, 115
KEYS = {KEY_POWER, KEY_VOLUMEUP}
@@ -59,6 +62,138 @@ class ChordPolicy:
return None
class PowerButtonPolicy:
"""Single Power short tap toggles screen; >= hold_seconds triggers long_power immediately."""
def __init__(self, hold_seconds=3.0, min_tap_seconds=0.02, held=()):
if not 1 <= hold_seconds <= 5:
raise ValueError('Choose a hold of 1 to 5 seconds, below the PMIC emergency reset')
self.hold_seconds = float(hold_seconds)
self.min_tap_seconds = float(min_tap_seconds)
self.last = None
self.resync(held)
def resync(self, held):
self.pressed = set(held) & KEYS
self.blocked = bool(self.pressed)
self.power_started = None
self.saw_volumeup = KEY_VOLUMEUP in self.pressed
self.long_fired = False
def check_timeout(self, now):
if (KEY_POWER in self.pressed and not self.blocked and not self.long_fired
and self.power_started is not None and now - self.power_started >= self.hold_seconds):
self.long_fired = True
self.power_started = None
return 'long_power'
return None
def event(self, key, value, timestamp):
if key not in KEYS or value not in (0, 1):
return None
if self.last is not None and timestamp < self.last:
self.resync(self.pressed | {key})
return None
self.last = timestamp
if value == 1:
if key in self.pressed:
return None
self.pressed.add(key)
if key == KEY_VOLUMEUP:
self.saw_volumeup = True
elif key == KEY_POWER and not self.blocked and not self.long_fired:
self.power_started = timestamp
return None
if key not in self.pressed:
return None
action = None
if key == KEY_POWER and self.power_started is not None and not self.blocked and not self.long_fired:
duration = timestamp - self.power_started
if duration >= self.hold_seconds:
action = 'long_power'
self.long_fired = True
elif not self.saw_volumeup and duration >= self.min_tap_seconds:
action = 'toggle_screen'
self.power_started = None
self.pressed.remove(key)
if not self.pressed:
self.resync(())
return action
def _read_text(path):
try:
return Path(path).read_text().strip()
except OSError:
return None
def is_boot_charger_mode(cmdline_path=Path('/proc/cmdline')):
raw = _read_text(cmdline_path)
if not raw:
return False
tokens = raw.split()
return 'androidboot.mode=charger' in tokens or 'androidboot.bootreason=usb_chg' in tokens
def is_external_power_online(sys_supply=Path('/sys/class/power_supply')):
for name in ('pm660-charger', 'qpnp-smbcharger', 'usb', 'charger'):
online = _read_text(Path(sys_supply) / name / 'online')
if online in ('1', 'true'):
return True
return False
def has_active_ssh_session(proc_net=Path('/proc/net')):
for name in ('tcp', 'tcp6'):
raw = _read_text(Path(proc_net) / name)
if not raw:
continue
for line in raw.splitlines()[1:]:
cols = line.split()
if len(cols) >= 4 and cols[3].upper() == '01' and cols[1].upper().endswith(':0016'):
return True
return False
def is_usb_data_host_connected(sys_root=Path('/sys')):
sys_root = Path(sys_root)
if _read_text(sys_root / 'class/net/usb0/carrier') != '1':
return False
usb_type = _read_text(sys_root / 'class/power_supply/pm660-charger/usb_type') or ''
if '[DCP]' in usb_type:
return False
return True
def can_auto_suspend(screen_on, sys_root=Path('/sys'), proc_net=Path('/proc/net'),
inhibit_path=Path('/run/platina-inhibit-suspend')):
if screen_on:
return False, 'screen on'
if Path(inhibit_path).exists():
return False, 'inhibit file'
if is_usb_data_host_connected(sys_root):
return False, 'usb data host'
if has_active_ssh_session(proc_net):
return False, 'active ssh session'
return True, 'idle'
def read_pwrkey_wakeup_count(sys_wakeup=Path('/sys/class/wakeup')):
root = Path(sys_wakeup)
if not root.exists():
return 0
for entry in root.glob('wakeup*'):
name = _read_text(entry / 'name') or ''
if ':pwrkey' in name:
cnt = _read_text(entry / 'event_count')
try:
return int(cnt)
except (TypeError, ValueError):
return 0
return 0
def find_devices(sys_input=Path('/sys/class/input'), dev_input=Path('/dev/input')):
result = {}
for key, name in DEVICES.items():
@@ -96,12 +231,82 @@ def dispatch(dry_run):
raise RuntimeError('Shutdown helper failed; exit ' + str(code))
def monitor(seconds, dry_run):
if os.geteuid() != 0:
raise ValueError('Run on the phone as root')
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('This service requires Platina')
descriptors, dropped = {}, set()
def _load_status_session_cls():
helper = Path('/usr/local/sbin/platina-status-screen')
if not helper.exists():
return None
mod = runpy.run_path(str(helper), run_name='status_screen')
return mod.get('StatusDisplaySession')
def set_cpu_standby(mode, cpufreq_root=Path('/sys/devices/system/cpu/cpufreq')):
"""Clamp or restore per-cluster scaling_max_freq without using kernel s2idle."""
if mode not in ('active', 'standby', 'charger'):
raise ValueError('Unsupported CPU standby mode: ' + str(mode))
root = Path(cpufreq_root)
applied = {}
if not root.exists():
return applied
for policy in sorted(root.glob('policy*')):
max_txt = _read_text(policy / 'cpuinfo_max_freq')
min_txt = _read_text(policy / 'scaling_min_freq')
if not max_txt or not min_txt:
continue
try:
cpu_max = int(max_txt)
cpu_min = int(min_txt)
except ValueError:
continue
if mode == 'active':
target = cpu_max
elif mode == 'charger':
target = cpu_min
else:
if cpu_max >= 2_000_000:
target = cpu_min
else:
avail_raw = _read_text(policy / 'scaling_available_frequencies')
freqs = []
if avail_raw:
for tok in avail_raw.split():
try:
freqs.append(int(tok))
except ValueError:
pass
under_cap = [f for f in freqs if f <= 633600]
if under_cap:
target = max(under_cap)
elif freqs:
target = min(freqs)
else:
target = min(cpu_max, max(cpu_min, 633600))
try:
(policy / 'scaling_max_freq').write_text(str(target) + '\n')
applied[policy.name] = target
except OSError:
continue
return applied
def _select_timeout(now, policy, screen_on, screen_opened_at, last_refresh,
screen_dur, charger_mode, idle_suspend_seconds,
last_activity, standby_active):
wait = 30.0
if (KEY_POWER in policy.pressed and not policy.blocked and not policy.long_fired
and policy.power_started is not None):
wait = min(wait, max(0.02, policy.power_started + policy.hold_seconds - now))
if screen_on:
wait = min(wait, max(0.05, min(last_refresh + 2.0, screen_opened_at + screen_dur) - now))
if charger_mode:
wait = min(wait, 1.0)
elif not screen_on and not standby_active and idle_suspend_seconds > 0:
target = last_activity + idle_suspend_seconds
wait = min(wait, max(0.2, min(10.0, target - now)))
return max(0.02, wait)
def _open_inputs():
descriptors = {}
try:
for key, device in find_devices().items():
fd = os.open(device, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
@@ -114,36 +319,207 @@ def monitor(seconds, dry_run):
raise ValueError('Input identity changed')
fcntl.ioctl(fd, 0x400445A0, struct.pack('i', 1)) # Monotonic timestamps.
fcntl.ioctl(fd, 0x40044590, 1) # EVIOCGRAB; no console actions.
def held():
return {key for fd, key in descriptors.items() if key_held(fd, key)}
policy = ChordPolicy(seconds, held())
log(('TEST ONLY' if dry_run else 'ACTIVE') + f'; hold both >= {seconds:g}s; release BOTH to power off')
except BaseException:
for fd in descriptors:
os.close(fd)
raise
return descriptors
def monitor(seconds, dry_run, power_key_mode=False, screen_seconds=12.0, idle_suspend_seconds=60.0):
if os.geteuid() != 0:
raise ValueError('Run on the phone as root')
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('This service requires Platina')
descriptors = _open_inputs()
dropped = set()
session_cls = _load_status_session_cls() if power_key_mode else None
display_session = None
screen_on = False
screen_opened_at = 0.0
last_refresh = 0.0
charger_mode = is_boot_charger_mode() if power_key_mode else False
standby_active = False
if charger_mode and not dry_run:
set_cpu_standby('charger')
standby_active = True
prev_online = is_external_power_online()
last_activity = time.monotonic()
def held():
return {key for fd, key in descriptors.items() if key_held(fd, key)}
def close_screen(reason=None):
nonlocal display_session, screen_on, last_activity
if display_session is not None:
try:
display_session.close()
except OSError as exc:
log(f'display close error: {exc}')
display_session = None
if screen_on and reason:
log(reason)
screen_on = False
last_activity = time.monotonic()
def open_screen(mode):
nonlocal display_session, screen_on, screen_opened_at, last_refresh, last_activity, standby_active
if session_cls is None:
log('status screen helper missing; cannot illuminate display')
return False
if not charger_mode and standby_active:
set_cpu_standby('active')
standby_active = False
if display_session is not None:
return True
try:
sess = session_cls(brightness=25, mode=mode)
sess.open()
display_session = sess
screen_on = True
now_t = time.monotonic()
screen_opened_at = now_t
last_refresh = now_t
last_activity = now_t
return True
except OSError as exc:
log(f'display open skipped ({exc})')
return False
def handle_action(action):
nonlocal charger_mode, prev_online, standby_active
if action == 'poweroff':
log('complete chord accepted')
dispatch(dry_run)
elif action == 'toggle_screen':
if screen_on:
close_screen('toggle_screen -> OFF')
else:
mode = 'charger' if charger_mode else 'status'
if open_screen(mode):
log(f'toggle_screen -> ON ({mode})')
elif action == 'long_power':
close_screen()
if charger_mode:
log('long Power in charger mode -> booting normal cellular/server')
charger_mode = False
if not dry_run:
set_cpu_standby('active')
standby_active = False
if Path('/usr/local/sbin/platina-cellular').exists():
subprocess.Popen(['/usr/local/sbin/platina-cellular', '--auto'], start_new_session=True)
open_screen('status')
elif is_external_power_online():
log('long Power with external power -> entering offline charger mode')
charger_mode = True
prev_online = True
if not dry_run:
set_cpu_standby('charger')
standby_active = True
if Path('/usr/local/sbin/platina-cellular').exists():
subprocess.Popen(['/usr/local/sbin/platina-cellular', '--down'], start_new_session=True)
open_screen('charger')
else:
log('long Power on battery -> shutting down')
if dry_run:
log('TEST ONLY: long Power accepted; would show Power off and shut down')
else:
set_cpu_standby('active')
standby_active = False
child = subprocess.Popen(['/usr/local/sbin/platina-poweroff', '--force'],
start_new_session=True)
code = child.wait()
if code:
raise RuntimeError('Shutdown helper failed; exit ' + str(code))
try:
policy = (PowerButtonPolicy(seconds, held=held())
if power_key_mode else ChordPolicy(seconds, held()))
log(('TEST ONLY' if dry_run else 'ACTIVE')
+ f'; power_key_mode={power_key_mode}; hold>={seconds:g}s; charger_mode={charger_mode}')
while True:
ready, _, _ = select.select(list(descriptors), [], [])
screen_dur = 5.0 if charger_mode else float(screen_seconds)
timeout = (_select_timeout(time.monotonic(), policy, screen_on, screen_opened_at,
last_refresh, screen_dur, charger_mode,
idle_suspend_seconds, last_activity, standby_active)
if power_key_mode else None)
try:
ready, _, _ = select.select(list(descriptors), [], [], timeout)
except InterruptedError:
continue
events = []
for fd in ready:
data = os.read(fd, EVENT.size * 64)
try:
data = os.read(fd, EVENT.size * 64)
except BlockingIOError:
continue
if not data or len(data) % EVENT.size:
raise ValueError('Disconnected or truncated input')
for offset in range(0, len(data), EVENT.size):
sec, usec, typ, code, value = EVENT.unpack_from(data, offset)
events.append((sec + usec / 1e6, fd, typ, code, value))
for timestamp, fd, typ, code, value in sorted(events):
if typ == 0 and code == 3: # SYN_DROPPED: cancel both keys.
if typ == 0 and code == 3: # SYN_DROPPED: cancel pending keys.
dropped.add(fd)
policy.resync(KEYS)
log('lost input events; pending chord cancelled')
log('lost input events; pending gesture cancelled')
elif typ == 0 and code == 0 and fd in dropped:
dropped.remove(fd)
policy.resync(held())
elif typ == 1 and code == descriptors[fd] and not dropped:
action = policy.event(code, value, timestamp)
if value in (0, 1):
last_activity = time.monotonic()
log(DEVICES[code] + (' pressed' if value else ' released'))
action = policy.event(code, value, timestamp)
if action:
log('complete chord accepted')
dispatch(dry_run)
handle_action(action)
if not power_key_mode:
continue
now = time.monotonic()
timeout_action = policy.check_timeout(now)
if timeout_action:
handle_action(timeout_action)
if charger_mode:
online_now = is_external_power_online()
if prev_online and not online_now:
close_screen()
log('charger unplugged in charger mode -> powering off')
if not dry_run:
subprocess.run(['/usr/sbin/poweroff'], check=True, timeout=10)
time.sleep(30)
raise RuntimeError('Poweroff did not finish within 30s')
prev_online = online_now
now = time.monotonic()
if screen_on:
dur = 5.0 if charger_mode else float(screen_seconds)
if now >= screen_opened_at + dur:
close_screen('screen auto-off')
elif now >= last_refresh + 2.0 and display_session is not None:
try:
display_session.refresh(mode='charger' if charger_mode else 'status')
except OSError as exc:
log(f'display refresh error: {exc}')
close_screen()
last_refresh = time.monotonic()
elif (not charger_mode and not screen_on and not standby_active
and idle_suspend_seconds > 0
and now - last_activity >= idle_suspend_seconds
and not Path('/run/platina-inhibit-suspend').exists()):
if not dry_run:
set_cpu_standby('standby')
standby_active = True
log('entered low-power DVFS standby (big=300MHz, little=633MHz, panel=off)')
finally:
close_screen()
if power_key_mode and not dry_run:
set_cpu_standby('active')
for fd in descriptors:
os.close(fd)
@@ -151,11 +527,18 @@ def monitor(seconds, dry_run):
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--hold-seconds', type=float, default=3)
parser.add_argument('--power-key-mode', action='store_true',
help='Enable single Power button screen toggle, hold shutdown/charger, and DVFS standby')
parser.add_argument('--screen-seconds', type=float, default=12)
parser.add_argument('--idle-suspend-seconds', type=float, default=60)
parser.add_argument('--dry-run', action='store_true')
args = parser.parse_args()
ChordPolicy(args.hold_seconds)
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
monitor(args.hold_seconds, args.dry_run)
monitor(args.hold_seconds, args.dry_run,
power_key_mode=args.power_key_mode,
screen_seconds=args.screen_seconds,
idle_suspend_seconds=args.idle_suspend_seconds)
if __name__ == '__main__':
+11 -15
View File
@@ -28,21 +28,17 @@ def is_charger_connected():
return False
def enter_charger_standby():
print('platina-poweroff: external power connected; entering low-power suspend standby', flush=True)
state_file = Path('/sys/power/state')
if state_file.exists():
for mode in ('mem', 'freeze'):
try:
state_file.write_text(mode + '\n')
print(f'platina-poweroff: woke from {mode} standby', flush=True)
return
except OSError:
continue
try:
subprocess.run(['pm-suspend'], check=True, timeout=10)
except (OSError, subprocess.SubprocessError):
pass
def enter_charger_standby(cpufreq_root=Path('/sys/devices/system/cpu/cpufreq')):
print('platina-poweroff: external power connected; applied low-power charger standby', flush=True)
root = Path(cpufreq_root)
if not root.exists():
return
for policy in sorted(root.glob('policy*')):
try:
min_freq = (policy / 'scaling_min_freq').read_text().strip()
(policy / 'scaling_max_freq').write_text(min_freq + '\n')
except OSError:
continue
def request_shutdown(force=False, standby=False):
+701
View File
@@ -0,0 +1,701 @@
#!/usr/bin/env python3
"""Render live system status or offline charger screen onto Platina /dev/fb0 (stdlib only)."""
import argparse
import fcntl
import json
import mmap
import os
from pathlib import Path
import signal
import struct
import subprocess
import sys
import time
BACKLIGHT = Path('/sys/class/backlight/backlight')
DRIVER = Path('/sys/bus/mipi-dsi/devices/c994000.dsi.0/driver')
PANEL = b'xiaomi,platina-tianma-nt36672a'
SPLASH_LOCK = Path('/run/platina-splash.lock')
FBIOBLANK = 0x4611
# BGRX8888 4-byte pixel helpers (little-endian: B, G, R, X=0)
def bgrx(r, g, b):
return bytes((b & 0xff, g & 0xff, r & 0xff, 0))
COL_BG = bgrx(6, 10, 14)
COL_CARD = bgrx(14, 21, 28)
COL_BORDER = bgrx(36, 53, 66)
COL_TEXT = bgrx(226, 236, 244)
COL_MUTED = bgrx(138, 160, 178)
COL_ACCENT = bgrx(64, 184, 248)
COL_GREEN = bgrx(56, 208, 128)
COL_AMBER = bgrx(248, 184, 48)
COL_RED = bgrx(240, 82, 82)
COL_BAR_BG = bgrx(24, 34, 44)
# Crisp 8x8 bitmap font for printable ASCII (0x20..0x7E); bit 7 is leftmost pixel.
FONT_8X8 = {
' ': (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
'!': (0x18, 0x3c, 0x3c, 0x18, 0x18, 0x00, 0x18, 0x00),
'"': (0x6c, 0x6c, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00),
'#': (0x36, 0x36, 0x7f, 0x36, 0x7f, 0x36, 0x36, 0x00),
'$': (0x18, 0x3e, 0x60, 0x3c, 0x06, 0x7c, 0x18, 0x00),
'%': (0x62, 0x64, 0x08, 0x10, 0x26, 0x46, 0x00, 0x00),
'&': (0x38, 0x44, 0x38, 0x74, 0x4c, 0x44, 0x3a, 0x00),
"'": (0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00),
'(': (0x0c, 0x18, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x00),
')': (0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x18, 0x30, 0x00),
'*': (0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00),
'+': (0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00),
',': (0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30),
'-': (0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00),
'.': (0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00),
'/': (0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00),
'0': (0x3c, 0x66, 0x6e, 0x76, 0x66, 0x66, 0x3c, 0x00),
'1': (0x18, 0x38, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x00),
'2': (0x3c, 0x66, 0x06, 0x1c, 0x30, 0x60, 0x7e, 0x00),
'3': (0x3c, 0x66, 0x06, 0x1c, 0x06, 0x66, 0x3c, 0x00),
'4': (0x0c, 0x1c, 0x3c, 0x6c, 0x7e, 0x0c, 0x0c, 0x00),
'5': (0x7e, 0x60, 0x7c, 0x06, 0x06, 0x66, 0x3c, 0x00),
'6': (0x3c, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x3c, 0x00),
'7': (0x7e, 0x66, 0x06, 0x0c, 0x18, 0x18, 0x18, 0x00),
'8': (0x3c, 0x66, 0x66, 0x3c, 0x66, 0x66, 0x3c, 0x00),
'9': (0x3c, 0x66, 0x66, 0x3e, 0x06, 0x0c, 0x38, 0x00),
':': (0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00),
';': (0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x30, 0x00),
'<': (0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x00),
'=': (0x00, 0x00, 0x7e, 0x00, 0x7e, 0x00, 0x00, 0x00),
'>': (0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x00),
'?': (0x3c, 0x66, 0x06, 0x0c, 0x18, 0x00, 0x18, 0x00),
'@': (0x3c, 0x66, 0x6e, 0x6e, 0x60, 0x62, 0x3c, 0x00),
'A': (0x18, 0x3c, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x00),
'B': (0x7c, 0x66, 0x66, 0x7c, 0x66, 0x66, 0x7c, 0x00),
'C': (0x3c, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3c, 0x00),
'D': (0x78, 0x6c, 0x66, 0x66, 0x66, 0x6c, 0x78, 0x00),
'E': (0x7e, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x7e, 0x00),
'F': (0x7e, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x60, 0x00),
'G': (0x3c, 0x66, 0x60, 0x6e, 0x66, 0x66, 0x3e, 0x00),
'H': (0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66, 0x00),
'I': (0x3c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00),
'J': (0x1e, 0x0c, 0x0c, 0x0c, 0x6c, 0x6c, 0x38, 0x00),
'K': (0x66, 0x6c, 0x78, 0x70, 0x78, 0x6c, 0x66, 0x00),
'L': (0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7e, 0x00),
'M': (0x63, 0x77, 0x7f, 0x6b, 0x63, 0x63, 0x63, 0x00),
'N': (0x66, 0x76, 0x7e, 0x7e, 0x6e, 0x66, 0x66, 0x00),
'O': (0x3c, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00),
'P': (0x7c, 0x66, 0x66, 0x7c, 0x60, 0x60, 0x60, 0x00),
'Q': (0x3c, 0x66, 0x66, 0x66, 0x6a, 0x6c, 0x36, 0x00),
'R': (0x7c, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0x66, 0x00),
'S': (0x3c, 0x66, 0x60, 0x3c, 0x06, 0x66, 0x3c, 0x00),
'T': (0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00),
'U': (0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00),
'V': (0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x00),
'W': (0x63, 0x63, 0x63, 0x6b, 0x7f, 0x77, 0x63, 0x00),
'X': (0x66, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0x66, 0x00),
'Y': (0x66, 0x66, 0x66, 0x3c, 0x18, 0x18, 0x18, 0x00),
'Z': (0x7e, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x7e, 0x00),
'[': (0x3c, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3c, 0x00),
'\\': (0x80, 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x00),
']': (0x3c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x3c, 0x00),
'^': (0x18, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00),
'_': (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x00),
'`': (0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00),
'a': (0x00, 0x00, 0x3c, 0x06, 0x3e, 0x66, 0x3e, 0x00),
'b': (0x60, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x7c, 0x00),
'c': (0x00, 0x00, 0x3c, 0x66, 0x60, 0x66, 0x3c, 0x00),
'd': (0x06, 0x06, 0x3e, 0x66, 0x66, 0x66, 0x3e, 0x00),
'e': (0x00, 0x00, 0x3c, 0x66, 0x7e, 0x60, 0x3c, 0x00),
'f': (0x1c, 0x30, 0x7c, 0x30, 0x30, 0x30, 0x30, 0x00),
'g': (0x00, 0x00, 0x3e, 0x66, 0x66, 0x3e, 0x06, 0x3c),
'h': (0x60, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x66, 0x00),
'i': (0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00),
'j': (0x0c, 0x00, 0x1c, 0x0c, 0x0c, 0x6c, 0x6c, 0x38),
'k': (0x60, 0x60, 0x66, 0x6c, 0x78, 0x6c, 0x66, 0x00),
'l': (0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00),
'm': (0x00, 0x00, 0x66, 0x7f, 0x7f, 0x6b, 0x63, 0x00),
'n': (0x00, 0x00, 0x7c, 0x66, 0x66, 0x66, 0x66, 0x00),
'o': (0x00, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x3c, 0x00),
'p': (0x00, 0x00, 0x7c, 0x66, 0x66, 0x7c, 0x60, 0x60),
'q': (0x00, 0x00, 0x3e, 0x66, 0x66, 0x3e, 0x06, 0x06),
'r': (0x00, 0x00, 0x6c, 0x76, 0x60, 0x60, 0x60, 0x00),
's': (0x00, 0x00, 0x3e, 0x60, 0x3c, 0x06, 0x7c, 0x00),
't': (0x30, 0x30, 0x7c, 0x30, 0x30, 0x34, 0x18, 0x00),
'u': (0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3e, 0x00),
'v': (0x00, 0x00, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x00),
'w': (0x00, 0x00, 0x63, 0x6b, 0x7f, 0x7f, 0x36, 0x00),
'x': (0x00, 0x00, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0x00),
'y': (0x00, 0x00, 0x66, 0x66, 0x66, 0x3e, 0x06, 0x3c),
'z': (0x00, 0x00, 0x7e, 0x0c, 0x18, 0x30, 0x7e, 0x00),
'{': (0x0e, 0x18, 0x18, 0x70, 0x18, 0x18, 0x0e, 0x00),
'|': (0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00),
'}': (0x70, 0x18, 0x18, 0x0e, 0x18, 0x18, 0x70, 0x00),
'~': (0x3b, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
}
_GLYPH_CACHE = {}
def _read_text(path):
try:
return Path(path).read_text().strip()
except OSError:
return None
def _read_int(path):
text = _read_text(path)
if text is None:
return None
try:
return int(text)
except ValueError:
return None
def _parse_active_bracket(raw):
if not raw:
return None
start = raw.find('[')
end = raw.find(']', start + 1)
if start != -1 and end != -1:
return raw[start + 1:end]
return raw.split()[0] if raw.split() else None
def _format_uptime(seconds):
total = int(seconds)
days, rem = divmod(total, 86400)
hours, rem = divmod(rem, 3600)
minutes, secs = divmod(rem, 60)
if days:
return f'{days}d {hours:02d}h {minutes:02d}m'
return f'{hours:02d}h {minutes:02d}m {secs:02d}s'
def collect_telemetry(sys_path='/sys', proc_path='/proc', run=subprocess.run):
"""Collect power, battery, cellular, network, and host load telemetry safely."""
sys_root = Path(sys_path)
proc_root = Path(proc_path)
uptime_raw = _read_text(proc_root / 'uptime')
uptime_s = 0.0
if uptime_raw:
try:
uptime_s = float(uptime_raw.split()[0])
except ValueError:
pass
load_raw = _read_text(proc_root / 'loadavg')
load_avg = ' '.join(load_raw.split()[:3]) if load_raw else 'n/a'
mem_total_kb = mem_avail_kb = None
mem_raw = _read_text(proc_root / 'meminfo')
if mem_raw:
for line in mem_raw.splitlines():
if line.startswith('MemTotal:'):
mem_total_kb = int(line.split()[1])
elif line.startswith('MemAvailable:'):
mem_avail_kb = int(line.split()[1])
mem_total_mb = (mem_total_kb // 1024) if mem_total_kb else None
mem_used_mb = ((mem_total_kb - mem_avail_kb) // 1024) if (mem_total_kb and mem_avail_kb is not None) else None
bat_dir = sys_root / 'class/power_supply/qcom-battery'
chg_dir = sys_root / 'class/power_supply/pm660-charger'
cap = _read_int(bat_dir / 'capacity')
bat_status = _read_text(bat_dir / 'status') or 'Unknown'
volt_uv = _read_int(bat_dir / 'voltage_now')
temp_deci = _read_int(bat_dir / 'temp')
chg_online = _read_text(chg_dir / 'online') == '1'
usb_type = _parse_active_bracket(_read_text(chg_dir / 'usb_type'))
charge_behaviour = _parse_active_bracket(_read_text(chg_dir / 'charge_behaviour'))
inhibited = charge_behaviour == 'inhibit-charge'
if inhibited and chg_online:
power_state = 'Paused (80% Guard)'
elif chg_online:
power_state = bat_status
else:
power_state = 'Discharging'
ipa_ready = _read_text(sys_root / 'devices/platform/soc@0/147c0000.ipa/modem/datapath_ready') == '1'
usb0_carrier = _read_text(sys_root / 'class/net/usb0/carrier') == '1'
cpu_max_mhz = []
cpufreq_dir = sys_root / 'devices/system/cpu/cpufreq'
if cpufreq_dir.exists():
for policy in sorted(cpufreq_dir.glob('policy*')):
freq_khz = _read_int(policy / 'scaling_max_freq')
if freq_khz:
cpu_max_mhz.append(freq_khz // 1000)
default_dev = None
iface_ips = {}
try:
r_def = run(['ip', '-4', 'route', 'show', 'default'],
capture_output=True, text=True, timeout=0.8)
if r_def.returncode == 0 and r_def.stdout.strip():
parts = r_def.stdout.splitlines()[0].split()
if 'dev' in parts:
default_dev = parts[parts.index('dev') + 1]
except (OSError, subprocess.SubprocessError):
pass
try:
r_addr = run(['ip', '-4', '-o', 'addr', 'show'],
capture_output=True, text=True, timeout=0.8)
if r_addr.returncode == 0:
for line in r_addr.stdout.splitlines():
cols = line.split()
if len(cols) >= 4 and cols[2] == 'inet':
iface_ips[cols[1]] = cols[3].split('/')[0]
except (OSError, subprocess.SubprocessError):
pass
cell_state = 'unregistered'
cell_operator = None
cell_tech = None
cell_signal = None
try:
r_mm = run(['mmcli', '-m', 'any', '-K'],
capture_output=True, text=True, timeout=0.8)
if r_mm.returncode == 0:
for line in r_mm.stdout.splitlines():
if ':' not in line:
continue
k, v = [p.strip() for p in line.split(':', 1)]
if v in ('--', ''):
continue
if k == 'modem.generic.state':
cell_state = v
elif k == 'modem.3gpp.operator-name':
cell_operator = v
elif k == 'modem.generic.access-technologies.value[1]':
cell_tech = v
elif k == 'modem.generic.signal-quality.value':
try:
cell_signal = int(v)
except ValueError:
pass
except (OSError, subprocess.SubprocessError):
pass
return {
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
'clock': time.strftime('%H:%M:%S'),
'date': time.strftime('%Y-%m-%d'),
'uptime_s': round(uptime_s, 1),
'uptime_str': _format_uptime(uptime_s),
'load_avg': load_avg,
'mem_used_mb': mem_used_mb,
'mem_total_mb': mem_total_mb,
'cpu_max_mhz': cpu_max_mhz,
'battery': {
'capacity': cap,
'status': bat_status,
'power_state': power_state,
'voltage_v': round(volt_uv / 1e6, 2) if volt_uv is not None else None,
'temp_c': round(temp_deci / 10.0, 1) if temp_deci is not None else None,
'charger_online': chg_online,
'usb_type': usb_type,
'inhibited': inhibited,
},
'cellular': {
'datapath_ready': ipa_ready,
'state': cell_state,
'operator': cell_operator,
'access_tech': cell_tech,
'signal_percent': cell_signal,
'ip': iface_ips.get('qmapmux0.0'),
'is_default': default_dev == 'qmapmux0.0',
},
'network': {
'default_dev': default_dev,
'wlan0_ip': iface_ips.get('wlan0'),
'usb0_ip': iface_ips.get('usb0'),
'usb0_carrier': usb0_carrier,
'tun0_ip': iface_ips.get('tun0'),
},
}
def _glyph_rows(ch, scale, fg_px, bg_px):
key = (ch, scale, fg_px, bg_px)
cached = _GLYPH_CACHE.get(key)
if cached is not None:
return cached
bits = FONT_8X8.get(ch, FONT_8X8[' '])
rows = []
for row_mask in bits:
row_bytes = bytearray()
for col in range(8):
px = fg_px if (row_mask & (0x80 >> col)) else bg_px
row_bytes.extend(px * scale)
immutable = bytes(row_bytes)
for _ in range(scale):
rows.append(immutable)
if len(_GLYPH_CACHE) > 2048:
_GLYPH_CACHE.clear()
_GLYPH_CACHE[key] = rows
return rows
def fill_rect(buf, width, height, x, y, w, h, color_px):
x0 = max(0, x)
y0 = max(0, y)
x1 = min(width, x + w)
y1 = min(height, y + h)
if x0 >= x1 or y0 >= y1:
return
row_bytes = color_px * (x1 - x0)
span = len(row_bytes)
stride = width * 4
for row in range(y0, y1):
start = row * stride + x0 * 4
buf[start:start + span] = row_bytes
def draw_rect_border(buf, width, height, x, y, w, h, border_px, thickness=2):
fill_rect(buf, width, height, x, y, w, thickness, border_px)
fill_rect(buf, width, height, x, y + h - thickness, w, thickness, border_px)
fill_rect(buf, width, height, x, y, thickness, h, border_px)
fill_rect(buf, width, height, x + w - thickness, y, thickness, h, border_px)
def draw_text(buf, width, height, x, y, text, scale=3, fg_px=COL_TEXT, bg_px=COL_CARD):
advance = 8 * scale
glyph_w = 8 * scale
stride = width * 4
cur_x = x
for raw_ch in str(text):
ch = raw_ch if raw_ch in FONT_8X8 else '?'
if cur_x + glyph_w > width:
break
if cur_x >= 0 and y >= 0 and y + glyph_w <= height:
rows = _glyph_rows(ch, scale, fg_px, bg_px)
for dy, row_bytes in enumerate(rows):
start = (y + dy) * stride + cur_x * 4
buf[start:start + len(row_bytes)] = row_bytes
cur_x += advance
def draw_progress_bar(buf, width, height, x, y, w, h, percent, fill_px, bg_px=COL_BAR_BG, border_px=COL_BORDER):
fill_rect(buf, width, height, x, y, w, h, bg_px)
draw_rect_border(buf, width, height, x, y, w, h, border_px, thickness=2)
pct = max(0, min(100, int(percent or 0)))
inner_w = max(0, (w - 8) * pct // 100)
if inner_w > 0:
fill_rect(buf, width, height, x + 4, y + 4, inner_w, h - 8, fill_px)
def draw_signal_bars(buf, width, height, x, y, percent):
filled = 0 if percent is None else max(1, min(4, (percent + 24) // 25))
bar_heights = (14, 22, 30, 38)
for idx, bh in enumerate(bar_heights):
bx = x + idx * 14
by = y + 38 - bh
color = COL_GREEN if idx < filled else COL_BAR_BG
fill_rect(buf, width, height, bx, by, 10, bh, color)
def render_dashboard_bgrx(telemetry, mode='status', width=1080, height=2280):
"""Render telemetry into a BGRX8888 bytearray matching 1080x2280 display."""
buf = bytearray(COL_BG * (width * height))
bat = telemetry['battery']
cap = bat.get('capacity')
volt = bat.get('voltage_v')
temp = bat.get('temp_c')
volt_str = f'{volt:.2f}V' if volt is not None else 'n/a'
temp_str = f'{temp:.1f}C' if temp is not None else 'n/a'
cap_str = f'{cap}%' if cap is not None else '--%'
bat_color = COL_GREEN if (cap or 0) >= 35 else (COL_AMBER if (cap or 0) >= 15 else COL_RED)
if mode == 'charger':
draw_text(buf, width, height, 72, 110, 'PLATINA LINUX CHARGER', scale=4, fg_px=COL_ACCENT, bg_px=COL_BG)
draw_text(buf, width, height, 72, 175, f"{telemetry['date']} {telemetry['clock']}", scale=3, fg_px=COL_MUTED, bg_px=COL_BG)
# Centered battery icon + fill
bx, by, bw, bh = 310, 480, 460, 740
fill_rect(buf, width, height, bx + 150, by - 46, 160, 46, COL_BORDER)
fill_rect(buf, width, height, bx, by, bw, bh, COL_CARD)
draw_rect_border(buf, width, height, bx, by, bw, bh, COL_BORDER, thickness=8)
pct = max(0, min(100, int(cap or 0)))
fill_h = (bh - 32) * pct // 100
if fill_h > 0:
fill_rect(buf, width, height, bx + 16, by + bh - 16 - fill_h, bw - 32, fill_h, bat_color)
draw_text(buf, width, height, 340, 1290, cap_str.center(5), scale=10, fg_px=COL_TEXT, bg_px=COL_BG)
state_lbl = 'PAUSED AT 80% GUARD' if bat.get('inhibited') else ('CHARGING' if bat.get('charger_online') else 'DISCHARGING')
draw_text(buf, width, height, 180, 1430, state_lbl, scale=4, fg_px=bat_color, bg_px=COL_BG)
draw_text(buf, width, height, 180, 1510, f"VOLTAGE: {volt_str} TEMP: {temp_str}", scale=4, fg_px=COL_MUTED, bg_px=COL_BG)
draw_text(buf, width, height, 180, 1575, f"SUPPLY: {bat.get('usb_type') or 'USB'}", scale=3, fg_px=COL_MUTED, bg_px=COL_BG)
fill_rect(buf, width, height, 60, 2060, 960, 110, COL_CARD)
draw_rect_border(buf, width, height, 60, 2060, 960, 110, COL_BORDER, thickness=2)
draw_text(buf, width, height, 100, 2085, 'TAP POWER: SLEEP SCREEN', scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 100, 2125, 'HOLD POWER 3S: BOOT LINUX | UNPLUG: OFF', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
return buf
# Header card
draw_text(buf, width, height, 68, 90, telemetry['clock'], scale=8, fg_px=COL_TEXT, bg_px=COL_BG)
draw_text(buf, width, height, 68, 175, f"{telemetry['date']} UP {telemetry['uptime_str']}", scale=3, fg_px=COL_MUTED, bg_px=COL_BG)
draw_text(buf, width, height, 68, 222, 'PLATINA LINUX SERVER', scale=3, fg_px=COL_ACCENT, bg_px=COL_BG)
def card(cy, ch, title):
fill_rect(buf, width, height, 60, cy, 960, ch, COL_CARD)
draw_rect_border(buf, width, height, 60, cy, 960, ch, COL_BORDER, thickness=2)
draw_text(buf, width, height, 92, cy + 26, title, scale=3, fg_px=COL_ACCENT, bg_px=COL_CARD)
# Card 1: Battery & Power
card(310, 340, 'BATTERY & POWER')
draw_text(buf, width, height, 92, 382, cap_str, scale=7, fg_px=bat_color, bg_px=COL_CARD)
draw_text(buf, width, height, 340, 392, bat['power_state'], scale=4, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 340, 442, f"{volt_str} {temp_str} {bat.get('usb_type') or 'BATT'}", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_progress_bar(buf, width, height, 92, 515, 896, 44, cap or 0, bat_color)
draw_text(buf, width, height, 92, 585, 'GUARD: 50-80% SOC | 45C CUTOFF | 5% OFF', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
# Card 2: Cellular 4G
cell = telemetry['cellular']
card(690, 370, 'CELLULAR 4G (IPA V2.6L)')
draw_signal_bars(buf, width, height, 92, 760, cell.get('signal_percent'))
op = (cell.get('operator') or 'NO CARRIER')[:16]
tech = (cell.get('access_tech') or '--').upper()
sig_str = f"{cell['signal_percent']}%" if cell.get('signal_percent') is not None else '--%'
draw_text(buf, width, height, 175, 762, f"{op} {tech} {sig_str}", scale=4, fg_px=COL_TEXT, bg_px=COL_CARD)
def_tag = ' [DEFAULT]' if cell.get('is_default') else ''
draw_text(buf, width, height, 92, 845, f"STATE : {cell['state']}{def_tag}", scale=3, fg_px=COL_GREEN if cell.get('is_default') else COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 895, f"IPv4 : {cell.get('ip') or 'none'} (metric 700)", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 945, f"IPA : {'datapath ready' if cell.get('datapath_ready') else 'offline'}", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
# Card 3: Network & Mesh
net = telemetry['network']
card(1100, 380, 'NETWORK & MESH ROUTING')
draw_text(buf, width, height, 92, 1175, f"DEFAULT : {net.get('default_dev') or 'none'}", scale=4, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1245, f"WI-FI : {net.get('wlan0_ip') or 'disconnected'} (m 600)", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1295, f"USB NCM : {net.get('usb0_ip') or 'down'} ({'link' if net.get('usb0_carrier') else 'unplugged'})", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1345, f"EASYTIER: {net.get('tun0_ip') or 'stopped'}", scale=3, fg_px=COL_GREEN if net.get('tun0_ip') else COL_MUTED, bg_px=COL_CARD)
# Card 4: Compute
card(1520, 270, 'SYSTEM RESOURCES')
ram_str = f"{telemetry['mem_used_mb']} / {telemetry['mem_total_mb']} MB" if telemetry.get('mem_total_mb') else 'n/a'
cpus = telemetry.get('cpu_max_mhz') or []
cpu_str = '/'.join(str(m) for m in cpus) + ' MHz' if cpus else 'n/a'
draw_text(buf, width, height, 92, 1600, f"CPU : {cpu_str} | LOAD {telemetry['load_avg']}", scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1655, f"RAM : {ram_str}", scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1710, 'MODE : LIGHTWEIGHT SERVER (DVFS/CPUIDLE)', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
# Footer controls
fill_rect(buf, width, height, 60, 2020, 960, 140, COL_CARD)
draw_rect_border(buf, width, height, 60, 2020, 960, 140, COL_BORDER, thickness=2)
draw_text(buf, width, height, 92, 2050, 'TAP POWER : SLEEP SCREEN (AUTO 12S)', scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 2098, 'HOLD 3S : SHUTDOWN / CHARGER MODE', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
return buf
def _validate_panel():
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('This command requires Platina')
if DRIVER.resolve(strict=True).name != 'panel-novatek-nt36672a':
raise ValueError('Integrated Tianma driver required')
compatible = (DRIVER.parent / 'of_node/compatible').read_bytes().split(b'\0')
if PANEL not in compatible:
raise ValueError('Unexpected panel variant')
if Path('/sys/module/platina_panel_dcs').exists():
raise ValueError('Temporary LCD module loaded; refusing display write')
def _fb_geometry(variable, fixed):
v = struct.unpack_from('=40I', variable)
memory = struct.unpack_from('=I', fixed, 24)[0]
stride = struct.unpack_from('=I', fixed, 48)[0]
width, height, virtual_width, virtual_height, xoff, yoff, bpp = v[:7]
if (width, height, bpp) != (1080, 2280, 32):
raise ValueError('Framebuffer resolution/pixel depth mismatch')
if xoff + width > virtual_width or yoff + height > virtual_height:
raise ValueError('Framebuffer viewport exceeds virtual dimensions')
if stride < (xoff + width) * 4 or not 0 < memory <= 64_000_000:
raise ValueError('Invalid framebuffer memory layout')
offset = yoff * stride + xoff * 4
if offset + (height - 1) * stride + width * 4 > memory:
raise ValueError('Framebuffer viewport exceeds mapped memory')
return width, height, stride, offset, memory
def _fb_paint(target, raw, layout):
width, height, stride, offset, _ = layout
row = width * 4
for y in range(height):
start = offset + y * stride
target[start:start + row] = raw[y * row:(y + 1) * row]
def _set_brightness(percent):
pct = max(0, min(100, int(percent)))
maximum = int((BACKLIGHT / 'max_brightness').read_text())
level = max(1, maximum * pct // 100) if pct else 0
(BACKLIGHT / 'brightness').write_text(str(level) + '\n')
class StatusDisplaySession:
"""Exclusive owner of /dev/fb0 while a temporary status/charger screen is illuminated."""
def __init__(self, brightness=25, mode='status'):
if os.geteuid() != 0:
raise ValueError('Run display changes on the phone as root')
_validate_panel()
self.brightness = brightness
self.mode = mode
self._lock_fh = None
self._fb = None
self._tty = None
self._prev_kd = None
self._mmap = None
self._layout = None
self._closed = True
def open(self, telemetry=None, mode=None):
if mode is not None:
self.mode = mode
lock_fh = SPLASH_LOCK.open('a')
try:
fcntl.flock(lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
fb = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
try:
var, fixed = bytearray(160), bytearray(80)
fcntl.ioctl(fb, 0x4600, var, True)
fcntl.ioctl(fb, 0x4602, fixed, True)
layout = _fb_geometry(var, fixed)
tty = os.open('/dev/tty0', os.O_RDWR | os.O_CLOEXEC)
kd = bytearray(4)
fcntl.ioctl(tty, 0x4B3B, kd, True)
prev_kd = struct.unpack('=i', kd)[0]
fcntl.ioctl(tty, 0x4B3A, 1) # KD_GRAPHICS
screen = mmap.mmap(fb, layout[4], access=mmap.ACCESS_WRITE)
except BaseException:
os.close(fb)
raise
except BaseException:
lock_fh.close()
raise
self._lock_fh = lock_fh
self._fb = fb
self._tty = tty
self._prev_kd = prev_kd
self._mmap = screen
self._layout = layout
self._closed = False
try:
_set_brightness(0)
self.refresh(telemetry=telemetry, mode=self.mode)
fcntl.ioctl(fb, FBIOBLANK, 0)
(BACKLIGHT / 'bl_power').write_text('0\n')
_set_brightness(self.brightness)
except BaseException:
self.close()
raise
def refresh(self, telemetry=None, mode=None):
if self._closed:
return
active_mode = mode or self.mode
data = telemetry or collect_telemetry()
raw = render_dashboard_bgrx(data, mode=active_mode,
width=self._layout[0], height=self._layout[1])
_fb_paint(self._mmap, raw, self._layout)
def close(self):
if self._closed and self._fb is None and self._lock_fh is None:
return
self._closed = True
try:
try:
_set_brightness(0)
except OSError:
pass
if self._mmap is not None:
try:
self._mmap[:] = b'\0' * self._layout[4]
except OSError:
pass
try:
self._mmap.close()
except OSError:
pass
self._mmap = None
if self._tty is not None:
try:
if self._prev_kd is not None:
fcntl.ioctl(self._tty, 0x4B3A, self._prev_kd)
except OSError:
pass
try:
os.close(self._tty)
except OSError:
pass
self._tty = None
if self._fb is not None:
try:
fcntl.ioctl(self._fb, FBIOBLANK, 4) # FB_BLANK_POWERDOWN
except OSError:
pass
try:
os.close(self._fb)
except OSError:
pass
self._fb = None
try:
if _read_text('/sys/class/graphics/fb0/blank') != '4':
fb2 = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
try:
fcntl.ioctl(fb2, FBIOBLANK, 4)
finally:
os.close(fb2)
except OSError:
pass
finally:
if self._lock_fh is not None:
try:
self._lock_fh.close()
except OSError:
pass
self._lock_fh = None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--once', action='store_true', help='Display dashboard for --seconds then power off panel')
parser.add_argument('--mode', choices=('status', 'charger'), default='status')
parser.add_argument('--seconds', type=float, default=12.0)
parser.add_argument('--brightness', type=int, default=25)
parser.add_argument('--json', action='store_true', help='Print collected telemetry as JSON without touching display')
args = parser.parse_args()
if args.json:
print(json.dumps(collect_telemetry(), indent=2))
return 0
if not 0 < args.seconds <= 300:
parser.error('Choose --seconds between 0 and 300')
if not 1 <= args.brightness <= 100:
parser.error('Choose --brightness between 1 and 100')
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
session = StatusDisplaySession(brightness=args.brightness, mode=args.mode)
session.open()
try:
deadline = time.monotonic() + args.seconds
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
time.sleep(min(2.0, remaining))
if time.monotonic() < deadline:
session.refresh()
finally:
session.close()
return 0
if __name__ == '__main__':
raise SystemExit(main())
+3 -1
View File
@@ -144,7 +144,9 @@ def check():
raise ValueError('Profile version differs from recipe: ' + package)
if (ROOT / '.git').is_dir():
tracked = subprocess.check_output(['git', 'ls-files', '-z'], cwd=ROOT).decode().split('\0')
allowed = {str(p.relative_to(ROOT)) for p in candidates} | {'PLAN.md'}
release_files = ({str(p.relative_to(ROOT)) for p in (ROOT / 'release').rglob('*')
if p.is_file()} if (ROOT / 'release').is_dir() else set())
allowed = {str(p.relative_to(ROOT)) for p in candidates} | {'PLAN.md'} | release_files
if any(name and name not in allowed for name in tracked):
raise ValueError('Unexpected tracked path; review Git index')
run(['git', 'diff', '--check'])
+25 -20
View File
@@ -4,39 +4,44 @@
mkdir -p /sysroot/usr/local/sbin
cat << 'EOF' > /sysroot/usr/local/sbin/platina-usb-gadget
#!/bin/sh
# Platina USB gadget NCM bringup
# Platina USB gadget NCM bringup (preserves initramfs-bound g1 to avoid macOS NCM re-enumeration drops)
set -e
CONFIGFS=/sys/kernel/config/usb_gadget
# Mount configfs if not mounted
if ! mountpoint -q /sys/kernel/config; then
mount -t configfs none /sys/kernel/config 2>/dev/null || true
fi
mkdir -p $CONFIGFS/g1
echo "0x18D1" > $CONFIGFS/g1/idVendor
echo "0xD001" > $CONFIGFS/g1/idProduct
CURRENT_UDC=$(cat "$CONFIGFS/g1/UDC" 2>/dev/null || true)
if [ -z "$CURRENT_UDC" ]; then
mkdir -p "$CONFIGFS/g1"
echo "0x2717" > "$CONFIGFS/g1/idVendor"
echo "0xff80" > "$CONFIGFS/g1/idProduct"
mkdir -p $CONFIGFS/g1/strings/0x409
echo "Xiaomi" > $CONFIGFS/g1/strings/0x409/manufacturer
echo "postmarketOS" > $CONFIGFS/g1/strings/0x409/serialnumber
echo "Mi 8 Lite" > $CONFIGFS/g1/strings/0x409/product
mkdir -p "$CONFIGFS/g1/strings/0x409"
echo "Xiaomi" > "$CONFIGFS/g1/strings/0x409/manufacturer"
echo "63c36adb" > "$CONFIGFS/g1/strings/0x409/serialnumber"
echo "Xiaomi Mi 8 Lite" > "$CONFIGFS/g1/strings/0x409/product"
mkdir -p $CONFIGFS/g1/functions/ncm.usb0
mkdir -p $CONFIGFS/g1/configs/c.1/strings/0x409
echo "USB Network" > $CONFIGFS/g1/configs/c.1/strings/0x409/configuration
mkdir -p "$CONFIGFS/g1/functions/ncm.usb0"
echo "d2:d1:1e:20:5a:dc" > "$CONFIGFS/g1/functions/ncm.usb0/host_addr" 2>/dev/null || true
echo "0e:f1:f5:d7:ba:a9" > "$CONFIGFS/g1/functions/ncm.usb0/dev_addr" 2>/dev/null || true
if [ ! -L $CONFIGFS/g1/configs/c.1/ncm.usb0 ]; then
ln -s $CONFIGFS/g1/functions/ncm.usb0 $CONFIGFS/g1/configs/c.1/
fi
mkdir -p "$CONFIGFS/g1/configs/c.1/strings/0x409"
echo "USB Network" > "$CONFIGFS/g1/configs/c.1/strings/0x409/configuration"
UDC=$(ls /sys/class/udc | head -1)
if [ -n "$UDC" ]; then
CURRENT=$(cat $CONFIGFS/g1/UDC 2>/dev/null || true)
if [ "$CURRENT" != "$UDC" ]; then
echo "$UDC" > $CONFIGFS/g1/UDC
if [ ! -L "$CONFIGFS/g1/configs/c.1/ncm.usb0" ]; then
ln -s "$CONFIGFS/g1/functions/ncm.usb0" "$CONFIGFS/g1/configs/c.1/"
fi
UDC=$(ls /sys/class/udc | head -1)
if [ -n "$UDC" ]; then
echo "$UDC" > "$CONFIGFS/g1/UDC"
fi
fi
ip link set usb0 up 2>/dev/null || true
ip addr replace 172.16.42.1/24 dev usb0 2>/dev/null || true
EOF
chmod +x /sysroot/usr/local/sbin/platina-usb-gadget
+37
View File
@@ -0,0 +1,37 @@
/* SPDX-License-Identifier: GPL-2.0-only */
#include <assert.h>
#include <string.h>
#include "../project/cellular/ipa-v2/ipa_v2_cmd_format.h"
int main(void)
{
struct ipa_v2_shared_mem_cmd command;
struct ipa_v2_bam_desc descriptor;
const unsigned char command_bytes[] = {
0x00, 0x00, 0x40, 0x00, 0x40, 0x30, 0x20, 0x10,
0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned char descriptor_bytes[] = {
0xa0, 0x90, 0x80, 0x70, 0x13, 0x00, 0x00, 0x41,
};
assert(sizeof(command) == 16);
assert(sizeof(descriptor) == 8);
assert(!ipa_v2_shared_read_encode(&command, 0x10203040, 64, 0x80, 8192, 0));
assert(!memcmp(&command, command_bytes, sizeof(command_bytes)));
assert(!ipa_v2_shared_read_desc(&descriptor, 0x708090a0, sizeof(command)));
assert(!memcmp(&descriptor, descriptor_bytes, sizeof(descriptor_bytes)));
assert(ipa_v2_shared_read_desc(&descriptor, 0x708090a0, 19) == -ERANGE);
assert(ipa_v2_shared_read_desc(&descriptor, 0xfffffff8ULL, 16) == -ERANGE);
assert(ipa_v2_shared_read_encode(&command, 0x100000000ULL, 16, 0, 8192, 0) == -ERANGE);
assert(ipa_v2_shared_read_encode(&command, 0xfffffffcULL, 16, 0, 8192, 0) == -ERANGE);
assert(ipa_v2_shared_read_encode(&command, 0x1000, 0, 0, 8192, 0) == -ERANGE);
assert(ipa_v2_shared_read_encode(&command, 0x1000, 16, 8180, 8192, 0) == -ERANGE);
assert(ipa_v2_shared_read_encode(&command, 0x1000, 16, 0, 8192, 128) == -ERANGE);
assert(ipa_v2_shared_read_encode(&command, 0x1000, 16, 0x10000, 0x20000, 0) == -ERANGE);
assert(!ipa_v2_shared_read_encode(&command, 0xfffffff0ULL, 16, 8176, 8192, 0));
assert(ipa_v2_dma_range_valid(0xffffffffULL, 1));
assert(!ipa_v2_dma_range_valid(0xffffffffULL, 2));
assert(!ipa_v2_dma_range_valid(0, 0));
return 0;
}
+19
View File
@@ -0,0 +1,19 @@
"""Compile the actual command encoder and check its wire bytes and bounds."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
class BamCommandFormatTest(unittest.TestCase):
def test_command_encoding(self):
compiler = shutil.which("cc")
if not compiler:
self.skipTest("native C compiler not available")
source = Path(__file__).with_name("ipa_v2_cmd_format.c")
with tempfile.TemporaryDirectory() as directory:
executable = Path(directory) / "ipa-v2-format-test"
subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror",
str(source), "-o", str(executable)], check=True)
subprocess.run([str(executable)], check=True)
+119
View File
@@ -0,0 +1,119 @@
"""Fail-closed live-DT validation for the temporary IPA DMA test overlay."""
import importlib.util
from pathlib import Path
import struct
import tempfile
import unittest
SPEC = importlib.util.spec_from_file_location(
"cellular_bam_overlay",
Path(__file__).resolve().parents[1] / "scripts/phone-cellular-bam-overlay.py",
)
OVERLAY = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(OVERLAY)
class BamOverlayTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.put("compatible", b"xiaomi,platina\0qcom,sdm660\0")
self.put_cells("soc@0/#address-cells", 1)
self.put_cells("soc@0/#size-cells", 1)
self.put("soc@0/iommu@16c0000/compatible", b"qcom,sdm630-smmu-v2\0qcom,smmu-v2\0")
self.put_cells("soc@0/iommu@16c0000/phandle", 0x9C)
self.put_cells("soc@0/iommu@16c0000/#iommu-cells", 1)
self.put_cells("soc@0/rpm-cc/phandle", 0x29)
self.put_cells("soc@0/rpm-cc/#clock-cells", 1)
self.put("soc@0/ipa@14780000/compatible", b"qcom,sdm660-ipa\0qcom,ipa-v2.6\0")
self.put("soc@0/ipa@14780000/clock-names", b"core\0")
self.put_cells("soc@0/ipa@14780000/clocks", 0x29, 0x44)
def put(self, name, data):
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
def put_cells(self, name, *values):
self.put(name, struct.pack(f">{len(values)}I", *values))
def generate(self):
return OVERLAY.generate(self.root)
def test_live_phandles_are_used_without_modifying_parent(self):
self.put_cells("soc@0/iommu@16c0000/phandle", 0x17)
self.put_cells("soc@0/rpm-cc/phandle", 0x81)
self.put_cells("soc@0/ipa@14780000/clocks", 0x81, 0x44)
result = self.generate()
self.assertIn("iommus = <0x17 0x19c0>", result)
self.assertIn("clocks = <0x81 0x44>", result)
self.assertIn("reg = <0x147c0000 0x1000>, <0x14784000 0x26934>", result)
self.assertNotIn("#address-cells", result)
self.assertNotIn("#size-cells", result)
self.assertNotIn("ipa@14780000", result)
def test_other_machine_rejected(self):
self.put("compatible", b"other,phone\0")
with self.assertRaisesRegex(ValueError, "not xiaomi,platina"):
self.generate()
def test_other_address_layout_rejected(self):
self.put_cells("soc@0/#address-cells", 2)
with self.assertRaisesRegex(ValueError, "address/size"):
self.generate()
def test_existing_ap_stream_rejected(self):
self.put_cells("soc@0/ipa@14780000/iommus", 0x9C, 0x19C0)
with self.assertRaisesRegex(ValueError, "already declared"):
self.generate()
def test_non_ap_stream_allowed(self):
self.put_cells("soc@0/some-device/iommus", 0x9C, 0x19C1, 0x9C, 0x19C2)
self.assertIn("0x19c0", self.generate())
def test_unknown_iommu_provider_rejected(self):
self.put_cells("soc@0/some-device/iommus", 0xFF, 0x19C0)
with self.assertRaisesRegex(ValueError, "unresolved IOMMU"):
self.generate()
def test_truncated_iommu_spec_rejected(self):
self.put_cells("soc@0/some-device/iommus", 0x9C)
with self.assertRaisesRegex(ValueError, "invalid IOMMU arguments"):
self.generate()
def test_unexpected_iommu_cells_rejected(self):
self.put_cells("soc@0/iommu@16c0000/#iommu-cells", 2)
with self.assertRaisesRegex(ValueError, "IOMMU argument"):
self.generate()
def test_duplicate_phandle_rejected(self):
self.put_cells("soc@0/another-device/phandle", 0x29)
with self.assertRaisesRegex(ValueError, "duplicate phandle"):
self.generate()
def test_wrong_clock_rejected(self):
self.put_cells("soc@0/ipa@14780000/clocks", 0x29, 0x45)
with self.assertRaisesRegex(ValueError, "RPM IPA core clock"):
self.generate()
def test_clock_provider_cells_rejected(self):
self.put_cells("soc@0/rpm-cc/#clock-cells", 2)
with self.assertRaisesRegex(ValueError, "clock provider"):
self.generate()
def test_existing_test_device_rejected(self):
(self.root / "soc@0/platina-ipa-dma-test@147c0000").mkdir()
with self.assertRaisesRegex(ValueError, "test node already exists"):
self.generate()
def test_malformed_cells_rejected(self):
self.put("soc@0/ipa@14780000/clocks", b"\x00")
with self.assertRaisesRegex(ValueError, "invalid cells"):
self.generate()
if __name__ == "__main__":
unittest.main()
+53
View File
@@ -0,0 +1,53 @@
"""Exercise the opt-in early-IPA boot gate against fake remoteproc devices."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
DSP = ROOT / "scripts/phone-dsp.openrc"
RMTFS = ROOT / "project/cellular/ipa-v2/rmtfs-early.conf"
class EarlyIpaBootTest(unittest.TestCase):
def test_exact_cmdline_token_required(self):
for cmdline, enabled in (("quiet platina.ipa_bringup=1 panic=10", True),
("quiet platina.ipa_bringup=0", False),
("xplatina.ipa_bringup=1", False),
("platina.ipa_bringup=10", False),
("quiet", False)):
with self.subTest(cmdline=cmdline), tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "cmdline"
path.write_text(cmdline + "\n")
result = subprocess.run(["sh", "-c", '. "$1"; ipa_bringup_mode "$2"',
"sh", str(DSP), str(path)])
self.assertEqual(result.returncode == 0, enabled)
def test_only_modem_is_held_offline(self):
for mode in ("0", "1"):
with self.subTest(mode=mode), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for index, name in enumerate(("adsp", "cdsp", "4080000.remoteproc")):
node = root / f"remoteproc{index}"
node.mkdir()
(node / "name").write_text(name + "\n")
(node / "state").write_text("offline\n")
subprocess.run(["sh", "-c", '. "$1"; start_remoteprocs "$2" "$3"',
"sh", str(DSP), str(root), mode], check=True)
self.assertEqual((root / "remoteproc0/state").read_text(), "start\n")
self.assertEqual((root / "remoteproc1/state").read_text(), "start\n")
self.assertEqual((root / "remoteproc2/state").read_text(),
"offline\n" if mode == "1" else "start\n")
def test_rmtfs_sync_option_only_removed_in_test_boot(self):
for cmdline, expected in (("quiet", "-s -P -r -v"),
("quiet platina.ipa_bringup=1", "-P -r -v")):
with self.subTest(cmdline=cmdline):
script = ('cat() { printf "%s\\n" "$TEST_CMDLINE"; }; '
'command_args="-s -P -r -v"; . "$1"; '
'printf "%s" "$command_args"')
result = subprocess.run(["sh", "-c", script, "sh", str(RMTFS)],
env={"TEST_CMDLINE": cmdline}, capture_output=True,
text=True, check=True)
self.assertEqual(result.stdout, expected)
+93
View File
@@ -16,6 +16,48 @@ rpmsg = importlib.util.module_from_spec(spec)
spec.loader.exec_module(rpmsg)
class FrameStatsTests(unittest.TestCase):
@staticmethod
def encode(payload):
fcs = rpmsg.PPPFrameStats.fcs(payload) ^ 0xffff
frame = payload + fcs.to_bytes(2, 'little')
escaped = bytearray(b'\x7e')
for byte in frame:
if byte < 0x20 or byte in (0x7d, 0x7e):
escaped.extend((0x7d, byte ^ 0x20))
else:
escaped.append(byte)
return bytes(escaped) + b'\x7e'
def test_fcs_matches_captured_modem_lcp_frame(self):
stats = rpmsg.PPPFrameStats()
stats.feed(bytes.fromhex('7e80210100000467c37e'))
self.assertEqual(stats.protocols, {'ipcp': 1})
self.assertEqual(stats.invalid_fcs, 0)
def test_stream_splits_and_compression_do_not_change_ip_counts(self):
stats = rpmsg.PPPFrameStats()
payload = bytes(range(40)) + b'\x7d\x7e'
data = self.encode(b'\xff\x03\x00\x21' + payload)
data += self.encode(b'\x21' + payload)
# Includes every split position, including the middle of escapes/FCS.
for byte in b'CONNECT\r\n' + data:
stats.feed(bytes([byte]))
self.assertEqual(stats.protocols, {'ipv4': 2})
self.assertEqual(stats.ipv4_bytes, len(payload) * 2)
self.assertEqual(stats.invalid_fcs, 0)
def test_corrupt_and_oversized_frames_are_not_received_ip(self):
stats = rpmsg.PPPFrameStats()
stats.feed(b'\x7e\x21\x45\x01\x02\x03\x7e')
stats.feed(b'\x7e' + b'x' * 65537 + b'\x7e')
stats.feed(self.encode(b'\xc0\x21\x09\x00\x00\x04'))
self.assertEqual(stats.invalid_fcs, 1)
self.assertEqual(stats.oversized, 1)
self.assertEqual(stats.protocols, {'lcp': 1})
self.assertEqual(stats.ipv4_bytes, 0)
class ATTests(unittest.TestCase):
def exchange(self, chunks, command='AT', timeout=1):
host, modem = socket.socketpair(type=socket.SOCK_DGRAM)
@@ -108,6 +150,57 @@ class EndpointTests(unittest.TestCase):
class PPPTests(unittest.TestCase):
def test_shutdown_forwards_termination_and_peer_ack(self):
host, modem = socket.socketpair(type=socket.SOCK_DGRAM)
self.addCleanup(host.close)
self.addCleanup(modem.close)
host.setblocking(False)
modem.settimeout(2)
master, slave = rpmsg.pty.openpty()
self.addCleanup(os.close, master)
self.addCleanup(os.close, slave)
rpmsg.tty.setraw(slave)
os.set_blocking(master, False)
os.set_blocking(slave, False)
termination = b'\x7e\xff\x03\xc0\x21\x05\x01\x00\x04\x7e'
ack = b'\x7e\xff\x03\xc0\x21\x06\x01\x00\x04\x7e'
observed = []
def peer():
observed.append(modem.recv(1024))
modem.send(ack)
thread = threading.Thread(target=peer, daemon=True)
thread.start()
class Process:
killed = False
returncode = None
def terminate(self):
os.write(slave, termination)
def poll(self):
if select.select([slave], [], [], 0)[0]:
if os.read(slave, 1024) == ack:
self.returncode = 0
return self.returncode
def kill(self):
self.killed = True
self.returncode = -9
def wait(self, timeout=None):
return self.returncode
process = Process()
rpmsg.stop_ppp(process, host.fileno(), master, timeout=1)
thread.join(timeout=2)
self.assertFalse(thread.is_alive())
self.assertEqual(observed, [termination])
self.assertEqual(process.returncode, 0)
self.assertFalse(process.killed)
def test_manager_is_restored_when_modem_preparation_fails(self):
calls = []
+70
View File
@@ -78,6 +78,9 @@ class CellularSetupTests(unittest.TestCase):
self.assertIn('connection.autoconnect', cmds[0])
idx = cmds[0].index('connection.autoconnect')
self.assertEqual(cmds[0][idx + 1], 'no')
self.assertIn('ipv4.route-metric', cmds[0])
m_idx = cmds[0].index('ipv4.route-metric')
self.assertEqual(cmds[0][m_idx + 1], '700')
def test_build_nmcli_setup_commands_existing(self):
cmds = cellular.build_nmcli_setup_commands(
@@ -93,6 +96,9 @@ class CellularSetupTests(unittest.TestCase):
self.assertIn('connection.autoconnect', cmds[0])
idx = cmds[0].index('connection.autoconnect')
self.assertEqual(cmds[0][idx + 1], 'no')
self.assertIn('ipv4.route-metric', cmds[0])
m_idx = cmds[0].index('ipv4.route-metric')
self.assertEqual(cmds[0][m_idx + 1], '700')
def test_configure_cellular_invokes_executor(self):
recorded_calls = []
@@ -364,6 +370,70 @@ class CellularSetupTests(unittest.TestCase):
self.assertEqual(recorded[0], ['modprobe', '--ignore-install', 'qcom_q6v5_mss'])
self.assertEqual(recorded[1], ['modprobe', '--ignore-install', 'ipa'])
def test_daemon_waits_for_datapath_and_plmn_registration(self):
checks = [False, True, True]
mm_outputs = [
"General | path: /org/freedesktop/ModemManager1/Modem/0\nStatus | state: searching\n",
SAMPLE_MMCLI_OUTPUT.replace('46000', '46001').replace('CMCC', 'CHN-UNICOM'),
]
mm_idx = [0]
recorded = []
active_state = [False]
logs = []
def mock_datapath():
return checks.pop(0) if checks else True
def mock_executor(cmd, **kwargs):
recorded.append(cmd)
cmd_str = ' '.join(cmd)
if 'mmcli -L' in cmd_str:
return subprocess.CompletedProcess(cmd, 0,
stdout='/org/freedesktop/ModemManager1/Modem/0 [QUALCOMM] SDM660\n', stderr='')
if 'mmcli -m 0' in cmd_str:
out = mm_outputs[min(mm_idx[0], len(mm_outputs) - 1)]
mm_idx[0] += 1
return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr='')
if 'connection show --active' in cmd_str:
out = 'platina-cellular\n' if active_state[0] else 'platina-usb\n'
return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr='')
if 'connection show' in cmd_str:
return subprocess.CompletedProcess(cmd, 0, stdout='platina-usb\n', stderr='')
if 'connection up' in cmd_str:
active_state[0] = True
return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='')
return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='')
res = cellular.run_auto_connect(
daemon=True,
poll_interval=1,
max_attempts=3,
executor=mock_executor,
sleeper=lambda s: None,
logger=logs.append,
datapath_checker=mock_datapath,
)
self.assertFalse(res) # exits cleanly on max_attempts=3 in daemon loop
self.assertTrue(active_state[0])
add_calls = [c for c in recorded if 'add' in c]
self.assertEqual(len(add_calls), 1)
self.assertIn('3gnet', add_calls[0])
self.assertNotIn('cmnet', add_calls[0])
self.assertIn('700', add_calls[0])
self.assertTrue(any('dialing skipped' in log for log in logs))
self.assertTrue(any('waiting for registration' in log for log in logs))
def test_usb_profile_metric_yields_to_cellular_and_wifi(self):
usb_profile = (ROOT / 'ports/candidate/device-xiaomi-platina/platina-usb.nmconnection').read_text()
metric = None
for line in usb_profile.splitlines():
if line.strip().startswith('route-metric='):
metric = int(line.split('=', 1)[1].strip())
break
self.assertIsNotNone(metric)
self.assertEqual(metric, 2000)
self.assertGreater(metric, 700)
if __name__ == '__main__':
unittest.main()
+114
View File
@@ -104,5 +104,119 @@ class ChordTests(unittest.TestCase):
self.assertEqual(chord.find_devices(base), {P: Path('/dev/input/event7'), U: Path('/dev/input/event9')})
class PowerButtonAndStandbyTests(unittest.TestCase):
def test_short_power_tap_toggles_screen_and_ignores_glitches(self):
policy = chord.PowerButtonPolicy(hold_seconds=3.0)
# Sub-20ms bounce does nothing
self.assertIsNone(policy.event(P, 1, 10.0))
self.assertIsNone(policy.event(P, 0, 10.01))
# Normal 120ms tap toggles screen
self.assertIsNone(policy.event(P, 1, 20.0))
self.assertIsNone(policy.check_timeout(20.1))
self.assertEqual(policy.event(P, 0, 20.12), 'toggle_screen')
def test_long_power_fires_at_timeout_and_suppresses_release(self):
policy = chord.PowerButtonPolicy(hold_seconds=3.0)
self.assertIsNone(policy.event(P, 1, 100.0))
self.assertIsNone(policy.check_timeout(102.9))
self.assertEqual(policy.check_timeout(103.0), 'long_power')
self.assertIsNone(policy.check_timeout(103.5))
self.assertIsNone(policy.event(P, 0, 103.6))
def test_chord_compatible_and_volume_up_prevents_screen_toggle(self):
policy = chord.PowerButtonPolicy(hold_seconds=3.0)
self.assertIsNone(policy.event(U, 1, 50.0))
self.assertIsNone(policy.event(P, 1, 50.1))
self.assertIsNone(policy.event(P, 0, 50.5))
self.assertIsNone(policy.event(U, 0, 50.6))
# Full 3s hold with Power + Volume Up triggers long_power
self.assertIsNone(policy.event(P, 1, 60.0))
self.assertIsNone(policy.event(U, 1, 60.1))
self.assertEqual(policy.check_timeout(63.0), 'long_power')
self.assertIsNone(policy.event(U, 0, 63.1))
self.assertIsNone(policy.event(P, 0, 63.2))
def test_boot_charger_cmdline_detection(self):
with tempfile.TemporaryDirectory() as tmp:
cmd = Path(tmp) / 'cmdline'
cmd.write_text('quiet pmos_root_uuid=abc\n')
self.assertFalse(chord.is_boot_charger_mode(cmd))
cmd.write_text('quiet androidboot.mode=charger androidboot.serialno=63c36adb\n')
self.assertTrue(chord.is_boot_charger_mode(cmd))
cmd.write_text('quiet androidboot.bootreason=usb_chg\n')
self.assertTrue(chord.is_boot_charger_mode(cmd))
def test_can_auto_suspend_protects_screen_usb_host_ssh_and_inhibit(self):
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
sys_root = base / 'sys'
proc_net = base / 'proc_net'
inhibit = base / 'inhibit'
(sys_root / 'class/net/usb0').mkdir(parents=True)
(sys_root / 'class/power_supply/pm660-charger').mkdir(parents=True)
proc_net.mkdir()
(sys_root / 'class/net/usb0/carrier').write_text('0\n')
(sys_root / 'class/power_supply/pm660-charger/usb_type').write_text('Unknown SDP [DCP] CDP\n')
(proc_net / 'tcp').write_text(' sl local_address rem_address st\n')
(proc_net / 'tcp6').write_text(
' sl local_address rem_address st\n'
' 0: 00000000000000000000000000000000:0016 00000000000000000000000000000000:0000 0A\n')
# Idle battery/DCP with listening sshd only -> safe to suspend
self.assertEqual(chord.can_auto_suspend(False, sys_root, proc_net, inhibit)[0], True)
# Screen ON blocks
self.assertEqual(chord.can_auto_suspend(True, sys_root, proc_net, inhibit), (False, 'screen on'))
# Inhibit file blocks
inhibit.write_text('1')
self.assertEqual(chord.can_auto_suspend(False, sys_root, proc_net, inhibit), (False, 'inhibit file'))
inhibit.unlink()
# Active USB NCM SDP host blocks
(sys_root / 'class/net/usb0/carrier').write_text('1\n')
(sys_root / 'class/power_supply/pm660-charger/usb_type').write_text('Unknown [SDP] DCP CDP\n')
self.assertEqual(chord.can_auto_suspend(False, sys_root, proc_net, inhibit), (False, 'usb data host'))
(sys_root / 'class/net/usb0/carrier').write_text('0\n')
# Established SSH session on :0016 blocks
(proc_net / 'tcp').write_text(
' sl local_address rem_address st\n'
' 5: 012A10AC:0016 022A10AC:ED34 01\n')
self.assertEqual(chord.can_auto_suspend(False, sys_root, proc_net, inhibit), (False, 'active ssh session'))
def test_set_cpu_standby_clamps_and_restores_clusters(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / 'cpufreq'
p0 = root / 'policy0'
p1 = root / 'policy1'
p0.mkdir(parents=True)
p1.mkdir(parents=True)
(p0 / 'cpuinfo_max_freq').write_text('2208000\n')
(p0 / 'scaling_min_freq').write_text('300000\n')
(p0 / 'scaling_available_frequencies').write_text('300000 1113600 2208000\n')
(p0 / 'scaling_max_freq').write_text('2208000\n')
(p1 / 'cpuinfo_max_freq').write_text('1843200\n')
(p1 / 'scaling_min_freq').write_text('300000\n')
(p1 / 'scaling_available_frequencies').write_text('300000 633600 902400 1843200\n')
(p1 / 'scaling_max_freq').write_text('1843200\n')
res_std = chord.set_cpu_standby('standby', cpufreq_root=root)
self.assertEqual(res_std, {'policy0': 300000, 'policy1': 633600})
self.assertEqual((p0 / 'scaling_max_freq').read_text().strip(), '300000')
self.assertEqual((p1 / 'scaling_max_freq').read_text().strip(), '633600')
res_chg = chord.set_cpu_standby('charger', cpufreq_root=root)
self.assertEqual(res_chg, {'policy0': 300000, 'policy1': 300000})
self.assertEqual((p1 / 'scaling_max_freq').read_text().strip(), '300000')
res_act = chord.set_cpu_standby('active', cpufreq_root=root)
self.assertEqual(res_act, {'policy0': 2208000, 'policy1': 1843200})
self.assertEqual((p0 / 'scaling_max_freq').read_text().strip(), '2208000')
self.assertEqual((p1 / 'scaling_max_freq').read_text().strip(), '1843200')
with self.assertRaises(ValueError):
chord.set_cpu_standby('invalid', cpufreq_root=root)
if __name__ == '__main__':
unittest.main()
+123
View File
@@ -0,0 +1,123 @@
"""Verify telemetry collection and BGRX framebuffer rendering for platina-status-screen."""
import importlib.util
from pathlib import Path
import subprocess
import tempfile
import time
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('status_screen', ROOT / 'scripts/phone-status-screen.py')
screen = importlib.util.module_from_spec(spec)
spec.loader.exec_module(screen)
class StatusScreenTests(unittest.TestCase):
def _build_fixtures(self, base):
sys_dir = base / 'sys'
proc_dir = base / 'proc'
bat = sys_dir / 'class/power_supply/qcom-battery'
chg = sys_dir / 'class/power_supply/pm660-charger'
ipa = sys_dir / 'devices/platform/soc@0/147c0000.ipa/modem'
usb0 = sys_dir / 'class/net/usb0'
for d in (bat, chg, ipa, usb0, proc_dir):
d.mkdir(parents=True, exist_ok=True)
(bat / 'capacity').write_text('78\n')
(bat / 'status').write_text('Not charging\n')
(bat / 'voltage_now').write_text('4050000\n')
(bat / 'temp').write_text('315\n')
(chg / 'online').write_text('1\n')
(chg / 'usb_type').write_text('Unknown [SDP] DCP CDP\n')
(chg / 'charge_behaviour').write_text('auto [inhibit-charge] force-discharge\n')
(ipa / 'datapath_ready').write_text('1\n')
(usb0 / 'carrier').write_text('1\n')
(proc_dir / 'uptime').write_text('3661.2 14000.0\n')
(proc_dir / 'loadavg').write_text('0.12 0.08 0.05 1/180 42\n')
(proc_dir / 'meminfo').write_text('MemTotal: 4000000 kB\nMemAvailable: 3000000 kB\n')
return sys_dir, proc_dir
def test_collect_telemetry_reads_fixtures_and_commands(self):
with tempfile.TemporaryDirectory() as tmp:
sys_dir, proc_dir = self._build_fixtures(Path(tmp))
def fake_run(cmd, **kwargs):
if cmd[:4] == ['ip', '-4', 'route', 'show']:
return subprocess.CompletedProcess(
cmd, 0, 'default via 10.75.105.57 dev qmapmux0.0 metric 700\n', '')
if cmd[:4] == ['ip', '-4', '-o', 'addr']:
return subprocess.CompletedProcess(
cmd, 0,
'2: usb0 inet 172.16.42.1/24 brd 172.16.42.255\n'
'5: tun0 inet 192.168.20.10/24\n'
'6: qmapmux0.0 inet 10.75.105.56/28\n', '')
if cmd[:2] == ['mmcli', '-m']:
return subprocess.CompletedProcess(
cmd, 0,
'modem.generic.state : connected\n'
'modem.3gpp.operator-name : CHN-UNICOM\n'
'modem.generic.access-technologies.value[1] : lte\n'
'modem.generic.signal-quality.value : 97\n', '')
return subprocess.CompletedProcess(cmd, 1, '', '')
data = screen.collect_telemetry(sys_path=sys_dir, proc_path=proc_dir, run=fake_run)
self.assertEqual(data['battery']['capacity'], 78)
self.assertTrue(data['battery']['inhibited'])
self.assertEqual(data['battery']['power_state'], 'Paused (80% Guard)')
self.assertEqual(data['battery']['voltage_v'], 4.05)
self.assertEqual(data['battery']['temp_c'], 31.5)
self.assertEqual(data['cellular']['operator'], 'CHN-UNICOM')
self.assertEqual(data['cellular']['signal_percent'], 97)
self.assertTrue(data['cellular']['is_default'])
self.assertEqual(data['network']['tun0_ip'], '192.168.20.10')
def test_render_status_and_charger_bgrx_format_and_speed(self):
telemetry = {
'timestamp': '2026-11-17 22:30:00',
'clock': '22:30:00',
'date': '2026-11-17',
'uptime_s': 1234.0,
'uptime_str': '00h 20m 34s',
'load_avg': '0.10 0.08 0.05',
'mem_used_mb': 950,
'mem_total_mb': 3800,
'battery': {
'capacity': 78,
'status': 'Charging',
'power_state': 'Charging',
'voltage_v': 4.05,
'temp_c': 31.3,
'charger_online': True,
'usb_type': 'DCP',
'inhibited': False,
},
'cellular': {
'datapath_ready': True,
'state': 'connected',
'operator': 'CHN-UNICOM',
'access_tech': 'lte',
'signal_percent': 97,
'ip': '10.75.105.56',
'is_default': True,
},
'network': {
'default_dev': 'qmapmux0.0',
'wlan0_ip': None,
'usb0_ip': '172.16.42.1',
'usb0_carrier': False,
'tun0_ip': '192.168.20.10',
},
}
expected_len = 1080 * 2280 * 4
for mode in ('status', 'charger'):
t0 = time.monotonic()
raw = screen.render_dashboard_bgrx(telemetry, mode=mode)
elapsed = time.monotonic() - t0
self.assertEqual(len(raw), expected_len)
self.assertLess(elapsed, 0.5)
# Every BGRX pixel keeps byte 3 (X padding) as 0 and includes non-background pixels
self.assertEqual(set(raw[3::4]), {0})
self.assertNotEqual(bytes(raw), screen.COL_BG * (1080 * 2280))
if __name__ == '__main__':
unittest.main()