Bring up nokia-sparkler SMP/cpufreq/lk2nd/cam/haptics, fix timer and EDL USB timeout

- Add 0013 early-SCM 4-core SMP + cpufreq kernel patch and clock-frequency DT nodes
- Complete nokia-sparkler lk2nd port, boot/X11 session startup, 180-deg cached camera, and 157 Hz haptic audio
- Replace root-only timer backend with permissionless sxmo_timer.sh and keypad/hook cancellation
- Fix EDL Firehose rawmode ACK, USB active-config preservation, *+# hint, and 30 s default USB timeout
- Sync a1120 (cocojamboo) prebuilts, docs, tests, and verified checksums in check-rebuild.sh
This commit is contained in:
Luxferre committed 2026-11-16 11:45:38 +02:00
1 parent ab53423e33
commit d7992904bf
56 files changed
+31822 -28253

No files matched your search

+5 -3
View File
@@ -23,7 +23,7 @@ Keep this file short. Full details live in `README.md`, `MANUAL.md`, `SDK.md`, `
- Run `./scripts/check-rebuild.sh`, relevant `scripts/test-*.py` tests, `./scripts/sync-prebuilt-overlay.sh --check`,
and `git diff --check` before claiming a source, artifact, docs, or release change is complete.
- Cross-compile inside rootless Docker. Main builders are `scripts/build-sxmo-x11.sh`, `build-dmenu.sh`,
`build-dwm-plugins.sh`, `build-bananarchy-daemons.sh`, `build-kernel-audio.sh`, `build-lk2nd-beatles.sh`, `build-lk2nd-coconut.sh`, `build-games.sh`,
`build-dwm-plugins.sh`, `build-bananarchy-daemons.sh`, `build-kernel-audio.sh`, `build-lk2nd-beatles.sh`, `build-lk2nd-coconut.sh`, `build-lk2nd-sparkler.sh`, `build-games.sh`,
`build-fcitx5-t9.sh`, and `build-xlibre.sh`.
- Use `scripts/build-dmenu.sh` for dmenu-only changes and `scripts/build-dwm-plugins.sh` for NeoUI/plugin rebuilds. Do
not run a full `build-sxmo-x11.sh` casually: the shipped `dwm` binary contains cover IPC strings absent from source,
@@ -33,8 +33,9 @@ Keep this file short. Full details live in `README.md`, `MANUAL.md`, `SDK.md`, `
`prepare-release.sh`, and `flash-edl.sh`.
- Rebuild the target images for upcoming build `a1120` / `cocojamboo` with
`BANANARCHY_VERSION=a1120 BANANARCHY_CODENAME=cocojamboo ./rebuild-image.sh nokia-argon --mkinitfs`,
`BANANARCHY_VERSION=a1120 BANANARCHY_CODENAME=cocojamboo ./rebuild-image.sh nokia-beatles --mkinitfs`, and
`BANANARCHY_VERSION=a1120 BANANARCHY_CODENAME=cocojamboo ./rebuild-image.sh nokia-coconut --mkinitfs`, and package
`BANANARCHY_VERSION=a1120 BANANARCHY_CODENAME=cocojamboo ./rebuild-image.sh nokia-beatles --mkinitfs`,
`BANANARCHY_VERSION=a1120 BANANARCHY_CODENAME=cocojamboo ./rebuild-image.sh nokia-coconut --mkinitfs`, and
`BANANARCHY_VERSION=a1120 BANANARCHY_CODENAME=cocojamboo ./rebuild-image.sh nokia-sparkler --mkinitfs`, and package
release archives with `BANANARCHY_VERSION=a1120 BANANARCHY_CODENAME=cocojamboo ./prepare-release.sh <target>`. After a
verified rebuild, update the pinned hashes in `scripts/check-rebuild.sh` and `CHANGELOG.md`; verify with `e2fsck -fn`,
`debugfs`, bootfs sync, artifact sync, and `check-rebuild.sh`.
@@ -134,6 +135,7 @@ Keep this file short. Full details live in `README.md`, `MANUAL.md`, `SDK.md`, `
keypad udev/Xorg rules, BusyBox applet lists, and `scripts/set-bananarchy-hostname.sh`.
- The Power menu label is **Reboot to loader** and still calls `sxmo_power.sh bootloader`; `Logout` is removed from
`dmenu.c`, `dmenu.so`, `sxmo_appmenu.sh`, and `sxmo_hook_contextmenu.sh`. Keep the compact Power menu layout synchronized.
- Keep `msm8905-cam.c` 180-degree rotation enabled for `nokia,beatles`, `nokia,sparkler`, and `nokia,leo` alongside cached `row_buf` RAW10 demosaic; keep `patches/kernel/0013-msm8909-early-scm-smp-cpufreq.patch` (4-core SMP + `cpufreq` up to `1.267 GHz`), disabled `vibrator@c000` + `157.0 Hz` haptic audio (`sxmo_vibrate.c`), `DEFAULT_USB_TIMEOUT_MS = 30000` (`--usb-timeout`), and `sxmo_timer.sh` / `dmenu.c` keypad cancellation (`scripts/test-timer.py`, `scripts/test-sparkler-port.py`, `scripts/test-edl-firehose-read.py`).
- Bluetooth HOGP config and plugin load are verified, but full hardware sign-off still needs a wake-up paired keyboard
and **Connect Device** to confirm real HID key events.
+16 -4
View File
@@ -12,7 +12,18 @@ Release versions follow the `<year-letter><MM><DD>` format (where `2026` is `a`,
## Upcoming build `a1120` — codename `cocojamboo`
Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeting **Nokia 8110 4G (`nokia-argon`)**, **Nokia 2720 Flip (`nokia-beatles`)**, and **Nokia 800 Tough (`nokia-coconut`)** while keeping `a1114` (`carbonara`) as the current published release.
Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeting **Nokia 8110 4G (`nokia-argon`)**, **Nokia 2720 Flip (`nokia-beatles`)**, **Nokia 800 Tough (`nokia-coconut`)**, and **Nokia 8000 4G (`nokia-sparkler`)** while keeping `a1114` (`carbonara`) as the current published release.
### Nokia 8000 4G (`nokia-sparkler`) hardware-verified `lk2nd`, 4-core SMP/`cpufreq`, 157 Hz haptic audio, camera, and EDL bring-up
- **Layered `lk2nd` port (`bootloader/lk2nd/nokia-sparkler.patch`)**: added `nokia-sparkler.dtsi` (`msm8909-mtp.dts` `/lk2nd/nokia-sparkler`, matching `androidboot.hw.name=sparkler` without requiring `lk2nd,match-panel;`, GC9307 HLT 15-command and ST7789VX2 CTC 11-command 2.8" SPI init streams on BLSP1 QUP5 `0x078b9000`, `*` on `gpio90` as `KEY_VOLUMEUP` `0x115` alongside `#` `pm8941_resin` and Top Power) plus `"nokia,sparkler"` / `"nokia,leo"` support in `spi-display.c`; added `scripts/build-lk2nd-sparkler.sh`, `scripts/check-lk2nd-sparkler.py`, and `scripts/test-lk2nd-sparkler-port.py`, building `images/boot-lk2nd-nokia-sparkler{,-diagnostic,-display}.img` without altering `nokia-beatles` or `nokia-coconut` `lk2nd` images.
- **4-core Cortex-A7 SMP, `cpufreq` DVFS up to `1.267 GHz`, and clean fast X11 startup (`0013`)**: added `patches/kernel/0013-msm8909-early-scm-smp-cpufreq.patch` allocating a cache-flushed `early_virt` page for 6-argument `qcom_scm_set_boot_addr_mc()` (`ARM_SMCCC_STD_CALL`) before `qcom_scm_probe()` creates its mempool, guarding `qcom-cpufreq-nvmem.c` with `cpu_present(cpu)`, and adding `clock-frequency = <1094400000>;` to `/cpus/cpu@0..3` in `qcom-msm8909.dtsi` and `nokia-{sparkler,leo}.dts`; ordered `kill-plymouth` (`after dbus elogind`) and raised `Xorg :0` readiness wait to `10 s` in `bananarchy-x11-session.sh`, verified live with `present=0-3`, `online=0-3` (`nproc=4`), `schedutil` scaling to `1.2672 GHz` (`a53pll`), zero SMP/`clock-frequency`/`cpuidle` boot errors, and instant first-pass `dwm` / `fcitx5` startup.
- **Kernel DTS, 157 Hz speaker-LRA haptic audio, dual-GPIO torch, and upright cached-row camera (`msm8905-cam` / `camera.so`)**: set `deviceinfo_drm="true"` and `matrix_keypad`/`matrix_keymap` in `devices/nokia-sparkler/modules-initfs`; updated `qcom-msm8909-nokia-sparkler.dts` and `qcom-msm8909-nokia-sparkler.dtb` with stock MSM8909 MTP root IDs (`0xf5`/`0x8`/`0x100`/`0x1000d`), `512 MiB` `/memory`, QDSP6/Q6Voice audio (`wcd_codec: audio-codec@f000`, `apr`, `sound@7702000` with `dai-link-multimedia3` disabled, `lpass_codec: audio-codec@771c000`), Sxmo keypad codes (`0x500d4` `KEY_CAMERA`, `0x100007f` `KEY_COMPOSE`, `0x205000e` `BackSpace`, `0x301009e` `KEY_BACK`), and disabled unpopulated PM8909 `vibrator@c000` (`status = "disabled";`); added native `157.0 Hz` speaker-LRA haptic audio (`vibrate_haptic_audio()` over PipeWire/ALSA `default` with `500 ms` buffer and `plughw:0,0` fallback) to `src/dwm-plugins/sxmo_vibrate.c` (`links libasound` + `libm`); updated `src/leds-msm8905-torch/leds-msm8905-torch.c` (`GPIO_32` `flash-en` + `GPIO_31` `flash-now` `BC847BS`); added `nokia,sparkler` and `nokia,leo` to `rotate_180` plus cached `row_buf[2][CAM_RAW_STRIDE]` burst copies in `src/msm8905-cam/msm8905-cam.c` and reduced `camera_plugin.cpp` post-frame sleep to `10 ms` (verified `/dev/video0` frame time reduced from `1.34 s` to `0.193–0.229 s/frame` with upright JPEG output); wired `nokia-sparkler` across `check-beatles-bootimg.py`, `sync-beatles-bootfs.py`, `flash-edl.py`, `prepare-release.sh`, `check-rebuild.sh`, `test-sparkler-port.py`, and docs.
- **EDL Firehose `<read>`, USB reconnect, and `30 s` USB timeout (`vendor/edl/Library/{firehose,usb,sahara}.py`, `flash-edl.py`, `MANUAL.md`)**: handled standard Qualcomm `rawmode="true"` XML ACK packets in `qualcomm_firehose` (`_begin_raw_read` / `_read_raw_sectors`) alongside FIH's immediate raw streams and capped reads to `min(bytes_to_read, max_chunk)`, fixing GPT/partition corruption on `8k.mbn` (`nokia-sparkler`, `nokia-leo`) and `2720v.mbn`; skipped redundant `set_configuration()` in `usb_class.connect()` when an active USB configuration already exists; raised per-transfer USB bulk read/write timeout to `30000 ms` (`DEFAULT_USB_TIMEOUT_MS = 30000`, `flash-edl.py --usb-timeout`, `2000 ms` Sahara connect probe, and `5–30 s` Fastboot/ADB kick timeouts); added `nokia-leo` to `UNLOCK_DEFAULT_DEVICES`, suppressed duplicate `Bootloader (boot)` output when a per-device `lk2nd` image is active, updated the EDL/Fastboot button-combo hints to **`*` + `#`** (EDL) and **`#`** (Fastboot) for `nokia-sparkler` and `nokia-leo`, added `scripts/test-edl-firehose-read.py`, and verified full live `--only-backup --dump-diagnostics` extraction from the connected `nokia-sparkler`.
### Keypad-friendly timer countdown and alarm cancellation across all targets
- **Permissionless `sxmo_timer.sh`, `dmenu` **Stop Timer** / **Cancel Timer**, and hook integration**: replaced `sxmo_sleep -c boottime_alarm` (`CLOCK_BOOTTIME_ALARM`, which failed with `Operation not permitted` for unprivileged `user`) with tracked `${XDG_RUNTIME_DIR}/sxmo_timers/*.timer` + `/tmp/sxmo_timer_ringing` state in `overlay/rootfs/usr/bin/sxmo_timer.sh`; added non-blocking `stty min 0 time 10` + `dd | tr` keypad cancellation (`Enter`/`0`/`q`/`BackSpace`/`#`/`*`) during countdown and any-key dismissal on expiry; replaced the infinite notification/vibration loop with a single wake, one replaceable critical notification, and a bounded `30 s` alert loop (`pw-play` / `mpv` + `sxmo_vibrate`) alongside `status`, `stop`, and `stop_ringing` subcommands and `HUP INT TERM EXIT` traps; added live `timer_menu_state()` **Stop Timer** / **Cancel Timer** items at the top of the `Sys` and `Timer` menus and `Clear Notification` / `sxmo_hook_mute_ring.sh` / `sxmo_hook_discard.sh` cancellation hooks, verified offline (`scripts/test-timer.py`) and live on `nokia-sparkler`.
### MicroSD card detection fix across all targets
@@ -45,9 +56,10 @@ Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeti
### Image persistence and upcoming `a1120` (`cocojamboo`) release archives
- **Verified `a1120` / `cocojamboo` image set (`--mkinitfs`) and packaged archives**:
- `images/bananarchy-nokia-argon.img`: SHA-256 `8444544b0395c5bdef2f76b87721a99c326a868465d8236e85ff5572e7634cc0` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `44f49c177749e60bbd511fec3c458fdd4393644ebcace0f050f9842c6502fcf4`, alongside `bootloader/lk2nd-msm8909.img`).
- `images/bananarchy-nokia-beatles.img`: SHA-256 `7749caec22f5803112d21d24f032c09162bc7e6a239beabddb903272ebbd79c8`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `cc58d92e6a54eab77f355a148cbc0b424d2da64e65353e3163a9cfc1eba37235`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `4021aebf1c5c126e313947626d736cfc11d76f81e640f6d9862461ad0a5bbd1d`).
- `images/bananarchy-nokia-coconut.img`: SHA-256 `19d17f31b970099dc6c212da58efdf8a99249aaa43e65ebeb6e2b904d0c5809d`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `2ff959ec89916adc02296adb948788bf8180009cd26454643e9f59334f09ad08`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `2899c34b0f29623ce2d4e32e4a1a2e04763af4be0e7a312b0b47a7d979e02d54`).
- `images/bananarchy-nokia-argon.img`: SHA-256 `82f617e425fa9d33b1395c4e35639a6207e3c9d0aa376c7cedf35fddaccb5cc2` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `b1d47511ae36384a16db8e1cf64dc5b39ed72afcaf0128d555dbea8bffc2256b`, alongside `bootloader/lk2nd-msm8909.img`).
- `images/bananarchy-nokia-beatles.img`: SHA-256 `cc40c682fcdacb6415c112494344826362de2f965e6238685462859de66d660e`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `786e9a1f4e4ae92efc948393a1d8f04a9405840a214b6ef37914cf5821d7ed82`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `ab6b0bbea53298fdabb781ac8f29756f6f096872cde80fe31e4e45c851a3329f`).
- `images/bananarchy-nokia-coconut.img`: SHA-256 `e82d64bd9f14b1fcca2c078e9fd43a4c4268b29ff688f268b32a939213be0545`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `55299e15abe5923fc525b4e54e81aa4791f0e61f8a070e84fe7497f75c62d7d7`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `3ff640fcfa4360bd23e354379ffd343dd26a782daf096c770adda917a2ea6e75`).
- `images/bananarchy-nokia-sparkler.img`: SHA-256 `5dc17319742e4af95facc42681f0fe6fb2e80ddf30f421f3c54b9dbe04fefd3f`, `images/boot-bananarchy-nokia-sparkler.img`: SHA-256 `8205e2cb486d8ecc1e261a5c0b6f9ee7f70fd4eed2534d5bafc28ebc62d953d8`, and `images/boot-lk2nd-nokia-sparkler-display.img`: SHA-256 `bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f` (packaged in `bananarchy-nokia-sparkler-a1120-cocojamboo.zip`, SHA-256 `cd27557b8bc13ca83d04e3e41b40876d7fedb5e1149f744aee1dc8ca7a7bea73`).
---
+13 -11
View File
@@ -6,7 +6,8 @@ This manual covers flashing, operating, and customizing **Bananarchy Linux** (`2
- **Nokia 8110 4G (`nokia-argon`)** — verified public release: https://bananarchy.top/builds/bananarchy-nokia-argon-a1114-carbonara.zip
- **Nokia 2720 Flip (`nokia-beatles`)** — verified public release: https://bananarchy.top/builds/bananarchy-nokia-beatles-a1114-carbonara.zip
- **Nokia 800 Tough (`nokia-coconut`)** — hardware-verified for upcoming build `a1120` (`cocojamboo`); source build via `./rebuild-image.sh nokia-coconut --mkinitfs`
- **Nokia 8000 4G (`nokia-sparkler`)** and **Nokia 6300 4G (`nokia-leo`)** — source build via `./rebuild-image.sh nokia-sparkler --mkinitfs` / `nokia-leo`
- **Nokia 8000 4G (`nokia-sparkler`)** — hardware-verified for upcoming build `a1120` (`cocojamboo`); source build via `./rebuild-image.sh nokia-sparkler --mkinitfs`
- **Nokia 6300 4G (`nokia-leo`)** — sibling source build via `./rebuild-image.sh nokia-leo`
---
@@ -14,11 +15,11 @@ This manual covers flashing, operating, and customizing **Bananarchy Linux** (`2
### 1.1 System images (`images/`)
- `images/bananarchy-nokia-argon.img` and `images/bananarchy-nokia-beatles.img`: partitioned MBR images (`256 MiB` `ext2` `pmOS_boot` + `ext4` `pmOS_root`) ready for EDL flashing to `userdata`, `fastboot flash userdata`, or raw `dd` to a microSD card.
- `images/boot-lk2nd-nokia-beatles-display.img` and `images/boot-bananarchy-nokia-beatles.img`: the 2720 Flip display-enabled `lk2nd` secondary bootloader (`boot`) and standalone mainline Android `boot.img` (`recovery`). Equivalent `nokia-coconut` builds are written to `images/boot-lk2nd-nokia-coconut-display.img` and `images/boot-bananarchy-nokia-coconut.img`.
- `images/boot-lk2nd-nokia-beatles-display.img` and `images/boot-bananarchy-nokia-beatles.img`: the 2720 Flip display-enabled `lk2nd` secondary bootloader (`boot`) and standalone mainline Android `boot.img` (`recovery`). Equivalent builds for `nokia-coconut` and `nokia-sparkler` are written to `images/boot-lk2nd-nokia-<device>-display.img` and `images/boot-bananarchy-nokia-<device>.img`.
- If you downloaded a public release `.zip` archive (`bananarchy-nokia-argon-a1114-carbonara.zip` or `bananarchy-nokia-beatles-a1114-carbonara.zip`), extract its `.img` files into `images/` before running `./flash-edl.sh <device>`. Additional device images (`bananarchy-nokia-coconut.img`, `bananarchy-nokia-sparkler.img`, `bananarchy-nokia-leo.img`) can be built from source at any time via `./rebuild-image.sh <device> --mkinitfs`.
### 1.2 Bootloader and EDL programmer (`bootloader/`)
- `bootloader/lk2nd-msm8909.img`: secondary bootloader (`lk2nd`) providing Fastboot and `extlinux` boot discovery for MSM8905 and MSM8909 devices. `images/boot-lk2nd-nokia-beatles-display.img` and `images/boot-lk2nd-nokia-coconut-display.img` are the source-built 2720 Flip and 800 Tough ports (see `bootloader/lk2nd/README.md`).
- `bootloader/lk2nd-msm8909.img`: secondary bootloader (`lk2nd`) providing Fastboot and `extlinux` boot discovery for MSM8905 and MSM8909 devices. `images/boot-lk2nd-nokia-beatles-display.img`, `images/boot-lk2nd-nokia-coconut-display.img`, and `images/boot-lk2nd-nokia-sparkler-display.img` are the source-built 2720 Flip, 800 Tough, and 8000 4G ports (see `bootloader/lk2nd/README.md`).
- `bootloader/loaders/`: signed Qualcomm Sahara/Firehose programmers (`05c6:9008`), one per target. The flasher picks the right one from `--device` / the positional target; run `./flash-edl.sh --list-loaders` to see each file's embedded attestation identity and mapping. Pass `--variant us` for a 2720 Flip US variant or `--loader PATH` to override the programmer entirely.
### 1.3 Core architecture highlights
@@ -48,7 +49,7 @@ Run the automated EDL flasher from the repository root on your host machine:
sudo ./flash-edl.sh nokia-argon # Nokia 8110 4G
sudo ./flash-edl.sh nokia-beatles # Nokia 2720 Flip
```
*(To flash another target device image, pass its codename, e.g. `sudo ./flash-edl.sh nokia-sparkler`.)* The programmer is selected automatically: `8110.mbn` (8110 4G), `2720.mbn` (2720 Flip), `800t.mbn` (800 Tough), and `8k.mbn` for **both** 8000 4G and 6300 4G. The 2720 Flip US variant (`Nokia_bts_us`) uses `2720v.mbn`: pass `--variant us` (or `--loader ./bootloader/loaders/2720v.mbn`). Verify with `./flash-edl.sh --list-loaders`.
*(To flash another target device image, pass its codename, e.g. `sudo ./flash-edl.sh nokia-sparkler`. Pass `--usb-timeout SECS` to adjust per-transfer USB bulk timeout from the 30 s default if needed.)* The programmer is selected automatically: `8110.mbn` (8110 4G), `2720.mbn` (2720 Flip), `800t.mbn` (800 Tough), and `8k.mbn` for **both** 8000 4G and 6300 4G. The 2720 Flip US variant (`Nokia_bts_us`) uses `2720v.mbn`: pass `--variant us` (or `--loader ./bootloader/loaders/2720v.mbn`). Verify with `./flash-edl.sh --list-loaders`.
The script performs the following steps automatically:
1. Temporarily pauses host `ModemManager` so it does not interfere with `05c6:9008`.
@@ -56,7 +57,7 @@ The script performs the following steps automatically:
`05c6:9008` (QDLoader), `05c6:900e` (QHSUSB_BULK, common after a failed
boot) and `05c6:9006` (DLOAD); pass `--pid` to force one:
- **From Bananarchy Linux**: open the **Power** menu (`End / Power` key or `System menu -> Power`), select **Reboot to loader** (`sxmo_power.sh bootloader`) to enter the visible `lk2nd` Fastboot menu, then select **EDL** (or let `flash-edl.sh` automatically send `fastboot oem reboot-edl`). The low-bit reboot cookie now survives the stock boot chain and keeps the menu available.
- **Button combo**: power off the phone, hold **D-Pad up + D-Pad down**, and plug in the USB cable.
- **Button combo**: power off the phone, hold **D-Pad up + D-Pad down** (or **`*` + `#`** on `nokia-sparkler` and `nokia-leo`), and plug in the USB cable.
- **EDL cable**: hold the EDL cable button while plugging in USB.
- **From ADB or Fastboot**: the script automatically sends `adb reboot edl` or `fastboot oem reboot-edl` if detected.
- If the phone is stuck in Sahara with no fresh HELLO packet (e.g. a host
@@ -71,7 +72,7 @@ The script performs the following steps automatically:
### Method B: Fastboot flashing (once `lk2nd` is installed)
1. Enter the `lk2nd` Fastboot menu either by selecting **Reboot to loader** from the **Power** menu (`sxmo_power.sh bootloader`) or by holding **D-Pad down** while powering on the phone.
1. Enter the `lk2nd` Fastboot menu either by selecting **Reboot to loader** from the **Power** menu (`sxmo_power.sh bootloader`) or by holding **D-Pad down** (or **`#`** on `nokia-sparkler` and `nokia-leo`) while powering on the phone.
2. Flash the system image for your device (`nokia-argon` or `nokia-beatles`) to `userdata`:
```bash
fastboot flash userdata ./images/bananarchy-<device>.img
@@ -542,7 +543,7 @@ Both the rear loudspeaker (`Speaker`, with boosted `RX3 Digital Volume` for loud
### 5.3 Flashlight (`white:torch`), camera flash (`camera:flash`), keypad backlight (`white:kbd_backlight`), and vibration (`sxmo_vibrate`)
- **Turn flashlight on or off** (`nokia-argon`/`nokia-beatles` rear flash LED; dedicated top-edge LED on `nokia-coconut` while `camera:flash` drives its rear camera flash LED):
- **Turn flashlight on or off** (`nokia-argon`/`nokia-beatles` rear flash LED; dedicated top-edge `GPIO_13` LED on `nokia-coconut` while `camera:flash` drives its rear `GPIO_32` camera flash LED; digital `GPIO_32` `flash-en` + `GPIO_31` `flash-now` BC847BS `white:torch` on `nokia-sparkler`):
```bash
brightnessctl -d white:torch set 1
brightnessctl -d white:torch set 0
@@ -551,12 +552,13 @@ Both the rear loudspeaker (`Speaker`, with boosted `RX3 Digital Volume` for loud
```bash
brightnessctl -d white:kbd_backlight set 255
```
- **Trigger PM8909 vibration motor (`duration_ms [strength_1_to_3]`)**:
- **Trigger vibration (`duration_ms [strength_1_to_3]`)**: `sxmo_vibrate` drives the PM8909 haptic ERM actuator on `nokia-argon`, `nokia-beatles`, and `nokia-coconut`, and drives the 157 Hz multifunction speaker LRA via PipeWire/ALSA (`vibrate_haptic_audio`) on `nokia-sparkler` and `nokia-leo`:
```bash
sxmo_vibrate 350 1 # light (1600 mV, 38% duty cycle)
sxmo_vibrate 350 2 # medium (2100 mV, 67% duty cycle)
sxmo_vibrate 350 3 # strong (3100 mV, 100% continuous)
sxmo_vibrate 350 1 # light
sxmo_vibrate 350 2 # medium
sxmo_vibrate 350 3 # strong
```
- **Timer countdown and keypad cancellation (`sxmo_timer.sh`)**: open **Applications -> Timer** to start a timer or stopwatch (`Stopwatch`, `1h`, `30m`..`30s`). While counting down inside the terminal, press **Center `OK` (`Enter`)**, **`0`**, **`q`**, or **`BackSpace`** to cancel cleanly; once the timer expires (bounded 30 s alert with sound, vibration, and notification), press any keypad key inside the terminal or open **System menu -> Stop Timer** (or **Applications -> Timer -> Stop Timer**) to silence and close it immediately without rebooting.
### 5.4 Cellular modem, Dual-SIM, and QMI UIM helper
+3 -3
View File
@@ -27,7 +27,7 @@
### Keypad-first user experience and native DWM plugins
Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs a suite of 26 preloaded C/C++ plugins inside DWM that sleep at 0% CPU and open in `< 2 ms`:
- **System and context menus (`dmenu`)**: instant full-screen 10-line vertical menus with live T9 filtering, built-in submenus, and hardware toggles.
- **System and context menus (`dmenu`)**: instant full-screen 10-line vertical menus with live T9 filtering, built-in submenus, top-level **Stop Timer** / **Cancel Timer** controls when a timer is active, and hardware toggles.
- **Passcode-based fullscreen phone locker (`xlocker`), GUI passcode configurator (`xpasscode`), and Duress Mode**: zero-bypass `240x320` fullscreen numeric passcode lock screen verified against the current user's system shadow password (`/usr/bin/bananarchy-verify-passcode`), blocking all desktop, menu, drawer, terminal, and power actions while locked and automatically handing off the display only during incoming calls. Includes a NeoUI **Passcode Configurator (`xpasscode` / `passcode.so`)** in `Config -> Passcode` to change the real Linux user password (`user`, any numeric length `>= 4` digits) and configure a separate **Duress Passcode**. Entering the duress passcode on the lock screen switches the session into **Duress Mode** (`/tmp/duress_home` blank profile with no contacts, SMS, call logs, or personal files, microSD unmounted and disabled, `xfiles` clamped to the profile directory, Passcode/Privacy Center/Tox/IRC/SIP/`st` terminal hidden and blocked, `*#06#` displaying a session-persistent random Luhn-valid IMEI derived from the device's TAC, and theme/wallpaper locked to `NordFrost.xth` and `nordic-peaks.png` until poweroff or reboot).
- **Idle screen lock**: after the configurable **Screen blank** timeout, `bananarchy-idle-blank.sh` arms `bananarchy-idle-lock.sh`, which triggers `xlocker screenoff` after a 30 s dark-panel grace period (set `~/.config/sxmo/idle_lock_delay` to `0` for immediate locking or `off` to blank without a passcode). Waking the panel cancels the pending lock, so a quick key press returns to the unlocked desktop.
- **Privacy Center (`xprivacy` / `privacy` / `privacy.so`) and `/usr/bin/bananarchy-privacy-ctl`**: 5-tab NeoUI privacy and tunneling control center (`1:Tor`, `2:Warp`, `3:OVPN`, `4:GS`, `5:WG`, hidden and disabled in Duress Mode) with zero background CPU or battery consumption when services are turned off:
@@ -71,7 +71,7 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs
| **Nokia 8110 4G** | `nokia-argon` | Qualcomm MSM8905 (SD205) | 2x Cortex-A7 @ 1.1 GHz, 512 MB | 2.4" 240x320 SPI (`nokia,argon-gc9305-v2-panel.bin`) | `qcom-msm8905-nokia-argon.dtb` | Verified public release (`a1114`) |
| **Nokia 2720 Flip** | `nokia-beatles` | Qualcomm MSM8905 (SD205) | 2x Cortex-A7 @ 1.1 GHz, 512 MB | 2.8" 240x320 + 1.3" 240x240 cover SPI (`nokia,beatles-gc9305-panel.bin`, `nokia,beatles-gc9305-ext-panel.bin`) | `qcom-msm8905-nokia-beatles.dtb` | Verified public release (`a1114`) |
| **Nokia 800 Tough** | `nokia-coconut` | Qualcomm MSM8905 (SD205) | 2x Cortex-A7 @ 1.1 GHz, 512 MB | 2.4" 240x320 SPI (`nokia,coconut-gc9305-panel.bin`) | `qcom-msm8905-nokia-coconut.dtb` | Hardware-verified (upcoming `a1120`; `rebuild-image.sh`) |
| **Nokia 8000 4G** | `nokia-sparkler` | Qualcomm MSM8909 (SD210) | 4x Cortex-A7 @ 1.1 GHz, 512 MB | 2.8" 240x320 SPI (`nokia,sparkler-gc9307-hlt-28-panel.bin`) | `qcom-msm8909-nokia-sparkler.dtb` | Source build (`rebuild-image.sh`) |
| **Nokia 8000 4G** | `nokia-sparkler` | Qualcomm MSM8909 (SD210) | 4x Cortex-A7 @ 1.27 GHz, 512 MB | 2.8" 240x320 SPI (`nokia,sparkler-gc9307-hlt-28-panel.bin`) | `qcom-msm8909-nokia-sparkler.dtb` | Hardware-verified (upcoming `a1120`; `rebuild-image.sh`) |
| **Nokia 6300 4G** *(sibling)* | `nokia-leo` | Qualcomm MSM8909 (SD210) | 4x Cortex-A7 @ 1.1 GHz, 512 MB | 2.4" 240x320 SPI (`nokia,leo-gc9305-hlt-24-panel.bin`) | `qcom-msm8909-nokia-leo.dtb` | Source build (`rebuild-image.sh`) |
---
@@ -197,7 +197,7 @@ All components are pre-compiled in `prebuilt/` and `overlay/rootfs/`, and can be
```
Output images are written to `images/`:
- `images/bananarchy-<device>.img`: partitioned MBR image with `pmOS_boot` + `pmOS_root` for EDL `userdata`, `fastboot flash userdata`, or a microSD card.
- `images/boot-bananarchy-<device>.img`: standalone Android `boot.img` with the appended device DTB. On `nokia-beatles` and `nokia-coconut`, the default `--method lk2nd` boots the **source-built** `images/boot-lk2nd-nokia-<device>-display.img` first (`nokia-coconut.patch` layers on top of `nokia-beatles.patch` using upstream QCDT layout, `/cpus` partial-goods fix, `/lk2nd/nokia-<device>` nodes, and GC9305 v2 panel init stream; see `bootloader/lk2nd/README.md`), then lk2nd loads this kernel/DTB from `userdata` via `extlinux.conf`. The default writes lk2nd to `boot` (and refreshes `lk2nd` when present) and this standalone `boot.img` to `recovery`; `--method both` is the fallback that flashes it into both slots. Hold Volume Up (`nokia-beatles`) if the KaiOS splash persists. Stock 2720 and 800 Tough aboot images are locked, so the flasher sets `devinfo.is_unlocked=1` by default (see `scripts/make-unlocked-devinfo.py`); pass `--no-unlock-bootloader` only if you know the device is already unlocked. On `nokia-beatles`, eMMC `devinfo` unlock is effective (`VB_L` path, no `keymaster`), so EDL alone is sufficient; stock fastboot / `oem unlock-go` is not required. `--only-unlock` is optional. Before flashing an unverified `nokia-coconut` unit, back up stock partitions first with `sudo ./flash-edl.sh nokia-coconut --only-backup --dump-diagnostics` and inspect them offline with `scripts/inspect-stock-msm8905-dump.py`. After changing a device DTB, run `scripts/repack-beatles-bootimg.py` / `scripts/sync-beatles-bootfs.py --device <device> --debug-cmdline`; rebuild lk2nd with `scripts/build-lk2nd-beatles.sh` or `scripts/build-lk2nd-coconut.sh`; validate with `scripts/check-beatles-bootimg.py --device <device>`, `scripts/check-lk2nd-beatles.py` / `scripts/check-lk2nd-coconut.py`, `scripts/test-lk2nd-beatles-port.py` / `scripts/test-lk2nd-coconut-port.py`, and `scripts/sync-beatles-bootfs.py --device <device> --check`. If a 2720/800 Tough only shows the KaiOS logo and then goes dark, check `lsusb`: `05c6:900e` means aboot crashed into EDL. The confirmed cause on `nokia-beatles` was `ASSERT FAILED at (platform/msm_shared/partial_goods.c:80): 0` because lk2nd's QCDT DTBs lacked `/cpus`; both ports now add it. Flash `images/boot-lk2nd-nokia-<device>-diagnostic.img` with `--lk2nd-image --verify --dump-diagnostics` (forced fastboot + runtime `oem display-init` probe, QCDT panel fallback for chain-loading, final post-update `oem scan-dtb`, and bounded pstore console staging); see `bootloader/lk2nd/README.md`.
- `images/boot-bananarchy-<device>.img`: standalone Android `boot.img` with the appended device DTB. On `nokia-beatles`, `nokia-coconut`, and `nokia-sparkler`, the default `--method lk2nd` boots the **source-built** `images/boot-lk2nd-nokia-<device>-display.img` first (`nokia-coconut.patch` layers on top of `nokia-beatles.patch`, and `nokia-sparkler.patch` layers on top of both for MSM8909 MTP with GC9307 + ST7789VX2 SPI panel streams; see `bootloader/lk2nd/README.md`), then lk2nd loads this kernel/DTB from `userdata` via `extlinux.conf`. The default writes lk2nd to `boot` (and refreshes `lk2nd` when present) and this standalone `boot.img` to `recovery`; `--method both` is the fallback that flashes it into both slots. Hold Volume Up (`nokia-beatles`) if the KaiOS splash persists. Stock 2720, 800 Tough, and 8000 4G aboot images are locked, so the flasher sets `devinfo.is_unlocked=1` by default (see `scripts/make-unlocked-devinfo.py`); pass `--no-unlock-bootloader` only if you know the device is already unlocked. On `nokia-beatles`, eMMC `devinfo` unlock is effective (`VB_L` path, no `keymaster`), so EDL alone is sufficient; stock fastboot / `oem unlock-go` is not required. `--only-unlock` is optional. Before flashing an unverified `nokia-coconut` or `nokia-sparkler` unit, back up stock partitions first with `sudo ./flash-edl.sh <device> --only-backup --dump-diagnostics` and inspect them offline with `scripts/inspect-stock-msm8905-dump.py`. After changing a device DTB, run `scripts/repack-beatles-bootimg.py` / `scripts/sync-beatles-bootfs.py --device <device> --debug-cmdline`; rebuild lk2nd with `scripts/build-lk2nd-beatles.sh`, `scripts/build-lk2nd-coconut.sh`, or `scripts/build-lk2nd-sparkler.sh`; validate with `scripts/check-beatles-bootimg.py --device <device>`, `scripts/check-lk2nd-beatles.py` / `scripts/check-lk2nd-coconut.py` / `scripts/check-lk2nd-sparkler.py`, `scripts/test-lk2nd-beatles-port.py` / `scripts/test-lk2nd-coconut-port.py` / `scripts/test-lk2nd-sparkler-port.py` / `scripts/test-sparkler-port.py`, and `scripts/sync-beatles-bootfs.py --device <device> --check`. If a 2720/800 Tough/8000 4G only shows the KaiOS logo and then goes dark, check `lsusb`: `05c6:900e` means aboot crashed into EDL. The confirmed cause on `nokia-beatles` was `ASSERT FAILED at (platform/msm_shared/partial_goods.c:80): 0` because lk2nd's QCDT DTBs lacked `/cpus`; all three ports now add it. Flash `images/boot-lk2nd-nokia-<device>-diagnostic.img` with `--lk2nd-image --verify --dump-diagnostics` (forced fastboot + runtime `oem display-init` probe, QCDT panel fallback for chain-loading, final post-update `oem scan-dtb`, and bounded pstore console staging); see `bootloader/lk2nd/README.md`.
---
+10 -1
View File
@@ -45,5 +45,14 @@ Here are the special key mappings.
## Nokia 8000 4G (`nokia-sparkler`)
TBD
- `*` (`gpio90` `KEY_NUMERIC_STAR` and matrix row 0, col 4): `KP_Multiply`
- `#` (`pm8941_resin` `KEY_NUMERIC_POUND` and matrix row 2, col 4): `KP_Divide`
- Soft Left (`KEY_COMPOSE`, matrix row 1, col 0): `Menu`
- Soft Right (`KEY_BACK`, matrix row 3, col 1): `XF86Back`
- Soft Center (`KEY_ENTER`, matrix row 3, col 0): `Return`
- Call (`KEY_PICKUP_PHONE` `0x1bd`, matrix row 0, col 0): `XF86PickupPhone`
- Backspace / Clear (matrix row 1, col 5 and row 2, col 5): `BackSpace`
- End / Power (`pm8941_pwrkey`): `XF86PowerOff`
- Assistant / Camera slot (`KEY_CAMERA`, matrix row 0, col 5): `XF86WebCam`
- D-pad (`Left` / `Up` / `Right` / `Down`, matrix row 2 col 0 / row 3 col 3 / row 3 col 2 / row 3 col 4): `Left` / `Up` / `Right` / `Down`
+37
View File
@@ -299,3 +299,40 @@ sudo ./flash-edl.sh nokia-coconut --only-backup --dump-diagnostics --backup-dir
python3 scripts/inspect-stock-msm8905-dump.py ./backup/nokia-coconut/boot-nokia-coconut.img \
./backup/nokia-coconut/recovery-nokia-coconut.img --aboot ./backup/nokia-coconut/aboot-nokia-coconut.img
```
---
## Nokia 8000 4G (`nokia-sparkler`) layered port
Nokia 8000 4G (`nokia-sparkler`, MSM8909 MTP `0xf5`/`0x8`/`0x100`/`0`, PMIC
`0x1000d`, 512 MiB RAM, cmdline `androidboot.hw.name=sparkler`, 2.8" 240x320
SPI display on BLSP1 QUP5 `0x078b9000` with `dc-gpio=110`) builds through a
third layered patch `bootloader/lk2nd/nokia-sparkler.patch` applied after
`nokia-beatles.patch` and `nokia-coconut.patch`, keeping `nokia-beatles` and
`nokia-coconut` `lk2nd` images byte-for-byte untouched.
- **Device node, panel init streams, and boot menu keys**: `nokia-sparkler.dtsi`
adds `/lk2nd/nokia-sparkler` (`nokia,sparkler`, matching
`androidboot.hw.name=sparkler` without requiring `lk2nd,match-panel;` so
both GC9307 HLT 15-command and ST7789VX2 CTC 11-command panels match) to
`msm8909-mtp.dts`, wires `*` (`gpio90`) as `KEY_VOLUMEUP` (`0x115`) alongside
`#` (`pm8941_resin`) and Top Power for `lk2nd` boot menu navigation, and
adds `"nokia,sparkler"` / `"nokia,leo"` to `spi-display.c`.
- **Building and validating**:
```sh
./scripts/build-lk2nd-sparkler.sh
python3 scripts/check-lk2nd-sparkler.py --image images/boot-lk2nd-nokia-sparkler-display.img --expect-display 1
python3 scripts/test-lk2nd-sparkler-port.py
python3 scripts/test-sparkler-port.py
```
- **Pre-flash backup (physical hardware verification pending)**: back up stock
partitions over EDL first (using `bootloader/loaders/8k.mbn` signed
`Nokia_leo`) before flashing any physical Nokia 8000 4G unit:
```sh
sudo ./flash-edl.sh nokia-sparkler --only-backup --dump-diagnostics --backup-dir ./backup/nokia-sparkler
python3 scripts/inspect-stock-msm8905-dump.py ./backup/nokia-sparkler/boot-nokia-sparkler.img \
./backup/nokia-sparkler/recovery-nokia-sparkler.img --aboot ./backup/nokia-sparkler/aboot-nokia-sparkler.img
```
+141
View File
@@ -0,0 +1,141 @@
diff --git a/lk2nd/device/2nd/spi-display.c b/lk2nd/device/2nd/spi-display.c
index c123a39..37c94d4 100644
--- a/lk2nd/device/2nd/spi-display.c
+++ b/lk2nd/device/2nd/spi-display.c
@@ -252,7 +252,9 @@ static int spi_display_setup(void)
* even when fastboot boot replaced the original cmdline. */
if(lk2nd_dev.compatible &&
(!strcmp(lk2nd_dev.compatible, "nokia,beatles") ||
- !strcmp(lk2nd_dev.compatible, "nokia,coconut")) &&
+ !strcmp(lk2nd_dev.compatible, "nokia,coconut") ||
+ !strcmp(lk2nd_dev.compatible, "nokia,sparkler") ||
+ !strcmp(lk2nd_dev.compatible, "nokia,leo")) &&
(!lk2nd_dev.panel.intf || strcmp(lk2nd_dev.panel.intf, "spi")))
lk2nd_dev.panel.intf = "spi";
diff --git a/lk2nd/device/dts/msm8909/msm8909-mtp.dts b/lk2nd/device/dts/msm8909/msm8909-mtp.dts
index 1cea90b..e9a6edc 100644
--- a/lk2nd/device/dts/msm8909/msm8909-mtp.dts
+++ b/lk2nd/device/dts/msm8909/msm8909-mtp.dts
@@ -26,3 +26,5 @@
lk2nd,dtb-files = "msm8909-nokia-sparkler";
};
};
+
+#include "nokia-sparkler.dtsi"
diff --git a/lk2nd/device/dts/msm8909/nokia-sparkler.dtsi b/lk2nd/device/dts/msm8909/nokia-sparkler.dtsi
new file mode 100644
index 0000000..59714b8
--- /dev/null
+++ b/lk2nd/device/dts/msm8909/nokia-sparkler.dtsi
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: BSD-3-Clause
+/*
+ * Nokia 8000 4G (nokia-sparkler) lk2nd device node.
+ *
+ * The 8000 4G uses an MSM8909 MTP SoC/board variant and drives a 2.8"
+ * 240x320 RGB565 command-mode SPI panel on BLSP1 QUP5 (GC9307 HLT or
+ * ST7789VX2 CTC).
+ *
+ * lk2nd,panel-init holds the downstream KaiOS 2.5.4 qcom,mdss-spi-on-command
+ * byte stream in [wait dlen payload...] format so lk2nd can initialize the
+ * panel deterministically when booted directly or chain-loaded.
+ */
+
+&lk2nd {
+ nokia-sparkler {
+ model = "Nokia 8000 4G";
+ compatible = "nokia,sparkler";
+ lk2nd,dtb-files = "msm8909-nokia-sparkler";
+ lk2nd,menu-key-strings = "* and # keys", "Top power key";
+
+ panel {
+ compatible = "nokia,sparkler-panel";
+
+ qcom,mdss_spi_gc9307_hlt_28_qvga_cmd {
+ compatible = "nokia,sparkler-gc9307-hlt-28-panel";
+ lk2nd,panel-init = [
+ 78 01 11
+ 00 01 fe
+ 00 01 ef
+ 00 01 13
+ 00 01 38
+ 00 01 20
+ 00 02 36 00
+ 00 02 3a 05
+ 00 02 35 00
+ 00 02 89 0b
+ 00 02 eb 02
+ 00 05 2a 00 00 00 ef
+ 00 05 2b 00 00 01 3f
+ 00 01 29
+ 00 01 2c
+ ];
+ };
+
+ qcom,mdss_spi_gc9307_hlt_28_qvga_spi_cmd {
+ compatible = "nokia,sparkler-gc9307-hlt-28-panel";
+ lk2nd,panel-init = [
+ 78 01 11
+ 00 01 fe
+ 00 01 ef
+ 00 01 13
+ 00 01 38
+ 00 01 20
+ 00 02 36 00
+ 00 02 3a 05
+ 00 02 35 00
+ 00 02 89 0b
+ 00 02 eb 02
+ 00 05 2a 00 00 00 ef
+ 00 05 2b 00 00 01 3f
+ 00 01 29
+ 00 01 2c
+ ];
+ };
+
+ qcom,mdss_spi_st7789vx2_ctc_28_qvga_cmd {
+ compatible = "nokia,sparkler-st7789vx2-ctc-28-panel";
+ lk2nd,panel-init = [
+ 78 01 11
+ 00 01 29
+ 00 02 36 00
+ 00 02 3a 05
+ 00 02 35 00
+ 00 01 13
+ 00 01 38
+ 00 01 20
+ 00 05 2a 00 00 00 ef
+ 00 05 2b 00 00 01 3f
+ 00 01 2c
+ ];
+ };
+
+ qcom,mdss_spi_st7789vx2_ctc_28_qvga_spi_cmd {
+ compatible = "nokia,sparkler-st7789vx2-ctc-28-panel";
+ lk2nd,panel-init = [
+ 78 01 11
+ 00 01 29
+ 00 02 36 00
+ 00 02 3a 05
+ 00 02 35 00
+ 00 01 13
+ 00 01 38
+ 00 01 20
+ 00 05 2a 00 00 00 ef
+ 00 05 2b 00 00 01 3f
+ 00 01 2c
+ ];
+ };
+ };
+
+ gpio-keys {
+ compatible = "gpio-keys";
+
+ volume-up {
+ lk2nd,code = <KEY_VOLUMEUP>;
+ gpios = <&tlmm 90 (GPIO_ACTIVE_LOW | GPIO_PULL_UP)>;
+ };
+ };
+ };
+};
+1
View File
@@ -20,6 +20,7 @@ deviceinfo_chassis="handset"
deviceinfo_external_storage="true"
deviceinfo_screen_width="240"
deviceinfo_screen_height="320"
deviceinfo_drm="true"
# Bootloader related
deviceinfo_flash_method="fastboot"
+2
View File
@@ -1,3 +1,5 @@
pm8916-lbc
pm8916-bms-vm
panel-mipi-dbi
matrix_keypad
matrix_keymap
Binary file not shown.
@@ -42,6 +42,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x00>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -60,6 +61,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x01>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -78,6 +80,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x02>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -96,6 +99,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x03>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -7,6 +7,9 @@
model = "Nokia 8000 4G";
compatible = "nokia,sparkler", "qcom,msm8909";
chassis-type = "handset";
qcom,msm-id = <0xf5 0x00>;
qcom,board-id = <0x08 0x100>;
qcom,pmic-id = <0x1000d 0x00 0x00 0x00>;
aliases {
mmc0 = "/soc@0/sdhci@7824000";
@@ -19,7 +22,7 @@
clocks {
xo-board {
xo_board: xo-board {
compatible = "fixed-clock";
#clock-cells = <0x00>;
clock-frequency = <0x124f800>;
@@ -42,6 +45,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x00>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -60,6 +64,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x01>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -78,6 +83,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x02>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -96,6 +102,7 @@
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x03>;
clock-frequency = <1094400000>;
next-level-cache = <0x02>;
enable-method = "qcom,msm8909-smp";
clocks = <0x03>;
@@ -216,7 +223,7 @@
memory@80000000 {
device_type = "memory";
reg = <0x80000000 0x00>;
reg = <0x80000000 0x20000000>;
};
pmu {
@@ -346,7 +353,7 @@
pm8909-regulators {
compatible = "qcom,rpm-pm8909-regulators";
s2 {
pm8909_s2: s2 {
regulator-min-microvolt = <0x1c3a90>;
regulator-max-microvolt = <0x1c3a90>;
};
@@ -366,7 +373,7 @@
regulator-max-microvolt = <0x1b7740>;
};
l5 {
pm8909_l5: l5 {
regulator-min-microvolt = <0x1b7740>;
regulator-max-microvolt = <0x1b7740>;
phandle = <0x3d>;
@@ -418,7 +425,7 @@
phandle = <0x45>;
};
l13 {
pm8909_l13: l13 {
regulator-min-microvolt = <0x2eebb8>;
regulator-max-microvolt = <0x2eebb8>;
phandle = <0x68>;
@@ -1064,6 +1071,23 @@
phandle = <0x7d>;
};
cdc-pdm-lines {
pdm_lines_on: pdm-lines-on {
pins = "gpio59", "gpio60", "gpio61", "gpio62", "gpio63", "gpio64";
function = "cdc_pdm0";
drive-strength = <0x08>;
bias-disable;
};
pdm_lines_off: pdm-lines-off {
pins = "gpio59", "gpio60", "gpio61", "gpio62", "gpio63", "gpio64";
function = "cdc_pdm0";
drive-strength = <0x02>;
bias-pull-down;
};
};
panel-gpios-default-state {
pins = "gpio24", "gpio25", "gpio110";
function = "gpio";
@@ -1153,7 +1177,7 @@
};
};
spmi@200f000 {
spmi_bus: spmi@200f000 {
compatible = "qcom,spmi-pmic-arb";
reg = <0x200f000 0x1000 0x2400000 0x400000 0x2c00000 0x400000 0x3800000 0x200000 0x200a000 0x2100>;
reg-names = "core", "chnls", "obsrvr", "intr", "cnfg";
@@ -1299,6 +1323,25 @@
reg = <0xc000>;
status = "disabled";
};
wcd_codec: audio-codec@f000 {
compatible = "qcom,pm8916-wcd-analog-codec";
reg = <0xf000>;
reg-names = "pmic-codec-core";
interrupt-parent = <&spmi_bus>;
interrupts = <0x01 0xf0 0x00 0x00 0x01 0xf0 0x01 0x00 0x01 0xf0 0x02 0x00 0x01 0xf0 0x03 0x00 0x01 0xf0 0x04 0x00 0x01 0xf0 0x05 0x00 0x01 0xf0 0x06 0x00 0x01 0xf0 0x07 0x00 0x01 0xf1 0x00 0x00 0x01 0xf1 0x01 0x00 0x01 0xf1 0x02 0x00 0x01 0xf1 0x03 0x00 0x01 0xf1 0x04 0x00 0x01 0xf1 0x05 0x00>;
interrupt-names = "cdc_spk_cnp_int", "cdc_spk_clip_int", "cdc_spk_ocp_int", "mbhc_ins_rem_det1", "mbhc_but_rel_det", "mbhc_but_press_det", "mbhc_ins_rem_det", "mbhc_switch_int", "cdc_ear_ocp_int", "cdc_hphr_ocp_int", "cdc_hphl_ocp_det", "cdc_ear_cnp_int", "cdc_hphr_cnp_int", "cdc_hphl_cnp_int";
#sound-dai-cells = <0x01>;
status = "okay";
qcom,hphl-jack-type-normally-open;
qcom,micbias1-ext-cap;
qcom,micbias2-ext-cap;
qcom,mbhc-vthreshold-low = <0x4b 0x96 0xe1 0x1c2 0x1f4>;
qcom,mbhc-vthreshold-high = <0x4b 0x96 0xe1 0x1c2 0x1f4>;
vdd-cdc-io-supply = <&pm8909_l5>;
vdd-cdc-tx-rx-cx-supply = <&pm8909_s2>;
vdd-micbias-supply = <&pm8909_l13>;
};
};
};
@@ -1357,7 +1400,264 @@
qcom,ipc = <0x03 0x08 0x0c>;
qcom,remote-pid = <0x01>;
label = "hexagon";
apr {
compatible = "qcom,apr-v2";
qcom,smd-channels = "apr_audio_svc";
qcom,apr-domain = <0x04>;
#address-cells = <0x01>;
#size-cells = <0x00>;
status = "okay";
apr-service@3 {
reg = <0x03>;
compatible = "qcom,q6core";
};
apr-service@4 {
compatible = "qcom,q6afe";
reg = <0x04>;
q6afedai: dais {
compatible = "qcom,q6afe-dais";
#address-cells = <0x01>;
#size-cells = <0x00>;
#sound-dai-cells = <0x01>;
dai@16 {
reg = <0x10>;
qcom,sd-lines = <0x00 0x01>;
};
dai@20 {
reg = <0x15>;
qcom,sd-lines = <0x00 0x01>;
};
dai@136 {
reg = <0x88>;
};
dai@137 {
reg = <0x89>;
};
};
q6afeclk: clock-controller {
compatible = "qcom,q6afe-clocks";
#clock-cells = <0x02>;
};
};
apr-service@7 {
compatible = "qcom,q6asm";
reg = <0x07>;
q6asmdai: dais {
compatible = "qcom,q6asm-dais";
#address-cells = <0x01>;
#size-cells = <0x00>;
#sound-dai-cells = <0x01>;
dai@0 {
reg = <0x00>;
direction = <0x02>;
};
dai@1 {
reg = <0x01>;
direction = <0x01>;
};
dai@2 {
reg = <0x02>;
direction = <0x02>;
};
dai@3 {
reg = <0x03>;
direction = <0x02>;
is-compress-dai;
};
};
};
apr-service@8 {
compatible = "qcom,q6adm";
reg = <0x08>;
q6adm_routing: routing {
compatible = "qcom,q6adm-routing";
#sound-dai-cells = <0x00>;
};
};
apr-service@9 {
compatible = "qcom,q6mvm";
reg = <0x09>;
q6voicedai: dais {
compatible = "qcom,q6voice-dais";
#sound-dai-cells = <0x01>;
};
};
apr-service@a {
compatible = "qcom,q6cvs";
reg = <0x0a>;
};
apr-service@b {
compatible = "qcom,q6cvp";
reg = <0x0b>;
};
};
};
};
sound@7702000 {
status = "okay";
compatible = "qcom,msm8916-qdsp6-sndcard";
reg = <0x7702000 0x04 0x7702004 0x04>;
reg-names = "mic-iomux", "spkr-iomux";
model = "msm8916";
audio-routing = "AMIC1", "MIC BIAS External1", "AMIC2", "MIC BIAS Internal2", "AMIC3", "MIC BIAS External1";
pinctrl-names = "default", "sleep";
pinctrl-0 = <&pdm_lines_on>;
pinctrl-1 = <&pdm_lines_off>;
dai-link-multimedia1 {
link-name = "MultiMedia1";
cpu {
sound-dai = <&q6asmdai 0x00>;
};
};
dai-link-multimedia2 {
link-name = "MultiMedia2";
cpu {
sound-dai = <&q6asmdai 0x01>;
};
};
dai-link-multimedia3 {
link-name = "MultiMedia3";
status = "disabled";
cpu {
sound-dai = <&q6asmdai 0x02>;
};
};
dai-link-multimedia4 {
link-name = "MultiMedia4";
cpu {
sound-dai = <&q6asmdai 0x03>;
};
};
dai-link-voicemmode1 {
link-name = "VoiceMMode1";
cpu {
sound-dai = <&q6voicedai 0x01>;
};
};
dai-link-primary {
link-name = "Primary MI2S";
cpu {
sound-dai = <&q6afedai 0x10>;
};
platform {
sound-dai = <&q6adm_routing>;
};
codec {
sound-dai = <&lpass_codec 0x00 &wcd_codec 0x00>;
};
};
dai-link-secondary {
link-name = "Secondary MI2S";
status = "disabled";
cpu {
sound-dai = <&q6afedai 0x12>;
};
platform {
sound-dai = <&q6adm_routing>;
};
};
dai-link-tertiary {
link-name = "Tertiary MI2S";
cpu {
sound-dai = <&q6afedai 0x15>;
};
platform {
sound-dai = <&q6adm_routing>;
};
codec {
sound-dai = <&lpass_codec 0x01 &wcd_codec 0x01>;
};
};
dai-link-quaternary {
link-name = "Quaternary MI2S";
status = "disabled";
cpu {
sound-dai = <&q6afedai 0x16>;
};
platform {
sound-dai = <&q6adm_routing>;
};
};
dai-link-bt-sco-rx {
link-name = "Internal BT-SCO RX";
cpu {
sound-dai = <&q6afedai 0x88>;
};
platform {
sound-dai = <&q6adm_routing>;
};
};
dai-link-bt-sco-tx {
link-name = "Internal BT-SCO TX";
cpu {
sound-dai = <&q6afedai 0x89>;
};
platform {
sound-dai = <&q6adm_routing>;
};
};
};
lpass_codec: audio-codec@771c000 {
compatible = "qcom,msm8916-wcd-digital-codec";
reg = <0x771c000 0x400>;
clocks = <&xo_board &q6afeclk 0x32 0x01>;
clock-names = "ahbix-clk", "mclk";
assigned-clocks = <&q6afeclk 0x32 0x01>;
assigned-clock-rates = <0x927c00>;
#sound-dai-cells = <0x01>;
};
sdhci@7824000 {
@@ -2073,7 +2373,7 @@
pinctrl-names = "default";
row-gpios = <0x27 0x61 0x01 0x27 0x60 0x01 0x27 0x5f 0x01 0x27 0x5e 0x01>;
col-gpios = <0x27 0x00 0x01 0x27 0x03 0x01 0x27 0x07 0x01 0x27 0x63 0x01 0x27 0x06 0x01 0x27 0x01 0x01>;
linux,keymap = <0x1bd 0x10002 0x20005 0x30008 0x4020a 0x5008b 0x10002b8 0x1010003 0x1020006 0x1030009 0x104000b 0x105000e 0x2000069 0x2010004 0x2020007 0x203000a 0x204020b 0x20501be 0x300001c 0x30102b9 0x302006a 0x3030067 0x304006c>;
linux,keymap = <0x1bd 0x10002 0x20005 0x30008 0x4020a 0x500d4 0x100007f 0x1010003 0x1020006 0x1030009 0x104000b 0x105000e 0x2000069 0x2010004 0x2020007 0x203000a 0x204020b 0x205000e 0x300001c 0x301009e 0x302006a 0x3030067 0x304006c>;
};
leds {
+66 -33
View File
@@ -13,6 +13,7 @@ import usb.util
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_USER_PASSWORD = os.environ.get("BANANARCHY_USER_PASSWORD", "147147")
DEFAULT_USB_IO_TIMEOUT_SEC = 30
# The EDL client library is vendored under vendor/edl so a clean clone can
# flash without any manual download. A local edl/ checkout takes precedence
@@ -85,6 +86,11 @@ VARIANT_LOADER_IDENTITIES = {
# so a power-cycle is not needed just because the PID changed.
EDL_PIDS = (0x9008, 0x900E, 0x9006)
# On nokia-sparkler (8000 4G) and nokia-leo (6300 4G), * (gpio90) and #
# (pm8941_resin) wire to Volume Up + Volume Down in SBL1/aboot, so holding
# * + # while plugging in USB enters EDL (instead of D-Pad Up + D-Pad Down).
EDL_STAR_HASH_DEVICES = ("nokia-sparkler", "nokia-leo")
# images/boot-lk2nd-nokia-beatles.img is built from upstream lk2nd source plus
# bootloader/lk2nd/nokia-beatles.patch (see bootloader/lk2nd/README.md). It has
# a dedicated QCDT DTB for the exact stock 2720 IDs (0x14b/0x1000b/0x100), a
@@ -92,10 +98,10 @@ EDL_PIDS = (0x9008, 0x900E, 0x9006)
# and cmdline lk2nd.compatible=nokia,beatles. aboot hands off to lk2nd, lk2nd
# brings up the 240x320 RGB565 main panel and boots Bananarchy from userdata
# via extlinux.conf. This is the default path on nokia-beatles.
BOOT_IMAGE_DEVICES = ("nokia-beatles", "nokia-coconut")
# Stock 2720/800 Tough aboot has secure boot enabled and devinfo is locked. Writing a
BOOT_IMAGE_DEVICES = ("nokia-beatles", "nokia-coconut", "nokia-sparkler")
# Stock 2720/800 Tough/8000 4G/6300 4G aboot has secure boot enabled and devinfo is locked. Writing a
# custom boot.img (lk2nd or mainline) is rejected unless devinfo.is_unlocked=1.
UNLOCK_DEFAULT_DEVICES = ("nokia-beatles", "nokia-coconut")
UNLOCK_DEFAULT_DEVICES = ("nokia-beatles", "nokia-coconut", "nokia-sparkler", "nokia-leo")
DEVINFO_MAGIC = b"ANDROID-BOOT!"
DEVINFO_UNLOCKED_OFFSET = 13
DEVINFO_TAMPERED_OFFSET = 14
@@ -109,9 +115,11 @@ OEM_UNLOCK_FLAG_OFFSET = -1
# binary-patch the prebuilt bootloader/lk2nd-msm8909.img.
BEATLES_LK2ND_IMAGE = "images/boot-lk2nd-nokia-beatles-display.img"
COCONUT_LK2ND_IMAGE = "images/boot-lk2nd-nokia-coconut-display.img"
SPARKLER_LK2ND_IMAGE = "images/boot-lk2nd-nokia-sparkler-display.img"
DEVICE_LK2ND_IMAGES = {
"nokia-beatles": BEATLES_LK2ND_IMAGE,
"nokia-coconut": COCONUT_LK2ND_IMAGE,
"nokia-sparkler": SPARKLER_LK2ND_IMAGE,
}
BOOT_METHOD_PARTITIONS = {
"lk2nd": "boot", # lk2nd image into boot
@@ -134,7 +142,7 @@ DIAG_PARTITIONS = (
)
def _fb_read_status(ep_in, timeout_ms=5000):
def _fb_read_status(ep_in, timeout_ms=15000):
while True:
resp = bytes(ep_in.read(64, timeout=timeout_ms))
if resp.startswith(b"INFO"):
@@ -156,9 +164,9 @@ def _fb_send_edl(fb_dev):
if ep_out is None or ep_in is None:
return False
for cmd in (b"oem reboot-edl", b"oem edl"):
ep_out.write(cmd, timeout=1000)
ep_out.write(cmd, timeout=5000)
try:
resp = _fb_read_status(ep_in, timeout_ms=1500)
resp = _fb_read_status(ep_in, timeout_ms=5000)
if resp.startswith(b"OKAY"):
break
except Exception:
@@ -187,24 +195,24 @@ def _fb_upgrade_lk2nd_and_edl(fb_dev):
if ep_out is None or ep_in is None:
return
ep_out.write(f"download:{len(lk2nd_data):08x}".encode("ascii"), timeout=2000)
resp = _fb_read_status(ep_in, timeout_ms=2000)
ep_out.write(f"download:{len(lk2nd_data):08x}".encode("ascii"), timeout=5000)
resp = _fb_read_status(ep_in, timeout_ms=5000)
if not resp.startswith(b"DATA"):
return
chunk_sz = 16384
for off in range(0, len(lk2nd_data), chunk_sz):
ep_out.write(lk2nd_data[off:off + chunk_sz], timeout=5000)
if not _fb_read_status(ep_in, timeout_ms=5000).startswith(b"OKAY"):
ep_out.write(lk2nd_data[off:off + chunk_sz], timeout=15000)
if not _fb_read_status(ep_in, timeout_ms=15000).startswith(b"OKAY"):
return
ep_out.write(b"flash:boot", timeout=2000)
if not _fb_read_status(ep_in, timeout_ms=10000).startswith(b"OKAY"):
ep_out.write(b"flash:boot", timeout=5000)
if not _fb_read_status(ep_in, timeout_ms=30000).startswith(b"OKAY"):
return
ep_out.write(b"reboot-bootloader", timeout=2000)
ep_out.write(b"reboot-bootloader", timeout=5000)
try:
_fb_read_status(ep_in, timeout_ms=2000)
_fb_read_status(ep_in, timeout_ms=5000)
except Exception:
pass
usb.util.dispose_resources(fb_dev)
@@ -231,11 +239,11 @@ def try_kick_into_edl():
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
timeout=2,
timeout=5,
)
if res.returncode == 0 and "device" in res.stdout:
print("[*] Detected device in ADB mode. Sending 'adb reboot edl'...")
subprocess.run(["adb", "reboot", "edl"], timeout=5)
subprocess.run(["adb", "reboot", "edl"], timeout=10)
return
except Exception:
pass
@@ -257,18 +265,25 @@ def try_kick_into_edl():
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
timeout=2,
timeout=5,
)
if res.returncode == 0 and res.stdout.strip():
print("[*] Detected device in Fastboot mode. Sending 'fastboot oem reboot-edl'...")
rc = subprocess.run(["fastboot", "oem", "reboot-edl"], timeout=5)
rc = subprocess.run(["fastboot", "oem", "reboot-edl"], timeout=10)
if rc.returncode != 0:
subprocess.run(["fastboot", "oem", "edl"], timeout=5)
subprocess.run(["fastboot", "oem", "edl"], timeout=10)
except Exception:
pass
def wait_for_edl_usb(vid, pids, device_label, timeout_sec=0):
def edl_button_combo_hint(device=""):
if device in EDL_STAR_HASH_DEVICES:
return "* + #"
return "D-Pad Up + D-Pad Down"
def wait_for_edl_usb(vid, pids, device_label, timeout_sec=0, device="",
usb_timeout_ms=DEFAULT_USB_IO_TIMEOUT_SEC * 1000):
if isinstance(pids, int):
pids = (pids,)
pids = tuple(pids)
@@ -278,7 +293,7 @@ def wait_for_edl_usb(vid, pids, device_label, timeout_sec=0):
)
print(" To enter EDL mode on the phone, use one of:")
print(" 1) From lk2nd Fastboot menu, select 'EDL' (or connect in Fastboot mode)")
print(" 2) Power off, hold D-Pad Up + D-Pad Down, and plug in USB")
print(f" 2) Power off, hold {edl_button_combo_hint(device)}, and plug in USB")
print(" 3) Plug in via an EDL deep-flash cable")
print(" 4) Run 'adb reboot edl' or 'fastboot oem reboot-edl'")
@@ -290,7 +305,7 @@ def wait_for_edl_usb(vid, pids, device_label, timeout_sec=0):
for pid in pids:
if usb.core.find(idVendor=vid, idProduct=pid) is None:
continue
cdc = usb_class(vid=vid, pid=pid)
cdc = usb_class(vid=vid, pid=pid, timeout_ms=usb_timeout_ms)
try:
cdc.connected = cdc.connect()
except usb.core.USBError as exc:
@@ -660,9 +675,9 @@ def parse_args():
"--method",
choices=["lk2nd", "boot", "recovery", "both"],
default="",
help="Boot method (default: lk2nd for all targets). On nokia-beatles "
"and nokia-coconut lk2nd is written to boot and lk2nd, mainline "
"boot.img to recovery; both writes boot.img to boot and recovery",
help="Boot method (default: lk2nd for all targets). On nokia-beatles, "
"nokia-coconut, and nokia-sparkler lk2nd is written to boot and lk2nd, "
"mainline boot.img to recovery; both writes boot.img to boot and recovery",
)
parser.add_argument(
"--boot-image",
@@ -673,8 +688,8 @@ def parse_args():
parser.add_argument(
"--lk2nd-image",
default="",
help="Override the nokia-beatles/nokia-coconut lk2nd boot.img written to 'boot' "
"(e.g. images/boot-lk2nd-nokia-coconut-diagnostic.img for diagnostic logs)",
help="Override the nokia-beatles/nokia-coconut/nokia-sparkler lk2nd boot.img written to 'boot' "
"(e.g. images/boot-lk2nd-nokia-sparkler-diagnostic.img for diagnostic logs)",
)
parser.add_argument(
"--variant",
@@ -723,7 +738,7 @@ def parse_args():
parser.add_argument(
"--unlock-bootloader",
action="store_true",
help="Set devinfo.is_unlocked=1 (default on nokia-beatles/nokia-coconut; "
help="Set devinfo.is_unlocked=1 (default on nokia-beatles/nokia-coconut/nokia-sparkler/nokia-leo; "
"needed for locked stock aboot to accept an unsigned boot.img)",
)
parser.add_argument(
@@ -734,7 +749,7 @@ def parse_args():
parser.add_argument(
"--enable-oem-unlock",
action="store_true",
help="Patch config/frp allow-unlock flag (default on nokia-beatles/nokia-coconut). "
help="Patch config/frp allow-unlock flag (default on nokia-beatles/nokia-coconut/nokia-sparkler/nokia-leo). "
"Required before 'fastboot oem unlock-go' can write RPMB devinfo",
)
parser.add_argument(
@@ -768,6 +783,12 @@ def parse_args():
default=0,
help="Timeout in seconds while waiting for USB connection (0 = infinite)",
)
parser.add_argument(
"--usb-timeout",
type=int,
default=DEFAULT_USB_IO_TIMEOUT_SEC,
help="Per-transfer USB bulk read/write timeout in seconds (default: 30)",
)
parser.add_argument(
"--vid",
default="0x05C6",
@@ -854,6 +875,7 @@ def main():
if method == "lk2nd" and device in DEVICE_LK2ND_IMAGES:
print(f" LK2ND (boot) : {device_lk2nd_img} ({device} source port)")
print(f" Boot Image (rec) : {mainline_img}")
if not (method == "lk2nd" and device in DEVICE_LK2ND_IMAGES):
print(f" Bootloader (boot): {bootloader_img}")
print(f" System (userdata): {userdata_img}")
print(
@@ -894,7 +916,14 @@ def main():
vid = int(args.vid, 16)
pids = [int(args.pid, 16)] if args.pid else list(EDL_PIDS)
cdc = wait_for_edl_usb(vid, pids, device_label, timeout_sec=args.timeout)
cdc = wait_for_edl_usb(
vid,
pids,
device_label,
timeout_sec=args.timeout,
device=device,
usb_timeout_ms=max(1, args.usb_timeout) * 1000,
)
sahara = qualcomm_sahara(cdc)
with open(loader_mbn, "rb") as rf:
@@ -1064,7 +1093,8 @@ def main():
print(" UNLOCK PREPARATION COMPLETE")
print("============================================================")
print(" The stock aboot reads devinfo from RPMB, not eMMC. To finish:")
print(" 1. Power off, hold Volume Down, plug USB to enter fastboot.")
fastboot_key = "# (Volume Down)" if device in EDL_STAR_HASH_DEVICES else "Volume Down"
print(f" 1. Power off, hold {fastboot_key}, plug USB to enter fastboot.")
print(" 2. Run: fastboot oem unlock-go")
print(" (Confirm on-screen if asked; this wipes userdata.)")
print(" 3. Re-enter EDL and run the normal flash again.")
@@ -1191,9 +1221,12 @@ def main():
print(" boot now holds Bananarchy boot.img: a normal power-on boots it.")
print(" (system superblock wiped; restore boot + system from stock firmware")
print(" if you ever want KaiOS back.)")
elif method == "lk2nd" and device == "nokia-beatles":
print(" boot and lk2nd hold the display-enabled nokia-beatles lk2nd port; recovery holds the mainline boot.img.")
elif method == "lk2nd" and device in ("nokia-beatles", "nokia-coconut", "nokia-sparkler"):
print(" boot and lk2nd hold the display-enabled %s lk2nd port; recovery holds the mainline boot.img." % device)
print(" Normal power-on: aboot -> lk2nd -> extlinux -> Bananarchy.")
if device == "nokia-sparkler":
print(" Alternate recovery slot (# / Volume Down at power-on): aboot -> recovery -> mainline boot.img -> Bananarchy.")
else:
print(" Volume Up: aboot -> recovery -> mainline boot.img -> Bananarchy.")
else:
print(" The phone will now boot via lk2nd into Bananarchy Linux (Sxmo).")
+14018 -14018
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+1
View File
@@ -4,6 +4,7 @@ name="Exit plymouthd"
description="Stop plymouthd before running the graphical UI"
depend() {
after dbus elogind
before display-manager
before tinydm
}
@@ -137,7 +137,7 @@ if ! pidof -s Xorg >/dev/null 2>&1; then
"$XORG_BIN" :0 -s 0 -nolisten tcp -config "$XORG_CONFIG" -modulepath "$XORG_MODPATH" -logfile /dev/null -logverbose 0 >/dev/null 2>&1 </dev/null &
fi
i=0
while [ "$i" -lt 40 ]; do
while [ "$i" -lt 200 ]; do
if xset s off s noblank s 0 0 >/dev/null 2>&1; then
break
fi
+407
View File
@@ -0,0 +1,407 @@
#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2022 Sxmo Contributors
# title="$icon_clk Timer"
# include common definitions
# shellcheck source=scripts/core/sxmo_common.sh
. sxmo_common.sh
RUNTIME_DIR="${XDG_RUNTIME_DIR:-/tmp}"
TIMER_DIR="${SXMO_TIMER_DIR:-$RUNTIME_DIR/sxmo_timers}"
RING_FLAG="${SXMO_TIMER_RING_FLAG:-/tmp/sxmo_timer_ringing}"
TIMER_FILE=""
CHILD_SLEEP_PID=""
CHILD_SOUND_PID=""
CHILD_VIB_PID=""
ORIG_STTY=""
_cleanup_children() {
for p in "$CHILD_SLEEP_PID" "$CHILD_SOUND_PID" "$CHILD_VIB_PID"; do
if [ -n "$p" ]; then
kill "$p" 2>/dev/null || true
fi
done
CHILD_SLEEP_PID=""
CHILD_SOUND_PID=""
CHILD_VIB_PID=""
}
_finish_timerrun() {
trap - HUP INT TERM EXIT
_cleanup_children
if [ -n "$TIMER_FILE" ]; then
rm -f "$TIMER_FILE" 2>/dev/null || true
fi
if [ -f "$RING_FLAG" ]; then
cur_ring_pid=""
IFS= read -r cur_ring_pid < "$RING_FLAG" 2>/dev/null || true
if [ -z "$cur_ring_pid" ] || [ "$cur_ring_pid" = "$$" ]; then
rm -f "$RING_FLAG" 2>/dev/null || true
fi
fi
if [ -n "$ORIG_STTY" ] && [ -t 0 ]; then
stty "$ORIG_STTY" 2>/dev/null || true
ORIG_STTY=""
fi
exit 0
}
_fmt_hms() {
sec="$1"
[ "$sec" -lt 0 ] 2>/dev/null && sec=0
h=$(( sec / 3600 ))
m=$(( (sec % 3600) / 60 ))
s=$(( sec % 60 ))
printf '%02d:%02d:%02d' "$h" "$m" "$s"
}
_prune_stale_timers() {
[ -d "$TIMER_DIR" ] || return 0
for f in "$TIMER_DIR"/*.timer; do
[ -e "$f" ] || continue
pid="${f##*/}"
pid="${pid%.timer}"
case "$pid" in
''|*[!0-9]*)
rm -f "$f" 2>/dev/null || true
continue
;;
esac
if ! kill -0 "$pid" 2>/dev/null; then
rm -f "$f" 2>/dev/null || true
fi
done
if [ -f "$RING_FLAG" ]; then
rpid=""
IFS= read -r rpid < "$RING_FLAG" 2>/dev/null || true
case "$rpid" in
''|*[!0-9]*) rm -f "$RING_FLAG" 2>/dev/null || true ;;
*) kill -0 "$rpid" 2>/dev/null || rm -f "$RING_FLAG" 2>/dev/null || true ;;
esac
fi
}
status() {
_prune_stale_timers
found=1
if [ -d "$TIMER_DIR" ]; then
for f in "$TIMER_DIR"/*.timer; do
[ -e "$f" ] || continue
pid="${f##*/}"
pid="${pid%.timer}"
state=""
end_ts=""
label=""
IFS=' ' read -r state end_ts label < "$f" 2>/dev/null || continue
printf '%s %s %s %s\n' "$pid" "$state" "$end_ts" "$label"
found=0
done
fi
return "$found"
}
stop() {
_prune_stale_timers
if [ -d "$TIMER_DIR" ]; then
for f in "$TIMER_DIR"/*.timer; do
[ -e "$f" ] || continue
pid="${f##*/}"
pid="${pid%.timer}"
kill -TERM "$pid" 2>/dev/null || true
rm -f "$f" 2>/dev/null || true
done
fi
rm -f "$RING_FLAG" 2>/dev/null || true
killall -q -TERM sxmo_vibrate bananarchy-melody pw-play 2>/dev/null || true
dunstctl close-all >/dev/null 2>&1 || true
return 0
}
stop_ringing() {
_prune_stale_timers
stopped=0
if [ -d "$TIMER_DIR" ]; then
for f in "$TIMER_DIR"/*.timer; do
[ -e "$f" ] || continue
pid="${f##*/}"
pid="${pid%.timer}"
state=""
end_ts=""
label=""
IFS=' ' read -r state end_ts label < "$f" 2>/dev/null || continue
if [ "$state" = "ringing" ]; then
kill -TERM "$pid" 2>/dev/null || true
rm -f "$f" 2>/dev/null || true
stopped=1
fi
done
fi
if [ -f "$RING_FLAG" ]; then
rpid=""
IFS= read -r rpid < "$RING_FLAG" 2>/dev/null || true
case "$rpid" in
''|*[!0-9]*) ;;
*) kill -TERM "$rpid" 2>/dev/null || true ;;
esac
rm -f "$RING_FLAG" 2>/dev/null || true
stopped=1
fi
if [ "$stopped" -eq 1 ]; then
killall -q -TERM sxmo_vibrate bananarchy-melody pw-play 2>/dev/null || true
dunstctl close-all >/dev/null 2>&1 || true
fi
return 0
}
_is_dnd_active() {
[ -f "$RUNTIME_DIR/sxmo.busy" ] && return 0
cfg_home="${XDG_CONFIG_HOME:-$HOME/.config}"
if [ -f "$cfg_home/sxmo/.busy" ]; then
end=""
IFS= read -r end < "$cfg_home/sxmo/.busy" 2>/dev/null || true
case "$end" in
'') return 0 ;;
*[!0-9]*) return 1 ;;
*) [ "$(date +%s)" -lt "$end" ] && return 0 ;;
esac
fi
return 1
}
_play_timer_alert() {
_is_dnd_active && return 0
cfg_home="${XDG_CONFIG_HOME:-$HOME/.config}"
if [ -f "$cfg_home/sxmo/ringsettings" ]; then
# shellcheck disable=SC1091
. "$cfg_home/sxmo/ringsettings"
fi
notif_sound=""
if [ -s "$cfg_home/sxmo/notif_sound" ]; then
IFS= read -r notif_sound < "$cfg_home/sxmo/notif_sound" || true
fi
[ -z "$notif_sound" ] && notif_sound="${SXMO_TEXTSOUND:-}"
if [ -z "$notif_sound" ]; then
if [ -f "/usr/share/sxmo/ringtones/Soft_Bell.wav" ]; then
notif_sound="/usr/share/sxmo/ringtones/Soft_Bell.wav"
elif [ -f "/usr/share/sxmo/notify.ogg" ]; then
notif_sound="/usr/share/sxmo/notify.ogg"
fi
fi
if [ ! -f "$cfg_home/sxmo/.noring" ] && \
[ "$notif_sound" != "NONE" ] && [ "$notif_sound" != "none" ] && \
[ -n "$notif_sound" ] && [ -f "$notif_sound" ]; then
case "${SXMO_RINGVOL:-100}" in
''|*[!0-9]*) SXMO_RINGVOL=100 ;;
esac
if [ "$SXMO_RINGVOL" -gt 0 ]; then
notif_ext="$(printf '%s' "${notif_sound##*.}" | tr '[:upper:]' '[:lower:]')"
notif_play="$notif_sound"
case "$notif_ext" in
nrt|rtttl|rtx|emy|imy)
notif_play="$RUNTIME_DIR/sxmo_monotone_timer.wav"
bananarchy-melody --wav "$notif_sound" "$notif_play" >/dev/null 2>&1 || notif_play=""
;;
esac
if [ -n "$notif_play" ] && [ -f "$notif_play" ]; then
if command -v pw-play >/dev/null 2>&1 && [ -S "$RUNTIME_DIR/pipewire-0" ]; then
pw_vol="$(awk -v v="$SXMO_RINGVOL" 'BEGIN { s = v / 100.0; if (s < 0.0) s = 0.0; if (s > 1.0) s = 1.0; printf "%.2f", s }')"
pw-play --volume="$pw_vol" "$notif_play" >/dev/null 2>&1 &
CHILD_SOUND_PID=$!
elif command -v mpv >/dev/null 2>&1; then
mpv_vol=$(( SXMO_RINGVOL * 130 / 100 ))
mpv --no-config --no-terminal --no-resume-playback --quiet --no-video \
--end=3 --volume-max=150 --volume="$mpv_vol" "$notif_play" >/dev/null 2>&1 &
CHILD_SOUND_PID=$!
fi
fi
fi
fi
if [ ! -f "$cfg_home/sxmo/.novibrate" ]; then
sxmo_vibrate 800 "${SXMO_VIBRATE_STRENGTH:-2}" >/dev/null 2>&1 &
CHILD_VIB_PID=$!
fi
}
_read_tty_key_1s() {
dd bs=1 count=1 2>/dev/null | LC_ALL=C tr '\r\n\033\177\010' 'EEXBB' 2>/dev/null || true
}
_sleep_1s_or_cancel_key() {
if [ -t 0 ]; then
key="$(_read_tty_key_1s)"
case "$key" in
E|"0"|"q"|"Q"|'*'|'#'|X|B)
return 0
;;
esac
return 1
fi
sxmo_aligned_sleep 1 >/dev/null 2>&1 &
CHILD_SLEEP_PID=$!
wait "$CHILD_SLEEP_PID" 2>/dev/null || true
CHILD_SLEEP_PID=""
return 1
}
_sleep_1s_or_any_key() {
if [ -t 0 ]; then
key="$(_read_tty_key_1s)"
[ -n "$key" ] && return 0
return 1
fi
sleep 1 &
CHILD_SLEEP_PID=$!
wait "$CHILD_SLEEP_PID" 2>/dev/null || true
CHILD_SLEEP_PID=""
return 1
}
timerrun() {
trap '_finish_timerrun' HUP INT TERM EXIT
RAW_LABEL="$*"
TIME="$(
printf '%s\n' "$@" |
sed 's/\([^0-9]\)\([0-9]\)/\1+\2/g; s/h/*60m/g; s/m/*60s/g; s/s//g' |
bc 2>/dev/null
)"
case "$TIME" in
''|*[!0-9]*)
printf 'Invalid timer duration: %s\n' "$RAW_LABEL" >&2
exit 1
;;
esac
if [ "$TIME" -le 0 ]; then
printf 'Timer duration must be > 0s\n' >&2
exit 1
fi
mkdir -p "$TIMER_DIR" 2>/dev/null || true
TIMER_FILE="$TIMER_DIR/$$.timer"
NOW="$(date +%s)"
DATE1="$((NOW + TIME))"
printf 'running %s %s\n' "$DATE1" "$RAW_LABEL" > "$TIMER_FILE"
if [ -t 0 ]; then
ORIG_STTY="$(stty -g 2>/dev/null || true)"
stty -icanon -echo min 0 time 10 2>/dev/null || true
fi
printf 'Timer: %s\nPress Enter, 0, or q to cancel\n' "$RAW_LABEL"
while :; do
NOW="$(date +%s)"
REM=$((DATE1 - NOW))
if [ "$REM" -le 0 ]; then
break
fi
printf '\r%s ' "$(_fmt_hms "$REM")"
if _sleep_1s_or_cancel_key; then
printf '\nTimer cancelled.\n'
exit 0
fi
done
NOW="$(date +%s)"
printf 'ringing %s %s\n' "$NOW" "$RAW_LABEL" > "$TIMER_FILE"
printf '%s\n' "$$" > "$RING_FLAG"
printf '\r00:00:00 \nDone with %s\nPress any key or Menu -> Stop Timer\n' "$RAW_LABEL"
/usr/bin/bananarchy-screen-wake.sh >/dev/null 2>&1 || true
/usr/bin/bananarchy-cover-event.sh notification >/dev/null 2>&1 || true
if command -v dunstify >/dev/null 2>&1; then
dunstify -u critical -r 991042 -t 30000 "Timer" "Done with $RAW_LABEL" >/dev/null 2>&1 || true
else
notify-send -u critical -t 30000 "Done with $RAW_LABEL" >/dev/null 2>&1 || true
fi
MAX_RING_SECS="${SXMO_TIMER_RING_SECS:-30}"
case "$MAX_RING_SECS" in
''|*[!0-9]*) MAX_RING_SECS=30 ;;
esac
RING_END="$(( $(date +%s) + MAX_RING_SECS ))"
while [ -f "$RING_FLAG" ] && [ "$(date +%s)" -lt "$RING_END" ]; do
_play_timer_alert
for _tick in 1 2; do
[ ! -f "$RING_FLAG" ] && break 2
[ "$(date +%s)" -ge "$RING_END" ] && break 2
if _sleep_1s_or_any_key; then
printf '\nTimer stopped.\n'
_cleanup_children
break 2
fi
done
done
}
stopwatchrun() {
reset() {
start="$(date +%s)"
printf '\33[1A\33[2K\r%s\n' "$(date -u -d "@$time" +%H:%M:%S)"
if [ -n "$sid" ]; then
kill "$sid" >/dev/null 2>&1 || true
fi
}
finish() {
jobs -p | xargs -r kill >/dev/null 2>&1 || true
wait 2>/dev/null || true
exit 0
}
trap finish HUP INT TERM EXIT
start="$(date +%s)"
printf 'Stopwatch (Enter=Lap, q/0=Quit)\n'
(
trap reset USR1
while :; do
time="$(($(date +%s) - start))"
printf '\33[2K\r%s' "$(date -u -d "@$time" +%H:%M:%S)"
sxmo_aligned_sleep 1 &
sid=$!
wait
done
) &
jid=$!
while IFS= read -r line; do
case "$line" in
q|Q|0)
kill "$jid" >/dev/null 2>&1 || true
exit 0
;;
*)
kill -s USR1 "$jid" 2>/dev/null || true
;;
esac
done
}
menu() {
_prune_stale_timers
stop_entry=""
if [ -f "$RING_FLAG" ]; then
stop_entry="Stop Timer\n"
elif status >/dev/null 2>&1; then
stop_entry="Cancel Active Timer\n"
fi
TIMEINPUT="$(printf '%bStopwatch\n1h\n30m\n15m\n10m\n9m\n8m\n7m\n6m\n5m\n4m\n3m\n2m\n1m\n30s\nClose Menu\n' "$stop_entry" | sxmo_dmenu.sh -p Timer)" || exit
case "$TIMEINPUT" in
"Close Menu"|"")
exit 0
;;
"Stop Timer"|"Cancel Active Timer")
stop
;;
"Stopwatch")
sxmo_terminal.sh "$0" stopwatchrun
;;
*)
sxmo_terminal.sh "$0" timerrun "$TIMEINPUT"
;;
esac
}
if [ $# -gt 0 ]; then
"$@"
else
menu
fi
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -12,6 +12,7 @@
rm -f /tmp/sxmo_call_ringing 2>/dev/null || true
sxmo_jobs.sh stop ringing
killall -q -TERM bananarchy-melody sxmo_vibrate pw-play mpv 2>/dev/null || true
/usr/bin/sxmo_timer.sh stop_ringing >/dev/null 2>&1 || true
rpids="$(pgrep -f '[s]xmo_hook_ring\.sh|[p]w-play.*ring|[m]pv.*ring' 2>/dev/null || true)"
[ -n "$rpids" ] && kill -TERM $rpids 2>/dev/null || true
@@ -11,6 +11,7 @@
rm -f /tmp/sxmo_call_ringing 2>/dev/null || true
sxmo_jobs.sh stop ringing
killall -q -TERM bananarchy-melody sxmo_vibrate pw-play mpv 2>/dev/null || true
/usr/bin/sxmo_timer.sh stop_ringing >/dev/null 2>&1 || true
rpids="$(pgrep -f '[s]xmo_hook_ring\.sh|[p]w-play.*ring|[m]pv.*ring' 2>/dev/null || true)"
[ -n "$rpids" ] && kill -TERM $rpids 2>/dev/null || true
@@ -0,0 +1,165 @@
diff --git a/arch/arm/boot/dts/qcom/qcom-msm8909.dtsi b/arch/arm/boot/dts/qcom/qcom-msm8909.dtsi
index af87a9a..6112cda 100644
--- a/arch/arm/boot/dts/qcom/qcom-msm8909.dtsi
+++ b/arch/arm/boot/dts/qcom/qcom-msm8909.dtsi
@@ -49,6 +49,7 @@ cpu0: cpu@0 {
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x0>;
+ clock-frequency = <1094400000>;
next-level-cache = <&L2_0>;
enable-method = "qcom,msm8909-smp";
clocks = <&apcs>;
@@ -65,6 +66,7 @@ cpu1: cpu@1 {
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x1>;
+ clock-frequency = <1094400000>;
next-level-cache = <&L2_0>;
enable-method = "qcom,msm8909-smp";
clocks = <&apcs>;
@@ -81,6 +83,7 @@ cpu2: cpu@2 {
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x2>;
+ clock-frequency = <1094400000>;
next-level-cache = <&L2_0>;
enable-method = "qcom,msm8909-smp";
clocks = <&apcs>;
@@ -97,6 +100,7 @@ cpu3: cpu@3 {
device_type = "cpu";
compatible = "arm,cortex-a7";
reg = <0x3>;
+ clock-frequency = <1094400000>;
next-level-cache = <&L2_0>;
enable-method = "qcom,msm8909-smp";
clocks = <&apcs>;
diff --git a/drivers/cpufreq/qcom-cpufreq-nvmem.c b/drivers/cpufreq/qcom-cpufreq-nvmem.c
index cecbd1e..f8e302c 100644
--- a/drivers/cpufreq/qcom-cpufreq-nvmem.c
+++ b/drivers/cpufreq/qcom-cpufreq-nvmem.c
@@ -508,6 +508,9 @@ static int qcom_cpufreq_probe(struct platform_device *pdev)
.supported_hw = NULL,
};
+ if (!cpu_present(cpu))
+ continue;
+
cpu_dev = get_cpu_device(cpu);
if (NULL == cpu_dev) {
ret = -ENODEV;
@@ -571,7 +574,8 @@ static int qcom_cpufreq_probe(struct platform_device *pdev)
free_opp:
for_each_possible_cpu(cpu) {
qcom_cpufreq_put_virt_devs(drv, cpu);
- dev_pm_opp_clear_config(drv->cpus[cpu].opp_token);
+ if (drv->cpus[cpu].opp_token > 0)
+ dev_pm_opp_clear_config(drv->cpus[cpu].opp_token);
}
return ret;
}
@@ -585,7 +589,8 @@ static void qcom_cpufreq_remove(struct platform_device *pdev)
for_each_possible_cpu(cpu) {
qcom_cpufreq_put_virt_devs(drv, cpu);
- dev_pm_opp_clear_config(drv->cpus[cpu].opp_token);
+ if (drv->cpus[cpu].opp_token > 0)
+ dev_pm_opp_clear_config(drv->cpus[cpu].opp_token);
}
}
diff --git a/drivers/firmware/qcom/qcom_scm-smc.c b/drivers/firmware/qcom/qcom_scm-smc.c
index 2b4c282..c2032e4 100644
--- a/drivers/firmware/qcom/qcom_scm-smc.c
+++ b/drivers/firmware/qcom/qcom_scm-smc.c
@@ -13,6 +13,10 @@
#include <linux/firmware/qcom/qcom_tzmem.h>
#include <linux/arm-smccc.h>
#include <linux/dma-mapping.h>
+#include <linux/mm.h>
+#ifdef CONFIG_ARM
+#include <asm/cacheflush.h>
+#endif
#include "qcom_scm.h"
@@ -156,6 +160,7 @@ int __scm_smc_call(struct device *dev, const struct qcom_scm_desc *desc,
int arglen = desc->arginfo & 0xf;
int i, ret;
void *args_virt __free(qcom_tzmem) = NULL;
+ void *early_virt __free(kfree) = NULL;
gfp_t flag = atomic ? GFP_ATOMIC : GFP_KERNEL;
u32 smccc_call_type = atomic ? ARM_SMCCC_FAST_CALL : ARM_SMCCC_STD_CALL;
u32 qcom_smccc_convention = (qcom_convention == SMC_CONVENTION_ARM_32) ?
@@ -173,27 +178,45 @@ int __scm_smc_call(struct device *dev, const struct qcom_scm_desc *desc,
smc.args[i + SCM_SMC_FIRST_REG_IDX] = desc->args[i];
if (unlikely(arglen > SCM_SMC_N_REG_ARGS)) {
- args_virt = qcom_tzmem_alloc(mempool,
- SCM_SMC_N_EXT_ARGS * sizeof(u64),
- flag);
- if (!args_virt)
- return -ENOMEM;
+ void *ext_virt;
+
+ if (mempool) {
+ args_virt = qcom_tzmem_alloc(mempool,
+ SCM_SMC_N_EXT_ARGS * sizeof(u64),
+ flag);
+ if (!args_virt)
+ return -ENOMEM;
+ ext_virt = args_virt;
+ } else {
+ /* Early SMP setup runs before qcom_scm creates its tzmem pool. */
+ early_virt = kzalloc(PAGE_SIZE, flag);
+ if (!early_virt)
+ return -ENOMEM;
+ ext_virt = early_virt;
+ }
if (qcom_smccc_convention == ARM_SMCCC_SMC_32) {
- __le32 *args = args_virt;
+ __le32 *args = ext_virt;
for (i = 0; i < SCM_SMC_N_EXT_ARGS; i++)
args[i] = cpu_to_le32(desc->args[i +
SCM_SMC_FIRST_EXT_IDX]);
} else {
- __le64 *args = args_virt;
+ __le64 *args = ext_virt;
for (i = 0; i < SCM_SMC_N_EXT_ARGS; i++)
args[i] = cpu_to_le64(desc->args[i +
SCM_SMC_FIRST_EXT_IDX]);
}
- smc.args[SCM_SMC_LAST_REG_IDX] = qcom_tzmem_to_phys(args_virt);
+ if (mempool) {
+ smc.args[SCM_SMC_LAST_REG_IDX] = qcom_tzmem_to_phys(args_virt);
+ } else {
+#ifdef CONFIG_ARM
+ __sync_cache_range_w(early_virt, PAGE_SIZE);
+#endif
+ smc.args[SCM_SMC_LAST_REG_IDX] = virt_to_phys(early_virt);
+ }
}
ret = __scm_smc_do(dev, &smc, &smc_res, atomic);
diff --git a/drivers/firmware/qcom/qcom_scm.c b/drivers/firmware/qcom/qcom_scm.c
index 2e4260b..bae849f 100644
--- a/drivers/firmware/qcom/qcom_scm.c
+++ b/drivers/firmware/qcom/qcom_scm.c
@@ -406,11 +406,10 @@ static int qcom_scm_set_boot_addr_mc(void *entry, unsigned int flags)
},
};
- /* Need a device for DMA of the additional arguments */
- if (!__scm || __get_convention() == SMC_CONVENTION_LEGACY)
+ if (__get_convention() == SMC_CONVENTION_LEGACY)
return -EOPNOTSUPP;
- return qcom_scm_call(__scm->dev, &desc, NULL);
+ return qcom_scm_call(__scm ? __scm->dev : NULL, &desc, NULL);
}
/**
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+13
View File
@@ -30,6 +30,10 @@ case "$BA_TARGET" in
DISPLAY_IMAGE="images/boot-lk2nd-nokia-coconut-display.img"
BOOT_IMAGE="images/boot-bananarchy-nokia-coconut.img"
;;
nokia-sparkler)
DISPLAY_IMAGE="images/boot-lk2nd-nokia-sparkler-display.img"
BOOT_IMAGE="images/boot-bananarchy-nokia-sparkler.img"
;;
esac
display_lk2nd_is_current() {
@@ -47,6 +51,14 @@ display_lk2nd_is_current() {
--patch bootloader/lk2nd/nokia-coconut.patch \
--expect-fastboot 0 --expect-display 1 >/dev/null 2>&1
;;
nokia-sparkler)
python3 scripts/check-lk2nd-sparkler.py \
--image "$DISPLAY_IMAGE" \
--beatles-patch bootloader/lk2nd/nokia-beatles.patch \
--coconut-patch bootloader/lk2nd/nokia-coconut.patch \
--patch bootloader/lk2nd/nokia-sparkler.patch \
--expect-fastboot 0 --expect-display 1 >/dev/null 2>&1
;;
*) return 1 ;;
esac
}
@@ -71,6 +83,7 @@ if [ -n "$DISPLAY_IMAGE" ] && \
case "$BA_TARGET" in
nokia-beatles) ./scripts/build-lk2nd-beatles.sh ;;
nokia-coconut) ./scripts/build-lk2nd-coconut.sh ;;
nokia-sparkler) ./scripts/build-lk2nd-sparkler.sh ;;
esac
fi
+2
View File
@@ -193,7 +193,9 @@ EOF
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/dwm-plugin
$CC $OPT_CFLAGS -std=c99 -D_DEFAULT_SOURCE -Wall -Wextra \
$(pkgconf --cflags alsa) \
/bananarchy/src/dwm-plugins/sxmo_vibrate.c \
$(pkgconf --libs alsa) -lm \
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/sxmo_vibrate
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/sxmo_vibrate
+6
View File
@@ -104,6 +104,10 @@ EOF
echo "[2k/5] Applying MSM8909 72h standby Wi-Fi, WCD analog, panel, LDO, and BMS patch..."
patch -p1 < /bananarchy/patches/kernel/0012-msm8909-standby-wifi-wcd-panel-ldo-bms.patch
fi
if ! grep -q "early_virt" drivers/firmware/qcom/qcom_scm-smc.c 2>/dev/null; then
echo "[2l/5] Applying MSM8909 early-SCM SMP boot address and cpufreq patch..."
patch -p1 < /bananarchy/patches/kernel/0013-msm8909-early-scm-smp-cpufreq.patch
fi
if [ ! -f include/config/auto.conf ] || \
! grep -q "CONFIG_NETFILTER_XT_MATCH_OWNER=m" .config 2>/dev/null || \
! grep -q "CONFIG_INTERCONNECT_QCOM_MSM8909=y" .config 2>/dev/null || \
@@ -150,6 +154,8 @@ EOF
patch -p1 < /bananarchy/patches/kernel/0011-msm8909-boot-icc-opp-usb-audio-fixes.patch
echo "[2k/5] Applying MSM8909 72h standby Wi-Fi, WCD analog, panel, LDO, and BMS patch..."
patch -p1 < /bananarchy/patches/kernel/0012-msm8909-standby-wifi-wcd-panel-ldo-bms.patch
echo "[2l/5] Applying MSM8909 early-SCM SMP boot address and cpufreq patch..."
patch -p1 < /bananarchy/patches/kernel/0013-msm8909-early-scm-smp-cpufreq.patch
echo "[3/5] Preparing kernel configuration and Module.symvers..."
cp /bananarchy/patches/kernel/config-bananarchy-msm8909.armv7 .config
+164
View File
@@ -0,0 +1,164 @@
#!/bin/sh
# Build the nokia-sparkler (Nokia 8000 4G) lk2nd boot images from upstream source.
#
# ./scripts/build-lk2nd-sparkler.sh build normal + diagnostic + display
# ./scripts/build-lk2nd-sparkler.sh --check validate the built images only
# ./scripts/build-lk2nd-sparkler.sh --only normal build just one variant
# ./scripts/build-lk2nd-sparkler.sh --force-panel-init append lk2nd.force-panel-init to
# the normal image cmdline
# WITH_DISPLAY=1 ./scripts/build-lk2nd-sparkler.sh enable the SPI display during boot
#
# Applies nokia-beatles.patch, nokia-coconut.patch, and nokia-sparkler.patch cleanly on top
# of pinned upstream lk2nd.
set -eu
BASE_DIR=$(cd "$(dirname "$0")/.." && pwd)
UPSTREAM=https://github.com/msm8916-mainline/lk2nd.git
COMMIT=cf45aefd22d744b2bf9b39455afae697ce430063
BEATLES_PATCH="$BASE_DIR/bootloader/lk2nd/nokia-beatles.patch"
COCONUT_PATCH="$BASE_DIR/bootloader/lk2nd/nokia-coconut.patch"
SPARKLER_PATCH="$BASE_DIR/bootloader/lk2nd/nokia-sparkler.patch"
NORMAL_IMAGE="$BASE_DIR/images/boot-lk2nd-nokia-sparkler.img"
DIAG_IMAGE="$BASE_DIR/images/boot-lk2nd-nokia-sparkler-diagnostic.img"
DISPLAY_IMAGE="$BASE_DIR/images/boot-lk2nd-nokia-sparkler-display.img"
DOCKER_IMAGE=bananarchy-lk2nd-build:local
BUILD_DIR=${BANANARCHY_LK2ND_BUILD_DIR:-"$BASE_DIR/.lk2nd-build"}
CHECK_ONLY=0
ONLY=all
FORCE_PANEL_INIT=0
WITH_DISPLAY=${WITH_DISPLAY:-0}
while [ $# -gt 0 ]; do
case "$1" in
--check) CHECK_ONLY=1 ;;
--only) shift; ONLY=${1:-all} ;;
--force-panel-init) FORCE_PANEL_INIT=1 ;;
--with-display) WITH_DISPLAY=1 ;;
*) echo "[!] unknown option: $1" >&2; exit 1 ;;
esac
shift
done
CMD_BASE="lk2nd lk2nd.compatible=nokia,sparkler"
if [ "$WITH_DISPLAY" != 1 ]; then
CMD_BASE="$CMD_BASE lk2nd.no-display"
fi
if [ "$FORCE_PANEL_INIT" = 1 ]; then
CMD_BASE="$CMD_BASE lk2nd.force-panel-init"
fi
CMD_DIAG="lk2nd lk2nd.compatible=nokia,sparkler lk2nd.no-display"
CMD_DISPLAY="lk2nd lk2nd.compatible=nokia,sparkler lk2nd.display=on"
check_images() {
python3 "$BASE_DIR/scripts/check-lk2nd-sparkler.py" \
--image "$NORMAL_IMAGE" --beatles-patch "$BEATLES_PATCH" \
--coconut-patch "$COCONUT_PATCH" --patch "$SPARKLER_PATCH" \
--expect-fastboot 0
python3 "$BASE_DIR/scripts/check-lk2nd-sparkler.py" \
--image "$DIAG_IMAGE" --beatles-patch "$BEATLES_PATCH" \
--coconut-patch "$COCONUT_PATCH" --patch "$SPARKLER_PATCH" \
--expect-fastboot 1
python3 "$BASE_DIR/scripts/check-lk2nd-sparkler.py" \
--image "$DISPLAY_IMAGE" --beatles-patch "$BEATLES_PATCH" \
--coconut-patch "$COCONUT_PATCH" --patch "$SPARKLER_PATCH" \
--expect-fastboot 0 --expect-display 1
}
if [ "$CHECK_ONLY" = 1 ]; then
check_images
exit 0
fi
for tool in git docker python3; do
if ! command -v "$tool" >/dev/null 2>&1; then
echo "[!] $tool is required" >&2
exit 1
fi
done
for patch in "$BEATLES_PATCH" "$COCONUT_PATCH" "$SPARKLER_PATCH"; do
if [ ! -f "$patch" ]; then
echo "[!] missing $patch" >&2
exit 1
fi
done
if [ -n "${BANANARCHY_LK2ND_SRC:-}" ]; then
SRC=$BANANARCHY_LK2ND_SRC
else
SRC="$BUILD_DIR/src"
mkdir -p "$BUILD_DIR"
if [ ! -d "$SRC/.git" ]; then
git init -q "$SRC"
git -C "$SRC" remote add origin "$UPSTREAM"
fi
head=$(git -C "$SRC" rev-parse HEAD 2>/dev/null || true)
if [ "$head" != "$COMMIT" ]; then
echo "[*] fetching upstream lk2nd at $COMMIT"
git -C "$SRC" fetch --depth 1 origin "$COMMIT"
git -C "$SRC" checkout -q FETCH_HEAD
fi
git -C "$SRC" reset --hard -q HEAD
git -C "$SRC" clean -fdq
fi
head=$(git -C "$SRC" rev-parse HEAD 2>/dev/null || true)
if [ "$head" != "$COMMIT" ]; then
echo "[!] $SRC is at ${head:-unknown}, expected $COMMIT" >&2
exit 1
fi
apply_patch() {
label=$1
patch=$2
if git -C "$SRC" apply --check --reverse "$patch" 2>/dev/null; then
echo "[*] $label patch already applied"
else
echo "[*] applying $label patch"
git -C "$SRC" apply --check "$patch"
git -C "$SRC" apply "$patch"
fi
}
apply_patch "nokia-beatles" "$BEATLES_PATCH"
apply_patch "nokia-coconut" "$COCONUT_PATCH"
apply_patch "nokia-sparkler" "$SPARKLER_PATCH"
# Keep the standalone header copy synchronized if built from a clean clone.
cp "$BASE_DIR/bootloader/lk2nd/spi-panel-init.h" "$SRC/lk2nd/include/lk2nd/spi-panel-init.h"
if ! docker image inspect "$DOCKER_IMAGE" >/dev/null 2>&1; then
echo "[*] building the arm-none-eabi toolchain image"
docker build -t "$DOCKER_IMAGE" "$BASE_DIR/bootloader/lk2nd"
fi
build_variant() {
label=$1
version=$2
extra=$3
cmdline=$4
out=$5
echo "[*] building lk2nd-msm8909 ($label)"
# shellcheck disable=SC2086
docker run --rm --user "$(id -u):$(id -g)" \
-v "$SRC:/src" -w /src "$DOCKER_IMAGE" \
make TOOLCHAIN_PREFIX=arm-none-eabi- \
LK2ND_VERSION="$version" \
MKBOOTIMG_CMDLINE="$cmdline" \
$extra -j"${JOBS:-4}" lk2nd-msm8909
mkdir -p "$(dirname "$out")"
cp "$SRC/build-lk2nd-msm8909/lk2nd.img" "$out"
echo "[*] wrote $out"
sha256sum "$out"
}
if [ "$ONLY" = all ] || [ "$ONLY" = normal ]; then
build_variant normal bananarchy-sparkler-a1120-r1 "" "$CMD_BASE" "$NORMAL_IMAGE"
fi
if [ "$ONLY" = all ] || [ "$ONLY" = diagnostic ]; then
build_variant diagnostic bananarchy-sparkler-a1120-diag-r1 \
"DEBUG=2 LK2ND_FORCE_FASTBOOT=1" "$CMD_DIAG" "$DIAG_IMAGE"
fi
if [ "$ONLY" = all ] || [ "$ONLY" = display ]; then
build_variant display bananarchy-sparkler-a1120-display-r1 "" "$CMD_DISPLAY" "$DISPLAY_IMAGE"
fi
check_images
+41 -14
View File
@@ -27,14 +27,37 @@ STOCK_BOARD_ID = struct.pack(">2I", 0x1000b, 0x100)
STOCK_PMIC_ID = struct.pack(">4I", 0x1000d, 0, 0, 0)
MEMORY_512M = struct.pack(">2I", 0x80000000, 0x20000000)
DEVICE_MODELS = {
"nokia-beatles": "Nokia 2720 Flip",
"nokia-coconut": "Nokia 800 Tough",
}
DEVICE_SHORT = {
"nokia-beatles": "2720",
"nokia-coconut": "800 Tough",
DEVICE_SPECS = {
"nokia-beatles": {
"model": "Nokia 2720 Flip",
"short": "2720",
"compatible": b"nokia,beatles",
"msm_id": STOCK_MSM_ID,
"board_id": STOCK_BOARD_ID,
"pmic_id": STOCK_PMIC_ID,
"addrs": (0x80008000, 0x81000000, 0x80000100),
},
"nokia-coconut": {
"model": "Nokia 800 Tough",
"short": "800 Tough",
"compatible": b"nokia,coconut",
"msm_id": STOCK_MSM_ID,
"board_id": STOCK_BOARD_ID,
"pmic_id": STOCK_PMIC_ID,
"addrs": (0x80008000, 0x81000000, 0x80000100),
},
"nokia-sparkler": {
"model": "Nokia 8000 4G",
"short": "8000 4G",
"compatible": b"nokia,sparkler",
"msm_id": struct.pack(">2I", 0xf5, 0),
"board_id": struct.pack(">2I", 0x8, 0x100),
"pmic_id": STOCK_PMIC_ID,
"addrs": (0x80008000, 0x82700000, 0x82500000),
},
}
DEVICE_MODELS = {dev: spec["model"] for dev, spec in DEVICE_SPECS.items()}
DEVICE_SHORT = {dev: spec["short"] for dev, spec in DEVICE_SPECS.items()}
def align(value, page):
@@ -110,8 +133,9 @@ def parse_args():
def main():
args = parse_args()
device = args.device
short_name = DEVICE_SHORT[device]
expected_model = DEVICE_MODELS[device]
spec = DEVICE_SPECS[device]
short_name = spec["short"]
expected_model = spec["model"]
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
boot = args.image or os.path.join(base, "images", "boot-bananarchy-%s.img" % device)
if not os.path.isfile(boot):
@@ -137,7 +161,7 @@ def main():
for flag in ("loglevel=8", "ignore_loglevel", "initcall_debug"):
if flag in cmdline_parts:
problems.append("cmdline still has kernel debug flag %s" % flag)
if kernel_addr != 0x80008000 or ramdisk_addr != 0x81000000 or tags_addr != 0x80000100:
if (kernel_addr, ramdisk_addr, tags_addr) != spec["addrs"]:
problems.append("boot header load addresses do not match the stock %s" % short_name)
kernel_off = page
dtb_rel = struct.unpack_from("<I", data, kernel_off + DTB_OFFSET_FIELD)[0]
@@ -155,11 +179,14 @@ def main():
model = root.get("model", b"").rstrip(b"\0").decode("utf-8", "replace")
if model != expected_model:
problems.append("appended DTB model is %r (expected %r)" % (model, expected_model))
for prop, expected in (("qcom,msm-id", STOCK_MSM_ID),
("qcom,board-id", STOCK_BOARD_ID),
("qcom,pmic-id", STOCK_PMIC_ID)):
compat_tokens = [c for c in root.get("compatible", b"").split(b"\0") if c]
if spec["compatible"] not in compat_tokens:
problems.append("appended DTB compatible %r lacks %r" % (compat_tokens, spec["compatible"]))
for prop, expected in (("qcom,msm-id", spec["msm_id"]),
("qcom,board-id", spec["board_id"]),
("qcom,pmic-id", spec["pmic_id"])):
if root.get(prop) != expected:
problems.append("%s does not match the stock %s QRD SKUB value" % (prop, short_name))
problems.append("%s does not match the expected %s value" % (prop, short_name))
mem = None
for path, props in nodes.items():
if props.get("device_type") == b"memory\0":
+469
View File
@@ -0,0 +1,469 @@
#!/usr/bin/env python3
"""Validate the source-built nokia-sparkler lk2nd boot image.
Checks (all offline, pure Python):
* Android boot.img header, cmdline, and SEANDROIDENFORCE trailer.
* QCDT v2 exact MSM8909 MTP entry (0xf5 / 0x8 / 0x100 / 0).
* Every unique QCDT DTB has /cpus/cpu@2 and /cpus/cpu@3 with a 4-byte
device_type (the partial-goods ASSERT fix).
* /lk2nd/nokia-sparkler node: model, compatible, match-cmdline, dtb-files,
menu-key-strings, gpio-keys/volume-up, and all four panel init streams
(GC9307 HLT 15-command and ST7789VX2 CTC 11-command variants).
* Base (beatles), coconut, and sparkler patch layers plus shared
spi-panel-init.h stay in sync.
"""
import argparse
import os
import struct
import sys
BOOT_MAGIC = b"ANDROID!"
QCDT_MAGIC = b"QCDT"
FDT_MAGIC = 0xd00dfeed
FDT_BEGIN_NODE = 1
FDT_END_NODE = 2
FDT_PROP = 3
FDT_NOP = 4
FDT_END = 9
STOCK_PLATFORM_ID = 0xf5
STOCK_VARIANT_ID = 0x8
STOCK_SUBTYPE = 0x100
STOCK_SOC_REV = 0
BOARD_ID = [STOCK_VARIANT_ID, STOCK_SUBTYPE]
EXPECTED_MENU_KEYS = ["* and # keys", "Top power key"]
KEY_VOLUMEUP_CODE = 0x115
GC9307_PANELS = (
"qcom,mdss_spi_gc9307_hlt_28_qvga_cmd",
"qcom,mdss_spi_gc9307_hlt_28_qvga_spi_cmd",
)
ST7789VX2_PANELS = (
"qcom,mdss_spi_st7789vx2_ctc_28_qvga_cmd",
"qcom,mdss_spi_st7789vx2_ctc_28_qvga_spi_cmd",
)
PANEL_SPECS = (
(GC9307_PANELS[0], 15, 58, "GC9307 HLT"),
(GC9307_PANELS[1], 15, 58, "GC9307 HLT SPI"),
(ST7789VX2_PANELS[0], 11, 44, "ST7789VX2 CTC"),
(ST7789VX2_PANELS[1], 11, 44, "ST7789VX2 CTC SPI"),
)
RGB565 = bytes([0x3a, 0x05])
COLUMN_WINDOW = bytes([0x2a, 0x00, 0x00, 0x00, 0xef])
ROW_WINDOW = bytes([0x2b, 0x00, 0x00, 0x01, 0x3f])
def align(value, page):
return (value + page - 1) // page * page
def fdt_nodes(data):
vals = struct.unpack_from(">10I", data, 0)
magic, totalsize, off_struct, off_strings, _, version = vals[:6]
size_strings, size_struct = vals[8], vals[9]
if magic != FDT_MAGIC or version not in (16, 17):
raise ValueError("invalid FDT header")
strings = data[off_strings:off_strings + size_strings]
nodes = {}
stack = []
pos = off_struct
while True:
token = struct.unpack_from(">I", data, pos)[0]
pos += 4
if token == FDT_BEGIN_NODE:
end = data.index(b"\0", pos)
name = data[pos:end].decode("utf-8", "replace")
pos = (end + 4) & ~3
if not stack:
path = "/"
elif stack[-1] == "/":
path = "/" + name
else:
path = stack[-1] + "/" + name
stack.append(path)
nodes[path] = {}
elif token == FDT_END_NODE:
stack.pop()
if not stack:
break
elif token == FDT_PROP:
length, nameoff = struct.unpack_from(">II", data, pos)
pos += 8
value = data[pos:pos + length]
pos = (pos + length + 3) & ~3
end = strings.index(b"\0", nameoff)
prop = strings[nameoff:end].decode("utf-8", "replace")
nodes[stack[-1]][prop] = value
elif token == FDT_NOP:
continue
elif token == FDT_END:
break
else:
raise ValueError("bad FDT token 0x%x" % token)
return nodes, totalsize
def prop_str(nodes, path, prop):
return nodes.get(path, {}).get(prop, b"").rstrip(b"\0").decode("utf-8", "replace")
def prop_strlist(nodes, path, prop):
raw = nodes.get(path, {}).get(prop, b"")
if not raw:
return []
return [s.decode("utf-8", "replace") for s in raw.rstrip(b"\0").split(b"\0")]
def prop_cells(nodes, path, prop):
raw = nodes.get(path, {}).get(prop, b"")
return list(struct.unpack(">%dI" % (len(raw) // 4), raw[:len(raw) // 4 * 4]))
def parse_stream(raw):
"""Return (commands, total_delay) or raise ValueError."""
off = 0
commands = []
total_delay = 0
while off + 2 <= len(raw):
wait, dlen = raw[off], raw[off + 1]
off += 2
if not dlen or off + dlen > len(raw):
raise ValueError("malformed command at byte %d" % (off - 2))
payload = raw[off:off + dlen]
off += dlen
commands.append((wait, payload))
total_delay += wait
if off != len(raw):
raise ValueError("trailing garbage at byte %d" % off)
return commands, total_delay
def check_stream(name, raw, expected_cmds, expected_bytes, problems):
if len(raw) != expected_bytes:
problems.append("%s panel init has %d bytes, expected %d" %
(name, len(raw), expected_bytes))
try:
commands, total_delay = parse_stream(raw)
except ValueError as exc:
problems.append("%s panel init stream: %s" % (name, exc))
return None
if len(commands) != expected_cmds:
problems.append("%s panel init has %d commands, expected %d" %
(name, len(commands), expected_cmds))
if total_delay != 120:
problems.append("%s panel init waits %d ms total, expected 120" %
(name, total_delay))
payloads = [payload for _, payload in commands]
for label, want in (("RGB565 COLMOD", RGB565),
("240 column window", COLUMN_WINDOW),
("320 row window", ROW_WINDOW)):
if want not in payloads:
problems.append("%s panel init is missing the %s command" % (name, label))
if b"\x11" not in payloads:
problems.append("%s panel init is missing sleep-out (0x11)" % name)
if b"\x29" not in payloads:
problems.append("%s panel init is missing display-on (0x29)" % name)
if not payloads or payloads[-1] != b"\x2c":
problems.append("%s panel init does not end with RAMWR (0x2c)" % name)
return commands
def check_device_node(nodes, label, problems):
prefix = "%s: " % label
if prop_cells(nodes, "/", "qcom,msm-id")[:2] != [STOCK_PLATFORM_ID, 0]:
problems.append(prefix + "qcom,msm-id is not the stock 0xf5/0")
board = prop_cells(nodes, "/", "qcom,board-id")
if board != BOARD_ID:
problems.append(prefix + "qcom,board-id is %r, expected %r" % (board, BOARD_ID))
if "/chosen" not in nodes:
problems.append(prefix + "missing /chosen")
if not any(props.get("device_type") == b"memory\0" for props in nodes.values()):
problems.append(prefix + "missing /memory node")
subnodes = sorted(p for p in nodes if p.startswith("/lk2nd/") and
p.count("/") == 2)
for needed in ("/lk2nd/nokia-leo", "/lk2nd/nokia-sparkler"):
if needed not in subnodes:
problems.append(prefix + "missing %s" % needed)
node = "/lk2nd/nokia-sparkler"
if node not in nodes:
problems.append(prefix + "missing /lk2nd/nokia-sparkler")
return None
props = nodes[node]
if prop_str(nodes, node, "model") != "Nokia 8000 4G":
problems.append(prefix + "wrong model %r" % prop_str(nodes, node, "model"))
if prop_str(nodes, node, "compatible") != "nokia,sparkler":
problems.append(prefix + "wrong compatible %r" %
prop_str(nodes, node, "compatible"))
if prop_str(nodes, node, "lk2nd,match-cmdline") != "* androidboot.hw.name=sparkler *":
problems.append(prefix + "wrong lk2nd,match-cmdline %r" %
prop_str(nodes, node, "lk2nd,match-cmdline"))
if "lk2nd,match-panel" in props:
problems.append(prefix + "sparkler node must not require lk2nd,match-panel")
if prop_str(nodes, node, "lk2nd,dtb-files") != "msm8909-nokia-sparkler":
problems.append(prefix + "wrong lk2nd,dtb-files %r" %
prop_str(nodes, node, "lk2nd,dtb-files"))
if prop_strlist(nodes, node, "lk2nd,menu-key-strings") != EXPECTED_MENU_KEYS:
problems.append(prefix + "wrong lk2nd,menu-key-strings %r" %
prop_strlist(nodes, node, "lk2nd,menu-key-strings"))
keys_node = node + "/gpio-keys"
vol_up_node = keys_node + "/volume-up"
if keys_node not in nodes or prop_str(nodes, keys_node, "compatible") != "gpio-keys":
problems.append(prefix + "missing /lk2nd/nokia-sparkler/gpio-keys")
elif vol_up_node not in nodes:
problems.append(prefix + "missing /lk2nd/nokia-sparkler/gpio-keys/volume-up")
else:
if prop_cells(nodes, vol_up_node, "lk2nd,code") != [KEY_VOLUMEUP_CODE]:
problems.append(prefix + "volume-up lk2nd,code is %r, expected [%d]" %
(prop_cells(nodes, vol_up_node, "lk2nd,code"),
KEY_VOLUMEUP_CODE))
gpios = prop_cells(nodes, vol_up_node, "gpios")
if len(gpios) != 3 or gpios[1] != 90:
problems.append(prefix + "volume-up gpios %r must target gpio 90" % (gpios,))
streams = {}
for name, expected_cmds, expected_bytes, desc in PANEL_SPECS:
panel = node + "/panel/" + name
if panel not in nodes:
problems.append(prefix + "missing %s panel node %s" % (desc, name))
continue
if "lk2nd,panel-init" not in nodes[panel]:
problems.append(prefix + "panel %s has no lk2nd,panel-init" % name)
else:
raw = nodes[panel]["lk2nd,panel-init"]
streams[name] = raw
check_stream(name, raw, expected_cmds, expected_bytes, problems)
return streams
def extract_patch_file(patch_text, path):
"""Return the added-file body for a 'new file' diff section."""
marker = "diff --git a/%s b/%s\n" % (path, path)
start = patch_text.find(marker)
if start < 0:
return None
lines = patch_text[start:].split("\n")
out = []
started = False
for line in lines[1:]:
if line.startswith("@@"):
started = True
continue
if not started:
continue
if line.startswith("diff --git "):
break
if line.startswith("+"):
out.append(line[1:])
return "\n".join(out) + "\n"
def format_c_array(name, raw):
lines = ["static const unsigned char %s[] = {" % name]
for i in range(0, len(raw), 12):
lines.append(" " + ", ".join("0x%02x" % x for x in raw[i:i + 12]) + ",")
lines.append("};")
return lines
def main():
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--image", default=os.path.join(base, "images", "boot-lk2nd-nokia-sparkler.img"))
ap.add_argument("--beatles-patch", default=os.path.join(base, "bootloader", "lk2nd", "nokia-beatles.patch"))
ap.add_argument("--coconut-patch", default=os.path.join(base, "bootloader", "lk2nd", "nokia-coconut.patch"))
ap.add_argument("--patch", default=os.path.join(base, "bootloader", "lk2nd", "nokia-sparkler.patch"))
ap.add_argument("--emit-streams-header", default=None,
help="write the GC9307 and ST7789VX2 panel init streams as C arrays")
ap.add_argument("--expect-fastboot", type=int, choices=(0, 1), default=0,
help="require (1) or forbid (0) the forced-fastboot diagnostic build")
ap.add_argument("--expect-display", type=int, choices=(0, 1), default=0,
help="require (1) or forbid (0) the boot-time SPI display build")
args = ap.parse_args()
problems = []
if not os.path.isfile(args.image):
print("FAIL: missing %s" % args.image)
return 1
data = open(args.image, "rb").read()
if data[:8] != BOOT_MAGIC:
print("FAIL: %s is not an Android boot image" % args.image)
return 1
hdr = struct.unpack_from("<8s10I", data, 0)
kernel_size, kernel_addr, ramdisk_size, _ = hdr[1:5]
second_size, _, _, page = hdr[5:9]
dt_size = hdr[9]
if page != 2048:
problems.append("page size is %d, expected 2048" % page)
if kernel_addr != 0x80008000:
problems.append("kernel load address %#x is not the stock 0x80008000" % kernel_addr)
if dt_size == 0 or dt_size % page != 0:
problems.append("dt_size %d is not a page-multiple QCDT image" % dt_size)
cmdline = data[64:576].split(b"\0")[0].decode("utf-8", "replace")
cmd_parts = cmdline.split(" ")
if cmd_parts[:2] != ["lk2nd", "lk2nd.compatible=nokia,sparkler"] or \
any(p not in ("lk2nd.force-panel-init", "lk2nd.no-display",
"lk2nd.display=on") for p in cmd_parts[2:]):
problems.append("cmdline is %r" % cmdline)
no_display = "lk2nd.no-display" in cmd_parts[2:]
display_on = "lk2nd.display=on" in cmd_parts[2:]
if args.expect_fastboot and not no_display:
problems.append("diagnostic image must carry lk2nd.no-display")
if args.expect_display and not display_on:
problems.append("display image must carry lk2nd.display=on")
if args.expect_display and no_display:
problems.append("display image must not carry lk2nd.no-display")
if not args.expect_display and display_on:
problems.append("non-display image must not carry lk2nd.display=on")
forced_fastboot = b"Fastboot mode was forced with compile-time flag." in data
if forced_fastboot != bool(args.expect_fastboot):
problems.append("fastboot diagnostic marker is %s, expected %s" %
(forced_fastboot, bool(args.expect_fastboot)))
for marker in (b"lk2nd.no-display", b"lk2nd.display=on",
b"oem scan-boot", b"oem display-init", b"oem display-test",
b"oem scan-dtb", b"QUP output FIFO timeout",
b"SPI panel %s: keeping aboot continuous splash",
b"SPI display ready",
b"scan-only: final kernel cmdline/DTB ready",
b"No valid pstore console",
b"SPI panel fallback from QCDT: %s",
b"offset is not block-aligned",
b"aligned read exceeds partition",
b"beatles low-bit reboot cookie"):
if marker not in data:
problems.append("binary is missing %r" % marker.decode("ascii", "replace"))
if not data.endswith(b"SEANDROIDENFORCE"):
problems.append("missing SEANDROIDENFORCE trailer")
qcdt_off = (page + align(kernel_size, page) + align(ramdisk_size, page) +
align(second_size, page))
sparkler_entry = None
seen_offsets = {}
if data[qcdt_off:qcdt_off + 4] != QCDT_MAGIC:
problems.append("no QCDT table at offset %d" % qcdt_off)
else:
_, version, num_entries = struct.unpack_from("<4sII", data, qcdt_off)
if version != 2:
problems.append("QCDT version is %d, expected 2" % version)
for i in range(num_entries):
off = qcdt_off + 12 + 24 * i
platform_id, variant_id, subtype, soc_rev, dtb_off, dtb_size = \
struct.unpack_from("<6I", data, off)
if dtb_off and dtb_size:
seen_offsets.setdefault(dtb_off, dtb_size)
if (platform_id == STOCK_PLATFORM_ID and variant_id == STOCK_VARIANT_ID and
subtype == STOCK_SUBTYPE and soc_rev == STOCK_SOC_REV):
sparkler_entry = (dtb_off, dtb_size, i)
if not sparkler_entry:
problems.append("QCDT has no MSM8909 MTP entry (0xf5/0x8/0x100/0)")
for dtb_off, dtb_size in seen_offsets.items():
dtb = data[qcdt_off + dtb_off:qcdt_off + dtb_off + dtb_size]
if dtb[:4] != b"\xd0\x0d\xfe\xed":
continue
try:
nodes, _ = fdt_nodes(dtb)
except ValueError:
continue
if "/cpus" not in nodes:
problems.append("QCDT DTB@0x%x lacks /cpus (aboot partial-goods ASSERT)" %
dtb_off)
continue
for cpu in ("cpu@2", "cpu@3"):
path = "/cpus/" + cpu
if path not in nodes:
problems.append("QCDT DTB@0x%x lacks %s" % (dtb_off, path))
elif nodes[path].get("device_type") != b"cpu\0":
problems.append("QCDT DTB@0x%x %s device_type is %r, expected b'cpu\\0'" %
(dtb_off, path, nodes[path].get("device_type")))
streams = {}
if sparkler_entry:
dtb_off, dtb_size, _ = sparkler_entry
dtb = data[qcdt_off + dtb_off:qcdt_off + dtb_off + dtb_size]
if dtb[:4] != b"\xd0\x0d\xfe\xed":
problems.append("8000 4G DTB is not an FDT")
else:
try:
nodes, totalsize = fdt_nodes(dtb)
if totalsize > dtb_size:
problems.append("8000 4G DTB is truncated (%d > %d)" %
(totalsize, dtb_size))
streams = check_device_node(nodes, "8000 4G DTB", problems) or {}
except ValueError as exc:
problems.append("8000 4G DTB: %s" % exc)
header_path = os.path.join(base, "bootloader", "lk2nd", "spi-panel-init.h")
if not os.path.isfile(args.beatles_patch):
problems.append("missing base patch %s" % args.beatles_patch)
elif not os.path.isfile(args.coconut_patch):
problems.append("missing coconut patch %s" % args.coconut_patch)
elif not os.path.isfile(args.patch):
problems.append("missing sparkler patch %s" % args.patch)
elif not os.path.isfile(header_path):
problems.append("missing %s" % header_path)
else:
base_text = open(args.beatles_patch, "r").read()
coco_text = open(args.coconut_patch, "r").read()
spark_text = open(args.patch, "r").read()
want = open(header_path, "r").read()
got = extract_patch_file(base_text, "lk2nd/include/lk2nd/spi-panel-init.h")
if got != want:
problems.append("bootloader/lk2nd/spi-panel-init.h is out of sync with nokia-beatles.patch")
if "diff --git a/lk2nd/device/dts/msm8909/nokia-coconut.dtsi" not in coco_text:
problems.append("nokia-coconut.patch is missing nokia-coconut.dtsi")
for needed in (
"lk2nd/device/2nd/spi-display.c",
"lk2nd/device/dts/msm8909/msm8909-mtp.dts",
"lk2nd/device/dts/msm8909/nokia-sparkler.dtsi",
):
if "diff --git a/%s b/%s" % (needed, needed) not in spark_text:
problems.append("sparkler patch is missing %s" % needed)
for token in ('"nokia,sparkler"', '#include "nokia-sparkler.dtsi"',
"qcom,mdss_spi_gc9307_hlt_28_qvga_cmd",
"qcom,mdss_spi_st7789vx2_ctc_28_qvga_cmd",
"* and # keys", "Top power key", "KEY_VOLUMEUP"):
if token not in spark_text:
problems.append("sparkler patch is missing %s" % token)
if problems:
for problem in problems:
print("FAIL: %s" % problem)
return 1
print("[ok] source-built sparkler lk2nd (%s): cmdline=%r, %d bytes, "
"dt_size=%d, 0xf5/0x8/0x100 -> DTB@0x%x" %
("diagnostic" if args.expect_fastboot else
"display" if args.expect_display else "normal",
cmdline, len(data), dt_size, sparkler_entry[0]))
print("[ok] all %d QCDT DTBs have /cpus/cpu@2 and cpu@3 (partial-goods fix)" %
len(seen_offsets))
print("[ok] 8000 4G DTB carries /lk2nd/nokia-sparkler with GC9307 + ST7789VX2 init streams and gpio90 KEY_VOLUMEUP")
print("[ok] patch layers and header in sync")
if args.emit_streams_header:
gc = streams.get(GC9307_PANELS[0], b"")
st = streams.get(ST7789VX2_PANELS[0], b"")
out = [
"/* generated by scripts/check-lk2nd-sparkler.py */",
"#ifndef PANEL_STREAMS_SPARKLER_H",
"#define PANEL_STREAMS_SPARKLER_H",
"",
]
out += format_c_array("stream_gc9307", gc)
out.append("")
out += format_c_array("stream_st7789vx2", st)
out += ["", "#endif"]
with open(args.emit_streams_header, "w") as fh:
fh.write("\n".join(out) + "\n")
print("[ok] wrote %s" % args.emit_streams_header)
return 0
if __name__ == "__main__":
sys.exit(main())
+175 -15
View File
@@ -179,12 +179,22 @@ for module in usb gpt sahara firehose utils; do
fail "missing vendor/edl/Library/$module.py"
fi
done
if [ ! -f "$BASE_DIR/vendor/edl/LICENSE" ]; then
fail "missing vendor/edl/LICENSE"
for f in vendor/edl/LICENSE scripts/test-edl-firehose-read.py; do
if [ ! -f "$BASE_DIR/$f" ]; then
fail "missing $f"
fi
done
if ! python3 "$BASE_DIR/scripts/test-edl-firehose-read.py" >/dev/null 2>&1; then
fail "Firehose rawmode read regression tests failed"
fi
if ! grep -q '^from Library\.sahara import qualcomm_sahara$' "$BASE_DIR/flash-edl.py"; then
fail "flash-edl.py is missing the Sahara client import"
fi
if ! grep -qF 'DEFAULT_USB_TIMEOUT_MS = 30000' "$BASE_DIR/vendor/edl/Library/usb.py" || \
! grep -qF 'DEFAULT_USB_IO_TIMEOUT_SEC = 30' "$BASE_DIR/flash-edl.py" || \
! grep -qF '"--usb-timeout"' "$BASE_DIR/flash-edl.py"; then
fail "EDL flasher USB transfer timeout defaults (30s) regressed"
fi
echo "[check] Device-specific EDL Firehose loaders..."
if ! grep -q '^DEVICE_LOADERS = {' "$BASE_DIR/flash-edl.py"; then
@@ -286,6 +296,7 @@ if ! grep -qF 'target_names = ("boot", "recovery", "lk2nd")' \
fi
for f in bootloader/lk2nd/nokia-beatles.patch \
bootloader/lk2nd/nokia-coconut.patch \
bootloader/lk2nd/nokia-sparkler.patch \
bootloader/lk2nd/README.md \
bootloader/lk2nd/spi-panel-init.h \
bootloader/lk2nd/Dockerfile \
@@ -294,6 +305,10 @@ for f in bootloader/lk2nd/nokia-beatles.patch \
scripts/build-lk2nd-coconut.sh \
scripts/check-lk2nd-coconut.py \
scripts/test-lk2nd-coconut-port.py \
scripts/build-lk2nd-sparkler.sh \
scripts/check-lk2nd-sparkler.py \
scripts/test-lk2nd-sparkler-port.py \
scripts/test-sparkler-port.py \
scripts/inspect-stock-msm8905-dump.py; do
if [ ! -f "$BASE_DIR/$f" ]; then
fail "missing lk2nd port / inspection file: $f"
@@ -303,6 +318,10 @@ if ! grep -qF 'COCONUT_LK2ND_IMAGE = "images/boot-lk2nd-nokia-coconut-display.im
"$BASE_DIR/flash-edl.py"; then
fail "flash-edl.py no longer references the display-enabled coconut lk2nd image"
fi
if ! grep -qF 'SPARKLER_LK2ND_IMAGE = "images/boot-lk2nd-nokia-sparkler-display.img"' \
"$BASE_DIR/flash-edl.py"; then
fail "flash-edl.py no longer references the display-enabled sparkler lk2nd image"
fi
for variant in normal diagnostic display; do
case "$variant" in
normal)
@@ -331,6 +350,34 @@ for variant in normal diagnostic display; do
fail "$label validation failed"
fi
done
for variant in normal diagnostic display; do
case "$variant" in
normal)
image="$BASE_DIR/images/boot-lk2nd-nokia-sparkler.img"
opts="--expect-fastboot 0"
label="source-built nokia-sparkler lk2nd"
;;
diagnostic)
image="$BASE_DIR/images/boot-lk2nd-nokia-sparkler-diagnostic.img"
opts="--expect-fastboot 1"
label="nokia-sparkler forced-fastboot diagnostic image"
;;
display)
image="$BASE_DIR/images/boot-lk2nd-nokia-sparkler-display.img"
opts="--expect-fastboot 0 --expect-display 1"
label="nokia-sparkler display lk2nd image with Fastboot reboot cookie"
;;
esac
if [ ! -f "$image" ]; then
echo "[skip] local build output ${image#"$BASE_DIR/"} is absent; prepare-release.sh will rebuild it"
continue
fi
# shellcheck disable=SC2086
if ! python3 "$BASE_DIR/scripts/check-lk2nd-sparkler.py" \
--image "$image" $opts; then
fail "$label validation failed"
fi
done
if [ -f "$BASE_DIR/scripts/make-beatles-lk2nd-bootimg.py" ]; then
fail "obsolete binary-patch lk2nd script is still present"
fi
@@ -434,13 +481,16 @@ fi
echo "[check] Known-good flashable image set..."
for pair in \
"8444544b0395c5bdef2f76b87721a99c326a868465d8236e85ff5572e7634cc0 images/bananarchy-nokia-argon.img" \
"7749caec22f5803112d21d24f032c09162bc7e6a239beabddb903272ebbd79c8 images/bananarchy-nokia-beatles.img" \
"cc58d92e6a54eab77f355a148cbc0b424d2da64e65353e3163a9cfc1eba37235 images/boot-bananarchy-nokia-beatles.img" \
"82f617e425fa9d33b1395c4e35639a6207e3c9d0aa376c7cedf35fddaccb5cc2 images/bananarchy-nokia-argon.img" \
"cc40c682fcdacb6415c112494344826362de2f965e6238685462859de66d660e images/bananarchy-nokia-beatles.img" \
"786e9a1f4e4ae92efc948393a1d8f04a9405840a214b6ef37914cf5821d7ed82 images/boot-bananarchy-nokia-beatles.img" \
"b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d images/boot-lk2nd-nokia-beatles-display.img" \
"19d17f31b970099dc6c212da58efdf8a99249aaa43e65ebeb6e2b904d0c5809d images/bananarchy-nokia-coconut.img" \
"2ff959ec89916adc02296adb948788bf8180009cd26454643e9f59334f09ad08 images/boot-bananarchy-nokia-coconut.img" \
"e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a images/boot-lk2nd-nokia-coconut-display.img"; do
"e82d64bd9f14b1fcca2c078e9fd43a4c4268b29ff688f268b32a939213be0545 images/bananarchy-nokia-coconut.img" \
"55299e15abe5923fc525b4e54e81aa4791f0e61f8a070e84fe7497f75c62d7d7 images/boot-bananarchy-nokia-coconut.img" \
"e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a images/boot-lk2nd-nokia-coconut-display.img" \
"5dc17319742e4af95facc42681f0fe6fb2e80ddf30f421f3c54b9dbe04fefd3f images/bananarchy-nokia-sparkler.img" \
"8205e2cb486d8ecc1e261a5c0b6f9ee7f70fd4eed2534d5bafc28ebc62d953d8 images/boot-bananarchy-nokia-sparkler.img" \
"bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f images/boot-lk2nd-nokia-sparkler-display.img"; do
set -- $pair
want=$1
path="$BASE_DIR/$2"
@@ -558,11 +608,13 @@ if ! grep -q 'msm8905-cam' "$BASE_DIR/overlay/rootfs/etc/local.d/10-bananarchy-h
fail "the local.d hardware fallback no longer loads the camera driver"
fi
CAM_DRIVER="$BASE_DIR/src/msm8905-cam/msm8905-cam.c"
if ! grep -qF 'cam->rotate_180 = of_machine_is_compatible("nokia,beatles");' \
"$CAM_DRIVER" || \
if ! grep -qF 'of_machine_is_compatible("nokia,beatles")' "$CAM_DRIVER" || \
! grep -qF 'of_machine_is_compatible("nokia,sparkler")' "$CAM_DRIVER" || \
! grep -qF 'of_machine_is_compatible("nokia,leo")' "$CAM_DRIVER" || \
! grep -qF 'row_buf' "$CAM_DRIVER" || \
! grep -qF 'msm8905_cam_demosaic(cam->raw_dma_buf, dst_rgb, cam->rotate_180);' \
"$CAM_DRIVER"; then
fail "the beatles-only 180-degree camera orientation correction is missing"
fail "msm8905-cam orientation (beatles/sparkler/leo) or cached-row demosaic check failed"
fi
if [ ! -f "$BASE_DIR/scripts/busybox-sbin-applets.txt" ] || \
! grep -qxF 'reboot' "$BASE_DIR/scripts/busybox-sbin-applets.txt"; then
@@ -809,6 +861,40 @@ else
echo "[skip] local build output images/bananarchy-nokia-coconut.img is absent; prepare-release.sh will rebuild it"
fi
echo "[check] 8000 4G (nokia-sparkler) appended DTB..."
SPARKLER_DTS="$BASE_DIR/devices/nokia-sparkler/qcom-msm8909-nokia-sparkler.dts"
if ! grep -qF 'qcom,msm-id = <0xf5 0x00>;' "$SPARKLER_DTS"; then
fail "nokia-sparkler DTS lost the stock MSM8909 msm-id"
fi
if ! grep -qF 'qcom,board-id = <0x08 0x100>;' "$SPARKLER_DTS"; then
fail "nokia-sparkler DTS lost the stock MTP board-id"
fi
if ! grep -qF 'qcom,pmic-id = <0x1000d 0x00 0x00 0x00>;' "$SPARKLER_DTS"; then
fail "nokia-sparkler DTS lost the stock pmic-id"
fi
if ! grep -qF 'reg = <0x80000000 0x20000000>;' "$SPARKLER_DTS"; then
fail "nokia-sparkler DTS lost the 512 MiB memory fallback"
fi
for node in 'sound@7702000' 'vibrator@c000' 'audio-codec@f000'; do
if ! grep -qF "$node" "$SPARKLER_DTS"; then
fail "nokia-sparkler DTS is missing $node"
fi
done
if [ -f "$BASE_DIR/images/boot-bananarchy-nokia-sparkler.img" ]; then
if ! python3 "$BASE_DIR/scripts/check-beatles-bootimg.py" --device nokia-sparkler; then
fail "8000 4G boot image validation failed"
fi
else
echo "[skip] local build output images/boot-bananarchy-nokia-sparkler.img is absent; prepare-release.sh will rebuild it"
fi
if [ -f "$BASE_DIR/images/bananarchy-nokia-sparkler.img" ]; then
if ! python3 "$BASE_DIR/scripts/sync-beatles-bootfs.py" --check --device nokia-sparkler --raw-image "$BASE_DIR/images/bananarchy-nokia-sparkler.img"; then
fail "8000 4G raw image pmOS_boot filesystem is damaged or stale"
fi
else
echo "[skip] local build output images/bananarchy-nokia-sparkler.img is absent; prepare-release.sh will rebuild it"
fi
echo "[check] Release hygiene..."
KCONFIG="$BASE_DIR/patches/kernel/config-bananarchy-msm8909.armv7"
for cfg in "$KCONFIG" \
@@ -977,7 +1063,7 @@ fi
if grep -qE '"\$\{?BASE_DIR\}?/prebuilt/kernel-6\.12\.1-msm8916/(leds|camera)/"\*\.ko\*' "$BASE_DIR/scripts/apply-bananarchy-overlay.sh"; then
fail "apply-bananarchy-overlay.sh still copies uncompressed .ko files via *.ko* wildcard"
fi
for dev_img in images/bananarchy-nokia-argon.img images/bananarchy-nokia-beatles.img; do
for dev_img in images/bananarchy-nokia-argon.img images/bananarchy-nokia-beatles.img images/bananarchy-nokia-coconut.img images/bananarchy-nokia-sparkler.img; do
if [ ! -f "$BASE_DIR/$dev_img" ]; then
echo "[skip] local build output $dev_img is absent; skipping initramfs depmod check"
continue
@@ -1493,7 +1579,8 @@ for dts in \
"$BASE_DIR/devices/nokia-argon/qcom-msm8905-nokia-argon.dts" \
"$BASE_DIR/devices/nokia-beatles/qcom-msm8905-nokia-beatles.dts" \
"$BASE_DIR/devices/nokia-beatles/qcom-msm8905-nokia-beatles-cover.dts" \
"$BASE_DIR/devices/nokia-coconut/qcom-msm8905-nokia-coconut.dts"; do
"$BASE_DIR/devices/nokia-coconut/qcom-msm8905-nokia-coconut.dts" \
"$BASE_DIR/devices/nokia-sparkler/qcom-msm8909-nokia-sparkler.dts"; do
if ! grep -A 3 'dai-link-multimedia3 {' "$dts" | grep -qF 'status = "disabled";'; then
fail "${dts#"$BASE_DIR/"} must keep dai-link-multimedia3 disabled"
fi
@@ -1507,13 +1594,16 @@ for q6cfg in \
done
if [ ! -f "$BASE_DIR/patches/kernel/0010-msm8909-rpm-lpm-bimc-wcd-ldo-uart.patch" ] || \
! grep -qF '0010-msm8909-rpm-lpm-bimc-wcd-ldo-uart.patch' "$BASE_DIR/scripts/build-kernel-audio.sh" || \
[ ! -f "$BASE_DIR/patches/kernel/0013-msm8909-early-scm-smp-cpufreq.patch" ] || \
! grep -qF '0013-msm8909-early-scm-smp-cpufreq.patch' "$BASE_DIR/scripts/build-kernel-audio.sh" || \
! grep -qxF 'CONFIG_QCOM_RPM_MASTER_STATS=y' "$BASE_DIR/patches/kernel/config-bananarchy-msm8909.armv7" || \
! grep -qxF 'CONFIG_QCOM_RPM_MASTER_STATS=y' "$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/kernel-config" || \
! grep -q ' qcom_mpm_enter_sleep$' "$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/System.map" || \
! grep -q ' spm_get_l2_device$' "$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/System.map" || \
! grep -q ' qcom_msm8909_gdsc_is_active$' "$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/System.map" || \
! grep -q ' qcom_iommu_resume$' "$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/System.map"; then
fail "deep-standby kernel patch 0010, RPM master stats config, or vMPM/L2-SAW/IOMMU symbols are missing"
! grep -q ' qcom_iommu_resume$' "$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/System.map" || \
! grep -q ' qcom_scm_set_boot_addr_mc$' "$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/System.map"; then
fail "deep-standby kernel patch 0010/0013, RPM master stats config, or vMPM/L2-SAW/IOMMU/early-SCM symbols are missing"
fi
for dts in \
"$BASE_DIR/devices/nokia-argon/qcom-msm8905-nokia-argon.dts" \
@@ -2240,6 +2330,76 @@ if ! grep -qF 'of_machine_is_compatible("nokia,coconut")' "$TORCH_SRC" || \
fail "nokia-coconut dual LED separation (GPIO_13 white:torch vs GPIO_32 camera:flash) is incomplete"
fi
echo "[check] Nokia 8000 4G (nokia-sparkler) keypad, audio, initfs, DRM & dual-GPIO torch invariants..."
SPARKLER_DEVINFO="$BASE_DIR/devices/nokia-sparkler/deviceinfo"
SPARKLER_INITFS="$BASE_DIR/devices/nokia-sparkler/modules-initfs"
SPARKLER_DTB="$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/dtbs/qcom-msm8909-nokia-sparkler.dtb"
TORCH_KO="$BASE_DIR/prebuilt/kernel-6.12.1-msm8916/leds/leds-msm8905-torch.ko"
if ! grep -qxF 'deviceinfo_drm="true"' "$SPARKLER_DEVINFO"; then
fail "devices/nokia-sparkler/deviceinfo must set deviceinfo_drm=\"true\""
fi
if ! grep -qxF 'matrix_keypad' "$SPARKLER_INITFS" || \
! grep -qxF 'matrix_keymap' "$SPARKLER_INITFS"; then
fail "devices/nokia-sparkler/modules-initfs must include matrix_keypad and matrix_keymap"
fi
if ! grep -qF '0x500d4' "$SPARKLER_DTS" || \
! grep -qF '0x100007f' "$SPARKLER_DTS" || \
! grep -qF '0x205000e' "$SPARKLER_DTS" || \
! grep -qF '0x301009e' "$SPARKLER_DTS" || \
! grep -qF 'clock-frequency = <1094400000>;' "$SPARKLER_DTS" || \
! awk '/vibrator@c000 \{/,/\};/ { if ($0 ~ /status = "disabled";/) found=1 } END { exit(found ? 0 : 1) }' "$SPARKLER_DTS" || \
grep -qE '0x5008b|0x10002b8|0x20501be|0x30102b9' "$SPARKLER_DTS"; then
fail "devices/nokia-sparkler/qcom-msm8909-nokia-sparkler.dts drifted from Sxmo keypad, CPU clock, or haptic invariants"
fi
if command -v dtc >/dev/null 2>&1 && [ -f "$SPARKLER_DTB" ]; then
dec_sparkler="$(dtc -q -I dtb -O dts "$SPARKLER_DTB" 2>/dev/null || true)"
if ! printf "%s\n" "$dec_sparkler" | grep -qF 'qcom,msm-id = <0xf5 0x00>;' || \
! printf "%s\n" "$dec_sparkler" | grep -qF 'qcom,board-id = <0x08 0x100>;' || \
! printf "%s\n" "$dec_sparkler" | grep -qF 'reg = <0x80000000 0x20000000>;' || \
! printf "%s\n" "$dec_sparkler" | grep -qF 'sound@7702000' || \
! printf "%s\n" "$dec_sparkler" | \
awk '/vibrator@c000 \{/,/\};/ { if ($0 ~ /status = "disabled";/) found=1 } END { exit(found ? 0 : 1) }' || \
! printf "%s\n" "$dec_sparkler" | grep -qF 'audio-codec@f000' || \
! printf "%s\n" "$dec_sparkler" | grep -qF '0x500d4' || \
! printf "%s\n" "$dec_sparkler" | grep -qF '0x100007f' || \
! printf "%s\n" "$dec_sparkler" | grep -qF '0x205000e' || \
! printf "%s\n" "$dec_sparkler" | grep -qF '0x301009e' || \
printf "%s\n" "$dec_sparkler" | grep -qE '0x5008b|0x10002b8|0x20501be|0x30102b9'
then
fail "prebuilt/kernel-6.12.1-msm8916/dtbs/qcom-msm8909-nokia-sparkler.dtb drifted from Sparkler DTS invariants"
fi
fi
if ! grep -qF 'vibrate_haptic_audio' "$BASE_DIR/src/dwm-plugins/sxmo_vibrate.c" || \
! grep -qF '157.0' "$BASE_DIR/src/dwm-plugins/sxmo_vibrate.c" || \
! grep -qF 'nokia,sparkler' "$BASE_DIR/src/dwm-plugins/sxmo_vibrate.c"; then
fail "sxmo_vibrate.c lost 157 Hz haptic audio support for nokia-sparkler"
fi
if ! grep -qF 'of_machine_is_compatible("nokia,sparkler")' "$TORCH_SRC" || \
! grep -qF 'MSM8905_TLMM_GPIO31_PHYS' "$TORCH_SRC" || \
{ [ -f "$TORCH_KO" ] && ! grep -qaF 'GPIO_32/GPIO_31 (BC847BS)' "$TORCH_KO"; }; then
fail "nokia-sparkler dual-GPIO BC847BS torch support in leds-msm8905-torch is incomplete"
fi
echo "[check] Universal keypad-friendly timer (sxmo_timer.sh, dmenu, hooks)..."
TIMER_SH="$BASE_DIR/overlay/rootfs/usr/bin/sxmo_timer.sh"
if [ ! -x "$TIMER_SH" ] || ! sh -n "$TIMER_SH" 2>/dev/null; then
fail "overlay/rootfs/usr/bin/sxmo_timer.sh is missing, not executable, or has invalid syntax"
fi
if grep -qE 'boottime_alarm|pkill' "$TIMER_SH" || \
! grep -qF '# title="$icon_clk Timer"' "$TIMER_SH" || \
! grep -qF 'HUP INT TERM EXIT' "$TIMER_SH" || \
! grep -qF 'stop_ringing()' "$TIMER_SH"; then
fail "overlay/rootfs/usr/bin/sxmo_timer.sh failed permissionless/cancellation invariants"
fi
if ! grep -qF 'timer_menu_state' "$DMENU_SRC" || \
! grep -qF '/usr/bin/sxmo_timer.sh stop_ringing' "$BASE_DIR/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_mute_ring.sh" || \
! grep -qF '/usr/bin/sxmo_timer.sh stop_ringing' "$BASE_DIR/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_discard.sh"; then
fail "dmenu or ring mute/discard hooks are missing timer stop integration"
fi
if ! python3 "$BASE_DIR/scripts/test-timer.py" >/dev/null 2>&1; then
fail "scripts/test-timer.py failed"
fi
if [ "$FAILURES" -ne 0 ]; then
echo "[check] $FAILURES check(s) failed."
exit 1
+7 -2
View File
@@ -31,6 +31,11 @@ BOOT_FS_FILES = {
"qcom-msm8905-nokia-beatles.dtb":
BASE_DIR / "devices" / "nokia-beatles" / "qcom-msm8905-nokia-beatles.dtb",
}
DEVICE_DTB_NAMES = {
"nokia-beatles": "qcom-msm8905-nokia-beatles.dtb",
"nokia-coconut": "qcom-msm8905-nokia-coconut.dtb",
"nokia-sparkler": "qcom-msm8909-nokia-sparkler.dtb",
}
DEBUG_PREFIX = "loglevel=8 ignore_loglevel initcall_debug panic=10"
QUIET_PREFIX = "quiet splash"
BOOT_CMD_FLAGS = "plymouth.ignore-serial-consoles plymouth.prefer-fbcon"
@@ -158,7 +163,7 @@ def check(raw_path, dtb_path, boot_img_path, verbose=True, allow_debug=False,
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--device", choices=["nokia-beatles", "nokia-coconut"],
parser.add_argument("--device", choices=tuple(DEVICE_DTB_NAMES.keys()),
default="nokia-beatles")
parser.add_argument("--raw-image", default="")
parser.add_argument("--source-boot-fs", default="",
@@ -176,7 +181,7 @@ def main():
help="Override the boot.img written to/checked in pmOS_boot")
args = parser.parse_args()
dtb_name = "qcom-msm8905-%s.dtb" % args.device
dtb_name = DEVICE_DTB_NAMES[args.device]
raw_image = args.raw_image or str(BASE_DIR / "images" / ("bananarchy-%s.img" % args.device))
dtb = Path(args.dtb) if args.dtb else (BASE_DIR / "devices" / args.device / dtb_name)
boot_img = Path(args.boot_image) if args.boot_image else (
+268
View File
@@ -0,0 +1,268 @@
#!/usr/bin/env python3
"""Offline tests for Firehose <read> handling across 8k/2720v and FIH loaders."""
import os
import struct
import sys
import tempfile
import unittest
from unittest import mock
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, "vendor", "edl"))
import Library.firehose as firehose_mod # noqa: E402
import Library.usb as usb_mod # noqa: E402
from Library.firehose import qualcomm_firehose, xmlparser # noqa: E402
from Library.gpt import gpt # noqa: E402
from Library.usb import usb_class # noqa: E402
def build_synthetic_gpt(sectors=32):
"""Construct a 32-sector raw GPT image containing boot and userdata entries."""
buf = bytearray(sectors * 512)
# Protective MBR signature at LBA 0
buf[510:512] = b"\x55\xaa"
# GPT header at LBA 1 (revision 0x00010000 LE == 0x100 BE)
header = struct.pack(
"<8s4I4Q16sQ2I",
b"EFI PART",
0x00010000,
92,
0,
0,
1,
1023,
34,
1000,
b"\x11" * 16,
2,
4,
128,
)
buf[512:512 + len(header)] = header
# Partition entries starting at LBA 2 (offset 1024)
entries = [
("boot", 34, 97),
("userdata", 100, 999),
]
for idx, (name, first_lba, last_lba) in enumerate(entries):
off = 1024 + idx * 128
ptype = struct.pack("<I", 0xEBD0A0A2) + b"\x00" * 12
puniq = bytes([idx + 1]) * 16
pname = name.encode("utf-16-le").ljust(72, b"\x00")
entry = struct.pack("<16s16s3Q72s", ptype, puniq, first_lba, last_lba, 0, pname)
buf[off:off + 128] = entry
return bytes(buf)
class FakeCdc:
def __init__(self, rx_packets):
self.rx_packets = [bytearray(pkt) for pkt in rx_packets]
self.tx_packets = []
self.read_lengths = []
def write(self, data, pktsize=64, timeout=None):
self.tx_packets.append((bytes(data) if not isinstance(data, str) else data.encode("utf-8"), pktsize))
def read(self, length=0x80000, timeout=None):
self.read_lengths.append(length)
if not self.rx_packets:
return bytearray()
pkt = self.rx_packets.pop(0)
if len(pkt) <= length:
return pkt
out = pkt[:length]
self.rx_packets.insert(0, pkt[length:])
return out
class TestEdlFirehoseRead(unittest.TestCase):
def _make_fh(self, rx_packets, max_payload=1048576):
cfg = qualcomm_firehose.cfg()
cfg.MemoryName = "eMMC"
cfg.SECTOR_SIZE_IN_BYTES = 512
cfg.MaxPayloadSizeToTargetInBytes = max_payload
cfg.MaxXMLSizeInBytes = 4096
cdc = FakeCdc(rx_packets)
return qualcomm_firehose(cdc, xmlparser(), cfg), cdc
def test_8k_rawmode_ack_gpt_parse(self):
gpt_bytes = build_synthetic_gpt(32)
rx = [
b'<?xml version="1.0" encoding="UTF-8" ?><data><log value="start 0, num 32" /></data>',
b'<?xml version="1.0" encoding="UTF-8" ?><data><response value="ACK" rawmode="true" /></data>\x00',
gpt_bytes[:8192],
gpt_bytes[8192:],
b'<?xml version="1.0" encoding="UTF-8" ?><data><log value="Finished sector address 32" /></data>',
b'<?xml version="1.0" encoding="UTF-8" ?><data><response value="ACK" rawmode="false" /></data>',
]
fh, cdc = self._make_fh(rx)
with mock.patch.object(firehose_mod.time, "sleep"):
got = fh.cmd_read_buffer(0, 0, 32, Display=False)
self.assertEqual(bytes(got), gpt_bytes)
table = gpt()
self.assertTrue(table.parse(got, 512))
self.assertEqual([e.name for e in table.partentries], ["boot", "userdata"])
# Check raw reads never ask for more than remaining bytes (16 KiB here).
self.assertEqual(cdc.read_lengths[0], 16384)
self.assertEqual(cdc.read_lengths[1], 16384)
self.assertEqual(cdc.read_lengths[2], 16384)
self.assertEqual(cdc.read_lengths[3], 8192)
def test_fih_immediate_raw_gpt_parse(self):
gpt_bytes = build_synthetic_gpt(32)
rx = [
gpt_bytes[:4096],
gpt_bytes[4096:12288],
gpt_bytes[12288:],
b'<?xml version="1.0" encoding="UTF-8" ?><data><response value="ACK" rawmode="false" /></data>',
]
fh, cdc = self._make_fh(rx)
with mock.patch.object(firehose_mod.time, "sleep"):
got = fh.cmd_read_buffer(0, 0, 32, Display=False)
self.assertEqual(bytes(got), gpt_bytes)
table = gpt()
self.assertTrue(table.parse(got, 512))
self.assertEqual([e.name for e in table.partentries], ["boot", "userdata"])
self.assertEqual(cdc.read_lengths[:3], [16384, 12288, 4096])
def test_single_sector_cmd_read_both_variants(self):
sector = bytes([0xA5]) * 512
for name, ack_pkts in (
("8k", [b'<?xml version="1.0" encoding="UTF-8" ?><data><response value="ACK" rawmode="true" /></data>']),
("fih", []),
):
with self.subTest(loader=name):
rx = ack_pkts + [
sector,
b'<?xml version="1.0" encoding="UTF-8" ?><data><response value="ACK" rawmode="false" /></data>',
]
fh, cdc = self._make_fh(rx)
with tempfile.TemporaryDirectory() as tmp:
out = os.path.join(tmp, "sec.bin")
with mock.patch.object(firehose_mod.time, "sleep"):
res = fh.cmd_read(0, 7, 1, out, Display=False)
self.assertTrue(res)
self.assertNotEqual(res, "")
with open(out, "rb") as handle:
self.assertEqual(handle.read(), sector)
self.assertEqual(cdc.read_lengths[0], 512)
def test_nak_before_raw_fails_cleanly(self):
rx = [
b'<?xml version="1.0" encoding="UTF-8" ?><data><log value="Invalid physical partition 9" /></data>',
b'<?xml version="1.0" encoding="UTF-8" ?><data><response value="NAK" rawmode="false" /></data>',
]
fh, _ = self._make_fh(rx)
got = fh.cmd_read_buffer(9, 0, 1, Display=False)
self.assertEqual(got, "")
def test_usb_connect_preserves_active_configuration(self):
fake_ep_out = object()
fake_ep_in = object()
class FakeDevice:
def __init__(self, initial_cfg, raise_on_get=False):
self.initial_cfg = initial_cfg
self.raise_on_get = raise_on_get
self.set_configuration_calls = 0
def is_kernel_driver_active(self, _):
return False
def get_active_configuration(self):
if self.raise_on_get and self.set_configuration_calls == 0:
raise usb_mod.usb.core.USBError("Entity not found")
return self.initial_cfg if self.set_configuration_calls == 0 else "cfg1"
def set_configuration(self):
self.set_configuration_calls += 1
with mock.patch.object(usb_mod.usb.util, "find_descriptor", side_effect=[
"intf0", fake_ep_out, fake_ep_in,
"intf0", fake_ep_out, fake_ep_in,
"intf0", fake_ep_out, fake_ep_in,
]), mock.patch.object(usb_mod.usb.util, "claim_interface"):
dev_active = FakeDevice("cfg1")
with mock.patch.object(usb_mod.usb.core, "find", return_value=dev_active):
cdc = usb_class()
self.assertTrue(cdc.connect())
self.assertEqual(dev_active.set_configuration_calls, 0)
dev_none = FakeDevice(None)
with mock.patch.object(usb_mod.usb.core, "find", return_value=dev_none):
cdc = usb_class()
self.assertTrue(cdc.connect())
self.assertEqual(dev_none.set_configuration_calls, 1)
dev_err = FakeDevice("cfg1", raise_on_get=True)
with mock.patch.object(usb_mod.usb.core, "find", return_value=dev_err):
cdc = usb_class()
self.assertTrue(cdc.connect())
self.assertEqual(dev_err.set_configuration_calls, 1)
def test_usb_timeout_defaults_and_sahara_connect_probe(self):
self.assertEqual(usb_mod.DEFAULT_USB_TIMEOUT_MS, 30000)
class TimeoutDevice:
def __init__(self):
self.default_timeout = 1000
self.writes = []
self.reads = []
def is_kernel_driver_active(self, _):
return False
def get_active_configuration(self):
return "cfg1"
def write(self, ep, payload, timeout=None):
self.writes.append((ep, bytes(payload), timeout))
def read(self, ep, length, timeout=None):
self.reads.append((ep, length, timeout))
return b"ok"
dev = TimeoutDevice()
with mock.patch.object(usb_mod.usb.core, "find", return_value=dev), \
mock.patch.object(usb_mod.usb.util, "find_descriptor", side_effect=["intf0", "ep_out", "ep_in"]), \
mock.patch.object(usb_mod.usb.util, "claim_interface"):
cdc = usb_class()
self.assertTrue(cdc.connect())
self.assertEqual(dev.default_timeout, 30000)
cdc.write(b"abc")
cdc.read(64)
cdc.read(64, timeout=2000)
self.assertEqual(dev.writes[-1], ("ep_out", b"abc", 30000))
self.assertEqual(dev.reads, [("ep_in", 64, 30000), ("ep_in", 64, 2000)])
class ProbeCdc:
def __init__(self):
self.read_calls = []
self.write_calls = []
def read(self, length=0x80000, timeout=None):
self.read_calls.append((length, timeout))
if len(self.read_calls) == 1:
raise TimeoutError("probe timed out")
return bytearray(b'<?xml version="1.0" ?><data><response value="ACK" /></data>')
def write(self, data, pktsize=64, timeout=None):
self.write_calls.append((data, pktsize, timeout))
from Library.sahara import qualcomm_sahara
pcdc = ProbeCdc()
sahara = qualcomm_sahara(pcdc)
self.assertEqual(sahara.connect(), "Firehose")
self.assertEqual(pcdc.read_calls[0][1], 2000)
self.assertIsNone(pcdc.read_calls[1][1])
with open(os.path.join(BASE_DIR, "flash-edl.py"), "r", encoding="utf-8") as handle:
flash_src = handle.read()
self.assertIn("DEFAULT_USB_IO_TIMEOUT_SEC = 30", flash_src)
self.assertIn('"--usb-timeout"', flash_src)
if __name__ == "__main__":
unittest.main()
+233
View File
@@ -0,0 +1,233 @@
#!/usr/bin/env python3
"""Host tests for the source-built nokia-sparkler lk2nd port.
Runs the image validator across all three build variants, compiles a host C
panel-init walker test against the GC9307 HLT and ST7789VX2 CTC byte streams
extracted from the QCDT DTB, checks repository wiring, and exercises negative
validation checks on tampered binaries.
"""
import os
import shutil
import subprocess
import sys
import tempfile
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PINNED = "cf45aefd22d744b2bf9b39455afae697ce430063"
HOST_TEST_C = r"""
#include <stdio.h>
#include <string.h>
#include "spi-panel-init.h"
#include "panel_streams_sparkler.h"
static unsigned char cmds[64];
static unsigned char data[64][16];
static unsigned int data_len[64];
static unsigned int cmd_count, delay_total, delay_count;
static int rec_cmd(const unsigned char *cmd)
{
if(cmd_count < 64)
cmds[cmd_count] = cmd[0];
cmd_count++;
return 0;
}
static int rec_data(const unsigned char *buf, unsigned int len)
{
if(cmd_count > 0 && cmd_count <= 64 && len <= 16) {
memcpy(data[cmd_count - 1], buf, len);
data_len[cmd_count - 1] = len;
}
return 0;
}
static void rec_delay(unsigned int ms)
{
delay_total += ms;
delay_count++;
}
static const struct lk2nd_spi_panel_init_ops ops = {
.write_cmd = rec_cmd,
.write_data = rec_data,
.delay = rec_delay,
};
static void reset(void)
{
cmd_count = delay_total = delay_count = 0;
memset(cmds, 0, sizeof(cmds));
memset(data_len, 0, sizeof(data_len));
}
#define CHECK(cond, msg) do { \
if(!(cond)) { \
printf("[fail] %s (line %d)\n", (msg), __LINE__); \
return 1; \
} \
} while(0)
static int has_cmd(const unsigned char *cmd, unsigned int len)
{
unsigned int i;
for(i = 0; i < cmd_count; i++) {
if(cmds[i] != cmd[0])
continue;
if(len == 1)
return 1;
if(data_len[i] == len - 1 && memcmp(data[i], cmd + 1, len - 1) == 0)
return 1;
}
return 0;
}
static int verify_stream(const char *label, const unsigned char *buf,
unsigned int len, unsigned int expected_cmds)
{
static const unsigned char rgb565[] = {0x3a, 0x05};
static const unsigned char window_x[] = {0x2a, 0x00, 0x00, 0x00, 0xef};
static const unsigned char window_y[] = {0x2b, 0x00, 0x00, 0x01, 0x3f};
static const unsigned char sleep_out[] = {0x11};
static const unsigned char disp_on[] = {0x29};
reset();
CHECK(lk2nd_spi_panel_init_run(buf, len, &ops) == 0, label);
CHECK(cmd_count == expected_cmds, "unexpected command count");
CHECK(delay_total == 120 && delay_count == 1, "expected 120 ms delay once");
CHECK(has_cmd(rgb565, sizeof(rgb565)), "missing RGB565 0x3a 0x05");
CHECK(has_cmd(window_x, sizeof(window_x)), "missing column window");
CHECK(has_cmd(window_y, sizeof(window_y)), "missing row window");
CHECK(has_cmd(sleep_out, sizeof(sleep_out)), "missing sleep-out 0x11");
CHECK(has_cmd(disp_on, sizeof(disp_on)), "missing display-on 0x29");
CHECK(cmds[cmd_count - 1] == 0x2c, "stream must end with RAMWR 0x2c");
return 0;
}
int main(void)
{
if(verify_stream("gc9307", stream_gc9307, sizeof(stream_gc9307), 15))
return 1;
if(verify_stream("st7789vx2", stream_st7789vx2, sizeof(stream_st7789vx2), 11))
return 1;
printf("[ok] verified sparkler GC9307 (15 cmds) and ST7789VX2 (11 cmds)\n");
return 0;
}
"""
def run(cmd, **kwargs):
return subprocess.run(cmd, cwd=BASE, capture_output=True, text=True, **kwargs)
def check(condition, message):
if not condition:
print("FAIL: %s" % message)
return False
print("[ok] %s" % message)
return True
def main():
ok = True
validator = os.path.join(BASE, "scripts", "check-lk2nd-sparkler.py")
build = os.path.join(BASE, "scripts", "build-lk2nd-sparkler.sh")
beatles_patch = os.path.join(BASE, "bootloader", "lk2nd", "nokia-beatles.patch")
coconut_patch = os.path.join(BASE, "bootloader", "lk2nd", "nokia-coconut.patch")
sparkler_patch = os.path.join(BASE, "bootloader", "lk2nd", "nokia-sparkler.patch")
header = os.path.join(BASE, "bootloader", "lk2nd", "spi-panel-init.h")
variants = (
("images/boot-lk2nd-nokia-sparkler.img", 0, 0),
("images/boot-lk2nd-nokia-sparkler-diagnostic.img", 1, 0),
("images/boot-lk2nd-nokia-sparkler-display.img", 0, 1),
)
for image, fastboot, display in variants:
full = os.path.join(BASE, image)
ok &= check(os.path.isfile(full), "%s exists" % image)
if not os.path.isfile(full):
continue
r = run([sys.executable, validator, "--image", image,
"--expect-fastboot", str(fastboot),
"--expect-display", str(display)])
for line in r.stdout.strip().split("\n"):
if line:
print(line)
ok &= check(r.returncode == 0,
"%s passes structural validation" % os.path.basename(image))
if r.returncode != 0:
print(r.stderr.strip())
for path, label in ((build, "build-lk2nd-sparkler.sh"),
(beatles_patch, "nokia-beatles.patch"),
(coconut_patch, "nokia-coconut.patch"),
(sparkler_patch, "nokia-sparkler.patch"),
(header, "spi-panel-init.h")):
ok &= check(os.path.isfile(path), "%s exists" % label)
script = open(build).read()
ok &= check(PINNED in script, "build script pins upstream commit %s" % PINNED)
ok &= check("LK2ND_FORCE_FASTBOOT=1" in script and "lk2nd.no-display" in script,
"build script supports forced-fastboot no-display diagnostic image")
ok &= check("lk2nd.compatible=nokia,sparkler" in script and
"lk2nd.display=on" in script,
"build script uses nokia,sparkler cmdline and display mode")
patch_text = open(sparkler_patch).read()
for needed in ("lk2nd/device/2nd/spi-display.c",
"lk2nd/device/dts/msm8909/msm8909-mtp.dts",
"lk2nd/device/dts/msm8909/nokia-sparkler.dtsi",
'"nokia,sparkler"',
"qcom,mdss_spi_gc9307_hlt_28_qvga_cmd",
"qcom,mdss_spi_st7789vx2_ctc_28_qvga_cmd",
"KEY_VOLUMEUP"):
ok &= check(needed in patch_text, "sparkler patch contains %s" % needed)
gcc = shutil.which("gcc") or shutil.which("cc")
img_path = os.path.join(BASE, "images", "boot-lk2nd-nokia-sparkler-display.img")
if gcc and os.path.isfile(img_path):
with tempfile.TemporaryDirectory() as tmp:
streams = os.path.join(tmp, "panel_streams_sparkler.h")
test_src = os.path.join(tmp, "test_sparkler_streams.c")
r = run([sys.executable, validator,
"--image", img_path,
"--expect-display", "1",
"--emit-streams-header", streams])
ok &= check(r.returncode == 0, "panel init streams extracted from QCDT DTB")
if r.returncode == 0:
with open(test_src, "w") as fh:
fh.write(HOST_TEST_C)
binary = os.path.join(tmp, "test_sparkler_streams")
r = run([gcc, "-std=c11", "-Wall", "-Wextra", "-Werror",
"-I", tmp, "-I", os.path.join(BASE, "bootloader", "lk2nd"),
"-o", binary, test_src])
ok &= check(r.returncode == 0,
"host C unit test compiles against spi-panel-init.h")
if r.returncode == 0:
r = run([binary])
if r.stdout.strip():
print(r.stdout.strip())
ok &= check(r.returncode == 0,
"host C unit test accepts GC9307 and ST7789VX2 streams")
tampered = os.path.join(tmp, "tampered.img")
raw = bytearray(open(img_path, "rb").read())
raw[-16:] = b"X" * 16
with open(tampered, "wb") as fh:
fh.write(raw)
r = run([sys.executable, validator, "--image", tampered,
"--expect-display", "1"])
ok &= check(r.returncode != 0 and "SEANDROIDENFORCE" in r.stdout,
"validator rejects tampered SEANDROIDENFORCE trailer")
elif not gcc:
print("[skip] no host C compiler; C unit test skipped")
print("[%s] nokia-sparkler lk2nd port tests" % ("ok" if ok else "FAIL"))
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env python3
"""Offline regression checks for Nokia 8000 4G (nokia-sparkler) bring-up."""
import os
import re
import shutil
import subprocess
import sys
import unittest
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def read_text(rel_path):
with open(os.path.join(BASE_DIR, rel_path), "r", encoding="utf-8") as handle:
return handle.read()
class TestSparklerPort(unittest.TestCase):
def test_deviceinfo_and_initfs(self):
deviceinfo = read_text("devices/nokia-sparkler/deviceinfo")
for expected in (
'deviceinfo_codename="nokia-sparkler"',
'deviceinfo_dtb="qcom-msm8909-nokia-sparkler"',
'deviceinfo_drm="true"',
'deviceinfo_flash_offset_base="0x80000000"',
'deviceinfo_flash_offset_kernel="0x00008000"',
'deviceinfo_flash_offset_ramdisk="0x02700000"',
'deviceinfo_flash_offset_tags="0x02500000"',
):
self.assertIn(expected, deviceinfo)
initfs = read_text("devices/nokia-sparkler/modules-initfs").splitlines()
for mod in ("pm8916-lbc", "pm8916-bms-vm", "panel-mipi-dbi", "matrix_keypad", "matrix_keymap"):
self.assertIn(mod, initfs)
def _assert_dts_invariants(self, text):
for expected in (
'model = "Nokia 8000 4G";',
'compatible = "nokia,sparkler", "qcom,msm8909";',
'qcom,msm-id = <0xf5 0x00>;',
'qcom,board-id = <0x08 0x100>;',
'qcom,pmic-id = <0x1000d 0x00 0x00 0x00>;',
'reg = <0x80000000 0x20000000>;',
'sound@7702000',
'audio-codec@f000',
'audio-codec@771c000',
'vibrator@c000',
'apr {',
'0x500d4',
'0x100007f',
'0x205000e',
'0x301009e',
):
self.assertIn(expected, text)
for forbidden in ('0x5008b', '0x10002b8', '0x20501be', '0x30102b9', 'cd-gpios', 'broken-cd'):
self.assertNotIn(forbidden, text)
mm3 = re.search(r'dai-link-multimedia3\s*\{[^}]*status\s*=\s*"disabled";', text, re.S)
self.assertIsNotNone(mm3, "dai-link-multimedia3 must be disabled")
vib = re.search(r'vibrator@c000\s*\{[^}]*status\s*=\s*"disabled";', text, re.S)
self.assertIsNotNone(vib, "vibrator@c000 must be disabled on sparkler (157 Hz haptic audio)")
star = re.search(r'key-star\s*\{[^}]*gpios\s*=\s*<0x27 0x5a 0x01>;[^}]*linux,code\s*=\s*<0x20a>;', text, re.S)
self.assertIsNotNone(star, "key-star on gpio90 (0x5a) must map to KEY_NUMERIC_STAR (0x20a)")
resin = re.search(r'resin\s*\{[^}]*compatible\s*=\s*"qcom,pm8941-resin";[^}]*linux,code\s*=\s*<0x20b>;', text, re.S)
self.assertIsNotNone(resin, "pm8941_resin must map to KEY_NUMERIC_POUND (0x20b)")
sdhci_ext = re.search(r'sdhci@7864000\s*\{[^}]*non-removable;', text, re.S)
self.assertIsNotNone(sdhci_ext, "sdhci@7864000 must set non-removable;")
def test_dts_and_compiled_dtb_invariants(self):
dts = read_text("devices/nokia-sparkler/qcom-msm8909-nokia-sparkler.dts")
self._assert_dts_invariants(dts)
for cpu_idx in range(4):
m = re.search(
rf'cpu@{cpu_idx}\s*\{{[^}}]*clock-frequency\s*=\s*<1094400000>;',
dts,
re.S,
)
self.assertIsNotNone(m, f"cpu@{cpu_idx} must set clock-frequency = <1094400000>;")
dtc = shutil.which("dtc")
if dtc is None:
return
for dtb_rel in (
"devices/nokia-sparkler/qcom-msm8909-nokia-sparkler.dtb",
"prebuilt/kernel-6.12.1-msm8916/dtbs/qcom-msm8909-nokia-sparkler.dtb",
):
dtb_path = os.path.join(BASE_DIR, dtb_rel)
self.assertTrue(os.path.isfile(dtb_path), "missing compiled DTB: " + dtb_rel)
with open(dtb_path, "rb") as handle:
raw_dtb = handle.read()
# 1094400000 Hz in big-endian u32 is 0x413b3800 ("A;8\0" in ASCII)
self.assertGreaterEqual(raw_dtb.count(b"\x41\x3b\x38\x00"), 4, dtb_rel)
dec = subprocess.check_output([dtc, "-q", "-I", "dtb", "-O", "dts", dtb_path], text=True)
self._assert_dts_invariants(dec)
def test_smp_cpufreq_haptic_audio_and_camera_fixes(self):
patch_0013 = read_text("patches/kernel/0013-msm8909-early-scm-smp-cpufreq.patch")
for expected in (
"early_virt",
"qcom_scm_set_boot_addr_mc",
"cpu_present(cpu)",
"clock-frequency = <1094400000>;",
):
self.assertIn(expected, patch_0013)
build_k = read_text("scripts/build-kernel-audio.sh")
self.assertIn("0013-msm8909-early-scm-smp-cpufreq.patch", build_k)
sysmap = read_text("prebuilt/kernel-6.12.1-msm8916/System.map")
self.assertIn(" qcom_scm_set_boot_addr_mc\n", sysmap)
vib_c = read_text("src/dwm-plugins/sxmo_vibrate.c")
for expected in ("is_haptic_audio_device", "vibrate_haptic_audio", "157.0", "nokia,sparkler"):
self.assertIn(expected, vib_c)
build_p = read_text("scripts/build-dwm-plugins.sh")
self.assertIn("alsa", build_p)
cam_c = read_text("src/msm8905-cam/msm8905-cam.c")
for expected in (
'of_machine_is_compatible("nokia,sparkler")',
"row_buf",
"msm8905_cam_demosaic(cam->raw_dma_buf, dst_rgb, cam->rotate_180);",
):
self.assertIn(expected, cam_c)
def test_dual_gpio_torch_driver_and_module(self):
torch_src = read_text("src/leds-msm8905-torch/leds-msm8905-torch.c")
for expected in (
'#define MSM8905_TLMM_GPIO31_PHYS 0x0101f000UL',
'of_machine_is_compatible("nokia,sparkler")',
'of_machine_is_compatible("nokia,leo")',
'is_sparkler_dual_gpio_torch',
'GPIO_32/GPIO_31 (BC847BS)',
):
self.assertIn(expected, torch_src)
ko_path = os.path.join(BASE_DIR, "prebuilt/kernel-6.12.1-msm8916/leds/leds-msm8905-torch.ko")
ko_zst = ko_path + ".zst"
self.assertTrue(os.path.isfile(ko_path), "missing leds-msm8905-torch.ko")
self.assertTrue(os.path.isfile(ko_zst), "missing leds-msm8905-torch.ko.zst")
with open(ko_path, "rb") as handle:
raw_ko = handle.read()
self.assertIn(b"GPIO_32/GPIO_31 (BC847BS)", raw_ko)
modinfo = shutil.which("modinfo")
if modinfo is not None:
out = subprocess.check_output([modinfo, "-F", "vermagic", ko_path], text=True).strip()
self.assertEqual(out, "6.12.1-msm8916 SMP preempt mod_unload ARMv7 p2v8")
deps = subprocess.check_output([modinfo, "-F", "depends", ko_path], text=True).strip()
self.assertEqual(deps, "")
def test_flash_release_and_boot_validators_wired(self):
flash_py = read_text("flash-edl.py")
for expected in (
'BOOT_IMAGE_DEVICES = ("nokia-beatles", "nokia-coconut", "nokia-sparkler")',
'UNLOCK_DEFAULT_DEVICES = ("nokia-beatles", "nokia-coconut", "nokia-sparkler", "nokia-leo")',
'EDL_STAR_HASH_DEVICES = ("nokia-sparkler", "nokia-leo")',
'SPARKLER_LK2ND_IMAGE = "images/boot-lk2nd-nokia-sparkler-display.img"',
'"nokia-sparkler": SPARKLER_LK2ND_IMAGE',
):
self.assertIn(expected, flash_py)
import importlib.util
flash_spec = importlib.util.spec_from_file_location(
"flash_edl",
os.path.join(BASE_DIR, "flash-edl.py"),
)
flash_mod = importlib.util.module_from_spec(flash_spec)
flash_spec.loader.exec_module(flash_mod)
self.assertEqual(flash_mod.edl_button_combo_hint("nokia-sparkler"), "* + #")
self.assertEqual(flash_mod.edl_button_combo_hint("nokia-leo"), "* + #")
self.assertEqual(flash_mod.edl_button_combo_hint("nokia-argon"), "D-Pad Up + D-Pad Down")
self.assertEqual(flash_mod.edl_button_combo_hint("nokia-beatles"), "D-Pad Up + D-Pad Down")
self.assertEqual(flash_mod.edl_button_combo_hint("nokia-coconut"), "D-Pad Up + D-Pad Down")
manual_md = read_text("MANUAL.md")
self.assertIn("`*` + `#`", manual_md)
prep_sh = read_text("prepare-release.sh")
for expected in (
'DISPLAY_IMAGE="images/boot-lk2nd-nokia-sparkler-display.img"',
'BOOT_IMAGE="images/boot-bananarchy-nokia-sparkler.img"',
'scripts/check-lk2nd-sparkler.py',
'./scripts/build-lk2nd-sparkler.sh',
):
self.assertIn(expected, prep_sh)
sys.path.insert(0, os.path.join(BASE_DIR, "scripts"))
import importlib
bootimg_mod = importlib.import_module("check-beatles-bootimg")
bootfs_mod = importlib.import_module("sync-beatles-bootfs")
self.assertIn("nokia-sparkler", bootimg_mod.DEVICE_MODELS)
self.assertEqual(bootimg_mod.DEVICE_MODELS["nokia-sparkler"], "Nokia 8000 4G")
spec = bootimg_mod.DEVICE_SPECS["nokia-sparkler"]
self.assertEqual(spec["addrs"], (0x80008000, 0x82700000, 0x82500000))
self.assertEqual(bootfs_mod.DEVICE_DTB_NAMES["nokia-sparkler"], "qcom-msm8909-nokia-sparkler.dtb")
if __name__ == "__main__":
unittest.main()
+291
View File
@@ -0,0 +1,291 @@
#!/usr/bin/env python3
"""Offline regression tests for sxmo_timer.sh, dmenu timer integration, and hooks."""
import os
import pty
import select
import shutil
import stat
import subprocess
import tempfile
import time
import unittest
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TIMER_SH = os.path.join(BASE_DIR, "overlay/rootfs/usr/bin/sxmo_timer.sh")
def read_text(rel_path):
with open(os.path.join(BASE_DIR, rel_path), "r", encoding="utf-8") as handle:
return handle.read()
class TestTimer(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="bananarchy-timer-test-")
self.bin_dir = os.path.join(self.tmp, "bin")
self.rt_dir = os.path.join(self.tmp, "runtime")
self.home_dir = os.path.join(self.tmp, "home")
os.makedirs(self.bin_dir, exist_ok=True)
os.makedirs(self.rt_dir, exist_ok=True)
os.makedirs(os.path.join(self.home_dir, ".config", "sxmo"), exist_ok=True)
self.ring_flag = os.path.join(self.tmp, "sxmo_timer_ringing")
self.notify_log = os.path.join(self.tmp, "notify.log")
self.vibrate_log = os.path.join(self.tmp, "vibrate.log")
self.wake_log = os.path.join(self.tmp, "wake.log")
# Minimal sxmo_common.sh stub and mock helpers so BusyBox/POSIX ash behaves
# identically offline without X11 or hardware access.
self._write_exec(
"sxmo_common.sh",
"#!/bin/sh\n"
"export XDG_RUNTIME_DIR=\"${XDG_RUNTIME_DIR:-/tmp}\"\n"
"export XDG_CONFIG_HOME=\"${XDG_CONFIG_HOME:-$HOME/.config}\"\n",
)
self._write_exec(
"sxmo_aligned_sleep",
"#!/bin/sh\nsleep \"${1:-1}\"\n",
)
self._write_exec(
"dunstify",
f"#!/bin/sh\nprintf '%s\\n' \"$*\" >> '{self.notify_log}'\n",
)
self._write_exec(
"notify-send",
f"#!/bin/sh\nprintf '%s\\n' \"$*\" >> '{self.notify_log}'\n",
)
self._write_exec(
"sxmo_vibrate",
f"#!/bin/sh\nprintf '%s\\n' \"$*\" >> '{self.vibrate_log}'\nexit 0\n",
)
self._write_exec(
"dunstctl",
"#!/bin/sh\nexit 0\n",
)
self._write_exec(
"killall",
"#!/bin/sh\nexit 0\n",
)
self.env = os.environ.copy()
self.env.update({
"PATH": f"{self.bin_dir}:{self.env.get('PATH', '')}",
"HOME": self.home_dir,
"XDG_CONFIG_HOME": os.path.join(self.home_dir, ".config"),
"XDG_RUNTIME_DIR": self.rt_dir,
"SXMO_TIMER_DIR": os.path.join(self.rt_dir, "sxmo_timers"),
"SXMO_TIMER_RING_FLAG": self.ring_flag,
"SXMO_TIMER_RING_SECS": "5",
})
def tearDown(self):
try:
subprocess.run(
[TIMER_SH, "stop"],
env=self.env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
check=False,
)
finally:
shutil.rmtree(self.tmp, ignore_errors=True)
def _write_exec(self, name, content):
path = os.path.join(self.bin_dir, name)
with open(path, "w", encoding="utf-8") as handle:
handle.write(content)
os.chmod(path, 0o755)
def test_script_and_hooks_invariants(self):
st_mode = os.stat(TIMER_SH).st_mode
self.assertTrue(bool(st_mode & stat.S_IXUSR), "sxmo_timer.sh must be executable")
subprocess.check_call(["sh", "-n", TIMER_SH])
text = read_text("overlay/rootfs/usr/bin/sxmo_timer.sh")
self.assertNotIn("boottime_alarm", text)
self.assertNotIn("pkill", text)
self.assertIn("HUP INT TERM EXIT", text)
self.assertIn("stop_ringing()", text)
for rel in (
"overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_mute_ring.sh",
"overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_discard.sh",
):
hook_txt = read_text(rel)
self.assertIn("/usr/bin/sxmo_timer.sh stop_ringing", hook_txt)
dmenu_c = read_text("src/sxmo-dmenu/dmenu.c")
for expected in ("timer_menu_state(", "Stop Timer", "Cancel Timer", "/usr/bin/sxmo_timer.sh stop"):
self.assertIn(expected, dmenu_c)
def test_countdown_no_permission_error_and_stop(self):
proc = subprocess.Popen(
[TIMER_SH, "timerrun", "10m"],
env=self.env,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
timer_dir = self.env["SXMO_TIMER_DIR"]
deadline = time.monotonic() + 3.0
timer_files = []
while time.monotonic() < deadline:
if os.path.isdir(timer_dir):
timer_files = [f for f in os.listdir(timer_dir) if f.endswith(".timer")]
if timer_files:
break
time.sleep(0.05)
self.assertTrue(timer_files, "expected active .timer state file during countdown")
st = subprocess.run(
[TIMER_SH, "status"],
env=self.env,
capture_output=True,
text=True,
check=True,
)
self.assertIn("running", st.stdout)
self.assertIn("10m", st.stdout)
subprocess.run([TIMER_SH, "stop"], env=self.env, check=True)
out, err = proc.communicate(timeout=4)
self.assertEqual(err.strip(), "", f"unexpected stderr: {err!r}")
self.assertIn("Timer: 10m", out)
self.assertEqual([f for f in os.listdir(timer_dir) if f.endswith(".timer")], [])
finally:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=3)
for pipe in (proc.stdout, proc.stderr):
if pipe is not None:
pipe.close()
def test_expiry_ringing_and_stop_ringing(self):
proc = subprocess.Popen(
[TIMER_SH, "timerrun", "1s"],
env=self.env,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
deadline = time.monotonic() + 4.0
while time.monotonic() < deadline and not os.path.exists(self.ring_flag):
time.sleep(0.05)
self.assertTrue(os.path.exists(self.ring_flag), "ring flag must appear on expiry")
time.sleep(0.3)
subprocess.run([TIMER_SH, "stop_ringing"], env=self.env, check=True)
out, err = proc.communicate(timeout=4)
self.assertEqual(err.strip(), "")
self.assertIn("Done with 1s", out)
self.assertFalse(os.path.exists(self.ring_flag), "ring flag must be cleaned on stop_ringing")
self.assertTrue(os.path.exists(self.notify_log), "expected expiry notification")
self.assertTrue(os.path.exists(self.vibrate_log), "expected expiry vibrate")
finally:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=3)
for pipe in (proc.stdout, proc.stderr):
if pipe is not None:
pipe.close()
def test_pty_keypress_cancels_countdown(self):
master_fd, slave_fd = pty.openpty()
proc = subprocess.Popen(
[TIMER_SH, "timerrun", "10m"],
env=self.env,
stdin=slave_fd,
stdout=slave_fd,
stderr=subprocess.PIPE,
close_fds=True,
)
os.close(slave_fd)
output = b""
try:
deadline = time.monotonic() + 3.0
while time.monotonic() < deadline:
rlist, _, _ = select.select([master_fd], [], [], 0.2)
if rlist:
output += os.read(master_fd, 4096)
if b"Timer: 10m" in output:
break
self.assertIn(b"Timer: 10m", output)
os.write(master_fd, b"q")
rc = proc.wait(timeout=4)
self.assertEqual(rc, 0)
err = proc.stderr.read().decode("utf-8", errors="replace")
self.assertEqual(err.strip(), "")
finally:
os.close(master_fd)
if proc.stderr is not None:
proc.stderr.close()
if proc.poll() is None:
proc.kill()
proc.wait(timeout=3)
def test_pty_expiry_any_key_and_sighup_clean(self):
master_fd, slave_fd = pty.openpty()
proc = subprocess.Popen(
[TIMER_SH, "timerrun", "1s"],
env=self.env,
stdin=slave_fd,
stdout=slave_fd,
stderr=subprocess.PIPE,
close_fds=True,
)
os.close(slave_fd)
try:
deadline = time.monotonic() + 4.0
while time.monotonic() < deadline and not os.path.exists(self.ring_flag):
rlist, _, _ = select.select([master_fd], [], [], 0.1)
if rlist:
os.read(master_fd, 4096)
self.assertTrue(os.path.exists(self.ring_flag), "ring flag must appear on PTY expiry")
os.write(master_fd, b"\r")
rc = proc.wait(timeout=4)
self.assertEqual(rc, 0)
err = proc.stderr.read().decode("utf-8", errors="replace")
self.assertEqual(err.strip(), "")
self.assertFalse(os.path.exists(self.ring_flag), "keypress must clear ring flag")
finally:
os.close(master_fd)
if proc.stderr is not None:
proc.stderr.close()
if proc.poll() is None:
proc.kill()
proc.wait(timeout=3)
proc_hup = subprocess.Popen(
[TIMER_SH, "timerrun", "10m"],
env=self.env,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
)
try:
timer_dir = self.env["SXMO_TIMER_DIR"]
deadline = time.monotonic() + 3.0
while time.monotonic() < deadline:
if os.path.isdir(timer_dir) and os.listdir(timer_dir):
break
time.sleep(0.05)
self.assertTrue(os.listdir(timer_dir), "expected timer state file before SIGHUP")
proc_hup.send_signal(1)
_, err_hup = proc_hup.communicate(timeout=4)
self.assertEqual(err_hup.strip(), "")
self.assertEqual([f for f in os.listdir(timer_dir) if f.endswith(".timer")], [])
finally:
if proc_hup.poll() is None:
proc_hup.kill()
proc_hup.wait(timeout=3)
if proc_hup.stderr is not None:
proc_hup.stderr.close()
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -394,8 +394,8 @@ int runCameraApp(int argc, char** argv) {
char c = 'F';
(void)::write(writePipe, &c, 1);
}
for (int s = 0; s < 5 && !vfShouldStop && gRunning && !snapRequested.load(); ++s) {
struct timespec ts {0, 20 * 1000 * 1000};
if (!vfShouldStop && gRunning && !snapRequested.load()) {
struct timespec ts {0, 10 * 1000 * 1000};
nanosleep(&ts, nullptr);
}
} else {
+376
View File
@@ -1,15 +1,24 @@
#include <alsa/asoundlib.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <grp.h>
#include <linux/input.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static volatile sig_atomic_t g_stop = 0;
static void handle_signal(int sig) {
@@ -133,6 +142,369 @@ static void sleep_ms_interruptible(long ms) {
}
}
static int contains_icase(const char* hay, const char* needle) {
if (!hay || !needle || !*needle) return 0;
size_t nlen = strlen(needle);
for (const char* p = hay; *p; ++p) {
size_t i = 0;
while (i < nlen && p[i] &&
tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i])) {
++i;
}
if (i == nlen) return 1;
}
return 0;
}
static int is_haptic_audio_device(void) {
const char* env_ha = getenv("SXMO_VIBRATE_HAPTIC_AUDIO");
if (env_ha && *env_ha == '1') return 1;
if (env_ha && *env_ha == '0') return 0;
int fd = open("/sys/firmware/devicetree/base/compatible", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
char buf[256];
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) return 0;
buf[n] = '\0';
const char* p = buf;
const char* end = buf + n;
while (p < end && *p) {
if (strcmp(p, "nokia,sparkler") == 0 || strcmp(p, "nokia,leo") == 0) {
return 1;
}
p += strlen(p) + 1;
}
return 0;
}
static int is_non_speaker_audio_route(void) {
char buf[128];
const char* paths[2];
char cfg_dir[448];
char cfg_path[512];
get_sxmo_config_dir(cfg_dir, sizeof(cfg_dir));
snprintf(cfg_path, sizeof(cfg_path), "%s/audio_out_device", cfg_dir);
paths[0] = "/tmp/sxmo_audio_out_device";
paths[1] = cfg_path;
for (int i = 0; i < 2; ++i) {
FILE* fp = fopen(paths[i], "r");
if (!fp) continue;
if (fgets(buf, sizeof(buf), fp)) {
fclose(fp);
if (contains_icase(buf, "Headphone") ||
contains_icase(buf, "Headset") ||
contains_icase(buf, "Bluetooth") ||
contains_icase(buf, "bluez")) {
return 1;
}
return 0;
}
fclose(fp);
}
return 0;
}
static int is_pw_sink_muted(void) {
FILE* fp = fopen("/tmp/sxmo_pw_sink_muted", "r");
if (!fp) return 0;
int ch = fgetc(fp);
fclose(fp);
return ch == '1';
}
struct haptic_ctl_state {
snd_ctl_t* ctl;
int has_spk_sw;
long saved_spk_sw;
int changed_spk_sw;
int has_pri_mm1;
long saved_pri_mm1;
int changed_pri_mm1;
int has_rx3_mux;
unsigned int saved_rx3_mux;
int changed_rx3_mux;
int has_rx3_vol;
long saved_rx3_vol;
int changed_rx3_vol;
};
static int ctl_read_elem(snd_ctl_t* ctl, const char* name,
snd_ctl_elem_info_t* info,
snd_ctl_elem_value_t* val) {
snd_ctl_elem_info_clear(info);
snd_ctl_elem_info_set_interface(info, SND_CTL_ELEM_IFACE_MIXER);
snd_ctl_elem_info_set_name(info, name);
if (snd_ctl_elem_info(ctl, info) < 0) return -1;
snd_ctl_elem_value_clear(val);
snd_ctl_elem_value_set_interface(val, SND_CTL_ELEM_IFACE_MIXER);
snd_ctl_elem_value_set_name(val, name);
if (snd_ctl_elem_read(ctl, val) < 0) return -1;
return 0;
}
static void haptic_ensure_speaker_ctl(struct haptic_ctl_state* st) {
memset(st, 0, sizeof(*st));
if (snd_ctl_open(&st->ctl, "hw:0", 0) < 0) {
st->ctl = NULL;
return;
}
snd_ctl_elem_info_t* info = NULL;
snd_ctl_elem_value_t* val = NULL;
snd_ctl_elem_info_alloca(&info);
snd_ctl_elem_value_alloca(&val);
if (ctl_read_elem(st->ctl, "PRI_MI2S_RX Audio Mixer MultiMedia1",
info, val) == 0) {
st->has_pri_mm1 = 1;
st->saved_pri_mm1 = snd_ctl_elem_value_get_boolean(val, 0);
if (st->saved_pri_mm1 == 0) {
snd_ctl_elem_value_set_boolean(val, 0, 1);
if (snd_ctl_elem_write(st->ctl, val) >= 0) st->changed_pri_mm1 = 1;
}
}
if (ctl_read_elem(st->ctl, "RX3 MIX1 INP1", info, val) == 0) {
st->has_rx3_mux = 1;
st->saved_rx3_mux = snd_ctl_elem_value_get_enumerated(val, 0);
if (st->saved_rx3_mux == 0) {
unsigned int items = snd_ctl_elem_info_get_items(info);
for (unsigned int i = 0; i < items; ++i) {
snd_ctl_elem_info_set_item(info, i);
if (snd_ctl_elem_info(st->ctl, info) == 0 &&
strcmp(snd_ctl_elem_info_get_item_name(info), "RX1") == 0) {
snd_ctl_elem_value_set_enumerated(val, 0, i);
if (snd_ctl_elem_write(st->ctl, val) >= 0) st->changed_rx3_mux = 1;
break;
}
}
}
}
if (ctl_read_elem(st->ctl, "SPK DAC Switch", info, val) == 0) {
st->has_spk_sw = 1;
st->saved_spk_sw = snd_ctl_elem_value_get_boolean(val, 0);
if (st->saved_spk_sw == 0) {
snd_ctl_elem_value_set_boolean(val, 0, 1);
if (snd_ctl_elem_write(st->ctl, val) >= 0) st->changed_spk_sw = 1;
}
}
if (ctl_read_elem(st->ctl, "RX3 Digital Volume", info, val) == 0) {
st->has_rx3_vol = 1;
st->saved_rx3_vol = snd_ctl_elem_value_get_integer(val, 0);
if (st->saved_rx3_vol < 80) {
long maxv = snd_ctl_elem_info_get_max(info);
long target = (maxv >= 88) ? 88 : maxv;
snd_ctl_elem_value_set_integer(val, 0, target);
if (snd_ctl_elem_write(st->ctl, val) >= 0) st->changed_rx3_vol = 1;
}
}
}
static void haptic_restore_speaker_ctl(struct haptic_ctl_state* st) {
if (!st || !st->ctl) return;
snd_ctl_elem_info_t* info = NULL;
snd_ctl_elem_value_t* val = NULL;
snd_ctl_elem_info_alloca(&info);
snd_ctl_elem_value_alloca(&val);
if (st->changed_rx3_vol && st->has_rx3_vol &&
ctl_read_elem(st->ctl, "RX3 Digital Volume", info, val) == 0) {
snd_ctl_elem_value_set_integer(val, 0, st->saved_rx3_vol);
(void)snd_ctl_elem_write(st->ctl, val);
}
if (st->changed_spk_sw && st->has_spk_sw &&
ctl_read_elem(st->ctl, "SPK DAC Switch", info, val) == 0) {
snd_ctl_elem_value_set_boolean(val, 0, st->saved_spk_sw);
(void)snd_ctl_elem_write(st->ctl, val);
}
if (st->changed_rx3_mux && st->has_rx3_mux &&
ctl_read_elem(st->ctl, "RX3 MIX1 INP1", info, val) == 0) {
snd_ctl_elem_value_set_enumerated(val, 0, st->saved_rx3_mux);
(void)snd_ctl_elem_write(st->ctl, val);
}
if (st->changed_pri_mm1 && st->has_pri_mm1 &&
ctl_read_elem(st->ctl, "PRI_MI2S_RX Audio Mixer MultiMedia1",
info, val) == 0) {
snd_ctl_elem_value_set_boolean(val, 0, st->saved_pri_mm1);
(void)snd_ctl_elem_write(st->ctl, val);
}
snd_ctl_close(st->ctl);
st->ctl = NULL;
}
static int write_pcm_frames_all(snd_pcm_t* pcm, const short* buf,
snd_pcm_uframes_t frames) {
snd_pcm_uframes_t off = 0;
while (off < frames && !g_stop) {
snd_pcm_sframes_t rc = snd_pcm_writei(pcm, buf + off * 2, frames - off);
if (rc == -EAGAIN || rc == -EINTR) {
continue;
}
if (rc < 0) {
rc = snd_pcm_recover(pcm, (int)rc, 1);
if (rc < 0) return -1;
continue;
}
off += (snd_pcm_uframes_t)rc;
}
return g_stop ? -1 : 0;
}
static int write_haptic_pulse(snd_pcm_t* pcm, long ms, double amp) {
if (ms <= 0 || g_stop) return 0;
const long rate = 48000L;
const double step = 2.0 * M_PI * 157.0 / (double)rate;
const long total_frames = (ms * rate) / 1000L;
long fade_frames = (5L * rate) / 1000L;
if (fade_frames > total_frames / 2) fade_frames = total_frames / 2;
short chunk[2400 * 2];
long pos = 0;
while (pos < total_frames && !g_stop) {
long n = total_frames - pos;
if (n > 2400L) n = 2400L;
for (long i = 0; i < n; ++i) {
long idx = pos + i;
double env = 1.0;
if (fade_frames > 0 && idx < fade_frames) {
env = 0.5 * (1.0 - cos(M_PI * (double)idx / (double)fade_frames));
} else if (fade_frames > 0 && idx >= total_frames - fade_frames) {
long tail = total_frames - 1 - idx;
env = 0.5 * (1.0 - cos(M_PI * (double)tail / (double)fade_frames));
}
double v = env * amp * sin(step * (double)idx);
if (v > 32767.0) v = 32767.0;
if (v < -32767.0) v = -32767.0;
short s = (short)lrint(v);
chunk[i * 2] = s;
chunk[i * 2 + 1] = s;
}
if (write_pcm_frames_all(pcm, chunk, (snd_pcm_uframes_t)n) < 0) {
return -1;
}
pos += n;
}
return 0;
}
static int write_haptic_silence(snd_pcm_t* pcm, long ms) {
if (ms <= 0 || g_stop) return 0;
const long total_frames = (ms * 48000L) / 1000L;
short zeros[2400 * 2];
memset(zeros, 0, sizeof(zeros));
long pos = 0;
while (pos < total_frames && !g_stop) {
long n = total_frames - pos;
if (n > 2400L) n = 2400L;
if (write_pcm_frames_all(pcm, zeros, (snd_pcm_uframes_t)n) < 0) {
return -1;
}
pos += n;
}
return 0;
}
static int vibrate_haptic_audio(long duration_ms, int level) {
if (is_non_speaker_audio_route()) {
return 0;
}
/* Match PipeWire socket ownership when invoked from a root hook/shell. */
if (getuid() == 0 && access("/run/user/10000/pipewire-0", F_OK) == 0) {
(void)initgroups("user", 10000);
if (setgid(10000) == 0 && setuid(10000) == 0) {
(void)setenv("XDG_RUNTIME_DIR", "/run/user/10000", 1);
}
} else {
const char* xdg = getenv("XDG_RUNTIME_DIR");
struct stat st_rt;
if (!xdg || !*xdg || stat(xdg, &st_rt) != 0) {
char rt_buf[64];
snprintf(rt_buf, sizeof(rt_buf), "/run/user/%lu",
(unsigned long)getuid());
(void)setenv("XDG_RUNTIME_DIR", rt_buf, 1);
}
}
struct haptic_ctl_state ctl_st;
memset(&ctl_st, 0, sizeof(ctl_st));
snd_pcm_t* pcm = NULL;
const char* devs[2];
if (is_pw_sink_muted()) {
devs[0] = "plughw:0,0";
devs[1] = "default";
} else {
devs[0] = "default";
devs[1] = "plughw:0,0";
}
const char* opened_dev = NULL;
for (int i = 0; i < 2 && !pcm; ++i) {
if (snd_pcm_open(&pcm, devs[i], SND_PCM_STREAM_PLAYBACK, 0) == 0) {
if (snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE,
SND_PCM_ACCESS_RW_INTERLEAVED, 2, 48000,
1, 500000) < 0) {
snd_pcm_close(pcm);
pcm = NULL;
} else {
opened_dev = devs[i];
}
}
}
if (!pcm) {
fprintf(stderr, "sxmo_vibrate: cannot open haptic audio PCM\n");
return 1;
}
if (opened_dev && strcmp(opened_dev, "plughw:0,0") == 0) {
haptic_ensure_speaker_ctl(&ctl_st);
}
double amp = 21000.0;
if (level <= 1) amp = 13000.0;
else if (level >= 3) amp = 29000.0;
if (level >= 3 || duration_ms <= 90) {
long actual_ms = (level == 1 && duration_ms > 55) ? 55 : duration_ms;
(void)write_haptic_pulse(pcm, actual_ms, amp);
} else {
long on_ms = (level == 1) ? 75 : 160;
long off_ms = (level == 1) ? 125 : 80;
long rem = duration_ms;
while (rem > 0 && !g_stop) {
long cur_on = (rem < on_ms) ? rem : on_ms;
if (write_haptic_pulse(pcm, cur_on, amp) < 0) break;
rem -= cur_on;
if (rem <= 0 || g_stop) break;
long cur_off = (rem < off_ms) ? rem : off_ms;
if (write_haptic_silence(pcm, cur_off) < 0) break;
rem -= cur_off;
}
}
if (g_stop) {
(void)snd_pcm_drop(pcm);
} else {
(void)snd_pcm_drain(pcm);
}
snd_pcm_close(pcm);
haptic_restore_speaker_ctl(&ctl_st);
return 0;
}
int main(int argc, char** argv) {
if (argc < 2 || argc > 3) {
fprintf(stderr, "Usage: sxmo_vibrate duration_ms [strength_number]\n");
@@ -174,6 +546,10 @@ int main(int argc, char** argv) {
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGHUP, &sa, NULL);
if (is_haptic_audio_device()) {
return vibrate_haptic_audio(duration_ms, level);
}
int fd = open_vibrator_device();
if (fd < 0) {
fprintf(stderr, "sxmo_vibrate: cannot open vibrator device: %s\n",
+106 -33
View File
@@ -25,15 +25,18 @@
#define MSM8905_TLMM_GPIO13_PHYS 0x0100d000UL
#define MSM8905_TLMM_GPIO13_SIZE 0x1000UL
#define GPIO13_CFG_REG 0x0000U
#define GPIO13_IO_REG 0x0004U
#define GPIO13_CFG_OUT_HIGH 0x02c0U /* OE | 8mA | no pull | func=0 (gpio) */
#define GPIO13_CFG_OUT_LOW 0x0201U /* OE | 2mA | pull-down | func=0 (gpio) */
#define GPIO13_IO_HIGH 0x0002U /* BIT(1) = GPIO_OUT high */
#define GPIO13_IO_LOW 0x0000U
#define MSM8905_TLMM_GPIO31_PHYS 0x0101f000UL
#define MSM8905_TLMM_GPIO31_SIZE 0x1000UL
#define MSM8905_TLMM_GPIO32_PHYS 0x01020000UL
#define MSM8905_TLMM_GPIO32_SIZE 0x1000UL
#define TLMM_GPIO_CFG_REG 0x0000U
#define TLMM_GPIO_IO_REG 0x0004U
#define TLMM_GPIO_CFG_OUT_HIGH 0x02c0U /* OE | 8mA | no pull | func=0 (gpio) */
#define TLMM_GPIO_CFG_OUT_LOW 0x0201U /* OE | 2mA | pull-down | func=0 (gpio) */
#define TLMM_GPIO_IO_HIGH 0x0002U /* BIT(1) = GPIO_OUT high */
#define TLMM_GPIO_IO_LOW 0x0000U
#define GPIO32_CFG_REG 0x0000U
#define GPIO32_CFG_CCI_TIMER1 0x0008U /* 2mA, no pull, func=2 (cci_timer1) */
#define GPIO32_CFG_GPIO_OFF 0x0001U /* 2mA, pull-down, func=0 (gpio in) */
@@ -79,6 +82,7 @@ module_param_string(next_reboot_mode, next_reboot_mode, sizeof(next_reboot_mode)
MODULE_PARM_DESC(next_reboot_mode, "Next reboot target mode (loader, bootloader, fastboot, edl)");
static void __iomem *tlmm_gpio13_base;
static void __iomem *tlmm_gpio31_base;
static void __iomem *tlmm_gpio32_base;
static void __iomem *gcc_camss_base;
static struct regmap *pon_regmap;
@@ -86,9 +90,21 @@ static struct sys_off_handler *pon_poweroff_handler;
static struct sys_off_handler *pon_restart_handler;
static DEFINE_SPINLOCK(torch_lock);
static bool is_coconut_dual_led;
static bool is_sparkler_dual_gpio_torch;
static enum led_brightness top_torch_brightness = LED_OFF;
static enum led_brightness current_brightness = LED_OFF;
static inline void msm8905_tlmm_gpio_set(void __iomem *base, bool high)
{
if (high) {
writel_relaxed(TLMM_GPIO_IO_HIGH, base + TLMM_GPIO_IO_REG);
writel_relaxed(TLMM_GPIO_CFG_OUT_HIGH, base + TLMM_GPIO_CFG_REG);
} else {
writel_relaxed(TLMM_GPIO_IO_LOW, base + TLMM_GPIO_IO_REG);
writel_relaxed(TLMM_GPIO_CFG_OUT_LOW, base + TLMM_GPIO_CFG_REG);
}
}
static void msm8905_top_torch_hw_enable(enum led_brightness value)
{
unsigned long flags;
@@ -97,8 +113,7 @@ static void msm8905_top_torch_hw_enable(enum led_brightness value)
return;
spin_lock_irqsave(&torch_lock, flags);
writel_relaxed(GPIO13_IO_HIGH, tlmm_gpio13_base + GPIO13_IO_REG);
writel_relaxed(GPIO13_CFG_OUT_HIGH, tlmm_gpio13_base + GPIO13_CFG_REG);
msm8905_tlmm_gpio_set(tlmm_gpio13_base, true);
wmb();
top_torch_brightness = value;
spin_unlock_irqrestore(&torch_lock, flags);
@@ -112,8 +127,7 @@ static void msm8905_top_torch_hw_disable(void)
return;
spin_lock_irqsave(&torch_lock, flags);
writel_relaxed(GPIO13_IO_LOW, tlmm_gpio13_base + GPIO13_IO_REG);
writel_relaxed(GPIO13_CFG_OUT_LOW, tlmm_gpio13_base + GPIO13_CFG_REG);
msm8905_tlmm_gpio_set(tlmm_gpio13_base, false);
wmb();
top_torch_brightness = LED_OFF;
spin_unlock_irqrestore(&torch_lock, flags);
@@ -139,6 +153,21 @@ static void msm8905_torch_hw_enable(enum led_brightness value)
u32 d_count;
u32 d_reg;
if (is_sparkler_dual_gpio_torch) {
if (!tlmm_gpio31_base || !tlmm_gpio32_base)
return;
spin_lock_irqsave(&torch_lock, flags);
/* Enable flash-en (GPIO_32) then assert flash-now (GPIO_31) digitally. */
msm8905_tlmm_gpio_set(tlmm_gpio32_base, true);
wmb();
msm8905_tlmm_gpio_set(tlmm_gpio31_base, true);
wmb();
current_brightness = value;
spin_unlock_irqrestore(&torch_lock, flags);
return;
}
/*
* Scale PWM duty cycle up to 50% (d_count = 64 of N = 128) at max brightness
* so the SY7807 remains in continuous Torch mode without triggering its
@@ -175,6 +204,17 @@ static void msm8905_torch_hw_disable(void)
spin_lock_irqsave(&torch_lock, flags);
if (is_sparkler_dual_gpio_torch) {
if (tlmm_gpio31_base)
msm8905_tlmm_gpio_set(tlmm_gpio31_base, false);
if (tlmm_gpio32_base)
msm8905_tlmm_gpio_set(tlmm_gpio32_base, false);
wmb();
current_brightness = LED_OFF;
spin_unlock_irqrestore(&torch_lock, flags);
return;
}
writel_relaxed(GPIO32_CFG_GPIO_OFF, tlmm_gpio32_base + GPIO32_CFG_REG);
writel_relaxed(0x0U, gcc_camss_base + GCC_CAMSS_GP1_CBCR_STOCK);
writel_relaxed(0x0U, gcc_camss_base + GCC_CAMSS_GP1_CBCR_MAIN);
@@ -419,57 +459,59 @@ static int __init msm8905_torch_init(void)
if (!of_machine_is_compatible("qcom,msm8905") &&
!of_machine_is_compatible("qcom,msm8909") &&
!of_machine_is_compatible("nokia,argon")) {
!of_machine_is_compatible("nokia,argon") &&
!of_machine_is_compatible("nokia,sparkler") &&
!of_machine_is_compatible("nokia,leo")) {
return -ENODEV;
}
is_coconut_dual_led = of_machine_is_compatible("nokia,coconut");
is_sparkler_dual_gpio_torch = of_machine_is_compatible("nokia,sparkler") ||
of_machine_is_compatible("nokia,leo");
tlmm_gpio32_base = ioremap(MSM8905_TLMM_GPIO32_PHYS, MSM8905_TLMM_GPIO32_SIZE);
if (!tlmm_gpio32_base)
return -ENOMEM;
if (is_sparkler_dual_gpio_torch) {
tlmm_gpio31_base = ioremap(MSM8905_TLMM_GPIO31_PHYS, MSM8905_TLMM_GPIO31_SIZE);
if (!tlmm_gpio31_base) {
iounmap(tlmm_gpio32_base);
tlmm_gpio32_base = NULL;
return -ENOMEM;
}
} else {
gcc_camss_base = ioremap(MSM8905_GCC_CAMSS_PHYS, MSM8905_GCC_CAMSS_SIZE);
if (!gcc_camss_base) {
iounmap(tlmm_gpio32_base);
tlmm_gpio32_base = NULL;
return -ENOMEM;
}
}
msm8905_torch_hw_disable();
is_coconut_dual_led = of_machine_is_compatible("nokia,coconut");
if (is_coconut_dual_led) {
tlmm_gpio13_base = ioremap(MSM8905_TLMM_GPIO13_PHYS, MSM8905_TLMM_GPIO13_SIZE);
if (!tlmm_gpio13_base) {
iounmap(gcc_camss_base);
iounmap(tlmm_gpio32_base);
return -ENOMEM;
ret = -ENOMEM;
goto err_unmap;
}
msm8905_top_torch_hw_disable();
ret = led_classdev_register(NULL, &msm8905_top_torch_led);
if (ret) {
iounmap(tlmm_gpio13_base);
tlmm_gpio13_base = NULL;
iounmap(gcc_camss_base);
iounmap(tlmm_gpio32_base);
return ret;
}
if (ret)
goto err_unmap_gpio13;
ret = led_classdev_register(NULL, &msm8905_cam_flash_led);
if (ret) {
led_classdev_unregister(&msm8905_top_torch_led);
iounmap(tlmm_gpio13_base);
tlmm_gpio13_base = NULL;
iounmap(gcc_camss_base);
iounmap(tlmm_gpio32_base);
return ret;
goto err_unmap_gpio13;
}
} else {
ret = led_classdev_register(NULL, &msm8905_torch_led);
if (ret) {
iounmap(gcc_camss_base);
iounmap(tlmm_gpio32_base);
return ret;
}
if (ret)
goto err_unmap;
}
msm8905_pon_lookup_regmap();
@@ -487,11 +529,32 @@ static int __init msm8905_torch_init(void)
if (is_coconut_dual_led) {
pr_info("leds-msm8905-torch: registered white:torch on GPIO_13 and camera:flash on GPIO_32 (cci_timer1 150kHz PWM), pon_regmap=%s\n",
pon_regmap ? "ready" : "none");
} else if (is_sparkler_dual_gpio_torch) {
pr_info("leds-msm8905-torch: registered white:torch on GPIO_32/GPIO_31 (BC847BS), pon_regmap=%s\n",
pon_regmap ? "ready" : "none");
} else {
pr_info("leds-msm8905-torch: registered white:torch on GPIO_32 (cci_timer1 150kHz PWM), pon_regmap=%s\n",
pon_regmap ? "ready" : "none");
}
return 0;
err_unmap_gpio13:
iounmap(tlmm_gpio13_base);
tlmm_gpio13_base = NULL;
err_unmap:
if (tlmm_gpio31_base) {
iounmap(tlmm_gpio31_base);
tlmm_gpio31_base = NULL;
}
if (gcc_camss_base) {
iounmap(gcc_camss_base);
gcc_camss_base = NULL;
}
if (tlmm_gpio32_base) {
iounmap(tlmm_gpio32_base);
tlmm_gpio32_base = NULL;
}
return ret;
}
static void __exit msm8905_torch_exit(void)
@@ -512,8 +575,18 @@ static void __exit msm8905_torch_exit(void)
iounmap(tlmm_gpio13_base);
tlmm_gpio13_base = NULL;
}
if (tlmm_gpio31_base) {
iounmap(tlmm_gpio31_base);
tlmm_gpio31_base = NULL;
}
if (gcc_camss_base) {
iounmap(gcc_camss_base);
gcc_camss_base = NULL;
}
if (tlmm_gpio32_base) {
iounmap(tlmm_gpio32_base);
tlmm_gpio32_base = NULL;
}
}
module_init(msm8905_torch_init);
+19 -4
View File
@@ -161,6 +161,7 @@ struct msm8905_cam_dev {
u8 *raw_dma_buf;
dma_addr_t raw_dma_phys;
u8 row_buf[2][CAM_RAW_STRIDE] __aligned(8);
u8 *mmap_bufs[CAM_MAX_MMAP_BUFS];
bool buf_queued[CAM_MAX_MMAP_BUFS];
@@ -703,11 +704,23 @@ static void msm8905_cam_demosaic(const u8 *raw, u8 *rgb, bool rotate_180)
{
u32 y, x;
u32 idx = 0;
u8 *row0_buf = g_cam ? g_cam->row_buf[0] : NULL;
u8 *row1_buf = g_cam ? g_cam->row_buf[1] : NULL;
for (y = 0; y < CAM_OUT_HEIGHT; y++) {
u32 src_y = rotate_180 ? CAM_OUT_HEIGHT - 1U - y : y;
const u8 *r0 = raw + (2U * src_y) * CAM_RAW_STRIDE;
const u8 *r1 = raw + (2U * src_y + 1U) * CAM_RAW_STRIDE;
const u8 *dma_r0 = raw + (2U * src_y) * CAM_RAW_STRIDE;
const u8 *dma_r1 = raw + (2U * src_y + 1U) * CAM_RAW_STRIDE;
const u8 *r0 = dma_r0;
const u8 *r1 = dma_r1;
/* Burst-copy from uncached coherent DMA memory into L1-cached line buffers. */
if (row0_buf && row1_buf) {
memcpy(row0_buf, dma_r0, CAM_RAW_STRIDE);
memcpy(row1_buf, dma_r1, CAM_RAW_STRIDE);
r0 = row0_buf;
r1 = row1_buf;
}
for (x = 0; x < CAM_OUT_WIDTH; x += 2U) {
u32 src_x = rotate_180 ? CAM_OUT_WIDTH - 2U - x : x;
@@ -1215,8 +1228,10 @@ static int __init msm8905_cam_init(void)
return -ENOMEM;
mutex_init(&cam->lock);
/* The 2720 Flip sensor is mounted 180 degrees from the other Nokia targets. */
cam->rotate_180 = of_machine_is_compatible("nokia,beatles");
/* The 2720 Flip, 8000 4G, and 6300 4G sensors are mounted 180 degrees rotated. */
cam->rotate_180 = of_machine_is_compatible("nokia,beatles") ||
of_machine_is_compatible("nokia,sparkler") ||
of_machine_is_compatible("nokia,leo");
cam->pdev = platform_device_register_simple("msm8905-cam", -1, NULL, 0);
if (IS_ERR(cam->pdev)) {
+82
View File
@@ -1210,6 +1210,7 @@ clear_all_notifications_now(void)
"dunstctl close-all >/dev/null 2>&1; "
"dunstctl history-clear >/dev/null 2>&1; "
"pkill -x dunstify >/dev/null 2>&1; "
"/usr/bin/sxmo_timer.sh stop_ringing >/dev/null 2>&1; "
"sxmo_hook_statusbar.sh notifications >/dev/null 2>&1");
}
@@ -2211,6 +2212,72 @@ bt_is_unblocked_fast(void)
return unblocked;
}
static int
timer_menu_state(char *desc, size_t desc_len)
{
if (desc && desc_len > 0)
desc[0] = '\0';
const char *rdir = getenv("XDG_RUNTIME_DIR");
const char *roots[3];
int nroots = 0;
if (rdir && rdir[0])
roots[nroots++] = rdir;
if (!rdir || strcmp(rdir, "/run/user/10000") != 0)
roots[nroots++] = "/run/user/10000";
if (!rdir || strcmp(rdir, "/tmp") != 0)
roots[nroots++] = "/tmp";
int state = 0;
for (int i = 0; i < nroots && state < 2; i++) {
char tdir[256];
snprintf(tdir, sizeof(tdir), "%s/sxmo_timers", roots[i]);
DIR *d = opendir(tdir);
if (!d)
continue;
struct dirent *ent;
while ((ent = readdir(d)) != NULL) {
size_t nlen = strlen(ent->d_name);
if (nlen <= 6 || strcmp(ent->d_name + nlen - 6, ".timer") != 0)
continue;
char *endp = NULL;
long pid = strtol(ent->d_name, &endp, 10);
if (!endp || strcmp(endp, ".timer") != 0 || pid <= 0 ||
kill((pid_t)pid, 0) != 0)
continue;
char fpath[384];
snprintf(fpath, sizeof(fpath), "%s/%s", tdir, ent->d_name);
char line[128] = "";
if (!read_first_line(fpath, line, sizeof(line)))
continue;
char tmode[32] = "", tend[32] = "", tlabel[64] = "";
int nf = sscanf(line, "%31s %31s %63[^\n]", tmode, tend, tlabel);
if (nf >= 1 && strcmp(tmode, "ringing") == 0) {
state = 2;
if (desc && desc_len > 0 && tlabel[0])
snprintf(desc, desc_len, "%s", tlabel);
break;
}
if (nf >= 1 && strcmp(tmode, "running") == 0 && state == 0) {
state = 1;
if (desc && desc_len > 0 && tlabel[0])
snprintf(desc, desc_len, "%s", tlabel);
}
}
closedir(d);
}
if (state < 2 && access("/tmp/sxmo_timer_ringing", F_OK) == 0) {
char rbuf[32] = "";
if (read_first_line("/tmp/sxmo_timer_ringing", rbuf, sizeof(rbuf))) {
long rpid = strtol(rbuf, NULL, 10);
if (rpid > 0 && kill((pid_t)rpid, 0) == 0)
state = 2;
}
}
return state;
}
static int
count_notifications(void)
{
@@ -2653,6 +2720,21 @@ open_builtin_menu(const char *menu_name, int keep_idx)
if (strcmp(menu_name, "sys") == 0) {
reset_session_defaults(1, "Sys");
append_active_call_entries();
char tdesc[64] = "";
int tstate = timer_menu_state(tdesc, sizeof(tdesc));
if (tstate == 2) {
if (tdesc[0])
snprintf(label, sizeof(label), "%s Stop Timer (%s)", ICON_CLK, tdesc);
else
snprintf(label, sizeof(label), "%s Stop Timer", ICON_CLK);
add_menu_item(label, "/usr/bin/sxmo_timer.sh stop", 0);
} else if (tstate == 1) {
if (tdesc[0])
snprintf(label, sizeof(label), "%s Cancel Timer (%s)", ICON_CLK, tdesc);
else
snprintf(label, sizeof(label), "%s Cancel Timer", ICON_CLK);
add_menu_item(label, "/usr/bin/sxmo_timer.sh stop", 0);
}
int nnotifs = count_notifications();
int dunst_vis = dunst_window_visible();
if (nnotifs > 0) {
+131 -78
View File
@@ -5,32 +5,41 @@ import os
from Library.utils import *
class xmlparser():
def getresponse(self,input):
lines=input.split(b"<?xml")
content = {}
for line in lines:
if line==b'':
def _iter_roots(self, raw):
raw_bytes = bytes(raw)
first_xml = raw_bytes.find(b"<?xml")
if first_xml == -1:
return []
roots = []
for chunk in raw_bytes[first_xml:].split(b"<?xml"):
if not chunk:
continue
line=b"<?xml"+line
part = b"<?xml" + chunk
end = part.find(b"</data>")
if end != -1:
part = part[:end + len(b"</data>")]
part = part.strip(b"\x00 \t\r\n")
if not part:
continue
try:
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(line, parser=parser)
e = ET.ElementTree(tree).getroot()
for atype in e.findall('response'):
roots.append(ET.fromstring(part, parser=parser))
except ET.ParseError:
continue
return roots
def getresponse(self, input):
content = {}
for root in self._iter_roots(input):
for atype in root.findall('response'):
for field in atype.attrib:
content[field] = atype.attrib[field]
return content
def getlog(self, input):
lines=input.split(b"<?xml")
data = ''
for line in lines:
if line==b'':
continue
line=b"<?xml"+line
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(line, parser=parser)
e = ET.ElementTree(tree).getroot()
for atype in e.findall('log'):
for root in self._iter_roots(input):
for atype in root.findall('log'):
if 'value' in atype.attrib:
data += atype.attrib['value']
return data
@@ -245,30 +254,98 @@ class qualcomm_firehose:
return False
return False
def cmd_read_buffer(self,physical_partition_number,start_sector,num_partition_sectors,Display=True):
def _begin_raw_read(self, xml_cmd, bytes_to_read):
"""Send a <read> command and handle optional initial ACK XML packets.
Standard Qualcomm Firehose loaders (8k.mbn, 2720v.mbn) answer <read>
with <response value="ACK" rawmode="true" /> before streaming raw
sectors, whereas FIH programmers (8110.mbn, 2720.mbn, 800t.mbn) stream
raw sector data immediately.
"""
self.cdc.write(xml_cmd, self.cfg.MaxXMLSizeInBytes)
sector_size = self.cfg.SECTOR_SIZE_IN_BYTES
max_chunk = max(sector_size, self.cfg.MaxPayloadSizeToTargetInBytes)
read_size = min(bytes_to_read, max_chunk) if bytes_to_read > 0 else max_chunk
pending = bytearray()
while True:
if pending:
pkt = bytes(pending)
pending = bytearray()
else:
pkt = bytes(self.cdc.read(read_size))
if not pkt:
return False, bytearray(), "empty response from device"
raw = pkt.lstrip(b"\x00 \t\r\n")
end_idx = pkt.find(b"</data>")
is_xml = (
raw.startswith(b"<?xml")
and end_idx != -1
and (b"<response" in pkt[:end_idx] or b"<log" in pkt[:end_idx])
)
if not is_xml:
return True, bytearray(pkt), ""
split_at = end_idx + len(b"</data>")
xml_part = pkt[:split_at]
tail = pkt[split_at:]
if tail and (len(tail) >= sector_size or tail.strip(b"\x00 \t\r\n")):
leftover = bytearray(tail)
else:
leftover = bytearray()
log_msg = self.xml.getlog(xml_part)
resp = self.xml.getresponse(xml_part)
if not resp:
if leftover and leftover.lstrip(b"\x00 \t\r\n").startswith(b"<?xml"):
pending = leftover
continue
if self.getstatus(resp):
return True, leftover, log_msg
return False, bytearray(), log_msg or xml_part.decode("utf-8", "replace")
def _read_raw_sectors(self, physical_partition_number, start_sector, num_partition_sectors, on_chunk, Display=True):
if Display:
print(f"\nReading from physical partition {str(physical_partition_number)}, sector {str(start_sector)}, sectors {str(num_partition_sectors)}")
data=f"<?xml version=\"1.0\" ?><data><read SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""+\
f" num_partition_sectors=\"{num_partition_sectors}\""+\
f" physical_partition_number=\"{physical_partition_number}\""+\
data = (
f"<?xml version=\"1.0\" ?><data><read SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""
f" num_partition_sectors=\"{num_partition_sectors}\""
f" physical_partition_number=\"{physical_partition_number}\""
f" start_sector=\"{start_sector}\"/>\n</data>"
rsp=self.xmlsend(data, True)
resData=bytearray()
if (rsp[0])==True:
bytesToRead=self.cfg.SECTOR_SIZE_IN_BYTES*num_partition_sectors
total=bytesToRead
)
bytes_to_read = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors
ok, initial_raw, err_info = self._begin_raw_read(data, bytes_to_read)
if not ok:
print(f"Error:{err_info}")
return False
max_chunk = max(self.cfg.SECTOR_SIZE_IN_BYTES, self.cfg.MaxPayloadSizeToTargetInBytes)
total = bytes_to_read
dataread = 0
old = 0
prog = 0
if Display:
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
while(bytesToRead>0):
tmp=self.cdc.read(self.cfg.MaxPayloadSizeToTargetInBytes)
bytesToRead-=len(tmp)
dataread+=len(tmp)
resData+=tmp
if initial_raw and bytes_to_read > 0:
chunk = initial_raw[:bytes_to_read]
on_chunk(chunk)
bytes_to_read -= len(chunk)
dataread += len(chunk)
if total > 0:
prog = int(float(dataread) / float(total) * float(100))
if (prog > old):
if prog > old:
if Display:
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
old = prog
while bytes_to_read > 0:
tmp = self.cdc.read(min(bytes_to_read, max_chunk))
if not tmp:
print("Error:Short read from device")
return False
chunk = tmp[:bytes_to_read]
on_chunk(chunk)
bytes_to_read -= len(chunk)
dataread += len(chunk)
prog = int(float(dataread) / float(total) * float(100))
if prog > old:
if Display:
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
old = prog
@@ -277,57 +354,33 @@ class qualcomm_firehose:
time.sleep(0.2)
info, rsp = self.wait_response()
if rsp.get("value") == "ACK":
return resData
else:
return True
print(f"Error:{info}")
return False
def cmd_read_buffer(self, physical_partition_number, start_sector, num_partition_sectors, Display=True):
resData = bytearray()
if not self._read_raw_sectors(
physical_partition_number,
start_sector,
num_partition_sectors,
resData.extend,
Display=Display,
):
return ""
else:
print(f"Error:{rsp[2]}")
return ""
return ""
return resData
def cmd_read(self, physical_partition_number, start_sector, num_partition_sectors, filename, Display=True):
if Display:
print(f"\nReading from physical partition {str(physical_partition_number)}, sector {str(start_sector)}, sectors {str(num_partition_sectors)}")
with open(filename, "wb") as wf:
data=f"<?xml version=\"1.0\" ?><data><read SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""+\
f" num_partition_sectors=\"{num_partition_sectors}\""+\
f" physical_partition_number=\"{physical_partition_number}\""+\
f" start_sector=\"{start_sector}\"/>\n</data>"
rsp=self.xmlsend(data, True)
if (rsp[0])==True:
bytesToRead=self.cfg.SECTOR_SIZE_IN_BYTES*num_partition_sectors
total=bytesToRead
dataread=0
old=0
prog=0
if Display:
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
while(bytesToRead>0):
tmp=self.cdc.read(self.cfg.MaxPayloadSizeToTargetInBytes)
bytesToRead-=len(tmp)
dataread+=len(tmp)
#resData+=tmp
wf.write(tmp)
prog = int(float(dataread) / float(total) * float(100))
if (prog > old):
if Display:
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
old = prog
#time.sleep(0.05)
if Display and prog!=100:
print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50)
time.sleep(0.2)
info, rsp = self.wait_response()
if rsp.get("value")=="ACK":
return tmp
else:
print(f"Error:{info}")
return ""
else:
print(f"Error:{rsp[1]}")
return ""
if not self._read_raw_sectors(
physical_partition_number,
start_sector,
num_partition_sectors,
wf.write,
Display=Display,
):
return ""
return True
def connect(self,lvl):
v = b'-1'
+1 -1
View File
@@ -260,7 +260,7 @@ class qualcomm_sahara():
def connect(self):
try:
v = self.cdc.read()
v = self.cdc.read(timeout=2000)
if b"<?xml" in v:
return "Firehose"
elif v[0]==0x01:
+17 -5
View File
@@ -1,6 +1,9 @@
import usb.core # pyusb
import usb.util
DEFAULT_USB_TIMEOUT_MS = 30000
class usb_class():
def log(self,level,msg):
@@ -10,10 +13,11 @@ class usb_class():
else:
print(msg)
def __init__(self,vid=0x05c6, pid=0x9008, Debug=False):
def __init__(self,vid=0x05c6, pid=0x9008, Debug=False, timeout_ms=DEFAULT_USB_TIMEOUT_MS):
self.vid=vid
self.pid=pid
self.debug=Debug
self.timeout_ms=timeout_ms
self.connected=False
def connect(self):
@@ -28,6 +32,11 @@ class usb_class():
except:
pass
try:
self.configuration = self.device.get_active_configuration()
except usb.core.USBError:
self.configuration = None
if self.configuration is None:
self.device.set_configuration()
self.configuration = self.device.get_active_configuration()
self.log(2, self.configuration)
@@ -56,20 +65,23 @@ class usb_class():
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_IN)
self.device.default_timeout = self.timeout_ms
self.connected=True
return True
def write(self,command,pktsize=64):
def write(self,command,pktsize=64,timeout=None):
eff_timeout=self.timeout_ms if timeout is None else timeout
pos=0
if command==b'':
self.device.write(self.EP_OUT, b'')
self.device.write(self.EP_OUT, b'', eff_timeout)
else:
while pos<len(command):
self.device.write(self.EP_OUT,command[pos:pos+pktsize])
self.device.write(self.EP_OUT,command[pos:pos+pktsize],eff_timeout)
pos+=pktsize
def read(self,length=0x80000,timeout=None):
eff_timeout=self.timeout_ms if timeout is None else timeout
tmp=b''
while (bytearray(tmp) == b''):
tmp=self.device.read(self.EP_IN, length,timeout)
tmp=self.device.read(self.EP_IN, length, eff_timeout)
return bytearray(tmp)