Package release ZIPs, streamline docs, and backport X11 DPMS/lock fixes

- Streamline README, INSTALL, MANUAL, ARCHITECTURE, and POWER-OPTIMIZATION docs
- Add release ZIP packager (package-image.sh, scripts/package-release-zip.py, rebuild-image.sh --package) with sanitized rootfs, SHA256SUMS, and FLASH-INSTRUCTIONS.txt
- Add automatic offline MT6797 firmware ext4 injection in flash-mtk.py and scripts/extract-vendor-fw.py
- Backport X11 DPMS wake + XResetScreenSaver in geminux-powerd and _GEMINUX_LOCK_READY + grab-first sync in geminux-lock, rebuild aarch64 prebuilts, and expand tests
This commit is contained in:
Luxferre committed 2026-11-28 09:18:51 +02:00
1 parent 5472d4273a
commit 180d0a91e6
18 files changed
+1242 -480

No files matched your search

+1
View File
@@ -20,5 +20,6 @@ __pycache__/
/keys/geminux-local.rsa /keys/geminux-local.rsa
!/keys/geminux-local.rsa.pub !/keys/geminux-local.rsa.pub
/prebuilt/apk-repo/ /prebuilt/apk-repo/
/releases/
.DS_Store .DS_Store
local-reflash.sh local-reflash.sh
+33 -95
View File
@@ -1,117 +1,55 @@
# Architecture # Architecture
Geminux combines a custom-patched Linux `7.3.5` kernel, pure-Linux MTK flasher, XLibre graphics server, patched suckless desktop, unified `.Xresources` + wallpaper engine, and zero-poll C11 daemons packaged as signed Alpine APKs so standard Alpine Edge updates continue working cleanly. Geminux pairs a custom-patched Linux `7.3.5` kernel with XLibre X11, a hardened suckless desktop, unified `.Xresources` + native wallpaper rendering, zero-poll C11 daemons, pure-Linux MTK flashing/packaging tooling, and signed local APK pinning.
## Kernel and MediaTek MT6797X support ## Kernel and MediaTek MT6797X support
Vanilla Linux `7.3.5` is built from [patches/kernel/](patches/kernel/) with built-in IPsec (`CONFIG_XFRM_USER=y`, `esp4`, `esp6`, `af_key`, `xfrm_interface`) for 3GPP IMS alongside Gemini PDA hardware support: Vanilla Linux `7.3.5` builds from [patches/kernel/](patches/kernel/) with `CONFIG_XFRM_USER=y` and IPsec modules (`esp4`, `esp6`, `af_key`, `xfrm_interface`) for 3GPP IMS:
| Patch | Purpose | | Patch | Summary |
| --- | --- | | --- | --- |
| `0001-ixoo-gemini-pda-mainline-7.3.5.patch` | Core MT6797X / Gemini PDA mainline `7.3.5` platform, DRM, keypad, PMIC, and fuel-gauge base | | `0001-ixoo-gemini-pda-mainline-7.3.5.patch` | Core MT6797X / Gemini PDA `7.3.5` platform, DRM, keypad, PMIC, and fuel-gauge base |
| `0002-mt6797-ccci-cldma-and-md1-domain.patch` | Staged `mt6797-ccci-cldma` baseband transport and MD1 power-domain support | | `0002-mt6797-ccci-cldma-and-md1-domain.patch` | Staged `mt6797-ccci-cldma` baseband transport and MD1 power domains |
| `0003-arm64-dts-mediatek-geminux-gemini-pda.patch` | Geminux Device Tree bindings, pinmux, regulators, and peripheral wiring | | `0003-arm64-dts-mediatek-geminux-gemini-pda.patch` | Device Tree pinmux, regulators, and peripheral bindings |
| `0004-gemini-ssd2092-display-and-touch.patch` | Solomon Systech `SSD2092` DSI FHD+ panel and multi-touch controller fixes | | `0004-gemini-ssd2092-display-and-touch.patch` | Solomon Systech `SSD2092` DSI FHD+ panel and multi-touch controller fixes |
| `0005-mt6797-consys-wifi-factory-firmware.patch` | MT6797 CONSYS Wi-Fi/BT driver and factory firmware/NVRAM loading | | `0005-mt6797-consys-wifi-factory-firmware.patch` | CONSYS Wi-Fi/BT drivers and NVRAM/factory firmware loading |
| `0006-mt6797-boot-cleanups.patch` | Early boot and console noise cleanups | | `0006-mt6797-boot-cleanups.patch` | Early boot and console cleanups |
| `0007-mt6797-wlan-peer-deauth-and-rekey.patch` | WLAN station deauth recovery and GTK rekey stability | | `0007-mt6797-wlan-peer-deauth-and-rekey.patch` | WLAN peer deauth recovery and GTK rekey stability |
| `0008-gemini-resume-wake-and-spm-standby.patch` | S3 resume wake handling, `mt6797-spm-sleep` standby, `mtk-eint` debounce clear, and `mtk-pmic-keys` wakeups | | `0008-gemini-resume-wake-and-spm-standby.patch` | S3 resume wakes, `mt6797-spm-sleep` standby, `mtk-eint` debounce clear, `mtk-pmic-keys` |
| `0009-mt6797-wlan-drop-free-stability.patch` | CONSYS WLAN RX/TX buffer drop-free stability under load | | `0009-mt6797-wlan-drop-free-stability.patch` | CONSYS WLAN RX/TX buffer drop-free handling under load |
| `0010-mt6797-ccci-md1-boot-hs-v2-and-rpc.patch` | MD1 boot handshake v2 and CCCI RPC stabilization | | `0010-mt6797-ccci-md1-boot-hs-v2-and-rpc.patch` | MD1 boot handshake v2 and CCCI RPC stabilization |
| `0011-gemini-lid-sync-filter-and-debounce.patch` | Synchronous Hall `GPIO66` lid-close keystroke/touch filtering, `1 ms` Hall EINT & `10 ms` keypad debounce, and touch inhibit | | `0011-gemini-lid-sync-filter-and-debounce.patch` | Hall `GPIO66` synchronous lid filtering, `1 ms` Hall / `10 ms` keypad debounce, touch inhibit |
| `0012-gemini-lid-wake-and-fg-taper-fix.patch` | `gemini-lid` `PM_POST_SUSPEND` + raw-GPIO reconciliation (`BL_CORE_SUSPENDED`/input lockout fix) and `mt6351` + `bq25890` zero-current OCV calibration, CV-taper checks, `+1%` cap, and `180 mV` `ADC21` sag tolerance | | `0012-gemini-lid-wake-and-fg-taper-fix.patch` | `PM_POST_SUSPEND` + raw-GPIO lid reconciliation and `mt6351`+`bq25890` zero-current OCV/taper fuel gauge |
| `0013-gemini-pmic-wake-and-spm-safety.patch` | Moves `mt6397_irq_suspend`/`mt6397_irq_resume` from `PM_SUSPEND_PREPARE` into `LATE_SYSTEM_SLEEP_PM_OPS` so child `enable_irq_wake()` settings arm cleanly before deep sleep; hardens `mt6797-spm-sleep` `s.sleep` with `WAKE_PCM_WDT`, `pcm_wdt`, `im_wait` (`1000 us`), and a `5000 ms` `cntp` physical timer backstop (`100 ms` on `s.sodi`) | | `0013-gemini-pmic-wake-and-spm-safety.patch` | Moves `mt6397_irq_suspend`/`resume` to `LATE_SYSTEM_SLEEP_PM_OPS` and adds SPM `WAKE_PCM_WDT` + `5000 ms` `cntp` backstop |
### Hardware subsystems - **Graphics & Radios**: `mediatek-drm` + `SSD2092` DSI/touch, early `simpledrm` (`DRM_SIMPLEDRM=y` + rotated `TER16x32` console), Mali-T880 `panfrost`, `sii902x` HDMI bridge, and `mt6797_wlan_core`/`btmt6797` CONSYS.
- **Modem / eSIM / IMS**: `mt6797-ccci-cldma` exposes `/dev/ccci_*`, `/dev/ttyC0..3`, and `ccmni*` via `struct mt6797_ccci_header` ([mt6797_ccci.h](prebuilt/kernel/include/linux/mt6797_ccci.h)). [geminux-ccci-fs.c](src/geminux-daemons/geminux-ccci-fs.c) serves MD1 boot HS v2 / NVRAM / RPC; [geminux-cellctl.c](src/geminux-daemons/geminux-cellctl.c) manages SIM/ST33 eUICC (`lpac`) & `ccmni*` PDNs; [geminux-imsd.c](src/geminux-daemons/geminux-imsd.c) implements VoLTE/VoWiFi (`strongswan` `SWu`), MILENAGE AKA, XFRM `ipsec-3gpp`, SIP, `RP-DATA` SMS, and 20 ms RTP.
- **Graphics & display**: MediaTek DRM (`mediatek-drm`), `SSD2092` DSI FHD+ panel/touch, early-boot `simpledrm` (`DRM_SIMPLEDRM=y` + rotated `TER16x32` console), Mali-T880 `panfrost` GPU, and `sii902x` Slimport/HDMI bridge. - **Boot, LUKS2 FDE & Recovery**: `mkbootimg-osm0sis` packs LK images (`<= 16 MiB` boot/recovery, `<= 512 KiB` DTB). Built-in `BLK_DEV_DM=y`, `DM_CRYPT=y`, and ARMv8 AES-CE (`CRYPTO_AES_ARM64_CE_BLK=y`) power LUKS2 unlock in [src/initramfs/init](src/initramfs/init) (`cryptsetup` + `/etc/gemini-us.kmap`, `DM_DISABLE_UDEV=1`, `e2fsck -p`, `resize2fs -f`). [src/initramfs/init-recovery](src/initramfs/init-recovery) provides a USB NCM shell (`172.16.42.1/24`) with LUKS2-aware helpers. See [POWER-OPTIMIZATION.md](POWER-OPTIMIZATION.md) for suspend and CPU/power architecture.
- **Wi-Fi / Bluetooth CONSYS**: Staged `mt6797_wlan_core` and `btmt6797` drivers backed by NVRAM/factory firmware provisioning (`geminux-wifi-nvram` and `firmware-cache/mt6797/`), hardened by `0007` and `0009`.
- **Modem / Telephony / eSIM / IMS**: `mt6797-ccci-cldma` exposes `/dev/ccci_md_ctl`, `/dev/ccci_fs`, `/dev/ccci_rpc`, `/dev/ttyC0..3`, and `ccmni*` via the 16-byte `struct mt6797_ccci_header` UAPI ([prebuilt/kernel/include/linux/mt6797_ccci.h](prebuilt/kernel/include/linux/mt6797_ccci.h)):
- [geminux-ccci-fs.c](src/geminux-daemons/geminux-ccci-fs.c) (`geminux-ccci-daemon`): MD1 boot HS v2, NVRAM/CCCI_FS I/O, and RPC (`MD_STATE=READY`).
- [geminux-cellctl.c](src/geminux-daemons/geminux-cellctl.c) (`geminux-cellctl`): physical SIM vs. ST33 eUICC `AT+ESIMS` switching, `lpac` AT-`CSIM`/`CGLA` APDU bridging, and `ccmni*` LTE PDN bring-up.
- [geminux-imsd.c](src/geminux-daemons/geminux-imsd.c) (`geminux-imsd`): 3GPP VoLTE (`ccmni*`) & VoWiFi (`SWu` IKEv2/IPsec via `strongswan`), MILENAGE AKA, kernel XFRM `ipsec-3gpp` (with RFC 4303 userspace ESP fallback), SIP signaling, `RP-DATA` SMS, and 20 ms `timerfd` AMR-NB/AMR-WB/G.711/DTMF RTP bridged to PipeWire/ALSA `VoiceCall`.
- **Boot, LUKS2 FDE & recovery**: LK-compatible images (`images/boot-geminux.img`, `images/recovery-geminux.img`) built with `mkbootimg-osm0sis` (`16 MiB` boot ceiling, `512 KiB` DTB ceiling). Built-in `BLK_DEV_DM=y`, `DM_CRYPT=y`, and ARMv8 AES-CE (`CRYPTO_AES_ARM64_CE_BLK=y`) power initramfs unlock (`cryptsetup` + `/etc/gemini-us.kmap`, `DM_DISABLE_UDEV=1`). [src/initramfs/init](src/initramfs/init) runs the off-mode charger guard, optionally unlocks `PARTLABEL=linux` -> `/dev/mapper/geminux_root`, checks ext4 (`e2fsck -p </dev/null`), and expands the filesystem on first boot (`resize2fs -f </dev/null`). [src/initramfs/init-recovery](src/initramfs/init-recovery) provides a USB NCM/RNDIS shell (`172.16.42.1/24`) with LUKS2-aware `unlock-root`, `check-fs`, and `mount-root`.
## Graphics, window management, and stability ## Graphics, window management, and stability
### XLibre (`25.x`) - **XLibre (`25.x`)**: Cross-compiled against pure Alpine Edge `aarch64` sysroots ([scripts/build-xlibre.sh](scripts/build-xlibre.sh)). [10-geminux-gpu.conf](overlay/rootfs/etc/X11/xorg.conf.d/10-geminux-gpu.conf) uses `AccelMethod "none"`, `ShadowFB "true"`, `TearFree "true"`, `PageFlip "false"`, `SWcursor "true"`, and `Rotate "left"` to avoid rotated DSI tearing while keeping Panfrost EGL/OpenGL 3D enabled. Zero Wayland compositors are installed.
- **`dwm`**: 32-bit ARGB XEmbed systray (`_NET_SYSTEM_TRAY_S0`, reparent/input race fixes, restacked under fullscreen lockscreen); EWMH/ICCCM/NETWM (`_NET_WORKAREA` struts, `_NET_WM_STATE_{FOCUSED,STICKY,ABOVE,HIDDEN}`, `WM_CHANGE_STATE`, `nofocuswin`, Wine/DXVK focus recovery); `in_xerror` recursion & non-fatal `RENDER` error guards, bounded `200 ms` `getservertime()`, async pointer/button grabs; Pango `PANGO_ELLIPSIZE_END`, `FC_COLOR=FcFalse`, and UTF-8 sanitization in `drw.c`; `>= 78 px` bar, `Mod4` tap-latch, `Fn+F`, `Mod4+Shift+r`/`SIGUSR1` `.Xresources` reload, and `SIGHUP` self-reexec.
- **`dmenu` & `st` & `dunst`**: `dmenu` uses Pango/HarfBuzz `82 px` rows, `dmenu_xerror`/`RENDER` guards, `FC_COLOR=FcFalse`, UTF-8 sanitization, and pairs with `geminux-launcher`. `st` adds HarfBuzz Fira Code ligatures (`hb.c`), wheel scrollback, `FocusIn`/`FocusOut` cursor sync + unfocused blink gating, and `XA_RESOURCE_MANAGER` + `SIGUSR1` reloads. `dunst v1.12.2` ([src/dunst-notify/](src/dunst-notify/)) runs pure-X11 without `gdk-pixbuf`.
Cross-compiled against pure Alpine Edge `aarch64` sysroots with `modesetting_drv.so`, `fbdev_drv.so`, `libinput_drv.so`, and Panfrost Glamor EGL (`libglamoregl.so`) via [scripts/build-xlibre.sh](scripts/build-xlibre.sh). [10-geminux-gpu.conf](overlay/rootfs/etc/X11/xorg.conf.d/10-geminux-gpu.conf) sets `AccelMethod "none"`, `ShadowFB "true"`, `TearFree "true"`, `PageFlip "false"`, `SWcursor "true"`, and `Rotate "left"` to prevent rotated DSI tearing and Glamor fence spin-wait overhead while keeping Panfrost EGL/OpenGL 3D active for applications. Zero Wayland compositors are installed. ## Unified theming, wallpaper engine, and media
### Patched suckless desktop - **Unified Theming**: Defaults to **Anodized** (`192 DPI`, `baseFontSize: 32`, `Xcursor.size: 64`). `geminux-session` merges new `/etc/skel/.xthemes/*.xth` files into `~/.xthemes/`, seeds `/etc/skel/.config/geminux/wallpaper.conf` on first boot, and loads `~/.Xresources` via `xrdb -nocpp -load`. [geminux-xth.h](src/geminux-apps/geminux-xth.h) powers `geminux-themes` interactive Editor & `.xth` Importer (`~/.config/geminux/themes/`). `geminux-apply-theme` syncs Dunst, GTK2/GTK3/GTK4/`libadwaita` (`ADW_DISABLE_PORTAL=1` + `dconf` in [10-geminux-env.sh](overlay/rootfs/etc/profile.d/10-geminux-env.sh)), `xsettingsd`, Qt5/Qt6 (`qt6ct` `QT_QPA_PLATFORMTHEME=qt6ct:gtk3` + Kvantum), Tk/Ttk (`gtkTtk 0.9` in [src/gtkTtk/](src/gtkTtk/)), live X11 clients, and wallpaper mattes (`USE_THEME_BG=1`).
- **Native X11 Wallpaper Engine**: [geminux-wallpaper.h](src/geminux-apps/geminux-wallpaper.h) + [geminux-wallpaper-x11.h](src/geminux-apps/geminux-wallpaper-x11.h) decode images in pure C via `dlopen("libgdk_pixbuf-2.0.so.0")` (`geminux-gdk-pixbuf`, EXIF orientation), Cairo PNG, `libjpeg-turbo`, `libwebp`, and `magick`/`convert` fallback; draw to a retained root `Pixmap` (`_XROOTPMAP_ID`, `ESETROOT_PMAP_ID`, `RetainPermanent`, `XKillClient`, XRandR/Xinerama multi-monitor); and bundle `artwork/wallpapers/` into `/usr/share/geminux/wallpapers/`.
- **`dwm`**: - **Webarchy & Media**: [webarchy.cpp](src/webarchy/webarchy.cpp) (`GTK3` + `WebKit2GTK-4.1`, software crash fallback), pure-C `gdk-pixbuf 2.42.12` + GSettings schemas ([scripts/build-webarchy.sh](scripts/build-webarchy.sh), [scripts/compile-gsettings-schemas.sh](scripts/compile-gsettings-schemas.sh)), native `mpv` ([mpv.conf](overlay/rootfs/etc/mpv/mpv.conf)), `ffmpeg`/`gst-libav`, and `yt-dlp` (`quickjs`).
- **Systray & stacking**: 32-bit ARGB XEmbed systray (`_NET_SYSTEM_TRAY_S0`), XEmbed reparent/input race protection, and automatic restacking below fullscreen lockscreen windows.
- **EWMH / ICCCM / NETWM**: `_NET_WORKAREA` dock struts, `_NET_WM_STATE_{FOCUSED,STICKY,ABOVE,HIDDEN}`, desktop/PID atoms, `WM_CHANGE_STATE`, `nofocuswin` fallback, and Wine/DXVK focus recovery.
- **X11 / Pango hardening**: `in_xerror` recursion guard with rate-limited non-fatal `RENDER` error ignoring, bounded `200 ms` `getservertime()` polling, async grab safety (`AsyncBoth` / `GrabModeAsync`), and Pango `PANGO_ELLIPSIZE_END` + `FC_COLOR=FcFalse` + UTF-8 sanitization in `drw.c` (avoiding XRender `BadLength` faults on color emoji glyphs).
- **Gemini UX**: `>= 78 px` touch top bar, `Mod4 = Fn+Alt` + one-shot `Super_L` tap-latch, `Fn+F` Airplane Mode binding, `Mod4 + Shift + r` & `SIGUSR1` `.Xresources` reload, and `SIGHUP` self-reexec.
- **`dmenu`**: Pango/HarfBuzz rendering with `82 px` touch rows, `dmenu_xerror` recursion & non-fatal `RENDER` guards, `FC_COLOR=FcFalse` + UTF-8 sanitization, and direct mouse/touch selection. Pairs with `geminux-launcher` pinning the 11 GUI apps alongside `Wallpaper`, `Webarchy Browser`, `Bantam AI agent`, and `Lynx Web Browser` in `st` (wrapping `Terminal=true` `.desktop` entries in `st -e`).
- **`st`**: HarfBuzz Fira Code ligatures (`hb.c`), Nerd Font fallback, mouse/two-finger wheel scrollback, immediate cursor redraw on `FocusIn`/`FocusOut` + unfocused blink gating, and live theme reloading via both direct `XA_RESOURCE_MANAGER` `PropertyNotify` and `SIGUSR1`.
- **Notifications**: Pure-X11 zero-`gdk-pixbuf` `dunst v1.12.2` (`WAYLAND=0 DUNSTIFY=0`) with custom pure-C PNG/JPEG icon loader ([src/dunst-notify/](src/dunst-notify/)) and lightweight GDBus `notify-send` / `dunstify`.
## Unified theming and native X11 wallpaper engine
Geminux defaults to the **Anodized** theme (`192 DPI`, `baseFontSize: 32`, `Xcursor.size: 64`) across `/etc/skel/.Xresources` and all compiled-in and script fallbacks. On login, `geminux-session` non-destructively copies newly added `/etc/skel/.xthemes/*.xth` themes into `~/.xthemes/` and loads `~/.Xresources` cleanly via `xrdb -nocpp -load`.
### Theme editor, importer & toolkit synchronization
- **Editor & Importer**: [geminux-xth.h](src/geminux-apps/geminux-xth.h) provides shared `.xth` parsing/serialization for `geminux-themes` (`Edit`, `Duplicate`, `New`, `Reset`/`Delete`, live WCAG contrast ratio against `bgMain`, and `Import .xth` stored under `~/.config/geminux/themes/`).
- **Synced targets**: `geminux-apply-theme` (`.xth` -> `~/.Xresources` + `xrdb -nocpp -load`) synchronizes:
- **Dunst**: `~/.config/dunst/dunstrc` via `geminux-sync-dunst-theme`
- **GTK2 / GTK3 / `xsettingsd`**: `Geminux-<Theme>` light/dark styling in `~/.gtkrc-2.0`, `~/.config/gtk-3.0/{settings.ini,gtk.css}`, and `~/.config/xsettingsd/xsettingsd.conf` (`SIGHUP` reload)
- **GTK4 & `libadwaita`**: `~/.config/gtk-4.0/{settings.ini,gtk.css}` + `dconf` `color-scheme` (`ADW_DISABLE_PORTAL=1` in [10-geminux-env.sh](overlay/rootfs/etc/profile.d/10-geminux-env.sh))
- **Qt5 / Qt6**: `qt6ct` 21-role `QPalette` (`QT_QPA_PLATFORMTHEME=qt6ct:gtk3`) and Kvantum (`QT_STYLE_OVERRIDE=kvantum`)
- **Tcl/Tk (`gtkTtk 0.9`)**: `*TkTheme: gtkTtk` + DPI-scaled widget geometry against `~/.gtkrc-2.0` with pure-X11 XImage blitting and zero-poll `XA_RESOURCE_MANAGER` live reload ([src/gtkTtk/](src/gtkTtk/))
- **X11 clients**: Instant redraw via `XA_RESOURCE_MANAGER` `PropertyNotify` and `SIGUSR1` (`dwm`, `st`, `webarchy`, `libgemui`)
### Native X11 + Cairo wallpaper engine
- **Core engine**: [geminux-wallpaper.h](src/geminux-apps/geminux-wallpaper.h) (pure-C11 config & placement geometry) + [geminux-wallpaper-x11.h](src/geminux-apps/geminux-wallpaper-x11.h) (X11/Cairo renderer) integrated into `geminux-themes` and exposed to CLI via `geminux-apply-wallpaper`.
- **Image decoders**: Decodes via runtime `dlopen("libgdk_pixbuf-2.0.so.0")` (EXIF auto-orientation + PNG/JPEG/GIF/BMP/ICO/XPM/XBM/TGA/PNM powered by `geminux-gdk-pixbuf`), Cairo PNG, `libjpeg-turbo`, `libwebp`, and optional `magick`/`convert` fallback.
- **Root Pixmap protocol**: Renders onto an X11 root `Pixmap` using a dedicated `Display` connection with `XSetCloseDownMode(..., RetainPermanent)`, publishing `_XROOTPMAP_ID` and `ESETROOT_PMAP_ID` and cleaning up previous clients via `XKillClient`. Supports multi-monitor geometry via XRandR and Xinerama.
- **Persistence & hooks**: Saves state to `~/.config/geminux/wallpaper.conf` and restores automatically on login (`geminux-session`), on theme changes when `USE_THEME_BG=1` (`geminux-apply-theme`), and after external HDMI `xrandr` layout switches (`geminux-net`).
### Webarchy, pure-C `gdk-pixbuf` & media stack
- **Webarchy**: [src/webarchy/webarchy.cpp](src/webarchy/webarchy.cpp) is a C++20 `GTK3` + `WebKit2GTK-4.1` browser tuned for `2160x1080` (`1080x506` logical @ `GDK_SCALE=2`) with a collapsible right-side vertical tab bar, `SIGUSR1` `.Xresources` reloading, SQLite cookies/bookmarks, single-instance FIFO forwarding, and WebProcess crash software fallback.
- **Pure-C `gdk-pixbuf` & schemas**: [scripts/build-webarchy.sh](scripts/build-webarchy.sh) cross-compiles pure-C GNOME `gdk-pixbuf 2.42.12` (`-Dbuiltin_loaders=all`, zero `libglycin`/`librsvg`), and [scripts/compile-gsettings-schemas.sh](scripts/compile-gsettings-schemas.sh) builds `/usr/share/glib-2.0/schemas/gschemas.compiled`.
- **Media & `yt-dlp`**: Native Alpine Edge `mpv` ([overlay/rootfs/etc/mpv/mpv.conf](overlay/rootfs/etc/mpv/mpv.conf) — Panfrost X11 EGL, PipeWire/Pulse/ALSA, `/tmp/geminux-mpv.sock` IPC), `ffmpeg`/`ffprobe`, `gst-libav`, `mpg123`, `openmpt123`, `python3`/`py3-pip`, and `yt-dlp` (`quickjs`, avoiding `deno`/`py3-cryptography`).
## Custom UI toolkit and zero-poll C11 daemons ## Custom UI toolkit and zero-poll C11 daemons
- **`libgemui.so`** ([src/libgemui/](src/libgemui/)): Double-buffered Cairo + Pango/HarfBuzz Xlib toolkit with direct `XA_RESOURCE_MANAGER` `PropertyNotify` and `SIGUSR1` `.Xresources` live reloads, fullscreen lockscreen visibility restacking, button contrast guards, X11 clipboard paste, dynamic timers, `MSG_NOSIGNAL` socket IPC (`gemui_unix_cmd`), and non-blocking extra FDs. - **`libgemui.so`** ([src/libgemui/](src/libgemui/)): Double-buffered Cairo + Pango/HarfBuzz X11 toolkit with `XA_RESOURCE_MANAGER` + `SIGUSR1` live reloads, lockscreen restacking, contrast guards, clipboard paste, and socket IPC.
- **11 landscape HiDPI apps** ([src/geminux-apps/](src/geminux-apps/)): `geminux-control`, `geminux-audio`, `geminux-datetime`, `geminux-net` (Wi-Fi, Cellular/ST33 eSIM, Bluetooth, HDMI, `DNS` tab, Airplane Mode), `geminux-dialer`, `geminux-callscreen`, `geminux-sms`, `geminux-contacts`, `geminux-camera`, `geminux-themes` (Themes, Theme Editor, `.xth` Importer & Wallpaper), and `geminux-lock`. - **11 HiDPI apps** ([src/geminux-apps/](src/geminux-apps/)): `geminux-control`, `geminux-audio`, `geminux-datetime`, `geminux-net`, `geminux-dialer`, `geminux-callscreen`, `geminux-sms`, `geminux-contacts`, `geminux-camera`, `geminux-themes`, and `geminux-lock`.
- **Zero-poll C11 daemons** ([src/geminux-daemons/](src/geminux-daemons/)): - **Zero-poll daemons** ([src/geminux-daemons/](src/geminux-daemons/)): `geminux-powerd`, `geminux-statusd`, `geminux-touchd`, `geminux-leds`, `geminux-ccci-daemon`, `geminux-cellctl`, `geminux-imsd`, `geminux-modem-ctl`, `geminux-bt-obex`, `geminux-dnsctl`, `geminux-power-ctl`, `geminux-power-audit`, `geminux-tzctl`, `geminux-wifi-nvram`, and `geminux-checkpw` (detailed in [POWER-OPTIMIZATION.md](POWER-OPTIMIZATION.md)).
- **`geminux-powerd`**: `epoll` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`, `mtk-pmic-keys` `KEY_ESC`), filtered `KOBJECT_UEVENT` (`input`, `power_supply`, `drm`), `/run/geminux/powerd.sock`, and `timerfd`:
- Enforces `inhibit_ac_lid` (locks/blanks without unloading CONSYS or calling `/sys/power/state` while on USB/AC).
- Tears down `mt6797_consys` and parks `cpu1..9` offline before battery `mem` suspend or zero-thrash `low_power_standby` when `MD1` is active (never `freeze`/`s2idle`).
- Polls post-resume input/lid events (`90 ms`) even when the lid is open so only a `closed -> open` lid transition, real `EV_KEY`/`EV_REL`/`EV_ABS` activity, or USB/AC attach counts as a wake; internal timer wakes during open-lid idle lock re-suspend cleanly (`quiet_timer_resleep`) without reloading CONSYS or waking the backlight.
- Persists hardware Airplane Mode (`/var/lib/geminux/airplane-mode`) and resolves UID `10000` dynamically.
- **`geminux-statusd`**: `epoll` over `signalfd` (`SIGUSR1`), `RTMGRP_LINK`/`RTMGRP_IPV4_IFADDR`, filtered `KOBJECT_UEVENT` (`power_supply`, `net`), `inotify`, and minute-aligned `timerfd`; shows `AIRPLANE` status and deduplicates `WM_NAME` updates with zero shell forks.
- **`geminux-touchd`**: XInput 2.2 multi-touch gesture recognizer.
- **`geminux-leds`**: AW9120 back cover RGB controller (`/run/geminux/leds.sock`, off when idle/100%, amber `rgb:indicator-6` while charging, persistent manual override).
- **`geminux-ccci-daemon`, `geminux-cellctl`, `geminux-imsd`, `geminux-modem-ctl`, `geminux-bt-obex`, `geminux-dnsctl`, `geminux-power-ctl`, `geminux-power-audit`, `geminux-tzctl`, `geminux-wifi-nvram`, `geminux-checkpw`**: Event-driven platform daemons and control helpers.
## APK package pinning and package policy ## APK package policy
1. **Pure Edge rootfs**: Host Docker containers use `postmarketos/v26.06` only for `gcc-aarch64`, `binutils-aarch64`, and `mkbootimg-osm0sis`. Both `$SYSROOT` and target `$ROOTFS` come strictly from **Alpine Edge** (`main`, `community`, `testing`) plus the RSA-4096 signed local `@geminux` repo (`/var/lib/geminux/apk-repo`). Target `$ROOTFS` installs only pure **Alpine Edge** (`main`, `community`, `testing`) plus 11 RSA-4096 signed `@geminux` APKs built by [scripts/package-local-apks.sh](scripts/package-local-apks.sh): `geminux-kernel-modules`, `geminux-xlibre`, `geminux-suckless`, `geminux-dunst`, `geminux-ui`, `geminux-bantam` ([build-bantam.sh](scripts/build-bantam.sh)), `geminux-gsocket` ([build-gsocket.sh](scripts/build-gsocket.sh)), `geminux-gdk-pixbuf`, `geminux-webarchy`, `geminux-gtkttk` ([build-gtkttk.sh](scripts/build-gtkttk.sh)), and `geminux-config` (including bundled wallpapers, `/etc/mpv/mpv.conf`, `geminux-sdcard` udev/OpenRC units). `/etc/apk/world` pins all 11 with `name@geminux=version` and blocks disallowed Rust/Wayland overrides via [scripts/rootfs-prune-packages.txt](scripts/rootfs-prune-packages.txt), enforced by [scripts/check-rebuild.sh](scripts/check-rebuild.sh). `/etc/apk/protected_paths.d/geminux.list` shields configs across upgrades.
2. **Eleven signed local packages**: [scripts/package-local-apks.sh](scripts/package-local-apks.sh) builds and indexes:
- `geminux-kernel-modules`
- `geminux-xlibre`
- `geminux-suckless`
- `geminux-dunst`
- `geminux-ui`
- `geminux-bantam` ([scripts/build-bantam.sh](scripts/build-bantam.sh))
- `geminux-gsocket` ([scripts/build-gsocket.sh](scripts/build-gsocket.sh))
- `geminux-gdk-pixbuf` ([scripts/build-webarchy.sh](scripts/build-webarchy.sh))
- `geminux-webarchy` ([scripts/build-webarchy.sh](scripts/build-webarchy.sh))
- `geminux-gtkttk` ([scripts/build-gtkttk.sh](scripts/build-gtkttk.sh))
- `geminux-config` (`/etc/mpv/mpv.conf`, `/etc/htoprc`, `~/.lynx.cfg`, `~/.apexrc`, `~/.bashrc` with `GPG_TTY`, `/etc/profile.d/10-geminux-env.sh`, `/etc/init.d/geminux-sdcard` + `95-geminux-sdcard.rules` + `/usr/sbin/geminux-sdcard-mount`)
3. **World pins & exclusions**: `/etc/apk/world` exact-pins all 11 with `name@geminux=version` and blocks Rust/Wayland/override packages via `!` constraints from [scripts/rootfs-prune-packages.txt](scripts/rootfs-prune-packages.txt) (`librsvg`, `rav1e`/`rav1e-libs`, `libdovi` whitelisted). Enforced by ELF Rust scans, `apk upgrade --simulate`, and 9 host Python test suites in [scripts/check-rebuild.sh](scripts/check-rebuild.sh).
4. **Config protection**: `/etc/apk/protected_paths.d/geminux.list` shields Geminux config directories across `apk upgrade`.
## Pure-Linux flasher and eMMC layout ## Flasher, offline provisioning, and release ZIP packager
[flash-mtk.py](flash-mtk.py) embeds vendored GPLv3 `mtkclient` + `MTK_DA_V5_MT6797.bin` to communicate directly over USB BROM/DA. Protected partitions in `LBA 0..0x6FFFF` (`preloader`, `nvram`, `proinfo`, `lk`, `tee1`, `md1img`, etc.) are backed up and write-blocked by default (`0x0E000000` boundary verified in [scripts/test-flash-mtk-gpt.py](scripts/test-flash-mtk-gpt.py)). - **BROM/DA Flasher**: [flash-mtk.py](flash-mtk.py) uses vendored `mtkclient` + `MTK_DA_V5_MT6797.bin`, write-blocking protected factory partitions (`LBA 0..0x6FFFF` / `0x0E000000`, verified in [scripts/test-flash-mtk-gpt.py](scripts/test-flash-mtk-gpt.py)).
- **Staged ext4 Customization**: On temporary ext4 copies, [scripts/extract-vendor-fw.py](scripts/extract-vendor-fw.py) injects MT6797 firmware blobs via `debugfs`/`e2fsck`, [scripts/geminux_accounts.py](scripts/geminux_accounts.py) provisions SHA-512 `/etc/{passwd,group,shadow}` + `/home/<user>`, and [scripts/geminux_luks.py](scripts/geminux_luks.py) optionally applies offline LUKS2 encryption (`cryptsetup reencrypt`).
On staged copies of `geminux-rootfs.img` (without modifying `images/geminux-rootfs.img`), [scripts/geminux_accounts.py](scripts/geminux_accounts.py) handles offline `$6$` SHA-512 `/etc/{passwd,group,shadow}` and `/home/<username>` provisioning via `debugfs`/`e2fsck`, and [scripts/geminux_luks.py](scripts/geminux_luks.py) optionally wraps the staged ext4 image in LUKS2 via unprivileged host `cryptsetup reencrypt --encrypt --disable-locks`. - **Release ZIP Packager**: [package-image.sh](package-image.sh) ([scripts/package-release-zip.py](scripts/package-release-zip.py)) clones and sanitizes `geminux-rootfs.img` (stripping SSH keys and proprietary MT6797 blobs by default), runs `e2fsck -fn`, generates `SHA256SUMS.txt` + `FLASH-INSTRUCTIONS.txt`, and writes a verified ZIP64 release archive + `.sha256`.
+62 -88
View File
@@ -1,128 +1,102 @@
# Installation guide # Installation guide
This guide walks through building Geminux images and flashing a **Planet Computers Gemini PDA** (Wi-Fi + 4G, MT6797X) directly from Linux without MediaTek's proprietary FlashTool GUI. Flash a **Planet Computers Gemini PDA** (Wi-Fi + 4G, MT6797X) directly from Linux using Geminux's bundled pure-Python MediaTek BROM/DA flasher—either from a prebuilt release ZIP or from a local source build.
## Prerequisites on the Linux host ## Option A: Flash a prebuilt release ZIP
1. **Docker** (`docker`) installed and running for `aarch64` cross-compilation and Alpine rootfs assembly. ### Host prerequisites (no Docker required)
2. **Host tools**: `python3`, `libusb-1.0`, and `udev` or `sudo` privileges for MediaTek USB BROM/DA access.
3. **Optional sparse tools**: `img2simg` and `simg2img` (`android-tools` or `ext4` sparse utilities) if you want Android sparse image output.
4. **Hardware**: A Planet Computers Gemini PDA (x27 Wi-Fi + 4G) and a USB-C data cable connected directly to a host USB port (avoid unpowered hubs).
On hosts running `ModemManager`, [flash-mtk.sh](flash-mtk.sh) automatically pauses `ModemManager` during flashing and restarts it on exit so `/dev/ttyACM*` is not claimed away from the BROM/Preloader handshake. 1. Linux x86_64/arm64 PC with `python3`, `python3-pip`, `libusb-1.0`, `e2fsprogs` (`debugfs`, `e2fsck`), and `sudo` (raw USB access).
2. Optional: `cryptsetup` (only for `--encrypt` LUKS2 full-disk encryption) and `simg2img` (only if extracting firmware from a sparse stock Android `system.img`).
3. Gemini PDA (x27) connected directly to a host USB port via USB-C data cable (avoid unpowered hubs).
## Step 1: Build the Geminux images ### Steps
From the repository root:
```sh ```sh
./rebuild-image.sh unzip geminux-<version>-<codename>-gemini-x27.zip
./scripts/check-rebuild.sh cd geminux-<version>-<codename>-gemini-x27
sha256sum -c SHA256SUMS.txt
cat FLASH-INSTRUCTIONS.txt # bundled plain-text flashing guide
``` ```
This writes: Continue to [Flashing to the Gemini PDA](#flashing-to-the-gemini-pda) below.
- `images/boot-geminux.img` — `<= 16 MiB` LK boot image containing `Image.gz`, `mt6797-gemini-pda-geminux.dtb`, and initramfs ## Option B: Build from source and package a release
- `images/recovery-geminux.img` — initramfs recovery image with USB NCM rescue shell
- `images/geminux-rootfs.img` — ext4 root filesystem labeled `geminux-root`
- `images/geminux-rootfs.simg` — Android sparse copy (generated when `img2simg` is installed)
- `images/SHA256SUMS`
## Step 2: Backup factory partitions and extract MediaTek firmware ### Build host prerequisites
In addition to `python3`, `libusb-1.0`, `e2fsprogs`, and optional `img2simg`/`simg2img`, building images requires **Docker** (`docker`).
```sh
./rebuild-image.sh # or ./rebuild-image.sh --rebuild-all --force-bootstrap
./scripts/check-rebuild.sh # offline APK, ELF, DTB, image & Python unit checks
```
Outputs `images/boot-geminux.img`, `images/recovery-geminux.img`, `images/geminux-rootfs.img` (plus `.simg` if `img2simg` is installed), and `images/SHA256SUMS`.
### Package a redistributable release ZIP
Create a self-contained ZIP archive under `releases/` containing the images, `SHA256SUMS.txt`, plain-text `FLASH-INSTRUCTIONS.txt`, `flash-mtk.sh`, helper scripts, and `vendor/mtkclient/`:
```sh
./package-image.sh # or ./rebuild-image.sh --package
```
By default, [scripts/package-release-zip.py](scripts/package-release-zip.py) stages a copy of `geminux-rootfs.img`, strips SSH host/authorized keys and proprietary `/lib/firmware/mediatek/mt6797/` blobs so the archive can be shared safely, verifies `e2fsck -fn` and ZIP CRCs, and writes `<archive>.zip.sha256` (`--include-firmware` / `--keep-ssh-keys` keep them for single-device personal archives).
## Flashing to the Gemini PDA
> [!WARNING] > [!WARNING]
> Never wipe or overwrite MediaTek factory calibration, baseband, or bootloader partitions (`proinfo`, `nvram`, `nvdata`, `protect1`, `protect2`, `seccfg`, `lk`, `tee1`, `md1img`, `scp1`, `preloader`). > Never wipe or overwrite MediaTek factory calibration, baseband, or bootloader partitions (`proinfo`, `nvram`, `nvdata`, `protect1`, `protect2`, `seccfg`, `lk`, `tee1`, `md1img`, `scp1`, `preloader`).
Power off the Gemini PDA completely and leave it unplugged. Run the backup command, then plug the USB-C cable into the **left** USB-C port (closest to the Esc side) while powered off to enter MediaTek BROM/Preloader mode: Geminux claims user-writable eMMC past `LBA 0x70000` (`0x0E000000`), replacing Android `system`, `cache`, and `userdata` with `boot`, `recovery`, `boot2`, and a single full-disk `linux` ext4 partition.
- **Connecting BROM/Preloader mode**: Keep the Gemini powered off and unplugged, start the flash command on your host, then plug the USB-C cable into the **left** USB-C port (closest to `Esc`). [flash-mtk.sh](flash-mtk.sh) pauses host `ModemManager` temporarily so `/dev/ttyACM*` is not grabbed mid-handshake.
- **Turnkey firmware handling**: Clean release archives do not ship proprietary MediaTek blobs. During `--flash-full`, [flash-mtk.py](flash-mtk.py) automatically reads your device's stock Android `system` partition before repartitioning, saves Wi-Fi/BT/SPM blobs into `firmware-cache/mt6797/`, and injects them offline into the staged `linux` rootfs via `debugfs` (`--skip-firmware-inject` disables). If Android was already replaced earlier, extract blobs once from a stock `system.img` first:
```sh
./flash-mtk.sh --extract-firmware --system-img /path/to/system.img
```
### Flasher commands
```sh ```sh
# 1. Optional standalone backup -> backup/<timestamp>/ + pgpt.bin + sgpt.bin:
./flash-mtk.sh --only-backup ./flash-mtk.sh --only-backup
```
Backups are stored under `backup/<timestamp>/` alongside `pgpt.bin` and `sgpt.bin`. # 2. Full interactive install (prompts for user/root credentials & optional LUKS2):
Next, extract the device-owned proprietary MediaTek firmware blobs (`MT6797` Wi-Fi, Bluetooth, SPM, and MD1 radio images, never redistributed in git) either from the Gemini's existing Android `system` partition or from a local `system.img`:
```sh
# From a connected Gemini in BROM mode:
./flash-mtk.sh --extract-firmware
# Or from a local stock Android system image:
./flash-mtk.sh --extract-firmware --system-img /path/to/system.img
```
Extracted blobs go into `firmware-cache/mt6797/` and are injected into `/lib/firmware/mediatek/mt6797/` on build. Re-run `./rebuild-image.sh` so `geminux-rootfs.img` bundles them:
```sh
./rebuild-image.sh
```
## Step 3: Flash full eMMC with Geminux
Geminux claims all user-writable eMMC past the protected MediaTek boundary (`LBA 0x70000`, byte offset `0x0E000000`, `SYS0..SYS27`), replacing Android `system`, `cache`, and `userdata` with `boot`, `recovery`, `boot2`, and a single full-disk `linux` ext4 partition:
```sh
# Interactive: prompts for desktop username, desktop password, root password,
# and optional LUKS2 encryption before waiting for USB BROM/Preloader:
./flash-mtk.sh --flash-full ./flash-mtk.sh --flash-full
# Non-interactive with explicit username, prompted passwords, and LUKS2 encryption: # 3. Non-interactive example with explicit username, prompted passwords & LUKS2:
./flash-mtk.sh --flash-full --username alice --ask-user-password --ask-root-password --encrypt ./flash-mtk.sh --flash-full --username alice --ask-user-password --ask-root-password --encrypt
# Non-interactive using image defaults (unencrypted): # 4. Keep image defaults (unencrypted, login: user / geminux):
./flash-mtk.sh --flash-full --use-default-credentials ./flash-mtk.sh --flash-full --use-default-credentials
``` ```
### What `--flash-full` performs **What `--flash-full` runs**: Resolves credentials/LUKS2 passphrase upfront, backs up protected partitions into `backup/<timestamp>/` (reuse via `--skip-backup --backup-dir ...`), verifies protected GPT boundaries (`--force-gpt` overrides), writes & readback-checks updated Primary/Backup GPT, stages `geminux-rootfs.img` cleanly with firmware injection, `/etc/{passwd,group,shadow}` provisioning, and optional LUKS2 (`aes-xts-plain64`, Argon2id), writes & readback-verifies `boot`, `recovery`, and `boot2`, flashes `linux`, and reboots (`--no-reboot` / `--poweroff` overrides).
Implemented across [flash-mtk.py](flash-mtk.py), [scripts/geminux_accounts.py](scripts/geminux_accounts.py), [scripts/geminux_luks.py](scripts/geminux_luks.py), and [scripts/geminux_gpt.py](scripts/geminux_gpt.py): ### Partial updates and restore
1. **Pre-flash credential resolution**: Prompts/validates desktop `username`, desktop `password`, `root` `password`, and optional `--encrypt` LUKS2 passphrase before waiting for USB (`--username`, `--user-password`, `--ask-user-password`, `--root-password`, `--ask-root-password`, `--use-default-credentials`, `--encrypt`, `--luks-password`, `--ask-luks-password`). The LUKS2 passphrase is independent of login passwords.
2. **Safety backup**: Saves an initial backup in `backup/<timestamp>/` (pass `--skip-backup --backup-dir backup/<timestamp>` on subsequent flashes to reuse one).
3. **Protected layout verification**: Verifies protected partitions before `0x0E000000` (pass `--force-gpt` only when intentionally converting a non-standard table).
4. **GPT write + readback**: Writes updated Primary (`LBA 0..33`) and Backup GPT with mandatory readback check.
5. **Staged provisioning & write**: Copies `geminux-rootfs.img` to a temporary file (leaving `images/` untouched), provisions `/etc/passwd`, `/etc/group`, `/etc/shadow`, and `/home/<username>` via `debugfs`/`e2fsck`, optionally encrypts with LUKS2 (`aes-xts-plain64`, Argon2id), flashes `boot-geminux.img` (`boot` & `boot2`), `recovery-geminux.img` (`recovery`), and `linux` with readback verification, then sends the DA reboot handshake (`--reboot` default, `--poweroff`, or `--no-reboot`).
### Partial flash and offline utilities
```sh ```sh
# Update only boot, boot2, and recovery without touching GPT or linux:
./flash-mtk.sh --flash-kernel-only ./flash-mtk.sh --flash-kernel-only
# Update only the linux rootfs partition (with optional credentials and --encrypt):
./flash-mtk.sh --flash-rootfs-only --username alice --ask-user-password --encrypt ./flash-mtk.sh --flash-rootfs-only --username alice --ask-user-password --encrypt
./flash-mtk.sh --customize-rootfs /tmp/custom.img --username alice --encrypt
# Create an offline customized (and optionally LUKS2-encrypted) ext4 rootfs image:
./flash-mtk.sh --customize-rootfs /tmp/custom-rootfs.img --username alice --ask-user-password --ask-root-password --encrypt
# Restore a previous backup:
./flash-mtk.sh --restore-backup backup/<timestamp> ./flash-mtk.sh --restore-backup backup/<timestamp>
``` ```
## First boot and recovery notes ## First boot and recovery notes
- **eSIM persistence**: Profiles provisioned on the hardware ST33 eUICC survive full `linux` rootfs reflashes (whereas flashing `linux` replaces `/` and `/home`). - **eSIM persistence**: Profiles on the hardware ST33 eUICC survive `linux` reflashes (whereas flashing `linux` replaces `/` and `/home`).
- **Power on**: Unplug the USB-C cable and hold the **Esc** (power) button until the device boots. - **Power on & USB fuel gauge**: Unplug USB-C and hold **Esc** to boot. If booted on USB power, `bq25890` pauses charging (~15 s while `VSYS` stays USB-powered) so `mt6351-fuel-gauge` calibrates true open-circuit battery voltage.
- **USB-attached boot fuel-gauge calibration**: When booting directly on USB power (for instance right after `--flash-full`), `bq25890` briefly holds charging disabled (`F_CHG_CFG=0`, ~15 s while `VSYS` stays powered via USB) so `mt6351-fuel-gauge` calibrates to true zero-current battery OCV rather than ~4.336 V charging voltage. - **LUKS2 unlock & ext4 expand**: Encrypted installs prompt on `tty1` using `/etc/gemini-us.kmap` and unlock the full dynamic `linux` partition (`--allow-discards`). First boot automatically runs `e2fsck -p` and `resize2fs -f` (~58 GiB) and creates `/var/lib/geminux/.rootfs-resized`. For LUKS2 cipher/kernel details, see [ARCHITECTURE.md](ARCHITECTURE.md).
- **LUKS2 unlock**: When flashed with `--encrypt`, initramfs loads `/etc/gemini-us.kmap` on `tty1` and prompts for the LUKS2 passphrase (`cryptsetup open --allow-discards` -> `/dev/mapper/geminux_root`, mapping the full dynamic partition after any off-mode charging check). - **Desktop defaults**: Auto-logs into XLibre + DWM as UID `10000` (provisioned username or `user`, default password `geminux`, default **Anodized** theme, and default `geminux-dark.png` wallpaper).
- **First-boot resize**: Initramfs runs `e2fsck -p </dev/null` and `resize2fs -f </dev/null` to expand ext4 across the ~58 GiB `linux` partition, records `/var/lib/geminux/.rootfs-resized`, and pivots to OpenRC. - **USB NCM rescue**: Connecting USB-C brings up `usb0` (`172.16.42.1/24`); recovery initramfs provides LUKS2-aware `unlock-root`, `check-fs`, and `mount-root`.
- **Desktop login & default theme**: TinyDM auto-logs into XLibre + DWM as UID `10000` (your provisioned username or `user`, default password `geminux` unless set; authorized key from `keys/geminux_id_ed25519.pub` if generated). The desktop opens in the default **Anodized** theme; customize themes with `Mod4 + t` (`geminux-themes`) and desktop wallpapers via `geminux-themes --wallpaper` or `geminux-apply-wallpaper`.
- **Rescue shell**: Plugging USB-C into a host starts USB NCM Ethernet (`usb0`) at `172.16.42.1/24`. In recovery mode, `unlock-root`, `check-fs`, and `mount-root` handle LUKS2 unlock automatically.
## Full-disk encryption (LUKS2) details
- **Kernel & Hardware**: Built-in `BLK_DEV_DM=y`, `DM_CRYPT=y`, `CRYPTO_ESSIV=y`, ARMv8 AES-CE (`CRYPTO_AES_ARM64_CE_BLK=y`, `CRYPTO_XTS=y`, `CRYPTO_SHA256=y`), `DRM_SIMPLEDRM=y` + rotated `TER16x32` console, and `KEYBOARD_MATRIX=y` + `PINCTRL_AW9523=y`.
- **Format & Expansion**: Host `cryptsetup reencrypt --encrypt --disable-locks` wraps the staged rootfs with a 32 MiB LUKS2 header pad (`16 MiB` payload offset, whole-device segment, `aes-xts-plain64` 512-bit, Argon2id 128 MiB / 4 threads) so no plaintext rootfs touches eMMC; unlocking maps the whole device and first boot expands ext4 to ~58 GiB.
- **Security Scope**: Protects data at rest against theft or physical eMMC extraction. Because stock MediaTek `lk` does not enforce AVB verified boot on `boot`/`recovery`/`boot2`, FDE does not protect against offline tampering of the `boot` partition.
## Live Gemini PDA x27 hardware validation checklist ## Live Gemini PDA x27 hardware validation checklist
Perform these checks on physical hardware after first boot: - [ ] `uname -r` shows `7.3.5-geminux`; `lsmod` shows `mediatek_drm`, `panfrost`, `mt6797_ccci_cldma`, `mt6797_wlan_core`, and `btmt6797`.
- [ ] `ssd2092` touchscreen, `geminux-touchd` gestures, and XKB keys (`Fn+1..0`, `Fn+Z/X`, `Fn+Alt = Mod4`, Planet key) work; `glxinfo | grep -i renderer` reports Panfrost.
- [ ] Confirm `uname -r` reports `7.3.5-geminux` and `lsmod` shows `mediatek_drm`, `panfrost`, `mt6797_ccci_cldma`, `mt6797_wlan_core`, and `btmt6797`. - [ ] **Anodized** default theme, `geminux-dark.png` default wallpaper, interactive theme editor, and `geminux-apply-wallpaper` restore cleanly.
- [ ] Verify `ssd2092` touchscreen input, `geminux-touchd` gestures (2-finger tap/scroll, 3-finger middle-click), and keyboard mappings (`Fn+1..0 = F1..F10`, `Fn+Z/X = F11/F12`, `Fn+Alt = Mod4`, Planet key). - [ ] Wi-Fi (`geminux-net`), Bluetooth, and PipeWire audio (speaker, 3.5 mm jack, internal mic) function normally.
- [ ] Confirm Glamor 3D acceleration via `glxinfo | grep -i renderer`. - [ ] With MD1 firmware present, `/dev/ccci_md_ctl`, `/dev/ttyC0`, `doas geminux-cellctl status` (`MD_STATE=READY` + SIM/ST33 eUICC), `geminux-imsd`, `ccmni*` data, voice calls (`geminux-dialer`), and SMS (`geminux-sms`) work.
- [ ] Verify **Anodized** default theme, interactive theme switching & Theme Editor (`geminux-themes`), and desktop wallpaper apply/restore (`geminux-themes --wallpaper` / `geminux-apply-wallpaper`). - [ ] Front camera capture (`geminux-camera`), external `SiI9024` HDMI, `/media/sdcard` automount, `Fn+F` Airplane Mode, lid-close & overnight battery deep sleep recovery (`0013`), and `geminux-power-audit` succeed.
- [ ] Test Wi-Fi and Bluetooth via `geminux-net` / `nmcli`, plus audio playback/recording (speaker, 3.5mm jack, internal mic).
- [ ] With MD1 firmware extracted, verify `/dev/ccci_md_ctl`, `/dev/ttyC0`, `doas geminux-cellctl status` (`MD_STATE=READY` + SIM/ST33 eUICC), `rc-service geminux-imsd status`, `ccmni*` data, voice calls (`geminux-dialer`), and SMS (`geminux-sms`).
- [ ] Test front camera preview/JPEG/AVI capture (`geminux-camera`), external HDMI (`SiI9024`), microSD automount at `/media/sdcard` (`geminux-sdcard-mount status`), `Fn+F` Airplane Mode, lid-close & overnight battery deep sleep recovery (`0013` PMIC/SPM safety and quiet open-lid timer re-suspend), and `geminux-power-audit`.
+67 -153
View File
@@ -1,210 +1,124 @@
# User manual # User manual
This manual covers keyboard bindings, DWM controls, touch gestures, themes, desktop wallpapers, built-in applications, and Alpine Edge package maintenance on Geminux. Daily usage reference for the Geminux desktop on the Planet Computers Gemini PDA (x27): keyboard layout, DWM window management, gestures, themes, wallpapers, applications, and safe Alpine Edge package updates.
## Gemini PDA US keyboard and XKB layout ## Keyboard and XKB layout
Geminux installs a custom XKB layout (`planet_vndr/geminux`, variant `us`) alongside a matching Linux console keymap (`etc/keymap/gemini-us.map`): Geminux installs custom XKB (`planet_vndr/geminux`, `us`) and Linux console (`etc/keymap/gemini-us.map`) keymaps:
| Key combination | Mapping / Action | | Key combination | Mapping / Action |
| --- | --- | | --- | --- |
| `Fn + 1` .. `Fn + 0` | `F1` .. `F10` | | `Fn + 1` .. `Fn + 0` | `F1` .. `F10` |
| `Fn + Z` / `Fn + X` | `F11` / `F12` (`Shift + Fn + Z/X` produces `«` / `»`) | | `Fn + Z` / `Fn + X` | `F11` / `F12` (`Shift + Fn + Z/X`: `«` / `»`) |
| `Fn + Alt` | `Super_L` (`Mod4`, primary DWM modifier) | | `Fn + Alt` | `Super_L` (`Mod4`, main window-manager modifier) |
| `Fn + F` (`XF86UWB` / `XF86RFKill`) | Toggle hardware Airplane Mode (`geminux-media-key airplane`), displaying a Dunst OSD toast and `AIRPLANE` in the DWM bar | | **Planet key** | `Mod4` / `geminux-launcher` trigger (supports single-handed one-shot `Mod4` tap-latch in DWM) |
| **Planet key** | `Mod4` / launcher trigger (also acts as a clean one-shot `Mod4` tap-latch in DWM for single-handed operation) | | `Fn + F` | Toggle hardware Airplane Mode (`geminux-media-key airplane`) + Dunst OSD + `AIRPLANE` status tag |
| **Media & special keys** | Backlight (`XF86MonBrightnessUp`/`Down`), volume & mic mute (`wpctl`), playback (`XF86AudioPlay`/`Pause`/`Prev`/`Next`/`Stop` -> `mpv` IPC `/tmp/geminux-mpv.sock`), `XF86WLAN` (`geminux-net`), `XF86Tools` (`geminux-control`), `XF86Option` (`geminux-audio`), and `XF86Sleep` (suspend), with immediate `geminux-statusd` `SIGUSR1` bar refresh | | **Media & HW keys** | Brightness (`XF86MonBrightness*`), `wpctl` volume/mic mute, `mpv` IPC playback (`/tmp/geminux-mpv.sock`), `XF86WLAN` (`geminux-net`), `XF86Tools` (`geminux-control`), `XF86Option` (`geminux-audio`), `XF86Sleep` (suspend) |
| `Print` / `Shift+Print` / `Ctrl+Print` | Capture full screen (`screenshot`) or active window (`screenshot-window`) | | `Print` / `Shift+Print` / `Ctrl+Print` | Capture full screen or active window screenshot |
## DWM window manager shortcuts ## DWM window manager shortcuts
Defined in [src/dwm/config.def.h](src/dwm/config.def.h), where `MODKEY` is `Mod4` (`Fn + Alt`): Defined in [src/dwm/config.def.h](src/dwm/config.def.h) (`MODKEY = Mod4`, i.e., `Fn + Alt`):
| Shortcut | Action | | Shortcut | Action |
| --- | --- | | --- | --- |
| `Mod4 + Return` | Open `st` terminal (with Fira Code HarfBuzz ligatures) | | `Mod4 + Return` / `Mod4 + Shift + Return` | Open `st` terminal / promote window to master (`zoom`) |
| `Mod4 + Shift + Return` | Promote focused window to master (`zoom`) | | `Mod4 + Space` / `Mod4 + p` | Open `geminux-launcher` (`dmenu` with pinned GUI apps, `Wallpaper`, `Webarchy`, `Bantam`, `Lynx`) |
| `Mod4 + Space` / `Mod4 + p` | Open `geminux-launcher` (`dmenu` with Nerd Font icons, pinned apps, `Wallpaper`, `Webarchy Browser`, `Bantam AI agent`, and `Lynx Web Browser` in `st`) | | `Mod4 + c` / `a` / `n` / `t` | Open `geminux-control` / `geminux-audio` / `geminux-net` / `geminux-themes` |
| `Mod4 + c` | Open `geminux-control` (backlight, volume, power profiles, LEDs, suspend) | | `Mod4 + d` / `s` / `v` | Open `geminux-dialer` / `geminux-sms` / `geminux-camera` |
| `Mod4 + a` | Open `geminux-audio` | | `Mod4 + Shift + l` / `Mod4 + Shift + r` | Lock screen (`geminux-lock`) / reload `~/.Xresources` & theme live |
| `Mod4 + d` | Open `geminux-dialer` | | `Mod4 + b` / `Mod4 + Shift + Space` | Toggle top bar / toggle floating mode |
| `Mod4 + s` | Open `geminux-sms` | | `Mod4 + j` / `k` (or `Down` / `Up`) | Focus next / previous window |
| `Mod4 + n` | Open `geminux-net` | | `Mod4 + h` / `l` (`Mod4 + i` / `o`) | Adjust master split ratio (increment/decrement master count) |
| `Mod4 + v` | Open `geminux-camera` | | `Mod4 + F1` .. `F4` (`m`, `g`) | Switch layout: `Tile`, `Monocle`, `Floating`, `Grid` |
| `Mod4 + t` | Open `geminux-themes` (`Themes & Editor` / `Wallpaper`) | | `Mod4 + 1..5` (`Shift + 1..5`) | View workspace tag (move window to tag) |
| `Mod4 + Shift + l` | Lock screen (`geminux-lock`) | | `Mod4 + Shift + c` / `q` (`Ctrl+Shift+q`) | Close focused window (quit DWM) |
| `Mod4 + Shift + r` | Reload `~/.Xresources` and active desktop theme live |
| `Mod4 + b` | Toggle top DWM bar |
| `Mod4 + Shift + Space` | Toggle floating mode on focused window |
| `Mod4 + j` / `k` (or `Down` / `Up`) | Focus next / previous window in stack |
| `Mod4 + h` / `l` | Adjust master split ratio (`Mod4 + i` / `o` adjusts master count) |
| `Mod4 + F1` .. `F4` | Switch layout: `Tile`, `Monocle`, `Floating`, `Grid` (`Mod4 + m` Monocle, `Mod4 + g` Grid) |
| `Mod4 + 1` .. `5` | Switch workspace tags (`Mod4 + Shift + 1..5` moves focused window to tag) |
| `Mod4 + Shift + c` / `Mod4 + Shift + q` | Close focused window (`Mod4 + Ctrl + Shift + q` quits DWM) |
Touchscreen input works directly across XLibre (`libinput`), DWM tag/layout/close buttons (top bar height `>= 78 px`), full-height `dmenu` menus (`82 px` touch rows), `st`, and all 11 `libgemui` apps (configured at `192 DPI` / `2x` scaling, `Xcursor.size: 64`). Touch input works natively across XLibre (`libinput`), DWM bar controls (`>= 78 px`), `dmenu` touch rows (`82 px`), `st`, and all 11 HiDPI (`192 DPI` / `2x`, `Xcursor.size: 64`) applications.
### Touchscreen multi-touch gestures ### Multi-touch gestures (`geminux-touchd`)
`geminux-touchd` intercepts raw XInput 2.2 touch events on the root window to provide right-click, middle-click, and two-finger scrolling without interfering with normal 1-finger taps or drags:
| Gesture | X11 action | Notes | | Gesture | X11 action | Notes |
| --- | --- | --- | | --- | --- | --- |
| 1-finger tap or drag | Left-click (`Button1`) / drag | Native passthrough for taps, text selection, sliders, and `Mod4 + drag` window move | | 1-finger tap / drag | Left-click (`Button1`) / drag | Standard tap, text selection, sliders, `Mod4 + drag` move |
| 2-finger tap | Right-click (`Button3`) | Context menus without moving the cursor first | | 2-finger tap / 1-finger hold (`0.5 s`) | Right-click (`Button3`) | Context menus without moving cursor first |
| 1-finger stationary hold (`0.5 s`) | Right-click (`Button3`) | Single-handed right-click alternative | | 3-finger tap | Middle-click (`Button2`) | Paste X11 primary selection in `st` or open tabs/links |
| 3-finger tap | Middle-click (`Button2`) | Pastes X11 primary selection in `st` and opens links/tabs in browsers | | 2-finger drag | Scroll (`Button4`–`Button7`) | Vertical & horizontal natural scroll (`GEMINUX_NATURAL_SCROLL=0` reverses) |
| 2-finger drag | Scroll wheel (`Button4`–`Button7`) | Natural vertical and horizontal scroll across X11 apps and `st` scrollback (`GEMINUX_NATURAL_SCROLL=0` restores classic scroll direction) |
## Unified theming, Theme Editor, and `.xth` importer ## Unified themes, Theme Editor, and `.xth` importer
Geminux ships **22** unified `.xth` color themes under `~/.xthemes/` (copied from `/etc/skel/.xthemes/`, with new system `.xth` files merged non-destructively at login by `geminux-session`). The default desktop theme is **Anodized** (obsidian `#08090b`, brushed silver `#cfd6e0`, brass-amber `#e2bc72` highlight). Geminux includes **22** built-in `.xth` themes in `~/.xthemes/` (new `/etc/skel/.xthemes/*.xth` files sync non-destructively at login), defaulting to **Anodized** (obsidian `#08090b`, brushed silver `#cfd6e0`, brass-amber `#e2bc72`). Custom and imported themes live under `~/.config/geminux/themes/` and override built-in names.
User-created, edited, and imported themes are stored in `~/.config/geminux/themes/` and take priority over built-in themes with the same name. - **Interactive GUI** (`Mod4 + t` -> `Themes & Editor` tab): Browse/apply palettes; use **Edit**, **Duplicate**, **New**, and **Reset**/**Delete** across four tabs (`General & Fonts`, `UI Colors`, `WM & Menu`, `Terminal`) with RGB sliders, `#RRGGBB` paste, live preview, and WCAG contrast readouts; or **Import .xth** files directly.
- **CLI usage**:
### Interactive Theme Editor & Importer ```sh
geminux-apply-theme # list themes
Open **Themes** via `Mod4 + t` or `geminux-launcher` (`Geminux Themes & Wallpaper` -> `Themes & Editor` tab): geminux-apply-theme TokyoNight # switch theme live
geminux-apply-theme --install ~/MyTheme.xth [Name] # install & apply .xth
- **Browse & Apply**: Preview built-in and user themes live and apply across the desktop. geminux-themes --install ~/MyTheme.xth [Name] # install via geminux-themes
- **Create & Edit**: Use **Edit**, **Duplicate**, **New**, and **Reset** / **Delete** across four property tabs (**General & Fonts**, **UI Colors**, **WM & Menu**, **Terminal**) with RGB sliders, `#RRGGBB` hex inputs, clipboard paste, a live preview panel, and automatic WCAG contrast ratio checks against `bgMain`. ```
- **Import `.xth`**: Use **Import .xth** to browse `.xth` files, preview their palette, and install them into `~/.config/geminux/themes/` (auto-sync toggle applies changes immediately). - **Synced targets**: Updates `~/.Xresources` (`xrdb -nocpp -load`), Dunst (`~/.config/dunst/dunstrc`), GTK2/GTK3/GTK4/`libadwaita`, `xsettingsd`, Qt5/Qt6 (`qt6ct` & Kvantum), Tk/Ttk (`gtkTtk`), live X11 apps (`dwm`, `st`, `webarchy`, `libgemui`), and wallpaper matte colors when `USE_THEME_BG=1`.
### Theme CLI commands
```sh
geminux-apply-theme # list available themes
geminux-apply-theme TokyoNight # switch active theme
geminux-apply-theme --install ~/MyTheme.xth [Name] # import & apply custom .xth
geminux-themes --install ~/MyTheme.xth [Name] # equivalent CLI via geminux-themes
```
### Synchronized toolkits
Switching or applying a theme updates every layer consistently:
| Layer / Toolkit | Update mechanism |
| --- | --- |
| **X11 resources & clients** | Copies `.xth` to `~/.Xresources` and replaces X11 resources cleanly via `xrdb -nocpp -load`; live `dwm`, `st`, `webarchy`, and `libgemui` clients redraw immediately via `XA_RESOURCE_MANAGER` / `SIGUSR1` |
| **Dunst OSD** | Translates `theme.*` keys into `~/.config/dunst/dunstrc` via `geminux-sync-dunst-theme` and restarts `dunst` |
| **GTK2 / GTK3 / `xsettingsd`** | `geminux-sync-gtk-theme` builds light- or dark-adapted `Geminux-<Theme>` assets under `~/.themes/` / `~/.local/share/themes/`, updates `~/.gtkrc-2.0`, `~/.config/gtk-3.0/{settings.ini,gtk.css}`, and `~/.config/xsettingsd/xsettingsd.conf`, and sends `SIGHUP` to `xsettingsd` |
| **GTK4 & `libadwaita`** | Updates `~/.config/gtk-4.0/{settings.ini,gtk.css}` (`@define-color` and `:root` tokens) plus `dconf`-backed `gsettings` `color-scheme`, bound via `ADW_DISABLE_PORTAL=1` |
| **Qt5 & Qt6** | Writes `~/.config/qt6ct/{qt6ct.conf,colors/Geminux-<Theme>.conf}` (21-role `QPalette`, `QT_QPA_PLATFORMTHEME=qt6ct:gtk3`) and Kvantum config (`~/.config/Kvantum/Geminux/Geminux.kvconfig` for `QT_STYLE_OVERRIDE=kvantum`) |
| **Tcl/Tk (`gtkTtk 0.9`)** | Sets `*TkTheme: gtkTtk` and DPI-scaled GTK2 metrics (`192 DPI` / `2x`); `gtkTtk` reloads automatically on `XA_RESOURCE_MANAGER` updates |
| **Wallpaper matte** | When `USE_THEME_BG=1` is enabled in `~/.config/geminux/wallpaper.conf`, `geminux-apply-theme` re-renders the active wallpaper against the new theme background |
## Desktop wallpaper management ## Desktop wallpaper management
Open the **Wallpaper** tab directly via `geminux-themes --wallpaper`, the **Wallpaper** entry in `geminux-launcher`, or press `Tab` inside `geminux-themes` to switch between **Themes & Editor** and **Wallpaper**. Open the **Wallpaper** view via `geminux-themes --wallpaper`, **Wallpaper** in `geminux-launcher`, or pressing `Tab` inside `geminux-themes`.
### GUI modes and controls - **Bundled artwork & quick folders**: Ships `geminux-dark.png` (first-boot default) and `geminux-light.png` under `/usr/share/geminux/wallpapers/`. Use quick buttons (**Stock**, **Home**, **Pictures**, **SD Card** `/media/sdcard`, **/**, plus **All** file filter) or type/paste paths.
- **Modes & Solid colors**: Supports **Fill**, **Fit**, **Center**, **Tile**, **Stretch**, and **Span** with theme-matched or custom `#RRGGBB` matte colors, plus pure **Solid Color** mode with RGB sliders and theme/dark swatches.
Geminux bundles `geminux-dark.png` (configured as the default wallpaper on first boot) and `geminux-light.png` under `/usr/share/geminux/wallpapers/`. - **Persistence & CLI**: Saves to `~/.config/geminux/wallpaper.conf` (seeded cleanly on first session launch) and auto-restores across login (`geminux-session`), theme switches (`USE_THEME_BG=1`), and external HDMI layout changes (`geminux-net`):
```sh
- **Image Wallpaper**: Browse quickly via **Stock** (`/usr/share/geminux/wallpapers`), **Home**, **Pictures**, **SD Card** (`/media/sdcard`), or **/** (`All` toggle reveals non-image files), type or paste paths (or pass short names like `geminux-apply-wallpaper geminux-light`), preview layout with a simulated DWM top bar, choose among six scaling modes (**Fill**, **Fit**, **Center**, **Tile**, **Stretch**, **Span**), and set a matte color matching the active theme or a custom `#RRGGBB`. geminux-apply-wallpaper --restore
- **Solid Color**: Pick **Match Active Theme Background**, dial custom RGB sliders, paste hex codes, or choose quick theme and dark swatches. geminux-apply-wallpaper geminux-light --mode fill --bg theme
geminux-apply-wallpaper ~/Pictures/photo.jpg --mode fit --no-save
### CLI & automatic restore geminux-apply-wallpaper --solid '#101318'
geminux-apply-wallpaper --theme-bg
Settings persist in `~/.config/geminux/wallpaper.conf` and automatically re-apply at session startup (`geminux-session`), on theme changes when `USE_THEME_BG=1` (`geminux-apply-theme`), and after external HDMI `xrandr` layout changes (`geminux-net`). ```
```sh
geminux-apply-wallpaper --restore
geminux-apply-wallpaper ~/Pictures/photo.jpg --mode fill --bg theme
geminux-apply-wallpaper --solid '#101318'
geminux-apply-wallpaper --theme-bg
```
Pass `--no-save` to preview or set a wallpaper temporarily without modifying `~/.config/geminux/wallpaper.conf`.
## Applications and daemons ## Applications and daemons
### Webarchy Browser (`webarchy` / `xwebarchy`) ### Webarchy Browser (`webarchy` / `xwebarchy`)
Ultrawide `2160x1080` `GTK3` + `WebKit2GTK` browser built for landscape PDA use: Ultrawide `2160x1080` `GTK3` + `WebKit2GTK` browser with collapsible right vertical tabs (`Ctrl+B` / `Alt+T`), omnibar search, SQLite cookies/bookmarks (`~/.config/geminux/webarchy/`, `~/.local/share/geminux/webarchy/`), Dark Mode inverter (`Ctrl+Shift+D`), Reader Width Fit, `SIGUSR1` live theming, and automatic software fallback on crash (`--software`).
- **Interface**: Collapsible right-side vertical tab bar (`Tabs` button or `Ctrl+B` / `Alt+T`), unified omnibar (URL + DuckDuckGo search), persistent SQLite cookies and bookmarks (`~/.config/geminux/webarchy/`, `~/.local/share/geminux/webarchy/`), User-Agent presets, Dark Mode inverter (`Ctrl+Shift+D`), Reader Width Fit, Find in Page (`Ctrl+F`), and single-instance CLI URL forwarding. **Shortcuts**: `Ctrl+T` new tab, `Ctrl+W` close, `Ctrl+Shift+T` reopen, `Ctrl+Tab` / `Alt+Up`/`Down` / `Alt+1..9` switch tab, `Ctrl+L` / `F6` URL bar, `Alt+Left`/`Right` back/forward, `Ctrl+F` find, `Ctrl+D` bookmark, `Ctrl++`/`-`/`0` zoom, `F11` fullscreen.
- **Resilience & theming**: Live `.Xresources` reloading via `SIGUSR1` and automatic software rendering fallback on WebProcess crash (`--software` or `~/.config/geminux/webarchy/software_renderer`).
- **Shortcuts**: `Ctrl+T` new tab, `Ctrl+W` close tab, `Ctrl+Shift+T` reopen closed tab, `Ctrl+Tab` / `Alt+Up`/`Down` / `Alt+1..9` switch tabs, `Ctrl+L` / `F6` focus URL bar, `Alt+Left` / `Alt+Right` history back/forward, `Ctrl+D` bookmark, `Ctrl++` / `-` / `0` zoom, `F11` fullscreen.
### Telephony, eSIM & IMS ### Telephony, eSIM & IMS
`geminux-dialer`, `geminux-callscreen`, `geminux-sms`, and `geminux-contacts` sit on top of `geminux-modem-ctl`, `geminux-ccci-daemon`, `geminux-cellctl`, and `geminux-imsd` (using ALSA UCM2 `VoiceCall`/`HiFi` switching and call suspend inhibitors). `geminux-imsd` supports 3GPP VoLTE over `ccmni*`, VoWiFi (`SWu` via `strongswan`), and SMS-over-IMS with automatic CS fallback. `geminux-dialer`, `geminux-callscreen`, `geminux-sms`, and `geminux-contacts` work with `geminux-modem-ctl`, `geminux-ccci-daemon`, `geminux-cellctl`, and `geminux-imsd` (3GPP VoLTE over `ccmni*`, VoWiFi `SWu`, SMS-over-IMS with CS fallback, ALSA `VoiceCall` switching, call suspend inhibitors).
Manage SIM slots, cellular data, and ST33 eUICC profiles from `geminux-net` or CLI:
```sh ```sh
doas geminux-cellctl status doas geminux-cellctl status
doas geminux-cellctl sim-slot <esim|physical> doas geminux-cellctl sim-slot <esim|physical>
doas geminux-cellctl apn-set <apn> doas geminux-cellctl apn-set <apn> && doas geminux-cellctl data-up [apn]
doas geminux-cellctl ims-set <on|off> doas geminux-cellctl ims-set <on|off>
doas geminux-cellctl data-up [apn]
doas geminux-cellctl data-down
# ST33 eUICC (lpac) management # ST33 eUICC (lpac)
doas geminux-cellctl esim-info doas geminux-cellctl esim-info | esim-list
doas geminux-cellctl esim-list
doas geminux-cellctl esim-download 'LPA:1$smdp$matchingId' [confirm-code] doas geminux-cellctl esim-download 'LPA:1$smdp$matchingId' [confirm-code]
doas geminux-cellctl esim-enable <#idx|iccid> doas geminux-cellctl esim-enable <#idx|iccid> # or esim-disable / esim-delete / esim-notif-process
doas geminux-cellctl esim-disable <#idx|iccid>
doas geminux-cellctl esim-delete <#idx|iccid>
doas geminux-cellctl esim-notif-process
``` ```
### Connectivity, DNS & Airplane Mode ### Connectivity, Airplane Mode, Media & System Apps
`geminux-net` unifies: - **`geminux-net`**: Wi-Fi (`nmcli`, active WLAN pinned top + Disconnect), Cellular/eSIM, Bluetooth (`bluetoothctl`/`rfkill`), `SiI9024` HDMI (`xrandr`), and **DNS** tab (`geminux-dnsctl`: router/Cloudflare/Google/RadicalDNS/Quad9/custom + lookup test).
- **Hardware Airplane Mode**: `Fn + F`, `geminux-control`, `geminux-net`, or `doas geminux-power-ctl airplane on|off|toggle|status` unloads CONSYS Wi-Fi/BT modules and sets MD1 to `AT+CFUN=4` across reboots while leaving `usb0` up.
- **Wi-Fi**: Managed via `nmcli` with the active WLAN pinned first alongside a **Disconnect** control. - **`geminux-audio`, `geminux-datetime`, `geminux-camera`**: PipeWire routing/volumes (`wpctl`), Chrony NTP + timezone (`geminux-tzctl`), and V4L2 10-bit Bayer ISP camera saving JPEG stills (`~/Pictures/`) and MJPEG-AVI (`~/Videos/`).
- **Cellular & eSIM**: Live MD1/CCCI, ModemManager, and ST33 eSIM controls (`geminux-cellctl` + `/run/geminux/ccci.sock`). - **`geminux-control`, `geminux-leds`, `geminux-lock`**: Brightness, volume, CPU profiles (`eco`, `balanced`, `performance`), AW9120 RGB LEDs (`/run/geminux/leds.sock`, off idle/full, amber charging LED, manual presets), and `doas` lockscreen.
- **Bluetooth & HDMI**: `bluetoothctl`/`rfkill` toggles and `SiI9024` external HDMI layout extend/mirror (`xrandr`, automatically restoring wallpaper geometry on change).
- **DNS tab**: Powered by `geminux-dnsctl` with Router Default, Cloudflare, Google, RadicalDNS, Quad9, custom IPv4/IPv6 nameservers, and live resolution checks.
- **Hardware Airplane Mode**: Toggled via `Fn + F`, `geminux-control`, `geminux-net`, or `doas geminux-power-ctl airplane on|off|toggle|status`. Persists across reboots by unloading CONSYS Wi-Fi/BT kernel modules and placing MD1 into `AT+CFUN=4` flight mode while keeping USB NCM (`usb0`) active.
### Audio, Date/Time & Camera
- **`geminux-audio`**: Manages PipeWire sink/source routing, mute state, and per-stream volumes via `wpctl`/`pactl`.
- **`geminux-datetime`**: Configures the system timezone (`geminux-tzctl`) and monitors Chrony NTP synchronization.
- **`geminux-camera`**: Drives the MT6797 Media Controller pipeline (`ov5670`/`s5k4e6` -> `seninf` -> `camsv`), captures 10-bit Bayer (`SBGGR10`/`SGRBG10`) frames over V4L2 `mmap` with a pure-C demosaic + AWB software ISP, and saves `libjpeg-turbo` stills to `~/Pictures/` and MJPEG-AVI videos to `~/Videos/`.
### System Control, LEDs, Lock & Power
- **`geminux-control`**: Adjusts display brightness, PipeWire volume, MT6797X power profile (`eco`, `balanced`, `performance`), hardware Airplane Mode, and back LED presets.
- **`geminux-leds`**: Controls the AW9120 RGB bar (`rgb:indicator-1..5` off by default when idle/full; `rgb:indicator-6` amber while charging) over `/run/geminux/leds.sock`, with presets (`rgb 160 16 0` "Amber Warn") and persistent manual overrides across battery uevents.
- **`geminux-lock`**: Locks X11 cleanly via `doas -n /usr/sbin/geminux-checkpw`, dynamically resolving the desktop user from UID `10000` (`--username` supported).
- **`geminux-powerd`**: Runs input-driven screensaver and lid policy (`epoll` zero-poll):
- On **USB/AC** (`inhibit_ac_lid`), closing the lid or idling locks X11 and blanks the backlight without unloading CONSYS or invoking `/sys/power/state`.
- On **battery**, closing the lid or reaching idle suspend enters `mem` sleep when MD1 is gated, or zero-thrash `low_power_standby` when MD1 is powered (never `freeze`/`s2idle`).
- Wakes only on `closed -> open` lid transitions, real input (`keyboard`/`touch`/`pointer`/`mtk-pmic-keys` Esc), or USB/AC attach; internal timer wakes during open-lid idle lock re-suspend quietly without reloading CONSYS or turning on the backlight.
### microSD Card Automount (`/media/sdcard`) ### microSD Card Automount (`/media/sdcard`)
`geminux-sdcard` (OpenRC) and `eudev` (`95-geminux-sdcard.rules` -> `/usr/sbin/geminux-sdcard-mount`) automatically check (`fsck.fat -a`, `fsck.exfat -p`, `e2fsck -p`) and mount `/dev/mmcblk1p1` or unpartitioned `/dev/mmcblk1` at `/media/sdcard`, unmounting cleanly on removal or shutdown. Desktop users (`UID 10000`, `plugdev` `GID 106`) get full read/write permissions across `vfat`, `exfat`, and `ext4`/`ext3`/`ext2`. `geminux-sdcard` (OpenRC) and `eudev` auto-check and mount `/dev/mmcblk1p1` (or unpartitioned `/dev/mmcblk1`) on boot/hotplug with full desktop read/write permissions (`UID 10000`, `plugdev` `GID 106`) for `vfat`, `exfat`, and `ext4`/`ext3`/`ext2`, unmounting cleanly on removal. Manage manually via `geminux-sdcard-mount status|remove|add` and `dosfstools` (`mkfs.vfat`, `fsck.vfat`, `fatlabel`).
```sh ### CLI tools
geminux-sdcard-mount status # inspect mount and card filesystem state
geminux-sdcard-mount remove # flush and unmount before physical eject
geminux-sdcard-mount add # manually mount (auto-escalates via doas)
```
`dosfstools` (`mkfs.vfat`, `fsck.vfat`, `fatlabel`) is included in default `PATH` for FAT card maintenance. Preinstalled: native `mpv` (`/etc/mpv/mpv.conf` + `/tmp/geminux-mpv.sock` IPC), `ffmpeg`/`ffprobe`, `gst-libav`, `mpg123`, `openmpt123`, `yt-dlp` (`quickjs`), `python3`/`pip3`, `tcl`/`tk` (`gtkTtk`), `gnupg` (`pinentry-curses`), `pass`, `bantam` (`kilo-auto/free` default; see [src/bantam/README.md](src/bantam/README.md)), `lynx` (`~/.lynx.cfg` -> `frogfind.com`), `gsocket`, `dtach`, `ovault`, `htop`, `.gitconfig`, and `/etc/skel/.apexrc` shell helpers (`nn`, `pg`, `l`, `rw`, `ee`, `pkgadd`/`sysup`, etc.).
### CLI Developer, Media & Security Tools
- **Media**: Native Alpine Edge `mpv` (`/etc/mpv/mpv.conf`: Panfrost X11 EGL, PipeWire, `/tmp/geminux-mpv.sock` media-key IPC), `ffmpeg`/`ffprobe`, `gst-libav`, `mpg123`, `openmpt123`, and `yt-dlp` (`yt-dlp-ejs-rt-quickjs`).
- **Languages & Toolkits**: `python3` & `pip3` (`py3-pip`), `tcl` (`tclsh`, `tcl-lib`, `tcl-tls`), and `tk` (`wish` themed live via `gtkTtk 0.9`).
- **AI, Web & Remote**: `bantam` (`geminux-bantam` C++20 CLI AI agent defaulting to `kilo-auto/free`; see [src/bantam/README.md](src/bantam/README.md)), `lynx` (`~/.lynx.cfg` with `http://frogfind.com` start page, UTF-8, vi keys, mouse, persistent cookies), `gsocket` (`gs-netcat`, `gs-key`, `gs-enter`, `gs-deploy-cmd`), `dtach` (`dmux`), and `ovault`.
- **Security & Shell UX**: `gpg` (`gnupg` + `pinentry-curses` + `GPG_TTY`), `pass`, default `htop` layout (`/etc/htoprc`), `/etc/skel/.gitconfig`, and `/etc/skel/.apexrc` helpers (`EDITOR='nano -FEDSMAGic/max%_T2'`, `PAGER='less -RXF'`, `nn`, `pg`, `l`, `defalias`/`toalias`/`savealias`, `rw`/`ee`, `sshed`, `dl`, `gcm`/`gp`/`gpm`, `sloc`, and `doas`-aware `pkgadd`/`pkgdel`/`pkgsearch`/`sysup`/`sysclean`).
## Maintaining Alpine Edge packages safely ## Maintaining Alpine Edge packages safely
`/etc/apk/repositories` points directly to Alpine Edge (`main`, `community`, `testing`) alongside the local signed `@geminux` repository (`/var/lib/geminux/apk-repo`): `/etc/apk/repositories` tracks pure Alpine Edge alongside the signed local `@geminux` repo (`/var/lib/geminux/apk-repo`):
```sh ```sh
doas apk update doas apk update && doas apk upgrade
doas apk upgrade
``` ```
All custom components (`geminux-kernel-modules`, `geminux-xlibre`, `geminux-suckless`, `geminux-dunst`, `geminux-ui`, `geminux-bantam`, `geminux-gsocket`, `geminux-gdk-pixbuf`, `geminux-webarchy`, `geminux-gtkttk`, `geminux-config`) are exact-version pinned (`name@geminux=version`) in `/etc/apk/world`. Disallowed Rust, Wayland, and upstream override packages (`!rust`, `!cargo`, `!libglycin`, `!gdk-pixbuf`, `!deno`, `!py3-cryptography`, `!xorg-server`, `!linux-edge`, etc., with `librsvg`, `rav1e`/`rav1e-libs`, and `libdovi` whitelisted) are negated in `/etc/apk/world`. All **11** custom `@geminux` packages are exact-version pinned (`name@geminux=version`) in `/etc/apk/world`, while disallowed Rust/Wayland/upstream overrides are blocked via `!` pins (`librsvg`, `rav1e`, `libdovi` whitelisted). Normal `apk upgrade` safely updates upstream libraries without touching patched Geminux binaries.
Standard `apk upgrade` safely updates upstream libraries, utilities, NetworkManager, ModemManager, PipeWire, and Mesa without overwriting patched binaries. On a Linux build host, run `./rebuild-image.sh --force-bootstrap` to refresh `rootfs/` packages when generating new images.
+32 -41
View File
@@ -1,78 +1,69 @@
# Power optimization # Power optimization
Battery endurance and reliable deep-sleep recovery are designed across the kernel, system daemons, radios, display, audio, and storage stack in Geminux. Battery endurance and reliable deep-sleep recovery span kernel configuration, suspend/wake IRQ handling, zero-poll daemons, CPU cluster gating, audio, radios, and storage in Geminux.
## Kernel-level optimizations ## Kernel-level optimizations
Configured in [kernel/configs/geminux-mt6797x.config](kernel/configs/geminux-mt6797x.config) and built into `7.3.5-geminux`: Built into `7.3.5-geminux` via [kernel/configs/geminux-mt6797x.config](kernel/configs/geminux-mt6797x.config):
- **`CONFIG_HZ_100=y`**: 100 Hz tick rate cuts periodic timer interrupt overhead compared to 250/1000 Hz kernels while keeping interactive X11 responsiveness high. - **`CONFIG_HZ_100=y` & `CONFIG_RCU_LAZY=y`**: Cuts timer interrupt overhead vs. 250/1000 Hz kernels and batches idle RCU callbacks for deeper CPU C-state residency.
- **`CONFIG_RCU_LAZY=y`**: Batches idle RCU callbacks to extend CPU C-state residency. - **`CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL=y`**: Enables `schedutil` DVFS via `clk-mt6797-mcusys` + `cpufreq-dt` loaded by [geminux-hwinit](overlay/rootfs/etc/init.d/geminux-hwinit) (`GEMINUX_ENABLE_CPUFREQ="yes"` in [conf.d/geminux-hwinit](overlay/rootfs/etc/conf.d/geminux-hwinit)), scaling `policy0` (`221..897 MHz`) and `policy4` (`325..1209 MHz`) independently of Cortex-A72 bring-up (`GEMINUX_ENABLE_A72="no"`).
- **`CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL=y`**: Drives scheduler-guided frequency scaling (`schedutil`) across the MT6797X tri-cluster CPU. [geminux-hwinit](overlay/rootfs/etc/init.d/geminux-hwinit) loads `clk-mt6797-mcusys` and `cpufreq-dt` (`GEMINUX_ENABLE_CPUFREQ="yes"` in [conf.d/geminux-hwinit](overlay/rootfs/etc/conf.d/geminux-hwinit)) independently of experimental Cortex-A72 enablement (`GEMINUX_ENABLE_A72="no"`), providing `policy0` (`221..897 MHz`) and `policy4` (`325..1209 MHz`) scaling and `soc-thermal` throttling. - **`mt6797-gate-unused`**: Gates ~25 unused bootloader leaf clocks (`SPI`, `UART`, `PWM`, `IRTX`, `ICUSB`, `ANC_MD32`, etc.) left on by `clk_ignore_unused`.
- **`mt6797-gate-unused`**: Loaded at the end of `geminux-hwinit` (`GEMINUX_GATE_UNUSED_CLOCKS="yes"`) to gate ~25 unused bootloader peripheral leaf clocks (`SPI`, `UART`, `PWM`, `IRTX`, `ICUSB`, `ANC_MD32`, etc.) left enabled due to `clk_ignore_unused` while leaving active display/I2C clocks untouched. - **Sensor IR LED gating**: Blacklists `stk3310` in [modprobe.d/geminux.conf](overlay/rootfs/etc/modprobe.d/geminux.conf) (`GEMINUX_ENABLE_SENSORS="no"`) to stop unconsumed ALS/proximity IR polling.
- **Sensor IR LED gating**: `stk3310` is blacklisted in [modprobe.d/geminux.conf](overlay/rootfs/etc/modprobe.d/geminux.conf) (`GEMINUX_ENABLE_SENSORS="no"`) so its ALS/proximity IR LED does not continuously poll without a consumer. - **`CONFIG_ZRAM_DEF_COMP_LZ4=y` & `CONFIG_CRYPTO_AES_ARM64_CE_BLK=y`**: `2 GiB` LZ4 `zram` (`vm.swappiness=100`) avoids eMMC flash swap writes; ARMv8 AES-CE accelerates optional LUKS2 (`--allow-discards`).
- **`CONFIG_ZRAM_DEF_COMP_LZ4=y`**: Pairs `2 GiB` LZ4 `zram` swap (`etc/conf.d/zram-init`) with `vm.swappiness=100` (`etc/sysctl.d/99-geminux-power.conf`) and `commit=60,noatime` mounts (`etc/fstab`) to minimize power-hungry eMMC flash swap writes.
- **`CONFIG_CRYPTO_AES_ARM64_CE_BLK=y`**: Accelerates optional LUKS2 `dm-crypt` (`aes-xts-plain64`) with ARMv8 Cryptography Extensions (`--allow-discards` enabled in initramfs) for negligible encryption overhead.
## Deep sleep (`mem`) and wakeup reliability ## Deep sleep (`mem`) and wakeup reliability
`CONFIG_SUSPEND=y` enables Suspend-to-RAM (`mem` / `deep`) via `mt6797-spm-sleep` (`sodi_idle=0 pmic_modes=0 timer_sec=600` in [modprobe.d/geminux.conf](overlay/rootfs/etc/modprobe.d/geminux.conf)): `CONFIG_SUSPEND=y` drives Suspend-to-RAM (`mem`) through `mt6797-spm-sleep` (`sodi_idle=0 pmic_modes=0 timer_sec=600` in [modprobe.d/geminux.conf](overlay/rootfs/etc/modprobe.d/geminux.conf)):
- **`pmic_modes=0` & clean SPM timers**: Keeps `MT6351` from dropping `VCORE` to `0.600 V` sleep voltage while CPU0 remains in `WFI`. - **`pmic_modes=0`**: Prevents `MT6351` from dropping `VCORE` to `0.600 V` while CPU0 remains in `WFI`.
- **Wake IRQ & resume hardening (`0008`)**: Bounds `spm_enter()` PCM timer rollovers cleanly without `.suspend_again`, clears `mtk-eint` hardware debounce when arming edge wakeup pins (`SW_LID` / `EINT5`), and calls `pm_wakeup_event()` from `mtk-pmic-keys`. - **SPM & wake IRQ hardening (`0008`)**: Bounds `spm_enter()` PCM timer rollovers without `.suspend_again`, clears `mtk-eint` debounce on edge wakeups (`SW_LID`/`EINT5`), and fires `pm_wakeup_event()` from `mtk-pmic-keys`.
- **Hall lid filtering & debounce (`0011`)**: Tunes Hall EINT debounce to `1 ms` and matrix keypad debounce to `10 ms`, synchronously filtering spurious keystrokes/touches and inhibiting both keypad and touchscreen whenever the lid magnet closes. - **Hall lid filtering & debounce (`0011`)**: Applies `1 ms` Hall EINT / `10 ms` keypad debounce, synchronously filtering spurious inputs and inhibiting keypad + touch when closed.
- **Post-suspend lid reconciliation & fuel-gauge accuracy (`0012`)**: Reconciles `gemini-lid` state on `PM_POST_SUSPEND` and raw-GPIO rechecks to avoid stuck `BL_CORE_SUSPENDED`/input lockouts, and pairs `mt6351-fuel-gauge` + `bq25890` zero-current boot OCV calibration (`POWER_SUPPLY_PROP_CALIBRATE` / `MT6351_RGS_CHRDET`) with `win_ua`+`reg_ua` CV-taper validation, `+1%` step caps, and `180 mV` start-up `ADC21` sag tolerance. - **Lid resume & fuel gauge (`0012`)**: Reconciles `gemini-lid` state via `PM_POST_SUSPEND` + raw-GPIO rechecks (preventing stuck `BL_CORE_SUSPENDED`/input lockouts), and improves `mt6351-fuel-gauge` + `bq25890` zero-current boot OCV, CV-taper validation, `+1%` step caps, and `180 mV` `ADC21` sag tolerance.
- **PMIC wake IRQ timing & SPM safety backstops (`0013`)**: Moves MT6397/MT6351 PMIC wake IRQ masking (`mt6397_irq_suspend`/`mt6397_irq_resume`) from `PM_SUSPEND_PREPARE` into `LATE_SYSTEM_SLEEP_PM_OPS` so all child drivers' `enable_irq_wake()` settings are already armed before deep sleep, and hardens `mt6797-spm-sleep` `s.sleep` with `WAKE_PCM_WDT`, `pcm_wdt`, `im_wait` (`1000 us`), and a `5000 ms` `cntp` physical timer backstop (`100 ms` on `s.sodi`) so CPU0 cannot wedge indefinitely on an overnight suspend. - **PMIC wake IRQ order & SPM backstops (`0013`)**: Moves `mt6397_irq_suspend`/`mt6397_irq_resume` from `PM_SUSPEND_PREPARE` into `LATE_SYSTEM_SLEEP_PM_OPS` so child `enable_irq_wake()` settings arm cleanly before deep sleep, and adds `WAKE_PCM_WDT`, `pcm_wdt`, `im_wait` (`1000 us`), and a `5000 ms` `cntp` physical timer backstop (`100 ms` on `s.sodi`) on `mt6797-spm-sleep` `s.sleep` to prevent unrecoverable overnight hangs.
## Zero-poll userspace daemons ## Zero-poll userspace daemons
All background daemons sleep in event loops with no periodic polling timers:
### `geminux-powerd` ### `geminux-powerd`
Uses `epoll_wait()` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`, `mtk-pmic-keys` `KEY_ESC`), filtered `KOBJECT_UEVENT` netlink (`input`, `power_supply`, `drm`), `/run/geminux/powerd.sock`, and a lazy-rearming `timerfd`: Sleeps in `epoll_wait()` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`, `mtk-pmic-keys` `KEY_ESC`), filtered `KOBJECT_UEVENT` netlink (`input`, `power_supply`, `drm`), `/run/geminux/powerd.sock`, and a lazy `timerfd`:
- **USB/AC policy (`inhibit_ac_lid`)**: Closing the lid or timing out locks X11 and blanks the backlight without unloading CONSYS or invoking `/sys/power/state`, keeping `bq25890`'s `40 s` charger watchdog fed without `-EBUSY` suspend thrash. - **USB/AC policy (`inhibit_ac_lid`)**: Locks/blanks without unloading CONSYS or invoking `/sys/power/state`, keeping `bq25890`'s `40 s` watchdog fed without `-EBUSY` suspend thrash.
- **Battery `mem` vs. `low_power_standby`**: Before `mem` sleep, unloads `mt6797_consys` (and reverse dependents `btmt6797`, `radio_mt6797`, `gnss_mt6797`, `mac`) so `CONN`/`VCN*` rails power down and offlines `cpu1..9`. When 4G `MD1` is powered and blocks SPM `mem` sleep, uses zero-thrash `low_power_standby` (`cpu1..9` offline, `cpu0` pinned to `221 MHz` `powersave`, CONSYS unloaded, never `freeze`/`s2idle`). - **Battery `mem` vs. `low_power_standby`**: Unloads `mt6797_consys` (+ dependents) and offlines `cpu1..9` before `mem` sleep; if 4G `MD1` blocks `mem`, holds zero-thrash `low_power_standby` (`cpu0 @ 221 MHz` `powersave`, never `freeze`/`s2idle`).
- **Wakeup filtering & quiet open-lid re-suspend**: Polls post-resume input/lid events (`90 ms`) even when the lid is open; only a `closed -> open` lid transition, real `EV_KEY`/`EV_REL`/`EV_ABS` activity, or USB/AC attach triggers a desktop wake. Internal timer wakes in open-lid `IDLE_STAGE_LOCKED_BLANK` on battery re-suspend quietly (`quiet_timer_resleep`) without reloading CONSYS or enabling the backlight. - **Wakeup filtering & quiet open-lid re-suspend**: Polls post-resume events (`90 ms`) even with the lid open so only `closed -> open` lid events, genuine `EV_KEY`/`EV_REL`/`EV_ABS` activity, or USB/AC attach wake the session; internal timer wakes during open-lid `IDLE_STAGE_LOCKED_BLANK` re-suspend quietly (`quiet_timer_resleep`) without reloading CONSYS or waking the backlight.
- **Persisted hardware Airplane Mode**: `Fn+F` / `geminux-power-ctl airplane on` persists `/var/lib/geminux/airplane-mode`, keeps CONSYS Wi-Fi/BT modules unloaded, and puts MD1 into `AT+CFUN=4` while leaving `usb0` active. - **X11 DPMS wake & lock sync**: Unblanking runs `DPMSForceLevel(..., DPMSModeOn)` + `XResetScreenSaver()` in a privilege-dropped child so X11/HDMI outputs never stay blanked across S3 or lid events; pre-suspend locking waits up to `1800 ms` for `geminux-lock` to draw, grab input, and publish `_GEMINUX_LOCK_READY`.
- **Zero-thrash sysfs caching**: Caches applied CPUfreq/profile state to skip redundant sysfs writes, and measures idle timers strictly from the last user input (`CLOCK_MONOTONIC`). - **Persisted state & caching**: Persists Airplane Mode (`/var/lib/geminux/airplane-mode`) and caches CPUfreq/profile writes.
### Supporting daemons & X11 efficiency ### Supporting daemons & X11 efficiency
- **`geminux-statusd`**: `epoll` over `signalfd` (`SIGUSR1`), `RTMGRP_LINK`/`RTMGRP_IPV4_IFADDR`, `KOBJECT_UEVENT` (`power_supply`, `net`), `inotify`, and minute-aligned `timerfd`; deduplicates root `WM_NAME` updates (`XStoreName`) with zero child shell forks. - **`geminux-statusd`**: `epoll` (`signalfd`, netlink, filtered uevents, `inotify`, minute-aligned `timerfd`); deduplicates `WM_NAME` updates with zero shell forks.
- **Display & terminal**: [10-geminux-gpu.conf](overlay/rootfs/etc/X11/xorg.conf.d/10-geminux-gpu.conf) uses `AccelMethod "none"` + `ShadowFB "true"` + `TearFree "true"` to eliminate Glamor fence spin-waits, and `st` disables its cursor-blink timer while unfocused. - **Display & `st`**: `ShadowFB` + `TearFree` (`AccelMethod "none"` in [10-geminux-gpu.conf](overlay/rootfs/etc/X11/xorg.conf.d/10-geminux-gpu.conf)) eliminates Glamor spin-waits; `st` stops cursor blink timers when unfocused.
- **`geminux-touchd`**: Event-driven XInput 2.2 gesture engine with zero polling. - **Input, Audio, Modem, LEDs & Lock**: `geminux-touchd`, `geminux-ccci-daemon`, `geminux-modem-ctl`, `geminux-imsd` (20 ms RTP `timerfd` armed only mid-call), `geminux-bt-obex`, `geminux-leds` (AW9120 strip `0 mA` idle/100%, `rgb:indicator-6` while charging), and `geminux-lock` (`15 s` refresh, diff-checked).
- **Modem & IMS**: `geminux-ccci-daemon`, `geminux-modem-ctl`, and `geminux-imsd` sleep in `epoll_wait()`, arming `geminux-imsd`'s 20 ms RTP `timerfd` only during active voice calls.
- **`geminux-bt-obex`, `geminux-leds` & `geminux-lock`**: Pure event-driven GLib/GDBus and `epoll` + uevent operation; `geminux-leds` keeps `rgb:indicator-1..5` off (`0 mA`) when idle or at 100%, lighting only `rgb:indicator-6` while actively charging; `geminux-lock` uses a `15 s` refresh once grabbed and redraws only on clock or battery change.
## Cluster gating and profiles ## Cluster gating and profiles
`geminux-power-ctl` and `geminux-control` switch between three profiles defined in [src/geminux-daemons/geminux-power-policy.c](src/geminux-daemons/geminux-power-policy.c): Managed via `geminux-power-ctl` / `geminux-control` ([geminux-power-policy.c](src/geminux-daemons/geminux-power-policy.c)):
| Profile | Governor | A72 big cores (`cpu8..9`) | A53 LL (`policy0`) / L (`policy4`) max freq | Battery idle (dim -> lock+suspend) | AC idle (lock+blank screensaver) | | Profile | Governor | A72 (`cpu8..9`) | A53 LL (`policy0`) / L (`policy4`) max freq | Battery idle (dim -> suspend) | AC idle (lock+blank) |
| --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- |
| `eco` | `schedutil` | Offline (`0`) | `715 MHz` / `962 MHz` | `60 s` -> `180 s` | `180 s` | | `eco` | `schedutil` | Offline (`0`) | `715 MHz` / `962 MHz` | `60 s` -> `180 s` | `180 s` |
| `balanced` | `schedutil` | Online (`1`, `2002 MHz`) | `897 MHz` / `1209 MHz` (bat), `1547 MHz` / `1846 MHz` (AC) | `120 s` -> `300 s` | `300 s` | | `balanced` | `schedutil` | Online (`1`, `2002 MHz`) | `897` / `1209 MHz` (bat), `1547` / `1846 MHz` (AC) | `120 s` -> `300 s` | `300 s` |
| `performance` | `performance` | Online (`1`, `2600 MHz`) | `1547 MHz` / `1846 MHz` (clamped to DT `cpuinfo_max_freq`) | `180 s` (lock+blank, no suspend) | `600 s` | | `performance` | `performance` | Online (`1`, `2600 MHz`) | `1547 MHz` / `1846 MHz` (clamped to DT max) | `180 s` (lock+blank only) | `600 s` |
All idle thresholds run on `CLOCK_MONOTONIC` from the last active keyboard, touchscreen, pointer, or lid-open event and are never reset by periodic `power_supply` uevents. Closing the clamshell (`SW_LID = 1`) on battery enters RAM sleep (`mem` or zero-thrash `low_power_standby`) unless inhibited by USB/AC (`inhibit_ac_lid`), an active call (`inhibit add call`), an explicit inhibitor, or connected HDMI (`SiI9024`). Idle timers count strictly from the last user input (`CLOCK_MONOTONIC`), ignoring periodic battery uevents. Lid close (`SW_LID = 1`) on battery suspends unless inhibited by AC (`inhibit_ac_lid`), an active call, a manual inhibitor, or HDMI (`SiI9024`).
## Audio, radios, and storage defaults ## Audio, radios, and storage defaults
- **Audio**: PipeWire uses `default.clock.min-quantum = 1024` and `quantum = 2048` (`10-geminux-power.conf`); WirePlumber suspends idle ALSA/BlueZ nodes after `3 s` (`50-geminux-suspend.conf`) so audio DSP clocks gate quickly. - **Audio**: PipeWire `min-quantum = 1024`, `quantum = 2048` (`10-geminux-power.conf`); WirePlumber suspends idle nodes after `3 s`.
- **Bluetooth**: BlueZ sets `AutoEnable = false` and `FastConnectable = false` in [etc/bluetooth/main.conf](overlay/rootfs/etc/bluetooth/main.conf), and `geminux-hwinit` soft-blocks Bluetooth at boot until enabled in `geminux-net`. - **Bluetooth**: `AutoEnable = false`, `FastConnectable = false` ([etc/bluetooth/main.conf](overlay/rootfs/etc/bluetooth/main.conf)); soft-blocked at boot.
- **Wi-Fi & NTP**: NetworkManager keeps `wifi.powersave = 2` (`10-geminux-power.conf`) so associated WLAN never drops GTK rekeys or DNS; `geminux-powerd` powers down CONSYS across suspend. [10-geminux.sources](overlay/rootfs/etc/chrony/sources.d/10-geminux.sources) limits Chrony pools (`maxsources 2`, `minpoll 10 maxpoll 14`) with an offline hook in [30-geminux-chrony](overlay/rootfs/etc/NetworkManager/dispatcher.d/30-geminux-chrony). - **Wi-Fi & NTP**: `wifi.powersave = 2` prevents associated CONSYS key/DNS stalls; Chrony uses `maxsources 2`, `minpoll 10 maxpoll 14` ([10-geminux.sources](overlay/rootfs/etc/chrony/sources.d/10-geminux.sources)) + offline dispatch ([30-geminux-chrony](overlay/rootfs/etc/NetworkManager/dispatcher.d/30-geminux-chrony)).
- **GTK / Qt / Tk / XSETTINGS**: [10-geminux-env.sh](overlay/rootfs/etc/profile.d/10-geminux-env.sh) exports `NO_AT_BRIDGE=1` (disabling unused AT-SPI bridges) and `QT_QPA_PLATFORMTHEME=qt6ct:gtk3`; `xsettingsd` (`SIGHUP` reload), `gtkTtk` (`XA_RESOURCE_MANAGER` `PropertyNotify`), and portal-free `dconf` (`ADW_DISABLE_PORTAL=1`) operate without polling loops. - **Toolkits & Storage**: `NO_AT_BRIDGE=1` ([10-geminux-env.sh](overlay/rootfs/etc/profile.d/10-geminux-env.sh)) avoids idle AT-SPI daemons; `noatime,commit=60` and `dirty_writeback_centisecs=1500` cut eMMC wakes; `/media/sdcard` mounts `noatime` purely via `eudev` hotplug.
- **Storage**: `noatime,commit=60` in `etc/fstab` and `vm.dirty_writeback_centisecs=1500` cut eMMC wakeups; microSD mounts at `/media/sdcard` use `noatime` and pure `eudev` hotplug events (`95-geminux-sdcard.rules`) with zero idle polling.
## Auditing on device ## Auditing on device
Inspect live power policy and hardware state on the Gemini PDA at any time:
```sh ```sh
geminux-power-audit geminux-power-audit
geminux-power-audit --json geminux-power-audit --json
``` ```
Outputs active profile, battery capacity/voltage/current, online CPUs (including A72 cluster state), CPUfreq governor, `policy0`/`policy4` max frequencies, Bluetooth `rfkill` state, ZRAM algorithm, and `/sys/power/mem_sleep` modes. Measure actual multi-hour standby battery endurance and idle current draw directly on physical x27 hardware after flashing. Reports live profile, battery stats, online CPUs, governors, frequency caps, Bluetooth `rfkill` state, ZRAM algorithm, and `/sys/power/mem_sleep`. Actual idle current draw and overnight endurance must be measured on physical hardware.
+36 -68
View File
@@ -1,82 +1,50 @@
# Geminux # Geminux
Geminux is an Alpine Linux (`aarch64`, musl, OpenRC) distribution tailored for the **Planet Computers Gemini PDA** (Wi-Fi + 4G, MediaTek MT6797X / Helio X27). It pairs a custom-patched Linux `7.3.5-geminux` kernel with XLibre X11, a touch-friendly suckless desktop, 11 HiDPI C11 applications (`libgemui`), MT6797 cellular/eSIM/IMS daemons, and a pure-Linux MediaTek flasher with optional LUKS2 full-disk encryption. Geminux is an Alpine Linux (`aarch64`, musl, OpenRC) distribution built for the **Planet Computers Gemini PDA** (Wi-Fi + 4G, MediaTek MT6797X / Helio X27). It combines a patched Linux `7.3.5-geminux` kernel, XLibre X11, a touch-friendly suckless desktop, 11 HiDPI C11 applications, MT6797 cellular/eSIM/IMS daemons, and a pure-Linux MediaTek flasher.
## Highlights ## Highlights
- **Desktop & Theming**: Rotated `ShadowFB` + `TearFree` XLibre display with Panfrost EGL/OpenGL 3D acceleration, Pango/HarfBuzz `dwm` / `st` / `dmenu` (Fira Code ligatures and Nerd Fonts), `192 DPI` scaling (`2x`), **22** unified `.xth` themes defaulting to **Anodized**, an interactive **Theme Editor & Importer**, and a native X11 + Cairo **Wallpaper** manager. - **Desktop & Theming**: Rotated `ShadowFB` + `TearFree` XLibre display with Panfrost EGL/OpenGL 3D, Pango/HarfBuzz `dwm`/`st`/`dmenu` (`192 DPI`), **22** `.xth` themes defaulting to **Anodized**, an interactive Theme Editor & Importer, native X11 Wallpaper manager, and bundled wallpapers (`/usr/share/geminux/wallpapers/geminux-dark.png` default).
- **Cellular, Connectivity & Audio**: MT6797 MD1 cellular bring-up (`geminux-cellctl` + `lpac` ST33 eUICC eSIM), 3GPP VoLTE / VoWiFi / SMS-over-IMS (`geminux-imsd`), PipeWire audio + WirePlumber idle suspend, `Fn+F` hardware Airplane Mode, microSD `/media/sdcard` boot/hotplug automount (`geminux-sdcard` / `eudev`), and configurable DNS presets (`geminux-dnsctl`). - **Cellular, Audio & Connectivity**: MT6797 MD1 cellular bring-up (`geminux-cellctl` + ST33 eUICC `lpac` eSIM), 3GPP VoLTE/VoWiFi/SMS-over-IMS (`geminux-imsd`), PipeWire audio, `Fn+F` hardware Airplane Mode, microSD automount (`/media/sdcard`), and configurable DNS (`geminux-dnsctl`).
- **Browser, Media & CLI Tools**: Ultrawide `GTK3`/`WebKit2GTK` **Webarchy** browser (`webarchy` with collapsible vertical tabs), native Alpine Edge `mpv` + `ffmpeg` + `gst-libav`, `yt-dlp` (`quickjs`), `python3`/`pip`, `tcl`/`tk` with dynamic `gtkTtk 0.9`, `gnupg`/`pass`, `dosfstools`, `bantam` CLI AI agent (`kilo-auto/free` default), `lynx`, and `gsocket`. - **Browser, Media & CLI Tools**: Ultrawide `GTK3`/`WebKit2GTK` **Webarchy** browser, native `mpv` + `ffmpeg` + `gst-libav`, `yt-dlp` (`quickjs`), `python3`/`pip3`, `tcl`/`tk` (`gtkTtk 0.9`), `gnupg`/`pass`, `dosfstools`, `bantam` CLI AI agent, `lynx`, and `gsocket`.
- **Flashing & Security**: Pure-Linux `mtkclient` BROM/DA flasher preserving MediaTek protected partitions (`LBA 0..0x6FFFF`), offline desktop/`root` credential provisioning, and optional Argon2id + ARMv8 AES-CE **LUKS2** full-disk encryption (`--encrypt`) with Gemini matrix keyboard unlock in initramfs. - **Flashing & Security**: Redistributable release ZIP archives ([package-image.sh](package-image.sh)), turnkey `mtkclient` flashing with automatic firmware extraction/injection preserving protected factory partitions (`LBA 0..0x6FFFF`), offline credential setup, and optional Argon2id + ARMv8 AES-CE **LUKS2** encryption.
## Key design goals ## Quick start
- **Upgradable Alpine Edge userspace**: Standard packages update normally via `apk update && apk upgrade`. - **Flash a release ZIP (Linux host, no Docker required)**:
- **Pinned hardware stack**: Kernel modules, XLibre, suckless desktop, `dunst`, custom UI, Webarchy, pure-C `gdk-pixbuf`, `gtkTtk`, `bantam`, `gsocket`, and system configs live in **11** local RSA-signed `@geminux` APK packages (`name@geminux=version`). ```sh
- **Rust-free & Wayland-free policy**: Disallowed Rust/Wayland/upstream override packages are blocked via `!` pins in `/etc/apk/world` and verified by ELF scanning (`librsvg`, `rav1e`/`rav1e-libs`, and `libdovi` remain whitelisted for ecosystem compatibility and `ffmpeg`/`mpv`/`gst-libav`). unzip geminux-<version>-<codename>-gemini-x27.zip
- **Full eMMC layout**: Claims user-writable eMMC for Linux (`geminux-root`) without Android dual-boot partitioning, while write-protecting the MediaTek factory region (`LBA 0..0x6FFFF`). cd geminux-<version>-<codename>-gemini-x27
- **Optional full-disk encryption**: `--encrypt` wraps `geminux-rootfs` in LUKS2 `aes-xts-plain64` (hardware AES-CE, Argon2id) with early-boot `simpledrm` + Gemini US keyboard unlock and automatic first-boot ext4 expansion. sha256sum -c SHA256SUMS.txt
- **End-to-end battery optimization**: Combines kernel tuning (`HZ_100`, `RCU_LAZY`, `SUSPEND`, LZ4 `zram`, `SCHEDUTIL`, `0013` PMIC wake IRQ & SPM safety) with zero-poll `epoll` daemons, A72 cluster gating, `st` unfocused blink gating, default-off cover LEDs, and lid-close deep sleep. ./flash-mtk.sh --flash-full
```
- **Build images from source & run offline checks**:
```sh
./rebuild-image.sh # add --rebuild-all --force-bootstrap for clean rebuild
./scripts/check-rebuild.sh
```
- **Package a distributable release ZIP (sanitized rootfs + `FLASH-INSTRUCTIONS.txt`)**:
```sh
./package-image.sh # outputs releases/geminux-<ver>-<codename>-gemini-x27.zip
```
## Component stack ## Documentation
| Subsystem | Implementation | Source / Script | | Document | Scope |
| --- | --- | --- | | --- | --- |
| **Kernel & boot** | Linux `7.3.5-geminux` + 13 Gemini x27 patches (`0001`–`0013`): `SSD2092` DSI/touch, synchronous `gemini-lid`, `mt6351`+`bq25890` zero-current OCV & taper fuel gauge, CONSYS Wi-Fi/BT, CCCI/CLDMA + MD1, S3 resume + `0013` MT6397 `LATE_SYSTEM_SLEEP_PM_OPS` & SPM watchdog/timer safety, XFRM/ESP IPsec, `sii902x`, LUKS2 initramfs | [scripts/build-kernel.sh](scripts/build-kernel.sh) | | [INSTALL.md](INSTALL.md) | Release ZIP flashing, source build, firmware extraction, LUKS2 FDE, and hardware checklist |
| **Flasher & GPT** | Vendored GPLv3 `mtkclient` + MT6797 DA + GPT builder + offline credential & LUKS2 provisioning | [flash-mtk.sh](flash-mtk.sh), [flash-mtk.py](flash-mtk.py), [scripts/geminux_accounts.py](scripts/geminux_accounts.py), [scripts/geminux_luks.py](scripts/geminux_luks.py) | | [MANUAL.md](MANUAL.md) | Keyboard map, DWM shortcuts, gestures, themes, wallpapers, apps, and `apk upgrade` safety |
| **Display server** | XLibre Xorg 25.x (`modesetting` `ShadowFB` + `TearFree` rotated 2D scanout, Panfrost Glamor/EGL 3D, `fbdev`, `libinput`) | [scripts/build-xlibre.sh](scripts/build-xlibre.sh) | | [ARCHITECTURE.md](ARCHITECTURE.md) | Kernel patches, XLibre/suckless hardening, theming/wallpaper engine, daemons, APKs, and flasher internals |
| **WM & terminal** | Patched `dwm` (Pango `PANGO_ELLIPSIZE_END` & `FC_COLOR=FcFalse`, 32-bit ARGB XEmbed systray, full EWMH/ICCCM/NETWM + Wine/DXVK focus recovery, `xerror`/`RENDER` fault guards, live `.Xresources` reload, `Mod4`, `Fn+F` Airplane Mode, `SIGHUP` self-reexec), `st` (HarfBuzz ligatures, live `XA_RESOURCE_MANAGER`/`SIGUSR1` reloads, focus cursor sync & blink gating), full-height touch `dmenu` (82 px rows, `RENDER` guards, UTF-8 sanitization) | [scripts/build-suckless.sh](scripts/build-suckless.sh) | | [POWER-OPTIMIZATION.md](POWER-OPTIMIZATION.md) | Suspend/wakeup fixes, zero-poll daemons, cluster profiles, and `geminux-power-audit` |
| **Notifications** | Pure-X11 zero-`gdk-pixbuf` `dunst v1.12.2` + custom GDBus `notify-send` / `dunstify` (`geminux-sync-dunst-theme`) | [scripts/build-dunst.sh](scripts/build-dunst.sh) |
| **Web & toolkits** | Webarchy C++20 `GTK3` + `WebKit2GTK-4.1` browser (right-side vertical tabs, live `.Xresources` theming), pure-C `gdk-pixbuf 2.42.12`, `tcl`/`tk` + `gtkTtk 0.9` theme engine, synchronized GTK2/3/4/`libadwaita`/Qt5/Qt6/Tk theming | [scripts/build-webarchy.sh](scripts/build-webarchy.sh), [scripts/build-gtkttk.sh](scripts/build-gtkttk.sh), [scripts/compile-gsettings-schemas.sh](scripts/compile-gsettings-schemas.sh) |
| **UI, themes & daemons** | `libgemui.so`, 11 HiDPI apps including `geminux-themes` (22 `.xth` themes defaulting to **Anodized**, interactive Theme Editor & Importer, native X11 Wallpaper manager) + `geminux-apply-wallpaper`, zero-poll C11 daemons (`geminux-cellctl`, `geminux-imsd`, `geminux-powerd`, `geminux-statusd`, `geminux-touchd`, `geminux-dnsctl`, etc.) | [scripts/build-geminux-ui.sh](scripts/build-geminux-ui.sh) |
| **Media & CLI tools** | Native Alpine Edge `mpv` (`/etc/mpv/mpv.conf` Panfrost EGL + PipeWire + IPC), `ffmpeg`/`ffprobe`, `gst-libav`, `mpg123`, `openmpt123`, `yt-dlp` (`quickjs`), `python3`/`pip3`, `tclsh`/`wish`, `gpg`, `pass`, `dosfstools`, `bantam`, `lynx`, `gsocket`, `.apexrc`, default `htoprc` | [scripts/build-bantam.sh](scripts/build-bantam.sh), [scripts/build-gsocket.sh](scripts/build-gsocket.sh), [overlay/rootfs/etc/mpv/mpv.conf](overlay/rootfs/etc/mpv/mpv.conf) |
| **Local APK repository** | 11 signed `@geminux` `.apk` packages + `APKINDEX.tar.gz` | [scripts/package-local-apks.sh](scripts/package-local-apks.sh) |
| **Full build & checks** | Full image assembly + automated offline verification suite | [rebuild-image.sh](rebuild-image.sh), [scripts/check-rebuild.sh](scripts/check-rebuild.sh) |
## Repository layout ## Repository layout
- [kernel/](kernel/) and [patches/kernel/](patches/kernel/) — kernel manifest, MT6797X configuration, and 13 Linux `7.3.5` patches - [kernel/](kernel/) & [patches/kernel/](patches/kernel/) — Kernel manifest, MT6797X config, and Linux `7.3.5` patches (`0001`–`0013`)
- [src/](src/) — initramfs scripts, `st`, `dwm`, `dmenu`, `dunst-notify`, `bantam`, `webarchy`, `gtkTtk`, `libgemui`, `geminux-apps` (including `geminux-xth.h`, `geminux-wallpaper.h`, `geminux-wallpaper-x11.h`), and `geminux-daemons` - [src/](src/) — Initramfs, `st`, `dwm`, `dmenu`, `dunst-notify`, `bantam`, `webarchy`, `gtkTtk`, `libgemui`, 11 apps, and daemons
- [overlay/rootfs/](overlay/rootfs/) — OpenRC services (`geminux-sdcard`, `geminux-hwinit`, etc.), ALSA UCM2, XKB layout, console keymap, Xorg drop-ins, **22** `.xth` themes (default: `Anodized`), `geminux-apply-theme`, `geminux-apply-wallpaper`, PipeWire/WirePlumber, udev rules (`95-geminux-sdcard.rules`), `/etc/mpv/mpv.conf`, and NetworkManager configs - [overlay/rootfs/](overlay/rootfs/) & [artwork/](artwork/) — OpenRC units, XKB/keymap, Xorg configs, 22 `.xth` themes, stock wallpapers, and scripts
- [scripts/](scripts/) — cross-compilation builders, APK packager, rootfs bootstrapper, verification suite, and 9 host Python unit test suites - [scripts/](scripts/) — Cross-compile builders, APK/ZIP packagers, verification suite, and 9 Python unit test suites
- [prebuilt/](prebuilt/) — cross-compiled `aarch64` staging tree (`images/` holds built boot, recovery, and ext4 rootfs images) - [flash-mtk.sh](flash-mtk.sh), [rebuild-image.sh](rebuild-image.sh), [package-image.sh](package-image.sh) — Flashing, full build, and release packaging entry points
## Verification status vs. on-device testing ## Verification status
**Automated host verification** via [scripts/check-rebuild.sh](scripts/check-rebuild.sh) validates: Automated offline checks ([scripts/check-rebuild.sh](scripts/check-rebuild.sh)) verify ELF architectures, zero un-whitelisted Rust dependencies, `apk upgrade --simulate` compatibility, DTB constraints, `e2fsck`, image checksums, release ZIP packaging, and all 9 Python unit test suites. Physical hardware bring-up on Gemini PDA (x27) is verified across flashing, display/touch, Wi-Fi/BT, MD1/eSIM, camera, audio, deep sleep, and USB NCM; carrier/accessory checks are listed in [INSTALL.md](INSTALL.md).
- Cross-compiled binaries, kernel/DTB artifacts, and GPT repartitioning logic ([scripts/test-flash-mtk-gpt.py](scripts/test-flash-mtk-gpt.py))
- Offline credential/LUKS2 builders, XKB keymap compilation, and `.Xresources`-to-`dunstrc`/GTK/Qt/Tk theme syncing
- MT6797 CCCI framing/handshake, 3GPP IMS/AKA/ESP/SIP/RTP protocol handling ([scripts/test-ims-protocol.py](scripts/test-ims-protocol.py)), and zero-poll power policy
- Webarchy renderer profiles, WebKit GSettings schemas, `dosfstools` + `/media/sdcard` automount logic, ELF Rust scans, and `apk upgrade --simulate`
**Verified on physical Gemini PDA (x27 Wi-Fi + 4G) hardware**:
- USB BROM/DA flashing, offline credential provisioning, LUKS2 unlock, and first-boot ext4 resize
- `SSD2092` FHD+ display, `geminux-touchd` multi-touch gestures, and tear-free rotated `ShadowFB` scanout
- Lid-close and overnight S3 deep sleep/resume, CONSYS Wi-Fi/BT, MT6797 MD1 boot (`MD_STATE=READY`), ST33 eUICC/physical SIM slot switching, and `Fn+F` hardware Airplane Mode
- Webarchy Panfrost rendering, PipeWire audio, Media Controller + 10-bit Bayer camera ISP, AW9120 back LEDs, Chrony NTP sync, and USB NCM networking
> [!NOTE]
> Carrier- and accessory-dependent tests (such as live VoLTE/VoWiFi calls/SMS on an active carrier SIM or external Slimport/HDMI monitors) are covered in the hardware checklist in [INSTALL.md](INSTALL.md).
## Quick start (host build and checks)
```sh
./rebuild-image.sh
./scripts/check-rebuild.sh
```
To rebuild all cross-compiled components from scratch and upgrade preinstalled Alpine Edge packages in `rootfs/` to the latest Edge release:
```sh
./rebuild-image.sh --rebuild-all --force-bootstrap
./scripts/check-rebuild.sh
```
Running `./rebuild-image.sh --force-bootstrap` alone refreshes preinstalled Alpine Edge packages inside `rootfs/` without recompiling toolchains.
## Documentation index
- [INSTALL.md](INSTALL.md) — Host prerequisites, flashing workflow, backup, firmware extraction, LUKS2 encryption, and hardware validation checklist
- [MANUAL.md](MANUAL.md) — Keyboard layout, DWM shortcuts, themes & Theme Editor, desktop wallpapers, applications, and Alpine Edge maintenance
- [ARCHITECTURE.md](ARCHITECTURE.md) — Kernel patch queue, XLibre, suckless hardening, theming/wallpaper engine, `@geminux` APK pinning, and flasher internals
- [POWER-OPTIMIZATION.md](POWER-OPTIMIZATION.md) — Deep sleep fixes, zero-poll daemons, CPU cluster gating, and on-device power auditing
+45 -9
View File
@@ -266,13 +266,17 @@ def write_partition_checked(da_handler, part_name, img_path, verify=True, allow_
verify_written_partition(da_handler, part_name, img_path) verify_written_partition(da_handler, part_name, img_path)
def load_extract_firmware(): def load_firmware_module():
import importlib.util import importlib.util
fw_path = os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py") fw_path = os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py")
sp = importlib.util.spec_from_file_location("extract_vendor_fw", fw_path) sp = importlib.util.spec_from_file_location("extract_vendor_fw", fw_path)
mod = importlib.util.module_from_spec(sp) mod = importlib.util.module_from_spec(sp)
sp.loader.exec_module(mod) sp.loader.exec_module(mod)
return mod.extract_firmware return mod
def load_extract_firmware():
return load_firmware_module().extract_firmware
def extract_fw_from_device(da_handler, fw_out_dir): def extract_fw_from_device(da_handler, fw_out_dir):
@@ -399,16 +403,29 @@ def copy_raw_image(src, dst):
shutil.copyfile(src, dst) shutil.copyfile(src, dst)
def stage_rootfs_image(root_img, account_cfg, tmp_dir, always_copy=False, luks_cfg=None): def stage_rootfs_image(
"""Unsparse if needed and apply offline account/LUKS2 provisioning in tmp_dir.""" root_img,
account_cfg,
tmp_dir,
always_copy=False,
luks_cfg=None,
firmware_dir=None,
):
"""Unsparse if needed and apply firmware/account/LUKS2 provisioning in tmp_dir."""
if not os.path.isfile(root_img): if not os.path.isfile(root_img):
raise FileNotFoundError(f"Rootfs image not found: {root_img}") raise FileNotFoundError(f"Rootfs image not found: {root_img}")
with open(root_img, "rb") as rf: with open(root_img, "rb") as rf:
is_sparse = rf.read(4) == SPARSE_MAGIC is_sparse = rf.read(4) == SPARSE_MAGIC
fw_mod = None
has_firmware = False
if firmware_dir and os.path.isdir(firmware_dir):
fw_mod = load_firmware_module()
has_firmware = bool(fw_mod.list_firmware_blobs(firmware_dir))
has_changes = bool(account_cfg and account_cfg.has_changes) has_changes = bool(account_cfg and account_cfg.has_changes)
has_luks = bool(luks_cfg and luks_cfg.enabled) has_luks = bool(luks_cfg and luks_cfg.enabled)
if not is_sparse and not has_changes and not has_luks and not always_copy: if not is_sparse and not has_changes and not has_luks and not has_firmware and not always_copy:
return root_img return root_img
staged = os.path.join(tmp_dir, "linux.raw.img") staged = os.path.join(tmp_dir, "linux.raw.img")
@@ -419,6 +436,13 @@ def stage_rootfs_image(root_img, account_cfg, tmp_dir, always_copy=False, luks_c
else: else:
copy_raw_image(root_img, staged) copy_raw_image(root_img, staged)
if has_firmware:
injected = fw_mod.inject_firmware_into_ext4(staged, firmware_dir)
print(
f"[+] Injected {len(injected)} MT6797 firmware blob(s) into staged rootfs "
"(/lib/firmware/mediatek/mt6797)."
)
if has_changes: if has_changes:
customize_ext4_accounts( customize_ext4_accounts(
staged, staged,
@@ -450,9 +474,10 @@ def customize_rootfs_offline(args, account_cfg, luks_cfg=None):
out_dir = os.path.dirname(out_img) or "." out_dir = os.path.dirname(out_img) or "."
os.makedirs(out_dir, exist_ok=True) os.makedirs(out_dir, exist_ok=True)
has_luks = bool(luks_cfg and luks_cfg.enabled) has_luks = bool(luks_cfg and luks_cfg.enabled)
fw_dir = None if getattr(args, "skip_firmware_inject", False) else args.firmware_dir
with tempfile.TemporaryDirectory(dir=out_dir, prefix=".geminux-cust-") as tmp: with tempfile.TemporaryDirectory(dir=out_dir, prefix=".geminux-cust-") as tmp:
staged = stage_rootfs_image( staged = stage_rootfs_image(
root_img, account_cfg, tmp, always_copy=True, luks_cfg=luks_cfg root_img, account_cfg, tmp, always_copy=True, luks_cfg=luks_cfg, firmware_dir=fw_dir
) )
if not has_luks and (not account_cfg or not account_cfg.has_changes) and shutil.which("e2fsck"): if not has_luks and (not account_cfg or not account_cfg.has_changes) and shutil.which("e2fsck"):
subprocess.run(["e2fsck", "-fn", staged], check=True, stdout=subprocess.DEVNULL) subprocess.run(["e2fsck", "-fn", staged], check=True, stdout=subprocess.DEVNULL)
@@ -472,7 +497,10 @@ def flash_full(mtk, da_handler, args, account_cfg=None, luks_cfg=None):
req_check = os.path.join(args.firmware_dir, "WIFI_RAM_CODE_6797") req_check = os.path.join(args.firmware_dir, "WIFI_RAM_CODE_6797")
if not os.path.isfile(req_check): if not os.path.isfile(req_check):
extract_fw_from_device(da_handler, args.firmware_dir) extract_fw_from_device(da_handler, args.firmware_dir)
print("[*] Note: Rebuild rootfs image if extracted firmware was not yet bundled in images/geminux-rootfs.img.") if getattr(args, "skip_firmware_inject", False):
print("[*] Note: Rebuild or flash without --skip-firmware-inject so extracted firmware is bundled.")
else:
print("[*] Extracted firmware will be injected into staged rootfs automatically before flashing.")
total_sectors = get_emmc_total_sectors(mtk) total_sectors = get_emmc_total_sectors(mtk)
pgpt_raw = da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, "", "user", display=False) pgpt_raw = da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, "", "user", display=False)
@@ -526,8 +554,11 @@ def flash_full(mtk, da_handler, args, account_cfg=None, luks_cfg=None):
write_partition_checked(da_handler, "recovery", rec_img, verify=True) write_partition_checked(da_handler, "recovery", rec_img, verify=True)
write_partition_checked(da_handler, "boot2", boot_img, verify=True) write_partition_checked(da_handler, "boot2", boot_img, verify=True)
fw_dir = None if getattr(args, "skip_firmware_inject", False) else args.firmware_dir
with tempfile.TemporaryDirectory(prefix="geminux-stage-") as tmp: with tempfile.TemporaryDirectory(prefix="geminux-stage-") as tmp:
staged_root = stage_rootfs_image(root_img, account_cfg, tmp, luks_cfg=luks_cfg) staged_root = stage_rootfs_image(
root_img, account_cfg, tmp, luks_cfg=luks_cfg, firmware_dir=fw_dir
)
write_partition_checked(da_handler, "linux", staged_root, verify=False) write_partition_checked(da_handler, "linux", staged_root, verify=False)
print("[+] Full Geminux installation complete!") print("[+] Full Geminux installation complete!")
@@ -535,8 +566,11 @@ def flash_full(mtk, da_handler, args, account_cfg=None, luks_cfg=None):
def flash_rootfs_only(da_handler, args, account_cfg=None, luks_cfg=None): def flash_rootfs_only(da_handler, args, account_cfg=None, luks_cfg=None):
root_img = os.path.join(args.images_dir, "geminux-rootfs.img") root_img = os.path.join(args.images_dir, "geminux-rootfs.img")
fw_dir = None if getattr(args, "skip_firmware_inject", False) else args.firmware_dir
with tempfile.TemporaryDirectory(prefix="geminux-stage-") as tmp: with tempfile.TemporaryDirectory(prefix="geminux-stage-") as tmp:
staged_root = stage_rootfs_image(root_img, account_cfg, tmp, luks_cfg=luks_cfg) staged_root = stage_rootfs_image(
root_img, account_cfg, tmp, luks_cfg=luks_cfg, firmware_dir=fw_dir
)
write_partition_checked(da_handler, "linux", staged_root, verify=False) write_partition_checked(da_handler, "linux", staged_root, verify=False)
print("[+] Geminux rootfs update complete!") print("[+] Geminux rootfs update complete!")
@@ -649,6 +683,8 @@ def build_arg_parser():
p.add_argument("--preloader", help="Optional preloader binary path for DRAM init") p.add_argument("--preloader", help="Optional preloader binary path for DRAM init")
p.add_argument("--skip-backup", action="store_true", help="Skip backup if already taken in --backup-dir") p.add_argument("--skip-backup", action="store_true", help="Skip backup if already taken in --backup-dir")
p.add_argument("--skip-firmware-extract", action="store_true", help="Skip automatic firmware extraction") p.add_argument("--skip-firmware-extract", action="store_true", help="Skip automatic firmware extraction")
p.add_argument("--skip-firmware-inject", action="store_true",
help="Skip injecting blobs from --firmware-dir into the staged rootfs")
p.add_argument("--force-gpt", action="store_true", help="Allow repartitioning unrecognized GPT layouts") p.add_argument("--force-gpt", action="store_true", help="Allow repartitioning unrecognized GPT layouts")
p.add_argument("--no-reboot", action="store_true", p.add_argument("--no-reboot", action="store_true",
help="Power off instead of auto-rebooting after flashing") help="Power off instead of auto-rebooting after flashing")
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Package built Geminux images + flasher + TXT guide into a release ZIP archive.
set -eu
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
exec "${PYTHON_BIN:-python3}" "$BASE_DIR/scripts/package-release-zip.py" "$@"
Binary file not shown.
Binary file not shown.
+8 -1
View File
@@ -9,6 +9,7 @@ IMAGES_DIR="$BASE_DIR/images"
REBUILD_ALL=0 REBUILD_ALL=0
FORCE_BOOTSTRAP=0 FORCE_BOOTSTRAP=0
SKIP_APKS=0 SKIP_APKS=0
PACKAGE_ZIP=0
for arg in "$@"; do for arg in "$@"; do
case "$arg" in case "$arg" in
@@ -21,8 +22,11 @@ for arg in "$@"; do
--skip-apks) --skip-apks)
SKIP_APKS=1 SKIP_APKS=1
;; ;;
--package)
PACKAGE_ZIP=1
;;
--help|-h) --help|-h)
echo "Usage: $0 [--rebuild-all] [--force-bootstrap] [--skip-apks]" echo "Usage: $0 [--rebuild-all] [--force-bootstrap] [--skip-apks] [--package]"
exit 0 exit 0
;; ;;
*) *)
@@ -204,4 +208,7 @@ echo "[*] Generating SHA256SUMS manifest..."
sha256sum $TARGETS > SHA256SUMS sha256sum $TARGETS > SHA256SUMS
) )
cat "$IMAGES_DIR/SHA256SUMS" cat "$IMAGES_DIR/SHA256SUMS"
if [ "$PACKAGE_ZIP" -eq 1 ]; then
"$BASE_DIR/package-image.sh"
fi
echo "[+] Geminux image rebuild complete." echo "[+] Geminux image rebuild complete."
+101 -10
View File
@@ -33,6 +33,46 @@ SEARCH_SUBDIRS = (
SPARSE_MAGIC = b"\x3a\xff\x26\xed" SPARSE_MAGIC = b"\x3a\xff\x26\xed"
def is_firmware_blob_name(name):
"""Return True if filename is a required MT6797 blob or optional SPM binary."""
return name in REQUIRED_BLOBS or (
name.startswith(OPTIONAL_SPM_GLOB_PREFIX) and name.endswith(".bin")
)
def list_firmware_blobs(fw_dir):
"""Return sorted (filename, abs_path) pairs for MT6797 firmware blobs in fw_dir."""
if not fw_dir or not os.path.isdir(fw_dir):
return []
abs_fw = os.path.abspath(fw_dir)
blobs = []
for name in sorted(os.listdir(abs_fw)):
if not is_firmware_blob_name(name):
continue
path = os.path.join(abs_fw, name)
if os.path.isfile(path) and not os.path.islink(path):
blobs.append((name, path))
return blobs
def _have_host_e2fs():
return shutil.which("debugfs") is not None and shutil.which("e2fsck") is not None
def _run_docker_e2fs(img_dir, extra_mounts, shell_cmd, input_text=None):
docker_bin = shutil.which("docker")
if not docker_bin:
raise RuntimeError("Need host debugfs/e2fsck (e2fsprogs) or docker to modify ext4 image")
cmd = [docker_bin, "run", "--rm", "-i", "-v", f"{img_dir}:/img"]
for host_path, container_path in extra_mounts:
cmd += ["-v", f"{host_path}:{container_path}:ro"]
cmd += [
"alpine:3.24", "sh", "-eu", "-c",
f"apk add --no-cache e2fsprogs >/dev/null && {shell_cmd}",
]
return subprocess.run(cmd, input=input_text, text=True, check=True, capture_output=True)
def sha256_file(path): def sha256_file(path):
h = hashlib.sha256() h = hashlib.sha256()
with open(path, "rb") as f: with open(path, "rb") as f:
@@ -81,11 +121,7 @@ def extract_from_ext4(image_path, out_dir):
if not entries: if not entries:
continue continue
for name in entries: for name in entries:
is_req = name in REQUIRED_BLOBS if not is_firmware_blob_name(name) or name in found:
is_spm = name.startswith(OPTIONAL_SPM_GLOB_PREFIX) and name.endswith(".bin")
if not (is_req or is_spm):
continue
if name in found:
continue continue
dest = os.path.join(out_dir, name) dest = os.path.join(out_dir, name)
if debugfs_dump(image_path, f"{subdir}/{name}", dest): if debugfs_dump(image_path, f"{subdir}/{name}", dest):
@@ -102,11 +138,7 @@ def extract_from_dir(src_dir, out_dir):
if not os.path.isdir(base): if not os.path.isdir(base):
continue continue
for name in os.listdir(base): for name in os.listdir(base):
is_req = name in REQUIRED_BLOBS if not is_firmware_blob_name(name) or name in found:
is_spm = name.startswith(OPTIONAL_SPM_GLOB_PREFIX) and name.endswith(".bin")
if not (is_req or is_spm):
continue
if name in found:
continue continue
src = os.path.join(base, name) src = os.path.join(base, name)
if os.path.isfile(src): if os.path.isfile(src):
@@ -116,6 +148,65 @@ def extract_from_dir(src_dir, out_dir):
return found return found
def _debugfs_path_exists(abs_img, internal_path):
res = subprocess.run(
["debugfs", "-R", f"stat {internal_path}", abs_img],
capture_output=True, text=True, check=False,
)
return res.returncode == 0 and "Type:" in res.stdout
def inject_firmware_into_ext4(ext4_img_path, fw_dir):
"""Inject extracted MT6797 firmware blobs into /lib/firmware/mediatek/mt6797 of an ext4 image."""
blobs = list_firmware_blobs(fw_dir)
if not blobs:
return []
abs_img = os.path.abspath(ext4_img_path)
if not os.path.isfile(abs_img):
raise FileNotFoundError(f"ext4 image not found: {abs_img}")
abs_fw = os.path.abspath(fw_dir)
img_dir = os.path.dirname(abs_img)
img_name = os.path.basename(abs_img)
use_host = _have_host_e2fs()
target_dirs = ("/lib", "/lib/firmware", "/lib/firmware/mediatek", "/lib/firmware/mediatek/mt6797")
existing_files = set(debugfs_ls(abs_img, "lib/firmware/mediatek/mt6797")) if use_host else set()
def build_cmds(fw_prefix, check_exists):
cmds = []
for d in target_dirs:
if not check_exists or not _debugfs_path_exists(abs_img, d):
cmds.append(f"mkdir {d}")
cmds.append(f"set_inode_field {d} uid 0")
cmds.append(f"set_inode_field {d} gid 0")
cmds.append(f"set_inode_field {d} mode 040755")
for name, _host_p in blobs:
dst = f"/lib/firmware/mediatek/mt6797/{name}"
if not check_exists or name in existing_files:
cmds.append(f"rm {dst}")
cmds.append(f"write {fw_prefix}/{name} {dst}")
cmds.append(f"set_inode_field {dst} uid 0")
cmds.append(f"set_inode_field {dst} gid 0")
cmds.append(f"set_inode_field {dst} mode 0100644")
return "\n".join(cmds) + "\n"
if use_host:
subprocess.run(
["debugfs", "-w", abs_img],
input=build_cmds(abs_fw, True), text=True, check=True, stdout=subprocess.DEVNULL,
)
subprocess.run(["e2fsck", "-fn", abs_img], check=True, stdout=subprocess.DEVNULL)
else:
_run_docker_e2fs(
img_dir,
[(abs_fw, "/fw")],
f"debugfs -w '/img/{img_name}' >/dev/null 2>&1 && e2fsck -fn '/img/{img_name}' >/dev/null",
input_text=build_cmds("/fw", False),
)
return [name for name, _p in blobs]
def write_manifest(out_dir, found): def write_manifest(out_dir, found):
manifest = os.path.join(out_dir, "MANIFEST.sha256") manifest = os.path.join(out_dir, "MANIFEST.sha256")
with open(manifest, "w") as f: with open(manifest, "w") as f:
+501
View File
@@ -0,0 +1,501 @@
#!/usr/bin/env python3
"""Package Geminux flash images, pure-Linux MTK flasher, and TXT guide into a ZIP release."""
import argparse
import datetime
import hashlib
import importlib.util
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import zipfile
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts")
SPARSE_MAGIC = b"\x3a\xff\x26\xed"
FLASH_SCRIPTS = (
("scripts/bootstrap-flash-deps.sh", True),
("scripts/extract-vendor-fw.py", True),
("scripts/geminux_accounts.py", False),
("scripts/geminux_gpt.py", True),
("scripts/geminux_luks.py", False),
)
SKIP_VENDOR_DIRS = frozenset({"__pycache__"})
SKIP_VENDOR_FILES = frozenset({".DS_Store", ".state"})
SKIP_VENDOR_SUFFIXES = (".pyc", ".pyo")
def _load_fw_mod():
fw_path = os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py")
spec = importlib.util.spec_from_file_location("extract_vendor_fw", fw_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def _query_version_field(flag, fallback):
ver_sh = os.path.join(SCRIPTS_DIR, "version.sh")
if not os.path.isfile(ver_sh):
return fallback
res = subprocess.run([ver_sh, flag], capture_output=True, text=True, check=False)
val = res.stdout.strip()
return val if res.returncode == 0 and val else fallback
def sha256_file(path):
"""Compute streaming SHA-256 hex digest for a file."""
h = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(1048576)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def copy_sparse_raw_image(src, dst):
"""Unsparse src if needed, otherwise copy sparsely into dst."""
with open(src, "rb") as f:
is_sparse = f.read(4) == SPARSE_MAGIC
if is_sparse:
simg = shutil.which("simg2img")
if not simg:
raise RuntimeError("simg2img is required to unpack sparse geminux-rootfs.img")
subprocess.run([simg, src, dst], check=True)
return
if shutil.which("cp"):
subprocess.run(["cp", "--reflink=auto", "--sparse=always", src, dst], check=True)
else:
shutil.copyfile(src, dst)
def _debugfs_ls_details(abs_img, internal_dir):
"""Return list of (name, mode_str) entries inside internal_dir of an ext4 image."""
res = subprocess.run(
["debugfs", "-R", f"ls -p /{internal_dir}", abs_img],
capture_output=True, text=True, check=False,
)
if res.returncode != 0:
return []
out = []
for line in res.stdout.splitlines():
parts = line.split("/")
if len(parts) >= 6:
mode_str = parts[2]
name = parts[5]
if name and name not in (".", ".."):
out.append((name, mode_str))
return out
def sanitize_ext4_for_release(img_path, strip_firmware=True, strip_ssh_keys=True):
"""Remove SSH keys and/or proprietary MT6797 firmware blobs from a staged ext4 image."""
fw_mod = _load_fw_mod()
abs_img = os.path.abspath(img_path)
if not os.path.isfile(abs_img):
raise FileNotFoundError(f"ext4 image not found: {abs_img}")
if fw_mod._have_host_e2fs():
rm_paths = []
if strip_ssh_keys:
if fw_mod._debugfs_path_exists(abs_img, "/root/.ssh/authorized_keys"):
rm_paths.append("/root/.ssh/authorized_keys")
for hname, hmode in _debugfs_ls_details(abs_img, "home"):
if hmode.startswith("04"):
ak = f"/home/{hname}/.ssh/authorized_keys"
if fw_mod._debugfs_path_exists(abs_img, ak):
rm_paths.append(ak)
for ename, emode in _debugfs_ls_details(abs_img, "etc/ssh"):
if not emode.startswith("04") and ename.startswith("ssh_host_"):
rm_paths.append(f"/etc/ssh/{ename}")
if strip_firmware:
for fname, fmode in _debugfs_ls_details(abs_img, "lib/firmware/mediatek/mt6797"):
if not fmode.startswith("04"):
rm_paths.append(f"/lib/firmware/mediatek/mt6797/{fname}")
if rm_paths:
script = "\n".join(f"rm {p}" for p in rm_paths) + "\n"
subprocess.run(
["debugfs", "-w", abs_img],
input=script, text=True, check=True, stdout=subprocess.DEVNULL,
)
subprocess.run(["e2fsck", "-fn", abs_img], check=True, stdout=subprocess.DEVNULL)
return rm_paths
# Docker fallback when host lacks e2fsprogs
img_dir = os.path.dirname(abs_img)
img_name = os.path.basename(abs_img)
sf_flag = "1" if strip_firmware else "0"
sk_flag = "1" if strip_ssh_keys else "0"
docker_sh = f"""
IMG="/img/{img_name}"
RM_CMDS=""
if [ "{sk_flag}" = "1" ]; then
if debugfs -R "stat /root/.ssh/authorized_keys" "$IMG" 2>/dev/null | grep -q "Type:"; then
RM_CMDS="$RM_CMDS
rm /root/.ssh/authorized_keys"
fi
for u in $(debugfs -R "ls -p /home" "$IMG" 2>/dev/null | awk -F/ '$3 ~ /^04/ && $6 != "" && $6 != "." && $6 != ".." {{print $6}}'); do
if debugfs -R "stat /home/$u/.ssh/authorized_keys" "$IMG" 2>/dev/null | grep -q "Type:"; then
RM_CMDS="$RM_CMDS
rm /home/$u/.ssh/authorized_keys"
fi
done
for k in $(debugfs -R "ls -p /etc/ssh" "$IMG" 2>/dev/null | awk -F/ '$3 !~ /^04/ && $6 ~ /^ssh_host_/ {{print $6}}'); do
RM_CMDS="$RM_CMDS
rm /etc/ssh/$k"
done
fi
if [ "{sf_flag}" = "1" ]; then
for fw in $(debugfs -R "ls -p /lib/firmware/mediatek/mt6797" "$IMG" 2>/dev/null | awk -F/ '$3 !~ /^04/ && $6 != "" && $6 != "." && $6 != ".." {{print $6}}'); do
RM_CMDS="$RM_CMDS
rm /lib/firmware/mediatek/mt6797/$fw"
done
fi
if [ -n "$RM_CMDS" ]; then
printf '%s\n' "$RM_CMDS" | debugfs -w "$IMG" >/dev/null
fi
e2fsck -fn "$IMG" >/dev/null
"""
fw_mod._run_docker_e2fs(img_dir, [], docker_sh)
return ["(sanitized via docker e2fsprogs)"]
def render_flash_instructions(version, codename, build_date, top_dir, include_firmware=False):
"""Generate plain-text FLASH-INSTRUCTIONS.txt shipped inside the release ZIP."""
fw_mode = (
"INCLUDED (for personal single-device backup images)"
if include_firmware else
"CLEAN / STRIPPED (auto-extracted from your PDA during flashing)"
)
return f"""========================================================================
Geminux Linux for Planet Computers Gemini PDA (x27 Wi-Fi + 4G)
Release: {version} ({codename}) Built: {build_date}
Firmware: {fw_mode}
========================================================================
Archive Directory : {top_dir}/
1. ARCHIVE CONTENTS
-------------------
FLASH-INSTRUCTIONS.txt This guide
SHA256SUMS.txt SHA-256 checksums for all disk images
flash-mtk.sh / flash-mtk.py Pure-Linux MediaTek BROM/DA flasher
images/boot-geminux.img Linux 7.3.5-geminux kernel + DTB + initramfs
images/recovery-geminux.img USB NCM recovery shell image (172.16.42.1/24)
images/geminux-rootfs.img Alpine Edge aarch64 desktop ext4 rootfs
scripts/ Account, GPT, LUKS2, firmware & pip helpers
vendor/mtkclient/ Vendored GPLv3 mtkclient + MT6797 DA binary
2. LINUX HOST PREREQUISITES
---------------------------
Docker is NOT required to flash this release archive.
Required on the Linux PC:
- python3, python3-pip, libusb-1.0, and sudo (raw USB BROM/DA access)
- e2fsprogs (debugfs, e2fsck) for account & firmware rootfs staging
Optional:
- cryptsetup Needed only if you choose --encrypt (LUKS2 disk encryption)
- simg2img Needed only if extracting firmware from a sparse stock
Android system.img (--extract-firmware --system-img)
Note: On first run, ./flash-mtk.sh automatically installs its Python USB
helpers (pyusb, pyserial, pycryptodome, colorama) locally into .flash-deps/
and temporarily pauses host ModemManager so /dev/ttyACM* is not interrupted.
3. SAFETY & HARDWARE PREPARATION
--------------------------------
* Protected partitions (preloader, nvram, proinfo, lk, tee1, md1img, etc.
in LBA 0..0x6FFFF) hold device calibration and baseband data. Geminux
backs them up first and write-blocks them during normal flashing.
* ALWAYS use the LEFT USB-C port on the Gemini PDA (closest to Esc),
connected directly to the PC (avoid unpowered USB hubs).
* Geminux claims all user-writable eMMC after 0x0E000000 (replacing Android
system, cache, and userdata with boot, recovery, boot2, and ~58 GiB linux).
4. FLASHING STEPS
-----------------
Extract this ZIP and change into {top_dir}/:
unzip {top_dir}.zip
cd {top_dir}
Step A - Verify image checksums:
sha256sum -c SHA256SUMS.txt
Step B - Optional: backup factory partitions only (without modifying eMMC):
# Keep Gemini powered off and unplugged, start the command, then plug into
# the LEFT USB-C port:
./flash-mtk.sh --only-backup
Step C - Full Geminux installation:
# Interactive (prompts for username, passwords, and optional LUKS2 before
# waiting for USB; automatically backs up factory partitions, extracts MT6797
# Wi-Fi/BT/SPM blobs from stock Android 'system', injects them into the
# staged rootfs, repartitions eMMC, verifies readbacks, and reboots):
./flash-mtk.sh --flash-full
# Example with explicit username, prompted passwords, and LUKS2 encryption:
./flash-mtk.sh --flash-full --username alice --ask-user-password \\
--ask-root-password --encrypt
# Non-interactive with image defaults (unencrypted, user / geminux):
./flash-mtk.sh --flash-full --use-default-credentials
# Already flashed Linux previously (no stock Android system partition left)?
# Extract blobs once from your stock Android system.img beforehand:
./flash-mtk.sh --extract-firmware --system-img /path/to/stock-system.img
./flash-mtk.sh --flash-full
5. OTHER FLASHER COMMANDS
-------------------------
# Re-flash kernel + recovery slots only (preserves GPT and linux rootfs):
./flash-mtk.sh --flash-kernel-only
# Update only the linux rootfs partition:
./flash-mtk.sh --flash-rootfs-only --username alice --ask-user-password
# Restore an earlier MediaTek partition backup (keep backup/ safe!):
./flash-mtk.sh --restore-backup backup/<timestamp>
6. FIRST BOOT & QUICK REFERENCE
-------------------------------
* After flashing finishes, unplug USB-C if needed and hold Esc to boot.
* If booted on USB power, charging pauses briefly (~15 s) while VSYS stays
powered so the fuel gauge reads true open-circuit battery voltage.
* With --encrypt, unlock at the console prompt using the Gemini keyboard.
* First boot automatically expands ext4 across the ~58 GiB linux partition.
* Default login (unless customized): user / geminux (default theme: Anodized,
default wallpaper: /usr/share/geminux/wallpapers/geminux-dark.png).
* Rescue SSH: plug USB-C into a Linux host -> USB NCM usb0 at 172.16.42.1.
Essential shortcuts (Fn+Alt = Mod4):
Mod4 + Space App launcher Mod4 + t Themes & Wallpaper
Mod4 + Return st terminal Mod4 + n Network, eSIM & DNS
Mod4 + c Control Center Fn + F Airplane Mode
Mod4 + Shift + l Lock screen Mod4 + Shift+c Close window
7. TROUBLESHOOTING
------------------
* Device boots Android/screen instead of flashing: Unplug USB-C, power off
completely, run ./flash-mtk.sh first, then plug into the LEFT USB-C port.
* Device hung before connecting: Hold Esc + side Power for ~12 s while plugged
into the LEFT USB-C port to force hardware reset into BROM/Preloader.
* Missing debugfs/e2fsck or cryptsetup: Install e2fsprogs (and cryptsetup
if using --encrypt) from your Linux distribution's package manager.
"""
def _write_zip_entry(zf, src_path, arcname, is_exec, compress_level):
st = os.stat(src_path)
dt = time.localtime(st.st_mtime)[:6]
if dt[0] < 1980:
dt = (1980, 1, 1, 0, 0, 0)
zinfo = zipfile.ZipInfo(arcname, date_time=dt)
zinfo.compress_type = zipfile.ZIP_STORED if compress_level == 0 else zipfile.ZIP_DEFLATED
zinfo.create_system = 3
mode = stat.S_IFREG | (0o755 if is_exec else 0o644)
zinfo.external_attr = (mode & 0xFFFF) << 16
zinfo.file_size = st.st_size
force64 = st.st_size >= 0xF0000000
with open(src_path, "rb") as sf, zf.open(zinfo, "w", force_zip64=force64) as df:
shutil.copyfileobj(sf, df, length=4 * 1024 * 1024)
def _write_zip_bytes(zf, raw_bytes, arcname, is_exec, compress_level):
dt = time.gmtime()[:6]
zinfo = zipfile.ZipInfo(arcname, date_time=dt)
zinfo.compress_type = zipfile.ZIP_STORED if compress_level == 0 else zipfile.ZIP_DEFLATED
zinfo.create_system = 3
mode = stat.S_IFREG | (0o755 if is_exec else 0o644)
zinfo.external_attr = (mode & 0xFFFF) << 16
zinfo.file_size = len(raw_bytes)
with zf.open(zinfo, "w") as df:
df.write(raw_bytes)
def _collect_vendor_entries():
vendor_root = os.path.join(BASE_DIR, "vendor", "mtkclient")
if not os.path.isdir(vendor_root):
raise FileNotFoundError(f"Missing vendored mtkclient directory: {vendor_root}")
entries = []
for root, dirs, files in os.walk(vendor_root):
dirs[:] = sorted(d for d in dirs if d not in SKIP_VENDOR_DIRS)
for fn in sorted(files):
if fn in SKIP_VENDOR_FILES or fn.endswith(SKIP_VENDOR_SUFFIXES):
continue
src = os.path.join(root, fn)
if not os.path.isfile(src) or os.path.islink(src):
continue
rel = os.path.relpath(src, BASE_DIR).replace(os.sep, "/")
is_exec = bool(os.stat(src).st_mode & 0o111)
entries.append((src, rel, is_exec))
return entries
def package_release_zip(
images_dir,
output_zip=None,
version=None,
codename=None,
include_firmware=False,
keep_ssh_keys=False,
compress_level=6,
verify=True,
):
"""Create a redistributable Geminux release ZIP archive with TXT flashing guide."""
ver = version or _query_version_field("--print", "0.1.0")
cname = codename or _query_version_field("--print-codename", "helio")
top_dir = f"geminux-{ver}-{cname}-gemini-x27"
if not output_zip:
output_zip = os.path.join(BASE_DIR, "releases", f"{top_dir}.zip")
abs_images = os.path.abspath(images_dir)
abs_out = os.path.abspath(output_zip)
out_dir = os.path.dirname(abs_out) or "."
os.makedirs(out_dir, exist_ok=True)
boot_img = os.path.join(abs_images, "boot-geminux.img")
rec_img = os.path.join(abs_images, "recovery-geminux.img")
root_img = os.path.join(abs_images, "geminux-rootfs.img")
for req in (boot_img, rec_img, root_img):
if not os.path.isfile(req):
raise FileNotFoundError(f"Required build artifact not found: {req}")
for top_tool in ("flash-mtk.sh", "flash-mtk.py"):
if not os.path.isfile(os.path.join(BASE_DIR, top_tool)):
raise FileNotFoundError(f"Missing flasher file: {top_tool}")
with tempfile.TemporaryDirectory(dir=out_dir, prefix=".geminux-pkg-") as tmp:
staged_root = os.path.join(tmp, "geminux-rootfs.img")
print(f"[*] Staging rootfs image for release packaging ({root_img})...")
copy_sparse_raw_image(root_img, staged_root)
removed = sanitize_ext4_for_release(
staged_root,
strip_firmware=not include_firmware,
strip_ssh_keys=not keep_ssh_keys,
)
print(
f"[+] Sanitized staged ext4 rootfs (stripped {len(removed)} "
"firmware/key file(s); e2fsck clean)."
)
sums_lines = [
f"{sha256_file(boot_img)} images/boot-geminux.img",
f"{sha256_file(staged_root)} images/geminux-rootfs.img",
f"{sha256_file(rec_img)} images/recovery-geminux.img",
]
sums_bytes = ("\n".join(sums_lines) + "\n").encode("utf-8")
build_date = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
guide_text = render_flash_instructions(
ver, cname, build_date, top_dir, include_firmware=include_firmware
).encode("utf-8")
tmp_zip = abs_out + ".tmp"
if os.path.exists(tmp_zip):
os.unlink(tmp_zip)
print(f"[*] Writing ZIP archive -> {abs_out} (deflate level {compress_level})...")
try:
with zipfile.ZipFile(
tmp_zip,
"w",
compression=zipfile.ZIP_STORED if compress_level == 0 else zipfile.ZIP_DEFLATED,
compresslevel=compress_level,
allowZip64=True,
) as zf:
_write_zip_bytes(zf, guide_text, f"{top_dir}/FLASH-INSTRUCTIONS.txt", False, compress_level)
_write_zip_bytes(zf, sums_bytes, f"{top_dir}/SHA256SUMS.txt", False, compress_level)
_write_zip_entry(zf, os.path.join(BASE_DIR, "flash-mtk.sh"), f"{top_dir}/flash-mtk.sh", True, compress_level)
_write_zip_entry(zf, os.path.join(BASE_DIR, "flash-mtk.py"), f"{top_dir}/flash-mtk.py", True, compress_level)
for rel_script, is_exec in FLASH_SCRIPTS:
src_s = os.path.join(BASE_DIR, rel_script)
if not os.path.isfile(src_s):
raise FileNotFoundError(f"Missing flasher helper script: {src_s}")
_write_zip_entry(zf, src_s, f"{top_dir}/{rel_script}", is_exec, compress_level)
for src_v, rel_v, is_exec in _collect_vendor_entries():
_write_zip_entry(zf, src_v, f"{top_dir}/{rel_v}", is_exec, compress_level)
_write_zip_entry(zf, boot_img, f"{top_dir}/images/boot-geminux.img", False, compress_level)
_write_zip_entry(zf, rec_img, f"{top_dir}/images/recovery-geminux.img", False, compress_level)
_write_zip_entry(zf, staged_root, f"{top_dir}/images/geminux-rootfs.img", False, compress_level)
if verify:
print("[*] Verifying ZIP CRC32 integrity...")
with zipfile.ZipFile(tmp_zip, "r") as zf:
bad = zf.testzip()
if bad is not None:
raise RuntimeError(f"ZIP integrity verification failed at member: {bad}")
os.replace(tmp_zip, abs_out)
finally:
if os.path.exists(tmp_zip):
try:
os.unlink(tmp_zip)
except OSError:
pass
zip_sha = sha256_file(abs_out)
sha_path = abs_out + ".sha256"
with open(sha_path, "w", encoding="utf-8") as sf:
sf.write(f"{zip_sha} {os.path.basename(abs_out)}\n")
zip_mb = os.path.getsize(abs_out) / (1024.0 * 1024.0)
print(f"[+] Packaged release ZIP: {abs_out} ({zip_mb:.1f} MiB)")
print(f"[+] ZIP SHA-256: {zip_sha} ({sha_path})")
return abs_out, sha_path
def build_arg_parser():
p = argparse.ArgumentParser(
description="Package Geminux images, pure-Linux MTK flasher, and TXT guide into a ZIP release."
)
p.add_argument("-o", "--output", help="Output ZIP file path (default: releases/geminux-<ver>-<codename>-gemini-x27.zip)")
p.add_argument("--images-dir", default=os.path.join(BASE_DIR, "images"),
help="Directory containing boot-geminux.img, recovery-geminux.img, geminux-rootfs.img")
p.add_argument("--version", help="Override Geminux version string")
p.add_argument("--codename", help="Override Geminux codename")
p.add_argument("--include-firmware", action="store_true",
help="Keep /lib/firmware/mediatek/mt6797 blobs inside packaged rootfs (not for redistribution)")
p.add_argument("--keep-ssh-keys", action="store_true",
help="Keep SSH authorized_keys and ssh_host_* keys in packaged rootfs")
p.add_argument("--compress-level", type=int, default=6, choices=range(0, 10), metavar="0..9",
help="ZIP deflate compression level (default: 6)")
p.add_argument("--no-verify", action="store_true", help="Skip ZIP CRC verification pass")
return p
def main():
args = build_arg_parser().parse_args()
package_release_zip(
images_dir=args.images_dir,
output_zip=args.output,
version=args.version,
codename=args.codename,
include_firmware=args.include_firmware,
keep_ssh_keys=args.keep_ssh_keys,
compress_level=args.compress_level,
verify=not args.no_verify,
)
return 0
if __name__ == "__main__":
sys.exit(main())
+207
View File
@@ -731,6 +731,210 @@ def test_luks2_encryption_offline():
print("[PASS] Offline LUKS2 encryption, PTY passphrase unlock, and XTS-256 ext4 decryption verified") print("[PASS] Offline LUKS2 encryption, PTY passphrase unlock, and XTS-256 ext4 decryption verified")
def test_firmware_injection_ext4():
if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck")):
print("[SKIP] mke2fs/debugfs/e2fsck not available for firmware injection test")
return
fw_mod = flash_mtk.load_firmware_module()
with tempfile.TemporaryDirectory(prefix="geminux-fwinj-test-") as tmp:
sysroot = os.path.join(tmp, "sysroot")
os.makedirs(os.path.join(sysroot, "etc"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "home", "user"), exist_ok=True)
with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f:
f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n")
with open(os.path.join(sysroot, "etc", "group"), "w", encoding="utf-8") as f:
f.write("root:x:0:root\nuser:x:10000:\n")
with open(os.path.join(sysroot, "etc", "shadow"), "w", encoding="utf-8") as f:
f.write("root:*:::::::\nuser:*:::::::\n")
fw_dir = os.path.join(tmp, "fw")
os.makedirs(fw_dir, exist_ok=True)
expected_blobs = {
"WIFI_RAM_CODE_6797": b"WIFI_FW_HDR" * 100,
"WMT_SOC.cfg": b"cfg=1\n",
"ROMv3_patch_1_0_hdr.bin": b"ROM10",
"pcm_suspend.bin": b"PCM_SUSPEND",
}
for name, data in expected_blobs.items():
with open(os.path.join(fw_dir, name), "wb") as bf:
bf.write(data)
with open(os.path.join(fw_dir, "ignored.txt"), "w", encoding="utf-8") as uf:
uf.write("ignore-me\n")
img_dir = os.path.join(tmp, "images")
os.makedirs(img_dir, exist_ok=True)
orig_img = os.path.join(img_dir, "geminux-rootfs.img")
out_img = os.path.join(tmp, "out-rootfs.img")
subprocess.run(
["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, orig_img, "8M"],
check=True,
)
orig_sha = flash_mtk.sha256_file(orig_img)
res = subprocess.run(
[
os.path.join(BASE_DIR, "flash-mtk.sh"),
"--customize-rootfs", out_img,
"--images-dir", img_dir,
"--firmware-dir", fw_dir,
"--use-default-credentials",
],
capture_output=True, text=True, check=False,
)
assert res.returncode == 0, f"customize-rootfs fw inject failed: {res.stdout}\n{res.stderr}"
assert flash_mtk.sha256_file(orig_img) == orig_sha, "Source rootfs image was mutated!"
e2 = subprocess.run(["e2fsck", "-fn", out_img], capture_output=True, text=True)
assert e2.returncode == 0, f"e2fsck failed after fw inject: {e2.stdout}\n{e2.stderr}"
ls_entries = fw_mod.debugfs_ls(out_img, "lib/firmware/mediatek/mt6797")
assert set(ls_entries) == set(expected_blobs.keys()), ls_entries
for name, expected in expected_blobs.items():
dump_p = os.path.join(tmp, f"dump-{name}")
assert fw_mod.debugfs_dump(out_img, f"lib/firmware/mediatek/mt6797/{name}", dump_p)
with open(dump_p, "rb") as df:
assert df.read() == expected
st = subprocess.run(
["debugfs", "-R", f"stat /lib/firmware/mediatek/mt6797/{name}", out_img],
capture_output=True, text=True, check=True,
)
assert re.search(r"Mode:\s*0644\b", st.stdout), st.stdout
# Verify --skip-firmware-inject skips injection
out_skip = os.path.join(tmp, "out-skip.img")
res_skip = subprocess.run(
[
os.path.join(BASE_DIR, "flash-mtk.sh"),
"--customize-rootfs", out_skip,
"--images-dir", img_dir,
"--firmware-dir", fw_dir,
"--skip-firmware-inject",
"--use-default-credentials",
],
capture_output=True, text=True, check=False,
)
assert res_skip.returncode == 0, res_skip.stderr
assert fw_mod.debugfs_ls(out_skip, "lib/firmware/mediatek/mt6797") == []
print("[PASS] Offline MT6797 firmware ext4 injection verified")
def test_release_zip_packager():
import zipfile
if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck")):
print("[SKIP] mke2fs/debugfs/e2fsck not available for release ZIP packager test")
return
pkg_mod = _load_mod(
"package_release_zip", os.path.join(SCRIPTS_DIR, "package-release-zip.py")
)
with tempfile.TemporaryDirectory(prefix="geminux-zip-test-") as tmp:
sysroot = os.path.join(tmp, "sysroot")
os.makedirs(os.path.join(sysroot, "etc", "ssh"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "root", ".ssh"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "home", "user", ".ssh"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797"), exist_ok=True)
with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f:
f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n")
with open(os.path.join(sysroot, "etc", "ssh", "sshd_config"), "w", encoding="utf-8") as f:
f.write("Port 22\n")
with open(os.path.join(sysroot, "etc", "ssh", "ssh_host_ed25519_key"), "w", encoding="utf-8") as f:
f.write("PRIVATE HOST KEY\n")
with open(os.path.join(sysroot, "etc", "ssh", "ssh_host_ed25519_key.pub"), "w", encoding="utf-8") as f:
f.write("ssh-ed25519 AAAAC3...\n")
with open(os.path.join(sysroot, "root", ".ssh", "authorized_keys"), "w", encoding="utf-8") as f:
f.write("ssh-ed25519 AAAA_USER_KEY\n")
with open(os.path.join(sysroot, "home", "user", ".ssh", "authorized_keys"), "w", encoding="utf-8") as f:
f.write("ssh-ed25519 AAAA_USER_KEY\n")
with open(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797", "WIFI_RAM_CODE_6797"), "wb") as f:
f.write(b"PROPRIETARY_WIFI_BLOB")
with open(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797", "MANIFEST.sha256"), "w", encoding="utf-8") as f:
f.write("abc WIFI_RAM_CODE_6797\n")
img_dir = os.path.join(tmp, "images")
os.makedirs(img_dir, exist_ok=True)
with open(os.path.join(img_dir, "boot-geminux.img"), "wb") as f:
f.write(b"ANDROID!" + b"\x00" * 4088)
with open(os.path.join(img_dir, "recovery-geminux.img"), "wb") as f:
f.write(b"ANDROID!" + b"\x11" * 4088)
root_img = os.path.join(img_dir, "geminux-rootfs.img")
subprocess.run(
["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, root_img, "8M"],
check=True,
)
orig_root_sha = flash_mtk.sha256_file(root_img)
out_zip = os.path.join(tmp, "geminux-0.1.0-helio-gemini-x27.zip")
res = subprocess.run(
[
os.path.join(BASE_DIR, "package-image.sh"),
"--images-dir", img_dir,
"--output", out_zip,
"--version", "0.1.0",
"--codename", "helio",
],
capture_output=True, text=True, check=False,
)
assert res.returncode == 0, f"package-image.sh failed:\n{res.stdout}\n{res.stderr}"
assert flash_mtk.sha256_file(root_img) == orig_root_sha, "Source rootfs image was mutated!"
assert os.path.isfile(out_zip) and os.path.isfile(out_zip + ".sha256")
top = "geminux-0.1.0-helio-gemini-x27"
with zipfile.ZipFile(out_zip, "r") as zf:
assert zf.testzip() is None
names = set(zf.namelist())
for req in (
f"{top}/FLASH-INSTRUCTIONS.txt",
f"{top}/SHA256SUMS.txt",
f"{top}/flash-mtk.sh",
f"{top}/flash-mtk.py",
f"{top}/images/boot-geminux.img",
f"{top}/images/recovery-geminux.img",
f"{top}/images/geminux-rootfs.img",
f"{top}/scripts/bootstrap-flash-deps.sh",
f"{top}/scripts/extract-vendor-fw.py",
f"{top}/scripts/geminux_accounts.py",
f"{top}/scripts/geminux_gpt.py",
f"{top}/scripts/geminux_luks.py",
f"{top}/vendor/mtkclient/mtkclient/Loader/MTK_DA_V5_MT6797.bin",
):
assert req in names, f"ZIP missing {req}"
assert not any("__pycache__" in n or n.endswith((".pyc", ".pyo")) for n in names), "Found bytecode in ZIP"
sh_info = zf.getinfo(f"{top}/flash-mtk.sh")
assert ((sh_info.external_attr >> 16) & 0o111) == 0o111, "flash-mtk.sh missing +x attr"
txt = zf.read(f"{top}/FLASH-INSTRUCTIONS.txt").decode("utf-8")
for needle in ("./flash-mtk.sh --flash-full", "sha256sum -c SHA256SUMS.txt", "LEFT USB-C port", "Docker is NOT required"):
assert needle in txt, f"FLASH-INSTRUCTIONS.txt missing {needle!r}"
# Extract with unzip to verify preserved executable bits, SHA256SUMS, and flasher launch
ext_dir = os.path.join(tmp, "extracted")
os.makedirs(ext_dir, exist_ok=True)
subprocess.run(["unzip", "-q", out_zip, "-d", ext_dir], check=True)
rel_dir = os.path.join(ext_dir, top)
subprocess.run(["sha256sum", "-c", "SHA256SUMS.txt"], cwd=rel_dir, check=True, stdout=subprocess.DEVNULL)
ext_env = dict(os.environ)
if os.path.isdir(FLASH_DEPS):
ext_env["PYTHONPATH"] = FLASH_DEPS
hres = subprocess.run(
["./flash-mtk.sh", "--help"],
cwd=rel_dir, env=ext_env, capture_output=True, text=True, check=False,
)
assert hres.returncode == 0, f"Extracted flash-mtk.sh --help failed:\n{hres.stdout}\n{hres.stderr}"
sanitized_img = os.path.join(rel_dir, "images", "geminux-rootfs.img")
assert subprocess.run(["e2fsck", "-fn", sanitized_img], capture_output=True).returncode == 0
fw_mod = flash_mtk.load_firmware_module()
assert fw_mod.debugfs_ls(sanitized_img, "lib/firmware/mediatek/mt6797") == []
assert [n for n, _m in pkg_mod._debugfs_ls_details(sanitized_img, "etc/ssh") if n.startswith("ssh_host_")] == []
assert "sshd_config" in fw_mod.debugfs_ls(sanitized_img, "etc/ssh")
assert not fw_mod._debugfs_path_exists(sanitized_img, "/root/.ssh/authorized_keys")
assert not fw_mod._debugfs_path_exists(sanitized_img, "/home/user/.ssh/authorized_keys")
print("[PASS] Release ZIP packager (sanitized rootfs, FLASH-INSTRUCTIONS.txt, SHA256SUMS, runnable flasher) verified")
def test_cli_help(): def test_cli_help():
res = subprocess.run( res = subprocess.run(
[os.path.join(BASE_DIR, "flash-mtk.sh"), "--help"], [os.path.join(BASE_DIR, "flash-mtk.sh"), "--help"],
@@ -744,6 +948,7 @@ def test_cli_help():
"--flash-full", "--flash-full",
"--flash-rootfs-only", "--flash-rootfs-only",
"--customize-rootfs", "--customize-rootfs",
"--skip-firmware-inject",
"--username", "--username",
"--user-password", "--user-password",
"--ask-user-password", "--ask-user-password",
@@ -773,6 +978,8 @@ def main():
test_sha512_crypt_and_username_validation() test_sha512_crypt_and_username_validation()
test_account_customization_ext4() test_account_customization_ext4()
test_luks2_encryption_offline() test_luks2_encryption_offline()
test_firmware_injection_ext4()
test_release_zip_packager()
test_cli_help() test_cli_help()
+34
View File
@@ -723,6 +723,40 @@ def main():
if '"/sys/power/state", "freeze"' in trig_src: if '"/sys/power/state", "freeze"' in trig_src:
raise AssertionError("trigger_suspend must not fall back to s2idle freeze") raise AssertionError("trigger_suspend must not fall back to s2idle freeze")
powerd_path = os.path.join(
os.path.dirname(APPS_DIR), "geminux-daemons", "geminux-powerd.c"
)
with open(powerd_path, "r", encoding="utf-8") as handle:
powerd_dpms_src = handle.read()
for needle in (
"wake_x11_display_dpms",
"DPMSForceLevel",
"DPMSModeOn",
"XResetScreenSaver",
"poll(&pf, 1, 1800)",
):
if needle not in powerd_dpms_src:
raise AssertionError(f"geminux-powerd.c missing expected DPMS/lock sync token: {needle}")
tb_start = powerd_dpms_src.find("static void toggle_backlight")
tb_end = powerd_dpms_src.find("\nstatic ", tb_start + 1)
tb_src = powerd_dpms_src[tb_start:tb_end]
if "wake_x11_display_dpms()" not in tb_src:
raise AssertionError("toggle_backlight must invoke wake_x11_display_dpms() when waking display")
lock_path = os.path.join(APPS_DIR, "geminux-lock.c")
with open(lock_path, "r", encoding="utf-8") as handle:
lock_src = handle.read()
for needle in ("publish_lock_ready", "_GEMINUX_LOCK_READY", "XSync"):
if needle not in lock_src:
raise AssertionError(f"geminux-lock.c missing expected readiness token: {needle}")
ot_start = lock_src.find("static void on_timer")
ot_end = lock_src.find("\nstatic ", ot_start + 1)
ot_src = lock_src[ot_start:ot_end]
grab_idx = ot_src.find("gemui_grab_input")
pub_idx = ot_src.find("publish_lock_ready")
if grab_idx < 0 or pub_idx < 0 or grab_idx > pub_idx:
raise AssertionError("geminux-lock.c on_timer must attempt gemui_grab_input before publish_lock_ready")
with open(os.path.join(APPS_DIR, "geminux-control.c"), "r", encoding="utf-8") as handle: with open(os.path.join(APPS_DIR, "geminux-control.c"), "r", encoding="utf-8") as handle:
ctrl_src = handle.read() ctrl_src = handle.read()
if "st->bl_path" not in ctrl_src or "flush_vol_helper(" not in ctrl_src: if "st->bl_path" not in ctrl_src or "flush_vol_helper(" not in ctrl_src:
+39 -12
View File
@@ -10,6 +10,7 @@
#include <sys/wait.h> #include <sys/wait.h>
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
#include <X11/Xatom.h>
#define HIT_UNLOCK 1 #define HIT_UNLOCK 1
#define HIT_CLEAR 2 #define HIT_CLEAR 2
@@ -24,7 +25,10 @@ typedef struct {
int last_yday; int last_yday;
int timer_ms; int timer_ms;
int ready_fd; int ready_fd;
int ready_wait_ms;
bool grabbed; bool grabbed;
bool drawn;
bool ready_published;
bool checking; bool checking;
} lock_state_t; } lock_state_t;
@@ -99,25 +103,45 @@ static void attempt_unlock(lock_state_t *st) {
gemui_request_redraw(st->app); gemui_request_redraw(st->app);
} }
static void on_timer(gemui_app_t *app, void *ud) { static void publish_lock_ready(lock_state_t *st) {
lock_state_t *st = ud; if (!st->ready_published) {
Display *dpy = gemui_display(st->app);
Window win = gemui_window(st->app);
if (dpy && win) {
Atom ready_atom = XInternAtom(dpy, "_GEMINUX_LOCK_READY", False);
unsigned long val = 1UL;
XChangeProperty(dpy, win, ready_atom, XA_CARDINAL, 32, PropModeReplace,
(const unsigned char *)&val, 1);
XSync(dpy, False);
}
st->ready_published = true;
}
if (st->ready_fd >= 0) { if (st->ready_fd >= 0) {
ssize_t wr = write(st->ready_fd, "1", 1); ssize_t wr = write(st->ready_fd, "1", 1);
(void)wr; (void)wr;
close(st->ready_fd); close(st->ready_fd);
st->ready_fd = -1; st->ready_fd = -1;
int next_ms = st->grabbed ? 15000 : 250;
if (st->timer_ms != next_ms) {
st->timer_ms = next_ms;
gemui_set_timer_ms(app, next_ms, on_timer, st);
}
} }
}
static void on_timer(gemui_app_t *app, void *ud) {
lock_state_t *st = ud;
if (!st->grabbed) { if (!st->grabbed) {
st->grabbed = gemui_grab_input(app); st->grabbed = gemui_grab_input(app);
if (st->grabbed && st->timer_ms != 15000) { }
st->timer_ms = 15000; if (st->ready_fd >= 0) {
gemui_set_timer_ms(app, 15000, on_timer, st); st->ready_wait_ms += st->timer_ms;
if ((st->drawn && (st->grabbed || st->ready_wait_ms >= 600)) ||
st->ready_wait_ms >= 1500) {
publish_lock_ready(st);
} }
} else if (!st->ready_published && st->drawn && st->grabbed) {
publish_lock_ready(st);
}
int next_ms = (st->ready_fd >= 0) ? 25 : (st->grabbed ? 15000 : 250);
if (st->timer_ms != next_ms) {
st->timer_ms = next_ms;
gemui_set_timer_ms(app, next_ms, on_timer, st);
} }
char prev_bat[96]; char prev_bat[96];
snprintf(prev_bat, sizeof(prev_bat), "%s", st->bat_text); snprintf(prev_bat, sizeof(prev_bat), "%s", st->bat_text);
@@ -134,6 +158,7 @@ static void on_timer(gemui_app_t *app, void *ud) {
static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) {
lock_state_t *st = ud; lock_state_t *st = ud;
st->drawn = true;
const gemui_theme_t *t = gemui_theme(app); const gemui_theme_t *t = gemui_theme(app);
gemui_fill_rect(cr, (gemui_rect_t){0, 0, w, h}, t->bg_main); gemui_fill_rect(cr, (gemui_rect_t){0, 0, w, h}, t->bg_main);
@@ -242,10 +267,12 @@ int main(void) {
gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr };
gemui_set_handlers(st.app, &h, &st); gemui_set_handlers(st.app, &h, &st);
/* Signal readiness after the first on_draw + XFlush completes on Xorg. */ /* Signal readiness after first draw + input grab completes on Xorg. */
st.timer_ms = (st.ready_fd >= 0) ? 20 : (st.grabbed ? 15000 : 250); st.timer_ms = (st.ready_fd >= 0) ? 25 : (st.grabbed ? 15000 : 250);
gemui_set_timer_ms(st.app, st.timer_ms, on_timer, &st); gemui_set_timer_ms(st.app, st.timer_ms, on_timer, &st);
int rc = gemui_run(st.app); int rc = gemui_run(st.app);
volatile unsigned char *pw_wipe = (volatile unsigned char *)st.password;
for (size_t i = 0; i < sizeof(st.password); i++) pw_wipe[i] = 0;
gemui_ungrab_input(st.app); gemui_ungrab_input(st.app);
gemui_destroy(st.app); gemui_destroy(st.app);
return rc; return rc;
+3 -1
View File
@@ -7,6 +7,8 @@ KERNEL_INC ?= ../../prebuilt/kernel/include
CFLAGS += -std=c11 -Wall -Wextra -O2 -I. -I$(KERNEL_INC) CFLAGS += -std=c11 -Wall -Wextra -O2 -I. -I$(KERNEL_INC)
X11_CFLAGS = $(shell $(PKG_CONFIG) --cflags x11) X11_CFLAGS = $(shell $(PKG_CONFIG) --cflags x11)
X11_LIBS = $(shell $(PKG_CONFIG) --libs x11) X11_LIBS = $(shell $(PKG_CONFIG) --libs x11)
X11_EXT_CFLAGS = $(shell $(PKG_CONFIG) --cflags x11 xext)
X11_EXT_LIBS = $(shell $(PKG_CONFIG) --libs x11 xext)
XTOUCH_CFLAGS = $(shell $(PKG_CONFIG) --cflags x11 xi xtst) XTOUCH_CFLAGS = $(shell $(PKG_CONFIG) --cflags x11 xi xtst)
XTOUCH_LIBS = $(shell $(PKG_CONFIG) --libs x11 xi xtst) -lm XTOUCH_LIBS = $(shell $(PKG_CONFIG) --libs x11 xi xtst) -lm
GIO_CFLAGS = $(shell $(PKG_CONFIG) --cflags gio-2.0 glib-2.0 gobject-2.0) GIO_CFLAGS = $(shell $(PKG_CONFIG) --cflags gio-2.0 glib-2.0 gobject-2.0)
@@ -36,7 +38,7 @@ BINS = \
all: $(BINS) all: $(BINS)
geminux-powerd: geminux-powerd.c geminux-power-policy.c geminux-power-policy.h geminux-powerd: geminux-powerd.c geminux-power-policy.c geminux-power-policy.h
$(CC) $(CFLAGS) -o $@ geminux-powerd.c geminux-power-policy.c $(CC) $(CFLAGS) $(X11_EXT_CFLAGS) -o $@ geminux-powerd.c geminux-power-policy.c $(X11_EXT_LIBS)
geminux-power-ctl: geminux-power-ctl.c geminux-power-ctl: geminux-power-ctl.c
$(CC) $(CFLAGS) -o $@ $< $(CC) $(CFLAGS) -o $@ $<
+67 -2
View File
@@ -24,6 +24,8 @@
#include <sys/wait.h> #include <sys/wait.h>
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
#include <X11/Xlib.h>
#include <X11/extensions/dpms.h>
#define SOCK_PATH "/run/geminux/powerd.sock" #define SOCK_PATH "/run/geminux/powerd.sock"
#define PROFILE_FILE "/run/geminux/power-profile" #define PROFILE_FILE "/run/geminux/power-profile"
@@ -242,6 +244,7 @@ static void refresh_ac_and_hdmi(powerd_ctx_t *ctx) {
} }
static void lock_x11_session(void); static void lock_x11_session(void);
static void wake_x11_display_dpms(void);
static void trigger_suspend(powerd_ctx_t *ctx); static void trigger_suspend(powerd_ctx_t *ctx);
static void restore_cpus_after_resume(powerd_ctx_t *ctx); static void restore_cpus_after_resume(powerd_ctx_t *ctx);
static void exit_low_power_standby(powerd_ctx_t *ctx); static void exit_low_power_standby(powerd_ctx_t *ctx);
@@ -258,7 +261,10 @@ static void save_active_brightness(powerd_ctx_t *ctx, const char *bri_path) {
static void toggle_backlight(powerd_ctx_t *ctx, bool on) { static void toggle_backlight(powerd_ctx_t *ctx, bool on) {
DIR *d = opendir("/sys/class/backlight"); DIR *d = opendir("/sys/class/backlight");
if (!d) return; if (!d) {
if (on) wake_x11_display_dpms();
return;
}
struct dirent *de; struct dirent *de;
while ((de = readdir(d)) != NULL) { while ((de = readdir(d)) != NULL) {
if (de->d_name[0] == '.') continue; if (de->d_name[0] == '.') continue;
@@ -279,6 +285,7 @@ static void toggle_backlight(powerd_ctx_t *ctx, bool on) {
break; break;
} }
closedir(d); closedir(d);
if (on) wake_x11_display_dpms();
} }
static void dim_backlight(powerd_ctx_t *ctx) { static void dim_backlight(powerd_ctx_t *ctx) {
@@ -528,10 +535,65 @@ static void lock_x11_session(void) {
waitpid(pid, NULL, 0); waitpid(pid, NULL, 0);
struct pollfd pf = { .fd = pfd[0], .events = POLLIN }; struct pollfd pf = { .fd = pfd[0], .events = POLLIN };
poll(&pf, 1, 500); poll(&pf, 1, 1800);
close(pfd[0]); close(pfd[0]);
} }
/* Force X11 DPMS On and reset the X11 screen saver inside a double-forked,
* privilege-dropped child so XIOError or display restarts never affect root
* powerd, and external HDMI/client DPMS states always wake across S3/lid. */
static void wake_x11_display_dpms(void) {
pid_t pid = fork();
if (pid < 0) return;
if (pid == 0) {
pid_t grand = fork();
if (grand < 0) _exit(1);
if (grand > 0) _exit(0);
unblock_signals();
setsid();
int devnull = open("/dev/null", O_RDWR);
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
dup2(devnull, STDOUT_FILENO);
dup2(devnull, STDERR_FILENO);
if (devnull > STDERR_FILENO) close(devnull);
}
struct passwd *pw = getpwnam("user");
uid_t uid = (pw && pw->pw_uid > 0) ? pw->pw_uid : 10000;
gid_t gid = (pw && pw->pw_gid > 0) ? pw->pw_gid : 10000;
const char *home = (pw && pw->pw_dir && pw->pw_dir[0]) ? pw->pw_dir : "/home/user";
if (setgid(gid) != 0) _exit(1);
if (setuid(uid) != 0) _exit(1);
setenv("HOME", home, 1);
setenv("DISPLAY", ":0", 1);
char xauth[512];
snprintf(xauth, sizeof(xauth), "%s/.Xauthority", home);
setenv("XAUTHORITY", xauth, 1);
Display *dpy = XOpenDisplay(":0");
if (!dpy) _exit(0);
int ev_base = 0, err_base = 0;
if (DPMSQueryExtension(dpy, &ev_base, &err_base) && DPMSCapable(dpy)) {
CARD16 power_level = DPMSModeOn;
BOOL dpms_enabled = False;
if (DPMSInfo(dpy, &power_level, &dpms_enabled) &&
dpms_enabled && power_level != DPMSModeOn) {
DPMSForceLevel(dpy, DPMSModeOn);
}
}
XResetScreenSaver(dpy);
XSync(dpy, False);
XCloseDisplay(dpy);
_exit(0);
}
waitpid(pid, NULL, 0);
}
static int run_cmd_sync(const char *const argv[]) { static int run_cmd_sync(const char *const argv[]) {
pid_t pid = fork(); pid_t pid = fork();
if (pid < 0) return -1; if (pid < 0) return -1;
@@ -1533,6 +1595,9 @@ int main(void) {
} }
} }
if (ctx.idle_stage != IDLE_STAGE_ACTIVE && !ctx.policy.lid_closed) {
toggle_backlight(&ctx, true);
}
save_fuel_gauge_state(&ctx); save_fuel_gauge_state(&ctx);
unlink(SOCK_PATH); unlink(SOCK_PATH);
close(ctx.epfd); close(ctx.epfd);