Преглед изворни кода

init: PID-1 service manager and parent-death process tree

Add a ring-3 init as PID 1.  The kernel starts /ramfs/bin/init after
wm_server_init(), records init_pid before the process is made runnable,
protects it from SYS_KILL and restarts it from the kworker.  Init is the
only WM creator: the kernel launcher/fallback and wm_expected_pid are
gone, and wm_server_attach accepts only an init child named "wm".

Every PCB now carries parent_pid; process_exit(), process_kill() and the
reaper kill the descendant subtree, and a child born while its parent
dies is aborted.  SYS_SPAWN gains 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).  Terminal commands, WM apps and kernel
commands stay parented; files/disks/chat and the WiFi helpers use
detached spawns.  Browser and gallery launchers spawn the real app
parented and wait, so terminal launches stay foreground and Ctrl-C or
closing the terminal kills the app.

Init owns one private tty per service, drains it to
/share/svc-<name>.log, writes /share/svc-<name>.state and serves the
NBI1 control protocol on its own tty.  The service CLI/GUI starts,
stops, restarts, kills and tails websrv (the first unit) and the WM;
logs and state are RAM-only, and an init crash resets the ring-3 tree
and restarts the desired services.  New syscalls are SYS_TTY_ALLOC,
SYS_TTY_WRITE, SYS_TTY_CLOSE and SYS_IS_INIT; TTY_MAX is 16.

SYS_PROCINFO exposes parent_pid, so the process monitor now draws an
indented parent/child tree while still sorting sibling groups.  It
protects init, and the WM start menu gains a Services entry
(/ramfs/bin/service --gui).

The spawn/tty ABI is deliberately not backward compatible: kernel,
command pack, root.img, UEFI payload and host harness must be rebuilt
together, and the new kernel needs init in the rootfs for a WM.

Tested in QEMU on BIOS and UEFI: init PID 1 starts the WM and terminal;
service list/status/start/stop/restart/kill/logs and service --gui;
WM restart; an init crash reset; gallery foreground/Ctrl-C parent-death;
a file-manager launched viewer surviving the file manager; the process
tree; and the start-menu Services entry.
Johannes Zellner пре 1 дан
родитељ
комит
6b7600b448

+ 135 - 39
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:
@@ -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
@@ -238,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
@@ -253,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
@@ -294,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 (`0xB02000` with today's 2.1 MB pack, at most `0xD00000`); 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
@@ -349,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),
@@ -495,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
@@ -561,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
@@ -608,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
@@ -1572,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
@@ -1600,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,
@@ -1625,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
@@ -1648,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
@@ -2393,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
@@ -2956,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
@@ -3007,9 +3076,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    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.0 MiB gzip (~2 MB under the
-   cap), inflating to ~4.35 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.3 MiB) now takes about four
@@ -3083,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.
 
@@ -3532,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
@@ -3544,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.

+ 13 - 2
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 \
@@ -399,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)
@@ -489,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

+ 2 - 1
docs/boot.html

@@ -411,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>
@@ -466,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>

+ 7 - 2
docs/cpu.html

@@ -233,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">
@@ -406,7 +410,8 @@
 		<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>

+ 1 - 1
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>

+ 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>

+ 5 - 0
docs/index.html

@@ -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>

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
docs/network.html


+ 116 - 11
docs/userland.html

@@ -4,7 +4,7 @@
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Userland | NebOS Architecture</title>
-<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 47-command pack, GUI applications and the browser.">
+<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 54-command pack, init/services, GUI applications and the browser.">
 <link rel="icon" href="favicon.svg" type="image/svg+xml">
 <link rel="stylesheet" href="style.css">
 </head>
@@ -38,13 +38,13 @@
 			Ring-3 programs are static ELFs linked at <code>0x40000000</code>.
 			The shell resolves a command name against builtins, the per-terminal
 			PATH and the kernel command registry, then spawns it with one
-			argument string. The command pack supplies 47 PATH commands by default.
+			argument string. The command pack supplies 54 PATH commands by default, including the PID-1 <code>init</code> manager and the <code>service</code> client.
 		</p>
 		<div class="meta">
 			<span class="pill">int 0x80</span>
 			<span class="pill">one string argument</span>
-			<span class="pill">47 PATH commands</span>
-			<span class="pill">8 TTYs · 8 windows</span>
+			<span class="pill">54 PATH commands</span>
+			<span class="pill">16 TTYs · 8 windows</span>
 		</div>
 	</div>
 
@@ -52,6 +52,7 @@
 		<h2>On this page</h2>
 		<ul>
 			<li><a href="#model">Ring-3 model</a></li>
+			<li><a href="#services">Init &amp; services</a></li>
 			<li><a href="#libc">Ring-3 libc</a></li>
 			<li><a href="#spawn">Spawn path</a></li>
 			<li><a href="#syscalls">Syscall ABI</a></li>
@@ -89,6 +90,87 @@
 		</div>
 	</section>
 
+	<section id="services">
+		<h2>Init &amp; services</h2>
+		<p>
+			The kernel starts <code>/ramfs/bin/init</code> as PID 1 after the
+			ramfs and <code>/share</code> mounts, and before any WM exists.
+			Init is a normal ring-3 process; the kernel only loads it, records
+			<code>init_pid</code> before the process is runnable, refuses
+			<code>SYS_KILL(init)</code> and restarts it from the kworker if it
+			dies. A user-run <code>init</code> exits immediately because
+			<code>SYS_IS_INIT</code> is false.
+		</p>
+		<ul>
+			<li><strong>Init owns the WM.</strong> The kernel never starts a
+			WM. Init spawns <code>/ramfs/bin/wm</code>, watches its pid and
+			respawns it after an exit; the kernel's WM watchdog only kills a
+			wedged WM. <code>SYS_WM_ATTACH</code> accepts only an init child
+			named <code>wm</code>, maps the shadow and disables the boot
+			console. If init or the WM binary is missing the boot console
+			stays visible and there is no desktop.</li>
+			<li><strong>Services.</strong> The static table lives in
+			<span class="file">user/apps/service/service_defs.c</span>. The
+			first unit is <code>websrv</code> (<code>/ramfs/bin/websrv
+			8080</code>, autostart off). Init allocates one tty per running
+			service with <code>SYS_TTY_ALLOC</code>, drains it into a 32 KB
+			<code>/share/svc-&lt;name&gt;.log</code> and writes
+			<code>/share/svc-&lt;name&gt;.state</code> (state, desired, pid,
+			tty, start time). The control tty and the WM pid are in
+			<code>/share/init.state</code>; <code>/share/init.log</code> is
+			the manager log.</li>
+			<li><strong>Lifecycle.</strong> Start, stop, restart and kill are
+			requests to init; a service that exits unexpectedly is marked
+			stopped (no v1 auto-restart). There are no signals, so stop and
+			kill both terminate the process; kill is the forced variant and
+			init drains/closes the log tty when it observes the exit.
+			On an init restart the new init first kills every leftover ring-3
+			process (kernel threads survive), then restarts the WM and the
+			services whose saved desired state is running.</li>
+			<li><strong>Parent death and detach.</strong> Every process has a
+			<code>parent_pid</code>; exit, kill and the reaper kill the
+			descendant subtree. <code>SYS_SPAWN</code> is parented by default;
+			<code>SYS_SPAWN_DETACH</code> attaches the child to the caller's
+			parent (the terminal/WM session), so a file manager, chat window
+			or WiFi helper can launch something that outlives it without
+			leaking a root process. Terminal commands are parented and
+			foreground; the browser and gallery launchers spawn the real app
+			parented and wait for it, so Ctrl-C/terminal close kills it.
+			<code>SYS_SPAWN_KCMD</code> stays parented.</li>
+			<li><strong>CLI and GUI.</strong> <code>service</code> lists
+			<code>init</code>, <code>wm</code> and the user services;
+			<code>service status &lt;name&gt;</code>, <code>start</code>,
+			<code>stop</code>, <code>restart</code>, <code>kill</code>,
+			<code>logs &lt;name&gt;</code>, <code>logtail &lt;name&gt;</code>
+			and <code>service --gui</code> are the client. The GUI has a
+			service list, Start/Stop/Restart/Kill controls (Kill asks for a
+			second click), a log pane and a refresh loop; closing it does not
+			stop services. <code>wm</code> is a system service: Stop is
+			refused, Restart/Kill respawn it and close its windows.</li>
+			<li><strong>Protocol.</strong> A client allocates a response tty,
+			reads <code>/share/init.state</code> and writes
+			<code>NBI1 &lt;seq&gt; &lt;op&gt; &lt;name&gt; &lt;resp_tty&gt;</code>
+			to init's control tty; init replies
+			<code>NBI1 &lt;seq&gt; &lt;code&gt; &lt;pid&gt; &lt;message&gt;</code>.
+			<code>SYS_TTY_WRITE</code> is non-blocking and never writes a
+			partial message; <code>SYS_TTY_CLOSE</code> is owner-only.
+			<code>TTY_MAX</code> is 16.</li>
+			<li><strong>Not a service.</strong> <code>bootscan</code> is a
+			kernel thread plus a log viewer; <code>netconsole</code> and
+			<code>netkexec</code> are kernel facilities. The terminal is
+			started by the WM.</li>
+		</ul>
+		<div class="note">
+			<p><strong>NIC caveat.</strong> A running <code>websrv</code>
+			owns the raw NIC receiver. Browser/curl TCP connections and
+			<code>make net-dev</code> fail until <code>service stop
+			websrv</code>. Logs, state and the service table's enabled state
+			are RAM-only in this version; there is no persisted autostart.
+			The kernel and command pack have no old-ABI compatibility after
+			the spawn/tty changes.</p>
+		</div>
+	</section>
+
 	<section id="libc">
 		<h2>Ring-3 libc</h2>
 		<p>
@@ -185,7 +267,7 @@
 
 				<rect class="svg-box green" x="216" y="146" width="376" height="58" rx="9"/>
 				<text class="svg-text" x="236" y="171">VFS load → process_create_user</text>
-				<text class="svg-sub" x="236" y="191">ELF segments · page directory · 8-page stack · arg</text>
+				<text class="svg-sub" x="236" y="191">ELF segments · page directory · 32-page stack · arg</text>
 
 				<rect class="svg-box amber" x="628" y="146" width="270" height="58" rx="9"/>
 				<text class="svg-text" x="646" y="171">kernel process</text>
@@ -203,6 +285,20 @@
 				kernel. Builtins are handled inline, before either lookup.
 			</figcaption>
 		</figure>
+		<p>
+			<code>SYS_SPAWN</code> takes a <code>struct sys_spawn</code> with
+			path, argument, cwd, tty and a flags word. The default parent is
+			the caller; <code>SYS_SPAWN_DETACH</code> attaches the child to the
+			caller's parent (the terminal/WM session), or to PID 0 when that
+			parent is gone. Every process has a <code>parent_pid</code>: exit,
+			kill and the reaper recursively kill descendants, so closing a
+			terminal kills its commands, closing the WM kills its apps, and an
+			init crash resets the userland tree. File managers, chat and the
+			WiFi helpers use detached spawns for launched apps/daemons; terminal
+			commands and <code>SYS_SPAWN_KCMD</code> stay parented. The browser
+			and gallery launchers spawn the real app parented and wait for it,
+			so a terminal launch is foreground and Ctrl-C kills the app.
+		</p>
 	</section>
 
 	<section id="syscalls">
@@ -225,7 +321,7 @@
 					<tr><td>System info</td><td>12–16, 49–51, 91–92, 102–103, 107</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, Chrome EC sensors, AC/battery</td></tr>
 					<tr><td>Network</td><td>17–47, 106</td><td>NIC config/acquire, raw frames, DHCP/DNS/NTP, TCP client, ARP, cwd</td></tr>
 					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87, 109</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize/scroll</td></tr>
-					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90, 108</td><td>TTY, spawn, getpid, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
+					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90, 108, 124–127</td><td>TTY create/alloc/read/write/close, spawn flags, getpid, alive, kill subtree, chdir, scheduler info, heap alloc/grow/free, is-init</td></tr>
 					<tr><td>TCP server</td><td>93–97, 99–101</td><td>listen, accept, server recv/send/close, peer, speed, MAC set</td></tr>
 					<tr><td>WiFi</td><td>110</td><td><code>SYS_WIFI(op, a2, a3)</code>: up, status, scan/results, connect/disconnect, EAPOL RX/TX, set key, authorize, set/get PTK for the rekey helper (<span class="file">wifi.c</span>)</td></tr>
 					<tr><td>NIC menu</td><td>111–112</td><td><code>SYS_NET_DEVLIST</code> (present drivers with kind/active/link) and <code>SYS_NET_SELECT</code> (make a named netdev active)</td></tr>
@@ -326,7 +422,7 @@
 			</div>
 			<div class="card">
 				<h3>System</h3>
-				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>process</code> <code>mouseinfo</code> <code>touchpad</code> <code>sensors</code> <code>powerinfo</code> <code>date</code> <code>spin</code> <code>membench</code> <code>clock</code> <code>colors</code></p>
+				<p><code>init</code> <code>service</code> <code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>process</code> <code>mouseinfo</code> <code>touchpad</code> <code>sensors</code> <code>powerinfo</code> <code>date</code> <code>spin</code> <code>membench</code> <code>clock</code> <code>colors</code></p>
 			</div>
 			<div class="card">
 				<h3>Network</h3>
@@ -334,7 +430,7 @@
 			</div>
 			<div class="card">
 				<h3>GUI</h3>
-				<p><code>wm</code> <code>term</code> <code>bootscan</code> <code>files</code> <code>disks</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>process</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
+				<p><code>wm</code> <code>term</code> <code>bootscan</code> <code>files</code> <code>disks</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>process</code> <code>service --gui</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
 			</div>
 		</div>
 		<p>
@@ -343,7 +439,12 @@
 			<code>/share</code> (<code>BROWSER</code> or <code>GALLERY</code>)
 			before the pack copy and the FAT fallback on <code>root.img</code>.
 			This lets <code>make browser-dev</code> and <code>make gallery-dev</code>
-			update an app without rebuilding the pack.
+			update an app without rebuilding the pack.  The launchers spawn
+			the real app as a parented child and wait for it, so a terminal
+			launch stays foreground and Ctrl-C/terminal close kills the app;
+			when a GUI app launches them, that app uses a detached spawn so
+			the launcher/app subtree survives the file manager or chat window
+			but still dies with the terminal/WM session.
 		</p>
 	</section>
 
@@ -352,9 +453,10 @@
 		<ul>
 			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
 			<li><strong>bootscan</strong> — live tail of the boot storage-scan kernel thread's output (the WM opens it before the terminal, flush right under the top bar). The kernel captures the thread's COM1 trail (mounts, probes, boot traces) into a ring exposed by <code>SYS_BOOTLOG</code>; the window follows the tail while the scan runs, keeps the scrollback afterwards, pauses the follow when scrolled up, and closes with Esc. The deferred USB mount pass runs after the window's ring closes, so its lines appear on COM1/netmon but not in the bootscan scrollback. Also startable from the shell.</li>
-			<li><strong>process</strong> — graphical task manager (start menu <em>Tasks</em> entry or <code>process</code>), the ngui counterpart of <code>top</code>. It samples once per second into 60 s histories of CPU busy (<code>SYS_SCHEDINFO</code> idle ticks summed over all CPUs), physical memory in use (<code>SYS_MEMINFO</code>) and NIC throughput (<code>SYS_NET_INFO.rx_bytes</code>/<code>tx_bytes</code> from the netdev frame counters), then draws the three graphs with ngui rectangles and lines. The table lists PID, state, CPU%, memory, total CPU time and name; clicking a header sorts by PID, state, CPU, memory, time or name, and PgUp/PgDn or the wheel scrolls. Selecting a row shows its details; <em>End task</em> asks for a second click and then calls <code>SYS_KILL</code>, while kernel threads (<code>kernel_thread</code> in the process snapshot) and the monitor itself are protected. Esc closes it.</li>
+			<li><strong>process</strong> — graphical task manager (start menu <em>Tasks</em> entry or <code>process</code>), the ngui counterpart of <code>top</code>. It samples once per second into 60 s histories of CPU busy (<code>SYS_SCHEDINFO</code> idle ticks summed over all CPUs), physical memory in use (<code>SYS_MEMINFO</code>) and NIC throughput (<code>SYS_NET_INFO.rx_bytes</code>/<code>tx_bytes</code> from the netdev frame counters), then draws the three graphs with ngui rectangles and lines. The table is a process tree: it lists PID, state, CPU%, memory, total CPU time and name, indents children under their <code>parent_pid</code>, and still sorts sibling groups by PID, state, CPU, memory, time or name when a header is clicked; PgUp/PgDn or the wheel scrolls. Selecting a row shows its pid/ppid and details; <em>End task</em> asks for a second click and then calls <code>SYS_KILL</code> (which kills the subtree), while kernel threads (<code>kernel_thread</code> in the process snapshot), the monitor itself and init are protected. Esc closes it.</li>
 			<li><strong>disks</strong> — storage manager (start menu <em>Disks</em> entry, or the <em>Disks</em> button in <code>files</code>): devices, MBR partitions and mounts; per-volume mount name, read-only and automount saved to <code>/data/MOUNTS.CFG</code>; Format and Install NebOS dialogs that run <code>format -y</code>/<code>install -y</code> on a private tty and show the log. See <a href="filesystems.html#disks">Filesystems → Storage manager</a>.</li>
 			<li><strong>gallery</strong> — live widget and primitive showcase; the real app ships in the pack.</li>
+			<li><strong>service</strong> — the init client: <code>service</code> lists <code>init</code>, <code>wm</code> and the user services, <code>status/start/stop/restart/kill/logs/logtail</code> act through init, and <code>service --gui</code> (or the start menu's <em>Services</em> entry) opens the ngui service list with Start/Stop/Restart/Kill (Kill needs a second click) and a live log pane. It is a stateless client: state and logs are read from <code>/share</code>, actions go over init's control tty.</li>
 			<li><strong>chat</strong> — native Cloudron Chat client (start menu <em>Chat</em> entry, or <code>chat [config-path]</code>): username/password/TOTP login through the Cloudron OIDC API or a pasted session cookie, channels and DMs with unread badges and presence, history with older paging, inline image attachments, link-preview cards (click one to open it in the browser) and profile-picture avatars, sending, REST polling, read markers, browse/join and new DM.  The session cookie (never the password) is saved in <code>/data/CHAT.CFG</code> when the persistent volume is mounted, or in the RAM-only <code>/share/chat.cfg</code> otherwise.  Keys: Enter sends, PgUp/PgDn scroll, Home at the top pages in older history, Ctrl+B browse, Ctrl+N new DM, Ctrl+R refresh, and with the composer unfocused (Esc) Up/Down switch conversations.  See <a href="network.html#chat">Network → Chat client</a>.</li>
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
 			<li><strong>mines</strong> — second ngui canvas app; shares the toolkit and event model.</li>
@@ -438,8 +540,11 @@
 			<li><code>kernel/syscall.c</code>, <code>kernel/syscall_stub.S</code>, <code>include/syscall.h</code></li>
 			<li><code>kernel/sys_info.c</code> — kernel-state snapshots (memory, sensors, power)</li>
 			<li><code>kernel/rtc.c</code> — CMOS RTC read/write, format decoding and the 1970–2069 year window</li>
-			<li><code>kernel/process.c</code> — ELF load and spawn</li>
+			<li><code>kernel/process.c</code> — ELF load and spawn, parent tracking and subtree kill</li>
+			<li><code>kernel/init.c/h</code> — PID-1 init bootstrap, protection and restart</li>
 			<li><code>kernel/elf.c</code> — ELF parser</li>
+			<li><code>user/apps/init/ucmd_init.c</code> — init service manager, WM supervisor, logs/state and control tty</li>
+			<li><code>user/apps/service/ucmd_service.c</code>, <code>service_proto.c</code>, <code>service_defs.c</code>, <code>user/service_proto.h</code> — <code>service</code> CLI/GUI, shared units and the init protocol</li>
 			<li><code>user/apps/term/ucmd_term.c</code> — windowed shell, scrollback, PATH</li>
 			<li><code>kernel/terminal.c</code> — privileged kernel command registry</li>
 			<li><code>kernel/install.c</code> — privileged live-image clone installer</li>

+ 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 */

+ 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");

+ 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);

+ 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);

+ 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)
 {

Неке датотеке нису приказане због велике количине промена