From 8d12d341bf812dc2383550c6949bdea59841c4d8 Mon Sep 17 00:00:00 2001 From: shenlei Date: Wed, 18 Nov 2026 01:39:26 +0900 Subject: [PATCH] feat(cellular, power): enable SDM660 IPA v2.6L 4G LTE, power-key status screen, and DVFS standby --- README.md | 10 +- docs/CELLULAR.md | 330 ++- docs/SHUTDOWN.md | 68 +- .../candidate/device-xiaomi-platina/APKBUILD | 4 +- .../platina-usb.nmconnection | 2 +- ...tina-touch-dual-panel-vsp-power-dvfs.patch | 11 +- ...042-arm64-dts-sdm660-add-ipa-v2-node.patch | 30 +- ...implement-sdm660-v2-6l-bam-transport.patch | 2608 +++++++++++++++++ ...a-reject-unimplemented-bam-transport.patch | 61 - ...dm630-fix-anoc2-context-irq-polarity.patch | 30 + .../linux-postmarketos-qcom-sdm660/APKBUILD | 12 +- project/cellular/ipa-v2/INITIALIZATION.md | 82 + project/cellular/ipa-v2/Makefile | 4 + project/cellular/ipa-v2/README.md | 164 ++ project/cellular/ipa-v2/ipa_v2_cmd_format.h | 121 + project/cellular/ipa-v2/ipa_v2_dma.h | 48 + .../cellular/ipa-v2/platina_ipa_v2_cmd_test.c | 804 +++++ .../cellular/ipa-v2/platina_ipa_v2_dma_test.c | 269 ++ .../cellular/ipa-v2/platina_ipa_v2_probe.c | 214 ++ project/cellular/ipa-v2/rmtfs-early.conf | 5 + project/sources.lock.json | 4 +- scripts/flash_release.sh | 15 +- scripts/image-runtime.py | 1 + scripts/phone-cellular-bam-overlay.py | 100 + scripts/phone-cellular-rpmsg.py | 124 +- scripts/phone-cellular-setup.py | 39 +- scripts/phone-dsp.openrc | 61 +- scripts/phone-headless.start | 21 +- scripts/phone-power-chord.conf | 5 +- scripts/phone-power-chord.openrc | 7 +- scripts/phone-power-chord.py | 421 ++- scripts/phone-poweroff.py | 26 +- scripts/phone-status-screen.py | 701 +++++ scripts/project.py | 4 +- scripts/setup_usb_gadget_service.sh | 45 +- tests/ipa_v2_cmd_format.c | 37 + tests/test_cellular_bam_format.py | 19 + tests/test_cellular_bam_overlay.py | 119 + tests/test_cellular_early_boot.py | 53 + tests/test_cellular_rpmsg.py | 93 + tests/test_cellular_setup.py | 70 + tests/test_power_chord.py | 114 + tests/test_status_screen.py | 123 + 43 files changed, 6850 insertions(+), 229 deletions(-) create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-implement-sdm660-v2-6l-bam-transport.patch delete mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-reject-unimplemented-bam-transport.patch create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0045-arm64-dts-sdm630-fix-anoc2-context-irq-polarity.patch create mode 100644 project/cellular/ipa-v2/INITIALIZATION.md create mode 100644 project/cellular/ipa-v2/Makefile create mode 100644 project/cellular/ipa-v2/README.md create mode 100644 project/cellular/ipa-v2/ipa_v2_cmd_format.h create mode 100644 project/cellular/ipa-v2/ipa_v2_dma.h create mode 100644 project/cellular/ipa-v2/platina_ipa_v2_cmd_test.c create mode 100644 project/cellular/ipa-v2/platina_ipa_v2_dma_test.c create mode 100644 project/cellular/ipa-v2/platina_ipa_v2_probe.c create mode 100644 project/cellular/ipa-v2/rmtfs-early.conf create mode 100644 scripts/phone-cellular-bam-overlay.py create mode 100755 scripts/phone-status-screen.py create mode 100644 tests/ipa_v2_cmd_format.c create mode 100644 tests/test_cellular_bam_format.py create mode 100644 tests/test_cellular_bam_overlay.py create mode 100644 tests/test_cellular_early_boot.py create mode 100644 tests/test_status_screen.py diff --git a/README.md b/README.md index a244361..236910f 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/CELLULAR.md b/docs/CELLULAR.md index 7ae9732..a42165d 100644 --- a/docs/CELLULAR.md +++ b/docs/CELLULAR.md @@ -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 diff --git a/docs/SHUTDOWN.md b/docs/SHUTDOWN.md index 43b7d83..af0b5b1 100644 --- a/docs/SHUTDOWN.md +++ b/docs/SHUTDOWN.md @@ -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. diff --git a/ports/candidate/device-xiaomi-platina/APKBUILD b/ports/candidate/device-xiaomi-platina/APKBUILD index afe2b6a..efacdb8 100644 --- a/ports/candidate/device-xiaomi-platina/APKBUILD +++ b/ports/candidate/device-xiaomi-platina/APKBUILD @@ -3,7 +3,7 @@ maintainer="Platina local project " 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 " diff --git a/ports/candidate/device-xiaomi-platina/platina-usb.nmconnection b/ports/candidate/device-xiaomi-platina/platina-usb.nmconnection index 66de955..d1207a2 100644 --- a/ports/candidate/device-xiaomi-platina/platina-usb.nmconnection +++ b/ports/candidate/device-xiaomi-platina/platina-usb.nmconnection @@ -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] diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch index fce324e..6814d4a 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch @@ -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 diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0042-arm64-dts-sdm660-add-ipa-v2-node.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0042-arm64-dts-sdm660-add-ipa-v2-node.patch index ba436ae..7a0d866 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/0042-arm64-dts-sdm660-add-ipa-v2-node.patch +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0042-arm64-dts-sdm660-add-ipa-v2-node.patch @@ -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"; + }; }; diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-implement-sdm660-v2-6l-bam-transport.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-implement-sdm660-v2-6l-bam-transport.patch new file mode 100644 index 0000000..e4315f7 --- /dev/null +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-implement-sdm660-v2-6l-bam-transport.patch @@ -0,0 +1,2608 @@ +From: Platina Linux contributors +Subject: [PATCH] net: ipa: implement SDM660 IPA v2.6L BAM data transport + +Implement BAM pipe initialization, 128-byte-aligned DDR/SRAM routing and +filter tables, immediate command engine submission (pipe 3 CMD_PROD), AP +SMMU DMA mappings, and modem QMI service 0x31 handshake for Qualcomm SDM660 +IPA v2.6L hardware, derived from Xiaomi platina-o-oss (commit +0bb2780bccb9c7e05f0edf5db8860e779179b5f9). + +Configure IPA_V2_FILTER with FILTER_DIS=0 so per-pipe UL filters route +WWAN packets through Q6 LAN consumer pipe 8, pulse AGGR_FORCE_CLOSE on +ep[8] via pipe 3 IPA_REGISTER_WRITE after idle TX completion, and run +pipe 5 APPS_WAN_CONS in IPA_BYPASS_AGGR single-frame QMAP mode with exact +repost ring buffer indexing. + +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/Makefile /tmp/ipa-patch-gen/b/drivers/net/ipa/Makefile +--- a/drivers/net/ipa/Makefile 2026-11-17 16:17:18.344000000 +0800 ++++ b/drivers/net/ipa/Makefile 2026-11-16 17:58:58.092000000 +0800 +@@ -16,7 +16,7 @@ + gsi_trans.o ipa_gsi.o ipa_smp2p.o ipa_uc.o \ + ipa_endpoint.o ipa_cmd.o ipa_modem.o \ + ipa_resource.o ipa_qmi.o ipa_qmi_msg.o \ +- ipa_sysfs.o ++ ipa_sysfs.o ipa_v2_bam.o + + ipa-y += $(IPA_REG_VERSIONS:%=reg/ipa_reg-v%.o) + +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa.h /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa.h +--- a/drivers/net/ipa/ipa.h 2026-11-17 16:17:18.344000000 +0800 ++++ b/drivers/net/ipa/ipa.h 2026-11-16 17:58:58.092000000 +0800 +@@ -20,6 +20,7 @@ + struct ipa_interrupt; + struct ipa_power; + struct ipa_smp2p; ++struct ipa_v2_bam; + + /** + * struct ipa - IPA information +@@ -129,6 +130,7 @@ + atomic_t modem_state; /* enum ipa_modem_state */ + struct net_device *modem_netdev; + struct ipa_qmi qmi; ++ struct ipa_v2_bam *v2_bam; + }; + + /** +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa_endpoint.c /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa_endpoint.c +--- a/drivers/net/ipa/ipa_endpoint.c 2026-11-17 16:17:18.344000000 +0800 ++++ b/drivers/net/ipa/ipa_endpoint.c 2026-11-12 19:31:04.144000000 +0800 +@@ -1242,10 +1242,8 @@ + 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. +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa_main.c /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa_main.c +--- a/drivers/net/ipa/ipa_main.c 2026-11-17 16:17:18.344000000 +0800 ++++ b/drivers/net/ipa/ipa_main.c 2026-11-16 17:58:58.096000000 +0800 +@@ -31,6 +31,7 @@ + #include "ipa_sysfs.h" + #include "ipa_table.h" + #include "ipa_uc.h" ++#include "ipa_v2_bam.h" + #include "ipa_version.h" + + /** +@@ -841,9 +842,9 @@ + } + + if (data->version < IPA_VERSION_3_0) +- loader = IPA_LOADER_SKIP; +- else +- loader = ipa_firmware_loader(dev); ++ return ipa_v2_bam_probe(pdev, data); ++ ++ loader = ipa_firmware_loader(dev); + if (loader == IPA_LOADER_INVALID) + return -EINVAL; + if (loader == IPA_LOADER_DEFER) +@@ -987,6 +988,10 @@ + int ret; + + ipa = dev_get_drvdata(&pdev->dev); ++ if (ipa->version < IPA_VERSION_3_0) { ++ ipa_v2_bam_remove(pdev); ++ return; ++ } + dev = ipa->dev; + WARN_ON(dev != &pdev->dev); + +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa_modem.c /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa_modem.c +--- a/drivers/net/ipa/ipa_modem.c 2026-11-17 16:17:18.344000000 +0800 ++++ b/drivers/net/ipa/ipa_modem.c 2026-11-12 19:31:04.144000000 +0800 +@@ -139,12 +139,8 @@ + 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; + +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa_power.c /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa_power.c +--- a/drivers/net/ipa/ipa_power.c 2026-11-17 16:17:18.344000000 +0800 ++++ b/drivers/net/ipa/ipa_power.c 2026-11-16 17:58:58.096000000 +0800 +@@ -166,6 +166,9 @@ + { + struct ipa *ipa = dev_get_drvdata(dev); + ++ if (ipa->version < IPA_VERSION_3_0) ++ return 0; ++ + /* Increment the disable depth to ensure that the IRQ won't + * be re-enabled until the matching _enable call in + * ipa_resume(). We do this to ensure that the interrupt +@@ -185,6 +188,9 @@ + struct ipa *ipa = dev_get_drvdata(dev); + int ret; + ++ if (ipa->version < IPA_VERSION_3_0) ++ return 0; ++ + ret = pm_runtime_force_resume(dev); + + /* Now that PM runtime is enabled again it's safe +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa_sysfs.c /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa_sysfs.c +--- a/drivers/net/ipa/ipa_sysfs.c 2026-11-17 16:17:18.344000000 +0800 ++++ b/drivers/net/ipa/ipa_sysfs.c 2026-11-17 13:34:04.044000000 +0800 +@@ -8,6 +8,7 @@ + + #include "ipa.h" + #include "ipa_sysfs.h" ++#include "ipa_v2_bam.h" + #include "ipa_version.h" + + static const char *ipa_version_string(struct ipa *ipa) +@@ -46,7 +47,7 @@ + case IPA_VERSION_5_5: + return "5.5"; + default: +- return "0.0"; /* Should not happen */ ++ return "0.0"; + } + } + +@@ -60,8 +61,22 @@ + + static DEVICE_ATTR_RO(version); + ++static ssize_t ++ipa_version_show(struct device *dev, struct device_attribute *attr, char *buf) ++{ ++ struct ipa *ipa = dev_get_drvdata(dev); ++ ++ if (ipa->version == IPA_VERSION_2_6) ++ return sysfs_emit(buf, "2.6L\n"); ++ ++ return sysfs_emit(buf, "%s\n", ipa_version_string(ipa)); ++} ++ ++static DEVICE_ATTR_RO(ipa_version); ++ + static struct attribute *ipa_attrs[] = { + &dev_attr_version.attr, ++ &dev_attr_ipa_version.attr, + NULL + }; + +@@ -94,6 +109,17 @@ + + static DEVICE_ATTR_RO(tx_offload); + ++static umode_t ipa_feature_is_visible(struct kobject *kobj, ++ struct attribute *attr, int n) ++{ ++ struct ipa *ipa = dev_get_drvdata(kobj_to_dev(kobj)); ++ ++ if (ipa->version < IPA_VERSION_3_0) ++ return 0; ++ ++ return attr->mode; ++} ++ + static struct attribute *ipa_feature_attrs[] = { + &dev_attr_rx_offload.attr, + &dev_attr_tx_offload.attr, +@@ -102,6 +128,7 @@ + + const struct attribute_group ipa_feature_attribute_group = { + .name = "feature", ++ .is_visible = ipa_feature_is_visible, + .attrs = ipa_feature_attrs, + }; + +@@ -116,10 +143,9 @@ + if (ipa->version < IPA_VERSION_3_0) + return attr->mode; + +- if (!ipa->name_map) +- return 0; ++ if (attr == &dev_attr_version.attr) ++ return attr->mode; + +- /* An endpoint id attribute is only visible if it's defined */ + dev_attr = container_of(attr, struct device_attribute, attr); + ea = container_of(dev_attr, struct dev_ext_attribute, attr); + +@@ -137,8 +163,7 @@ + u32 endpoint_id; + + ea = container_of(attr, struct dev_ext_attribute, attr); +- if (ipa->name_map) +- endpoint = ipa->name_map[(enum ipa_endpoint_name)(uintptr_t)ea->var]; ++ endpoint = ipa->name_map[(enum ipa_endpoint_name)(uintptr_t)ea->var]; + + if (endpoint) { + endpoint_id = endpoint->endpoint_id; +@@ -146,9 +171,9 @@ + enum ipa_endpoint_name name = (enum ipa_endpoint_name)(uintptr_t)ea->var; + + if (name == IPA_ENDPOINT_AP_MODEM_RX) +- endpoint_id = 16; ++ endpoint_id = 5; + else +- endpoint_id = 3; ++ endpoint_id = 4; + } else { + return -ENODEV; + } +@@ -177,7 +202,6 @@ + .attrs = ipa_endpoint_id_attrs, + }; + +-/* Reuse endpoint ID attributes for the legacy modem endpoint IDs */ + #define MODEM_ATTR(_n, _endpoint_name) \ + static struct dev_ext_attribute dev_attr_modem_ ## _n = { \ + .attr = __ATTR(_n, 0444, endpoint_id_attr_show, NULL), \ +@@ -187,14 +211,58 @@ + MODEM_ATTR(rx_endpoint_id, IPA_ENDPOINT_AP_MODEM_RX); + MODEM_ATTR(tx_endpoint_id, IPA_ENDPOINT_AP_MODEM_TX); + ++static ssize_t datapath_ready_show(struct device *dev, ++ struct device_attribute *attr, char *buf) ++{ ++ struct ipa *ipa = dev_get_drvdata(dev); ++ bool ready; ++ ++ if (ipa->version < IPA_VERSION_3_0) ++ ready = ipa_v2_bam_datapath_ready(ipa); ++ else ++ ready = ipa->setup_complete; ++ ++ return sysfs_emit(buf, "%u\n", ready ? 1 : 0); ++} ++ ++static DEVICE_ATTR_RO(datapath_ready); ++ ++static ssize_t debug_state_show(struct device *dev, ++ struct device_attribute *attr, char *buf) ++{ ++ struct ipa *ipa = dev_get_drvdata(dev); ++ ++ if (ipa->version < IPA_VERSION_3_0) ++ return ipa_v2_bam_debug_show(ipa, buf); ++ ++ return -EOPNOTSUPP; ++} ++ ++static DEVICE_ATTR_RO(debug_state); ++ ++static umode_t ipa_modem_is_visible(struct kobject *kobj, ++ struct attribute *attr, int n) ++{ ++ struct ipa *ipa = dev_get_drvdata(kobj_to_dev(kobj)); ++ ++ if (attr == &dev_attr_datapath_ready.attr) ++ return attr->mode; ++ if (attr == &dev_attr_debug_state.attr) ++ return ipa->version < IPA_VERSION_3_0 ? attr->mode : 0; ++ ++ return ipa_endpoint_id_is_visible(kobj, attr, n); ++} ++ + static struct attribute *ipa_modem_attrs[] = { + &dev_attr_modem_rx_endpoint_id.attr.attr, + &dev_attr_modem_tx_endpoint_id.attr.attr, ++ &dev_attr_datapath_ready.attr, ++ &dev_attr_debug_state.attr, + NULL, + }; + + const struct attribute_group ipa_modem_attribute_group = { + .name = "modem", +- .is_visible = ipa_endpoint_id_is_visible, ++ .is_visible = ipa_modem_is_visible, + .attrs = ipa_modem_attrs, + }; +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa_v2_bam.c /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa_v2_bam.c +--- a/drivers/net/ipa/ipa_v2_bam.c 1970-01-01 08:00:00.000000000 +0800 ++++ b/drivers/net/ipa/ipa_v2_bam.c 2026-11-17 16:08:34.320000000 +0800 +@@ -0,0 +1,2274 @@ ++// SPDX-License-Identifier: GPL-2.0 ++/* ++ * Qualcomm SDM660 IPA v2.6L BAM data transport & QMI modem integration. ++ * ++ * Derived from hardware qualification and Xiaomi platina-o-oss reference ++ * (commit 0bb2780bccb9c7e05f0edf5db8860e779179b5f9). ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "ipa.h" ++#include "ipa_data.h" ++#include "ipa_qmi_msg.h" ++#include "ipa_v2_bam.h" ++ ++/* IPA v2.6L MMIO register offsets (base 0x147c0000) */ ++#define IPA_V2_COMP_HW_VERSION 0x0030 ++#define IPA_V2_HW_VERSION_2_6L 0x20060001U ++#define IPA_V2_COMP_CFG 0x0038 ++#define IPA_V2_COMP_CFG_VAL 0x00000011U /* ENABLE | DCMP_FAST_CLK */ ++#define IPA_V2_ROUTE 0x0044 ++#define IPA_V2_FILTER 0x0048 ++#define IPA_V2_SHARED_MEM_SIZE 0x0050 ++#define IPA_V2_ENDP_INIT_CTRL(n) (0x0070 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_CFG(n) (0x00c0 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_NAT(n) (0x0120 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_HDR(n) (0x0170 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_HDR_EXT(n) (0x01c0 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_HDR_META_MSK(n) (0x0220 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_MODE(n) (0x02c0 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_AGGR(n) (0x0320 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_ROUTE(n) (0x0370 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_HOLB_EN(n) (0x03c0 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_HOLB_TMR(n) (0x0420 + 4 * (n)) ++#define IPA_V2_ENDP_INIT_DEAGGR(n) (0x0470 + 4 * (n)) ++#define IPA_V2_ENDP_STATUS(n) (0x04c0 + 4 * (n)) ++#define IPA_V2_BCR 0x05b0 ++#define IPA_V2_BCR_VAL 0x001fff7fU ++#define IPA_V2_ENABLED_PIPES 0x05dc ++#define IPA_V2_COUNTER_CFG 0x05e8 ++#define IPA_V2_COUNTER_CFG_VAL (15U << 4) /* 500 us @ 32 kHz */ ++#define IPA_V2_AGGR_EN 1U ++#define IPA_V2_AGGR_TYPE_GENERIC 4U ++#define IPA_V2_AGGR_SW_EOF_ACTIVE BIT(21) ++#define IPA_V2_AGGR_FORCE_CLOSE BIT(22) ++#define IPA_V2_IRQ_STTS_EE0 0x1008 ++#define IPA_V2_IRQ_CLR_EE0 0x1010 ++#define IPA_V2_IRQ_SUSPEND_INFO_EE0 0x1098 ++#define IPA_V2_PROC_ERR_IRQ BIT(15) ++#define IPA_V2_SRAM_BASE 0x5000 ++ ++/* SDM660 IPA v2.6L SRAM partition (8192 bytes, 0 restricted) */ ++#define IPA_V2_SRAM_SIZE 0x2000 ++#define IPA_V2_V4_FLT_OFST 0x0288 ++#define IPA_V2_V4_FLT_SIZE 0x0058 /* (1 + 21) * 4 = 88 */ ++#define IPA_V2_V6_FLT_OFST 0x02e8 ++#define IPA_V2_V6_FLT_SIZE 0x0058 ++#define IPA_V2_V4_RT_OFST 0x0348 ++#define IPA_V2_V4_RT_SIZE 0x003c /* 15 * 4 = 60 */ ++#define IPA_V2_V4_MODEM_RT_COUNT 7 /* indices 0..6 (hi = 6) */ ++#define IPA_V2_V6_RT_OFST 0x0388 ++#define IPA_V2_V6_RT_SIZE 0x003c ++#define IPA_V2_V6_MODEM_RT_COUNT 7 ++#define IPA_V2_MODEM_HDR_OFST 0x03c8 ++#define IPA_V2_MODEM_HDR_SIZE 0x0140 /* 320 */ ++#define IPA_V2_MODEM_ZIP_OFST 0x0510 ++#define IPA_V2_MODEM_ZIP_SIZE 0x0200 /* 512 */ ++#define IPA_V2_MODEM_MEM_OFST 0x0714 ++#define IPA_V2_MODEM_MEM_SIZE 0x18e8 /* 6376, ends at 0x1ffc */ ++#define IPA_V2_CANARY_VAL 0xdeadbeefU ++ ++/* Immediate command opcodes on Pipe 3 / Pipe 4 */ ++#define IPA_V2_IMM_V4_FLT_INIT 3 ++#define IPA_V2_IMM_V6_FLT_INIT 4 ++#define IPA_V2_IMM_V4_RT_INIT 7 ++#define IPA_V2_IMM_V6_RT_INIT 8 ++#define IPA_V2_IMM_HDR_INIT_LOCAL 9 ++#define IPA_V2_IMM_HDR_INIT_SYSTEM 10 ++#define IPA_V2_IMM_REGISTER_WRITE 12 ++#define IPA_V2_IMM_PKT_INIT 16 ++#define IPA_V2_IMM_DMA_SHARED_MEM 19 ++ ++/* SDM660 IPA v2.6L endpoint/pipe indices */ ++#define IPA_V2_PIPE_LAN_CONS 2 /* IPA -> AP exception drain */ ++#define IPA_V2_PIPE_CMD_PROD 3 /* AP -> IPA immediate commands */ ++#define IPA_V2_PIPE_WAN_PROD 4 /* AP -> IPA WWAN QMAP TX */ ++#define IPA_V2_PIPE_WAN_CONS 5 /* IPA -> AP WWAN QMAP RX */ ++#define IPA_V2_PIPE_Q6_LAN_CONS 8 /* IPA -> Q6 QMAP control */ ++ ++/* BAM NDP MMIO register offsets (base 0x14784000) */ ++#define BAM_CTRL 0x0000 ++#define BAM_CTRL_EN BIT(1) ++#define BAM_CTRL_LOCAL_CLK_GATING 0x60000U ++#define BAM_DESC_CNT_TRSHLD 0x0008 ++#define BAM_IRQ_STTS 0x0014 ++#define BAM_IRQ_CLR 0x001c ++#define BAM_CNFG_BITS 0x007c ++#define BAM_CNFG_DEFAULT 0xfffff7ffU ++#define BAM_IRQ_SRCS_EE0 0x3000 ++#define BAM_IRQ_SRCS_MSK_EE0 0x3004 ++#define BAM_PIPE_CTRL(n) (0x13000 + (n) * 0x1000) ++#define BAM_PIPE_RST(n) (0x13004 + (n) * 0x1000) ++#define BAM_PIPE_IRQ_STTS(n) (0x13010 + (n) * 0x1000) ++#define BAM_PIPE_IRQ_CLR(n) (0x13014 + (n) * 0x1000) ++#define BAM_PIPE_IRQ_EN(n) (0x13018 + (n) * 0x1000) ++#define BAM_PIPE_SW_OFST(n) (0x13800 + (n) * 0x1000) ++#define BAM_PIPE_EVNT_REG(n) (0x13818 + (n) * 0x1000) ++#define BAM_PIPE_DESC_FIFO_ADDR(n) (0x1381c + (n) * 0x1000) ++#define BAM_PIPE_FIFO_SIZES(n) (0x13820 + (n) * 0x1000) ++#define BAM_PIPE_EVNT_GEN_TRSHLD(n) (0x13828 + (n) * 0x1000) ++ ++#define BAM_PIPE_CTRL_EN BIT(1) ++#define BAM_PIPE_CTRL_DIR_PROD BIT(3) /* BAM producer: IPA -> DDR */ ++#define BAM_PIPE_CTRL_SYS_MODE BIT(5) ++ ++#define BAM_P_IRQ_PRCSD_DESC BIT(0) ++#define BAM_P_IRQ_OUT_OF_DESC BIT(3) ++#define BAM_P_IRQ_ERR BIT(4) ++#define BAM_P_IRQ_TRNSFR_END BIT(5) ++#define BAM_P_IRQ_RST_ERR BIT(6) ++#define BAM_P_IRQ_HRESP_ERR BIT(7) ++#define BAM_P_IRQ_ERRORS (BAM_P_IRQ_ERR | BAM_P_IRQ_RST_ERR | \ ++ BAM_P_IRQ_HRESP_ERR) ++#define BAM_P_IRQ_DATA_MASK (BAM_P_IRQ_TRNSFR_END | \ ++ BAM_P_IRQ_PRCSD_DESC | \ ++ BAM_P_IRQ_ERRORS) ++ ++/* BAM 8-byte hardware descriptor flags */ ++#define BAM_DESC_FLAG_IMME 0x0100 ++#define BAM_DESC_FLAG_EOT 0x4000 ++#define BAM_DESC_FLAG_INT 0x8000 ++ ++/* Ring and buffer geometry */ ++#define IPA_V2_CMD_RING_COUNT 64 ++#define IPA_V2_LAN_RX_RING_COUNT 32 ++#define IPA_V2_LAN_RX_BUF_SZ 2048 ++#define IPA_V2_TX_SLOT_COUNT 64 ++#define IPA_V2_TX_RING_COUNT 128 /* up to 2 descs per TX slot */ ++#define IPA_V2_TX_BUF_SZ 4096 ++#define IPA_V2_RX_RING_COUNT 64 ++#define IPA_V2_RX_BUF_SZ 4096 ++ ++#define IPA_V2_SVS_CLK_RATE 75000000UL ++#define IPA_V2_ICC_MEM_AVG_BW 80000 ++#define IPA_V2_ICC_MEM_PEAK_BW 640000 ++#define IPA_V2_ICC_CFG_AVG_BW 80000 ++#define IPA_V2_ICC_CFG_PEAK_BW 80000 ++ ++/* QMI service 0x31 protocol constants */ ++#define IPA_V2_QMI_SVC_ID 0x31 ++#define IPA_V2_QMI_SVC_VER 1 ++#define IPA_V2_QMI_HOST_INS_ID 1 ++#define IPA_V2_QMI_MODEM_INS_ID 2 ++#define IPA_V2_QMI_RECV_BUF_SZ 24576 ++#define IPA_V2_QMI_INSTALL_FLT_REQ 0x0023 ++#define IPA_V2_QMI_INSTALL_FLT_RSP 0x0023 ++#define IPA_V2_QMI_FLT_NOTIF_REQ 0x0024 ++#define IPA_V2_QMI_FLT_NOTIF_RSP 0x0024 ++#define IPA_V2_QMI_CONFIG_REQ 0x0027 ++#define IPA_V2_QMI_CONFIG_RSP 0x0027 ++#define IPA_V2_QMI_MAX_FILTERS 64 ++#define IPA_V2_UL_FLT_HDL_BASE 69 ++ ++struct ipa_v2_bam_desc { ++ __le32 addr; ++ __le16 size; ++ __le16 flags; ++}; ++ ++struct ipa_v2_cmd_dma_shared_mem { ++ __le32 size; ++ __le32 system_addr; ++ __le32 local_dir; ++ __le32 padding; ++}; ++ ++struct ipa_v2_cmd_hdr_init_local { ++ __le32 hdr_table_src_addr; ++ __le32 size_dst; ++}; ++ ++struct ipa_v2_cmd_hdr_init_system { ++ __le32 hdr_table_addr; ++ __le32 reserved; ++}; ++ ++struct ipa_v2_cmd_rt_flt_v4_init { ++ __le32 rules_addr; ++ __le32 size_addr; ++}; ++ ++struct ipa_v2_cmd_rt_flt_v6_init { ++ __le32 rules_addr; ++ __le32 size_addr; ++}; ++ ++struct ipa_v2_cmd_pkt_init { ++ u8 dst_pipe; ++ u8 metadata[4]; ++ u8 reserved[3]; ++}; ++ ++struct ipa_v2_cmd_reg_write { ++ __le32 flags_offset; ++ __le32 value; ++ __le32 value_mask; ++}; ++ ++/* ++ * Persistent 128-byte-aligned table & command arena mapped in ANOC2 SMMU. ++ * IPA v2.6L requires 128-byte alignment on DDR routing/filter rule lists. ++ */ ++struct ipa_v2_tables { ++ u8 sys_hdr[2048] __aligned(128); ++ __le32 empty_rule[32] __aligned(128); ++ __le32 lan_dflt_rt[32] __aligned(128); ++ __le32 wan_dflt_rt[32] __aligned(128); ++ __le32 rt4_init[32] __aligned(128); ++ __le32 rt6_init[32] __aligned(128); ++ __le32 flt4_init[32] __aligned(128); ++ __le32 flt6_init[32] __aligned(128); ++ __le32 glob_flt4[32] __aligned(128); ++ __le32 glob_flt6[32] __aligned(128); ++ u8 zero_buf[2048] __aligned(128); ++ u8 cmd_pyld[128] __aligned(128); ++ struct ipa_v2_cmd_pkt_init pkt_init[IPA_V2_TX_SLOT_COUNT] __aligned(128); ++}; ++ ++/* Minimal wire-exact QMI 0x0023 / 0x0024 / 0x0027 structures */ ++struct ipa_v2_qmi_flt_spec { ++ u32 filter_spec_identifier; ++ s32 ip_type; ++ u8 filter_rule_raw[150]; ++ s32 filter_action; ++ u8 is_routing_table_index_valid; ++ u32 route_table_index; ++ u8 is_mux_id_valid; ++ u32 mux_id; ++}; ++ ++struct ipa_v2_qmi_flt_hdl_map { ++ u32 filter_spec_identifier; ++ u32 filter_handle; ++}; ++ ++struct ipa_v2_qmi_install_flt_req { ++ u8 filter_spec_list_valid; ++ u32 filter_spec_list_len; ++ struct ipa_v2_qmi_flt_spec filter_spec_list[IPA_V2_QMI_MAX_FILTERS]; ++}; ++ ++struct ipa_v2_qmi_install_flt_rsp { ++ struct qmi_response_type_v01 rsp; ++ u8 filter_handle_list_valid; ++ u32 filter_handle_list_len; ++ struct ipa_v2_qmi_flt_hdl_map filter_handle_list[IPA_V2_QMI_MAX_FILTERS]; ++}; ++ ++struct ipa_v2_qmi_simple_req { ++ u8 placeholder; ++}; ++ ++struct ipa_v2_qmi_simple_rsp { ++ struct qmi_response_type_v01 rsp; ++}; ++ ++struct ipa_v2_tx_meta { ++ u16 desc_count; ++ u32 byte_len; ++ bool is_data; ++}; ++ ++struct ipa_v2_bam { ++ struct ipa *ipa; ++ struct device *dev; ++ void __iomem *ipa_reg; ++ void __iomem *bam_reg; ++ int bam_irq; ++ ++ struct clk *core_clk; ++ struct icc_path *icc_mem; ++ struct icc_path *icc_cfg; ++ ++ struct ipa_v2_tables *tables; ++ dma_addr_t tables_dma; ++ ++ /* Pipe 3: AP immediate commands (polled) */ ++ struct mutex cmd_lock; ++ struct ipa_v2_bam_desc *cmd_ring; ++ dma_addr_t cmd_ring_dma; ++ u32 cmd_tail; ++ ++ /* Pipe 2: LAN/exception RX drain */ ++ struct ipa_v2_bam_desc *lan_ring; ++ dma_addr_t lan_ring_dma; ++ u8 *lan_bufs; ++ dma_addr_t lan_bufs_dma; ++ u32 lan_head; ++ u32 lan_tail; ++ u64 lan_rx_pkts; ++ u16 last_lan_len; ++ u8 last_lan_pkt[32]; ++ ++ /* Pipe 4: WWAN QMAP TX */ ++ spinlock_t tx_lock; ++ struct ipa_v2_bam_desc *tx_ring; ++ dma_addr_t tx_ring_dma; ++ u8 *tx_bufs; ++ dma_addr_t tx_bufs_dma; ++ struct ipa_v2_tx_meta tx_slot_meta[IPA_V2_TX_SLOT_COUNT]; ++ u32 tx_desc_head; ++ u32 tx_desc_tail; ++ u32 tx_slot_head; ++ u32 tx_slot_tail; ++ u32 tx_slots_used; ++ struct work_struct ul_flush_work; ++ u64 ul_flushes; ++ ++ /* Pipe 5: WWAN QMAP RX */ ++ struct ipa_v2_bam_desc *rx_ring; ++ dma_addr_t rx_ring_dma; ++ u8 *rx_bufs; ++ dma_addr_t rx_bufs_dma; ++ u32 rx_head; ++ u32 rx_tail; ++ ++ /* Netdev & NAPI */ ++ struct net_device *netdev; ++ struct napi_struct napi; ++ ++ /* QMI service & client state */ ++ struct mutex qmi_lock; ++ struct qmi_handle server_handle; ++ struct qmi_handle client_handle; ++ struct sockaddr_qrtr modem_sq; ++ struct sockaddr_qrtr ind_client_sq; ++ struct work_struct init_driver_work; ++ bool modem_server_up; ++ bool modem_init_fin; ++ bool indication_fin; ++ bool indication_sent; ++ bool init_pending_stage2; ++ bool uc_init_complete_rcvd; ++ bool uc_loaded; ++ bool ssr_needs_reinit; ++ atomic_t datapath_ready; ++ atomic_t shutting_down; ++}; ++ ++struct ipa_v2_netdev_priv { ++ struct ipa_v2_bam *v2; ++}; ++ ++static const u16 ipa_v2_canary_offsets[] = { ++ 0x0280, 0x0284, ++ 0x02e0, 0x02e4, ++ 0x0340, 0x0344, ++ 0x0384, ++ 0x03c4, ++ 0x0508, 0x050c, ++ 0x0710, ++ 0x1ffc, ++}; ++ ++/* QMI element info definitions for 0x0023, 0x0024, 0x0027 */ ++static const struct qmi_elem_info ipa_v2_qmi_flt_spec_ei[] = { ++ { ++ .data_type = QMI_UNSIGNED_4_BYTE, ++ .elem_len = 1, ++ .elem_size = sizeof(u32), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ filter_spec_identifier), ++ }, ++ { ++ .data_type = QMI_SIGNED_4_BYTE_ENUM, ++ .elem_len = 1, ++ .elem_size = sizeof(s32), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ ip_type), ++ }, ++ { ++ .data_type = QMI_UNSIGNED_1_BYTE, ++ .elem_len = 150, ++ .elem_size = sizeof(u8), ++ .array_type = STATIC_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ filter_rule_raw), ++ }, ++ { ++ .data_type = QMI_SIGNED_4_BYTE_ENUM, ++ .elem_len = 1, ++ .elem_size = sizeof(s32), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ filter_action), ++ }, ++ { ++ .data_type = QMI_UNSIGNED_1_BYTE, ++ .elem_len = 1, ++ .elem_size = sizeof(u8), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ is_routing_table_index_valid), ++ }, ++ { ++ .data_type = QMI_UNSIGNED_4_BYTE, ++ .elem_len = 1, ++ .elem_size = sizeof(u32), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ route_table_index), ++ }, ++ { ++ .data_type = QMI_UNSIGNED_1_BYTE, ++ .elem_len = 1, ++ .elem_size = sizeof(u8), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ is_mux_id_valid), ++ }, ++ { ++ .data_type = QMI_UNSIGNED_4_BYTE, ++ .elem_len = 1, ++ .elem_size = sizeof(u32), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_spec, ++ mux_id), ++ }, ++ { ++ .data_type = QMI_EOTI, ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ }, ++}; ++ ++static const struct qmi_elem_info ipa_v2_qmi_flt_hdl_map_ei[] = { ++ { ++ .data_type = QMI_UNSIGNED_4_BYTE, ++ .elem_len = 1, ++ .elem_size = sizeof(u32), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_hdl_map, ++ filter_spec_identifier), ++ }, ++ { ++ .data_type = QMI_UNSIGNED_4_BYTE, ++ .elem_len = 1, ++ .elem_size = sizeof(u32), ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ .offset = offsetof(struct ipa_v2_qmi_flt_hdl_map, ++ filter_handle), ++ }, ++ { ++ .data_type = QMI_EOTI, ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ }, ++}; ++ ++static const struct qmi_elem_info ipa_v2_qmi_install_flt_req_ei[] = { ++ { ++ .data_type = QMI_OPT_FLAG, ++ .elem_len = 1, ++ .elem_size = sizeof(u8), ++ .array_type = NO_ARRAY, ++ .tlv_type = 0x10, ++ .offset = offsetof(struct ipa_v2_qmi_install_flt_req, ++ filter_spec_list_valid), ++ }, ++ { ++ .data_type = QMI_DATA_LEN, ++ .elem_len = 1, ++ .elem_size = sizeof(u8), ++ .array_type = NO_ARRAY, ++ .tlv_type = 0x10, ++ .offset = offsetof(struct ipa_v2_qmi_install_flt_req, ++ filter_spec_list_len), ++ }, ++ { ++ .data_type = QMI_STRUCT, ++ .elem_len = IPA_V2_QMI_MAX_FILTERS, ++ .elem_size = sizeof(struct ipa_v2_qmi_flt_spec), ++ .array_type = VAR_LEN_ARRAY, ++ .tlv_type = 0x10, ++ .offset = offsetof(struct ipa_v2_qmi_install_flt_req, ++ filter_spec_list), ++ .ei_array = ipa_v2_qmi_flt_spec_ei, ++ }, ++ { ++ .data_type = QMI_EOTI, ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ }, ++}; ++ ++static const struct qmi_elem_info ipa_v2_qmi_install_flt_rsp_ei[] = { ++ { ++ .data_type = QMI_STRUCT, ++ .elem_len = 1, ++ .elem_size = sizeof(struct qmi_response_type_v01), ++ .array_type = NO_ARRAY, ++ .tlv_type = 0x02, ++ .offset = offsetof(struct ipa_v2_qmi_install_flt_rsp, ++ rsp), ++ .ei_array = qmi_response_type_v01_ei, ++ }, ++ { ++ .data_type = QMI_OPT_FLAG, ++ .elem_len = 1, ++ .elem_size = sizeof(u8), ++ .array_type = NO_ARRAY, ++ .tlv_type = 0x10, ++ .offset = offsetof(struct ipa_v2_qmi_install_flt_rsp, ++ filter_handle_list_valid), ++ }, ++ { ++ .data_type = QMI_DATA_LEN, ++ .elem_len = 1, ++ .elem_size = sizeof(u8), ++ .array_type = NO_ARRAY, ++ .tlv_type = 0x10, ++ .offset = offsetof(struct ipa_v2_qmi_install_flt_rsp, ++ filter_handle_list_len), ++ }, ++ { ++ .data_type = QMI_STRUCT, ++ .elem_len = IPA_V2_QMI_MAX_FILTERS, ++ .elem_size = sizeof(struct ipa_v2_qmi_flt_hdl_map), ++ .array_type = VAR_LEN_ARRAY, ++ .tlv_type = 0x10, ++ .offset = offsetof(struct ipa_v2_qmi_install_flt_rsp, ++ filter_handle_list), ++ .ei_array = ipa_v2_qmi_flt_hdl_map_ei, ++ }, ++ { ++ .data_type = QMI_EOTI, ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ }, ++}; ++ ++static const struct qmi_elem_info ipa_v2_qmi_simple_req_ei[] = { ++ { ++ .data_type = QMI_EOTI, ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ }, ++}; ++ ++static const struct qmi_elem_info ipa_v2_qmi_simple_rsp_ei[] = { ++ { ++ .data_type = QMI_STRUCT, ++ .elem_len = 1, ++ .elem_size = sizeof(struct qmi_response_type_v01), ++ .array_type = NO_ARRAY, ++ .tlv_type = 0x02, ++ .offset = offsetof(struct ipa_v2_qmi_simple_rsp, rsp), ++ .ei_array = qmi_response_type_v01_ei, ++ }, ++ { ++ .data_type = QMI_EOTI, ++ .array_type = NO_ARRAY, ++ .tlv_type = QMI_COMMON_TLV_TYPE, ++ }, ++}; ++ ++static inline dma_addr_t ipa_v2_tbl_dma(struct ipa_v2_bam *v2, const void *ptr) ++{ ++ return v2->tables_dma + ((const u8 *)ptr - (const u8 *)v2->tables); ++} ++ ++bool ipa_v2_bam_datapath_ready(struct ipa *ipa) ++{ ++ if (!ipa || !ipa->v2_bam) ++ return false; ++ ++ return atomic_read(&ipa->v2_bam->datapath_ready) != 0; ++} ++ ++static void ipa_v2_bam_reset_pipe(struct ipa_v2_bam *v2, u32 pipe) ++{ ++ writel(0, v2->bam_reg + BAM_PIPE_CTRL(pipe)); ++ writel(1, v2->bam_reg + BAM_PIPE_RST(pipe)); ++ wmb(); ++ udelay(10); ++ writel(0, v2->bam_reg + BAM_PIPE_RST(pipe)); ++ wmb(); ++} ++ ++/* Submit one immediate command on BAM Pipe 3 and poll for completion. */ ++static int ipa_v2_send_imm_cmd(struct ipa_v2_bam *v2, u16 opcode, ++ const void *payload, u32 len) ++{ ++ struct ipa_v2_bam_desc *desc; ++ dma_addr_t pyld_dma; ++ unsigned long timeout; ++ u32 next_tail, target_off, sw_off, p_stts, ipa_irq; ++ int ret = -ETIMEDOUT; ++ ++ if (len > sizeof(v2->tables->cmd_pyld)) ++ return -EINVAL; ++ ++ mutex_lock(&v2->cmd_lock); ++ ++ /* Clear any stale status bits before submitting. */ ++ writel( ~0U, v2->bam_reg + BAM_PIPE_IRQ_CLR(IPA_V2_PIPE_CMD_PROD)); ++ writel(IPA_V2_PROC_ERR_IRQ, v2->ipa_reg + IPA_V2_IRQ_CLR_EE0); ++ ++ memcpy(v2->tables->cmd_pyld, payload, len); ++ pyld_dma = ipa_v2_tbl_dma(v2, v2->tables->cmd_pyld); ++ ++ desc = &v2->cmd_ring[v2->cmd_tail]; ++ desc->addr = cpu_to_le32((u32)pyld_dma); ++ desc->size = cpu_to_le16(opcode); ++ desc->flags = cpu_to_le16(BAM_DESC_FLAG_EOT | BAM_DESC_FLAG_IMME); ++ ++ next_tail = (v2->cmd_tail + 1) % IPA_V2_CMD_RING_COUNT; ++ target_off = next_tail * sizeof(*desc); ++ v2->cmd_tail = next_tail; ++ ++ dma_wmb(); ++ writel(target_off, v2->bam_reg + BAM_PIPE_EVNT_REG(IPA_V2_PIPE_CMD_PROD)); ++ ++ timeout = jiffies + msecs_to_jiffies(500); ++ do { ++ sw_off = readl(v2->bam_reg + BAM_PIPE_SW_OFST(IPA_V2_PIPE_CMD_PROD)) & 0xffff; ++ p_stts = readl(v2->bam_reg + BAM_PIPE_IRQ_STTS(IPA_V2_PIPE_CMD_PROD)); ++ if (p_stts & BAM_P_IRQ_ERRORS) { ++ dev_err(v2->dev, "pipe 3 BAM error stts=%#x opcode=%u\n", ++ p_stts, opcode); ++ ret = -EIO; ++ break; ++ } ++ if (sw_off == target_off && (p_stts & BAM_P_IRQ_TRNSFR_END)) { ++ ret = 0; ++ break; ++ } ++ usleep_range(50, 100); ++ } while (time_before(jiffies, timeout)); ++ ++ writel(p_stts, v2->bam_reg + BAM_PIPE_IRQ_CLR(IPA_V2_PIPE_CMD_PROD)); ++ ++ if (!ret) { ++ /* Allow IPA command processor a few cycles to retire DMA. */ ++ udelay(5); ++ ipa_irq = readl(v2->ipa_reg + IPA_V2_IRQ_STTS_EE0); ++ if (ipa_irq & IPA_V2_PROC_ERR_IRQ) { ++ writel(IPA_V2_PROC_ERR_IRQ, ++ v2->ipa_reg + IPA_V2_IRQ_CLR_EE0); ++ dev_err(v2->dev, "IPA_PROC_ERR_IRQ on opcode=%u irq=%#x\n", ++ opcode, ipa_irq); ++ ret = -EIO; ++ } ++ } ++ ++ mutex_unlock(&v2->cmd_lock); ++ return ret; ++} ++ ++static int ipa_v2_dma_write_sram(struct ipa_v2_bam *v2, dma_addr_t src_dma, ++ u16 sram_off, u16 len) ++{ ++ struct ipa_v2_cmd_dma_shared_mem cmd = { ++ .size = cpu_to_le32((u32)len << 16), ++ .system_addr = cpu_to_le32((u32)src_dma), ++ .local_dir = cpu_to_le32((u32)sram_off), ++ .padding = 0, ++ }; ++ ++ if ((u32)sram_off + len > IPA_V2_SRAM_SIZE - sizeof(u32)) ++ return -ERANGE; ++ ++ return ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_DMA_SHARED_MEM, ++ &cmd, sizeof(cmd)); ++} ++ ++static int ipa_v2_zero_sram_range(struct ipa_v2_bam *v2, u16 offset, u16 total_len) ++{ ++ dma_addr_t zero_dma = ipa_v2_tbl_dma(v2, v2->tables->zero_buf); ++ u16 done = 0; ++ int ret; ++ ++ while (done < total_len) { ++ u16 chunk = min_t(u16, total_len - done, ++ sizeof(v2->tables->zero_buf)); ++ ++ ret = ipa_v2_dma_write_sram(v2, zero_dma, offset + done, chunk); ++ if (ret) ++ return ret; ++ done += chunk; ++ } ++ ++ return 0; ++} ++ ++static int ipa_v2_zero_modem_sram(struct ipa_v2_bam *v2) ++{ ++ int ret; ++ ++ ret = ipa_v2_zero_sram_range(v2, IPA_V2_MODEM_HDR_OFST, ++ IPA_V2_MODEM_HDR_SIZE); ++ if (ret) ++ return ret; ++ ++ ret = ipa_v2_zero_sram_range(v2, IPA_V2_MODEM_ZIP_OFST, ++ IPA_V2_MODEM_ZIP_SIZE); ++ if (ret) ++ return ret; ++ ++ return ipa_v2_zero_sram_range(v2, IPA_V2_MODEM_MEM_OFST, ++ IPA_V2_MODEM_MEM_SIZE); ++} ++ ++static int ipa_v2_init_hw_and_tables(struct ipa_v2_bam *v2) ++{ ++ struct ipa_v2_cmd_hdr_init_local hdr_lcl; ++ struct ipa_v2_cmd_hdr_init_system hdr_sys; ++ struct ipa_v2_cmd_rt_flt_v4_init v4_cmd; ++ struct ipa_v2_cmd_rt_flt_v6_init v6_cmd; ++ dma_addr_t empty_dma, lan_rt_dma, wan_rt_dma; ++ u32 hw_ver, smem_sz, bam_ctrl, route_reg; ++ unsigned int i; ++ int ret; ++ ++ hw_ver = readl(v2->ipa_reg + IPA_V2_COMP_HW_VERSION); ++ smem_sz = readl(v2->ipa_reg + IPA_V2_SHARED_MEM_SIZE); ++ if (hw_ver != IPA_V2_HW_VERSION_2_6L || smem_sz != IPA_V2_SRAM_SIZE) { ++ dev_err(v2->dev, "unexpected IPA hw_ver=%#x smem_sz=%#x\n", ++ hw_ver, smem_sz); ++ return -ENODEV; ++ } ++ ++ /* Configure global IPA registers without asserting global SW reset. */ ++ writel(IPA_V2_BCR_VAL, v2->ipa_reg + IPA_V2_BCR); ++ writel(IPA_V2_COMP_CFG_VAL, v2->ipa_reg + IPA_V2_COMP_CFG); ++ writel(IPA_V2_COUNTER_CFG_VAL, v2->ipa_reg + IPA_V2_COUNTER_CFG); ++ ++ /* Default route -> Pipe 2 (APPS_LAN_CONS), system header table, offset 0. */ ++ route_reg = (IPA_V2_PIPE_LAN_CONS << 1) | BIT(6) | ++ (IPA_V2_PIPE_LAN_CONS << 17); ++ writel(route_reg, v2->ipa_reg + IPA_V2_ROUTE); ++ writel(0, v2->ipa_reg + IPA_V2_FILTER); /* FILTER_DIS = 0 */ ++ ++ /* Ensure BAM controller is enabled; never pulse global BAM reset. */ ++ bam_ctrl = readl(v2->bam_reg + BAM_CTRL); ++ if (!(bam_ctrl & BAM_CTRL_EN)) { ++ writel(BAM_CTRL_LOCAL_CLK_GATING | BAM_CTRL_EN, ++ v2->bam_reg + BAM_CTRL); ++ writel(0x10, v2->bam_reg + BAM_DESC_CNT_TRSHLD); ++ writel(BAM_CNFG_DEFAULT, v2->bam_reg + BAM_CNFG_BITS); ++ } ++ ++ /* Keep Pipe 3 out of EE0 IRQ mask so immediate commands stay polled. */ ++ writel(readl(v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0) & ++ ~(BIT(IPA_V2_PIPE_LAN_CONS) | BIT(IPA_V2_PIPE_CMD_PROD) | ++ BIT(IPA_V2_PIPE_WAN_PROD) | BIT(IPA_V2_PIPE_WAN_CONS)), ++ v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0); ++ ++ /* Set up BAM Pipe 3 (APPS_CMD_PROD). */ ++ v2->cmd_tail = 0; ++ memset(v2->cmd_ring, 0, ++ IPA_V2_CMD_RING_COUNT * sizeof(*v2->cmd_ring)); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_CMD_PROD); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_CTRL(IPA_V2_PIPE_CMD_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_NAT(IPA_V2_PIPE_CMD_PROD)); ++ writel(2U | (IPA_V2_PIPE_LAN_CONS << 4), ++ v2->ipa_reg + IPA_V2_ENDP_INIT_MODE(IPA_V2_PIPE_CMD_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_AGGR(IPA_V2_PIPE_CMD_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_DEAGGR(IPA_V2_PIPE_CMD_PROD)); ++ writel((u32)v2->cmd_ring_dma, ++ v2->bam_reg + BAM_PIPE_DESC_FIFO_ADDR(IPA_V2_PIPE_CMD_PROD)); ++ writel(IPA_V2_CMD_RING_COUNT * sizeof(*v2->cmd_ring), ++ v2->bam_reg + BAM_PIPE_FIFO_SIZES(IPA_V2_PIPE_CMD_PROD)); ++ writel(16, v2->bam_reg + BAM_PIPE_EVNT_GEN_TRSHLD(IPA_V2_PIPE_CMD_PROD)); ++ writel(BAM_P_IRQ_TRNSFR_END | BAM_P_IRQ_ERRORS, ++ v2->bam_reg + BAM_PIPE_IRQ_EN(IPA_V2_PIPE_CMD_PROD)); ++ dma_wmb(); ++ writel(BAM_PIPE_CTRL_SYS_MODE | BAM_PIPE_CTRL_EN, ++ v2->bam_reg + BAM_PIPE_CTRL(IPA_V2_PIPE_CMD_PROD)); ++ ++ /* Stamp SRAM canary words at v2.6L partition boundaries. */ ++ for (i = 0; i < ARRAY_SIZE(ipa_v2_canary_offsets); i++) ++ writel(IPA_V2_CANARY_VAL, ++ v2->ipa_reg + IPA_V2_SRAM_BASE + ipa_v2_canary_offsets[i]); ++ ++ /* Zero modem SRAM blocks before QMI handshake. */ ++ ret = ipa_v2_zero_modem_sram(v2); ++ if (ret) ++ return ret; ++ ++ /* Build coherent DDR routing & filter structures (128-byte aligned). */ ++ empty_dma = ipa_v2_tbl_dma(v2, v2->tables->empty_rule); ++ lan_rt_dma = ipa_v2_tbl_dma(v2, v2->tables->lan_dflt_rt); ++ wan_rt_dma = ipa_v2_tbl_dma(v2, v2->tables->wan_dflt_rt); ++ ++ /* Catch-all LAN default route -> Pipe 2, system hdr offset 0 */ ++ v2->tables->lan_dflt_rt[0] = ++ cpu_to_le32((IPA_V2_PIPE_LAN_CONS << 16) | BIT(21)); ++ v2->tables->lan_dflt_rt[1] = 0; ++ ++ /* Catch-all WAN default route -> Pipe 5, system hdr offset 2 (8B) */ ++ v2->tables->wan_dflt_rt[0] = ++ cpu_to_le32((IPA_V2_PIPE_WAN_CONS << 16) | BIT(21) | (2U << 22)); ++ v2->tables->wan_dflt_rt[1] = 0; ++ ++ for (i = 0; i < 15; i++) { ++ u32 addr = (u32)empty_dma; ++ ++ if (i == 7) ++ addr = (u32)lan_rt_dma; ++ else if (i == 8) ++ addr = (u32)wan_rt_dma; ++ v2->tables->rt4_init[i] = cpu_to_le32(addr); ++ v2->tables->rt6_init[i] = cpu_to_le32(addr); ++ } ++ ++ /* ++ * Workaround for IPA v2 global filter erratum: keep a non-empty dummy ++ * global filter rule that always misses so hardware evaluates per-pipe ++ * filter rules (including Pipe 4 UL and Pipe 6 DL rules). ++ */ ++ v2->tables->glob_flt4[0] = cpu_to_le32((7U << 21) | BIT(26) | 0x0006U); ++ v2->tables->glob_flt4[1] = cpu_to_le32(0x000000ffU); ++ v2->tables->glob_flt4[2] = cpu_to_le32(0xffffff10U); ++ v2->tables->glob_flt4[3] = cpu_to_le32(0xffffffffU); ++ v2->tables->glob_flt4[4] = cpu_to_le32(0x000000ffU); ++ v2->tables->glob_flt4[5] = 0; ++ ++ v2->tables->glob_flt6[0] = cpu_to_le32((7U << 21) | BIT(26) | 0x0202U); ++ v2->tables->glob_flt6[1] = cpu_to_le32(0x000000ffU); ++ v2->tables->glob_flt6[2] = cpu_to_le32(0xffffff18U); ++ for (i = 3; i <= 9; i++) ++ v2->tables->glob_flt6[i] = cpu_to_le32(0xffffffffU); ++ v2->tables->glob_flt6[10] = cpu_to_le32(0x000000ffU); ++ v2->tables->glob_flt6[11] = 0; ++ ++ /* v2.6L filter header: 20-pipe bitmap (0xFFFFF << 1) | DDR bit0 (1) */ ++ v2->tables->flt4_init[0] = cpu_to_le32((0xfffffU << 1) | 0x1U); ++ v2->tables->flt6_init[0] = cpu_to_le32((0xfffffU << 1) | 0x1U); ++ v2->tables->flt4_init[1] = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->glob_flt4)); ++ v2->tables->flt6_init[1] = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->glob_flt6)); ++ for (i = 2; i <= 21; i++) { ++ v2->tables->flt4_init[i] = cpu_to_le32((u32)empty_dma); ++ v2->tables->flt6_init[i] = cpu_to_le32((u32)empty_dma); ++ } ++ v2->tables->sys_hdr[8 + 1] = 1; ++ dma_wmb(); ++ ++ /* Initialize local (modem) and system (AP) header tables. */ ++ hdr_lcl.hdr_table_src_addr = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->zero_buf)); ++ hdr_lcl.size_dst = cpu_to_le32((IPA_V2_MODEM_HDR_SIZE & 0xfffU) | ++ (IPA_V2_MODEM_HDR_OFST << 12)); ++ ret = ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_HDR_INIT_LOCAL, ++ &hdr_lcl, sizeof(hdr_lcl)); ++ if (ret) ++ return ret; ++ ++ hdr_sys.hdr_table_addr = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->sys_hdr)); ++ hdr_sys.reserved = 0; ++ ret = ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_HDR_INIT_SYSTEM, ++ &hdr_sys, sizeof(hdr_sys)); ++ if (ret) ++ return ret; ++ ++ /* Initialize IPv4 & IPv6 routing tables. */ ++ v4_cmd.rules_addr = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->rt4_init)); ++ v4_cmd.size_addr = cpu_to_le32((IPA_V2_V4_RT_SIZE & 0xfffU) | ++ (IPA_V2_V4_RT_OFST << 12)); ++ ret = ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_V4_RT_INIT, ++ &v4_cmd, sizeof(v4_cmd)); ++ if (ret) ++ return ret; ++ ++ v6_cmd.rules_addr = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->rt6_init)); ++ v6_cmd.size_addr = cpu_to_le32((IPA_V2_V6_RT_SIZE & 0xffffU) | ++ (IPA_V2_V6_RT_OFST << 16)); ++ ret = ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_V6_RT_INIT, ++ &v6_cmd, sizeof(v6_cmd)); ++ if (ret) ++ return ret; ++ ++ /* Initialize IPv4 & IPv6 filter tables. */ ++ v4_cmd.rules_addr = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->flt4_init)); ++ v4_cmd.size_addr = cpu_to_le32((IPA_V2_V4_FLT_SIZE & 0xfffU) | ++ (IPA_V2_V4_FLT_OFST << 12)); ++ ret = ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_V4_FLT_INIT, ++ &v4_cmd, sizeof(v4_cmd)); ++ if (ret) ++ return ret; ++ ++ v6_cmd.rules_addr = ++ cpu_to_le32((u32)ipa_v2_tbl_dma(v2, v2->tables->flt6_init)); ++ v6_cmd.size_addr = cpu_to_le32((IPA_V2_V6_FLT_SIZE & 0xffffU) | ++ (IPA_V2_V6_FLT_OFST << 16)); ++ return ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_V6_FLT_INIT, ++ &v6_cmd, sizeof(v6_cmd)); ++} ++ ++static void ipa_v2_setup_data_pipes(struct ipa_v2_bam *v2) ++{ ++ unsigned int i; ++ u32 ee_mask; ++ ++ /* ++ * Pipe 2: APPS_LAN_CONS (IPA -> AP exception drain). ++ * Enable HOLB drop (timer=0, en=1) so unhandled exception frames can ++ * never back-pressure IPA internal pipelines. ++ */ ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_LAN_CONS); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_CTRL(IPA_V2_PIPE_LAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_CFG(IPA_V2_PIPE_LAN_CONS)); ++ writel(8, v2->ipa_reg + IPA_V2_ENDP_INIT_HDR(IPA_V2_PIPE_LAN_CONS)); ++ writel(BIT(0) | BIT(1) | (2U << 10), ++ v2->ipa_reg + IPA_V2_ENDP_INIT_HDR_EXT(IPA_V2_PIPE_LAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_AGGR(IPA_V2_PIPE_LAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_STATUS(IPA_V2_PIPE_LAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_HOLB_TMR(IPA_V2_PIPE_LAN_CONS)); ++ writel(1, v2->ipa_reg + IPA_V2_ENDP_INIT_HOLB_EN(IPA_V2_PIPE_LAN_CONS)); ++ ++ memset(v2->lan_ring, 0, ++ IPA_V2_LAN_RX_RING_COUNT * sizeof(*v2->lan_ring)); ++ for (i = 0; i < IPA_V2_LAN_RX_RING_COUNT; i++) { ++ v2->lan_ring[i].addr = ++ cpu_to_le32((u32)(v2->lan_bufs_dma + i * IPA_V2_LAN_RX_BUF_SZ)); ++ v2->lan_ring[i].size = cpu_to_le16(IPA_V2_LAN_RX_BUF_SZ); ++ v2->lan_ring[i].flags = cpu_to_le16(BAM_DESC_FLAG_INT); ++ } ++ v2->lan_head = 0; ++ v2->lan_tail = IPA_V2_LAN_RX_RING_COUNT - 1; ++ writel((u32)v2->lan_ring_dma, ++ v2->bam_reg + BAM_PIPE_DESC_FIFO_ADDR(IPA_V2_PIPE_LAN_CONS)); ++ writel(IPA_V2_LAN_RX_RING_COUNT * sizeof(*v2->lan_ring), ++ v2->bam_reg + BAM_PIPE_FIFO_SIZES(IPA_V2_PIPE_LAN_CONS)); ++ writel(16, v2->bam_reg + BAM_PIPE_EVNT_GEN_TRSHLD(IPA_V2_PIPE_LAN_CONS)); ++ writel(BAM_P_IRQ_DATA_MASK, ++ v2->bam_reg + BAM_PIPE_IRQ_EN(IPA_V2_PIPE_LAN_CONS)); ++ dma_wmb(); ++ writel(BAM_PIPE_CTRL_SYS_MODE | BAM_PIPE_CTRL_DIR_PROD | BAM_PIPE_CTRL_EN, ++ v2->bam_reg + BAM_PIPE_CTRL(IPA_V2_PIPE_LAN_CONS)); ++ writel(v2->lan_tail * sizeof(*v2->lan_ring), ++ v2->bam_reg + BAM_PIPE_EVNT_REG(IPA_V2_PIPE_LAN_CONS)); ++ ++ /* ++ * Pipe 4: APPS_LAN_WAN_PROD (AP -> IPA WWAN QMAP TX). ++ * 4-byte big-endian QMAP header, metadata at offset 0. ++ */ ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_WAN_PROD); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_CTRL(IPA_V2_PIPE_WAN_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_CFG(IPA_V2_PIPE_WAN_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_NAT(IPA_V2_PIPE_WAN_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_MODE(IPA_V2_PIPE_WAN_PROD)); ++ writel(4U | BIT(6), ++ v2->ipa_reg + IPA_V2_ENDP_INIT_HDR(IPA_V2_PIPE_WAN_PROD)); ++ writel(BIT(0), ++ v2->ipa_reg + IPA_V2_ENDP_INIT_HDR_EXT(IPA_V2_PIPE_WAN_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_AGGR(IPA_V2_PIPE_WAN_PROD)); ++ writel(7, v2->ipa_reg + IPA_V2_ENDP_INIT_ROUTE(IPA_V2_PIPE_WAN_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_DEAGGR(IPA_V2_PIPE_WAN_PROD)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_STATUS(IPA_V2_PIPE_WAN_PROD)); ++ ++ memset(v2->tx_ring, 0, IPA_V2_TX_RING_COUNT * sizeof(*v2->tx_ring)); ++ memset(v2->tx_slot_meta, 0, sizeof(v2->tx_slot_meta)); ++ v2->tx_desc_head = 0; ++ v2->tx_desc_tail = 0; ++ v2->tx_slot_head = 0; ++ v2->tx_slot_tail = 0; ++ v2->tx_slots_used = 0; ++ writel((u32)v2->tx_ring_dma, ++ v2->bam_reg + BAM_PIPE_DESC_FIFO_ADDR(IPA_V2_PIPE_WAN_PROD)); ++ writel(IPA_V2_TX_RING_COUNT * sizeof(*v2->tx_ring), ++ v2->bam_reg + BAM_PIPE_FIFO_SIZES(IPA_V2_PIPE_WAN_PROD)); ++ writel(16, v2->bam_reg + BAM_PIPE_EVNT_GEN_TRSHLD(IPA_V2_PIPE_WAN_PROD)); ++ writel(BAM_P_IRQ_DATA_MASK, ++ v2->bam_reg + BAM_PIPE_IRQ_EN(IPA_V2_PIPE_WAN_PROD)); ++ dma_wmb(); ++ writel(BAM_PIPE_CTRL_SYS_MODE | BAM_PIPE_CTRL_EN, ++ v2->bam_reg + BAM_PIPE_CTRL(IPA_V2_PIPE_WAN_PROD)); ++ ++ /* ++ * Pipe 5: APPS_WAN_CONS (IPA -> AP WWAN QMAP RX). ++ * 4-byte big-endian QMAP header (mux_id at byte 1, pkt_len at byte 2), ++ * IPA_BYPASS_AGGR single-frame QMAP delivery matching platina-o-oss. ++ */ ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_WAN_CONS); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_CTRL(IPA_V2_PIPE_WAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_CFG(IPA_V2_PIPE_WAN_CONS)); ++ writel(4U | BIT(6) | (1U << 7) | BIT(19) | (2U << 20), ++ v2->ipa_reg + IPA_V2_ENDP_INIT_HDR(IPA_V2_PIPE_WAN_CONS)); ++ writel(BIT(0) | BIT(1) | BIT(3), ++ v2->ipa_reg + IPA_V2_ENDP_INIT_HDR_EXT(IPA_V2_PIPE_WAN_CONS)); ++ writel(0xff000000U, ++ v2->ipa_reg + IPA_V2_ENDP_INIT_HDR_META_MSK(IPA_V2_PIPE_WAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_AGGR(IPA_V2_PIPE_WAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_STATUS(IPA_V2_PIPE_WAN_CONS)); ++ writel(32, v2->ipa_reg + IPA_V2_ENDP_INIT_HOLB_TMR(IPA_V2_PIPE_WAN_CONS)); ++ writel(0, v2->ipa_reg + IPA_V2_ENDP_INIT_HOLB_EN(IPA_V2_PIPE_WAN_CONS)); ++ ++ memset(v2->rx_ring, 0, IPA_V2_RX_RING_COUNT * sizeof(*v2->rx_ring)); ++ for (i = 0; i < IPA_V2_RX_RING_COUNT; i++) { ++ v2->rx_ring[i].addr = ++ cpu_to_le32((u32)(v2->rx_bufs_dma + i * IPA_V2_RX_BUF_SZ)); ++ v2->rx_ring[i].size = cpu_to_le16(IPA_V2_RX_BUF_SZ); ++ v2->rx_ring[i].flags = cpu_to_le16(BAM_DESC_FLAG_INT); ++ } ++ v2->rx_head = 0; ++ v2->rx_tail = IPA_V2_RX_RING_COUNT - 1; ++ writel((u32)v2->rx_ring_dma, ++ v2->bam_reg + BAM_PIPE_DESC_FIFO_ADDR(IPA_V2_PIPE_WAN_CONS)); ++ writel(IPA_V2_RX_RING_COUNT * sizeof(*v2->rx_ring), ++ v2->bam_reg + BAM_PIPE_FIFO_SIZES(IPA_V2_PIPE_WAN_CONS)); ++ writel(16, v2->bam_reg + BAM_PIPE_EVNT_GEN_TRSHLD(IPA_V2_PIPE_WAN_CONS)); ++ writel(BAM_P_IRQ_DATA_MASK, ++ v2->bam_reg + BAM_PIPE_IRQ_EN(IPA_V2_PIPE_WAN_CONS)); ++ dma_wmb(); ++ writel(BAM_PIPE_CTRL_SYS_MODE | BAM_PIPE_CTRL_DIR_PROD | BAM_PIPE_CTRL_EN, ++ v2->bam_reg + BAM_PIPE_CTRL(IPA_V2_PIPE_WAN_CONS)); ++ writel(v2->rx_tail * sizeof(*v2->rx_ring), ++ v2->bam_reg + BAM_PIPE_EVNT_REG(IPA_V2_PIPE_WAN_CONS)); ++ ++ /* Unmask BAM EE0 interrupts for Pipes 2, 4, and 5. */ ++ ee_mask = readl(v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0); ++ ee_mask &= ~BIT(IPA_V2_PIPE_CMD_PROD); ++ ee_mask |= BIT(IPA_V2_PIPE_LAN_CONS) | BIT(IPA_V2_PIPE_WAN_PROD) | ++ BIT(IPA_V2_PIPE_WAN_CONS); ++ writel(ee_mask, v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0); ++} ++ ++static void ipa_v2_drain_lan_rx(struct ipa_v2_bam *v2) ++{ ++ u32 sw_idx = (readl(v2->bam_reg + BAM_PIPE_SW_OFST(IPA_V2_PIPE_LAN_CONS)) & ++ 0xffff) / sizeof(struct ipa_v2_bam_desc); ++ bool moved = false; ++ ++ while (v2->lan_head != sw_idx) { ++ u32 slot = v2->lan_head; ++ u32 repost = v2->lan_tail; ++ u16 pkt_len; ++ ++ dma_rmb(); ++ pkt_len = le16_to_cpu(v2->lan_ring[slot].size); ++ v2->lan_rx_pkts++; ++ v2->last_lan_len = pkt_len; ++ memset(v2->last_lan_pkt, 0, sizeof(v2->last_lan_pkt)); ++ if (pkt_len > 0 && pkt_len <= IPA_V2_LAN_RX_BUF_SZ) { ++ memcpy(v2->last_lan_pkt, ++ v2->lan_bufs + slot * IPA_V2_LAN_RX_BUF_SZ, ++ min_t(u16, pkt_len, sizeof(v2->last_lan_pkt))); ++ } ++ ++ v2->lan_ring[repost].addr = ++ cpu_to_le32((u32)(v2->lan_bufs_dma + repost * IPA_V2_LAN_RX_BUF_SZ)); ++ v2->lan_ring[repost].size = cpu_to_le16(IPA_V2_LAN_RX_BUF_SZ); ++ v2->lan_ring[repost].flags = cpu_to_le16(BAM_DESC_FLAG_INT); ++ ++ v2->lan_head = (v2->lan_head + 1) % IPA_V2_LAN_RX_RING_COUNT; ++ v2->lan_tail = (v2->lan_tail + 1) % IPA_V2_LAN_RX_RING_COUNT; ++ moved = true; ++ } ++ ++ if (moved) { ++ dma_wmb(); ++ writel(v2->lan_tail * sizeof(struct ipa_v2_bam_desc), ++ v2->bam_reg + BAM_PIPE_EVNT_REG(IPA_V2_PIPE_LAN_CONS)); ++ } ++} ++ ++static inline u32 ipa_v2_ring_dist(u32 from, u32 to, u32 ring_sz) ++{ ++ return (to >= from) ? (to - from) : (ring_sz - from + to); ++} ++ ++static void ipa_v2_ul_flush_work(struct work_struct *work) ++{ ++ struct ipa_v2_bam *v2 = ++ container_of(work, struct ipa_v2_bam, ul_flush_work); ++ struct ipa_v2_cmd_reg_write cmd = { ++ .flags_offset = cpu_to_le32( ++ (u32)IPA_V2_ENDP_INIT_AGGR(IPA_V2_PIPE_Q6_LAN_CONS) << 16), ++ .value = cpu_to_le32(IPA_V2_AGGR_FORCE_CLOSE), ++ .value_mask = cpu_to_le32(IPA_V2_AGGR_FORCE_CLOSE), ++ }; ++ unsigned long deadline = jiffies + msecs_to_jiffies(100); ++ ++ if (atomic_read(&v2->shutting_down) || !atomic_read(&v2->datapath_ready)) ++ return; ++ ++ while (readl(v2->ipa_reg + IPA_V2_ENDP_INIT_CTRL(IPA_V2_PIPE_Q6_LAN_CONS)) & 1U) { ++ if (atomic_read(&v2->shutting_down) || ++ !atomic_read(&v2->datapath_ready) || ++ time_after(jiffies, deadline)) ++ return; ++ usleep_range(500, 1000); ++ } ++ ++ udelay(50); ++ ++ if (atomic_read(&v2->shutting_down) || !atomic_read(&v2->datapath_ready)) ++ return; ++ ++ if (!ipa_v2_send_imm_cmd(v2, IPA_V2_IMM_REGISTER_WRITE, &cmd, sizeof(cmd))) ++ v2->ul_flushes++; ++} ++ ++static void ipa_v2_reap_tx(struct ipa_v2_bam *v2) ++{ ++ unsigned long flags; ++ u32 sw_idx, avail; ++ bool wake = false; ++ bool reaped_data = false; ++ bool need_flush; ++ ++ spin_lock_irqsave(&v2->tx_lock, flags); ++ sw_idx = (readl(v2->bam_reg + BAM_PIPE_SW_OFST(IPA_V2_PIPE_WAN_PROD)) & ++ 0xffff) / sizeof(struct ipa_v2_bam_desc); ++ avail = ipa_v2_ring_dist(v2->tx_desc_head, sw_idx, IPA_V2_TX_RING_COUNT); ++ ++ while (v2->tx_slots_used > 0) { ++ struct ipa_v2_tx_meta *meta = &v2->tx_slot_meta[v2->tx_slot_head]; ++ ++ if (avail < meta->desc_count) ++ break; ++ ++ avail -= meta->desc_count; ++ v2->tx_desc_head = (v2->tx_desc_head + meta->desc_count) % ++ IPA_V2_TX_RING_COUNT; ++ v2->netdev->stats.tx_packets++; ++ v2->netdev->stats.tx_bytes += meta->byte_len; ++ if (meta->is_data) ++ reaped_data = true; ++ meta->desc_count = 0; ++ meta->byte_len = 0; ++ meta->is_data = false; ++ v2->tx_slot_head = (v2->tx_slot_head + 1) % IPA_V2_TX_SLOT_COUNT; ++ v2->tx_slots_used--; ++ wake = true; ++ } ++ ++ need_flush = reaped_data && v2->tx_slots_used == 0 && ++ atomic_read(&v2->datapath_ready) && ++ !atomic_read(&v2->shutting_down); ++ ++ if (wake && netif_queue_stopped(v2->netdev) && ++ v2->tx_slots_used <= (IPA_V2_TX_SLOT_COUNT / 2) && ++ atomic_read(&v2->datapath_ready)) ++ netif_wake_queue(v2->netdev); ++ ++ spin_unlock_irqrestore(&v2->tx_lock, flags); ++ ++ if (need_flush) ++ queue_work(system_highpri_wq, &v2->ul_flush_work); ++} ++ ++static int ipa_v2_poll(struct napi_struct *napi, int budget) ++{ ++ struct ipa_v2_bam *v2 = container_of(napi, struct ipa_v2_bam, napi); ++ int work_done = 0; ++ bool reposted = false; ++ u32 sw_idx; ++ ++ ipa_v2_reap_tx(v2); ++ ++ sw_idx = (readl(v2->bam_reg + BAM_PIPE_SW_OFST(IPA_V2_PIPE_WAN_CONS)) & ++ 0xffff) / sizeof(struct ipa_v2_bam_desc); ++ ++ while (v2->rx_head != sw_idx && work_done < budget) { ++ u32 slot = v2->rx_head; ++ u32 repost = v2->rx_tail; ++ u16 pkt_len; ++ struct sk_buff *skb; ++ ++ dma_rmb(); ++ pkt_len = le16_to_cpu(v2->rx_ring[slot].size); ++ ++ if (likely(pkt_len > 0 && pkt_len <= IPA_V2_RX_BUF_SZ && ++ (v2->netdev->flags & IFF_UP))) { ++ skb = napi_alloc_skb(napi, pkt_len); ++ if (likely(skb)) { ++ skb_put_data(skb, ++ v2->rx_bufs + slot * IPA_V2_RX_BUF_SZ, ++ pkt_len); ++ skb->dev = v2->netdev; ++ skb->protocol = htons(ETH_P_MAP); ++ v2->netdev->stats.rx_packets++; ++ v2->netdev->stats.rx_bytes += pkt_len; ++ netif_receive_skb(skb); ++ } else { ++ v2->netdev->stats.rx_dropped++; ++ } ++ } else if (pkt_len > IPA_V2_RX_BUF_SZ) { ++ v2->netdev->stats.rx_length_errors++; ++ } ++ ++ v2->rx_ring[repost].addr = ++ cpu_to_le32((u32)(v2->rx_bufs_dma + repost * IPA_V2_RX_BUF_SZ)); ++ v2->rx_ring[repost].size = cpu_to_le16(IPA_V2_RX_BUF_SZ); ++ v2->rx_ring[repost].flags = cpu_to_le16(BAM_DESC_FLAG_INT); ++ ++ v2->rx_head = (v2->rx_head + 1) % IPA_V2_RX_RING_COUNT; ++ v2->rx_tail = (v2->rx_tail + 1) % IPA_V2_RX_RING_COUNT; ++ reposted = true; ++ work_done++; ++ } ++ ++ if (reposted) { ++ dma_wmb(); ++ writel(v2->rx_tail * sizeof(struct ipa_v2_bam_desc), ++ v2->bam_reg + BAM_PIPE_EVNT_REG(IPA_V2_PIPE_WAN_CONS)); ++ } ++ ++ if (work_done < budget) { ++ if (napi_complete_done(napi, work_done)) { ++ writel(BAM_P_IRQ_DATA_MASK, ++ v2->bam_reg + BAM_PIPE_IRQ_EN(IPA_V2_PIPE_WAN_CONS)); ++ sw_idx = (readl(v2->bam_reg + ++ BAM_PIPE_SW_OFST(IPA_V2_PIPE_WAN_CONS)) & ++ 0xffff) / sizeof(struct ipa_v2_bam_desc); ++ if (v2->rx_head != sw_idx && ++ napi_schedule_prep(napi)) { ++ writel(0, v2->bam_reg + ++ BAM_PIPE_IRQ_EN(IPA_V2_PIPE_WAN_CONS)); ++ __napi_schedule(napi); ++ } ++ } ++ } ++ ++ return work_done; ++} ++ ++static irqreturn_t ipa_v2_bam_isr(int irq, void *dev_id) ++{ ++ struct ipa_v2_bam *v2 = dev_id; ++ u32 srcs, stts; ++ ++ srcs = readl(v2->bam_reg + BAM_IRQ_SRCS_EE0); ++ if (!srcs) ++ return IRQ_NONE; ++ ++ if (srcs & BIT(31)) { ++ stts = readl(v2->bam_reg + BAM_IRQ_STTS); ++ writel(stts, v2->bam_reg + BAM_IRQ_CLR); ++ } ++ ++ if (srcs & BIT(IPA_V2_PIPE_LAN_CONS)) { ++ stts = readl(v2->bam_reg + BAM_PIPE_IRQ_STTS(IPA_V2_PIPE_LAN_CONS)); ++ writel(stts, v2->bam_reg + BAM_PIPE_IRQ_CLR(IPA_V2_PIPE_LAN_CONS)); ++ ipa_v2_drain_lan_rx(v2); ++ } ++ ++ if (srcs & BIT(IPA_V2_PIPE_WAN_PROD)) { ++ stts = readl(v2->bam_reg + BAM_PIPE_IRQ_STTS(IPA_V2_PIPE_WAN_PROD)); ++ writel(stts, v2->bam_reg + BAM_PIPE_IRQ_CLR(IPA_V2_PIPE_WAN_PROD)); ++ ipa_v2_reap_tx(v2); ++ } ++ ++ if (srcs & BIT(IPA_V2_PIPE_WAN_CONS)) { ++ stts = readl(v2->bam_reg + BAM_PIPE_IRQ_STTS(IPA_V2_PIPE_WAN_CONS)); ++ writel(stts, v2->bam_reg + BAM_PIPE_IRQ_CLR(IPA_V2_PIPE_WAN_CONS)); ++ if (napi_schedule_prep(&v2->napi)) { ++ writel(0, v2->bam_reg + BAM_PIPE_IRQ_EN(IPA_V2_PIPE_WAN_CONS)); ++ __napi_schedule(&v2->napi); ++ } ++ } ++ ++ return IRQ_HANDLED; ++} ++ ++static int ipa_v2_netdev_open(struct net_device *netdev) ++{ ++ struct ipa_v2_netdev_priv *priv = netdev_priv(netdev); ++ struct ipa_v2_bam *v2 = priv->v2; ++ ++ napi_enable(&v2->napi); ++ if (atomic_read(&v2->datapath_ready)) { ++ netif_carrier_on(netdev); ++ netif_start_queue(netdev); ++ } else { ++ netif_carrier_off(netdev); ++ netif_stop_queue(netdev); ++ } ++ ++ return 0; ++} ++ ++static int ipa_v2_netdev_stop(struct net_device *netdev) ++{ ++ struct ipa_v2_netdev_priv *priv = netdev_priv(netdev); ++ struct ipa_v2_bam *v2 = priv->v2; ++ ++ netif_stop_queue(netdev); ++ napi_disable(&v2->napi); ++ cancel_work_sync(&v2->ul_flush_work); ++ return 0; ++} ++ ++static netdev_tx_t ipa_v2_start_xmit(struct sk_buff *skb, ++ struct net_device *netdev) ++{ ++ struct ipa_v2_netdev_priv *priv = netdev_priv(netdev); ++ struct ipa_v2_bam *v2 = priv->v2; ++ unsigned long flags; ++ bool is_qmap_ctrl; ++ u32 need_descs, free_descs, slot, d_idx; ++ u8 *dst; ++ ++ if (unlikely(skb->protocol != htons(ETH_P_MAP) || ++ skb->len < sizeof(struct rmnet_map_header) || ++ skb->len > IPA_V2_TX_BUF_SZ || ++ !atomic_read(&v2->datapath_ready))) { ++ dev_kfree_skb_any(skb); ++ netdev->stats.tx_dropped++; ++ return NETDEV_TX_OK; ++ } ++ ++ if (skb_linearize(skb)) { ++ dev_kfree_skb_any(skb); ++ netdev->stats.tx_dropped++; ++ return NETDEV_TX_OK; ++ } ++ ++ is_qmap_ctrl = !!(skb->data[0] & 0x80); ++ need_descs = is_qmap_ctrl ? 2 : 1; ++ ++ spin_lock_irqsave(&v2->tx_lock, flags); ++ free_descs = IPA_V2_TX_RING_COUNT - 1 - ++ ipa_v2_ring_dist(v2->tx_desc_head, v2->tx_desc_tail, ++ IPA_V2_TX_RING_COUNT); ++ if (v2->tx_slots_used >= IPA_V2_TX_SLOT_COUNT - 1 || ++ free_descs < need_descs) { ++ netif_stop_queue(netdev); ++ spin_unlock_irqrestore(&v2->tx_lock, flags); ++ return NETDEV_TX_BUSY; ++ } ++ ++ slot = v2->tx_slot_tail; ++ dst = v2->tx_bufs + slot * IPA_V2_TX_BUF_SZ; ++ memcpy(dst, skb->data, skb->len); ++ ++ d_idx = v2->tx_desc_tail; ++ if (is_qmap_ctrl) { ++ struct ipa_v2_cmd_pkt_init *pi = &v2->tables->pkt_init[slot]; ++ dma_addr_t pi_dma = ipa_v2_tbl_dma(v2, pi); ++ ++ memset(pi, 0, sizeof(*pi)); ++ pi->dst_pipe = IPA_V2_PIPE_Q6_LAN_CONS; ++ ++ v2->tx_ring[d_idx].addr = cpu_to_le32((u32)pi_dma); ++ v2->tx_ring[d_idx].size = cpu_to_le16(IPA_V2_IMM_PKT_INIT); ++ v2->tx_ring[d_idx].flags = cpu_to_le16(BAM_DESC_FLAG_IMME); ++ d_idx = (d_idx + 1) % IPA_V2_TX_RING_COUNT; ++ } ++ ++ v2->tx_ring[d_idx].addr = ++ cpu_to_le32((u32)(v2->tx_bufs_dma + slot * IPA_V2_TX_BUF_SZ)); ++ v2->tx_ring[d_idx].size = cpu_to_le16(skb->len); ++ v2->tx_ring[d_idx].flags = ++ cpu_to_le16(BAM_DESC_FLAG_INT | BAM_DESC_FLAG_EOT); ++ d_idx = (d_idx + 1) % IPA_V2_TX_RING_COUNT; ++ ++ v2->tx_slot_meta[slot].desc_count = need_descs; ++ v2->tx_slot_meta[slot].byte_len = skb->len; ++ v2->tx_slot_meta[slot].is_data = !is_qmap_ctrl; ++ v2->tx_slot_tail = (slot + 1) % IPA_V2_TX_SLOT_COUNT; ++ v2->tx_slots_used++; ++ v2->tx_desc_tail = d_idx; ++ ++ if (v2->tx_slots_used >= IPA_V2_TX_SLOT_COUNT - 2) ++ netif_stop_queue(netdev); ++ ++ dma_wmb(); ++ writel(v2->tx_desc_tail * sizeof(struct ipa_v2_bam_desc), ++ v2->bam_reg + BAM_PIPE_EVNT_REG(IPA_V2_PIPE_WAN_PROD)); ++ spin_unlock_irqrestore(&v2->tx_lock, flags); ++ ++ dev_consume_skb_any(skb); ++ return NETDEV_TX_OK; ++} ++ ++static const struct net_device_ops ipa_v2_netdev_ops = { ++ .ndo_open = ipa_v2_netdev_open, ++ .ndo_stop = ipa_v2_netdev_stop, ++ .ndo_start_xmit = ipa_v2_start_xmit, ++}; ++ ++static void ipa_v2_netdev_setup(struct net_device *netdev) ++{ ++ netdev->netdev_ops = &ipa_v2_netdev_ops; ++ netdev->header_ops = NULL; ++ netdev->type = ARPHRD_RAWIP; ++ netdev->hard_header_len = 0; ++ netdev->min_mtu = ETH_MIN_MTU; ++ netdev->max_mtu = IPA_V2_TX_BUF_SZ - sizeof(struct rmnet_map_header); ++ netdev->mtu = 2000; ++ netdev->addr_len = 0; ++ netdev->tx_queue_len = 1000; ++ netdev->flags &= ~(IFF_BROADCAST | IFF_MULTICAST); ++ netdev->flags |= IFF_NOARP; ++ netdev->priv_flags |= IFF_TX_SKB_SHARING; ++ netdev->needed_headroom = 8; ++ netdev->watchdog_timeo = 10 * HZ; ++} ++ ++/* Must be called with v2->qmi_lock held. */ ++static void ipa_v2_qmi_check_ready_locked(struct ipa_v2_bam *v2) ++{ ++ struct ipa_init_complete_ind ind = { }; ++ int ret; ++ ++ if (!v2->modem_init_fin) ++ return; ++ ++ if (v2->init_pending_stage2 && !v2->uc_init_complete_rcvd) ++ return; ++ ++ if (v2->indication_fin && !v2->indication_sent) { ++ ind.status.result = QMI_RESULT_SUCCESS_V01; ++ ind.status.error = QMI_ERR_NONE_V01; ++ ret = qmi_send_indication(&v2->server_handle, ++ &v2->ind_client_sq, ++ IPA_QMI_INIT_COMPLETE, ++ IPA_QMI_INIT_COMPLETE_IND_SZ, ++ ipa_init_complete_ind_ei, &ind); ++ if (ret) { ++ dev_err(v2->dev, ++ "failed to send QMI_IPA_INIT_COMPLETE ind: %d\n", ++ ret); ++ return; ++ } ++ v2->indication_sent = true; ++ } ++ ++ /* On initial boot wait until MASTER_DRIVER_INIT_COMPLETE_IND is sent. */ ++ if (!v2->uc_loaded && !v2->indication_sent) ++ return; ++ ++ v2->uc_loaded = true; ++ if (!atomic_xchg(&v2->datapath_ready, 1)) { ++ dev_info(v2->dev, "SDM660 IPA v2.6L QMI & BAM datapath ready\n"); ++ if (v2->netdev) { ++ netif_carrier_on(v2->netdev); ++ if (v2->netdev->flags & IFF_UP) ++ netif_wake_queue(v2->netdev); ++ } ++ } ++} ++ ++static void ipa_v2_qmi_indication_register(struct qmi_handle *qmi, ++ struct sockaddr_qrtr *sq, ++ struct qmi_txn *txn, ++ const void *decoded) ++{ ++ struct ipa_v2_bam *v2 = ++ container_of(qmi, struct ipa_v2_bam, server_handle); ++ struct ipa_indication_register_rsp rsp = { }; ++ int ret; ++ ++ rsp.rsp.result = QMI_RESULT_SUCCESS_V01; ++ rsp.rsp.error = QMI_ERR_NONE_V01; ++ ++ ret = qmi_send_response(qmi, sq, txn, IPA_QMI_INDICATION_REGISTER, ++ IPA_QMI_INDICATION_REGISTER_RSP_SZ, ++ ipa_indication_register_rsp_ei, &rsp); ++ if (ret) { ++ dev_err(v2->dev, "INDICATION_REGISTER rsp failed: %d\n", ret); ++ return; ++ } ++ ++ mutex_lock(&v2->qmi_lock); ++ v2->ind_client_sq = *sq; ++ v2->indication_fin = true; ++ ipa_v2_qmi_check_ready_locked(v2); ++ mutex_unlock(&v2->qmi_lock); ++} ++ ++static void ipa_v2_qmi_driver_init_complete(struct qmi_handle *qmi, ++ struct sockaddr_qrtr *sq, ++ struct qmi_txn *txn, ++ const void *decoded) ++{ ++ struct ipa_v2_bam *v2 = ++ container_of(qmi, struct ipa_v2_bam, server_handle); ++ struct ipa_driver_init_complete_rsp rsp = { }; ++ int ret; ++ ++ rsp.rsp.result = QMI_RESULT_SUCCESS_V01; ++ rsp.rsp.error = QMI_ERR_NONE_V01; ++ ++ ret = qmi_send_response(qmi, sq, txn, IPA_QMI_DRIVER_INIT_COMPLETE, ++ IPA_QMI_DRIVER_INIT_COMPLETE_RSP_SZ, ++ ipa_driver_init_complete_rsp_ei, &rsp); ++ if (ret) { ++ dev_err(v2->dev, "DRIVER_INIT_COMPLETE rsp failed: %d\n", ret); ++ return; ++ } ++ ++ mutex_lock(&v2->qmi_lock); ++ v2->uc_init_complete_rcvd = true; ++ ipa_v2_qmi_check_ready_locked(v2); ++ mutex_unlock(&v2->qmi_lock); ++} ++ ++static void ipa_v2_qmi_install_filter_rule(struct qmi_handle *qmi, ++ struct sockaddr_qrtr *sq, ++ struct qmi_txn *txn, ++ const void *decoded) ++{ ++ struct ipa_v2_bam *v2 = ++ container_of(qmi, struct ipa_v2_bam, server_handle); ++ const struct ipa_v2_qmi_install_flt_req *req = decoded; ++ struct ipa_v2_qmi_install_flt_rsp *rsp; ++ u32 i, count = 0; ++ int ret; ++ ++ rsp = kzalloc(sizeof(*rsp), GFP_KERNEL); ++ if (!rsp) ++ return; ++ ++ rsp->rsp.result = QMI_RESULT_SUCCESS_V01; ++ rsp->rsp.error = QMI_ERR_NONE_V01; ++ ++ if (req->filter_spec_list_valid) { ++ count = min_t(u32, req->filter_spec_list_len, ++ IPA_V2_QMI_MAX_FILTERS); ++ rsp->filter_handle_list_valid = 1; ++ rsp->filter_handle_list_len = count; ++ for (i = 0; i < count; i++) { ++ rsp->filter_handle_list[i].filter_spec_identifier = ++ req->filter_spec_list[i].filter_spec_identifier; ++ rsp->filter_handle_list[i].filter_handle = ++ IPA_V2_UL_FLT_HDL_BASE + i; ++ } ++ } ++ ++ ret = qmi_send_response(qmi, sq, txn, IPA_V2_QMI_INSTALL_FLT_RSP, ++ 783, ipa_v2_qmi_install_flt_rsp_ei, rsp); ++ if (ret) ++ dev_err(v2->dev, "INSTALL_FILTER_RULE rsp failed: %d\n", ret); ++ else ++ dev_info(v2->dev, "acknowledged %u modem UL filter specs\n", ++ count); ++ ++ kfree(rsp); ++} ++ ++static void ipa_v2_qmi_filter_installed_notif(struct qmi_handle *qmi, ++ struct sockaddr_qrtr *sq, ++ struct qmi_txn *txn, ++ const void *decoded) ++{ ++ struct ipa_v2_qmi_simple_rsp rsp = { ++ .rsp = { ++ .result = QMI_RESULT_SUCCESS_V01, ++ .error = QMI_ERR_NONE_V01, ++ }, ++ }; ++ ++ (void)qmi_send_response(qmi, sq, txn, IPA_V2_QMI_FLT_NOTIF_RSP, ++ 7, ipa_v2_qmi_simple_rsp_ei, &rsp); ++} ++ ++static void ipa_v2_qmi_config_req(struct qmi_handle *qmi, ++ struct sockaddr_qrtr *sq, ++ struct qmi_txn *txn, ++ const void *decoded) ++{ ++ struct ipa_v2_qmi_simple_rsp rsp = { ++ .rsp = { ++ .result = QMI_RESULT_SUCCESS_V01, ++ .error = QMI_ERR_NONE_V01, ++ }, ++ }; ++ ++ (void)qmi_send_response(qmi, sq, txn, IPA_V2_QMI_CONFIG_RSP, ++ 7, ipa_v2_qmi_simple_rsp_ei, &rsp); ++} ++ ++static const struct qmi_msg_handler ipa_v2_server_handlers[] = { ++ { ++ .type = QMI_REQUEST, ++ .msg_id = IPA_QMI_INDICATION_REGISTER, ++ .ei = ipa_indication_register_req_ei, ++ .decoded_size = sizeof(struct ipa_indication_register_req), ++ .fn = ipa_v2_qmi_indication_register, ++ }, ++ { ++ .type = QMI_REQUEST, ++ .msg_id = IPA_QMI_DRIVER_INIT_COMPLETE, ++ .ei = ipa_driver_init_complete_req_ei, ++ .decoded_size = sizeof(struct ipa_driver_init_complete_req), ++ .fn = ipa_v2_qmi_driver_init_complete, ++ }, ++ { ++ .type = QMI_REQUEST, ++ .msg_id = IPA_V2_QMI_INSTALL_FLT_REQ, ++ .ei = ipa_v2_qmi_install_flt_req_ei, ++ .decoded_size = sizeof(struct ipa_v2_qmi_install_flt_req), ++ .fn = ipa_v2_qmi_install_filter_rule, ++ }, ++ { ++ .type = QMI_REQUEST, ++ .msg_id = IPA_V2_QMI_FLT_NOTIF_REQ, ++ .ei = ipa_v2_qmi_simple_req_ei, ++ .decoded_size = sizeof(struct ipa_v2_qmi_simple_req), ++ .fn = ipa_v2_qmi_filter_installed_notif, ++ }, ++ { ++ .type = QMI_REQUEST, ++ .msg_id = IPA_V2_QMI_CONFIG_REQ, ++ .ei = ipa_v2_qmi_simple_req_ei, ++ .decoded_size = sizeof(struct ipa_v2_qmi_simple_req), ++ .fn = ipa_v2_qmi_config_req, ++ }, ++ { }, ++}; ++ ++static void ipa_v2_init_driver_work(struct work_struct *work) ++{ ++ struct ipa_v2_bam *v2 = ++ container_of(work, struct ipa_v2_bam, init_driver_work); ++ struct ipa_init_modem_driver_req req = { }; ++ struct ipa_init_modem_driver_rsp rsp = { }; ++ struct sockaddr_qrtr sq; ++ struct qmi_txn txn; ++ bool ssr_reinit, uc_loaded; ++ int ret; ++ ++ if (atomic_read(&v2->shutting_down)) ++ return; ++ ++ mutex_lock(&v2->qmi_lock); ++ if (!v2->modem_server_up) { ++ mutex_unlock(&v2->qmi_lock); ++ return; ++ } ++ sq = v2->modem_sq; ++ ssr_reinit = v2->ssr_needs_reinit; ++ uc_loaded = v2->uc_loaded; ++ mutex_unlock(&v2->qmi_lock); ++ ++ if (ssr_reinit) { ++ dma_addr_t rt4_dma = ipa_v2_tbl_dma(v2, v2->tables->rt4_init); ++ dma_addr_t rt6_dma = ipa_v2_tbl_dma(v2, v2->tables->rt6_init); ++ dma_addr_t flt4_dma = ipa_v2_tbl_dma(v2, v2->tables->flt4_init); ++ dma_addr_t flt6_dma = ipa_v2_tbl_dma(v2, v2->tables->flt6_init); ++ ++ dev_info(v2->dev, "re-zeroing modem SRAM after SSR\n"); ++ ret = ipa_v2_zero_modem_sram(v2); ++ if (!ret) ++ ret = ipa_v2_dma_write_sram(v2, rt4_dma, ++ IPA_V2_V4_RT_OFST, ++ IPA_V2_V4_MODEM_RT_COUNT * 4); ++ if (!ret) ++ ret = ipa_v2_dma_write_sram(v2, rt6_dma, ++ IPA_V2_V6_RT_OFST, ++ IPA_V2_V6_MODEM_RT_COUNT * 4); ++ if (!ret) ++ ret = ipa_v2_dma_write_sram(v2, flt4_dma, ++ IPA_V2_V4_FLT_OFST, ++ IPA_V2_V4_FLT_SIZE); ++ if (!ret) ++ ret = ipa_v2_dma_write_sram(v2, flt6_dma, ++ IPA_V2_V6_FLT_OFST, ++ IPA_V2_V6_FLT_SIZE); ++ if (ret) { ++ dev_err(v2->dev, "SSR SRAM re-init failed: %d\n", ret); ++ return; ++ } ++ } ++ ++ req.platform_type_valid = 1; ++ req.platform_type = IPA_QMI_PLATFORM_TYPE_MSM_ANDROID; ++ ++ req.hdr_tbl_info_valid = 1; ++ req.hdr_tbl_info.start = IPA_V2_MODEM_HDR_OFST; ++ req.hdr_tbl_info.end = IPA_V2_MODEM_HDR_OFST + IPA_V2_MODEM_HDR_SIZE - 1; ++ ++ req.v4_route_tbl_info_valid = 1; ++ req.v4_route_tbl_info.start = IPA_V2_V4_RT_OFST; ++ req.v4_route_tbl_info.end = IPA_V2_V4_MODEM_RT_COUNT - 1; /* hi = 6 */ ++ ++ req.v6_route_tbl_info_valid = 1; ++ req.v6_route_tbl_info.start = IPA_V2_V6_RT_OFST; ++ req.v6_route_tbl_info.end = IPA_V2_V6_MODEM_RT_COUNT - 1; /* hi = 6 */ ++ ++ req.v4_filter_tbl_start_valid = 1; ++ req.v4_filter_tbl_start = IPA_V2_V4_FLT_OFST; ++ ++ req.v6_filter_tbl_start_valid = 1; ++ req.v6_filter_tbl_start = IPA_V2_V6_FLT_OFST; ++ ++ req.modem_mem_info_valid = 1; ++ req.modem_mem_info.start = IPA_V2_MODEM_MEM_OFST; ++ req.modem_mem_info.size = IPA_V2_MODEM_MEM_SIZE; ++ ++ req.ctrl_comm_dest_end_pt_valid = 1; ++ req.ctrl_comm_dest_end_pt = IPA_V2_PIPE_WAN_CONS; ++ ++ /* v2.6L has no proc_ctx region; zip_tbl_info matches platina-o-oss. */ ++ req.hdr_proc_ctx_tbl_info_valid = 0; ++ req.zip_tbl_info_valid = 1; ++ req.zip_tbl_info.start = IPA_V2_MODEM_ZIP_OFST; ++ req.zip_tbl_info.end = IPA_V2_MODEM_ZIP_OFST + IPA_V2_MODEM_ZIP_SIZE - 1; ++ ++ if (uc_loaded) { ++ req.skip_uc_load_valid = 1; ++ req.skip_uc_load = 1; ++ } ++ ++ ret = qmi_txn_init(&v2->client_handle, &txn, ++ ipa_init_modem_driver_rsp_ei, &rsp); ++ if (ret < 0) { ++ dev_err(v2->dev, "qmi_txn_init failed: %d\n", ret); ++ return; ++ } ++ ++ ret = qmi_send_request(&v2->client_handle, &sq, &txn, ++ IPA_QMI_INIT_DRIVER, IPA_QMI_INIT_DRIVER_REQ_SZ, ++ ipa_init_modem_driver_req_ei, &req); ++ if (ret < 0) { ++ qmi_txn_cancel(&txn); ++ dev_err(v2->dev, "QMI_IPA_INIT_MODEM_DRIVER send failed: %d\n", ++ ret); ++ return; ++ } ++ ++ ret = qmi_txn_wait(&txn, msecs_to_jiffies(60000)); ++ if (ret < 0) { ++ dev_err(v2->dev, "QMI_IPA_INIT_MODEM_DRIVER wait failed: %d\n", ++ ret); ++ return; ++ } ++ ++ if (rsp.rsp.result != QMI_RESULT_SUCCESS_V01) { ++ dev_err(v2->dev, ++ "QMI_IPA_INIT_MODEM_DRIVER rejected result=%u err=%u\n", ++ rsp.rsp.result, rsp.rsp.error); ++ return; ++ } ++ ++ dev_info(v2->dev, ++ "QMI_IPA_INIT_MODEM_DRIVER ok (ctrl_ep=%u pending=%u)\n", ++ rsp.ctrl_comm_dest_end_pt_valid ? rsp.ctrl_comm_dest_end_pt : 0, ++ rsp.modem_driver_init_pending_valid ? ++ rsp.modem_driver_init_pending : 0); ++ ++ mutex_lock(&v2->qmi_lock); ++ v2->ssr_needs_reinit = false; ++ v2->modem_init_fin = true; ++ v2->init_pending_stage2 = rsp.modem_driver_init_pending_valid && ++ rsp.modem_driver_init_pending; ++ ipa_v2_qmi_check_ready_locked(v2); ++ mutex_unlock(&v2->qmi_lock); ++} ++ ++static int ipa_v2_qmi_new_server(struct qmi_handle *qmi, ++ struct qmi_service *svc) ++{ ++ struct ipa_v2_bam *v2 = ++ container_of(qmi, struct ipa_v2_bam, client_handle); ++ ++ mutex_lock(&v2->qmi_lock); ++ v2->modem_sq.sq_family = AF_QIPCRTR; ++ v2->modem_sq.sq_node = svc->node; ++ v2->modem_sq.sq_port = svc->port; ++ v2->modem_server_up = true; ++ mutex_unlock(&v2->qmi_lock); ++ ++ if (!atomic_read(&v2->shutting_down)) ++ schedule_work(&v2->init_driver_work); ++ ++ return 0; ++} ++ ++static void ipa_v2_qmi_del_server(struct qmi_handle *qmi, ++ struct qmi_service *svc) ++{ ++ struct ipa_v2_bam *v2 = ++ container_of(qmi, struct ipa_v2_bam, client_handle); ++ ++ mutex_lock(&v2->qmi_lock); ++ if (v2->modem_server_up) ++ v2->ssr_needs_reinit = true; ++ v2->modem_server_up = false; ++ v2->modem_init_fin = false; ++ v2->indication_fin = false; ++ v2->indication_sent = false; ++ v2->init_pending_stage2 = false; ++ v2->uc_init_complete_rcvd = false; ++ if (atomic_xchg(&v2->datapath_ready, 0) && v2->netdev) { ++ netif_carrier_off(v2->netdev); ++ netif_stop_queue(v2->netdev); ++ } ++ mutex_unlock(&v2->qmi_lock); ++ cancel_work_sync(&v2->ul_flush_work); ++} ++ ++static const struct qmi_ops ipa_v2_client_ops = { ++ .new_server = ipa_v2_qmi_new_server, ++ .del_server = ipa_v2_qmi_del_server, ++}; ++ ++static int ipa_v2_qmi_init(struct ipa_v2_bam *v2) ++{ ++ int ret; ++ ++ INIT_WORK(&v2->init_driver_work, ipa_v2_init_driver_work); ++ ++ ret = qmi_handle_init(&v2->server_handle, IPA_V2_QMI_RECV_BUF_SZ, ++ NULL, ipa_v2_server_handlers); ++ if (ret) ++ return ret; ++ ++ ret = qmi_add_server(&v2->server_handle, IPA_V2_QMI_SVC_ID, ++ IPA_V2_QMI_SVC_VER, IPA_V2_QMI_HOST_INS_ID); ++ if (ret) ++ goto err_release_server; ++ ++ ret = qmi_handle_init(&v2->client_handle, 256, ++ &ipa_v2_client_ops, NULL); ++ if (ret) ++ goto err_release_server; ++ ++ ret = qmi_add_lookup(&v2->client_handle, IPA_V2_QMI_SVC_ID, ++ IPA_V2_QMI_SVC_VER, IPA_V2_QMI_MODEM_INS_ID); ++ if (ret) ++ goto err_release_client; ++ ++ return 0; ++ ++err_release_client: ++ qmi_handle_release(&v2->client_handle); ++err_release_server: ++ qmi_handle_release(&v2->server_handle); ++ return ret; ++} ++ ++static void ipa_v2_qmi_exit(struct ipa_v2_bam *v2) ++{ ++ atomic_set(&v2->shutting_down, 1); ++ cancel_work_sync(&v2->init_driver_work); ++ qmi_handle_release(&v2->client_handle); ++ qmi_handle_release(&v2->server_handle); ++} ++ ++static int ipa_v2_alloc_dma_pools(struct ipa_v2_bam *v2) ++{ ++ struct device *dev = v2->dev; ++ ++ v2->tables = dma_alloc_coherent(dev, sizeof(*v2->tables), ++ &v2->tables_dma, GFP_KERNEL); ++ if (!v2->tables) ++ return -ENOMEM; ++ ++ v2->cmd_ring = dma_alloc_coherent(dev, ++ IPA_V2_CMD_RING_COUNT * sizeof(*v2->cmd_ring), ++ &v2->cmd_ring_dma, GFP_KERNEL); ++ if (!v2->cmd_ring) ++ goto err_free_tables; ++ ++ v2->lan_ring = dma_alloc_coherent(dev, ++ IPA_V2_LAN_RX_RING_COUNT * sizeof(*v2->lan_ring), ++ &v2->lan_ring_dma, GFP_KERNEL); ++ if (!v2->lan_ring) ++ goto err_free_cmd; ++ ++ v2->lan_bufs = dma_alloc_coherent(dev, ++ IPA_V2_LAN_RX_RING_COUNT * IPA_V2_LAN_RX_BUF_SZ, ++ &v2->lan_bufs_dma, GFP_KERNEL); ++ if (!v2->lan_bufs) ++ goto err_free_lan_ring; ++ ++ v2->tx_ring = dma_alloc_coherent(dev, ++ IPA_V2_TX_RING_COUNT * sizeof(*v2->tx_ring), ++ &v2->tx_ring_dma, GFP_KERNEL); ++ if (!v2->tx_ring) ++ goto err_free_lan_bufs; ++ ++ v2->tx_bufs = dma_alloc_coherent(dev, ++ IPA_V2_TX_SLOT_COUNT * IPA_V2_TX_BUF_SZ, ++ &v2->tx_bufs_dma, GFP_KERNEL); ++ if (!v2->tx_bufs) ++ goto err_free_tx_ring; ++ ++ v2->rx_ring = dma_alloc_coherent(dev, ++ IPA_V2_RX_RING_COUNT * sizeof(*v2->rx_ring), ++ &v2->rx_ring_dma, GFP_KERNEL); ++ if (!v2->rx_ring) ++ goto err_free_tx_bufs; ++ ++ v2->rx_bufs = dma_alloc_coherent(dev, ++ IPA_V2_RX_RING_COUNT * IPA_V2_RX_BUF_SZ, ++ &v2->rx_bufs_dma, GFP_KERNEL); ++ if (!v2->rx_bufs) ++ goto err_free_rx_ring; ++ ++ return 0; ++ ++err_free_rx_ring: ++ dma_free_coherent(dev, IPA_V2_RX_RING_COUNT * sizeof(*v2->rx_ring), ++ v2->rx_ring, v2->rx_ring_dma); ++err_free_tx_bufs: ++ dma_free_coherent(dev, IPA_V2_TX_SLOT_COUNT * IPA_V2_TX_BUF_SZ, ++ v2->tx_bufs, v2->tx_bufs_dma); ++err_free_tx_ring: ++ dma_free_coherent(dev, IPA_V2_TX_RING_COUNT * sizeof(*v2->tx_ring), ++ v2->tx_ring, v2->tx_ring_dma); ++err_free_lan_bufs: ++ dma_free_coherent(dev, IPA_V2_LAN_RX_RING_COUNT * IPA_V2_LAN_RX_BUF_SZ, ++ v2->lan_bufs, v2->lan_bufs_dma); ++err_free_lan_ring: ++ dma_free_coherent(dev, IPA_V2_LAN_RX_RING_COUNT * sizeof(*v2->lan_ring), ++ v2->lan_ring, v2->lan_ring_dma); ++err_free_cmd: ++ dma_free_coherent(dev, IPA_V2_CMD_RING_COUNT * sizeof(*v2->cmd_ring), ++ v2->cmd_ring, v2->cmd_ring_dma); ++err_free_tables: ++ dma_free_coherent(dev, sizeof(*v2->tables), ++ v2->tables, v2->tables_dma); ++ return -ENOMEM; ++} ++ ++static void ipa_v2_free_dma_pools(struct ipa_v2_bam *v2) ++{ ++ struct device *dev = v2->dev; ++ ++ dma_free_coherent(dev, IPA_V2_RX_RING_COUNT * IPA_V2_RX_BUF_SZ, ++ v2->rx_bufs, v2->rx_bufs_dma); ++ dma_free_coherent(dev, IPA_V2_RX_RING_COUNT * sizeof(*v2->rx_ring), ++ v2->rx_ring, v2->rx_ring_dma); ++ dma_free_coherent(dev, IPA_V2_TX_SLOT_COUNT * IPA_V2_TX_BUF_SZ, ++ v2->tx_bufs, v2->tx_bufs_dma); ++ dma_free_coherent(dev, IPA_V2_TX_RING_COUNT * sizeof(*v2->tx_ring), ++ v2->tx_ring, v2->tx_ring_dma); ++ dma_free_coherent(dev, IPA_V2_LAN_RX_RING_COUNT * IPA_V2_LAN_RX_BUF_SZ, ++ v2->lan_bufs, v2->lan_bufs_dma); ++ dma_free_coherent(dev, IPA_V2_LAN_RX_RING_COUNT * sizeof(*v2->lan_ring), ++ v2->lan_ring, v2->lan_ring_dma); ++ dma_free_coherent(dev, IPA_V2_CMD_RING_COUNT * sizeof(*v2->cmd_ring), ++ v2->cmd_ring, v2->cmd_ring_dma); ++ dma_free_coherent(dev, sizeof(*v2->tables), ++ v2->tables, v2->tables_dma); ++} ++ ++int ipa_v2_bam_probe(struct platform_device *pdev, const struct ipa_data *data) ++{ ++ struct device *dev = &pdev->dev; ++ struct ipa_v2_netdev_priv *npriv; ++ struct net_device *netdev; ++ struct ipa_v2_bam *v2; ++ struct resource *res; ++ struct ipa *ipa; ++ int ret; ++ ++ ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32)); ++ if (ret) ++ return dev_err_probe(dev, ret, "failed to set 32-bit DMA mask\n"); ++ ++ ipa = kzalloc(sizeof(*ipa), GFP_KERNEL); ++ if (!ipa) ++ return -ENOMEM; ++ ++ v2 = kzalloc(sizeof(*v2), GFP_KERNEL); ++ if (!v2) { ++ ret = -ENOMEM; ++ goto err_free_ipa; ++ } ++ ++ ipa->dev = dev; ++ ipa->version = data->version; ++ ipa->v2_bam = v2; ++ v2->ipa = ipa; ++ v2->dev = dev; ++ mutex_init(&v2->cmd_lock); ++ mutex_init(&v2->qmi_lock); ++ spin_lock_init(&v2->tx_lock); ++ INIT_WORK(&v2->ul_flush_work, ipa_v2_ul_flush_work); ++ dev_set_drvdata(dev, ipa); ++ ++ v2->bam_irq = platform_get_irq_byname(pdev, "bam"); ++ if (v2->bam_irq < 0) { ++ ret = v2->bam_irq; ++ goto err_free_v2; ++ } ++ ++ res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "ipa-reg"); ++ v2->ipa_reg = devm_ioremap_resource(dev, res); ++ if (IS_ERR(v2->ipa_reg)) { ++ ret = PTR_ERR(v2->ipa_reg); ++ goto err_free_v2; ++ } ++ ++ res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "bam"); ++ v2->bam_reg = devm_ioremap_resource(dev, res); ++ if (IS_ERR(v2->bam_reg)) { ++ ret = PTR_ERR(v2->bam_reg); ++ goto err_free_v2; ++ } ++ ++ v2->core_clk = clk_get(dev, "core"); ++ if (IS_ERR(v2->core_clk)) { ++ ret = dev_err_probe(dev, PTR_ERR(v2->core_clk), ++ "failed to get IPA core clock\n"); ++ goto err_free_v2; ++ } ++ ++ v2->icc_mem = of_icc_get(dev, "memory"); ++ if (IS_ERR(v2->icc_mem)) { ++ ret = dev_err_probe(dev, PTR_ERR(v2->icc_mem), ++ "failed to get memory interconnect\n"); ++ goto err_put_clk; ++ } ++ ++ v2->icc_cfg = of_icc_get(dev, "config"); ++ if (IS_ERR(v2->icc_cfg)) { ++ ret = dev_err_probe(dev, PTR_ERR(v2->icc_cfg), ++ "failed to get config interconnect\n"); ++ goto err_put_icc_mem; ++ } ++ ++ if (v2->icc_mem) { ++ ret = icc_set_bw(v2->icc_mem, IPA_V2_ICC_MEM_AVG_BW, ++ IPA_V2_ICC_MEM_PEAK_BW); ++ if (ret) ++ goto err_put_icc_cfg; ++ } ++ if (v2->icc_cfg) { ++ ret = icc_set_bw(v2->icc_cfg, IPA_V2_ICC_CFG_AVG_BW, ++ IPA_V2_ICC_CFG_PEAK_BW); ++ if (ret) ++ goto err_unvote_icc_mem; ++ } ++ ++ ret = clk_prepare_enable(v2->core_clk); ++ if (ret) ++ goto err_unvote_icc_cfg; ++ ++ ret = clk_set_rate(v2->core_clk, IPA_V2_SVS_CLK_RATE); ++ if (ret) ++ goto err_disable_clk; ++ ++ ret = ipa_v2_alloc_dma_pools(v2); ++ if (ret) ++ goto err_disable_clk; ++ ++ netdev = alloc_netdev(sizeof(*npriv), "rmnet_ipa%d", ++ NET_NAME_UNKNOWN, ipa_v2_netdev_setup); ++ if (!netdev) { ++ ret = -ENOMEM; ++ goto err_free_dma; ++ } ++ SET_NETDEV_DEV(netdev, dev); ++ npriv = netdev_priv(netdev); ++ npriv->v2 = v2; ++ v2->netdev = netdev; ++ ipa->modem_netdev = netdev; ++ netif_carrier_off(netdev); ++ netif_napi_add(netdev, &v2->napi, ipa_v2_poll); ++ ++ ret = ipa_v2_init_hw_and_tables(v2); ++ if (ret) ++ goto err_free_netdev; ++ ++ ipa_v2_setup_data_pipes(v2); ++ ++ ret = request_irq(v2->bam_irq, ipa_v2_bam_isr, 0, "ipa-v2-bam", v2); ++ if (ret) ++ goto err_reset_pipes; ++ ++ ret = register_netdev(netdev); ++ if (ret) ++ goto err_free_irq; ++ ++ ret = ipa_v2_qmi_init(v2); ++ if (ret) ++ goto err_unreg_netdev; ++ ++ dev_info(dev, "SDM660 IPA v2.6L BAM driver initialized (rmnet_ipa0)\n"); ++ return 0; ++ ++err_unreg_netdev: ++ unregister_netdev(netdev); ++err_free_irq: ++ free_irq(v2->bam_irq, v2); ++err_reset_pipes: ++ writel(readl(v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0) & ++ ~(BIT(IPA_V2_PIPE_LAN_CONS) | BIT(IPA_V2_PIPE_WAN_PROD) | ++ BIT(IPA_V2_PIPE_WAN_CONS)), ++ v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_WAN_CONS); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_WAN_PROD); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_LAN_CONS); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_CMD_PROD); ++err_free_netdev: ++ netif_napi_del(&v2->napi); ++ free_netdev(netdev); ++err_free_dma: ++ ipa_v2_free_dma_pools(v2); ++err_disable_clk: ++ clk_disable_unprepare(v2->core_clk); ++err_unvote_icc_cfg: ++ if (v2->icc_cfg) ++ icc_set_bw(v2->icc_cfg, 0, 0); ++err_unvote_icc_mem: ++ if (v2->icc_mem) ++ icc_set_bw(v2->icc_mem, 0, 0); ++err_put_icc_cfg: ++ icc_put(v2->icc_cfg); ++err_put_icc_mem: ++ icc_put(v2->icc_mem); ++err_put_clk: ++ clk_put(v2->core_clk); ++err_free_v2: ++ kfree(v2); ++err_free_ipa: ++ kfree(ipa); ++ return ret; ++} ++ ++void ipa_v2_bam_remove(struct platform_device *pdev) ++{ ++ struct ipa *ipa = dev_get_drvdata(&pdev->dev); ++ struct ipa_v2_bam *v2; ++ ++ if (!ipa || !ipa->v2_bam) ++ return; ++ v2 = ipa->v2_bam; ++ ++ atomic_set(&v2->datapath_ready, 0); ++ atomic_set(&v2->shutting_down, 1); ++ cancel_work_sync(&v2->ul_flush_work); ++ ipa_v2_qmi_exit(v2); ++ ++ unregister_netdev(v2->netdev); ++ ++ writel(readl(v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0) & ++ ~(BIT(IPA_V2_PIPE_LAN_CONS) | BIT(IPA_V2_PIPE_WAN_PROD) | ++ BIT(IPA_V2_PIPE_WAN_CONS)), ++ v2->bam_reg + BAM_IRQ_SRCS_MSK_EE0); ++ free_irq(v2->bam_irq, v2); ++ ++ netif_napi_del(&v2->napi); ++ free_netdev(v2->netdev); ++ ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_WAN_CONS); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_WAN_PROD); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_LAN_CONS); ++ ipa_v2_bam_reset_pipe(v2, IPA_V2_PIPE_CMD_PROD); ++ ++ ipa_v2_free_dma_pools(v2); ++ ++ clk_disable_unprepare(v2->core_clk); ++ if (v2->icc_cfg) ++ icc_set_bw(v2->icc_cfg, 0, 0); ++ if (v2->icc_mem) ++ icc_set_bw(v2->icc_mem, 0, 0); ++ icc_put(v2->icc_cfg); ++ icc_put(v2->icc_mem); ++ clk_put(v2->core_clk); ++ ++ kfree(v2); ++ kfree(ipa); ++} ++ ++ssize_t ipa_v2_bam_debug_show(struct ipa *ipa, char *buf) ++{ ++ struct ipa_v2_bam *v2; ++ static const u32 ap_bam_pipes[] = { 2, 3, 4, 5 }; ++ static const u32 ipa_ep_pipes[] = { 2, 4, 5, 6, 8, 9 }; ++ int len = 0; ++ unsigned int i; ++ ++ if (!ipa || !ipa->v2_bam) ++ return -ENODEV; ++ v2 = ipa->v2_bam; ++ ++ len += sysfs_emit_at(buf, len, ++ "tables=%#llx empty=%#llx ready=%d enabled=%#x cntr=%#x irq=%#x flt=%#x rt=%#x susp=%#x\n", ++ (u64)v2->tables_dma, ++ (u64)ipa_v2_tbl_dma(v2, v2->tables->empty_rule), ++ atomic_read(&v2->datapath_ready), ++ readl(v2->ipa_reg + IPA_V2_ENABLED_PIPES), ++ readl(v2->ipa_reg + IPA_V2_COUNTER_CFG), ++ readl(v2->ipa_reg + IPA_V2_IRQ_STTS_EE0), ++ readl(v2->ipa_reg + IPA_V2_FILTER), ++ readl(v2->ipa_reg + IPA_V2_ROUTE), ++ readl(v2->ipa_reg + IPA_V2_IRQ_SUSPEND_INFO_EE0)); ++ len += sysfs_emit_at(buf, len, ++ "lan_rx=%llu ul_flushes=%llu last_len=%u last_pkt=%32phN\n", ++ v2->lan_rx_pkts, v2->ul_flushes, ++ v2->last_lan_len, v2->last_lan_pkt); ++ ++ for (i = 0; i < ARRAY_SIZE(ap_bam_pipes); i++) { ++ u32 p = ap_bam_pipes[i]; ++ ++ len += sysfs_emit_at(buf, len, ++ "bam[%u]: ctrl=%#x sw=%#x evnt=%#x stts=%#x\n", ++ p, ++ readl(v2->bam_reg + BAM_PIPE_CTRL(p)), ++ readl(v2->bam_reg + BAM_PIPE_SW_OFST(p)), ++ readl(v2->bam_reg + BAM_PIPE_EVNT_REG(p)), ++ readl(v2->bam_reg + BAM_PIPE_IRQ_STTS(p))); ++ } ++ ++ for (i = 0; i < ARRAY_SIZE(ipa_ep_pipes); i++) { ++ u32 p = ipa_ep_pipes[i]; ++ ++ len += sysfs_emit_at(buf, len, ++ "ep[%u]: ctrl=%#x hdr=%#x ext=%#x mode=%#x aggr=%#x rt=%#x st=%#x holb=%#x\n", ++ p, ++ readl(v2->ipa_reg + IPA_V2_ENDP_INIT_CTRL(p)), ++ readl(v2->ipa_reg + IPA_V2_ENDP_INIT_HDR(p)), ++ readl(v2->ipa_reg + IPA_V2_ENDP_INIT_HDR_EXT(p)), ++ readl(v2->ipa_reg + IPA_V2_ENDP_INIT_MODE(p)), ++ readl(v2->ipa_reg + IPA_V2_ENDP_INIT_AGGR(p)), ++ readl(v2->ipa_reg + IPA_V2_ENDP_INIT_ROUTE(p)), ++ readl(v2->ipa_reg + IPA_V2_ENDP_STATUS(p)), ++ readl(v2->ipa_reg + IPA_V2_ENDP_INIT_HOLB_EN(p))); ++ } ++ ++ len += sysfs_emit_at(buf, len, "sram_flt4:"); ++ for (i = 0; i < 22; i++) ++ len += sysfs_emit_at(buf, len, " %08x", ++ readl(v2->ipa_reg + IPA_V2_SRAM_BASE + ++ IPA_V2_V4_FLT_OFST + 4 * i)); ++ len += sysfs_emit_at(buf, len, "\nsram_rt4:"); ++ for (i = 0; i < 15; i++) ++ len += sysfs_emit_at(buf, len, " %08x", ++ readl(v2->ipa_reg + IPA_V2_SRAM_BASE + ++ IPA_V2_V4_RT_OFST + 4 * i)); ++ len += sysfs_emit_at(buf, len, "\n"); ++ ++ return len; ++} +diff -uNr /tmp/ipa-patch-gen/a/drivers/net/ipa/ipa_v2_bam.h /tmp/ipa-patch-gen/b/drivers/net/ipa/ipa_v2_bam.h +--- a/drivers/net/ipa/ipa_v2_bam.h 1970-01-01 08:00:00.000000000 +0800 ++++ b/drivers/net/ipa/ipa_v2_bam.h 2026-11-17 15:44:10.624000000 +0800 +@@ -0,0 +1,16 @@ ++/* SPDX-License-Identifier: GPL-2.0 */ ++#ifndef _IPA_V2_BAM_H_ ++#define _IPA_V2_BAM_H_ ++ ++#include ++ ++struct ipa; ++struct ipa_data; ++struct platform_device; ++ ++int ipa_v2_bam_probe(struct platform_device *pdev, const struct ipa_data *data); ++void ipa_v2_bam_remove(struct platform_device *pdev); ++bool ipa_v2_bam_datapath_ready(struct ipa *ipa); ++ssize_t ipa_v2_bam_debug_show(struct ipa *ipa, char *buf); ++ ++#endif /* _IPA_V2_BAM_H_ */ diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-reject-unimplemented-bam-transport.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-reject-unimplemented-bam-transport.patch deleted file mode 100644 index 2f5a317..0000000 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-reject-unimplemented-bam-transport.patch +++ /dev/null @@ -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; - diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0045-arm64-dts-sdm630-fix-anoc2-context-irq-polarity.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0045-arm64-dts-sdm630-fix-anoc2-context-irq-polarity.patch new file mode 100644 index 0000000..7ebabcf --- /dev/null +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0045-arm64-dts-sdm630-fix-anoc2-context-irq-polarity.patch @@ -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 @@ + , + + , +- , +- , +- , +- , +- , ++ , ++ , ++ , ++ , ++ , + , + , + , diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD index 7c7b480..e6bf7bd 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD @@ -3,7 +3,7 @@ maintainer="Alexey Minnekhanov " _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 " diff --git a/project/cellular/ipa-v2/INITIALIZATION.md b/project/cellular/ipa-v2/INITIALIZATION.md new file mode 100644 index 0000000..0d618cd --- /dev/null +++ b/project/cellular/ipa-v2/INITIALIZATION.md @@ -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. diff --git a/project/cellular/ipa-v2/Makefile b/project/cellular/ipa-v2/Makefile new file mode 100644 index 0000000..ad4c0cc --- /dev/null +++ b/project/cellular/ipa-v2/Makefile @@ -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 diff --git a/project/cellular/ipa-v2/README.md b/project/cellular/ipa-v2/README.md new file mode 100644 index 0000000..bd738d4 --- /dev/null +++ b/project/cellular/ipa-v2/README.md @@ -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. diff --git a/project/cellular/ipa-v2/ipa_v2_cmd_format.h b/project/cellular/ipa-v2/ipa_v2_cmd_format.h new file mode 100644 index 0000000..adbe414 --- /dev/null +++ b/project/cellular/ipa-v2/ipa_v2_cmd_format.h @@ -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 +#include +#include +#else +#include +#include +#include +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 diff --git a/project/cellular/ipa-v2/ipa_v2_dma.h b/project/cellular/ipa-v2/ipa_v2_dma.h new file mode 100644 index 0000000..491bc39 --- /dev/null +++ b/project/cellular/ipa-v2/ipa_v2_dma.h @@ -0,0 +1,48 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PLATINA_IPA_V2_DMA_H +#define PLATINA_IPA_V2_DMA_H + +#include +#include +#include + +/* 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 diff --git a/project/cellular/ipa-v2/platina_ipa_v2_cmd_test.c b/project/cellular/ipa-v2/platina_ipa_v2_cmd_test.c new file mode 100644 index 0000000..8e7d499 --- /dev/null +++ b/project/cellular/ipa-v2/platina_ipa_v2_cmd_test.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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"); diff --git a/project/cellular/ipa-v2/platina_ipa_v2_dma_test.c b/project/cellular/ipa-v2/platina_ipa_v2_dma_test.c new file mode 100644 index 0000000..0aec6ba --- /dev/null +++ b/project/cellular/ipa-v2/platina_ipa_v2_dma_test.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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"); diff --git a/project/cellular/ipa-v2/platina_ipa_v2_probe.c b/project/cellular/ipa-v2/platina_ipa_v2_probe.c new file mode 100644 index 0000000..fc4a35a --- /dev/null +++ b/project/cellular/ipa-v2/platina_ipa_v2_probe.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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"); diff --git a/project/cellular/ipa-v2/rmtfs-early.conf b/project/cellular/ipa-v2/rmtfs-early.conf new file mode 100644 index 0000000..f471b4e --- /dev/null +++ b/project/cellular/ipa-v2/rmtfs-early.conf @@ -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 diff --git a/project/sources.lock.json b/project/sources.lock.json index e5170b9..10fcb6f 100644 --- a/project/sources.lock.json +++ b/project/sources.lock.json @@ -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" } }, diff --git a/scripts/flash_release.sh b/scripts/flash_release.sh index 1c2467a..dfbc25d 100755 --- a/scripts/flash_release.sh +++ b/scripts/flash_release.sh @@ -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" "$@" diff --git a/scripts/image-runtime.py b/scripts/image-runtime.py index c835bce..a024073 100644 --- a/scripts/image-runtime.py +++ b/scripts/image-runtime.py @@ -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', diff --git a/scripts/phone-cellular-bam-overlay.py b/scripts/phone-cellular-bam-overlay.py new file mode 100644 index 0000000..72c3565 --- /dev/null +++ b/scripts/phone-cellular-bam-overlay.py @@ -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() diff --git a/scripts/phone-cellular-rpmsg.py b/scripts/phone-cellular-rpmsg.py index dd6c59c..83f5466 100644 --- a/scripts/phone-cellular-rpmsg.py +++ b/scripts/phone-cellular-rpmsg.py @@ -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) diff --git a/scripts/phone-cellular-setup.py b/scripts/phone-cellular-setup.py index 40da8d1..8de1334 100755 --- a/scripts/phone-cellular-setup.py +++ b/scripts/phone-cellular-setup.py @@ -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, diff --git a/scripts/phone-dsp.openrc b/scripts/phone-dsp.openrc index 8ab02e9..5e8ea16 100755 --- a/scripts/phone-dsp.openrc +++ b/scripts/phone-dsp.openrc @@ -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 diff --git a/scripts/phone-headless.start b/scripts/phone-headless.start index 10df8e8..ea4bcdc 100755 --- a/scripts/phone-headless.start +++ b/scripts/phone-headless.start @@ -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 ( diff --git a/scripts/phone-power-chord.conf b/scripts/phone-power-chord.conf index 7883fe4..fae5860 100644 --- a/scripts/phone-power-chord.conf +++ b/scripts/phone-power-chord.conf @@ -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 diff --git a/scripts/phone-power-chord.openrc b/scripts/phone-power-chord.openrc index 148a169..a6ec522 100644 --- a/scripts/phone-power-chord.openrc +++ b/scripts/phone-power-chord.openrc @@ -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 diff --git a/scripts/phone-power-chord.py b/scripts/phone-power-chord.py index 8e2401b..076e171 100644 --- a/scripts/phone-power-chord.py +++ b/scripts/phone-power-chord.py @@ -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__': diff --git a/scripts/phone-poweroff.py b/scripts/phone-poweroff.py index 7762e2c..d7582d4 100644 --- a/scripts/phone-poweroff.py +++ b/scripts/phone-poweroff.py @@ -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): diff --git a/scripts/phone-status-screen.py b/scripts/phone-status-screen.py new file mode 100755 index 0000000..f1daa96 --- /dev/null +++ b/scripts/phone-status-screen.py @@ -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()) diff --git a/scripts/project.py b/scripts/project.py index f4d6b8a..f625c33 100755 --- a/scripts/project.py +++ b/scripts/project.py @@ -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']) diff --git a/scripts/setup_usb_gadget_service.sh b/scripts/setup_usb_gadget_service.sh index 2b4af65..ee947b5 100644 --- a/scripts/setup_usb_gadget_service.sh +++ b/scripts/setup_usb_gadget_service.sh @@ -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 diff --git a/tests/ipa_v2_cmd_format.c b/tests/ipa_v2_cmd_format.c new file mode 100644 index 0000000..c9de23d --- /dev/null +++ b/tests/ipa_v2_cmd_format.c @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include +#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; +} diff --git a/tests/test_cellular_bam_format.py b/tests/test_cellular_bam_format.py new file mode 100644 index 0000000..c6dcd87 --- /dev/null +++ b/tests/test_cellular_bam_format.py @@ -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) diff --git a/tests/test_cellular_bam_overlay.py b/tests/test_cellular_bam_overlay.py new file mode 100644 index 0000000..9e05638 --- /dev/null +++ b/tests/test_cellular_bam_overlay.py @@ -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() diff --git a/tests/test_cellular_early_boot.py b/tests/test_cellular_early_boot.py new file mode 100644 index 0000000..b6fb414 --- /dev/null +++ b/tests/test_cellular_early_boot.py @@ -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) diff --git a/tests/test_cellular_rpmsg.py b/tests/test_cellular_rpmsg.py index 22ee827..22935ae 100644 --- a/tests/test_cellular_rpmsg.py +++ b/tests/test_cellular_rpmsg.py @@ -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 = [] diff --git a/tests/test_cellular_setup.py b/tests/test_cellular_setup.py index b390173..3dc07f5 100644 --- a/tests/test_cellular_setup.py +++ b/tests/test_cellular_setup.py @@ -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() diff --git a/tests/test_power_chord.py b/tests/test_power_chord.py index 672673b..3c5161b 100644 --- a/tests/test_power_chord.py +++ b/tests/test_power_chord.py @@ -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() diff --git a/tests/test_status_screen.py b/tests/test_status_screen.py new file mode 100644 index 0000000..cc0564a --- /dev/null +++ b/tests/test_status_screen.py @@ -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()