5 Commits 75e0dc9ead ... 6b7600b448

Autor SHA1 Mensaje Fecha
  Johannes Zellner 6b7600b448 init: PID-1 service manager and parent-death process tree hace 1 día
  Johannes Zellner 15a0c3e30c sched: account the BSP tick with the period it covered hace 2 días
  Johannes Zellner 2fa060e0ee acpi: reset via the FADT RESET_REG on UEFI reboot hace 2 días
  Johannes Zellner ccb4fdc5ba rootfs: raise the compressed pack cap to 4 MB and reloads to 8 MB hace 2 días
  Johannes Zellner 0c0473ea82 browser: reliable tooltips, opacity, transitions and modal stacking hace 2 días
Se han modificado 50 ficheros con 3428 adiciones y 267 borrados
  1. 202 58
      AGENTS.md
  2. 22 3
      Makefile
  3. 1 1
      boot/efi/main.c
  4. 5 1
      boot/vesa_stage.S
  5. 6 4
      docs/boot.html
  6. 14 3
      docs/cpu.html
  7. 2 2
      docs/development.html
  8. 21 11
      docs/graphics.html
  9. 6 1
      docs/index.html
  10. 1 1
      docs/memory.html
  11. 0 0
      docs/network.html
  12. 112 10
      docs/userland.html
  13. 22 5
      include/syscall.h
  14. 43 0
      kernel/acpi.c
  15. 4 0
      kernel/acpi.h
  16. 71 0
      kernel/init.c
  17. 16 0
      kernel/init.h
  18. 14 4
      kernel/io.c
  19. 12 6
      kernel/kernel.c
  20. 3 1
      kernel/kexec.h
  21. 1 1
      kernel/payload.c
  22. 80 4
      kernel/process.c
  23. 10 0
      kernel/process.h
  24. 38 5
      kernel/reboot.c
  25. 12 5
      kernel/sched.c
  26. 31 3
      kernel/syscall.c
  27. 44 4
      kernel/tty.c
  28. 5 2
      kernel/tty.h
  29. 33 74
      kernel/wm.c
  30. 0 1
      kernel/wm.h
  31. 1 1
      tools/netkexec_send.c
  32. 395 25
      user/apps/browser/browser.c
  33. 217 18
      user/apps/browser/browser_html.c
  34. 15 0
      user/apps/browser/browser_html.h
  35. 4 0
      user/apps/browser/ucmd_browser.c
  36. 1 1
      user/apps/chat/ucmd_chat.c
  37. 1 1
      user/apps/disks/ucmd_disks.c
  38. 4 4
      user/apps/files/ucmd_files.c
  39. 2 0
      user/apps/gallery/ucmd_gallery.c
  40. 634 0
      user/apps/init/ucmd_init.c
  41. 1 1
      user/apps/netmenu/ucmd_netmenu.c
  42. 80 4
      user/apps/process/ucmd_process.c
  43. 12 0
      user/apps/service/service_defs.c
  44. 291 0
      user/apps/service/service_proto.c
  45. 807 0
      user/apps/service/ucmd_service.c
  46. 4 1
      user/apps/term/ucmd_term.c
  47. 1 1
      user/apps/wifi/ucmd_wifi.c
  48. 1 0
      user/apps/wm/ucmd_wm.c
  49. 73 0
      user/service_proto.h
  50. 53 0
      user/ucmd_lib.h

+ 202 - 58
AGENTS.md

@@ -13,8 +13,8 @@ Targets i586 (first-gen Pentium); runs under QEMU or on real hardware.
 | `kernel/` | The kernel, its drivers and services, `kernel.ld`, `ap_tramp.*`, `kexec_tramp.S`, `irqret.inc`; host tests `ccmp_test.c`, `touchpad_gesture_test.c` |
 | `common/` | Freestanding code linked into both kernel and userland: `inflate.c/h`, `font_8x16.c/h` |
 | `include/` | ABI headers shared by boot, kernel, userland and host tools: `syscall.h`, `wm_abi.h`, `version.h`, `bootinfo.h`, `phys.h`, `rootfs.h`, `wifi_cfg.h`, `rtl8821a_tbl.h` |
-| `user/` | `ucmd_lib.h` (the ring-3 syscall wrappers) and `ucmd.ld` |
-| `user/apps/<name>/` | One ring-3 program per directory: entry file `ucmd_<name>.c` plus private modules (`browser/` holds `browser.c`, `browser_html.c`, `js_*.c`, `svg_raster.c`; `chat/` holds `chat_login.c`; `gallery/` holds the real `gallery.c` behind the `ucmd_gallery.c` launcher; `hello/` has its own `hello.ld`) |
+| `user/` | `ucmd_lib.h` (the ring-3 syscall wrappers), `service_proto.h` (the init/service protocol and unit table) and `ucmd.ld` |
+| `user/apps/<name>/` | One ring-3 program per directory: entry file `ucmd_<name>.c` plus private modules (`browser/` holds `browser.c`, `browser_html.c`, `js_*.c`, `svg_raster.c`; `chat/` holds `chat_login.c`; `gallery/` holds the real `gallery.c` behind the `ucmd_gallery.c` launcher; `init/` is the PID-1 service manager; `service/` holds the CLI/GUI client and its shared `service_defs.c`/`service_proto.c`; `hello/` has its own `hello.ld`) |
 | `user/lib/<lib>/` | Ring-3 libraries: `libc`, `ngui`, `ufont`, `img`, `tls` (crypto incl. `wpa_crypto.c`), `uhttp`, `ujson`, `uwm` (`uwm_lib.c`), `wifi` (`wifi_store.c`, `wpa.c`); host tests live next to their library |
 | `tools/` | Host tools (`mkpack.c`, `mkrootfs.c`, `mkrtwtbl.c`, `mkcursors.c`, `mkicons.c`, `jsstrip.c`, `mkwoff.py`, `kexec_send.c`, `netkexec_send.c`, `netmonitor.c`, `flash.sh`, `xcursor_trim.py`), the QMP test scripts and `cursor_test.c` |
 | `assets/` | Imported assets: `assets/cursors/adwaita/` (the Adwaita 24 px Xcursor files) and `assets/icons/adwaita/` (the Adwaita symbolic SVGs used as UI icons), both LGPL-3 / CC-BY-SA-3.0, with README and licences |
@@ -57,7 +57,7 @@ this file **and** the matching page:
 | `docs/filesystems.html` | VFS/`fs_ops`, FAT, ramfs pack, `/share`, WebDAV |
 | `docs/graphics.html` | VBE/shadow, damage, blit, WM, canvas ABI, ngui, images |
 | `docs/network.html` | netdev, ARP/ICMP/UDP/DHCP/DNS, TCP, TLS, netconsole/netkexec |
-| `docs/userland.html` | Ring-3 model, ELF spawn, syscalls, shell/PATH, pack, apps |
+| `docs/userland.html` | Ring-3 model, ELF spawn and parent/detach, syscalls, init/services, shell/PATH, pack, apps |
 | `docs/development.html` | Toolchain, make targets, hot reload, tests, debugging |
 
 Rules:
@@ -130,7 +130,7 @@ make clean
 - Build flags (in `Makefile`): `-m32 -march=i586 -ffreestanding -fno-pie -nostdlib
   -fno-stack-protector -mno-sse -mno-sse2 -mno-mmx -O2`.  The ring-3 WM and
   viewer are per-object `-Os` with function sections, like the other size-
-  sensitive GUIs, because the 2 MB gzip rootfs pack is close to its cap.
+  sensitive GUIs, to keep the gzip rootfs pack small (its cap is 4 MB).
 - `make browser-host` is a development-only harness, not part of the images: it
   builds `browser.c`, ngui, the image/TLS stack and QuickJS as a 32-bit Linux
   program against the same `SYS_*` ABI (`host/syscall.c`, an SDL3 window,
@@ -154,9 +154,11 @@ make clean
   `cmds-lite.pack` (everything but `firmware/*`, the cursor bundle,
   `install/kernel.bin` and `bin/browser.app`), because the ~1 MB WiFi
   firmware and the ~500 KB gzip browser do not fit a 1.44 MB floppy; a
-  floppy boot runs the browser from `BROWSER` on `root.img`.  The kernel itself no longer
-  carries the pack; the boot path loads it into RAM and `ramfs_init` takes a
-  private copy (`bin/<name>` mounted at `/ramfs`).
+  floppy boot runs the browser from `BROWSER` on `root.img`.  `bin/init` and
+  `bin/service` are in **both** packs; the current lite gzip pack is ~682 KB
+  and the floppy image still has ~390 KB of internal padding.  The kernel
+  itself no longer carries the pack; the boot path loads it into RAM and
+  `ramfs_init` takes a private copy (`bin/<name>` mounted at `/ramfs`).
 - The WiFi firmware `firmware/iwlwifi-7265D-29.ucode` (Chromebook) and
   `firmware/iwlwifi-6000-4.ucode` (ThinkPad X201) are decompressed from the
   host's linux-firmware (`WIFI_FW_7265D` / `WIFI_FW_6000` override the
@@ -228,7 +230,8 @@ and `make net-dev`/`kernel-net-dev` reload over the network.  `bootlog save
    12-dword `struct boot_info` (magic/checksum/rsdp/flags/pack range) to
    `0x500`, enters protected mode and jumps to `kernel_entry` (`entry.S`,
    re-points ESP to the current stack top, then `kernel_main`).  The pack
-   never occupies the low gap, so the cap is `PACK_MAX` (2 MB) and the
+   never occupies the low gap, so the cap is `PACK_MAX` (4 MB, copied to
+   `0x900000..0xD00000`) and the
    kernel BSS/boot stack may extend past `0x60000`.  The stage prints
    `Loading rootfs [d=<drive> lba=<hex> e=<0|1> m=<C|L>]...`, then a dot
    after the header and one per 16 KB chunk, so a BIOS hang is localised.
@@ -237,8 +240,9 @@ and `make net-dev`/`kernel-net-dev` reload over the network.  `bootlog save
 3. `kernel.c` — `kernel_main` zeroes BSS then inits serial → memory/paging →
    ACPI/MADT → I/O → power → idle → processes → timer (PIT; 1 kHz busy,
    100 Hz idle + IDT) → SMP AP bring-up → PS/2 mouse (the I2C touchpad
-   probe only on Airmont) → VGA shadow buffer → ramfs inflate → WM →
-   publish `vfs_scan_busy` → `wm_server_boot_ready()` → wait (idle `hlt`,
+   probe only on Airmont) → VGA shadow buffer → ramfs inflate →
+   `wm_server_init()` → start `/ramfs/bin/init` as PID 1 → init spawns the
+   WM → publish `vfs_scan_busy` → `wm_server_boot_ready()` → wait (idle `hlt`,
    1 s cap) until the first terminal has presented → USB bring-up and scan
    (non-preemptible, as before the WM existed: reset/SOF timing) → NIC probe
    → kworker → the `bootscan` kernel thread (non-USB storage scan + FAT
@@ -252,7 +256,9 @@ and `make net-dev`/`kernel-net-dev` reload over the network.  `bootlog save
    first terminal presents (the bootscan window is not counted): the end
    point of a boot-time measurement
    (~0.5-0.6 s after the kernel starts on QEMU's USB image; the bootscan
-   window is created first).
+   window is created first).  The kernel never starts the WM: init is the
+   only creator, and `wm_server_attach` admits an init child named `wm`.
+   Without `/ramfs/bin/init` there is no WM; the boot console stays visible.
 4. `mbr.S` — MBR (USB/HDD boot); loads the active partition's boot sector
    (partition 1 at LBA 63).
 5. **UEFI (`boot/efi/`)** — an x86-64 PE32+ `BOOTX64.EFI` loads from the ESP. It
@@ -293,7 +299,7 @@ a Pentium 1 (and a Pentium II board without ACPI) on the UP path.
 | `0x60000` | No longer a rootfs staging area: the legacy stage copies each 16 KB chunk straight to `0x900000`.  The kernel BSS/boot stack may use this range |
 | `_end`    | Kernel end (linker symbol; `kernel.ld` keeps `_end <= 0x90000` so the top of the low-memory gap and the EBDA stay untouched).  BSS and the boot stack may extend past `0x60000` |
 | (in-image) | Bootstrap/protected-mode stack: 8 KB `.stack` NOLOAD section, `__boot_stack_top`/`__boot_stack_bottom` (travels with the kernel) |
-| `0x900000`| Legacy boot-time rootfs pack written directly by `vesa_stage.S` (reserved by `mm_init` until `ramfs_init` takes its copy, then freed); `mm_init` places the frame bitmap in the first RAM after it (`0xAF3000` with today's pack); process stacks and kexec staging also start here |
+| `0x900000`| Legacy boot-time rootfs pack written directly by `vesa_stage.S` (reserved by `mm_init` until `ramfs_init` takes its copy, then freed); `mm_init` places the frame bitmap in the first RAM after it (`0xB08000` with today's ~2.13 MB pack, at most `0xD00000`; the `mm: bitmap ...` boot line reports the actual address); process stacks and kexec staging also start here |
 | `0x100000`| VGA shadow buffer (`VGA_SHADOW_BASE`, `vga.h`) |
 
 The legacy stage uses `0x3000..0x6FFF` as a 16 KB-chunk rootfs staging
@@ -348,12 +354,47 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   is the only global-tick source.  APs do not start taking user work until
   `smp_enable_sched()`, i.e. after device/FS setup.  LAPIC IPIs (vector 0x31)
   request a reschedule; they must be EOIed on the target LAPIC.
-  `SYS_PROCINFO` exposes weight/state/CPU/ticks and the `kernel_thread` flag
-  for the ring-3 `top` and `process` commands, and `sched`/`renice` plus
-  `SYS_SCHEDINFO` expose the scheduler counters.
+  `SYS_PROCINFO` exposes pid/parent_pid, weight/state/CPU/ticks, pages and
+  the `kernel_thread` flag for the ring-3 `top` and `process` commands, and
+  `sched`/`renice` plus `SYS_SCHEDINFO` expose the scheduler counters.
   Ring 0 is preemptible at tick boundaries unless `preempt_count` is set (FAT
   and the shadow flush) or the BKL is held; voluntary blocks/yields go through
   the `int 0x81` gate.
+  Every PCB carries `parent_pid` (0 = root).  `process_exit()`,
+  `process_kill()` and the reaper kill the whole descendant subtree; a
+  child born while its parent dies is aborted.  `SYS_SPAWN` has a flags word:
+  the default parents the child to the caller, `SYS_SPAWN_DETACH` attaches it
+  to the caller's parent (the terminal/WM session), or to 0 if that parent is
+  gone.  `init` and kernel threads are roots; the WM and services are init's
+  children, the terminal/start-menu apps are the WM's, and terminal commands
+  are the terminal's.  `SYS_SPAWN_KCMD` stays parented.  The process monitor's
+  End task kills the subtree.
+- **Init and services**: `kernel/init.c/h` loads `/ramfs/bin/init` as PID 1
+  after `wm_server_init()` and before the WM.  It records `init_pid` inside
+  `process_create_user_full()` before the process is runnable, refuses
+  `SYS_KILL(init)`, and the kworker restarts init if it dies.  The ring-3
+  manager (`user/apps/init/ucmd_init.c`) is the only WM creator: it
+  `SYS_SPAWN`s `/ramfs/bin/wm`, monitors it, and respawns it after a crash.
+  It owns one private tty per running service, drains it to
+  `/share/svc-<name>.log` (32 KB), and writes `/share/svc-<name>.state`.
+  `/share/init.state` carries its pid/control tty/WM pid; `/share/init.log`
+  is its own log.  `init` serves a small line protocol on a tty allocated
+  with `SYS_TTY_ALLOC`; the `service` CLI/GUI (`user/apps/service/`) sends
+  `NBI1 <seq> <op> <name> <resp_tty>` and reads the response tty.  The
+  shared table/protocol lives in `user/service_proto.h`,
+  `user/apps/service/service_defs.c` and `service_proto.c`.  Service starts,
+  stops, restarts and kills are init's state machine; a service that exits
+  unexpectedly is marked stopped (no v1 auto-restart), while the WM is
+  restart-on-death.  On init restart it first kills every leftover ring-3
+  process (kernel threads stay), then starts the WM and the services whose
+  saved desired state is running.  The control syscalls are
+  `SYS_TTY_ALLOC` (tty owned by the caller, no stdout rebind),
+  `SYS_TTY_WRITE` (non-blocking, no partial writes), `SYS_TTY_CLOSE` (owner)
+  and `SYS_IS_INIT`; `TTY_MAX` is 16.  The first service is `websrv`
+  (`/ramfs/bin/websrv 8080`, autostart off: it owns the raw NIC receiver, so
+  stop it before browsing/`curl`/`net-dev`).  `service logs init|websrv`,
+  `service logtail`, `service --gui` and `service status` are the user
+  tools; `bootscan` is a kernel thread/log viewer, not a service.
 - **SMP / ACPI**: `acpi.c/h` (RSDP → RSDT/XSDT → MADT; CPU/LAPIC and IOAPIC
   base lists; 4 MB table page mapping; the FADT PM1 control blocks, flags and
   the DSDT (or SSDT) `\_S5` sleep types; malformed tables are ignored),
@@ -390,7 +431,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   (both hand the kernel the same ACPI tables); the Bochs/QEMU ports are
   only the emulator fallback.  If no path works the command returns instead
   of halting: the WM shows `poweroff failed` and the FADT/S5/`SCI_EN` state
-  is in the netlog.
+  is in the netlog.  `acpi_reset()` caches and writes the ACPI 2.0
+  `RESET_REG`/`RESET_VALUE` pair (`RESET_REG_SUP`), and is what `reboot`
+  tries before the Intel PCH, keyboard-controller and triple-fault
+  fallbacks.
 - **Memory**: `phys.h` — `MM_MAX_PHYS` (1 GB, the lowmem/identity-map
   ceiling, also used by the UEFI loader for the pack buffer), `MM_KMAP_VA`
   (`0x4FC00000`) and `MM_HIGH_LIMIT` (4 GB).  Lowmem ends where ring-3 space
@@ -491,7 +535,13 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `uwm_lib.c`).  The kernel maps the shadow and each window's RGB565 front
   canvas at `WM_CONTENT_VA_BASE`, routes input, owns the cursor, kexec
   detection and the boot-console handoff.  Every window is a canvas client;
-  there is no in-kernel WM or terminal fallback.  The WM paints the desktop,
+  there is no in-kernel WM or terminal fallback.  Init is the only WM
+  creator (`SYS_SPAWN("/ramfs/bin/wm")`); the kernel never starts one.
+  `wm_server_attach` admits only a process named `wm` whose `parent_pid` is
+  the current init pid, cleans up a dead previous WM, maps the shadow and
+  disables the boot console.  If init or `/ramfs/bin/wm` is absent the boot
+  console stays; there is no fallback.  The WM watchdog still kills a wedged
+  WM (`wm_last_seen` > 15 s) and init respawns it.  The WM paints the desktop,
   spawns the `/ramfs/bin/bootscan` live-log window first and only then the
   first terminal after `wm_server_boot_ready()`, so the terminal is the
   newest window and keeps the keyboard focus on startup, and composites the
@@ -557,9 +607,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   first row is the dim `Applications` caption, `theme.panel_alt` hover rows
   and a rounded Power tile.  It lists every self-contained GUI app in the
   pack -- Terminal, Files, Web, Gallery, Chat, Clock, Text editor, Colors,
-  Mines, Cards, Disks, Tasks, Settings and Date & Time -- with a coloured
-  letter tile and a hover highlight, shrinks its row height to fit short
-  panels, and closes on an outside press.  The last row, Power, opens a
+  Mines, Cards, Disks, Tasks, Services, Settings and Date & Time -- with a
+  coloured letter tile and a hover highlight, shrinks its row height to fit
+  short panels, and closes on an outside press.  The last row, Power, opens a
   submenu with Reboot and Power off; both spawn the privileged kernel
   command through `SYS_SPAWN_KCMD` with no tty.  The menu floats above every
   window and is redrawn with the brightness OSD overlay.  The bar notice and
@@ -604,8 +654,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   popover and then continues with the normal click handling; a second click
   on the status cluster toggles it.
   The start menu entries spawn the same pack binaries (`Chat` ->
-  `/ramfs/bin/chat`, `Tasks` -> `/ramfs/bin/process`, `Disks` ->
-  `/ramfs/bin/disks`, ...).  When the full date/time would cross
+  `/ramfs/bin/chat`, `Tasks` -> `/ramfs/bin/process`, `Services` ->
+  `/ramfs/bin/service --gui`, `Disks` -> `/ramfs/bin/disks`, ...).  When the full date/time would cross
   `WM_BAR_LEFT_END`, the clock falls back to `MM-DD HH:MM` and is hidden if
   even that does not fit.
   `terminal.c` keeps the privileged kernel command
@@ -1568,9 +1618,18 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   ELF through the VFS and spawns it as a ring-3 process; `hello` is just
   `bin/hello`.  New command: create `user/apps/<name>/ucmd_<name>.c` and add
   `<name>` to UCMDS — the pack, the mount and the PATH listing pick it up
-  automatically (a command that links libraries also needs an `.elf` rule).  `SYS_SPAWN` still
-  loads ELFs from any VFS mount, so commands can also live on `/share` or a
-  FAT disk (`path /share/bin`, or an absolute path).  They talk to the kernel through
+  automatically (a command that links libraries also needs an `.elf` rule).
+  `init` and `service` are in both packs; `init` is PID 1 and refuses a
+  user-run start through `SYS_IS_INIT`.
+  `SYS_SPAWN` still loads ELFs from any VFS mount, so commands can also live
+  on `/share` or a FAT disk (`path /share/bin`, or an absolute path).  Its
+  `struct sys_spawn` carries a flags word: default parented, or
+  `SYS_SPAWN_DETACH` to attach to the caller's parent (the session).  There
+  is deliberately no old-ABI compatibility: the kernel, pack, `root.img`,
+  UEFI payload and host harness must be rebuilt together.  The browser and
+  gallery launchers spawn the real app parented and wait for it, so a
+  terminal launch stays foreground and Ctrl-C/terminal close kills the app;
+  files/disks/chat and the WiFi helpers use detached spawns.  They talk to the kernel through
   `int 0x80` (`syscall.h`: putstr/ticks/sleep/exit, the whole-file service in
   `sys_fs.c`, the state snapshots in `sys_info.c` and the network service in
   `sys_net.c`) and inherit the terminal's screen, so their output lands in
@@ -1596,7 +1655,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   ELF ships in the pack as `bin/gallery.app`; `ucmd_gallery.c` is the tiny
   `bin/gallery` launcher, which prefers `/share/GALLERY` (development upload
   via `make gallery-dev`), then the pack copy, then the `GALLERY` disk
-  fallback on `root.img`/FAT mounts.
+  fallback on `root.img`/FAT mounts.  Like the browser launcher it spawns
+  the real app parented and waits for it.
 - **Boot scan window**: `ucmd_bootscan.c` is the `bootscan` window, a live
   tail of the `bootscan` kernel thread's own COM1 output.  `boot_storage_main()`
   calls `bootcon_scan_begin()`/`bootcon_scan_end()`; while active,
@@ -1621,12 +1681,15 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   histories of CPU busy (summed `SYS_SCHEDINFO` idle ticks over all CPUs),
   physical memory in use (`SYS_MEMINFO`) and NIC throughput (the 32-bit frame
   byte counters in `SYS_NET_INFO`).  Three cards draw the graphs with ngui
-  rectangles/lines; the process table below is sortable by PID, state, CPU,
-  memory, time or name (click a header) and scrolls with PgUp/PgDn or the
-  wheel.
-  Selecting a row shows its details; `End task` asks for a second click, then
-  calls `SYS_KILL`.  Kernel threads and the monitor itself are protected
-  (`sys_procinfo.kernel_thread`, `SYS_GETPID`).  Esc closes the window.
+  rectangles/lines; the process table is a tree: children are indented under
+  their `parent_pid`, while each sibling group stays sortable by PID, state,
+  CPU, memory, time or name (click a header).  PgUp/PgDn or the wheel
+  scrolls.
+  Selecting a row shows its pid/ppid and details; `End task` asks for a second
+  click, then
+  calls `SYS_KILL`, which also kills the process's descendants.  Kernel
+  threads and the monitor itself are protected (`sys_procinfo.kernel_thread`,
+  `SYS_GETPID`); init is protected in the kernel.  Esc closes the window.
 - **Solitaire**: `ucmd_solitaire.c` — a Windows 95 style Klondike game on the
   canvas service: green felt, a Game/Help menu (ngui buttons and menu items:
   new game, draw one/three, blue or red deck), four foundations, seven tableau
@@ -1644,8 +1707,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `ucmd_browser.c` is the tiny `bin/browser` launcher; it prefers
   `/share/BROWSER` (`make browser-dev` uploads it via the board's `websrv`;
   stop `websrv` before browsing HTTP, because it owns the NIC), then the pack
-  copy, then `BROWSER` on `root.img`/IDE/SATA fat mounts.  The launcher
-  forwards its argument and cwd.
+  copy, then the disk fallback; it spawns the real app parented and waits for
+  it, so a terminal launch stays foreground and Ctrl-C/terminal close kills
+  the app.  The launcher forwards its argument and cwd.
   `uhttp.c/h` is the shared ring-3 HTTP client extracted from curl: URL
   parsing/resolution (unsafe path bytes are percent-encoded; path
   normalization stops at `?`/`#`), redirects, chunked decoding, timeouts
@@ -2114,8 +2178,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   scripted page and whenever the page width changes.  A geometry read
   after a DOM change (`offsetWidth`, `getBoundingClientRect`, ...) runs a
   synchronous layout first (`js_force_layout()`: measure + render into the
-  page back buffer, at most 40 ms per 100 ms), like a browser's forced
-  reflow; `documentElement.clientWidth/Height` are the viewport.
+  page back buffer), like a browser's forced reflow.  The guard is a count
+  (`FORCE_LAYOUT_PER_PASS`, 8 per main-loop pass), not a time budget: on
+  the ION one cloudron.io re-layout takes longer than any sensible budget,
+  and a refused reflow left Bootstrap placing its tooltip from stale boxes.
+  `documentElement.clientWidth/Height` are the viewport.
   **Hover**: each frame the element under the pointer (`hover_target()`:
   the innermost box, or the link/control hit inside it) is compared with
   the last one, and `page_hover_events()` dispatches `mouseout`/
@@ -2128,7 +2195,33 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   An absolute/fixed box with an auto width and one horizontal offset is
   shrink-to-fit, absolute/fixed children add nothing to a parent's
   shrink-to-fit width and do not end a float row, and `<a href="">` is a
-  link to the page itself.  The logged-in
+  link to the page itself.  A fixed box pinned by `top` and `bottom` with
+  an auto height spans the viewport between them (a modal backdrop).
+  **Opacity and transitions**: `opacity` is a 0..255 alpha
+  (`br_style.opacity`; `opacity_hidden` is alpha 0).  A translucent
+  absolute/fixed box gets group opacity: the deferred painter saves the
+  page area (`alpha_begin()`), paints the box and blends it back over its
+  layout box (`alpha_end()`); in-flow elements still paint opaque.
+  `transition`/`transition-property|duration|timing-function` reduce to a
+  mask of opacity/transform, one duration and an easing (`tr_mask`,
+  `tr_ms`, `tr_ease`).  The render pass remembers each element's last
+  target opacity and `translate()` offset (`pstate[]`; `translate()` takes
+  percentages of the own box, `tx_pct`/`ty_pct`); a changed target on an
+  element with a matching transition starts an animation from the value on
+  screen (`anim_value()`, up to 32 at once), the page re-renders every
+  pass while one runs, and `transitionend` is dispatched when it ends
+  (`anim_after_frame()`); animations of elements no longer painted are
+  dropped.  The start value is whatever the previous paint saw, which is
+  why a forced reflow is a paint pass: Bootstrap reads `offsetWidth` after
+  showing the modal and before adding `.in`, so its backdrop fades in and
+  the dialog slides down.  **Stacking for input**: each painted
+  absolute/fixed box with a background or a `z-index` (and without
+  `pointer-events: none`, parsed and inherited as `pe_none`) adds an
+  occluder hit below its own link hits (`hit_add_occluder()`): links
+  painted under it stop matching (`find_hit_ex()`), and the box search for
+  clicks/hover is limited to the covering box's subtree, so a click on a
+  modal's backdrop reaches `.modal` (Bootstrap closes it) instead of the
+  page behind.  The logged-in
   dashboard (sidebar with expandable groups, header, app grid, hash-routed
   views) was verified in QEMU against a local stand-in that proxies the
   public dashboard assets and mocks `/api/v1` and the OIDC endpoints.  The
@@ -2360,7 +2453,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 `mkdir <path>`, `rmdir <path>`, `hello`, `acpidump` (writes the mapped
 DSDT to `/share/DSDT.BIN`), `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `bootscan` (the live boot storage-scan window), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), and `chat [config-path]` (Cloudron Chat client).
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `service [list|status <name>|start|stop|restart|kill <name>|logs <name>|logtail <name>|--gui]` (init's client; `websrv` is the first service and holds the raw NIC receiver while running), `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher; waits for the app so a terminal launch is foreground), and `chat [config-path]` (Cloudron Chat client).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `netdev [name]` (kernel command: show the active NIC driver or
@@ -2445,8 +2538,9 @@ The commands live in `cmds.pack` (`bin/<name>` entries, built by `mkpack`),
 compressed with `libdeflate-gzip -12` when it is installed (falling back to
 `gzip -9`) to `cmds_pack_gz.bin` and wrapped by `mkrootfs` with a
 one-sector `NBROOT1` header (magic, version, exact `pack_bytes`, checksum,
-gzip flag).  The build rejects a pack above the `PACK_MAX` cap (2 MB,
-`CMDS_GZ_MAX` in the Makefile, `PACK_MAX` in `vesa_stage.S`);
+gzip flag).  The build rejects a pack above the `PACK_MAX` cap (4 MB,
+`CMDS_GZ_MAX` in the Makefile, `PACK_MAX` in `vesa_stage.S`, the embedded
+cap in `boot/efi/main.c`; all three must match);
 `libdeflate` buys several KB over `gzip -9` and is still preferred.  The boot
 path loads the gz pack into RAM — the legacy stage copies it directly to
 `0x900000` with its protected-mode `rep movsb`, the UEFI loader into a
@@ -2454,7 +2548,10 @@ loader-data buffer below 512 MB, kexec via its staging buffer — and
 `ramfs_init()`
 inflates it into page-allocated memory and mounts it read-only at `/ramfs`.
 The kernel image no longer contains it, so the pack no longer moves `_end`;
-the high-memory legacy path supports up to 2 MB (known issue 8).  The UI
+the high-memory legacy path supports up to 4 MB (known issue 8).  Hot
+reloads stage kernel + gzip pack, or a raw runtime pack (`cmds-dev`/
+`net-cmds`, up to the 8 MB ramfs cap), in one buffer of at most `KEXEC_MAX`
+(8 MB, `kexec.h`; `PAYLOAD_MAX` in `payload.c` and `netkexec_send.c` match).  The UI
 font subsets live in the pack under `fonts/`, the WiFi firmware under
 `firmware/`, the mouse cursors at `cursors/adwaita24.cur` (full pack only),
 the UI icons at `icons/adwaita16.icn` (both packs) and the flat kernel at `install/kernel.bin` (full pack only;
@@ -2919,6 +3016,15 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
   grown (new cluster allocation for directories is not implemented).
 - **Keep the memory map in sync** — hardcoded addresses appear in `.S`, `.c`, and
   linker scripts; changing one without the others breaks boot/loading.
+- **Parent death is the default** — `parent_pid` is part of every PCB; exit,
+  kill and the reaper kill descendants.  Spawn sites that must outlive their
+  launcher use `SYS_SPAWN_DETACH` (attach to the caller's parent/session).
+  Do not make a daemon a root process just because it is long-lived: put it
+  under init or detach it to the session.  Kernel threads are roots.
+- **No syscall ABI compatibility for now** — `struct sys_spawn` grew a flags
+  word and `TTY_MAX`/the tty API changed.  Rebuild the kernel, command pack,
+  `root.img`, UEFI payload and host harness together; an old rootfs or an
+  old command on `/share`/FAT is not expected to work.
 - **Ring-3 data segments** — when an IRET returns to ring 3, the CPU nulls
   DS/ES/FS/GS whose DPL is below CPL 3.  Every stub that loads 0x10 to run
   kernel code must therefore restore the user data selector (0x23) before
@@ -2962,19 +3068,21 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    load (the USB rootfs partition is 8 MB, so this only bites if the cap is
    raised without a bigger partition).  The legacy stage copies the
    compressed pack directly to `0x900000` with a protected-mode
-   `rep movsb`, so the cap is `PACK_MAX` 2 MB (raised from 1 MB for the WiFi
-   firmware).  The browser and
+   `rep movsb`, so the cap is `PACK_MAX` 4 MB (raised from 1 MB for the WiFi
+   firmware, then from 2 MB when the browser grew; it ends at `0xD00000`,
+   inside the 16 MB no-E820 fallback).  A 4.15 MB pack was boot-tested on
+   the legacy and UEFI paths and over `net-dev`.  The browser and
    its ring-3 dependencies are compiled with function sections and linked
    with `--gc-sections`; the current full pack with the UI fonts, both
    WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes,
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
-   bytes) and `install/kernel.bin` is ~2.00 MiB gzip (~4 KB under the
-   cap), inflating to ~4.13 MB, which adds about
-   half a second to the boot; the floppy lite pack is ~641 KiB gzip and
+   bytes) and `install/kernel.bin` is ~2.13 MiB gzip (~2 MB under the
+   cap), inflating to ~4.4 MB, which adds about
+   half a second to the boot; the floppy lite pack is ~682 KiB gzip and
    deliberately omits the firmware, `install/kernel.bin` and the browser
    (`BROWSER` on `root.img` is the floppy copy).  `libdeflate-gzip -12` is still preferred.  Over
-   115200 serial a raw `cmds-dev` pack (4.1 MiB) now takes about four
-   minutes; use `net-cmds`.
+   115200 serial a raw `cmds-dev` pack (4.3 MiB) now takes about four
+   minutes; use `net-cmds` (~45 s in QEMU).
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
     board that exposes only MP tables stays UP (deliberate; there is no test
     hardware).
@@ -3044,8 +3152,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     8×16 boot-console font, the IOAPIC/AMD-thermal additions and the safe
     AMD MTRR path, the 32x32 cursor save buffer and the mount-policy table)
     ~0x8bf20 once the frame bitmap moved out of BSS; with the ioremap
-    window, the EHCI handoff fix and the boot-scan log ring it is ~0x8df80,
-    ~8 KB below the `0x90000` wall, and the
+    window, the EHCI handoff fix, the boot-scan log ring, the init bootstrap,
+    parent-pid tree kill, the tty control syscalls and `TTY_MAX` 16 it is
+    ~0x8f260, ~3.4 KB below the `0x90000` wall, and the
     remaining limit
     is kernel code/buffers only.
 
@@ -3103,8 +3212,15 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     background layers, `background-attachment`, 3D/perspective transforms
     and transformed text/descendants (`scale`/`rotate` paint the element box
     and inline images; layout geometry is unchanged), border-radius clipping
-    of descendant content, gradients/box-shadow/transitions (a gradient
+    of descendant content, gradients/box-shadow (a gradient
     background falls back to its last solid colour), or CSS `color-mix`.
+    Transitions animate only `opacity` (painted only on absolute/fixed
+    boxes; in-flow translucency paints opaque) and `translate()`; colours,
+    sizes, `scale`/`rotate`, `@keyframes` animations, per-property
+    durations/delays in one `transition` list and `transitioncancel`/
+    `transitionstart` are not supported, and every animation frame is a
+    full page re-render (~25 ms on the host, several times that on the
+    ION, so slides are choppy there).
     A non-uniform `background-size` uses the width scale for both axes.
     CSS custom properties (`var()`: one document-wide table, expanded when
     a sheet is parsed; definitions on `:root`/`html`/`body`/`*`/`:host`
@@ -3226,11 +3342,13 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     OVMF delivers the ISA IRQs through the 8259 path; the kernel nevertheless
     masks the IOAPIC's normal redirection entries after ACPI init, so
     firmware-left vectors cannot collide with the PIC or LAPIC timer.
-    UEFI runtime services are not used: `reboot` still pulses the keyboard
-    controller and `poweroff` uses ACPI S5 (the FADT PM1a/PM1b control blocks
-    and the DSDT `\_S5` sleep type, enabling ACPI through the SMI command
-    when `SCI_EN` is clear) on both BIOS and UEFI boots, with the
-    Bochs/QEMU ports as an emulator fallback.  The image is 17 MB: the
+    UEFI runtime services are not used: `reboot` writes the ACPI 2.0
+    `RESET_REG`/`RESET_VALUE` when `RESET_REG_SUP` is set, then falls back
+    to the Intel PCH 0xCF9, the keyboard controller and a triple fault;
+    `poweroff` uses ACPI S5 (the FADT PM1a/PM1b control blocks and the DSDT
+    `\_S5` sleep type, enabling ACPI through the SMI command when `SCI_EN`
+    is clear) on both BIOS and UEFI boots, with the Bochs/QEMU ports as an
+    emulator fallback.  The image is 17 MB: the
     9 MB kernel + rootfs disk and the 8 MB ESP.  Maxwell GPUs such as the
     GTX 960 use the firmware VBE/GOP framebuffer only; there is no native
     NVIDIA driver, and `nv50_probe()` is gated to the ION/nv50 chipsets.
@@ -3484,8 +3602,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     for every spinner frame; both paths were written from the Linux
     drivers and only Cirrus and the software cursor are tested in QEMU.
     The cursor shape follows the WM poll, so it can lag the pointer by
-    one WM loop.  The 4 KB save buffer and the cursor code (~8 KB in all) are included in
-    `_end` ~0x8df80, ~8 KB below the `0x90000` wall.
+    one WM loop.  The 4 KB save buffer and the cursor code are included in
+    `_end` (see item 21).
 
 40. Wallpaper limits: one screen-aspect image pre-scaled to at most
     1440x810 (cropped to cover, no crop/position choice), no slideshow and
@@ -3496,3 +3614,29 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `/share/wallpaper` otherwise.  The WM keeps a 2.4 MB static copy plus a
     256 KB RGB565->BGRA table (16/24 bpp convert per pixel), all inside the
     4 MB user image window, and has no image decoder of its own.
+
+41. Init/service limits: the service table is static (`service_defs.c`), with
+    no enable/disable persistence, dependencies, targets, one-shot services,
+    timers or failed-service auto-restart (the WM is the only always-restart
+    unit).  `stop` and `kill` both terminate the process: there are no
+    signals or graceful shutdown hooks; `kill` is the forced variant and
+    init drains/closes the log tty when it observes the exit.
+    Logs and state are RAM-only `/share` files (32 KB per service), so they
+    vanish across reboot/kexec.  An init crash intentionally resets the
+    whole ring-3 tree (WM, terminals, apps and detached helpers); kernel
+    threads survive.  Detached spawns outlive their launcher but not init.
+    The control protocol is a trusted single-user tty channel with no
+    authentication.  `TTY_MAX` is 16, so a browser with four helpers plus
+    several services can exhaust tty slots.  `websrv` holds the raw NIC
+    receiver while running: stop it before browser `curl`/`net-dev`, and a
+    second network owner fails with "network busy".  `disks` format/install
+    kernel commands are parented: closing the Disks window aborts them, and
+    a mid-write install can leave P1/P2 intermediate (the MBR is written
+    last).  There is no old `SYS_SPAWN` ABI compatibility: kernel, pack,
+    `root.img`, UEFI payload and host harness must be rebuilt together, and
+    `make kernel-dev` with an old rootfs is unsupported (the new kernel also
+    needs `/ramfs/bin/init` for a WM).  `bootscan` is not a service; it is a
+    kernel thread plus the log viewer.  The display server remains in the
+    kernel (window/canvas bookkeeping, input routing and shadow); a full
+    userland display service would need a generic framebuffer/shared-memory
+    and input API and is not part of this change.

+ 22 - 3
Makefile

@@ -108,7 +108,7 @@ $(B)/$(QJS_DIR)/%.o: $(QJS_DIR)/%.c
 
 # Link order is part of the image layout: keep it stable.  vesa_stage comes
 # from boot/ (it is the 0x7E00 entry), font_8x16/inflate from common/.
-KERNEL_LINK_ORDER = vesa_stage entry kernel timer switch sched process mm \
+KERNEL_LINK_ORDER = vesa_stage entry kernel timer switch sched process init mm \
 	kmalloc paging elf tss syscall sys_wm syscall_stub screen io tty rtc \
 	terminal wm reboot poweroff disk fat serial serial_ring_buf serial_loop \
 	vga blit cpu thermal it87 tpec ec cros_ec power_src power vga_copy \
@@ -133,6 +133,11 @@ $(B)/kernel/e1000e.o: OPT = -Oz
 # and the kernel is close to the low-memory wall; squeeze them hard.
 $(B)/kernel/acpi.o: OPT = -Oz
 $(B)/kernel/poweroff.o: OPT = -Oz
+$(B)/kernel/reboot.o: OPT = -Oz
+$(B)/kernel/terminal.o: OPT = -Oz
+# process.o is the largest -O2 object and not on a drawing path; -Oz keeps
+# the kernel under the 0x90000 wall now that S5/reset live in it.
+$(B)/kernel/process.o: OPT = -Oz
 
 # The AP trampoline is linked at 0x6000 and embedded as a binary blob; ld
 # names its symbols after the input path, so run it inside the build dir
@@ -394,7 +399,7 @@ UCMDS = cpuinfo ls cat save rm mkdir rmdir \
         netconsole netregs netloop netreset net100 netmac curl \
         files view sensors powerinfo mines solitaire \
         settime date gallery websrv browser chat \
-        wifi netmenu disks membench
+        wifi netmenu disks membench init service
 
 app = $(U)/apps/$(1)/ucmd_$(1)
 UCMD_ELFS = $(foreach a,$(UCMDS),$(call app,$(a)).elf)
@@ -484,6 +489,17 @@ $(call app,netmenu).elf: $(call app,netmenu).o $(WIFI_STORE) $(NGUI_APP) $(UCMD_
 $(call app,disks).elf: $(call app,disks).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 
+# Init manager and its CLI/GUI client.  The shared service table/state/control
+# code is linked into both binaries.
+SERVICE_COMMON = $(U)/apps/service/service_proto.o \
+                 $(U)/apps/service/service_defs.o
+$(call app,init).elf: $(call app,init).o $(SERVICE_COMMON) $(UCMD_LD) $(LIBC_A)
+	$(ULINK)
+$(call app,service).elf: $(call app,service).o $(SERVICE_COMMON) $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
+	$(ULINK)
+$(call app,init).o $(call app,service).o $(SERVICE_COMMON): OPT = -Os
+$(call app,init).o $(call app,service).o $(SERVICE_COMMON): XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
+
 # chat: native Cloudron Chat client (ngui + uhttp/TLS + cookie jar + JSON +
 # the native OIDC login driver).
 CHAT_LOGIN = $(U)/apps/chat/chat_login.o
@@ -919,7 +935,10 @@ cmds-lite.pack: $(PACK_DEPS)
 # floppy images use the firmware-less lite pack (rootfs.bin).
 CMDS_GZ     = $(shell command -v libdeflate-gzip >/dev/null 2>&1 && \
 		     echo "libdeflate-gzip -12 -c" || echo "gzip -9 -n -c")
-CMDS_GZ_MAX = 2097152
+# The compressed rootfs cap: PACK_MAX in boot/vesa_stage.S (the legacy stage
+# copies the pack to 0x900000..0xD00000) and the embedded cap in
+# boot/efi/main.c must match.
+CMDS_GZ_MAX = 4194304
 cmds_lite_gz.bin: cmds-lite.pack
 	$(CMDS_GZ) $< > $@
 

+ 1 - 1
boot/efi/main.c

@@ -698,7 +698,7 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st)
 	embed_psize = (UINT32)(pack_image_end - pack_image_start);
 	if (embed_ksize == 0 || embed_ksize > KERNEL_MAX)
 		fail_before(st, "kernel image size invalid");
-	if (embed_psize == 0 || embed_psize > 0x400000u)
+	if (embed_psize == 0 || embed_psize > 0x400000u) /* PACK_MAX */
 		fail_before(st, "rootfs image size invalid");
 	kernel_size = embed_ksize;
 	pack_size = embed_psize;

+ 5 - 1
boot/vesa_stage.S

@@ -28,7 +28,11 @@
 
 /* Rootfs/boot-info constants (must match rootfs.h / bootinfo.h). */
 .equ ROOTFS_VERSION,   1
-.equ PACK_MAX,         0x200000      /* 2 MB compressed rootfs cap */
+.equ PACK_MAX,         0x400000      /* 4 MB compressed rootfs cap; also
+                                       * CMDS_GZ_MAX (Makefile) and the
+                                       * embedded cap in boot/efi/main.c.
+                                       * 0x900000..0xD00000 stays below the
+                                       * 16 MB no-E820 fallback. */
 .equ PACK_HIGH_ADDR,   0x900000      /* above the 8 MB VGA-shadow reserve */
 .equ BOOT_INFO_MAGIC,  0x4E425349
 .equ BOOT_INFO_VERSION, 2

+ 6 - 4
docs/boot.html

@@ -176,8 +176,9 @@
 		</ol>
 		<p>
 			The pack no longer occupies the old <code>0x60000..0x9FBFF</code>
-			low gap, so the legacy cap is <code>PACK_MAX</code> (2 MB, raised
-			from 1 MB for the WiFi firmware) and the
+			low gap, so the legacy cap is <code>PACK_MAX</code> (4 MB, raised
+			from 1 MB for the WiFi firmware and from 2 MB as the browser grew; the
+			copy ends at <code>0xD00000</code>) and the
 			kernel BSS/boot stack may use the gap. The kernel image only has to
 			stay below <code>0x90000</code> so the top of low memory and the
 			EBDA remain untouched; <span class="file">kernel.ld</span> enforces
@@ -410,7 +411,7 @@
 			<li>Create the process table, then start the PIT and verify it ticks.</li>
 			<li>Start APs through INIT-SIPI-SIPI (they idle until scheduling is enabled).</li>
 			<li>Initialise PS/2 (the I2C touchpad probe only on Airmont) and the VGA shadow buffer.</li>
-			<li>Inflate the command pack into <code>/ramfs</code> (table-driven whole-buffer inflate); start the WM and the first frame.</li>
+			<li>Inflate the command pack into <code>/ramfs</code> (table-driven whole-buffer inflate), initialize the kernel window server and start <code>/ramfs/bin/init</code> as PID 1. Init spawns <code>/ramfs/bin/wm</code>; the kernel never starts a WM and the boot console stays if init is absent.</li>
 			<li>Publish <code>vfs_scan_busy</code> and call <code>wm_server_boot_ready()</code>; the WM spawns the <code>bootscan</code> log window first and the first terminal after it, then idle (1 s cap) until the terminal presents.</li>
 			<li>Bring up USB (controllers, HID, USB NICs/WiFi/disks) non-preemptibly, as before the WM existed; probe the NIC, restore retained network config, start the kworker.</li>
 			<li>Start the <code>bootscan</code> kernel thread (non-USB storage probe + FAT mounts, then the deferred USB mounts after the scan window closes, then the <code>/data</code> WiFi autoconnect once the boot DHCP is done); its COM1 output is captured into the <code>SYS_BOOTLOG</code> ring, which the <code>bootscan</code> window tails live. The deferred USB pass can wait seconds for a slow card reader without holding up the desktop, the scan window or the other volumes. Run DHCP if needed.</li>
@@ -444,7 +445,7 @@
 		<h2>Failure modes to know</h2>
 		<ul>
 			<li><strong>No VBE mode.</strong> The legacy stage cannot produce a framebuffer; the kernel may start headless or the boot stops in the stage.</li>
-			<li><strong>Pack larger than the cap.</strong> The legacy BIOS path caps the compressed pack at 2 MB <code>PACK_MAX</code> (<code>CMDS_GZ_MAX</code> in the Makefile); UEFI and kexec can carry larger packs up to the 8 MB ramfs cap. The WiFi firmware, the bundled install kernel and the UI assets make the full pack about 1.98 MB, close to the cap, and inflating it adds roughly half a second to the boot.</li>
+			<li><strong>Pack larger than the cap.</strong> The compressed pack is capped at 4 MB: <code>PACK_MAX</code> in <span class="file">vesa_stage.S</span>, <code>CMDS_GZ_MAX</code> in the Makefile and the embedded-pack check in <span class="file">boot/efi/main.c</span> must agree. Hot reloads stage kernel + pack, or a raw runtime pack, in at most <code>KEXEC_MAX</code> (8 MB, <span class="file">kexec.h</span>), matching the 8 MB ramfs cap. The full pack is about 2.0 MB today, and inflating it adds roughly half a second to the boot.</li>
 			<li><strong>PIT not ticking.</strong> <code>kernel_main</code> prints <code>*** PIT NOT TICKING ***</code> and halts; no process scheduling is possible.</li>
 			<li><strong>UEFI Secure Boot.</strong> The unsigned <code>BOOTX64.EFI</code> is rejected before any NebOS code runs.</li>
 			<li><strong>Stale boot info.</strong> The checksum makes an invalid <code>0x500</code> block read as absent rather than as a bogus pack or RSDP.</li>
@@ -465,6 +466,7 @@
 			<li><code>kernel/kexec.c</code>, <code>kernel/kexec_tramp.S</code> — serial reload</li>
 			<li><code>kernel/netkexec.c</code> — network reload</li>
 			<li><code>kernel/kernel.c</code> — init order</li>
+			<li><code>kernel/init.c</code>, <code>kernel/init.h</code> — PID-1 init bootstrap and restart</li>
 			<li><code>kernel/bootcon.c</code>, <code>common/font_8x16.c</code> — direct-to-LFB boot console and the <code>bootscan</code> thread's serial ring (<code>SYS_BOOTLOG</code>)</li>
 			<li><code>kernel/install.c</code>, <code>kernel/install.h</code> — clone, self-update and net-install writer</li>
 			<li><code>include/rootfs.h</code> — installed image geometry</li>

+ 14 - 3
docs/cpu.html

@@ -180,7 +180,12 @@
 			Emulators whose tables do not decode <code>\_S5</code> fall back to
 			the Bochs/QEMU shutdown ports. A failed poweroff returns to the
 			desktop instead of halting, and the boot/poweroff log carries the
-			PM1, <code>\_S5</code> and <code>SCI_EN</code> state.
+			PM1, <code>\_S5</code> and <code>SCI_EN</code> state. The same FADT
+			walk caches the ACPI 2.0 <code>RESET_REG</code>/<code>RESET_VALUE</code>
+			(when <code>RESET_REG_SUP</code> is set); <code>reboot</code> writes
+			it first, then tries the Intel PCH <code>0xCF9</code>, the keyboard
+			controller and a triple fault. That is what resets a UEFI machine
+			with no working legacy keyboard controller.
 		</p>
 		<ol>
 			<li>Copy the AP trampoline to <code>0x6000</code> (SIPI vector <code>0x06</code>).</li>
@@ -228,7 +233,11 @@
 			<li><strong>Kernel threads</strong> are created with <code>process_create</code> and take the BKL automatically.</li>
 			<li><strong>Ring-3 processes</strong> are created from an ELF image with their own page directory, 32-page (128 KB) user stack and cwd.</li>
 			<li><strong>The kworker</strong> is an ordinary kernel process that performs housekeeping and zombie reaping, so it cannot be starved by a busy system.</li>
-			<li><strong>Stable naming:</strong> process names are 12 bytes; the PCB holds the TTY id, cwd, affinity mask, CPU accounting and the scheduling entity.</li>
+			<li><strong>Stable naming:</strong> process names are 12 bytes; the PCB holds the TTY id, cwd, affinity mask, CPU accounting, the parent pid and the scheduling entity.</li>
+			<li><strong>PID 1 is init.</strong> The kernel starts <code>/ramfs/bin/init</code> after the ramfs and <code>/share</code> mounts and before the WM. Init is a root process and the only creator of the WM and services; the kernel restarts it if it dies. <code>SYS_IS_INIT</code> lets the binary refuse a user-run start.</li>
+			<li><strong>Parent death is the default.</strong> <code>process_exit()</code>, <code>process_kill()</code> and the reaper kill a process's whole descendant subtree. A child born while its parent is dying is aborted, and the process monitor's <em>End task</em> kills the subtree too.</li>
+			<li><strong>Detached spawns.</strong> <code>SYS_SPAWN</code> takes a flags word. The default parents the child to the caller; <code>SYS_SPAWN_DETACH</code> skips the immediate parent and attaches the child to its parent (the terminal/WM session), or to 0 if that parent is gone. This keeps launched apps in the session tree: they outlive a file manager or chat window, but not the terminal/WM. Kernel commands (<code>SYS_SPAWN_KCMD</code>) stay parented. <code>SYS_PROCINFO</code> exposes <code>parent_pid</code>, and the graphical <code>process</code> monitor draws the table as an indented tree under each parent.</li>
+			<li><strong>Fatal faults.</strong> A ring-3 fault kills that process (and its descendants) and keeps the kernel running; a ring-0 fault still shows the panic banner and halts.</li>
 		</ul>
 
 		<figure class="figure">
@@ -401,11 +410,13 @@
 		<h2>Source map</h2>
 		<ul class="filelist">
 			<li><code>kernel/sched.c</code>, <code>kernel/sched.h</code> — scheduler core and BKL</li>
-			<li><code>kernel/process.c</code>, <code>kernel/process.h</code> — PCBs and lifecycle</li>
+			<li><code>kernel/process.c</code>, <code>kernel/process.h</code> — PCBs, parent tracking, subtree kill and lifecycle</li>
+			<li><code>kernel/init.c</code>, <code>kernel/init.h</code> — PID-1 init bootstrap, protection and restart</li>
 			<li><code>kernel/switch.S</code> — context switch</li>
 			<li><code>kernel/tss.c</code>, <code>kernel/tss.h</code> — per-CPU TSS</li>
 			<li><code>kernel/acpi.c</code>, <code>kernel/ioapic.c</code>, <code>kernel/lapic.c</code>, <code>kernel/smp.c</code> — SMP, IOAPIC masking and the FADT S5 shutdown data</li>
 			<li><code>kernel/poweroff.c</code> — ACPI S5 poweroff with the emulator port fallback</li>
+			<li><code>kernel/reboot.c</code> — FADT ACPI reset with PCH/KBC/triple-fault fallbacks</li>
 			<li><code>kernel/ap_tramp.S</code> — AP startup blob</li>
 			<li><code>kernel/timer.S</code>, <code>kernel/idle.c</code>, <code>kernel/power.c</code></li>
 			<li><code>kernel/thermal.c</code> — Intel DTS and AMD D18F3xA4 sampling</li>

+ 2 - 2
docs/development.html

@@ -218,7 +218,7 @@
 					<tr><td><code>make uefi</code> / <code>run-uefi</code> / <code>test-uefi</code></td><td>Build the dual-boot image, boot it under OVMF, or run the headless serial check.</td></tr>
 					<tr><td><code>make rootfs</code></td><td>Rebuild <code>cmds.img</code> only.</td></tr>
 					<tr><td><code>make nowm</code></td><td>Diagnostic kernel with the WM disabled; the boot console stays visible.</td></tr>
-					<tr><td><code>make dev</code> / <code>kernel-dev</code></td><td>Serial reload of kernel + rootfs, or kernel only (keep the running rootfs).</td></tr>
+					<tr><td><code>make dev</code> / <code>kernel-dev</code></td><td>Serial reload of kernel + rootfs, or kernel only (keep the running rootfs). The spawn/tty ABI is not backward compatible and the new kernel needs <code>/ramfs/bin/init</code> for a WM, so do one full <code>make dev</code> after this change; later kernel-only reloads with that rootfs are fine.</td></tr>
 					<tr><td><code>make net-dev</code> / <code>kernel-net-dev</code></td><td>RAM-only network reload of kernel + rootfs, or kernel only.</td></tr>
 					<tr><td><code>make net-install</code></td><td>Persist kernel + full rootfs to P1/P2 over UDP, keeping <code>/data</code>; <code>NETINSTALL_TARGET=auto</code> selects the internal NebOS disk.</td></tr>
 					<tr><td><code>make cmds-dev</code> / <code>net-cmds</code></td><td>Replace <code>/ramfs</code> at runtime over serial or UDP.</td></tr>
@@ -330,7 +330,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Existing processes are unaffected.</strong> They already loaded their ELF.</li>
 			<li><strong>The next spawn sees the new files.</strong></li>
 			<li><strong>RAM only.</strong> A cold boot uses the flashed rootfs; reflash after changing the bundle.</li>
-			<li><strong>Size.</strong> The raw pack is about 2 MB with the WiFi firmware, so <code>cmds-dev</code> over 115200 serial takes roughly three minutes; prefer <code>net-cmds</code>.</li>
+			<li><strong>Size.</strong> The raw pack is about 4.3 MB with the WiFi firmware, so <code>cmds-dev</code> over 115200 serial takes roughly four minutes; prefer <code>net-cmds</code> (about 45 s in QEMU). Reloads carry up to <code>KEXEC_MAX</code> (8 MB).</li>
 		</ul>
 	</section>
 

+ 21 - 11
docs/graphics.html

@@ -196,7 +196,7 @@
 			rows and a rounded Power tile. Every self-contained GUI
 			application in the pack gets a row with a coloured letter tile —
 			Terminal, Files, Web, Gallery, Chat, Clock, Text editor, Colors,
-			Mines, Cards, Disks, Tasks, Settings and Date &amp; Time — the
+			Mines, Cards, Disks, Tasks, Services, Settings and Date &amp; Time — the
 			pointer highlights the hovered row, and an outside press dismisses
 			the panel. Row height shrinks to keep the whole list inside the
 			work area on short panels. The last row, Power, opens a submenu
@@ -231,15 +231,20 @@
 		</p>
 		<p>
 			The WM is the ring-3 process loaded from
-			<code>/ramfs/bin/wm</code>; there is no kernel WM fallback. The
-			kernel window server in <span class="file">wm.c</span> owns the
-			shadow mapping, the per-window canvases, input routing, the cursor,
-			kexec detection and the boot-console handoff. It starts the first
-			terminal after the storage mount
-			(<code>wm_server_boot_ready</code>) and leaves the boot console
-			visible until the WM attaches. The console uses the same 8×16 face
-			and top-left origin as the terminal, so the first frame replaces it
-			without a size or position jump.
+			<code>/ramfs/bin/wm</code>; init is its only creator and there is
+			no kernel WM fallback. The kernel window server in
+			<span class="file">wm.c</span> owns the shadow mapping, the
+			per-window canvases, input routing, the cursor, kexec detection and
+			the boot-console handoff. <code>SYS_WM_ATTACH</code> admits only a
+			process named <code>wm</code> whose parent is the current init pid;
+			it maps the shadow, resets the window mapping state and disables
+			the boot console. If init or the WM binary is missing the console
+			stays visible. The WM starts the first terminal after the storage
+			mount (<code>wm_server_boot_ready</code>); the console uses the same
+			8×16 face and top-left origin as the terminal, so the first frame
+			replaces it without a size or position jump. A wedged WM is killed
+			by the kernel watchdog and init respawns it; its terminal, bootscan
+			window and start-menu apps die with it.
 		</p>
 
 		<figure class="figure">
@@ -452,7 +457,11 @@
 			</div>
 			<div class="card">
 				<h3>process</h3>
-				<p>Graphical task manager (the start menu's <em>Tasks</em> entry or <code>process</code>, the ngui counterpart of <code>top</code>): 60 s CPU, physical-memory and NIC-throughput graphs fed by one sample per second, and a sortable process table (PID, state, CPU%, memory, CPU time, name). A selected row shows its details and <em>End task</em> terminates it after a second confirming click; kernel threads and the monitor itself are protected. Headers sort, PgUp/PgDn and the wheel scroll, Esc closes.</p>
+				<p>Graphical task manager (the start menu's <em>Tasks</em> entry or <code>process</code>, the ngui counterpart of <code>top</code>): 60 s CPU, physical-memory and NIC-throughput graphs fed by one sample per second, and a process tree (PID, state, CPU%, memory, CPU time, name) whose rows are indented under their <code>parent_pid</code>; sibling groups sort by clicking a header. A selected row shows its pid/ppid and details and <em>End task</em> terminates the subtree after a second confirming click; kernel threads, the monitor itself and init are protected. PgUp/PgDn and the wheel scroll, Esc closes.</p>
+			</div>
+			<div class="card">
+				<h3>service</h3>
+				<p>Init's service manager client (<code>service --gui</code>, or the start menu's <em>Services</em> entry): <code>init</code>, <code>wm</code> and user services with Start/Stop/Restart/Kill, status and a live log pane. Kill asks for a second click; WM stop is refused because it is the session service.</p>
 			</div>
 			<div class="card">
 				<h3>gallery</h3>
@@ -593,6 +602,7 @@
 			<li><code>kernel/blit.c</code>, <code>kernel/blit.h</code> — pixel vtable</li>
 			<li><code>kernel/cpu.c</code> — SSE2 probing</li>
 			<li><code>kernel/wm.c</code>, <code>kernel/wm.h</code>, <code>include/wm_abi.h</code> — kernel window server and shared ABI</li>
+			<li><code>kernel/init.c</code>, <code>kernel/init.h</code> — starts PID 1; init is the only WM creator</li>
 			<li><code>user/apps/wm/ucmd_wm.c</code>, <code>user/lib/uwm/uwm_lib.c</code> — ring-3 WM</li>
 			<li><code>user/apps/netmenu/ucmd_netmenu.c</code> — top-bar control panel (network/WiFi, brightness, power mode, Date &amp; Time)</li>
 			<li><code>user/apps/settime/ucmd_settime.c</code>, <code>kernel/rtc.c</code>, <code>kernel/ntp.c</code> — Date &amp; Time editor, RTC access and SNTP sync</li>

+ 6 - 1
docs/index.html

@@ -159,7 +159,7 @@
 			<li><strong>Identity-mapped paging.</strong> Physical and virtual addresses are equal. There is no per-process address space or isolation.</li>
 			<li><strong>1 GB lowmem, 4 GB highmem.</strong> The identity map ends where ring-3 space starts (<code>0x40000000</code>); RAM up to 4 GB backs ring-3 pages through per-CPU <code>kmap</code> slots.</li>
 			<li><strong>Hardcoded low memory.</strong> Boot info, the E820 map, the framebuffer block and the AP trampoline have fixed addresses that every boot path must honour.</li>
-			<li><strong>No firmware runtime.</strong> <code>reboot</code> resets through the keyboard controller and <code>poweroff</code> writes ACPI S5 from the FADT/DSDT; UEFI runtime services are not called after <code>ExitBootServices</code>.</li>
+			<li><strong>No firmware runtime.</strong> <code>reboot</code> uses the ACPI reset register (with PCH/KBC fallbacks) and <code>poweroff</code> writes ACPI S5 from the FADT/DSDT; UEFI runtime services are not called after <code>ExitBootServices</code>.</li>
 		</ul>
 		<div class="warn">
 			<p><strong>Fresh memory is not zeroed.</strong> <code>mm_alloc_page</code> and <code>kmalloc</code> return whatever RAM contained. Every structure read before it is written must be cleared on allocation; QEMU hides this because its RAM starts clear.</p>
@@ -235,6 +235,11 @@
 				<p>Ring-3 address space, ELF loading, syscall groups, the optional libc and malloc, PATH dispatch, the command pack and GUI apps.</p>
 				<span class="card-tag">userland.html</span>
 			</a>
+			<a class="card" href="userland.html#services">
+				<h3>Init &amp; services</h3>
+				<p>PID 1 init, the WM and service lifecycle, per-service tty logs and state, the <code>service</code> CLI/GUI, and the parent-death process tree with explicit detached spawns.</p>
+				<span class="card-tag">userland.html#services</span>
+			</a>
 			<a class="card" href="userland.html#libc">
 				<h3>Ring-3 libc</h3>
 				<p>Optional static <code>libc.a</code>: boundary-tag malloc/free/realloc, strings, stdlib and heap_reset over the 64 MB SYS_MEM arena.</p>

+ 1 - 1
docs/memory.html

@@ -319,7 +319,7 @@
 	<section id="pack">
 		<h2>Rootfs pack lifetime</h2>
 		<ol>
-			<li>The compressed pack is at most 2 MB (<code>PACK_MAX</code>), so the legacy copy ends below <code>0xB00000</code>; inflated it is about 4.1 MB with the WiFi firmware (the 8 MB <code>RAMFS_MAX_DECOMPRESSED</code> cap applies).</li>
+			<li>The compressed pack is at most 4 MB (<code>PACK_MAX</code>), so the legacy copy ends below <code>0xD00000</code>, still inside the 16 MB no-E820 fallback; inflated it is about 4.35 MB with the WiFi firmware (the 8 MB <code>RAMFS_MAX_DECOMPRESSED</code> cap applies).</li>
 			<li>The boot path places the gzip pack in RAM: the legacy stage copies it directly to <code>0x900000</code> with a protected-mode <code>rep movsb</code>, UEFI into a loader-data buffer below 1 GB, kexec in its staging buffer.</li>
 			<li><code>mm_init</code> reserves <code>[pack_addr, pack_addr + pack_size)</code> so the frame allocator cannot reuse it.</li>
 			<li><code>ramfs_init</code> takes a private page-allocated copy, validates the <code>NBROOT1</code> header and inflates the pack into it.</li>

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
docs/network.html


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 112 - 10
docs/userland.html


+ 22 - 5
include/syscall.h

@@ -90,8 +90,8 @@
 #define SYS_NTP_EREPLY  (-6)  /* malformed, unsynchronised or KoD reply */
 #define SYS_NTP_EBUSY   (-7)  /* another process owns the receiver */
 
-/* Window-manager service (see wm_abi.h).  Only the kernel-spawned WM process
- * may call the WM_* entries; ordinary commands get -1. */
+/* Window-manager service (see wm_abi.h).  Only init's child named "wm" may
+ * attach and call the WM_* entries; ordinary commands get -1. */
 #define SYS_WM_ATTACH      57  /* (struct wm_screen_info *out) -> 0/-1 */
 #define SYS_WM_INFO        58  /* (index, struct wm_window_info *out) -> 1/0/-1 */
 #define SYS_WM_MAP         59  /* (index, struct wm_map_info *out) -> 0/-1 */
@@ -257,23 +257,39 @@ struct sys_bootlog {
 #define SYS_FS_STAT        98  /* (path, struct sys_stat *out) -> 0/<0 */
 
 /* Terminal / process services used by the ring-3 shell. */
-#define SYS_TTY_CREATE     73  /* () -> tty id 1..TTY_MAX / -1 */
+#define SYS_TTY_CREATE     73  /* () -> tty id 1..TTY_MAX / -1; binds the caller */
 #define SYS_TTY_READ       74  /* (id, buf, max) -> bytes / 0 / -1 */
-#define SYS_SPAWN          75  /* (path, arg, tty, cwd) -> pid / <0 */
+#define SYS_SPAWN          75  /* (const struct sys_spawn *in) -> pid / <0 */
 #define SYS_SPAWN_KCMD     76  /* (name, arg, tty) -> pid / <0 */
 #define SYS_ALIVE          77  /* (pid) -> 1/0 */
-#define SYS_KILL           78  /* (pid) -> 0/-1 */
+#define SYS_KILL           78  /* (pid) -> 0 / -1 / -2 (init protected);
+				  kills the whole subtree */
 #define SYS_CHDIR          79  /* (path) -> 0/-1 */
 #define SYS_WIN_KEY_WAIT   80  /* (timeout_ms) -> key / 0 timeout / -1 */
 #define SYS_SCHEDINFO      81  /* (struct sys_schedinfo *out) -> 0/-1 */
 
+/* Spawn flags.  The default parent is the caller; DETACH attaches the child
+ * to the caller's parent (the terminal/WM session) instead, or to 0 when that
+ * parent is absent/dead. */
+#define SYS_SPAWN_DETACH   0x1
+
 struct sys_spawn {
 	const char *path;
 	const char *arg;
 	const char *cwd;
 	unsigned int tty;
+	unsigned int flags;      /* SYS_SPAWN_* */
 };
 
+/* Init control-channel support.  SYS_TTY_ALLOC creates a tty owned by the
+ * caller without rebinding its own stdout; SYS_TTY_WRITE is a non-blocking
+ * write to any valid tty (init's control channel and client response rings);
+ * SYS_TTY_CLOSE frees a tty the caller owns.  TTY_MAX is 16. */
+#define SYS_TTY_ALLOC     124 /* () -> tty id 1..TTY_MAX / -1 */
+#define SYS_TTY_WRITE     125 /* (id, buf, len) -> 0/-1 (no partial writes) */
+#define SYS_TTY_CLOSE     126 /* (id) -> 0/-1; owner only */
+#define SYS_IS_INIT       127 /* () -> 1 when the caller is the kernel's init */
+
 struct sys_netinfo {
 	unsigned int present;
 	unsigned char mac[6];
@@ -377,6 +393,7 @@ struct sys_meminfo {
  * derived. */
 struct sys_procinfo {
 	unsigned int pid;
+	unsigned int parent_pid;  /* 0 = root/detached */
 	unsigned int state;       /* PROC_*: 1 ready, 2 running, 4 sleep, 5 block */
 	unsigned int cpu_ticks;   /* ticks spent as the running process */
 	unsigned int life_ticks;  /* ticks since creation, >= 1 */

+ 43 - 0
kernel/acpi.c

@@ -66,6 +66,11 @@ static unsigned int fadt_pm1_cnt_len;
 static unsigned int fadt_smi_cmd;
 static unsigned int fadt_acpi_enable;
 static unsigned int fadt_flags;
+static unsigned int fadt_reset_space;
+static unsigned int fadt_reset_addr;
+static unsigned int fadt_reset_value;
+static unsigned int fadt_reset_width;
+static unsigned int fadt_reset_access;
 static unsigned int dsdt_addr;
 static unsigned int ssdt_addr[4];
 static unsigned int nssdt;
@@ -325,6 +330,16 @@ static void parse_fadt(const unsigned char *t, unsigned int len)
 	fadt_acpi_enable = t[52];
 	if (len >= 116)
 		fadt_flags = *(const unsigned int *)(t + 112);
+	/* ACPI 2.0+ reset register (GAS at 116, value at 128). */
+	if (len >= 129) {
+		fadt_reset_space = t[116];
+		fadt_reset_width = t[117];
+		fadt_reset_access = t[119];
+		fadt_reset_value = t[128];
+		x = *(const unsigned long long *)(t + 120);
+		if (x && (unsigned int)(x >> 32) == 0)
+			fadt_reset_addr = (unsigned int)x;
+	}
 	/* ACPI 2.0+ firmware may publish the DSDT only in X_DSDT. */
 	if (len >= 148) {
 		x = *(const unsigned long long *)(t + 140);
@@ -498,6 +513,11 @@ int acpi_init(void)
 	fadt_smi_cmd = 0;
 	fadt_acpi_enable = 0;
 	fadt_flags = 0;
+	fadt_reset_space = 0;
+	fadt_reset_addr = 0;
+	fadt_reset_value = 0;
+	fadt_reset_width = 0;
+	fadt_reset_access = 0;
 	dsdt_addr = 0;
 	nssdt = 0;
 	dsdt_ptr = 0;
@@ -640,6 +660,29 @@ static void nvidia_s5_prepare(unsigned int smi_base)
 	}
 }
 
+/* Reset the machine through the FADT reset register (ACPI 2.0+), the only
+ * reliable reset on machines without a working 8042.  Returns 0 when the
+ * register write was issued, -1 when the firmware does not provide one. */
+int acpi_reset(void)
+{
+	unsigned int addr = fadt_reset_addr;
+
+	if (!fadt_ok || !(fadt_flags & (1u << 10)) || !addr)
+		return -1;
+	if (fadt_reset_space == 1) {          /* System I/O */
+		if (addr > 0xFFFFu)
+			return -1;
+		if (fadt_reset_access >= 2 || fadt_reset_width >= 16)
+			port_outw((unsigned short)addr,
+				  (unsigned short)fadt_reset_value);
+		else
+			port_outb((unsigned short)addr,
+				  (unsigned char)fadt_reset_value);
+		return 0;
+	}
+	return -1;
+}
+
 int acpi_poweroff(void)
 {
 	unsigned int t0, sci, smi, cmd;

+ 4 - 0
kernel/acpi.h

@@ -28,6 +28,10 @@ unsigned int acpi_rtc_century_reg(void);
  * issued, -1 when the firmware provides no usable S5 path. */
 int acpi_poweroff(void);
 
+/* Reset through the FADT RESET_REG/RESET_VALUE.  Returns 0 when the register
+ * write was issued, -1 when the firmware provides no usable reset register. */
+int acpi_reset(void);
+
 /* Write the DSDT (as mapped at boot) to a VFS path, for diagnostics. */
 int acpi_dump_dsdt(const char *path);
 

+ 71 - 0
kernel/init.c

@@ -0,0 +1,71 @@
+/* Micro-init bootstrap.  The real policy lives in the ring-3 init binary; this
+ * file only loads it, records its pid and restarts it if it ever exits. */
+
+#include "init.h"
+#include "process.h"
+#include "serial.h"
+#include "timer.h"
+#include "vfs.h"
+
+static unsigned int init_pid;
+static unsigned int init_last_start;
+static int init_supported = -1;   /* -1 unknown, 0 no binary, 1 present */
+
+unsigned int init_server_pid(void)
+{
+	return init_pid;
+}
+
+void init_server_note_pid(unsigned int pid)
+{
+	init_pid = pid;
+}
+
+int init_server_start(void)
+{
+	struct vfs_file f;
+	struct vfs_mount *m = 0;
+	unsigned int now = get_ticks_ms();
+	int pid;
+
+	if (init_supported == 0)
+		return 0;
+	if (init_pid && process_is_alive(init_pid))
+		return 1;
+	if (init_last_start && now - init_last_start < 1000)
+		return 0;
+	init_last_start = now;
+
+	if (vfs_load_file("/ramfs/bin/init", &f, &m) != 0) {
+		init_supported = 0;
+		serial_puts(SERIAL_COM1,
+			    "init: /ramfs/bin/init not found; no WM\n");
+		return 0;
+	}
+	init_supported = 1;
+	pid = process_create_user_full("init", f.data, f.size, "", "/", 0, 0,
+				       PROC_CREATE_INIT);
+	vfs_release_file(m, &f);
+	if (pid <= 0) {
+		serial_puts(SERIAL_COM1, "init: cannot start /ramfs/bin/init\n");
+		return 0;
+	}
+	process_set_weight((unsigned int)pid, 12);
+	serial_puts(SERIAL_COM1, "init: started\n");
+	return 1;
+}
+
+void init_server_supervise(void)
+{
+	if (init_supported == 0)
+		return;
+	if (init_pid && process_is_alive(init_pid))
+		return;
+	if (init_pid) {
+		serial_puts(SERIAL_COM1, "init: process died; restarting\n");
+		init_pid = 0;
+	}
+	/* init_server_start() throttles itself, so a crash loop retries once a
+	 * second and a startup failure is not retried at the kworker rate. */
+	init_server_start();
+}

+ 16 - 0
kernel/init.h

@@ -0,0 +1,16 @@
+/* Ring-3 init bootstrap and supervision.
+ *
+ * The kernel starts /ramfs/bin/init as PID 1 after the ramfs/share mounts and
+ * wm_server_init(), and before any WM exists.  Init owns the WM and services;
+ * the kernel only restarts init if it dies.  `init_pid` is recorded inside
+ * process_create_user_full() before the process is made runnable, so an AP
+ * cannot run init and see an empty pid. */
+#ifndef INIT_H
+#define INIT_H
+
+unsigned int init_server_pid(void);
+void init_server_note_pid(unsigned int pid);
+int  init_server_start(void);
+void init_server_supervise(void);
+
+#endif

+ 14 - 4
kernel/io.c

@@ -238,7 +238,9 @@ static int io_tty(void)
 	struct process *p = current_proc();
 	int id = p ? p->tty : 0;
 
-	return tty_valid(id) ? id : 0;
+	if (!id)
+		return 0;        /* no tty: the boot/fallback console */
+	return tty_valid(id) ? id : -1;  /* stale tty: drop output */
 }
 
 
@@ -247,10 +249,12 @@ void io_putchar(char c)
 {
 	int id = io_tty();
 
-	if (id) {
+	if (id > 0) {
 		tty_write(id, &c, 1);
 		return;
 	}
+	if (id < 0)
+		return;
 	screen_putchar(io_current_screen(), c);
 }
 
@@ -258,16 +262,22 @@ void io_putstr(const char *s)
 {
 	int id = io_tty();
 
-	if (id) {
+	if (id > 0) {
 		tty_write_str(id, s);
 		return;
 	}
+	if (id < 0)
+		return;
 	screen_putstr(io_current_screen(), s);
 }
 
 void io_puthex(unsigned int n)
 {
-	if (io_tty()) {
+	int id = io_tty();
+
+	if (id < 0)
+		return;
+	if (id > 0) {
 		static const char hex[] = "0123456789ABCDEF";
 		char buf[9];
 		unsigned int i = 8;

+ 12 - 6
kernel/kernel.c

@@ -7,6 +7,7 @@
 #include "cpu.h"
 #include "cros_ec.h"
 #include "idle.h"
+#include "init.h"
 #include "io.h"
 #include "ioapic.h"
 #include "lapic.h"
@@ -258,6 +259,7 @@ static void system_housekeeping(void)
 	netlog_flush();
 #ifndef NOWM
 	wm_handle_kexec();
+	init_server_supervise();
 	wm_server_supervise();
 	if (!wm_server_frame_active())
 		vga_fb_flush_budget(VGA_FLUSH_BUDGET_BYTES);
@@ -388,8 +390,11 @@ static void boot_wifi_autoconnect(void)
 		struct vfs_mount *m = 0;
 
 		if (vfs_load_file("/ramfs/bin/wifi", &f, &m) == 0) {
-			if (process_create_user("wifi", f.data, f.size,
-						"autoconnect", "/") > 0)
+			/* The bootscan thread exits right after starting
+			 * this helper, so it must be detached (parent 0). */
+			if (process_create_user_full("wifi", f.data, f.size,
+						     "autoconnect", "/", 0, 0,
+						     0) > 0)
 				serial_puts(SERIAL_COM1,
 					    "wifi: autoconnect started\n");
 			vfs_release_file(m, &f);
@@ -583,12 +588,13 @@ void kernel_main(void)
 	boot_val("ramfs files", ramfs_count());
 
 #ifndef NOWM
-	/* Start the WM before touching disks: the first frame can be painted
-	 * while storage and the network are still being probed. */
+	/* Hand the userland over to PID 1 before touching disks.  Init starts
+	 * the WM and the services; if /ramfs/bin/init is absent there is no WM
+	 * and the boot console stays visible. */
 	wm_server_init();
 	boot_trace("wm init");
-	wm_server_start();
-	boot_trace("wm");
+	init_server_start();
+	boot_trace("init");
 #else
 	/* Diagnostic build: boot to the console, no WM, no terminal. */
 	bootcon_puts("WM disabled (diagnostic build)\n");

+ 3 - 1
kernel/kexec.h

@@ -9,7 +9,9 @@ void program_kexec_main(void);
  * fixed region below the VGA window, which forced the low-memory map to move
  * whenever the kernel grew. */
 #define KEXEC_LOAD  0x7E00
-#define KEXEC_MAX   0x400000
+/* Kernel + gzip rootfs (PACK_MAX is 4 MB) or a raw runtime pack, which
+ * ramfs caps at RAMFS_MAX_DECOMPRESSED (8 MB). */
+#define KEXEC_MAX   0x800000
 
 /* Allocate the staging buffer for an image of `size` bytes (contiguous,
  * page-aligned, identity-mapped).  Sets kexec_stage; returns 1 on success. */

+ 1 - 1
kernel/payload.c

@@ -21,7 +21,7 @@
 #include "vfs.h"
 
 #define PAYLOAD_MAGIC 0x504E584B /* "KXNP" little-endian */
-#define PAYLOAD_MAX   0x400000   /* sanity cap, like KEXEC_MAX */
+#define PAYLOAD_MAX   0x800000   /* raw pack; RAMFS_MAX_DECOMPRESSED, KEXEC_MAX */
 
 int payload_pending(void)
 {

+ 80 - 4
kernel/process.c

@@ -8,6 +8,7 @@
 #include "process.h"
 #include "elf.h"
 #include "idle.h"
+#include "init.h"
 #include "io.h"
 #include "kmalloc.h"
 #include "mm.h"
@@ -30,6 +31,7 @@ static unsigned int next_pid_counter = 1; /* monotonic, wraps */
 static unsigned int fallback_stack_next;  /* 0..PROC_FALLBACK_STACK_MAX */
 static struct process *zombie_head, *zombie_tail;
 static struct wait_queue exit_wq;
+static void process_kill_children(unsigned int pid);
 
 /* Top of the in-image bootstrap stack (see kernel.ld). */
 extern char __boot_stack_top[];
@@ -143,6 +145,7 @@ static void proc_commit(struct process *p, int slot, const char *name,
 
 	p->esp = esp;
 	p->pid = next_pid_counter++;
+	p->parent_pid = parent ? parent->pid : 0;
 	p->slot = (unsigned int)slot;
 	p->stack_base = owned ? stack_base : 0;
 	p->cr3 = cr3;
@@ -412,9 +415,11 @@ int process_create_ptr(const char *name, void (*entry)(void *), void *arg)
 	return pid;
 }
 
-/* Load an ELF image into a fresh address space and run it as a ring-3 process. */
-int process_create_user_tty(const char *name, const void *image, unsigned int size,
-			    const char *arg, const char *cwd, unsigned int tty)
+/* Load an ELF image into a fresh address space and run it as a ring-3 process.
+ * `parent_pid` is recorded before the process becomes runnable. */
+int process_create_user_full(const char *name, const void *image, unsigned int size,
+			     const char *arg, const char *cwd, unsigned int tty,
+			     unsigned int parent_pid, unsigned int cflags)
 {
 	int slot, owned, pid;
 	unsigned int base, top, *sp, cr3, entry;
@@ -523,10 +528,29 @@ int process_create_user_tty(const char *name, const void *image, unsigned int si
 
 	proc_commit(p, slot, name, (unsigned int)sp, owned, base, cr3, top,
 		    0, 0);
+	p->parent_pid = parent_pid;
 	if (cwd)
 		cwd_copy(p, cwd);
 	if (tty)
 		p->tty = (int)tty;
+
+	/* A process may not outlive the parent that is creating it.  A detached
+	 * process falls back to the root when the session parent raced with the
+	 * spawn; a normal child is aborted instead. */
+	if (parent_pid && !process_is_alive(parent_pid)) {
+		if (cflags & PROC_CREATE_DETACH) {
+			p->parent_pid = 0;
+		} else {
+			process_kill(p->pid);
+			irq_restore(flags);
+			return -1;
+		}
+	}
+	/* Record the init pid before sched_add_ready(): an AP could otherwise
+	 * run init and fail SYS_IS_INIT or its WM's attach check. */
+	if (cflags & PROC_CREATE_INIT)
+		init_server_note_pid(p->pid);
+
 	sched_add_ready(p);
 	pid = (int)p->pid;
 
@@ -534,6 +558,15 @@ int process_create_user_tty(const char *name, const void *image, unsigned int si
 	return pid;
 }
 
+int process_create_user_tty(const char *name, const void *image, unsigned int size,
+			    const char *arg, const char *cwd, unsigned int tty)
+{
+	unsigned int parent = current_proc() ? current_proc()->pid : 0;
+
+	return process_create_user_full(name, image, size, arg, cwd, tty,
+					parent, 0);
+}
+
 int process_create_user(const char *name, const void *image, unsigned int size,
 			const char *arg, const char *cwd)
 {
@@ -644,6 +677,8 @@ void process_reap_dead(void)
 	for (p = list; p; ) {
 		struct process *next = p->zombie_next;
 
+		/* Safety net for a child born while its parent was dying. */
+		process_kill_children(p->pid);
 		sys_net_reap(p->pid);   /* release a held NIC */
 		tty_reap(p->pid);       /* drop its terminal queue */
 		if (p->stack_base)
@@ -679,8 +714,14 @@ void process_exit(void)
 {
 	struct process *p = current_proc();
 
-	if (p)
+	if (p) {
+		unsigned int flags = sched_lock_acquire();
+
 		p->state = PROC_DEAD;
+		sched_lock_release(flags);
+		/* A parent owns its subtree: no child may outlive it. */
+		process_kill_children(p->pid);
+	}
 	wait_wake_all(&exit_wq);
 	sched_yield();          /* switch away immediately via int 0x81 */
 	for (;;)
@@ -807,6 +848,7 @@ int process_procinfo(unsigned int index, struct sys_procinfo *out)
 
 		life = get_ticks_ms() - p->start_ticks;
 		out->pid        = p->pid;
+		out->parent_pid = p->parent_pid;
 		out->state      = p->state;
 		out->cpu_ticks  = p->cpu_ticks;
 		out->life_ticks = life ? life : 1;
@@ -831,6 +873,8 @@ int process_kill(unsigned int pid)
 
 	if (pid == 0)
 		return -1; /* cannot kill the kernel idle process */
+	if (pid == init_server_pid())
+		return -2; /* init is protected; the kernel restarts it */
 	flags = sched_lock_acquire();
 	for (i = 0; i < PROC_MAX; i++) {
 		struct process *p = procs[i];
@@ -847,6 +891,7 @@ int process_kill(unsigned int pid)
 	if (target == current_proc()) {
 		target->state = PROC_DEAD;
 		sched_lock_release(flags);
+		process_kill_children(pid);
 		wait_wake_all(&exit_wq);
 		sched_yield();     /* never resumes */
 		return 0;
@@ -867,9 +912,40 @@ int process_kill(unsigned int pid)
 		 * has switched away from it. */
 		smp_resched_cpu(on_cpu);
 	}
+	/* Queue the target first: if one of its descendants is the caller, the
+	 * recursive kill will switch away from this call. */
+	process_kill_children(pid);
 	return 0;
 }
 
+/* Kill every direct child of `pid`; process_kill() recurses.  The scan is
+ * repeated because a child may already have been reaped or marked dead while
+ * we were walking the table.  Called without sched_lock held. */
+static void process_kill_children(unsigned int pid)
+{
+	unsigned int i;
+
+	if (!pid)
+		return;   /* PID 0's child is init, which is protected */
+	for (;;) {
+		unsigned int child = 0;
+		unsigned int flags = sched_lock_acquire();
+
+		for (i = 0; i < PROC_MAX; i++) {
+			struct process *p = procs[i];
+
+			if (p && p->parent_pid == pid &&
+			    p->state != PROC_DEAD) {
+				child = p->pid;
+				break;
+			}
+		}
+		sched_lock_release(flags);
+		if (!child || process_kill(child) != 0)
+			break;
+	}
+}
+
 int process_set_weight(unsigned int pid, unsigned int weight)
 {
 	unsigned int i, flags;

+ 10 - 0
kernel/process.h

@@ -37,6 +37,7 @@ struct process {
 	unsigned int esp;            /* offset 0: switch.S saves it here */
 	unsigned int state;
 	unsigned int pid;
+	unsigned int parent_pid;     /* 0 = root/detached */
 	unsigned int slot;           /* index in procs[], PROC_MAX for idle */
 	char         name[PROC_NAME_LEN];
 	unsigned int stack_base;     /* page to free on exit, or 0 (bootstrap/fallback) */
@@ -117,6 +118,15 @@ int process_create_user(const char *name, const void *image, unsigned int size,
 int process_create_user_tty(const char *name, const void *image,
 			unsigned int size, const char *arg, const char *cwd,
 			unsigned int tty);
+/* Full creation path: explicit parent pid and kernel-only flags.  The child is
+ * not made runnable until its parent (and, for PROC_CREATE_INIT, the init pid)
+ * has been recorded, so an AP cannot observe a half-initialised process. */
+#define PROC_CREATE_DETACH 0x1
+#define PROC_CREATE_INIT   0x2
+int process_create_user_full(const char *name, const void *image,
+			unsigned int size, const char *arg, const char *cwd,
+			unsigned int tty, unsigned int parent_pid,
+			unsigned int flags);
 /* Render target override for the running process (0 = the screen). */
 struct surface *process_render_target(void);
 void process_set_render_target(struct surface *s);

+ 38 - 5
kernel/reboot.c

@@ -1,14 +1,47 @@
-/* Reboot command: trigger a CPU reset via the keyboard controller. */
+/* Reboot command: ACPI reset register first, then the legacy fallbacks.
+ *
+ * The 8042 pulse alone does nothing on machines without a legacy keyboard
+ * controller (the Chromebook), which used to leave the BSP halted with the
+ * BKL held.  The FADT RESET_REG/RESET_VALUE pair is the firmware-provided
+ * reset path; 0xCF9 is the Intel PCH fallback, and a triple fault is the
+ * last resort. */
 
-static inline void outb(unsigned short port, unsigned char v)
+#include "acpi.h"
+#include "pci.h"
+#include "timer.h"
+
+static void wait_ms(unsigned int ms)
 {
-	__asm__ volatile ("outb %0, %1" : : "a"(v), "Nd"(port));
+	unsigned int t0 = get_ticks_ms();
+
+	while (get_ticks_ms() - t0 < ms)
+		__asm__ volatile ("hlt");
 }
 
 void program_reboot_main(void)
 {
-	/* Pulse the CPU reset line via the keyboard controller (port 0x64). */
-	outb(0x64, 0xFE);
+	if (acpi_reset() == 0)
+		wait_ms(500);
+
+	/* Intel PCH reset control: SYS_RST, then RST_CPU|SYS_RST. */
+	port_outb(0xCF9, 0x02);
+	port_outb(0xCF9, 0x06);
+	wait_ms(300);
+
+	/* Legacy 8042 reset pulse, for boards where that is the only path. */
+	port_outb(0x64, 0xFE);
+	wait_ms(300);
+
+	/* Zero IDT + int3: a triple fault forces a CPU reset. */
+	{
+		struct {
+			unsigned short limit;
+			unsigned int base;
+		} __attribute__((packed)) idt = { 0, 0 };
+
+		__asm__ volatile ("lidt %0" : : "m"(idt));
+		__asm__ volatile ("int3");
+	}
 	for (;;)
 		__asm__ volatile ("hlt");
 }

+ 12 - 5
kernel/sched.c

@@ -814,14 +814,20 @@ int sched_tick_bsp(void)
 {
 	struct cpu *c = this_cpu();
 	struct process *p;
-	unsigned int flags = sched_lock_acquire();
+	unsigned int flags, ms;
 	int r;
 
+	/* Read the period this tick covered before anything else: waking a
+	 * sleeper shortens the next period (smp_resched_wake() reprograms the
+	 * PIT and sets tick_ms to 1), and charging the elapsed tick with the
+	 * new value made every 10 ms idle tick look like 1 ms of idle. */
+	ms = timer_tick_ms();
+	flags = sched_lock_acquire();
 	thermal_tick();
 	p = c->current;
-	power_tick(p == c->idle, timer_tick_ms());
+	power_tick(p == c->idle, ms);
 	wake_sleepers_locked();
-	r = tick_decide_locked(c, p, 0, timer_tick_ms());
+	r = tick_decide_locked(c, p, 0, ms);
 	sched_lock_release(flags);
 	return r;
 }
@@ -833,12 +839,13 @@ int sched_tick_ap(void)
 	struct cpu *c = this_cpu();
 	struct process *p;
 	unsigned int flags = sched_lock_acquire();
+	unsigned int ms = c->tick_ms;
 	int r;
 
 	thermal_tick();
 	p = c->current;
-	power_tick(p == c->idle, c->tick_ms);
-	r = tick_decide_locked(c, p, 1, c->tick_ms);
+	power_tick(p == c->idle, ms);
+	r = tick_decide_locked(c, p, 1, ms);
 	if (!r && p == c->idle && c->tick_ms != 10) {
 		/* Entered idle without a schedule(): stretch this CPU's LAPIC
 		 * period so MWAIT can hold C2 for 10 ms. */

+ 31 - 3
kernel/syscall.c

@@ -3,6 +3,7 @@
 #include "syscall.h"
 #include "backlight.h"
 #include "bootcon.h"
+#include "init.h"
 #include "io.h"
 #include "paging.h"
 #include "power.h"
@@ -380,6 +381,21 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sched_snapshot((struct sys_schedinfo *)a1);
 	case SYS_TTY_CREATE:
 		return tty_create();
+	case SYS_TTY_ALLOC:
+		return tty_alloc();
+	case SYS_TTY_WRITE: {
+		int id = a1;
+		const char *buf = (const char *)a2;
+		unsigned int len = (unsigned int)a3;
+
+		if (!tty_valid(id) || !buf || !len ||
+		    !paging_user_range_ok(current_proc()->cr3,
+					  (unsigned int)buf, len, 0))
+			return -1;
+		return tty_try_write(id, buf, len);
+	}
+	case SYS_TTY_CLOSE:
+		return tty_close_owned(a1, current_proc()->pid);
 	case SYS_TTY_READ: {
 		int id = a1;
 		char *buf = (char *)a2;
@@ -391,16 +407,20 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 			return -1;
 		return tty_read(id, buf, max);
 	}
+	case SYS_IS_INIT:
+		return init_server_pid() == current_proc()->pid;
 	case SYS_SPAWN: {
 		struct sys_spawn in;
 		struct vfs_file f;
 		struct vfs_mount *m = 0;
+		struct process *self = current_proc();
 		char path[VFS_PATH_MAX], arg[VFS_PATH_MAX], cwd[VFS_PATH_MAX];
+		unsigned int parent_pid, cflags = 0;
 		const char *name;
 		int pid;
 		int lr;
 
-		if (!paging_user_range_ok(current_proc()->cr3,
+		if (!paging_user_range_ok(self->cr3,
 					  (unsigned int)a1, sizeof(in), 0))
 			return -1;
 		{
@@ -411,6 +431,8 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 			for (i = 0; i < sizeof(in); i++)
 				d[i] = (unsigned char)p[i];
 		}
+		if (in.flags & ~SYS_SPAWN_DETACH)
+			return -1;
 		if (in.tty && !tty_valid((int)in.tty))
 			return -1;
 		if (copy_user_string(path, sizeof(path), in.path) != 0 ||
@@ -418,6 +440,12 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		    copy_user_string(cwd, sizeof(cwd), in.cwd) != 0)
 			return -1;
 
+		parent_pid = self ? self->pid : 0;
+		if (in.flags & SYS_SPAWN_DETACH) {
+			parent_pid = self ? self->parent_pid : 0;
+			cflags = PROC_CREATE_DETACH;
+		}
+
 		/* A FAT load reads the floppy through IRQ 6, so open the
 		 * syscall's interrupts-off section for the duration (the same
 		 * window SYS_READ_FILE uses). */
@@ -435,8 +463,8 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 				q++;
 			}
 		}
-		pid = process_create_user_tty(name, f.data, f.size, arg, cwd,
-					      in.tty);
+		pid = process_create_user_full(name, f.data, f.size, arg, cwd,
+					       in.tty, parent_pid, cflags);
 		vfs_release_file(m, &f);
 		return pid;
 	}

+ 44 - 4
kernel/tty.c

@@ -19,8 +19,9 @@ struct tty {
 _Static_assert(sizeof(struct tty) <= TTY_STRIDE,
 	       "tty state no longer fits its two-page slot");
 
-/* The rings are 16 KB of state; allocate them from the frame heap instead of
- * BSS to keep the kernel's low-memory footprint small. */
+/* The rings are 8 KB of state each (128 KB at TTY_MAX 16); allocate them from
+ * the frame heap instead of BSS to keep the kernel's low-memory footprint
+ * small. */
 static struct tty *ttys;
 static int tty_ready;
 
@@ -73,7 +74,7 @@ int tty_free_count(void)
 	return (int)n;
 }
 
-int tty_create(void)
+int tty_alloc(void)
 {
 	struct process *p = current_proc();
 	unsigned int i;
@@ -87,13 +88,22 @@ int tty_create(void)
 			t->used = 1;
 			t->owner = p->pid;
 			t->head = t->tail = 0;
-			p->tty = (int)(i + 1);
 			return (int)(i + 1);
 		}
 	}
 	return -1;
 }
 
+int tty_create(void)
+{
+	struct process *p = current_proc();
+	int id = tty_alloc();
+
+	if (id > 0 && p)
+		p->tty = id;
+	return id;
+}
+
 void tty_close(int id)
 {
 	struct tty *t = tty_get(id);
@@ -104,6 +114,17 @@ void tty_close(int id)
 	}
 }
 
+int tty_close_owned(int id, unsigned int pid)
+{
+	struct tty *t = tty_get(id);
+
+	if (!t || !t->used || t->owner != pid)
+		return -1;
+	t->used = 0;
+	t->head = t->tail = 0;
+	return 0;
+}
+
 int tty_write(int id, const char *buf, unsigned int len)
 {
 	struct tty *t;
@@ -137,6 +158,25 @@ int tty_write(int id, const char *buf, unsigned int len)
 	return 0;
 }
 
+int tty_try_write(int id, const char *buf, unsigned int len)
+{
+	struct tty *t;
+	unsigned int i, used, free;
+
+	if (!(t = tty_get(id)) || !t->used)
+		return -1;
+	used = (t->head + TTY_BUF - t->tail) % TTY_BUF;
+	free = TTY_BUF - 1 - used;
+	if (len > free)
+		return -1;               /* no partial control messages */
+	for (i = 0; i < len; i++) {
+		t->buf[t->head] = (unsigned char)buf[i];
+		t->head = (t->head + 1) % TTY_BUF;
+		netlog_char(buf[i]);
+	}
+	return 0;
+}
+
 int tty_write_str(int id, const char *s)
 {
 	unsigned int n = 0;

+ 5 - 2
kernel/tty.h

@@ -5,13 +5,16 @@
 #ifndef TTY_H
 #define TTY_H
 
-#define TTY_MAX 8
+#define TTY_MAX 16
 #define TTY_BUF 4096
 
-int  tty_create(void);                    /* owner = current process */
+int  tty_create(void);                    /* owner = current process, rebinds */
+int  tty_alloc(void);                     /* owner = current, does not rebind */
 int  tty_free_count(void);                /* unused terminal slots */
 void tty_close(int id);
+int  tty_close_owned(int id, unsigned int pid);
 int  tty_write(int id, const char *buf, unsigned int len); /* 0/-1, blocks */
+int  tty_try_write(int id, const char *buf, unsigned int len); /* 0/-1, drops */
 int  tty_write_str(int id, const char *s);
 int  tty_read(int id, char *buf, unsigned int max);        /* bytes, 0 if none */
 int  tty_valid(int id);

+ 33 - 74
kernel/wm.c

@@ -5,6 +5,7 @@
 #include "cursor_abi.h"
 #include "backlight.h"
 #include "bootcon.h"
+#include "init.h"
 #include "io.h"
 #include "kexec.h"
 #include "mm.h"
@@ -42,18 +43,15 @@ static int wm_cursor_override = CURSOR_NO_OVERRIDE;
 static int wm_pointer_owned;
 static int wm_ptr_capture = -1;
 
-/* Ring-3 WM lifecycle.  The kernel only admits the process it spawned; a
- * stale pid cannot keep drawing after a restart. */
-static unsigned int wm_expected_pid;
+/* Ring-3 WM lifecycle.  Init is the only creator: the attach auth below
+ * admits an init child named "wm"; the kernel never starts a WM itself. */
 static unsigned int wm_pid;
 static unsigned int wm_cr3;
 static int wm_attached;
 static int wm_frame_active;
 static int wm_first_frame;
 static int wm_boot_ready;
-static int wm_boot_logged;
 static unsigned int wm_wallpaper_seq;
-static unsigned int wm_last_start;
 static unsigned int wm_last_seen;
 
 static inline unsigned int irq_save_disable(void)
@@ -73,6 +71,7 @@ static inline void invlpg_va(unsigned int va)
 	__asm__ volatile ("invlpg (%0)" : : "r"(va) : "memory");
 }
 
+static void wm_server_wm_died(void);
 static void wm_focus_index(unsigned int idx);
 static void wm_focus_top(void);
 static void wm_close_window(unsigned int idx);
@@ -734,15 +733,28 @@ int wm_server_key_wait(unsigned int timeout_ms)
 
 int wm_server_attach(struct wm_screen_info *out)
 {
+	struct process *cur = current_proc();
 	struct surface *s;
 	unsigned int pages, i, bytes;
 
-	if (!out || !wm_expected_pid ||
-	    current_proc()->pid != wm_expected_pid || wm_attached) {
-		serial_puts(SERIAL_COM1, "wm: attach rejected (expected ");
-		serial_puthex(SERIAL_COM1, wm_expected_pid);
-		serial_puts(SERIAL_COM1, " current ");
-		serial_puthex(SERIAL_COM1, current_proc()->pid);
+	if (!out || !cur)
+		return -1;
+	/* A WM that died but was not reaped yet must not block its replacement. */
+	if (wm_pid && !process_is_alive(wm_pid)) {
+		wm_server_wm_died();
+		wm_pid = 0;
+	}
+	if (wm_attached ||
+	    !init_server_pid() ||
+	    cur->parent_pid != init_server_pid() ||
+	    cur->name[0] != 'w' || cur->name[1] != 'm' ||
+	    cur->name[2] != '\0') {
+		serial_puts(SERIAL_COM1, "wm: attach rejected (pid ");
+		serial_puthex(SERIAL_COM1, cur->pid);
+		serial_puts(SERIAL_COM1, " parent ");
+		serial_puthex(SERIAL_COM1, cur->parent_pid);
+		serial_puts(SERIAL_COM1, " init ");
+		serial_puthex(SERIAL_COM1, init_server_pid());
 		serial_puts(SERIAL_COM1, ")\n");
 		return -1;
 	}
@@ -781,7 +793,6 @@ int wm_server_attach(struct wm_screen_info *out)
 	wm_pid = current_proc()->pid;
 	wm_attached = 1;
 	wm_frame_active = 0;
-	wm_boot_logged = 0;
 	wm_last_seen = get_ticks_ms();
 	mouse_set_auto_draw(1);
 	wm_full_redraw = 1;
@@ -1214,71 +1225,25 @@ static void wm_server_wm_died(void)
 		windows[i].mapped_src = 0;
 	}
 	wm_full_redraw = 1;
-	serial_puts(SERIAL_COM1, "wm: ring-3 WM stopped; restarting\n");
-}
-
-void wm_server_start(void)
-{
-	struct vfs_file f;
-	struct vfs_mount *m = 0;
-	unsigned int flags;
-	int pid;
-
-	if (wm_expected_pid && process_is_alive(wm_expected_pid))
-		return;
-	if (wm_last_start && get_ticks_ms() - wm_last_start < 1000)
-		return;
-	wm_last_start = get_ticks_ms();
-
-	if (vfs_load_file("/ramfs/bin/wm", &f, &m) != 0) {
-		if (!wm_boot_logged) {
-			wm_boot_logged = 1;
-			serial_puts(SERIAL_COM1, "wm: /ramfs/bin/wm not found\n");
-			bootcon_puts("wm: /ramfs/bin/wm not found\n");
-		}
-		return;
-	}
-
-	flags = irq_save_disable();
-	pid = process_create_user("wm", f.data, f.size, "", "/");
-	if (pid > 0)
-		wm_expected_pid = (unsigned int)pid;
-	irq_restore(flags);
-	vfs_release_file(m, &f);
-	if (pid <= 0) {
-		if (!wm_boot_logged) {
-			wm_boot_logged = 1;
-			serial_puts(SERIAL_COM1, "wm: cannot load /ramfs/bin/wm\n");
-			bootcon_puts("wm: cannot load /ramfs/bin/wm\n");
-		}
-		return;
-	}
-	process_set_weight((unsigned int)pid, 16);
-	wm_boot_logged = 0;
-	serial_puts(SERIAL_COM1, "wm: ring-3 WM started\n");
+	serial_puts(SERIAL_COM1, "wm: ring-3 WM stopped\n");
 }
 
 void wm_server_supervise(void)
 {
 	unsigned int i, now = get_ticks_ms();
 
-	/* Watchdog: a WM that never attaches, or stops polling for several
-	 * seconds, is treated like a crash so a wedged UI can recover. */
-	if (wm_expected_pid && process_is_alive(wm_expected_pid) &&
-	    !process_is_sleeping(wm_expected_pid)) {
-		/* A sleeping WM is usually blocked on the BKL or its normal
-		 * 10 ms poll sleep; do not treat a long disk scan as a hang. */
-		if ((wm_attached && now - wm_last_seen > 15000) ||
-		    (!wm_attached && now - wm_last_start > 10000)) {
-			serial_puts(SERIAL_COM1, "wm: watchdog, killing WM\n");
-			process_kill(wm_expected_pid);
-		}
+	/* Watchdog: a WM that stops polling for several seconds is treated
+	 * like a crash so init can replace it.  Sleeping is not a hang: it is
+	 * usually the BKL or the normal 10 ms poll sleep. */
+	if (wm_pid && process_is_alive(wm_pid) &&
+	    !process_is_sleeping(wm_pid) && wm_attached &&
+	    now - wm_last_seen > 15000) {
+		serial_puts(SERIAL_COM1, "wm: watchdog, killing WM\n");
+		process_kill(wm_pid);
 	}
 
-	if (wm_expected_pid && !process_is_alive(wm_expected_pid)) {
+	if (wm_pid && !process_is_alive(wm_pid))
 		wm_server_wm_died();
-		wm_expected_pid = 0;
-	}
 
 	/* Owner processes that exited close their windows.  Only at a safe
 	 * point: the WM may still be between INFO/MAP and PRESENT. */
@@ -1293,10 +1258,6 @@ void wm_server_supervise(void)
 			wm_close_window(i);
 		}
 	}
-
-	if (wm_expected_pid && process_is_alive(wm_expected_pid))
-		return;
-	wm_server_start();
 }
 
 void wm_server_init(void)
@@ -1312,10 +1273,8 @@ void wm_server_init(void)
 	}
 	wm_full_redraw = 1;
 	wm_boot_ready = 0;
-	wm_boot_logged = 0;
 	wm_ptr_buttons = 0;
 	wm_ptr_capture = -1;
-	wm_expected_pid = 0;
 	wm_pid = 0;
 	wm_cr3 = 0;
 	wm_attached = 0;

+ 0 - 1
kernel/wm.h

@@ -61,7 +61,6 @@ int  wm_spawn_terminal(void);
 
 /* Kernel window server / ring-3 WM ABI (see wm_abi.h). */
 void wm_server_init(void);
-void wm_server_start(void);
 void wm_server_supervise(void);
 int  wm_server_is_wm(void);
 int  wm_server_frame_active(void);

+ 1 - 1
tools/netkexec_send.c

@@ -177,7 +177,7 @@ int main(int argc, char **argv)
 	if (pack_path)
 		pdata = read_file(pack_path, &psize);
 	size = ksize + psize;
-	if (size <= 0 || size > 0x400000) {   /* matches kexec.h KEXEC_MAX */
+	if (size <= 0 || size > 0x800000) {   /* matches kexec.h KEXEC_MAX */
 		fprintf(stderr, "netkexec_send: bad total size %ld\n", size);
 		return 1;
 	}

+ 395 - 25
user/apps/browser/browser.c

@@ -363,6 +363,10 @@ struct lay {
 struct hit {
 	int x, y, w, h;
 	unsigned short node;
+	/* A painted absolute/fixed box (a modal, its backdrop, a fixed
+	 * header): it hides the hits painted before it.  Inserted below the
+	 * box's own hits, so its links still win. */
+	unsigned char occl;
 };
 
 /* Live form state; the DOM attributes stay the initial/default value. */
@@ -392,6 +396,8 @@ static int s_eq(const char *a, const char *b);
 static void form_key(int k);
 static void form_click(unsigned int node);
 static void style_for_node(unsigned int node, struct br_style *out);
+static void anim_reset(void);
+static void anim_after_frame(void);
 static int form_author_styled(const struct br_style *st);
 static int css_radius(const struct br_style *st, int corner, int w, int h);
 static void form_paint_author(struct ngui *ui, struct ngui_rect box,
@@ -732,6 +738,7 @@ static int heap_start(void)
 
 static void heap_clear(void)
 {
+	anim_reset();           /* also drops the page-heap alpha buffer */
 	memset(font_faces, 0, sizeof(font_faces));
 	memset(font_pick, 0, sizeof(font_pick));
 	ngui_font_detach(&ui);
@@ -1218,7 +1225,12 @@ static int js_host_computed(unsigned int node, const char *property,
 		static const char *cl[] = { "none", "left", "right", "both" };
 		snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
 	} else if (!strcmp(name, "opacity")) {
-		snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
+		if (st.opacity >= 255)
+			snprintf(buf, cap, "1");
+		else
+			snprintf(buf, cap, "0.%02d",
+				 (st.opacity * 100 + 127) / 255 > 99 ? 99 :
+				 (st.opacity * 100 + 127) / 255);
 	} else if (!strcmp(name, "visibility")) {
 		snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
 	} else if (!strcmp(name, "overflow")) {
@@ -8012,6 +8024,7 @@ static void flush_line(struct lay *l)
 						h->w = w;
 						h->h = hh;
 						h->node = (unsigned short)target;
+						h->occl = 0;
 						nhits++;
 					}
 				}
@@ -9935,6 +9948,244 @@ static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
 static int intrinsic_width(struct ngui *ui, unsigned int node,
 			   const struct br_style *pst, int depth, int base);
 
+/* ---- CSS transitions (opacity, transform translate) ----
+ *
+ * The cascade only knows the current computed value, so the paint pass
+ * remembers each element's last target value (pstate[]).  When a later
+ * paint sees a different target and the element has a transition for that
+ * property, an animation from the value on screen to the new target starts
+ * and the page is repainted every pass until it ends; then `transitionend`
+ * is dispatched.  The start state is whatever the previous paint saw: a
+ * script that changes a class right after display (Bootstrap adds `.in`)
+ * forces a reflow first (offsetWidth), and js_force_layout() is a paint
+ * pass, so that state is recorded like in a browser.  Only the render
+ * pass records (render_pass); the measure pass does not. */
+#define ANIM_MAX  32
+#define ANIM_OP   0
+#define ANIM_TX   1
+#define ANIM_TY   2
+
+struct anim {
+	unsigned short node;
+	unsigned char prop, ease;
+	short from, to;
+	unsigned int t0, dur;
+	unsigned int seq;       /* render_seq of the last paint that saw it */
+};
+
+struct paint_state {
+	short tx, ty;
+	unsigned char op;
+	unsigned char seen;     /* bit per ANIM_* prop */
+};
+
+static struct paint_state pstate[BR_MAX_NODES];
+static struct anim anims[ANIM_MAX];
+static int nanims;
+static int render_pass;
+static unsigned int render_seq;
+static unsigned short anim_ended[ANIM_MAX];
+static int nanim_ended;
+
+
+
+static int anim_ease(int ease, int p)      /* p and result 0..1024 */
+{
+	int q = 1024 - p;
+
+	switch (ease) {
+	case BR_EASE_LINEAR:
+		return p;
+	case BR_EASE_IN:
+		return (int)((long)p * p / 1024);
+	case BR_EASE_OUT:
+		return 1024 - (int)((long)q * q / 1024 * q / 1024);
+	default:                /* ease, ease-in-out: smoothstep */
+		return (int)((long)p * p / 1024 * (3072 - 2 * p) / 1024);
+	}
+}
+
+static int anim_find(unsigned int node, int prop)
+{
+	int i;
+
+	for (i = 0; i < nanims; i++)
+		if (anims[i].node == node && anims[i].prop == prop)
+			return i;
+	return -1;
+}
+
+static int anim_now(const struct anim *a, unsigned int now)
+{
+	unsigned int dt = now - a->t0;
+	int p;
+
+	if (dt >= a->dur)
+		return a->to;
+	p = anim_ease(a->ease, (int)(dt * 1024 / a->dur));
+	return a->from + (int)((long)(a->to - a->from) * p / 1024);
+}
+
+static int anim_has(unsigned int node)
+{
+	int i;
+
+	for (i = 0; i < nanims; i++)
+		if (anims[i].node == node)
+			return 1;
+	return 0;
+}
+
+/* The value to paint for a property whose computed target is `target`. */
+static int anim_value(unsigned int node, int prop, int target,
+		      const struct br_style *st)
+{
+	struct paint_state *ps;
+	unsigned int now = u_ticks_ms();
+	int i, prev, bit = 1 << prop;
+	int tr = prop == ANIM_OP ? (st->tr_mask & BR_TR_OPACITY) :
+				   (st->tr_mask & BR_TR_TRANSFORM);
+
+	if (!render_pass || node >= BR_MAX_NODES)
+		return target;
+	ps = &pstate[node];
+	prev = prop == ANIM_OP ? ps->op : prop == ANIM_TX ? ps->tx : ps->ty;
+	i = anim_find(node, prop);
+	if ((ps->seen & bit) && prev != target) {
+		if (tr && st->tr_ms) {
+			int from = i >= 0 ? anim_now(&anims[i], now) : prev;
+
+			if (i < 0 && nanims < ANIM_MAX)
+				i = nanims++;
+			if (i >= 0) {
+				anims[i].node = (unsigned short)node;
+				anims[i].prop = (unsigned char)prop;
+				anims[i].ease = st->tr_ease;
+				anims[i].from = (short)from;
+				anims[i].to = (short)target;
+				anims[i].t0 = now;
+				anims[i].dur = st->tr_ms;
+				anims[i].seq = render_seq;
+			}
+		} else if (i >= 0) {
+			anims[i] = anims[--nanims];
+			i = -1;
+		}
+	}
+	ps->seen |= (unsigned char)bit;
+	if (prop == ANIM_OP)
+		ps->op = (unsigned char)target;
+	else if (prop == ANIM_TX)
+		ps->tx = (short)target;
+	else
+		ps->ty = (short)target;
+	if (i < 0)
+		return target;
+	anims[i].seq = render_seq;
+	if (now - anims[i].t0 >= anims[i].dur) {
+		if (nanim_ended < ANIM_MAX)
+			anim_ended[nanim_ended++] = anims[i].node;
+		anims[i] = anims[--nanims];
+		return target;
+	}
+	return anim_now(&anims[i], now);
+}
+
+/* After the frame: running animations need another paint, and finished
+ * ones get their `transitionend` (Bootstrap also has a timer fallback). */
+static void anim_after_frame(void)
+{
+	static unsigned int checked_seq;
+	int i, j, n = nanim_ended;
+
+	/* An element removed or hidden mid-transition is no longer painted;
+	 * its animation would otherwise keep every frame re-rendering. */
+	if (render_seq != checked_seq) {
+		for (i = 0; i < nanims; )
+			if (anims[i].seq != render_seq)
+				anims[i] = anims[--nanims];
+			else
+				i++;
+		checked_seq = render_seq;
+	}
+	if (nanims) {
+		page_cache_valid = 0;
+		ngui_invalidate(&ui);
+	}
+	nanim_ended = 0;
+	if (!js_browser_active())
+		return;
+	for (i = 0; i < n; i++) {
+		for (j = 0; j < i; j++)
+			if (anim_ended[j] == anim_ended[i])
+				break;
+		if (j == i && anim_ended[i] < doc.nnode)
+			js_browser_event(anim_ended[i], "transitionend", 1, 0);
+	}
+}
+
+/* Group opacity for a translucent positioned box: the page area under it
+ * is saved before the box paints and blended back afterwards. */
+static unsigned short *alpha_snap;
+static unsigned int alpha_snap_px;
+
+static void anim_reset(void)
+{
+	memset(pstate, 0, sizeof(pstate));
+	nanims = 0;
+	nanim_ended = 0;
+	alpha_snap = 0;         /* lived in the page heap that is being reset */
+	alpha_snap_px = 0;
+}
+
+static int alpha_begin(struct ngui_rect r)
+{
+	unsigned int n = (unsigned int)r.w * (unsigned int)r.h;
+	int y;
+
+	if (r.w <= 0 || r.h <= 0)
+		return 0;
+	if (n > alpha_snap_px) {
+		free(alpha_snap);
+		alpha_snap = (unsigned short *)malloc(n * 2u);
+		alpha_snap_px = alpha_snap ? n : 0;
+		if (!alpha_snap)
+			return 0;
+	}
+	for (y = 0; y < r.h; y++)
+		memcpy(alpha_snap + y * r.w, ui.px + (r.y + y) * ui.w + r.x,
+		       (unsigned int)r.w * 2u);
+	return 1;
+}
+
+static void alpha_end(struct ngui_rect r, struct ngui_rect box, int a)
+{
+	int x, y, x0, x1, y0, y1;
+
+	x0 = box.x > r.x ? box.x : r.x;
+	y0 = box.y > r.y ? box.y : r.y;
+	x1 = box.x + box.w < r.x + r.w ? box.x + box.w : r.x + r.w;
+	y1 = box.y + box.h < r.y + r.h ? box.y + box.h : r.y + r.h;
+	for (y = y0; y < y1; y++) {
+		unsigned short *d = ui.px + y * ui.w;
+		const unsigned short *o = alpha_snap + (y - r.y) * r.w - r.x;
+
+		for (x = x0; x < x1; x++) {
+			unsigned int n = d[x], b = o[x];
+			unsigned int rr, gg, bb;
+
+			if (n == b)
+				continue;
+			rr = (((n >> 11) & 31) * a + ((b >> 11) & 31) *
+			      (255 - a)) / 255;
+			gg = (((n >> 5) & 63) * a + ((b >> 5) & 63) *
+			      (255 - a)) / 255;
+			bb = ((n & 31) * a + (b & 31) * (255 - a)) / 255;
+			d[x] = (unsigned short)(rr << 11 | gg << 5 | bb);
+		}
+	}
+}
+
 static void layout_block(struct lay *l, unsigned int node,
 			 const struct br_style *st, int depth,
 			 unsigned short link)
@@ -10078,9 +10329,25 @@ static void layout_block(struct lay *l, unsigned int node,
 		rel_dy = st->top_set ? st->top :
 			 (st->bottom_set ? -st->bottom : 0);
 	}
-	if (st->transform_set) {
-		rel_dx += st->tx;
-		rel_dy += st->ty;
+	if (st->transform_set || (st->tr_mask & BR_TR_TRANSFORM) ||
+	    (render_pass && anim_has(node))) {
+		int tx = st->tx, ty = st->ty;
+
+		/* translate(0, -25%): a percentage of the element's own
+		 * box (the measure pass's height, the flow width). */
+		if (st->tx_pct)
+			tx = (old_right - old_left) * st->tx / 100;
+		if (st->ty_pct)
+			ty = node < BR_MAX_NODES ? block_h[node] * st->ty / 100
+						 : 0;
+		if (!st->transform_set)
+			tx = ty = 0;
+		tx = anim_value(node, ANIM_TX, tx, st);
+		ty = anim_value(node, ANIM_TY, ty, st);
+		rel_dx += tx;
+		rel_dy += ty;
+		if (tx || ty)
+			shifted = 1;
 	}
 	if ((doc.nodes[node].tag == BR_TAG_INPUT ||
 	     doc.nodes[node].tag == BR_TAG_TEXTAREA ||
@@ -10485,6 +10752,16 @@ static void layout_block(struct lay *l, unsigned int node,
 	if (!st->height_kind && node < BR_MAX_NODES &&
 	    content_h + deco_h < flex_stretch_h[node])
 		content_h = flex_stretch_h[node] - deco_h;
+	/* A fixed box pinned by both top and bottom with an auto height
+	 * spans the viewport between them (Bootstrap's .modal-backdrop is
+	 * an empty `position: fixed; top: 0; bottom: 0` box). */
+	if (!st->height_kind && st->pos == 2 && st->top_set &&
+	    st->bottom_set) {
+		int fh = page_rect.h - st->top - st->bottom - deco_h;
+
+		if (content_h < fh)
+			content_h = fh;
+	}
 	if (st->max_height_kind) {
 		int mh = st->max_height_kind == 3 ?
 			 cbw * st->max_height_calc_pct / 100 +
@@ -13110,6 +13387,39 @@ static void sort_deferred(void)
 	}
 }
 
+static void hit_add_occluder(unsigned int node, int at)
+{
+	const struct br_layout_box *b;
+	struct hit h;
+	int x0, y0, x1, y1;
+
+	if (node >= BR_MAX_NODES || nhits >= HIT_MAX || at > nhits)
+		return;
+	b = &layout_boxes[node];
+	if (!b->valid)
+		return;
+	x0 = b->x > page_rect.x ? b->x : page_rect.x;
+	y0 = b->y > page_rect.y ? b->y : page_rect.y;
+	x1 = b->x + b->w;
+	y1 = b->y + b->h;
+	if (x1 > page_rect.x + page_rect.w - 12)
+		x1 = page_rect.x + page_rect.w - 12;
+	if (y1 > page_rect.y + page_rect.h)
+		y1 = page_rect.y + page_rect.h;
+	if (x1 <= x0 || y1 <= y0)
+		return;
+	h.x = x0;
+	h.y = y0;
+	h.w = x1 - x0;
+	h.h = y1 - y0;
+	h.node = (unsigned short)node;
+	h.occl = 1;
+	memmove(&hits[at + 1], &hits[at],
+		(unsigned int)(nhits - at) * sizeof(hits[0]));
+	hits[at] = h;
+	nhits++;
+}
+
 static void render_page(int left, int right, int y0)
 {
 	struct lay *l = &layout_state;
@@ -13139,6 +13449,8 @@ static void render_page(int left, int right, int y0)
 	l->space_pending = 0;
 	nhits = 0;
 	ndeferred = 0;
+	render_pass = 1;
+	render_seq++;
 	base = root_style();
 	layout_children(l, doc.root, &base, 0, 0);
 	sort_deferred();
@@ -13147,15 +13459,22 @@ static void render_page(int left, int right, int y0)
 
 		for (i = 0; i < ndeferred; i++) {
 			struct br_style st;
-			int hide;
+			int hide, op, blend, hit0;
 
 			br_style_for(&doc, deferred[i].node, &base, &st);
 			if (st.display == BR_DISPLAY_NONE)
 				continue;
 			/* A transparent or visibility:hidden positioned box
 			 * still gets its boxes (scripts measure it) but no
-			 * paint and no hit rectangles. */
-			hide = st.opacity_hidden || st.vis_hidden;
+			 * paint and no hit rectangles.  A translucent one
+			 * (a 50% modal backdrop, a fading tooltip) is
+			 * blended over what is under it; the opacity may be
+			 * mid-transition. */
+			hit0 = nhits;
+			op = anim_value(deferred[i].node, ANIM_OP, st.opacity,
+					&st);
+			hide = op == 0 || st.vis_hidden;
+			blend = !hide && op < 255 && alpha_begin(page_rect);
 			l->draw = !hide;
 			l->left = deferred[i].flow_left;
 			l->right = deferred[i].flow_right;
@@ -13230,25 +13549,62 @@ static void render_page(int left, int right, int y0)
 				layout_block(l, deferred[i].node, &st, 0,
 					     deferred[i].link);
 			}
+			if (!hide && !st.pe_none &&
+			    (st.pos == 1 || st.pos == 2) &&
+			    (st.has_bg || st.bg_image || st.z_set))
+				hit_add_occluder(deferred[i].node, hit0);
+			if (blend) {
+				const struct br_layout_box *b =
+					&layout_boxes[deferred[i].node];
+				struct ngui_rect box = page_rect;
+
+				/* The box itself; descendants may overflow
+				 * it, so a full-page box is the safe case. */
+				if (deferred[i].node < BR_MAX_NODES &&
+				    b->valid) {
+					box.x = b->x;
+					box.y = b->y;
+					box.w = b->w;
+					box.h = b->h;
+				}
+				alpha_end(page_rect, box, op);
+			}
 		}
 	}
+	render_pass = 0;
 }
 
 /* ---- UI ---- */
 
-static int find_hit(int x, int y)
+/* The link/control under a point, topmost first.  An occluder above it
+ * returns 0 and its node in *occl (when given), so the caller can target
+ * the covering box instead of content painted underneath. */
+static int find_hit_ex(int x, int y, int *occl)
 {
 	int i;
 
+	if (occl)
+		*occl = -1;
 	for (i = nhits - 1; i >= 0; i--) {
 		struct hit *h = &hits[i];
 		if (x >= h->x && y >= h->y && x < h->x + h->w &&
-		    y < h->y + h->h)
+		    y < h->y + h->h) {
+			if (h->occl) {
+				if (occl)
+					*occl = (int)h->node;
+				return 0;
+			}
 			return (int)h->node;
+		}
 	}
 	return 0;
 }
 
+static int find_hit(int x, int y)
+{
+	return find_hit_ex(x, y, 0);
+}
+
 /* ---- URL-bar autocomplete ----
  *
  * While the address bar has the focus a dropdown lists up to SUG_MAX
@@ -13858,7 +14214,21 @@ static void draw_page(struct ngui_rect page)
  * boxes for nodes they just inserted.  Absolute/fixed boxes only get their
  * boxes in the painting pass, so this is a full render; the next frame
  * repaints the screen as usual.  Skipped while the page has never been
- * drawn (no viewport yet) or without the back buffer. */
+ * drawn (no viewport yet) or without the back buffer.
+ *
+ * The guard is a count per main-loop pass, not a time budget: a hover or
+ * click handler (Bootstrap's tooltip does ~6 write/read rounds) must get
+ * correct geometry even on the ION, where one re-layout of cloudron.io
+ * takes longer than any reasonable per-window budget; only a script that
+ * keeps writing and reading in one pass falls back to the last layout. */
+#define FORCE_LAYOUT_PER_PASS 8
+static int force_layout_count;
+
+static void js_force_layout_pass_reset(void)
+{
+	force_layout_count = 0;
+}
+
 static void js_force_layout(void)
 {
 	static int busy;
@@ -13866,23 +14236,12 @@ static void js_force_layout(void)
 	int saved_w = ui.w, saved_h = ui.h;
 	struct ngui_rect page = page_rect;
 
-	static unsigned int window_t0, spent;
-	unsigned int t0 = u_ticks_ms();
-
 	if (busy || !page_backbuf || pagebuf_w != ui.w ||
 	    pagebuf_h != ui.h || page.w < 40 || page.h < 40 ||
-	    layout_right <= layout_left)
-		return;
-	/* Budget: a script that alternates writes and reads (an animation
-	 * loop) would otherwise re-render the page on every read.  Past
-	 * 40 ms of forced layouts in a 100 ms window it reads the last
-	 * layout, as before. */
-	if (t0 - window_t0 >= 100) {
-		window_t0 = t0;
-		spent = 0;
-	}
-	if (spent >= 40)
+	    layout_right <= layout_left ||
+	    force_layout_count >= FORCE_LAYOUT_PER_PASS)
 		return;
+	force_layout_count++;
 	busy = 1;
 	ui.px = page_backbuf;
 	layout_view_h = page.h;
@@ -13897,7 +14256,6 @@ static void js_force_layout(void)
 	ui.h = saved_h;
 	page_cache_valid = 0;
 	ngui_invalidate(&ui);
-	spent += u_ticks_ms() - t0;
 	busy = 0;
 }
 
@@ -14806,10 +15164,17 @@ static int node_invisible(unsigned int n)
  * that contains it (the last one wins a tie, i.e. the later/deeper node).
  * Used to deliver clicks to elements that are neither links nor controls
  * (a Vue <div role="button">, a card with a click listener). */
+static int node_contains(unsigned int a, unsigned int n);
+
 static unsigned int find_box_hit(int x, int y)
 {
 	unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
+	int root;
 
+	/* A covering positioned box (a modal) takes the point: only it and
+	 * its descendants are candidates, not the page painted under it. */
+	if (find_hit_ex(x, y, &root) || root < 0)
+		root = -1;
 	for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
 		const struct br_layout_box *b = &layout_boxes[i];
 		unsigned int area;
@@ -14818,6 +15183,8 @@ static unsigned int find_box_hit(int x, int y)
 		    x < b->x || y < b->y || x >= b->x + b->w ||
 		    y >= b->y + b->h)
 			continue;
+		if (root >= 0 && !node_contains((unsigned int)root, i))
+			continue;
 		area = (unsigned int)b->w * (unsigned int)b->h;
 		if (area <= best_area && !node_invisible(i)) {
 			best = i;
@@ -15200,6 +15567,7 @@ void _start(const char *arg)
 			preload_node = 0;
 			preload_active = 1;
 		}
+		js_force_layout_pass_reset();
 		js_browser_tick();
 		if (resize_pending && !pending_action) {
 			resize_pending = 0;
@@ -15227,10 +15595,12 @@ void _start(const char *arg)
 				continue;
 			}
 		} else {
+			js_force_layout_pass_reset();
 			draw(&action);
 			handle_keys(&action);
 			handle_page_click(&action);
 			page_hover_events();
+			anim_after_frame();
 			ngui_end(&ui);
 		}
 		if (action & ACT_NAV) {

+ 217 - 18
user/apps/browser/browser_html.c

@@ -2541,6 +2541,8 @@ enum {
 	PROP_FILL_MODE, PROP_FILL, PROP_STROKE_MODE, PROP_STROKE,
 	PROP_STROKE_W, PROP_FILL_RULE, PROP_CONTENT,
 	PROP_ASPECT_W, PROP_ASPECT_H, PROP_CURSOR,
+	PROP_TX_PCT, PROP_TY_PCT, PROP_TR_MASK, PROP_TR_MS, PROP_TR_EASE,
+	PROP_PE_NONE,
 	PROP_COUNT
 };
 
@@ -3760,6 +3762,163 @@ static int parse_fixed_100(const char *s, unsigned int len,
 	return 1;
 }
 
+/* One translate() argument: px (or rem/em/vw through parse_len), or a
+ * percentage of the element's own box, which only layout can resolve. */
+static int translate_arg(const char *v, unsigned int vl, unsigned int *off,
+			 int *pct)
+{
+	unsigned int q = *off;
+	signed short h100;
+
+	*pct = 0;
+	while (q < vl && is_space(v[q]))
+		q++;
+	if (parse_fixed_100(v, vl, &q, &h100) && q < vl && v[q] == '%') {
+		*off = q + 1;
+		*pct = 1;
+		return h100 / 100;
+	}
+	return parse_len(v, vl, off);
+}
+
+/* "0.3s" / ".15s" / "300ms" -> milliseconds; -1 when not a time. */
+static int parse_time_ms(const char *s, unsigned int len, unsigned int *pos)
+{
+	unsigned int i = *pos;
+	long v = 0, scale = 1000;
+	int digits = 0;
+
+	while (i < len && is_space(s[i]))
+		i++;
+	while (i < len && s[i] >= '0' && s[i] <= '9') {
+		v = v * 10 + (s[i] - '0');
+		digits = 1;
+		i++;
+	}
+	if (i < len && s[i] == '.') {
+		i++;
+		while (i < len && s[i] >= '0' && s[i] <= '9') {
+			if (scale > 1) {
+				v = v * 10 + (s[i] - '0');
+				scale /= 10;
+			}
+			digits = 1;
+			i++;
+		}
+	}
+	if (!digits)
+		return -1;
+	if (i + 1 < len && s[i] == 'm' && s[i + 1] == 's') {
+		*pos = i + 2;
+		v = v * scale / 1000;
+	} else if (i < len && s[i] == 's') {
+		*pos = i + 1;
+		v = v * scale;
+	} else {
+		return -1;
+	}
+	if (v > 10000)
+		v = 10000;
+	return (int)v;
+}
+
+static int ease_code(const char *s, unsigned int n)
+{
+	if (contains_ci_len(s, n, "ease-in-out"))
+		return BR_EASE_IN_OUT;
+	if (contains_ci_len(s, n, "ease-out"))
+		return BR_EASE_OUT;
+	if (contains_ci_len(s, n, "ease-in"))
+		return BR_EASE_IN;
+	if (contains_ci_len(s, n, "linear"))
+		return BR_EASE_LINEAR;
+	if (contains_ci_len(s, n, "cubic-bezier"))
+		return BR_EASE_OUT;
+	return BR_EASE_EASE;
+}
+
+static int tr_prop_mask(const char *s, unsigned int n)
+{
+	int m = 0;
+
+	if (contains_ci_len(s, n, "all"))
+		m |= BR_TR_OPACITY | BR_TR_TRANSFORM;
+	if (contains_ci_len(s, n, "opacity"))
+		m |= BR_TR_OPACITY;
+	if (contains_ci_len(s, n, "transform"))
+		m |= BR_TR_TRANSFORM;
+	return m;
+}
+
+/* `transition` (shorthand, comma list) and its longhands, reduced to the
+ * set of animated properties the engine supports (opacity, transform),
+ * one duration (the longest listed) and the first easing.  A shorthand
+ * item without a property name means `all`. */
+static void add_transition(struct br_decl *out, unsigned int *nout,
+			   const char *prop,
+			   const char *v, unsigned int vl, int important)
+{
+	unsigned int i = 0;
+	int mask = 0, ms = 0, ease = -1;
+
+	if (str_eq(prop, "transition-property")) {
+		decl_add(out, nout, PROP_TR_MASK, tr_prop_mask(v, vl),
+			 important);
+		return;
+	}
+	if (str_eq(prop, "transition-timing-function")) {
+		decl_add(out, nout, PROP_TR_EASE, ease_code(v, vl), important);
+		return;
+	}
+	while (i < vl) {
+		unsigned int a = i, e, q;
+		int t, item_ms = -1;
+
+		while (i < vl && v[i] != ',') {
+			if (v[i] == '(')
+				while (i < vl && v[i] != ')')
+					i++;
+			i++;
+		}
+		e = i < vl ? i : vl;
+		for (q = a; q < e; q++) {
+			unsigned int p = q;
+
+			if ((q == a || is_space(v[q - 1])) &&
+			    (t = parse_time_ms(v, e, &p)) >= 0) {
+				if (item_ms < 0)
+					item_ms = t;    /* the second time is the delay */
+				q = p;
+			}
+		}
+		if (str_eq(prop, "transition-duration")) {
+			if (item_ms > ms)
+				ms = item_ms;
+		} else if (item_ms > 0) {
+			int m = tr_prop_mask(v + a, e - a);
+
+			if (!m && !contains_ci_len(v + a, e - a, "none"))
+				m = BR_TR_OPACITY | BR_TR_TRANSFORM;
+			if (m) {
+				mask |= m;
+				if (item_ms > ms)
+					ms = item_ms;
+				if (ease < 0)
+					ease = ease_code(v + a, e - a);
+			}
+		}
+		i = e + 1;
+	}
+	if (str_eq(prop, "transition-duration")) {
+		decl_add(out, nout, PROP_TR_MS, ms, important);
+		return;
+	}
+	decl_add(out, nout, PROP_TR_MASK, mask, important);
+	decl_add(out, nout, PROP_TR_MS, ms, important);
+	decl_add(out, nout, PROP_TR_EASE, ease < 0 ? BR_EASE_EASE : ease,
+		 important);
+}
+
 static int find_fn(const char *v, unsigned int len, const char *name,
 		   unsigned int *arg)
 {
@@ -5819,6 +5978,10 @@ static void parse_decls(struct br_doc *d, const char *s,
 			decl_add(out, nout, PROP_UNDERLINE, u, important);
 			decl_add(out, nout, PROP_STRIKE, stv, important);
 			decl_add(out, nout, PROP_OVERLINE, ov, important);
+		} else if (str_eq(prop, "pointer-events")) {
+			decl_add(out, nout, PROP_PE_NONE,
+				 vend - vstart >= 4 &&
+				 ci_eq_n(s + vstart, "none", 4), important);
 		} else if (str_eq(prop, "cursor")) {
 			int c = parse_cursor(s + vstart, vend - vstart);
 
@@ -5846,21 +6009,25 @@ static void parse_decls(struct br_doc *d, const char *s,
 						"collapse");
 			decl_add(out, nout, PROP_VIS_HIDDEN, h, important);
 		} else if (str_eq(prop, "opacity")) {
-			unsigned int q;
-			int h = 1, any = 0;
-
-			for (q = vstart; q < vend; q++) {
-				if (s[q] >= '1' && s[q] <= '9') {
-					h = 0;
-					break;
-				}
-				if (s[q] >= '0' && s[q] <= '9')
-					any = 1;
+			/* Stored as transparency (255 - alpha), so a missing
+			 * declaration means opaque.  `0`, `.5`, `0.9`, `50%`;
+			 * anything unparsable (inherit, var leftovers) is 1. */
+			unsigned int q = vstart;
+			signed short h100;
+			int a = 255;
+
+			if (parse_fixed_100(s, vend, &q, &h100)) {
+				int pct = q < vend && s[q] == '%';
+				long v = pct ? h100 / 100 : h100;
+
+				if (v < 0)
+					v = 0;
+				if (v > 100)
+					v = 100;
+				a = (int)(v * 255 / 100);
 			}
-			if (!any || contains_ci_len(s + vstart, vend - vstart,
-						    "inherit"))
-				h = 0;
-			decl_add(out, nout, PROP_OPACITY_HIDDEN, h, important);
+			decl_add(out, nout, PROP_OPACITY_HIDDEN, 255 - a,
+				 important);
 		} else if (str_eq(prop, "overflow") ||
 			   str_eq(prop, "overflow-x") ||
 			   str_eq(prop, "overflow-y")) {
@@ -6103,7 +6270,7 @@ static void parse_decls(struct br_doc *d, const char *s,
 		} else if (str_eq(prop, "transform")) {
 			const char *v = s + vstart;
 			unsigned int vl = vend - vstart;
-			int tx = 0, ty = 0;
+			int tx = 0, ty = 0, txp = 0, typ = 0;
 			int is_x = contains_ci_len(v, vl, "translatex");
 			int is_y = contains_ci_len(v, vl, "translatey");
 			unsigned int off = 0, arg;
@@ -6114,13 +6281,15 @@ static void parse_decls(struct br_doc *d, const char *s,
 				if (off < vl)
 					off++;
 				if (!is_y)
-					tx = parse_len(v, vl, &off);
+					tx = translate_arg(v, vl, &off, &txp);
 				if (!is_x) {
 					while (off < vl &&
 					       (is_space(v[off]) || v[off] == ','))
 						off++;
-					ty = parse_len(v, vl, &off);
+					ty = translate_arg(v, vl, &off, &typ);
 				}
+				decl_add(out, nout, PROP_TX_PCT, txp, important);
+				decl_add(out, nout, PROP_TY_PCT, typ, important);
 				decl_add(out, nout, PROP_TRANSFORM_X, tx,
 					 important);
 				decl_add(out, nout, PROP_TRANSFORM_Y, ty,
@@ -6167,6 +6336,12 @@ static void parse_decls(struct br_doc *d, const char *s,
 						 important);
 				}
 			}
+		} else if (str_eq(prop, "transition") ||
+			   str_eq(prop, "transition-property") ||
+			   str_eq(prop, "transition-duration") ||
+			   str_eq(prop, "transition-timing-function")) {
+			add_transition(out, nout, prop, s + vstart,
+				       vend - vstart, important);
 		} else if (str_eq(prop, "transform-origin")) {
 			add_transform_origin(out, nout, s + vstart,
 					     vend - vstart, important);
@@ -8848,7 +9023,8 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 		st->vis_hidden = (unsigned char)(dcl->val != 0);
 		break;
 	case PROP_OPACITY_HIDDEN:
-		st->opacity_hidden = (unsigned char)(dcl->val != 0);
+		st->opacity = (unsigned char)(255 - (dcl->val & 255));
+		st->opacity_hidden = (unsigned char)(st->opacity == 0);
 		break;
 	case PROP_FILL_MODE:
 		st->fill_mode = (unsigned char)dcl->val;
@@ -9039,6 +9215,24 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 	case PROP_CURSOR:
 		st->cursor = (unsigned char)dcl->val;
 		break;
+	case PROP_PE_NONE:
+		st->pe_none = (unsigned char)(dcl->val != 0);
+		break;
+	case PROP_TX_PCT:
+		st->tx_pct = (unsigned char)(dcl->val != 0);
+		break;
+	case PROP_TY_PCT:
+		st->ty_pct = (unsigned char)(dcl->val != 0);
+		break;
+	case PROP_TR_MASK:
+		st->tr_mask = (unsigned char)dcl->val;
+		break;
+	case PROP_TR_MS:
+		st->tr_ms = (unsigned short)dcl->val;
+		break;
+	case PROP_TR_EASE:
+		st->tr_ease = (unsigned char)dcl->val;
+		break;
 	case PROP_FLOAT:
 		st->float_left = (unsigned char)dcl->val;
 		break;
@@ -9287,7 +9481,12 @@ void br_style_for(struct br_doc *d, unsigned int node,
 	out->z_index = 0;
 	out->z_set = 0;
 	out->tx = out->ty = 0;
+	out->tx_pct = out->ty_pct = 0;
 	out->transform_set = 0;
+	out->opacity = 255;
+	out->tr_mask = 0;
+	out->tr_ms = 0;
+	out->tr_ease = BR_EASE_EASE;
 	out->transform_scale = 0;
 	out->scale_x = out->scale_y = 100;
 	out->rotate_x100 = 0;

+ 15 - 0
user/apps/browser/browser_html.h

@@ -11,6 +11,15 @@
 #define BR_CURSOR_AUTO 0
 
 #define BR_MAX_NODES     16384
+
+/* CSS transitions the engine animates (br_style.tr_mask). */
+#define BR_TR_OPACITY   1
+#define BR_TR_TRANSFORM 2
+#define BR_EASE_LINEAR  0
+#define BR_EASE_EASE    1
+#define BR_EASE_IN      2
+#define BR_EASE_OUT     3
+#define BR_EASE_IN_OUT  4
 #define BR_TEXT_SIZE     524288
 #define BR_ATTR_SIZE     4194304
 #define BR_CSS_SIZE      262144  /* inline <style> text; google.com has ~94 KB */
@@ -163,7 +172,12 @@ struct br_style {
 	signed short z_index;
 	unsigned char z_set;
 	signed short tx, ty;
+	unsigned char tx_pct, ty_pct; /* tx/ty are percent of the own box */
 	unsigned char transform_set;
+	unsigned char opacity;      /* 0..255 (255 opaque); not inherited */
+	unsigned char tr_mask;      /* BR_TR_*: transitioned properties */
+	unsigned char tr_ease;      /* BR_EASE_* */
+	unsigned short tr_ms;       /* transition duration */
 	unsigned char transform_scale; /* scale()/rotate() paint hint */
 	signed short scale_x, scale_y; /* hundredths, 100 = 1.0 */
 	signed short rotate_x100;      /* hundredths of a degree */
@@ -174,6 +188,7 @@ struct br_style {
 	unsigned char list_item;    /* li marker is drawn */
 	unsigned char nowrap;       /* white-space: nowrap (inherited) */
 	unsigned char uppercase;    /* text-transform: uppercase (inherited) */
+	unsigned char pe_none;      /* pointer-events: none (inherited) */
 	unsigned char cursor;       /* CSS cursor (inherited): BR_CURSOR_AUTO or
 				       enum cursor_shape + 1 */
 	unsigned char border_w[4];  /* top, right, bottom, left */

+ 4 - 0
user/apps/browser/ucmd_browser.c

@@ -46,6 +46,10 @@ void _start(const char *arg)
 			u_puts("browser: started ");
 			u_puts(candidates[i]);
 			u_puts("\n");
+			/* Stay in the foreground (and keep the app in this
+			 * terminal/WM session) until it exits. */
+			while (u_alive((unsigned int)pid))
+				u_sleep_ms(100);
 			u_exit(0);
 		}
 	}

+ 1 - 1
user/apps/chat/ucmd_chat.c

@@ -3720,7 +3720,7 @@ static void run_action(void)
 		break;
 	case ACT_OPEN_URL:
 		if (arg >= 0 && arg < nmsg && msgs[arg].preview_url)
-			u_spawn("/ramfs/bin/browser", msgs[arg].preview_url,
+			u_spawn_detached("/ramfs/bin/browser", msgs[arg].preview_url,
 				0, "/");
 		break;
 	case ACT_OLDER:

+ 1 - 1
user/apps/disks/ucmd_disks.c

@@ -846,7 +846,7 @@ open_files:
 		char cwd[24];
 
 		snprintf(cwd, sizeof(cwd), "/%s", m->name);
-		if (u_spawn("/ramfs/bin/files", "", 0, cwd) < 0)
+		if (u_spawn_detached("/ramfs/bin/files", "", 0, cwd) < 0)
 			set_status("Could not start files", 1);
 	}
 	return y + 38;

+ 4 - 4
user/apps/files/ucmd_files.c

@@ -513,7 +513,7 @@ static void open_selected(void)
 	}
 	if (is_html_name(e->name)) {
 		path_join(cwd, e->name, path, sizeof(path));
-		pid = u_spawn("/ramfs/bin/browser", path, 0, cwd);
+		pid = u_spawn_detached("/ramfs/bin/browser", path, 0, cwd);
 		if (pid <= 0)
 			set_status("Cannot launch the browser", 1);
 		else
@@ -526,7 +526,7 @@ static void open_selected(void)
 			return;
 		}
 		path_join(cwd, e->name, path, sizeof(path));
-		pid = u_spawn("/ramfs/bin/view", path, 0, cwd);
+		pid = u_spawn_detached("/ramfs/bin/view", path, 0, cwd);
 		if (pid <= 0)
 			set_status("Cannot launch the viewer", 1);
 		else
@@ -538,7 +538,7 @@ static void open_selected(void)
 		return;
 	}
 	path_join(cwd, e->name, path, sizeof(path));
-	pid = u_spawn("/ramfs/bin/edit", path, 0, cwd);
+	pid = u_spawn_detached("/ramfs/bin/edit", path, 0, cwd);
 	if (pid <= 0)
 		set_status("Cannot launch the editor", 1);
 	else
@@ -613,7 +613,7 @@ static void do_action(unsigned int action)
 	if (action & ACT_NEW)
 		new_folder();
 	if ((action & ACT_DISKS) &&
-	    u_spawn("/ramfs/bin/disks", "", 0, "/") < 0)
+	    u_spawn_detached("/ramfs/bin/disks", "", 0, "/") < 0)
 		set_status("Cannot start disks", 1);
 	if (action & ACT_OPEN)
 		open_selected();

+ 2 - 0
user/apps/gallery/ucmd_gallery.c

@@ -44,6 +44,8 @@ void _start(const char *arg)
 			u_puts("gallery: started ");
 			u_puts(candidates[i]);
 			u_puts("\n");
+			while (u_alive((unsigned int)pid))
+				u_sleep_ms(100);
 			u_exit(0);
 		}
 	}

+ 634 - 0
user/apps/init/ucmd_init.c

@@ -0,0 +1,634 @@
+/* init: the userland service manager.
+ *
+ * The kernel starts this as PID 1 after /ramfs and /share are mounted.  It
+ * owns the WM and the service processes:
+ *   - spawns /ramfs/bin/wm, adopts nothing (the kernel never starts a WM),
+ *     and relaunches it when it dies;
+ *   - starts/stops/restarts services and drains one tty per service into
+ *     /share/svc-<name>.log;
+ *   - keeps /share/svc-<name>.state and /share/init.state for the CLI/GUI;
+ *   - serves a small control protocol on its own tty.
+ *
+ * On restart it kills every leftover ring-3 process first, so a crashed init
+ * always comes back to a clean userland tree.  Kernel threads (kworker,
+ * bootscan, netkexec, ...) are left alone.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "service_proto.h"
+#include "ucmd_lib.h"
+
+#define INIT_LOG_MAX   8192u
+#define LOOP_MS        100u
+#define START_GRACE_MS 300u
+#define RESTART_MS     200u
+#define DRAIN_CHUNK    1024u
+
+struct svc_rt {
+	const struct svc_def *def;
+	unsigned int state;
+	unsigned int desired;
+	unsigned int pid;
+	int tty;
+	unsigned int started;
+	unsigned int restart_at;
+	int restart_pending;
+	char *log;
+	unsigned int log_len;
+	int log_dirty;
+	int state_dirty;
+};
+
+static int ctl_tty;
+static int wm_pid;
+static unsigned int wm_restart_at;
+static struct svc_rt rt[SVC_MAX];
+static char init_log[INIT_LOG_MAX];
+static unsigned int init_log_len;
+static int init_log_dirty;
+static char line[256];
+static unsigned int line_len;
+
+static unsigned int now_ms(void)
+{
+	return u_ticks_ms();
+}
+
+static unsigned int atou(const char *s)
+{
+	unsigned int n = 0;
+
+	while (*s >= '0' && *s <= '9')
+		n = n * 10 + (unsigned int)(*s++ - '0');
+	return n;
+}
+
+/* Append bytes to a bounded linear log, dropping the oldest data first. */
+static void append_log(char *buf, unsigned int *len, unsigned int cap,
+		       const char *s, unsigned int n)
+{
+	if (!buf || !cap)
+		return;
+	if (n >= cap) {
+		s += n - (cap - 1);
+		n = cap - 1;
+	}
+	if (*len + n >= cap) {
+		unsigned int drop = *len + n - (cap - 1);
+
+		memmove(buf, buf + drop, *len - drop);
+		*len -= drop;
+	}
+	memcpy(buf + *len, s, n);
+	*len += n;
+}
+
+static void init_log_add(const char *s)
+{
+	append_log(init_log, &init_log_len, INIT_LOG_MAX, s,
+		   (unsigned int)strlen(s));
+	init_log_dirty = 1;
+}
+
+static void init_log_addf(const char *fmt, unsigned int a)
+{
+	char buf[80];
+	int n = snprintf(buf, sizeof(buf), fmt, a);
+
+	if (n > 0)
+		init_log_add(buf);
+}
+
+static void init_log_flush(void)
+{
+	if (!init_log_dirty)
+		return;
+	if (u_write_file(SVC_INIT_LOG, init_log, init_log_len) == 0)
+		init_log_dirty = 0;
+}
+
+static void svc_log_flush(struct svc_rt *s)
+{
+	char path[64];
+
+	if (!s->log_dirty || !s->log || !s->log_len)
+		return;
+	if (svc_make_log_path(path, sizeof(path), s->def->name) == 0 &&
+	    u_write_file(path, s->log, s->log_len) == 0)
+		s->log_dirty = 0;
+}
+
+static void svc_state_write(struct svc_rt *s)
+{
+	struct svc_state st;
+	char path[64], buf[256];
+
+	if (!s->state_dirty)
+		return;
+	memset(&st, 0, sizeof(st));
+	{
+		unsigned int i;
+
+		for (i = 0; s->def->name[i] && i + 1 < sizeof(st.name); i++)
+			st.name[i] = s->def->name[i];
+		st.name[i] = '\0';
+	}
+	st.state = s->state;
+	st.desired = s->desired;
+	st.pid = (s->pid && u_alive(s->pid)) ? s->pid : 0;
+	st.tty = s->tty > 0 ? (unsigned int)s->tty : 0;
+	st.started = s->started;
+	if (svc_make_state_path(path, sizeof(path), s->def->name) != 0 ||
+	    svc_format_state(buf, sizeof(buf), &st) != 0)
+		return;
+	if (u_write_file(path, buf, (unsigned int)strlen(buf)) == 0)
+		s->state_dirty = 0;
+}
+
+static void init_state_write(void)
+{
+	struct init_state st;
+	char buf[128];
+
+	st.pid = (unsigned int)u_getpid();
+	st.ctl = ctl_tty > 0 ? (unsigned int)ctl_tty : 0;
+	st.wm = (wm_pid > 0 && u_alive((unsigned int)wm_pid)) ?
+		(unsigned int)wm_pid : 0;
+	st.valid = 1;
+	if (svc_format_init_state(buf, sizeof(buf), &st) == 0)
+		u_write_file(SVC_INIT_STATE, buf, (unsigned int)strlen(buf));
+}
+
+/* Kill every user process except ourselves; kernel threads stay.  This is
+ * the clean-slate recovery path after an init crash. */
+static void reset_userland(void)
+{
+	struct sys_procinfo pi;
+	unsigned int pids[64];
+	unsigned int n = 0, i;
+	int self = u_getpid();
+
+	for (i = 0; n < 64 && u_procinfo(i, &pi) == 1; i++) {
+		if (pi.pid && pi.pid != (unsigned int)self && !pi.kernel_thread)
+			pids[n++] = pi.pid;
+	}
+	for (i = 0; i < n; i++)
+		u_kill(pids[i]);
+	if (n) {
+		init_log_addf("init: reset %u user processes\n", n);
+		u_sleep_ms(150);
+	}
+}
+
+static void drain_service(struct svc_rt *s)
+{
+	char buf[DRAIN_CHUNK];
+	unsigned int total = 0;
+	int n;
+
+	if (s->tty <= 0 || !s->log)
+		return;
+	while (total < 8192 &&
+	       (n = u_tty_read(s->tty, buf, sizeof(buf))) > 0) {
+		append_log(s->log, &s->log_len, SVC_LOG_MAX, buf,
+			   (unsigned int)n);
+		s->log_dirty = 1;
+		total += (unsigned int)n;
+	}
+}
+
+static int svc_start(struct svc_rt *s)
+{
+	char msg[96];
+	int pid;
+
+	if (s->pid && u_alive(s->pid))
+		return 0;
+	if (s->pid) {
+		drain_service(s);
+		if (s->tty > 0)
+			u_tty_close(s->tty);
+		s->pid = 0;
+		s->tty = 0;
+	}
+	if (s->tty <= 0)
+		s->tty = u_tty_alloc();
+	if (s->tty <= 0) {
+		snprintf(msg, sizeof(msg), "init: %s: no tty\n", s->def->name);
+		init_log_add(msg);
+		snprintf(msg, sizeof(msg), "[init] %s: no tty\n", s->def->name);
+		append_log(s->log, &s->log_len, SVC_LOG_MAX, msg,
+			   (unsigned int)strlen(msg));
+		s->desired = 0;
+		s->state = SVC_STOPPED;
+		s->state_dirty = 1;
+		s->log_dirty = 1;
+		return -1;
+	}
+	snprintf(msg, sizeof(msg), "[init] starting %s\n", s->def->name);
+	append_log(s->log, &s->log_len, SVC_LOG_MAX, msg,
+		   (unsigned int)strlen(msg));
+	pid = u_spawn(s->def->path, s->def->args, s->tty, "/");
+	if (pid <= 0) {
+		snprintf(msg, sizeof(msg), "[init] %s: spawn failed\n",
+			 s->def->name);
+		append_log(s->log, &s->log_len, SVC_LOG_MAX, msg,
+			   (unsigned int)strlen(msg));
+		u_tty_close(s->tty);
+		s->tty = 0;
+		s->pid = 0;
+		s->desired = 0;
+		s->state = SVC_STOPPED;
+		s->state_dirty = 1;
+		s->log_dirty = 1;
+		return -1;
+	}
+	s->pid = (unsigned int)pid;
+	s->state = SVC_STARTING;
+	s->started = now_ms();
+	s->restart_pending = 0;
+	s->state_dirty = 1;
+	s->log_dirty = 1;
+	return 0;
+}
+
+static void svc_stop(struct svc_rt *s, int force)
+{
+	s->desired = 0;
+	s->restart_pending = 0;
+	if (s->pid && u_alive(s->pid))
+		u_kill(s->pid);
+	if (s->pid && u_alive(s->pid)) {
+		/* Let svc_poll() drain the final bytes and observe the process
+		 * die; never untrack a still-live pid. */
+		s->state = SVC_STOPPING;
+		s->state_dirty = 1;
+		return;
+	}
+	if (s->pid) {
+		char msg[80];
+
+		drain_service(s);
+		if (s->tty > 0)
+			u_tty_close(s->tty);
+		snprintf(msg, sizeof(msg), "[init] %s: %s\n", s->def->name,
+			 force ? "killed" : "stopped");
+		append_log(s->log, &s->log_len, SVC_LOG_MAX, msg,
+			   (unsigned int)strlen(msg));
+		s->pid = 0;
+		s->tty = 0;
+		s->log_dirty = 1;
+	}
+	s->state = SVC_STOPPED;
+	s->state_dirty = 1;
+}
+
+static void svc_restart(struct svc_rt *s)
+{
+	s->desired = 1;
+	s->restart_pending = 1;
+	s->restart_at = now_ms() + RESTART_MS;
+	if (s->pid && u_alive(s->pid))
+		u_kill(s->pid);
+	s->state = SVC_RESTARTING;
+	s->state_dirty = 1;
+}
+
+static void svc_poll(struct svc_rt *s)
+{
+	unsigned int now = now_ms();
+
+	if (s->pid && u_alive(s->pid)) {
+		drain_service(s);
+		if (s->state == SVC_STARTING &&
+		    now - s->started >= START_GRACE_MS) {
+			s->state = SVC_RUNNING;
+			s->state_dirty = 1;
+		}
+		return;
+	}
+	if (s->pid) {
+		char msg[80];
+
+		drain_service(s);
+		if (s->tty > 0)
+			u_tty_close(s->tty);
+		s->tty = 0;
+		snprintf(msg, sizeof(msg), "[init] %s: exited\n", s->def->name);
+		append_log(s->log, &s->log_len, SVC_LOG_MAX, msg,
+			   (unsigned int)strlen(msg));
+		s->pid = 0;
+		s->log_dirty = 1;
+		if (s->restart_pending && s->desired) {
+			s->state = SVC_RESTARTING;
+			s->state_dirty = 1;
+		} else {
+			s->desired = 0;
+			s->state = SVC_STOPPED;
+			s->state_dirty = 1;
+		}
+		return;
+	}
+	if (s->desired && s->restart_pending) {
+		if ((int)(now - s->restart_at) >= 0)
+			svc_start(s);
+		return;
+	}
+	if (s->desired && !s->restart_pending)
+		svc_start(s);
+}
+
+static void wm_spawn(void)
+{
+	char msg[64];
+	int pid;
+
+	if (wm_pid > 0 && u_alive((unsigned int)wm_pid))
+		return;
+	pid = u_spawn("/ramfs/bin/wm", "", 0, "/");
+	if (pid <= 0) {
+		init_log_add("init: wm spawn failed\n");
+		wm_pid = 0;
+		wm_restart_at = now_ms() + 1000;
+		init_state_write();
+		return;
+	}
+	wm_pid = pid;
+	wm_restart_at = 0;
+	snprintf(msg, sizeof(msg), "init: wm started pid %d\n", pid);
+	init_log_add(msg);
+	init_state_write();
+}
+
+static void wm_poll(void)
+{
+	unsigned int now = now_ms();
+
+	if (wm_pid > 0 && !u_alive((unsigned int)wm_pid)) {
+		char msg[64];
+
+		snprintf(msg, sizeof(msg), "init: wm pid %d exited\n", wm_pid);
+		init_log_add(msg);
+		wm_pid = 0;
+		wm_restart_at = now + RESTART_MS;
+		init_state_write();
+	}
+	if (wm_pid <= 0 && (int)(now - wm_restart_at) >= 0)
+		wm_spawn();
+}
+
+static int read_text(const char *path, char *buf, unsigned int max)
+{
+	int n = u_read_file(path, buf, max);
+
+	if (n < 0)
+		return -1;
+	if ((unsigned int)n >= max)
+		n = (int)max - 1;
+	buf[n] = '\0';
+	return n;
+}
+
+static void load_services(void)
+{
+	char path[64], buf[512], log[128];
+	unsigned int i, now = now_ms();
+
+	for (i = 0; i < svc_def_count && i < SVC_MAX; i++) {
+		struct svc_rt *s = &rt[i];
+		struct svc_state st;
+		int n;
+
+		memset(s, 0, sizeof(*s));
+		s->def = &svc_defs[i];
+		s->tty = 0;
+		s->state = SVC_STOPPED;
+		s->desired = (svc_defs[i].flags & SVC_AUTOSTART) ? 1u : 0u;
+		s->log = (char *)malloc(SVC_LOG_MAX);
+		s->log_len = 0;
+		if (svc_make_state_path(path, sizeof(path), s->def->name) == 0 &&
+		    read_text(path, buf, sizeof(buf)) > 0 &&
+		    svc_parse_state(buf, (unsigned int)strlen(buf), &st) == 0) {
+			s->desired = st.desired ? 1u : 0u;
+		}
+		if (s->desired) {
+			s->restart_pending = 1;
+			/* Leave the reaper time to drop the old NIC/disk leases. */
+			s->restart_at = now + 300;
+		}
+		if (s->log &&
+		    svc_make_log_path(path, sizeof(path), s->def->name) == 0) {
+			n = u_read_file(path, s->log, SVC_LOG_MAX);
+			if (n > 0)
+				s->log_len = (unsigned int)n;
+		}
+		s->state_dirty = 1;
+		if (!s->log) {
+			snprintf(log, sizeof(log), "init: %s: no log memory\n",
+				 s->def->name);
+			init_log_add(log);
+		}
+	}
+}
+
+static void respond(int resp, unsigned int seq, int code, int pid,
+		    const char *msg)
+{
+	char rsp[160];
+	int n = snprintf(rsp, sizeof(rsp), "%s %u %d %d %s\n",
+			 SVC_CTL_MAGIC, seq, code, pid, msg);
+
+	if (n > 0 && (unsigned int)n < sizeof(rsp))
+		u_tty_write(resp, rsp, (unsigned int)n);
+}
+
+static char *next_tok(char **pp)
+{
+	char *p = *pp;
+	char *s;
+
+	while (*p == ' ' || *p == '\t')
+		p++;
+	if (!*p) {
+		*pp = p;
+		return NULL;
+	}
+	s = p;
+	while (*p && *p != ' ' && *p != '\t')
+		p++;
+	if (*p)
+		*p++ = '\0';
+	*pp = p;
+	return s;
+}
+
+static void handle_line(char *s, unsigned int len)
+{
+	char *p = s, *magic, *seqs, *op, *name, *resps;
+	unsigned int seq;
+	int resp, code = 0, pid = 0;
+	const char *msg = "ok";
+	int idx;
+
+	if (!len)
+		return;
+	magic = next_tok(&p);
+	seqs = next_tok(&p);
+	op = next_tok(&p);
+	name = next_tok(&p);
+	resps = next_tok(&p);
+	if (!magic || !seqs || !op || !name || !resps)
+		return;
+	if (strcmp(magic, SVC_CTL_MAGIC) != 0)
+		return;
+	seq = atou(seqs);
+	resp = (int)atou(resps);
+	if (resp <= 0)
+		return;
+
+	if (strcmp(name, "init") == 0) {
+		if (strcmp(op, "ping") == 0) {
+			pid = u_getpid();
+		} else {
+			code = 5;
+			msg = "init is protected";
+		}
+	} else if (strcmp(name, "wm") == 0) {
+		if (strcmp(op, "start") == 0) {
+			if (wm_pid > 0 && u_alive((unsigned int)wm_pid)) {
+				code = 3;
+				pid = wm_pid;
+				msg = "already running";
+			} else {
+				wm_spawn();
+				if (wm_pid > 0) {
+					pid = wm_pid;
+					msg = "started";
+				} else {
+					code = 1;
+					msg = "spawn failed";
+				}
+			}
+		} else if (strcmp(op, "restart") == 0 ||
+			   strcmp(op, "kill") == 0) {
+			if (wm_pid > 0 && u_alive((unsigned int)wm_pid))
+				u_kill((unsigned int)wm_pid);
+			wm_pid = 0;
+			wm_restart_at = now_ms() + RESTART_MS;
+			init_state_write();
+			msg = "restarting wm";
+		} else if (strcmp(op, "stop") == 0) {
+			code = 5;
+			msg = "wm is a system service";
+		} else {
+			code = 1;
+			msg = "bad op";
+		}
+	} else {
+		idx = svc_find(name);
+		if (idx < 0) {
+			code = 4;
+			msg = "unknown service";
+		} else {
+			struct svc_rt *r = &rt[idx];
+
+			if (strcmp(op, "start") == 0) {
+				if (r->pid && u_alive(r->pid)) {
+					code = 3;
+					pid = (int)r->pid;
+					msg = "already running";
+				} else {
+					r->desired = 1;
+					r->restart_pending = 0;
+					if (svc_start(r) == 0) {
+						pid = (int)r->pid;
+						msg = "started";
+					} else {
+						code = 1;
+						msg = "spawn failed";
+					}
+				}
+			} else if (strcmp(op, "stop") == 0) {
+				svc_stop(r, 0);
+				msg = "stopping";
+			} else if (strcmp(op, "kill") == 0) {
+				svc_stop(r, 1);
+				msg = "killed";
+			} else if (strcmp(op, "restart") == 0) {
+				svc_restart(r);
+				msg = "restarting";
+			} else {
+				code = 1;
+				msg = "bad op";
+			}
+		}
+	}
+	respond(resp, seq, code, pid, msg);
+}
+
+static void process_control(void)
+{
+	char buf[128];
+	int n;
+
+	while ((n = u_tty_read(ctl_tty, buf, sizeof(buf))) > 0) {
+		int i;
+
+		for (i = 0; i < n; i++) {
+			if (buf[i] == '\n' || buf[i] == '\r') {
+				line[line_len] = '\0';
+				handle_line(line, line_len);
+				line_len = 0;
+			} else if (line_len + 1 < sizeof(line)) {
+				line[line_len++] = buf[i];
+			} else {
+				line_len = 0;
+			}
+		}
+	}
+}
+
+void _start(const char *arg)
+{
+	unsigned int i;
+
+	(void)arg;
+	if (!u_is_init()) {
+		u_puts("init: only the kernel starts this\n");
+		u_exit(1);
+	}
+
+	/* Coming back from a crash: do not let old user processes keep any
+	 * state or ttys.  This also frees the tty slots before we allocate the
+	 * control channel. */
+	reset_userland();
+
+	ctl_tty = u_tty_alloc();
+	if (ctl_tty <= 0)
+		u_exit(1);
+	init_log_add("init: started\n");
+	load_services();
+	init_state_write();
+
+	wm_pid = 0;
+	wm_restart_at = 0;
+	wm_spawn();
+	init_state_write();
+	init_log_flush();
+
+	for (;;) {
+		process_control();
+		wm_poll();
+		for (i = 0; i < svc_def_count && i < SVC_MAX; i++)
+			svc_poll(&rt[i]);
+		init_log_flush();
+		for (i = 0; i < svc_def_count && i < SVC_MAX; i++) {
+			svc_log_flush(&rt[i]);
+			svc_state_write(&rt[i]);
+		}
+		u_sleep_ms(LOOP_MS);
+	}
+}

+ 1 - 1
user/apps/netmenu/ucmd_netmenu.c

@@ -585,7 +585,7 @@ static void start_connect(const char *pass)
 	conn_log[0] = '\0';
 	connect_start = u_ticks_ms();
 
-	pid = u_spawn("/ramfs/bin/wifi", "connectfile /share/netmenu.wifi",
+	pid = u_spawn_detached("/ramfs/bin/wifi", "connectfile /share/netmenu.wifi",
 		      connect_tty, "/");
 	if (pid < 0) {
 		u_syscall1(SYS_UNLINK, (int)"/share/netmenu.wifi");

+ 80 - 4
user/apps/process/ucmd_process.c

@@ -53,6 +53,8 @@ enum {
 
 struct prow {
 	unsigned int pid;
+	unsigned int parent_pid;
+	unsigned int depth;       /* tree indentation, 0 for roots */
 	unsigned int state;
 	unsigned int weight;
 	unsigned int cpu_pm;
@@ -441,6 +443,62 @@ static void sort_rows(void)
 	}
 }
 
+static int row_index_of_pid(unsigned int pid)
+{
+	unsigned int i;
+
+	for (i = 0; i < nrows; i++)
+		if (rows[i].pid == pid)
+			return (int)i;
+	return -1;
+}
+
+/* Append `pid` and its descendants depth-first.  The flat rows were sorted
+ * first, so siblings keep the selected column order. */
+static void append_subtree(unsigned int pid, unsigned int depth,
+			   struct prow *out, unsigned int *nout,
+			   unsigned char *seen)
+{
+	int idx = row_index_of_pid(pid);
+	unsigned int i;
+
+	if (idx < 0 || *nout >= PMAX || seen[idx])
+		return;
+	seen[idx] = 1;
+	out[*nout] = rows[idx];
+	out[*nout].depth = depth;
+	(*nout)++;
+	for (i = 0; i < nrows; i++)
+		if (!seen[i] && rows[i].parent_pid == pid)
+			append_subtree(rows[i].pid, depth + 1, out, nout, seen);
+}
+
+/* Reorder the sorted flat table as a process tree.  A process whose parent is
+ * not in the snapshot is treated as a root; cycles are broken by the seen
+ * mask. */
+static void tree_order(void)
+{
+	struct prow out[PMAX];
+	unsigned char seen[PMAX];
+	unsigned int i, n = 0;
+
+	if (nrows > PMAX)
+		nrows = PMAX;
+	for (i = 0; i < nrows; i++)
+		seen[i] = 0;
+	for (i = 0; i < nrows; i++) {
+		unsigned int p = rows[i].parent_pid;
+
+		if (!seen[i] && (!p || row_index_of_pid(p) < 0))
+			append_subtree(rows[i].pid, 0, out, &n, seen);
+	}
+	for (i = 0; i < nrows; i++)
+		if (!seen[i])
+			append_subtree(rows[i].pid, 0, out, &n, seen);
+	for (i = 0; i < n; i++)
+		rows[i] = out[i];
+}
+
 /* Turn a snapshot into table rows, computing CPU% from the previous sample. */
 static void build_rows(const struct sys_procinfo *cur, unsigned int n,
 		       unsigned int wall, int with_delta)
@@ -467,6 +525,8 @@ static void build_rows(const struct sys_procinfo *cur, unsigned int n,
 				}
 		}
 		r->pid = cur[i].pid;
+		r->parent_pid = cur[i].parent_pid;
+		r->depth = 0;
 		r->state = cur[i].state;
 		r->weight = cur[i].weight;
 		r->cpu_pm = pm;
@@ -476,6 +536,7 @@ static void build_rows(const struct sys_procinfo *cur, unsigned int n,
 		s_copy(r->name, sizeof(r->name), cur[i].name);
 	}
 	sort_rows();
+	tree_order();
 }
 
 /* Bytes over `wall` ms -> bytes per second without overflowing the
@@ -994,8 +1055,19 @@ static void draw_process_row(struct ngui *u, const struct ngui_rect *list,
 	fmt_span(b, sizeof(b), p->cpu_ticks);
 	text_right(u, xs[COL_TIME] + ws[COL_TIME] - 8, y + 2, b, fg);
 
-	ngui_text(u, xs[COL_NAME], y + 2, p->name,
-		  p->kernel && !selected ? u->theme.text_dim : fg);
+	{
+		int nx = xs[COL_NAME];
+		unsigned int d;
+
+		for (d = 0; d + 1 < p->depth; d++)
+			ngui_text(u, nx + (int)d * 14, y + 2, "|",
+				  selected ? fg : u->theme.text_dim);
+		if (p->depth)
+			ngui_text(u, nx + (int)(p->depth - 1) * 14, y + 2,
+				  "|-", selected ? fg : u->theme.text_dim);
+		ngui_text(u, nx + (int)p->depth * 14, y + 2, p->name,
+			  p->kernel && !selected ? u->theme.text_dim : fg);
+	}
 }
 
 static void draw_table(struct ngui *u, struct ngui_rect list)
@@ -1070,10 +1142,12 @@ static void draw_kill_button(struct ngui *u, struct ngui_rect r)
 			   u->theme.text_dim);
 		return;
 	}
-	if (sel->kernel || sel->pid == own_pid) {
+	if (sel->kernel || sel->pid == own_pid ||
+	    s_ci_cmp(sel->name, "init") == 0) {
 		ngui_fill_round_rect(u, br, 6, 6, 6, 6, u->theme.panel_alt);
 		text_right(u, br.x + br.w - 10, br.y + 4,
-			   sel->kernel ? "kernel thread" : "this window",
+			   sel->kernel ? "kernel thread" :
+			   sel->pid == own_pid ? "this window" : "system init",
 			   u->theme.text_dim);
 		ngui_cursor_rect(u, br, CURSOR_NOT_ALLOWED);
 		return;
@@ -1146,6 +1220,8 @@ static void draw_footer(struct ngui *u, struct ngui_rect r)
 		line[0] = '\0';
 		s_append(line, &n, "pid ", sizeof(line));
 		s_append_uint(line, &n, sel->pid, sizeof(line));
+		s_append(line, &n, "  ppid ", sizeof(line));
+		s_append_uint(line, &n, sel->parent_pid, sizeof(line));
 		s_append(line, &n, "  ", sizeof(line));
 		s_append(line, &n, sel->name, sizeof(line));
 		s_append(line, &n, "  ", sizeof(line));

+ 12 - 0
user/apps/service/service_defs.c

@@ -0,0 +1,12 @@
+/* Static service units.  Add a row here to make a service available to init
+ * and the CLI/GUI.  The executable must be in the command pack (or a mounted
+ * filesystem). */
+#include "service_proto.h"
+
+const struct svc_def svc_defs[] = {
+	{ "websrv", "/ramfs/bin/websrv", "8080",
+	  "HTTP + WebDAV server", 0 },
+};
+
+const unsigned int svc_def_count =
+	sizeof(svc_defs) / sizeof(svc_defs[0]);

+ 291 - 0
user/apps/service/service_proto.c

@@ -0,0 +1,291 @@
+/* Shared service table, state files and the init control-tty client. */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "service_proto.h"
+#include "ucmd_lib.h"
+
+static unsigned int slen(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static unsigned int atou(const char *s)
+{
+	unsigned int n = 0;
+
+	while (*s >= '0' && *s <= '9')
+		n = n * 10 + (unsigned int)(*s++ - '0');
+	return n;
+}
+
+static int key_is(const char *line, const char *key)
+{
+	unsigned int n = slen(key);
+
+	return strncmp(line, key, n) == 0 && line[n] == '=';
+}
+
+const char *svc_state_name(unsigned int state)
+{
+	switch (state) {
+	case SVC_STARTING:   return "starting";
+	case SVC_RUNNING:    return "running";
+	case SVC_STOPPING:   return "stopping";
+	case SVC_RESTARTING: return "restarting";
+	default:             return "stopped";
+	}
+}
+
+int svc_state_from_name(const char *s)
+{
+	if (!s)
+		return SVC_STOPPED;
+	if (strcmp(s, "starting") == 0)
+		return SVC_STARTING;
+	if (strcmp(s, "running") == 0)
+		return SVC_RUNNING;
+	if (strcmp(s, "stopping") == 0)
+		return SVC_STOPPING;
+	if (strcmp(s, "restarting") == 0)
+		return SVC_RESTARTING;
+	return SVC_STOPPED;
+}
+
+int svc_find(const char *name)
+{
+	unsigned int i;
+
+	if (!name)
+		return -1;
+	for (i = 0; i < svc_def_count; i++)
+		if (strcmp(svc_defs[i].name, name) == 0)
+			return (int)i;
+	return -1;
+}
+
+int svc_make_state_path(char *out, unsigned int max, const char *name)
+{
+	int n = snprintf(out, max, "/share/svc-%s.state", name);
+
+	return n > 0 && (unsigned int)n < max ? 0 : -1;
+}
+
+int svc_make_log_path(char *out, unsigned int max, const char *name)
+{
+	int n = snprintf(out, max, "/share/svc-%s.log", name);
+
+	return n > 0 && (unsigned int)n < max ? 0 : -1;
+}
+
+static void copy_str(char *dst, unsigned int max, const char *src)
+{
+	unsigned int i = 0;
+
+	for (i = 0; src && src[i] && i + 1 < max; i++)
+		dst[i] = src[i];
+	dst[i] = '\0';
+}
+
+int svc_parse_state(const char *buf, unsigned int len, struct svc_state *out)
+{
+	const char *p = buf, *end = buf + len;
+	unsigned int have_name = 0;
+
+	if (!buf || !out || len < sizeof(SVC_STATE_MAGIC) - 1 ||
+	    strncmp(buf, SVC_STATE_MAGIC, sizeof(SVC_STATE_MAGIC) - 1) != 0)
+		return -1;
+	memset(out, 0, sizeof(*out));
+	p += sizeof(SVC_STATE_MAGIC) - 1;
+	while (p < end) {
+		const char *e = p;
+		unsigned int n;
+
+		while (e < end && *e != '\n')
+			e++;
+		n = (unsigned int)(e - p);
+		if (n) {
+			if (key_is(p, "name")) {
+				char tmp[16];
+				unsigned int m = n - 5;
+
+				if (m >= sizeof(tmp))
+					m = sizeof(tmp) - 1;
+				memcpy(tmp, p + 5, m);
+				tmp[m] = '\0';
+				copy_str(out->name, sizeof(out->name), tmp);
+				have_name = 1;
+			} else if (key_is(p, "state")) {
+				char tmp[16];
+				unsigned int m = n - 6;
+
+				if (m >= sizeof(tmp))
+					m = sizeof(tmp) - 1;
+				memcpy(tmp, p + 6, m);
+				tmp[m] = '\0';
+				out->state = (unsigned int)svc_state_from_name(tmp);
+			} else if (key_is(p, "desired")) {
+				out->desired = (n > 8 && p[8] == 'r') ? 1u : 0u;
+			} else if (key_is(p, "pid")) {
+				out->pid = atou(p + 4);
+			} else if (key_is(p, "tty")) {
+				out->tty = atou(p + 4);
+			} else if (key_is(p, "started")) {
+				out->started = atou(p + 8);
+			}
+		}
+		p = e < end ? e + 1 : end;
+	}
+	return have_name ? 0 : -1;
+}
+
+int svc_format_state(char *out, unsigned int max, const struct svc_state *st)
+{
+	int n = snprintf(out, max,
+			 SVC_STATE_MAGIC
+			 "name=%s\nstate=%s\ndesired=%s\npid=%u\ntty=%u\nstarted=%u\n",
+			 st->name, svc_state_name(st->state),
+			 st->desired ? "running" : "stopped",
+			 st->pid, st->tty, st->started);
+
+	return n > 0 && (unsigned int)n < max ? 0 : -1;
+}
+
+int svc_parse_init_state(const char *buf, unsigned int len,
+			 struct init_state *out)
+{
+	const char *p, *end;
+
+	if (!buf || !out || len < sizeof(SVC_INIT_MAGIC) - 1 ||
+	    strncmp(buf, SVC_INIT_MAGIC, sizeof(SVC_INIT_MAGIC) - 1) != 0)
+		return -1;
+	memset(out, 0, sizeof(*out));
+	out->valid = 1;
+	p = buf + sizeof(SVC_INIT_MAGIC) - 1;
+	end = buf + len;
+	while (p < end) {
+		const char *e = p;
+
+		while (e < end && *e != '\n')
+			e++;
+		if (key_is(p, "pid"))
+			out->pid = atou(p + 4);
+		else if (key_is(p, "ctl"))
+			out->ctl = atou(p + 4);
+		else if (key_is(p, "wm"))
+			out->wm = atou(p + 3);
+		p = e < end ? e + 1 : end;
+	}
+	return 0;
+}
+
+int svc_format_init_state(char *out, unsigned int max,
+			  const struct init_state *st)
+{
+	int n = snprintf(out, max, SVC_INIT_MAGIC "pid=%u\nctl=%u\nwm=%u\n",
+			 st->pid, st->ctl, st->wm);
+
+	return n > 0 && (unsigned int)n < max ? 0 : -1;
+}
+
+/* Parse "NBI1 <seq> <code> <pid> <message>" and copy the message. */
+static int parse_response(const char *s, unsigned int *seq,
+			  int *code, int *pid, char *msg, unsigned int msgmax)
+{
+	const char *p = s;
+	unsigned int v;
+
+	if (strncmp(p, SVC_CTL_MAGIC, 4) != 0 || p[4] != ' ')
+		return -1;
+	p += 5;
+	v = atou(p);
+	while (*p >= '0' && *p <= '9')
+		p++;
+	if (*p != ' ')
+		return -1;
+	p++;
+	*seq = v;
+	*code = (int)atou(p);
+	while (*p >= '0' && *p <= '9')
+		p++;
+	if (*p != ' ')
+		return -1;
+	p++;
+	*pid = (int)atou(p);
+	while (*p >= '0' && *p <= '9')
+		p++;
+	if (*p == ' ')
+		p++;
+	copy_str(msg, msgmax, p);
+	return 0;
+}
+
+int svc_request(const char *op, const char *name, unsigned int wait_ms,
+		int *code, int *pid, char *msg, unsigned int msgmax)
+{
+	char buf[512];
+	char req[128];
+	char rsp[256];
+	struct init_state is;
+	unsigned int seq, used = 0, waited = 0;
+	int n, ret = -1, tries;
+	int resp;
+
+	n = u_read_file(SVC_INIT_STATE, buf, sizeof(buf) - 1);
+	if (n <= 0)
+		return -2;
+	buf[n] = '\0';
+	if (svc_parse_init_state(buf, (unsigned int)n, &is) != 0 ||
+	    !is.valid || !is.pid || !u_alive(is.pid))
+		return -2;
+	resp = u_tty_alloc();
+	if (resp <= 0)
+		return -3;
+	seq = (u_ticks_ms() * 2654435761u) ^ (unsigned int)u_getpid();
+	if (!seq)
+		seq = 1;
+	n = snprintf(req, sizeof(req), "%s %u %s %s %d\n",
+		     SVC_CTL_MAGIC, seq, op, name, resp);
+	if (n <= 0 || (unsigned int)n >= sizeof(req)) {
+		u_tty_close(resp);
+		return -3;
+	}
+	for (tries = 0; tries < 50; tries++) {
+		if (u_tty_write(is.ctl, req, (unsigned int)n) == 0)
+			break;
+		u_sleep_ms(10);
+	}
+	if (tries == 50) {
+		u_tty_close(resp);
+		return -3;
+	}
+	rsp[0] = '\0';
+	while (waited < wait_ms) {
+		n = u_tty_read(resp, rsp + used,
+			       (unsigned int)(sizeof(rsp) - 1 - used));
+		if (n < 0)
+			break;
+		if (n > 0) {
+			used += (unsigned int)n;
+			rsp[used] = '\0';
+			if (strchr(rsp, '\n'))
+				break;
+		}
+		u_sleep_ms(10);
+		waited += 10;
+	}
+	{
+		unsigned int rseq = 0;
+
+		if (parse_response(rsp, &rseq, code, pid, msg, msgmax) == 0 &&
+		    rseq == seq)
+			ret = 0;
+	}
+	u_tty_close(resp);
+	return ret;
+}

+ 807 - 0
user/apps/service/ucmd_service.c

@@ -0,0 +1,807 @@
+/* service: init's CLI and GUI client.
+ *
+ *   service                    list services
+ *   service status <name>
+ *   service start|stop|restart|kill <name>
+ *   service logs <name>        last lines
+ *   service logtail <name>     follow until Ctrl-C
+ *   service --gui
+ *
+ * State and logs are plain files in /share; actions are one-line requests on
+ * init's control tty (see service_proto.c).  The client never spawns or kills
+ * a service itself.
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "ngui.h"
+#include "service_proto.h"
+#include "ucmd_lib.h"
+
+#define LOG_LINES   40
+#define LOOP_MS     50
+#define POLL_MS     500
+
+static char log_buf[SVC_LOG_MAX + 1];
+
+/* ---- shared helpers -------------------------------------------------- */
+
+static int read_state_file(const char *name, struct svc_state *st)
+{
+	char path[64], buf[512];
+	int n;
+
+	if (svc_make_state_path(path, sizeof(path), name) != 0)
+		return -1;
+	n = u_read_file(path, buf, sizeof(buf) - 1);
+	if (n <= 0)
+		return -1;
+	buf[n] = '\0';
+	return svc_parse_state(buf, (unsigned int)n, st);
+}
+
+static int read_init_file(struct init_state *is)
+{
+	char buf[256];
+	int n = u_read_file(SVC_INIT_STATE, buf, sizeof(buf) - 1);
+
+	if (n <= 0)
+		return -1;
+	buf[n] = '\0';
+	return svc_parse_init_state(buf, (unsigned int)n, is);
+}
+
+static int init_is_running(const struct init_state *is)
+{
+	return is->valid && is->pid && u_alive(is->pid);
+}
+
+static int wm_is_running(const struct init_state *is)
+{
+	return is->valid && is->wm && u_alive(is->wm);
+}
+
+static void trim_line(char *s)
+{
+	unsigned int i = 0;
+
+	while (s[i] && s[i] != '\n' && s[i] != '\r')
+		i++;
+	s[i] = '\0';
+}
+
+static void fmt_age(unsigned int started, char *out, unsigned int max)
+{
+	unsigned int s, m, h;
+
+	if (!started) {
+		snprintf(out, max, "-");
+		return;
+	}
+	s = (u_ticks_ms() - started) / 1000u;
+	m = s / 60u;
+	h = m / 60u;
+	if (h)
+		snprintf(out, max, "%uh%um", h, m % 60u);
+	else if (m)
+		snprintf(out, max, "%um%us", m, s % 60u);
+	else
+		snprintf(out, max, "%us", s);
+}
+
+static int read_log(const char *name)
+{
+	char path[64];
+	int n;
+
+	if (strcmp(name, "init") == 0) {
+		n = u_read_file(SVC_INIT_LOG, log_buf, SVC_LOG_MAX);
+	} else if (strcmp(name, "wm") == 0) {
+		return -1;
+	} else {
+		if (svc_make_log_path(path, sizeof(path), name) != 0)
+			return -1;
+		n = u_read_file(path, log_buf, SVC_LOG_MAX);
+	}
+	if (n < 0)
+		n = 0;
+	log_buf[n] = '\0';
+	return n;
+}
+
+static void print_last_lines(int n, int want)
+{
+	int i = n, lines = 0;
+
+	while (i > 0 && lines < want) {
+		i--;
+		if (log_buf[i] == '\n' && i + 1 < n)
+			lines++;
+	}
+	u_puts(log_buf + i);
+}
+
+static int request_action(const char *op, const char *name, char *msg,
+			  unsigned int msgmax, int *pid)
+{
+	int code = 0;
+	int r;
+
+	if (pid)
+		*pid = 0;
+	r = svc_request(op, name, 2500, &code, pid, msg, msgmax);
+	if (r == -2) {
+		snprintf(msg, msgmax, "init is not running");
+		return -2;
+	}
+	if (r != 0) {
+		snprintf(msg, msgmax, "init is not responding");
+		return -1;
+	}
+	trim_line(msg);
+	return code;
+}
+
+/* ---- CLI ------------------------------------------------------------- */
+
+static void cli_list(void)
+{
+	struct init_state is;
+	struct svc_state st;
+	char age[16], line[160];
+	unsigned int i;
+
+	if (read_init_file(&is) != 0)
+		memset(&is, 0, sizeof(is));
+	u_puts("NAME       STATE      PID   AGE     DESCRIPTION\n");
+	if (init_is_running(&is)) {
+		snprintf(line, sizeof(line), "%-10s %-10s %-5u %-7s %s\n",
+			 "init", "running", is.pid, "-", "service manager");
+	} else {
+		snprintf(line, sizeof(line), "%-10s %-10s %-5s %-7s %s\n",
+			 "init", "down", "-", "-", "service manager");
+	}
+	u_puts(line);
+	if (wm_is_running(&is)) {
+		snprintf(line, sizeof(line), "%-10s %-10s %-5u %-7s %s\n",
+			 "wm", "running", is.wm, "-",
+			 "window manager (system)");
+	} else {
+		snprintf(line, sizeof(line), "%-10s %-10s %-5s %-7s %s\n",
+			 "wm", "stopped", "-", "-",
+			 "window manager (system)");
+	}
+	u_puts(line);
+	for (i = 0; i < svc_def_count; i++) {
+		const char *state = "stopped";
+		unsigned int pid = 0;
+		unsigned int started = 0;
+
+		if (read_state_file(svc_defs[i].name, &st) == 0) {
+			pid = st.pid;
+			started = st.started;
+			if (pid && !u_alive(pid))
+				pid = 0;
+			if (pid)
+				state = svc_state_name(st.state);
+		}
+		if (pid)
+			fmt_age(started, age, sizeof(age));
+		else
+			snprintf(age, sizeof(age), "-");
+		snprintf(line, sizeof(line), "%-10s %-10s %-5u %-7s %s\n",
+			 svc_defs[i].name, state, pid, age, svc_defs[i].desc);
+		u_puts(line);
+	}
+	if (!is.valid)
+		u_puts("service: init state is missing (use `service` after boot)\n");
+	else if (!init_is_running(&is))
+		u_puts("service: init is not running; the kernel will restart it\n");
+}
+
+static void cli_status(const char *name)
+{
+	struct init_state is;
+	struct svc_state st;
+	char age[16];
+
+	if (strcmp(name, "init") == 0) {
+		if (read_init_file(&is) != 0) {
+			u_puts("init: not running\n");
+			return;
+		}
+		u_puts(init_is_running(&is) ? "init: running\n" : "init: down\n");
+		u_puts("  pid "); u_putdec(is.pid);
+		u_puts(", control tty "); u_putdec(is.ctl);
+		u_puts(", wm "); u_putdec(wm_is_running(&is) ? is.wm : 0);
+		u_puts("\n  log " SVC_INIT_LOG "\n");
+		return;
+	}
+	if (strcmp(name, "wm") == 0) {
+		read_init_file(&is);
+		if (wm_is_running(&is)) {
+			u_puts("wm: running\n  pid ");
+			u_putdec(is.wm);
+			u_puts("\n  system service (restart/kill only)\n");
+		} else {
+			u_puts("wm: stopped\n");
+		}
+		return;
+	}
+	if (svc_find(name) < 0) {
+		u_puts("service: unknown service\n");
+		return;
+	}
+	if (read_state_file(name, &st) != 0) {
+		u_puts(name); u_puts(": stopped (no state file)\n");
+		return;
+	}
+	if (st.pid && !u_alive(st.pid))
+		st.pid = 0;
+	fmt_age(st.started, age, sizeof(age));
+	u_puts(name); u_puts(": ");
+	u_puts(st.pid ? svc_state_name(st.state) : "stopped");
+	u_puts("\n  pid "); u_putdec(st.pid);
+	u_puts(", tty "); u_putdec(st.tty);
+	u_puts(", age "); u_puts(age);
+	u_puts("\n  desired "); u_puts(st.desired ? "running" : "stopped");
+	u_puts("\n  ");
+	{
+		int i = svc_find(name);
+
+		u_puts(svc_defs[i].desc);
+	}
+	u_puts("\n");
+}
+
+static int cli_action(const char *op, const char *name)
+{
+	char msg[96];
+	int pid = 0;
+	int code = request_action(op, name, msg, sizeof(msg), &pid);
+
+	if (code < 0) {
+		u_puts("service: "); u_puts(msg); return 1;
+	}
+	u_puts(name); u_puts(": "); u_puts(msg);
+	if (pid > 0) {
+		u_puts(" (pid "); u_putdec((unsigned int)pid); u_puts(")");
+	}
+	u_puts("\n");
+	if (code == 0 &&
+	    (strcmp(op, "start") == 0 || strcmp(op, "restart") == 0)) {
+		struct svc_state st;
+
+		u_sleep_ms(350);
+		if (read_state_file(name, &st) == 0 &&
+		    (!st.pid || !u_alive(st.pid))) {
+			int n = read_log(name);
+
+			u_puts("service: "); u_puts(name);
+			u_puts(" did not stay up; last log lines:\n");
+			if (n > 0)
+				print_last_lines(n, 12);
+			return 1;
+		}
+	}
+	return code ? 1 : 0;
+}
+
+static int cli_logs(const char *name, int follow)
+{
+	unsigned int seen = 0;
+	int n;
+
+	if (strcmp(name, "wm") == 0) {
+		u_puts("wm: no captured log (the WM writes to the serial console)\n");
+		return 1;
+	}
+	if (read_log(name) < 0) {
+		u_puts("service: no log for "); u_puts(name); u_puts("\n");
+		return 1;
+	}
+	if (!follow) {
+		n = (int)strlen(log_buf);
+		if (!n) {
+			u_puts("service: log is empty\n");
+			return 0;
+		}
+		print_last_lines(n, LOG_LINES);
+		return 0;
+	}
+	for (;;) {
+		n = read_log(name);
+		if (n < 0)
+			n = 0;
+		if ((unsigned int)n < seen)
+			seen = 0;
+		if ((unsigned int)n > seen) {
+			u_puts(log_buf + seen);
+			seen = (unsigned int)n;
+		}
+		u_sleep_ms(250);
+	}
+}
+
+static void cli_usage(void)
+{
+	u_puts("usage: service [list]\n"
+	       "       service status <name>\n"
+	       "       service start|stop|restart|kill <name>\n"
+	       "       service logs <name> | logtail <name>\n"
+	       "       service --gui\n");
+}
+
+static void cli(const char *arg)
+{
+	char cmd[16], name[16];
+	unsigned int i = 0, n;
+
+	while (arg && (arg[i] == ' ' || arg[i] == '\t'))
+		i++;
+	n = 0;
+	while (arg && arg[i] && arg[i] != ' ' && arg[i] != '\t' &&
+	       n + 1 < sizeof(cmd))
+		cmd[n++] = arg[i++];
+	cmd[n] = '\0';
+	while (arg && (arg[i] == ' ' || arg[i] == '\t'))
+		i++;
+	n = 0;
+	while (arg && arg[i] && arg[i] != ' ' && arg[i] != '\t' &&
+	       n + 1 < sizeof(name))
+		name[n++] = arg[i++];
+	name[n] = '\0';
+
+	if (!cmd[0] || strcmp(cmd, "list") == 0) {
+		cli_list();
+		return;
+	}
+	if (strcmp(cmd, "help") == 0) {
+		cli_usage();
+		return;
+	}
+	if (strcmp(cmd, "status") == 0) {
+		if (!name[0]) { cli_usage(); return; }
+		cli_status(name);
+		return;
+	}
+	if (strcmp(cmd, "logs") == 0 || strcmp(cmd, "logtail") == 0) {
+		if (!name[0]) { cli_usage(); return; }
+		cli_logs(name, strcmp(cmd, "logtail") == 0);
+		return;
+	}
+	if (strcmp(cmd, "start") == 0 || strcmp(cmd, "stop") == 0 ||
+	    strcmp(cmd, "restart") == 0 || strcmp(cmd, "kill") == 0) {
+		if (!name[0]) { cli_usage(); return; }
+		cli_action(cmd, name);
+		return;
+	}
+	cli_usage();
+}
+
+/* ---- GUI ------------------------------------------------------------- */
+
+#define VIEW_MAX (2 + SVC_MAX)
+#define ROW_H    52
+
+enum {
+	ID_REFRESH = 1,
+	ID_START,
+	ID_STOP,
+	ID_RESTART,
+	ID_KILL,
+	ID_ROW_BASE = 100
+};
+
+struct view {
+	char name[16];
+	char state[16];
+	char desc[80];
+	unsigned int pid;
+	int running;
+	int is_init;
+	int is_wm;
+};
+
+static struct ngui ui;
+static struct win_info wi;
+static struct view views[VIEW_MAX];
+static int nviews;
+static int selected;
+static int pending_action;
+static int kill_arm;
+static unsigned int kill_arm_at;
+static char gui_status[96];
+static unsigned int gui_status_at;
+static unsigned int log_len;
+static struct ngui_scroll log_scroll;
+static int log_follow = 1;
+
+static void gui_refresh(void)
+{
+	struct init_state is;
+	struct svc_state st;
+	unsigned int i;
+
+	memset(&is, 0, sizeof(is));
+	read_init_file(&is);
+	nviews = 0;
+	memset(&views[nviews], 0, sizeof(views[nviews]));
+	snprintf(views[nviews].name, sizeof(views[nviews].name), "init");
+	snprintf(views[nviews].state, sizeof(views[nviews].state),
+		 init_is_running(&is) ? "running" : "down");
+	snprintf(views[nviews].desc, sizeof(views[nviews].desc),
+		 "service manager (pid 1)");
+	views[nviews].pid = init_is_running(&is) ? is.pid : 0;
+	views[nviews].running = init_is_running(&is);
+	views[nviews].is_init = 1;
+	nviews++;
+	memset(&views[nviews], 0, sizeof(views[nviews]));
+	snprintf(views[nviews].name, sizeof(views[nviews].name), "wm");
+	snprintf(views[nviews].state, sizeof(views[nviews].state),
+		 wm_is_running(&is) ? "running" : "stopped");
+	snprintf(views[nviews].desc, sizeof(views[nviews].desc),
+		 "window manager (system service)");
+	views[nviews].pid = wm_is_running(&is) ? is.wm : 0;
+	views[nviews].running = wm_is_running(&is);
+	views[nviews].is_wm = 1;
+	nviews++;
+	for (i = 0; i < svc_def_count && i < SVC_MAX; i++) {
+		struct view *v = &views[nviews];
+
+		memset(v, 0, sizeof(*v));
+		snprintf(v->name, sizeof(v->name), "%s", svc_defs[i].name);
+		snprintf(v->desc, sizeof(v->desc), "%s", svc_defs[i].desc);
+		snprintf(v->state, sizeof(v->state), "stopped");
+		if (read_state_file(svc_defs[i].name, &st) == 0) {
+			v->pid = st.pid;
+			if (v->pid && !u_alive(v->pid))
+				v->pid = 0;
+			if (v->pid)
+				snprintf(v->state, sizeof(v->state), "%s",
+					 svc_state_name(st.state));
+		}
+		v->running = v->pid != 0;
+		nviews++;
+	}
+	if (selected >= nviews)
+		selected = nviews - 1;
+	if (selected < 0)
+		selected = 0;
+}
+
+static void gui_read_log(void)
+{
+	struct view *v = &views[selected];
+	int n;
+
+	if (v->is_wm) {
+		log_len = 0;
+		return;
+	}
+	n = read_log(v->name);
+	if (n < 0)
+		n = 0;
+	log_len = (unsigned int)n;
+}
+
+static void gui_status_set(const char *s, int err)
+{
+	snprintf(gui_status, sizeof(gui_status), "%s", s);
+	gui_status_at = u_ticks_ms();
+	(void)err;
+}
+
+static void gui_action(const char *op)
+{
+	char msg[96];
+	int pid = 0, code;
+
+	code = request_action(op, views[selected].name, msg, sizeof(msg), &pid);
+	if (code < 0) {
+		gui_status_set(msg, 1);
+		return;
+	}
+	if (pid > 0) {
+		char b[80];
+
+		snprintf(b, sizeof(b), "%s: %s (pid %d)", views[selected].name,
+			 msg, pid);
+		gui_status_set(b, code != 0);
+	} else {
+		char b[80];
+
+		snprintf(b, sizeof(b), "%s: %s", views[selected].name, msg);
+		gui_status_set(b, code != 0);
+	}
+	gui_refresh();
+	ngui_invalidate(&ui);
+}
+
+static int draw_button(unsigned int id, struct ngui_rect r,
+		       const char *label, int enabled)
+{
+	if (enabled)
+		return ngui_button(&ui, id, r, label);
+	ngui_fill_rect(&ui, r, ui.theme.panel_alt);
+	ngui_text(&ui, r.x + 10, r.y + (r.h - 16) / 2, label,
+		  ui.theme.text_dim);
+	return 0;
+}
+
+static void gui_draw(void)
+{
+	struct ngui_rect list = { 10, 52, 300, ui.h - 62 };
+	struct ngui_rect right = { 320, 52, ui.w - 330, ui.h - 62 };
+	struct ngui_rect btn;
+	struct view *v = &views[selected];
+	int i, enabled;
+	unsigned int now = u_ticks_ms();
+	int line_h = ngui_text_line_height(&ui, 12, 1);
+	char sub[64], tr[16];
+
+	ngui_fill_rect(&ui, (struct ngui_rect){ 0, 0, ui.w, ui.h },
+		       ui.theme.bg);
+	{
+		char head[96];
+
+		if (views[0].running)
+			snprintf(head, sizeof(head), "Init: running (pid %u)",
+				 views[0].pid);
+		else
+			snprintf(head, sizeof(head), "Init: not running");
+		ngui_text(&ui, 12, 16, head, ui.theme.text);
+	}
+
+	for (i = 0; i < nviews; i++) {
+		struct view *r = &views[i];
+		struct ngui_row row;
+		struct ngui_rect rr = { list.x, list.y + i * ROW_H,
+					list.w, ROW_H };
+
+		if (rr.y + rr.h > list.y + list.h)
+			break;
+		snprintf(tr, sizeof(tr), "%u", r->pid);
+		snprintf(sub, sizeof(sub), "%s%s%s", r->state,
+			 r->pid ? "  pid " : "", r->pid ? tr : "");
+		row.title = r->name;
+		row.subtitle = sub;
+		row.trailing = r->desc;
+		row.bars = -1;
+		row.selected = (i == selected);
+		if (ngui_list_row(&ui, ID_ROW_BASE + (unsigned int)i, rr, &row)) {
+			selected = i;
+			kill_arm = 0;
+			log_scroll.offset = 0;
+			log_follow = 1;
+			gui_read_log();
+			ngui_invalidate(&ui);
+		}
+	}
+
+	btn = (struct ngui_rect){ right.x, right.y, 84, 30 };
+	enabled = !v->is_init && !v->running;
+	if (draw_button(ID_START, btn, "Start", enabled))
+		pending_action = ID_START;
+	btn.x += 92;
+	enabled = !v->is_init && !v->is_wm && v->running;
+	if (draw_button(ID_STOP, btn, "Stop", enabled))
+		pending_action = ID_STOP;
+	btn.x += 92;
+	enabled = !v->is_init;
+	if (draw_button(ID_RESTART, btn, "Restart", enabled))
+		pending_action = ID_RESTART;
+	btn.x += 92;
+	enabled = !v->is_init && v->running;
+	if (draw_button(ID_KILL, btn, "Kill", enabled))
+		pending_action = ID_KILL;
+	btn.x += 92;
+	if (draw_button(ID_REFRESH, btn, "Refresh", 1))
+		pending_action = ID_REFRESH;
+
+	if (gui_status[0] && now - gui_status_at < 5000) {
+		ngui_text_ellipsis(&ui, (struct ngui_rect){ right.x,
+				    right.y + 38, right.w, 20 }, right.x,
+				    right.y + 38, gui_status,
+				    ui.theme.text_dim);
+	} else {
+		ngui_text_ellipsis(&ui, (struct ngui_rect){ right.x,
+				    right.y + 38, right.w, 20 }, right.x,
+				    right.y + 38,
+				    v->is_wm ? "System service: restart/kill only"
+					     : v->desc,
+				    ui.theme.text_dim);
+	}
+
+	{
+		struct ngui_rect body = { right.x, right.y + 64, right.w,
+					  right.h - 64 };
+		int lines = 1, max, wheel;
+		unsigned int i2;
+
+		ngui_fill_rect(&ui, body, ui.theme.panel);
+		if (v->is_wm) {
+			ngui_text(&ui, body.x + 10, body.y + 10,
+				  "The WM writes to the serial console; no log.",
+				  ui.theme.text_dim);
+			return;
+		}
+		if (!log_len) {
+			ngui_text(&ui, body.x + 10, body.y + 10,
+				  "No log yet.", ui.theme.text_dim);
+			return;
+		}
+		for (i2 = 0; i2 < log_len; i2++)
+			if (log_buf[i2] == '\n')
+				lines++;
+		if (line_h < 10)
+			line_h = 10;
+		log_scroll.content_h = lines * line_h;
+		log_scroll.view_h = body.h;
+		log_scroll.hide_bar = 0;
+		ngui_scroll_begin(&ui, body, &log_scroll);
+		wheel = ngui_scroll_wheel(&ui, body, &log_scroll);
+		max = log_scroll.content_h - log_scroll.view_h;
+		if (max < 0)
+			max = 0;
+		if (wheel)
+			log_follow = 0;
+		if (log_follow)
+			ngui_scroll_to(&log_scroll, max);
+		if (log_scroll.offset >= max - 1)
+			log_follow = 1;
+		{
+			unsigned int start = 0, end = 0;
+			int idx = 0;
+			int ly;
+
+			while (end < log_len) {
+				while (end < log_len && log_buf[end] != '\n')
+					end++;
+				ly = body.y + idx * line_h - log_scroll.offset;
+				if (ly + line_h > body.y && ly < body.y + body.h)
+					ngui_text_px(&ui, body.x + 6, ly,
+						     log_buf + start,
+						     end - start,
+						     ui.theme.text, 12, 0, 0, 1);
+				idx++;
+				if (end < log_len)
+					end++;
+				start = end;
+			}
+		}
+		ngui_scroll_end(&ui, body, &log_scroll);
+	}
+}
+
+static void gui_handle_action(int id)
+{
+	unsigned int now = u_ticks_ms();
+	struct view *v = &views[selected];
+
+	if (id == ID_REFRESH) {
+		gui_refresh();
+		gui_read_log();
+		ngui_invalidate(&ui);
+		return;
+	}
+	if (id == ID_KILL) {
+		if (v->is_wm) {
+			gui_action("kill");
+			return;
+		}
+		if (kill_arm && now - kill_arm_at < 3000) {
+			kill_arm = 0;
+			gui_action("kill");
+		} else {
+			kill_arm = 1;
+			kill_arm_at = now;
+			gui_status_set("Press Kill again to confirm", 1);
+			ngui_invalidate(&ui);
+		}
+		return;
+	}
+	if (id == ID_START)
+		gui_action("start");
+	else if (id == ID_STOP)
+		gui_action("stop");
+	else if (id == ID_RESTART)
+		gui_action("restart");
+}
+
+static void gui(const char *arg)
+{
+	unsigned int sw = 0, sh = 0;
+	unsigned int w = 820, h = 560;
+	unsigned int last_poll = 0;
+	int quit = 0;
+
+	(void)arg;
+	if (u_screen_size(&sw, &sh) == 0) {
+		if (sw && w > sw - 30)
+			w = sw - 30;
+		if (sh && h > sh - 40)
+			h = sh - 40;
+	}
+	if (w < 520)
+		w = 520;
+	if (h < 360)
+		h = 360;
+	if (u_win_create(w, h, "Services", &wi) != 0) {
+		u_puts("service: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
+	gui_refresh();
+	gui_read_log();
+	ngui_invalidate(&ui);
+	for (;;) {
+		unsigned int now = u_ticks_ms();
+
+		if (now - last_poll >= POLL_MS) {
+			last_poll = now;
+			gui_refresh();
+			gui_read_log();
+			ngui_invalidate(&ui);
+		}
+		if (!ngui_begin(&ui)) {
+			ngui_end_ex(&ui, 0);
+			u_sleep_ms(LOOP_MS);
+			continue;
+		}
+		{
+			int k;
+
+			while ((k = ngui_key(&ui)) != 0) {
+				if (k == NGUI_KEY_ESC) {
+					quit = 1;
+					break;
+				}
+				if (k == NGUI_KEY_UP && selected > 0) {
+					selected--;
+					kill_arm = 0;
+					log_scroll.offset = 0;
+					log_follow = 1;
+					gui_read_log();
+					ngui_invalidate(&ui);
+				} else if (k == NGUI_KEY_DOWN &&
+					   selected + 1 < nviews) {
+					selected++;
+					kill_arm = 0;
+					log_scroll.offset = 0;
+					log_follow = 1;
+					gui_read_log();
+					ngui_invalidate(&ui);
+				}
+			}
+		}
+		if (quit)
+			break;
+		pending_action = 0;
+		gui_draw();
+		ngui_end(&ui);
+		if (pending_action)
+			gui_handle_action(pending_action);
+		u_sleep_ms(LOOP_MS);
+	}
+	u_win_close();
+	u_exit(0);
+}
+
+void _start(const char *arg)
+{
+	const char *a = arg;
+
+	while (a && (*a == ' ' || *a == '\t'))
+		a++;
+	if (a && ((strncmp(a, "--gui", 5) == 0 &&
+		   (a[5] == '\0' || a[5] == ' ' || a[5] == '\t')) ||
+		  strcmp(a, "gui") == 0)) {
+		gui(arg);
+		return;
+	}
+	cli(arg);
+	u_exit(0);
+}

+ 4 - 1
user/apps/term/ucmd_term.c

@@ -1075,8 +1075,11 @@ static void run_line(void)
 	if (word[0] == 'k' && word[1] == 'i' && word[2] == 'l' &&
 	    word[3] == 'l' && !word[4]) {
 		unsigned int pid = parse_num(args);
+		int r = pid ? u_kill(pid) : -1;
 
-		if (!pid || u_kill(pid) != 0)
+		if (r == -2)
+			term_puts("kill: init is protected\n");
+		else if (r != 0)
 			term_puts("kill: no such process\n");
 		prompt();
 		return;

+ 1 - 1
user/apps/wifi/ucmd_wifi.c

@@ -391,7 +391,7 @@ static void spawn_keeper(struct wpa_sm *sm, unsigned int conn_id)
 	tohex(id, 4, q);
 	q += 8;
 	*q = 0;
-	if (u_spawn("/ramfs/bin/wifi", arg, 0, "/") < 0)
+	if (u_spawn_detached("/ramfs/bin/wifi", arg, 0, "/") < 0)
 		u_puts("wifi: note: rekey helper did not start; the link will "
 		       "drop at the next group rekey\n");
 }

+ 1 - 0
user/apps/wm/ucmd_wm.c

@@ -196,6 +196,7 @@ static const struct sm_app sm_apps[] = {
 	{ "Cards",       "/ramfs/bin/solitaire","",                     0x3CA08Cu, 'S', SM_ACT_SPAWN },
 	{ "Disks",       "/ramfs/bin/disks",    "",                     0x5A8CC8u, 'D', SM_ACT_SPAWN },
 	{ "Tasks",       "/ramfs/bin/process",  "",                     0xE0B040u, 'P', SM_ACT_SPAWN },
+	{ "Services",    "/ramfs/bin/service",  "--gui",                0x9A6AC8u, 'V', SM_ACT_SPAWN },
 	{ "Settings",    "",                    "",                     0x7A7A9Au, 'S', SM_ACT_SETTINGS },
 	{ "Date & Time", "/ramfs/bin/settime",  "",                     0x5AA0A0u, 'D', SM_ACT_SPAWN },
 };

+ 73 - 0
user/service_proto.h

@@ -0,0 +1,73 @@
+/* Shared service definitions and the VFS/tty protocol used by init and the
+ * `service` CLI/GUI. */
+#ifndef SERVICE_PROTO_H
+#define SERVICE_PROTO_H
+
+#include "syscall.h"
+
+#define SVC_MAX        8
+#define SVC_LOG_MAX    (32u * 1024u)
+#define SVC_INIT_STATE "/share/init.state"
+#define SVC_INIT_LOG   "/share/init.log"
+#define SVC_STATE_MAGIC "NBSVC1\n"
+#define SVC_INIT_MAGIC  "NBINIT1\n"
+#define SVC_CTL_MAGIC   "NBI1"
+
+#define SVC_AUTOSTART  0x1
+
+enum svc_phase {
+	SVC_STOPPED = 0,
+	SVC_STARTING,
+	SVC_RUNNING,
+	SVC_STOPPING,
+	SVC_RESTARTING
+};
+
+struct svc_def {
+	const char *name;
+	const char *path;
+	const char *args;
+	const char *desc;
+	unsigned int flags;
+};
+
+extern const struct svc_def svc_defs[];
+extern const unsigned int svc_def_count;
+
+struct svc_state {
+	char name[16];
+	unsigned int state;
+	unsigned int desired;   /* 0 stopped, 1 running */
+	unsigned int pid;
+	unsigned int tty;
+	unsigned int started;   /* uptime ms */
+};
+
+struct init_state {
+	unsigned int pid;
+	unsigned int ctl;
+	unsigned int wm;
+	unsigned int valid;
+};
+
+const char *svc_state_name(unsigned int state);
+int svc_state_from_name(const char *s);
+int svc_find(const char *name);
+
+int svc_make_state_path(char *out, unsigned int max, const char *name);
+int svc_make_log_path(char *out, unsigned int max, const char *name);
+
+int svc_parse_state(const char *buf, unsigned int len, struct svc_state *out);
+int svc_format_state(char *out, unsigned int max, const struct svc_state *st);
+int svc_parse_init_state(const char *buf, unsigned int len,
+			 struct init_state *out);
+int svc_format_init_state(char *out, unsigned int max,
+			  const struct init_state *st);
+
+/* Send one control request to init and wait for its response.
+ * Returns 0 on a response, -1 on timeout, -2 when init is not running and
+ * -3 when the control/response tty could not be used. */
+int svc_request(const char *op, const char *name, unsigned int wait_ms,
+		int *code, int *pid, char *msg, unsigned int msgmax);
+
+#endif

+ 53 - 0
user/ucmd_lib.h

@@ -430,11 +430,26 @@ static inline int u_tty_create(void)
 	return u_syscall0(SYS_TTY_CREATE);
 }
 
+static inline int u_tty_alloc(void)
+{
+	return u_syscall0(SYS_TTY_ALLOC);
+}
+
 static inline int u_tty_read(int id, char *buf, unsigned int max)
 {
 	return u_syscall3(SYS_TTY_READ, id, (int)buf, (int)max);
 }
 
+static inline int u_tty_write(int id, const char *buf, unsigned int len)
+{
+	return u_syscall3(SYS_TTY_WRITE, id, (int)buf, (int)len);
+}
+
+static inline int u_tty_close(int id)
+{
+	return u_syscall1(SYS_TTY_CLOSE, id);
+}
+
 static inline int u_spawn(const char *path, const char *arg, int tty,
 			  const char *cwd)
 {
@@ -444,9 +459,31 @@ static inline int u_spawn(const char *path, const char *arg, int tty,
 	s.arg = arg;
 	s.cwd = cwd;
 	s.tty = (unsigned int)tty;
+	s.flags = 0;
 	return u_syscall1(SYS_SPAWN, (int)&s);
 }
 
+/* Give the child to the caller's parent (the terminal/WM session) instead of
+ * the caller, so it survives a launcher/file-manager exit but not the
+ * session. */
+static inline int u_spawn_detached(const char *path, const char *arg, int tty,
+				   const char *cwd)
+{
+	struct sys_spawn s;
+
+	s.path = path;
+	s.arg = arg;
+	s.cwd = cwd;
+	s.tty = (unsigned int)tty;
+	s.flags = SYS_SPAWN_DETACH;
+	return u_syscall1(SYS_SPAWN, (int)&s);
+}
+
+static inline int u_is_init(void)
+{
+	return u_syscall0(SYS_IS_INIT);
+}
+
 static inline int u_spawn_kcmd(const char *name, const char *arg, int tty)
 {
 	return u_syscall3(SYS_SPAWN_KCMD, (int)name, (int)arg, tty);
@@ -482,6 +519,11 @@ static inline int u_schedinfo(struct sys_schedinfo *out)
 	return u_syscall1(SYS_SCHEDINFO, (int)out);
 }
 
+static inline int u_procinfo(unsigned int index, struct sys_procinfo *out)
+{
+	return u_syscall2(SYS_PROCINFO, (int)index, (int)out);
+}
+
 static inline int u_cpu_temp(struct sys_cputemp *out)
 {
 	return u_syscall1(SYS_CPU_TEMP, (int)out);
@@ -535,6 +577,17 @@ static inline int u_stat(const char *path, struct sys_stat *out)
 	return u_syscall2(SYS_FS_STAT, (int)path, (int)out);
 }
 
+static inline int u_read_file(const char *path, void *buf, unsigned int max)
+{
+	return u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)max);
+}
+
+static inline int u_write_file(const char *path, const void *buf,
+			       unsigned int len)
+{
+	return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len);
+}
+
 /* TCP server (the caller owns the NIC). */
 static inline int u_tcp_listen(unsigned int port)
 {

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio