AGENTS.md 212 KB

AGENTS.md — NebOS (nebos)

A from-scratch, freestanding 32-bit x86 hobby operating system written in C and x86 assembly. Single-author project (~7,000 SLOC, no external runtime; the kernel has no libc, while ring-3 commands may link the in-tree libc.a). Targets i586 (first-gen Pentium); runs under QEMU or on real hardware.

Source tree

Directory Contents
boot/ boot.S (boot sector, linker.ld), mbr.S/mbr.ld, vesa_stage.S (linked first into kernel.elf), boot/efi/ (UEFI loader)
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/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, 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
host/ Linux SDL3 browser harness

The top-level Makefile builds everything. Objects go to build/ (mirroring the source paths, with -MMD header dependencies); the images and the files the workflows use (kernel.elf, kernel.bin, boot.bin, mbr.bin, floppy.img, usb.img, usb-efi.img, BOOTX64.EFI, cmds.pack, cmds_pack_gz.bin, rootfs*.bin, cmds.img, root.img, browser.elf, gallery.elf, the host tools and test binaries) stay at the top level. Include paths: the kernel sees include/, common/, kernel/; ring-3 code sees include/, common/, user/ and every user/lib/* (plus the libc headers unless an object clears XFLAGS). The kernel never includes a userland header; user/apps/term/ucmd_term.c is the one ring-3 file that uses kernel headers (IO_KEY_*, VFS_PATH_MAX) and gets -Ikernel. Per-object flags (OPT, XFLAGS) are target-specific variables on the .o; make does not track flag changes, so delete the object (or make clean) after editing one. The kernel link order is KERNEL_LINK_ORDER and is part of the image layout.

Documentation site (docs/)

docs/ is the static architecture site: hand-written HTML5, one shared style.css and a small hand-written SVG favicon, with no JavaScript, no build step and no external fonts or CDNs. Open docs/index.html directly (file:// works) or serve it with python3 -m http.server -d docs.

Keep the site in the same change as the code. Architecture changes belong in this file and the matching page:

Page Covers
docs/index.html Overview, layer diagram, at-a-glance numbers, subsystem map
docs/boot.html BIOS/VESA, MBR, UEFI loader, kexec, boot info, image layout
docs/memory.html Address map, E820/bitmap allocator, paging, MTRR, user arenas
docs/cpu.html GDT/TSS, interrupts, ACPI/SMP, CFS-lite, BKL, idle/power
docs/drivers.html PCI, FDC/PATA/AHCI, USB core + UHCI/OHCI/EHCI/xHCI, HID, mass storage, sensors
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/development.html Toolchain, make targets, hot reload, tests, debugging

Rules:

  • A change to a boot path, hardcoded address, scheduler/ABI, driver model, file service, graphics/WM path, protocol, syscall number, build target or reload workflow must update the corresponding page in the same change. A new subsystem needs a section on an existing page (or a new page linked from the index) and a card on docs/index.html.
  • Update AGENTS.md whenever the architecture or a documented invariant changes; AGENTS.md and docs/ are both source-of-truth maps and must not drift. Each page's "Source map" lists the files it documents; keep it current.
  • Charts and diagrams are hand-written HTML/CSS or inline SVG. No JavaScript, CDN, generated asset or build step. Every charted number must come from a source constant/table; cite the defining file in the caption or source map.
  • Keep internal links working, the active nav item correct, the layout usable from a phone width to a wide desktop, and the site readable from file://.
  • Keep version strings in the page heads and footers in sync with OS_NAME/OS_VERSION in version.h.

Build & run

Toolchain: gcc (32-bit multilib), as/ld/objcopy, mtools (mcopy/mkfs.fat), qemu.

make all        # floppy.img usb.img final.bin root.img
make run        # boot floppy.img + root.img in QEMU (fallback: qemu-system-x86_64)
make run-smp    # same with -smp 4 (BSP + 3 APs, the Atom 330 topology)
make run-usb    # boot usb.img as an IDE disk
make run-uhci   # like `make run` but with a UHCI controller + USB mouse
make run-ehci   # EHCI + UHCI companion: high-speed storage on EHCI, HID on UHCI
make run-ehci-asix # pass through a real ASIX AX88772 dongle on EHCI
make run-net    # like `make run` + a PCI NE2000 NIC on QEMU's user network (slirp; DHCP/DNS/NAT)
make run-rndis  # xHCI + QEMU usb-net RNDIS tethering device on slirp (rndis netdev)
make run-ahci   # like `make run` + an ICH9 AHCI controller and a 512 MB SATA disk (sata0)
make run-amd    # QEMU Opteron_G5 (FX-6350 family 15h model 2), 6 CPUs, OHCI + e1000
make test-amd   # headless AMD boot check (IOAPIC mask, 6 CPUs, PIT)
make uefi       # build BOOTX64.EFI and the dual-boot usb-efi.img
make run-uefi   # boot usb-efi.img under OVMF (x86-64 UEFI; serial log in /tmp/opencode)
make test-uefi  # headless OVMF boot test (greps the serial log for the boot line)
make test-install # installer test: clone, reinstall, install self, /data, BIOS/UEFI boot
make rootfs     # build cmds.img (the 8 MB rootfs partition image)
make browser-host # Linux SDL3 host harness (browser-host + host-curl); dev-only
make nowm       # diagnostic kernel with no WM; the boot console stays visible
make dev        # serial kernel + rootfs reload (KXE2)
make kernel-dev # serial kernel-only reload (keeps the running rootfs)
make net-dev    # network kernel + rootfs reload (KXN2, RAM only)
make net-install # persist kernel + full rootfs to P1/P2 (KXI2, keeps /data)
make kernel-net-dev
make flash      # write the dual-boot image (legacy BIOS + UEFI) to a USB stick
make test-usb   # headless USB mouse/keyboard regression tests (QEMU + python3)
make test-images  # host image-decoder + blit tests (ASan variant: test-images-asan)
make test-libc  # host tests for ring-3 malloc, stdio, math, div64 and setjmp
make test-js    # host tests: QuickJS through the js_mu stack API (ASan/UBSan)
make test-font  # host TrueType parser/rasterizer specimen test
make test-font-asan  # ASan/UBSan variant
make test-svg   # host tests for the inline-SVG rasterizer (ASan/UBSan)
make test-touchpad  # host tests for the contact gesture engine
make test-cursors   # host test for the NBCUR1 cursor bundle (mkcursors output)
make test-wpa   # host tests for the WPA2-PSK supplicant (SHA-1/PBKDF2/PRF/AES, 4-way)
make test-wifi-store  # host tests for the saved-network list file
make test-chat  # host tests: JSON parser, cookie jar, chat login parsers (ASan)
make test-chat-e2e  # QEMU + tools/mock_chat.py chat end-to-end (CHAT_E2E=--totp...)
make compat-serve  # serve the browser A/B ladder on port 8000
make fonts      # regenerate fonts/*.ttf with pyftsubset + system fonts
make clean
  • Build flags (in Makefile): -m32 -march=i586 -ffreestanding -fno-pie -nostdlib -fno-stack-protector -mno-sse -mno-sse2 -mno-mmx -O2.
  • make browser-host is a development-only harness, not part of the images: it builds browser.c, ngui, the image/TLS stack and QuickJS as a 32-bit Linux program against the same SYS_* ABI (host/syscall.c, an SDL3 window, host files/sockets and fork/exec for curl __serve). Run ./browser-host [--size WxH] [--root DIR] URL|FILE, or ./browser-host --headless --wait 3000 --shot out.ppm URL to render the compat ladder without a display; --keys 'clo{down}{enter}' types into the headless window (100 ms per key from 300 ms after the first frame; {enter} {esc} {tab} {bs} {del} {up} {down} {left} {right} {ctrl-l} {wait}, and {click:X,Y} for a left click at canvas coordinates). It needs the multilib lib32-sdl3, lib32-wayland and lib32-libxkbcommon; host sockets replace the NebOS TCP stack and the kernel/WM paths are not exercised.
  • QEMU guests default to 1 GB (QEMU_MEM), the lowmem size (MM_MAX_PHYS in phys.h); make run QEMU_MEM=3G exercises highmem. All run and UEFI targets pass -m.
  • The command pack is the system rootfs: cmds.pack (NBPAK1), gzip-compressed to cmds_pack_gz.bin, wrapped by mkrootfs with a one-sector NBROOT1 header into cmds.img (the 8 MB USB partition image) and BOOTX64.EFI. The floppy images append rootfs.bin, built the same way from 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).
  • 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 search; zstd needed for .zst). A missing file only prints a note and leaves that card without firmware. The Realtek RTL8821AU stick needs firmware/rtw8821a_fw.bin (linux-firmware rtw88/, WIFI_FW_8821A overrides) and firmware/rtl8821a.tbl, which the host tool mkrtwtbl builds from the vendored Linux tables in third_party/rtw88/ (BSD-3-Clause option of rtw88's dual license).
  • root.img is a second FAT12 floppy holding the disk fallback copies of the browser/gallery (BROWSER, GALLERY) and its DEMO.HTM/JS.HTM test pages plus PIC.BMP, and a few test files; it requires mtools to build.
  • UEFI needs x86_64-w64-mingw32-gcc (the 64-bit loader) and, for the QEMU targets, an OVMF firmware (OVMF=/path/to/OVMF.4m.fd overrides the default). make all does not build the UEFI image, so a machine without mingw still builds the legacy floppy/USB images normally.
  • usb.img is 9 MB: partition 1 (type 0x06, LBA 63, 1024 sectors) is the boot sector + kernel and partition 2 (type 0x7F, LBA 1088) is the 8 MB rootfs image (cmds.img), 512 KB behind the boot sector. With the WiFi firmware the gzip pack is ~1.3 MB, so it now ends past the first 1.44 MB: a BIOS that boots the stick as a CHS-only floppy can no longer read all of it (fixed-disk LBA boots are fine). The boot sector's pack_lba field points the VESA stage at partition 2. usb-efi.img (17 MB) adds an 8 MB FAT16 ESP as partition 3 (type 0xEF, LBA 18432); BOOTX64.EFI embeds the kernel + gz pack. The install command clones this used image (MBR through the last partition) from a visible block device, so a cloned target keeps both boot paths. make flash writes the dual image; make flash FLASH_IMG=usb.img writes the legacy-only image. One BPB byte is cleared in the dual image (disk offset 0x7E16, FATSize16): without that, UEFI firmware scans partition 1, sees the FAT16-looking boot sector and mounts the raw kernel blob as a volume, writing FAT/root pages over the kernel at LBA 64. boot.S and the BIOS never read FATSize16. make flash needs the mingw toolchain because it builds usb-efi.img.

The Gigabyte 970A-DS3P / FX-6350 / GTX 960 target is UEFI-first and serial-less: boot usb-efi.img from USB, use the 970A's SB950 AHCI/OHCI/EHCI, the RTL8111E (10ec:8168) and the GTX 960 through its GOP. The boot console is the only early log; once DHCP works, make netmon is the serial substitute and make net-dev/kernel-net-dev reload over the network. bootlog save /usb0p3/BOOTLOG.TXT writes the captured boot log to the live stick's FAT ESP.

Boot chain

  1. boot.S — 512-byte boot sector (FAT16 BPB). Loads contiguous kernel sectors to 0x7E00, one INT 13h per run of sectors into ES:0 with ES advanced (the offset never wraps): EDD LBA for hard disks, up to 64 sectors; CHS for floppies, up to the end of the track and never across a 64 KB physical ISA DMA boundary. Errors get three tries per run, then one sector per call (the old behaviour), three tries, then Disk read error. Jumps to the stage with the boot drive still in DL (do not clobber DX). The 512-byte sector has only a few bytes left before the partition table.
  2. vesa_stage.S — real-mode VESA stage. Probes INT 15h E820 into 0x1000, enables A20, reads the NBROOT1 rootfs header at the boot sector's pack_lba field and copies the gzip pack directly to PACK_HIGH_ADDR (0x900000, above the 8 MB VGA-shadow reserve) in 16 KB chunks through the 0x3000 staging buffer — one INT 13h per chunk (32 sectors over EDD, up to the end of the track over CHS; a refused multi-sector request falls back to one sector per call; the old per-sector loop made ~3600 BIOS calls and took ~1.5 s in QEMU) — with a temporary flat protected-mode rep movsb (pm_copy). The X201 BIOS's INT 15h AH=87h block move silently copies zeros to this range, which left the kernel with an empty pack; the CPU copy is used instead. paging_prepare_cpu() still clears the CR4/EFER state a BIOS protected-mode call can leave behind. The stage then picks the best VBE mode (≥16 bpp, LFB, fits VRAM, ≤1920px, shadow ≤8 MB and ≤2 M pixels so a full-screen RGB565 canvas fits the 4 MB window slot), writes mode info to 0x600 and the 12-dword struct boot_info (magic/checksum/rsdp/flags/pack range) to 0x500, enters protected mode and jumps to kernel_entry (entry.S, re-points ESP to the current stack top, then kernel_main). The pack never occupies the low gap, so the cap is PACK_MAX (2 MB) and the kernel BSS/boot stack may extend past 0x60000. The stage prints Loading rootfs [d=<drive> lba=<hex> e=<0|1> m=<C|L>]..., then a dot after the header and one per 16 KB chunk, so a BIOS hang is localised. Drives below 0x80 use CHS (the same path the boot sector's kernel load used); fixed disks use EDD LBA.
  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, 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 (storage scan + FAT mounts, then the /data WiFi autoconnect once the boot DHCP finished) → DHCP. So the terminal is on screen before USB, NIC and disks are probed; USB input, USB NICs and USB disks attach right after. The WM's SYS_NET_INFO does not trigger the NIC probe (it reports "no NIC" until kernel_main probed), so the first frame never waits for a PHY reset. COM1 prints wm: first window frame (term) at N ms (uptime) when the first app window presents: the end point of a boot-time measurement (~0.35-0.4 s after the kernel starts on QEMU's USB image).
  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 picks a GOP mode, converts GetMemoryMap into the E820 map at 0x1000 (all RAM below 4 GB, at most 32 runs), stages kernel.bin below 4 GB, allocates a loader-data buffer below the 1 GB identity window (above the low 1 MB) for the embedded gz rootfs and copies it there, fills 0x500 (boot info) and 0x600 (framebuffer), calls ExitBootServices, copies a 192-byte trampoline to 0x800, leaves IA-32e mode (CR0.PG, EFER.LME, CR4.PAE/PGE/PCIDE/SMEP/SMAP/ LA57), copies the kernel to 0x7E00 and jumps to kernel_entry. The BIOS boot sector / VESA stage are not executed on this path; the legacy chain is separate (it loads the same gz pack from the rootfs image).

SMP is ACPI-only: RSDP → RSDT/XSDT → MADT, then LAPIC + INIT-SIPI-SIPI. There is deliberately no Intel MP-table parser. If ACPI, a usable MADT, the CPUID APIC bit or the LAPIC is missing, cpu_count stays 1 and the machine boots exactly like before (8259 PIC + PIT, no APIC MSR/MMIO access). This keeps a Pentium 1 (and a Pentium II board without ACPI) on the UP path.

Hardcoded memory map (fragile — keep in sync when editing)

Address Purpose
0x500 Boot info (struct boot_info, bootinfo.h, 12 dwords): magic/checksum, ACPI RSDP, EFI/RGBX flags, and the boot-time rootfs pack addr/size; written by vesa_stage.S, the UEFI loader or kexec
0x600 Boot framebuffer info (struct vga_boot_fb_info, see vga.h; written by vesa_stage.S or the UEFI loader)
0x7C00 Boot sector load address; also the UEFI handoff stack top
0x7E00 Kernel load / VESA-stage entry (kernel.ld); the UEFI loader copies the kernel here and jumps to kernel_entry
0x800 kexec and UEFI handoff trampoline (relocated at runtime; below the kernel)
0x900 kexec/UEFI flat GDT + GDTR (built at runtime; below the kernel)
0x1000 E820 memory map (struct e820_map, written by vesa_stage.S or the UEFI loader, parsed by mm.c); also the kexec trampoline's private stack top (grows down, below the map)
0x3000 UHCI frame list (1024 × 4 B, 4 KB-aligned; uhci.c)
0x4000 ISA DMA buffer, one sector (disk.c)
0x6000 AP real/protected-mode trampoline (ap_tramp.S/ap_tramp.ld; SIPI vector 0x06, image ends below 0x6C00)
0x6C00 AP trampoline real-mode stack top (grows down)
0x6F00 AP startup info block (CR3, stack top, C entry, CPU index)
0x60000 No longer a rootfs staging area: the legacy stage copies each 16 KB chunk straight to 0x900000. The kernel BSS/boot stack may use this range
_end Kernel end (linker symbol; kernel.ld keeps _end <= 0x90000 so the top of the low-memory gap and the EBDA stay untouched). BSS and the boot stack may extend past 0x60000
(in-image) Bootstrap/protected-mode stack: 8 KB .stack NOLOAD section, __boot_stack_top/__boot_stack_bottom (travels with the kernel)
0x900000 Legacy boot-time rootfs pack written directly by vesa_stage.S (reserved by mm_init until ramfs_init takes its copy, then freed); mm_init places the frame bitmap in the first RAM after it (0xAF3000 with today's pack); process stacks and kexec staging also start here
0x100000 VGA shadow buffer (VGA_SHADOW_BASE, vga.h)

The legacy stage uses 0x3000..0x6FFF as a 16 KB-chunk rootfs staging buffer before the kernel starts; the UHCI frame list (0x3000), ISA DMA buffer (0x4000) and AP trampoline (0x6000) reinitialize those addresses later.

The boot-time rootfs pack placement depends on the boot path: the legacy stage copies it directly to 0x900000, the UEFI loader puts it at the top of RAM below 1 GB, and kexec leaves it in the staging buffer (≥ 0x900000). mm_init reserves [pack_addr, pack_addr+pack_size) from boot info when it is above the low 1 MB, so the legacy pack is protected from the frame allocator too. ramfs_init copies/inflates it into fresh pages and mm_free_range() releases the boot region when it is above the VGA shadow reserve.

Everything else is dynamic: process stacks and the kexec staging buffer come from the frame allocator (≥ 0x900000), and the fallback stack pool is a static BSS array. The UEFI loader's kernel staging buffer comes from AllocatePages below 4 GB and only lives until the 0x800 trampoline copies it to 0x7E00. The kernel region itself only has one wall (_end below 0x90000), so adding code no longer moves any address.

Key files

  • Multitasking: sched.c/h, process.c/h, tss.c/h, switch.S — CFS-lite weighted fair scheduling (weight 1..16, 64-bit vruntime, 10 ms slice; WM 16, default/commands/terminals 8, kworker 4), a sorted sleep list and wait queues (no polling scans), stable per-PCB objects in a sparse PROC_MAX pointer table, per-CPU struct cpu/GDT/TSS with %gs-based this_cpu(), and a per-CPU current (no global current_pid). Idle is not a process slot; a normal kworker process does the housekeeping and the zombie reaper. sched_lock (IRQ-safe spinlock) protects the global run/sleep/wait queues and the process-table state touched by timers; schedule() keeps it across the stack switch and sched_finish_switch() (called from switch.S after loading the new ESP) drops it, so another CPU can never pick a process whose kernel stack this CPU is still unwinding. Excess wake-up races are handled by skipping a queued process that is still marked running on another CPU. The big kernel lock (bkl_*) is a sleeping recursive mutex: every ring-3 syscall and every kernel thread takes it, voluntary block/sleep points drop it (sched_yield), and long serial/raw-network waits release it via bkl_pause()/bkl_resume(). A BKL holder is not timer-preempted, so it can safely be in the middle of kernel data structures. Kernel threads are pinned to the BSP; user processes may run on any CPU. The idle fallback uses bkl_trylock() (never blocks); the kworker and kernel commands take the BKL normally and release it around their sleeps. APs use their LAPIC timer (vector 0x30; 1 ms busy, 10 ms idle); the BSP keeps the 8259 PIC/PIT and 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. 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.
  • SMP / ACPI: acpi.c/h (RSDP → RSDT/XSDT → MADT; CPU/LAPIC and IOAPIC base lists; 4 MB table page mapping; malformed tables are ignored), ioapic.c/h (masks the normal IOAPIC redirection entries after ACPI init so the 8259/LINT0 path is deterministic; ExtINT entries are preserved), lapic.c/h (xAPIC MMIO access, BSP/AP init, INIT/SIPI/IPI, calibrated periodic timer), smp.c/h (trampoline copy, AP stacks via process_init_ap, INIT-SIPI-SIPI with a second SIPI retry, per-CPU smp_ap_main, smp_stop_aps, lazy smp_enable_sched), ap_tramp.S + ap_tramp.ld (real → protected-mode trampoline at 0x6000), and spinlock.h (the IRQ-safe spinlocks). cpu_enable_sse() runs on every AP: an AP starts with firmware CR4, and the SSE2 drawing fast paths #UD until OSFXSR/OSXMMEXCPT are set.
  • Memory: phys.h — MM_MAX_PHYS (1 GB, the lowmem/identity-map ceiling, also used by the UEFI loader for the pack buffer), MM_KMAP_VA (0x4FC00000) and MM_HIGH_LIMIT (4 GB). Lowmem ends where ring-3 space starts (USER_BASE = 0x40000000), and paging.c statically asserts that the identity map never reaches a user window. mm.c/h — INT 15h E820 detection (real-mode in vesa_stage.S, map at 0x1000) + a bitmap page-frame allocator (4 KB pages) over all RAM below 4 GB, in two zones: lowmem [0, 1 GB) is identity-mapped and serves every kernel allocation (mm_alloc_page, mm_alloc_pages, kmalloc: page tables, DMA buffers, canvases, kernel stacks); highmem [1 GB, 4 GB) is never identity-mapped and is handed out only by mm_alloc_user_page() (highmem first, lowmem fallback) for ring-3 program, stack and heap frames (elf.c, process.c, sys_mem.c). The kernel touches such a frame only through the owning process's mapping or kmap(phys)/kunmap() (paging.c): the 4 MB slot at MM_KMAP_VA (in the gap below USER_WIN_BASE) has one supervisor page table shared by every process directory, with 4 nesting (LIFO) slots per CPU; a highmem kmap disables preemption until kunmap and flushes only its local TLB entry, lowmem returns the identity address. Nothing may sleep between them. (It is not the last lowmem slot, where firmware puts the ACPI tables, nor the top PDE, where a VBE LFB may sit.) The kernel reserves low 1 MB and an 8 MB VGA-shadow region. The bitmap is sized to the highest E820 RAM address (32 KB at 1 GB, 96 KB at 3 GB) and is not in BSS: mm_init places it in the first lowmem RAM run at or above 0x900000 that avoids the boot pack and the LFB and marks its own pages used (a 512-byte static array covers the 16 MB no-E820 fallback); COM1 logs mm: bitmap ... highmem free N MB. Allocation is lowest address first within a zone: a per-zone first-free word hint skips the full low words, single pages are found with bsf, and mm_alloc_pages() steps over full and empty words 32 pages at a time. kmalloc.c/h — a power-of-two heap allocator on top of the frame allocator (used for PCBs and command context). Process stacks (≥ 0x900000) come from the frame allocator, with an 8-stack fallback pool (a static BSS array; no fixed address).
  • UEFI boot: bootinfo.h (the 0x500 block and its checksum/accessors), boot/efi/efi.h (minimal UEFI types and table/protocol layouts), boot/efi/main.c (GOP mode choice, GetMemoryMap → E820, kernel staging below 4 GB and rootfs pack in loader-data pages below 512 MB, boot-info/framebuffer blocks, ExitBootServices). The loader prefers the raw installed image: it locates the parent whole-disk Block I/O handle from the ESP device path, reads the P1 boot sector (kernel_lba/kernel_sectors/pack_lba), then reads the kernel from P1 and the NBROOT1 gzip pack from P2. The kernel and pack embedded in BOOTX64.EFI are only a fallback when the disk image is missing or invalid, so install/net-install update both boot paths without rewriting the ESP. boot/efi/tramp.S + boot/efi/tramp.ld (the 0x800 long-mode exit, kernel copy and jump) and boot/efi/payload.S (embeds kernel.bin, cmds_pack_gz.bin and the trampoline in BOOTX64.EFI). The legacy vesa_stage.S writes the same v2 boot info (with pack_addr/pack_size); vga.c/panic.c honour the RGBX flag and skip the VBE-only ATI CRTC reset / NVIDIA stolen-VRAM alias under EFI; mouse.c forces the software cursor; acpi.c prefers the passed RSDP and maps its page before validating it.
  • Paging: paging.c/h — identity-maps lowmem RAM (4 MB pages via CR4.PSE) and enables CR0.PG/WP. Nothing above lowmem is mapped at its physical address: device registers, firmware tables and the LFB go through ioremap(phys, size, IOREMAP_MMIO|IOREMAP_RAM), which returns the identity address for lowmem (an MMIO range there gets its 4 MB pages made uncacheable, as before) and otherwise a kernel address in the ioremap window [IOMAP_BASE = 0xC0000000, 4 GB): 4 KB pages, bump allocated, never torn down, with page tables allocated on first use and their PDEs copied into every live process directory (process_sync_kernel_pde(); later processes clone them). A request covered by a same-type mapping reuses it, and one that runs past the end of the newest mapping grows it in place (ACPI maps a table header, then the whole table). MMIO pages are uncached except those the LFB's WC MTRR covers, which are cacheable in every alias (so a GPU BAR containing the framebuffer and the LFB mapping agree); IOREMAP_RAM pages (ACPI/SMBIOS tables, the ION stolen-VRAM alias) are write-back. So ring-3 space can use all of [USER_BASE, IOMAP_BASE); paging.c statically asserts that no user window reaches the ioremap window. Drivers keep the physical BAR for logging and comparisons and use the returned pointer for registers; paging_lfb_va() is the LFB's kernel address (vga_fb_lfb_addr() returns it, vga_fb_lfb_phys() the physical one), and bootcon switches to it right after paging is enabled. paging_debug_map() gives peek/poke/dbg access to any physical byte: lowmem directly, highmem RAM through kmap, MMIO through its existing mapping or a new 4 KB uncached one. The LFB in lowmem keeps its identity mapping with WC/UC 4 MB pages (lfb_apply_pages). Before the switch it clears stale translation controls a BIOS protected-mode call can leave behind (CR4.PAE/PGE/LA57/PCIDE/SMEP/SMAP and EFER.LME); the X201's legacy stage historically returned from INT 15h AH=87h with CR4 set, and the first CR0.PG write then triple-faulted. The LFB PDE range is computed from the page index (a base above 0xFF000000 used to wrap base + 16 MB and map nothing), and mm_init reserves a low LFB range so the boot console cannot overwrite the page directory. Each process gets a page directory cloned from the kernel identity map (kernel stacks are mapped everywhere, so CR3 can switch on the old stack); paging_current_cr3() reads CR3. The kexec trampoline (kexec_tramp.S) clears CR0.PG before the copy so it can overwrite the old kernel's page tables safely.
  • Window manager / window server: wm.c/h is the kernel window server; the only WM is the ring-3 process loaded from /ramfs/bin/wm (ucmd_wm.c, 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, spawns the first terminal after wm_server_boot_ready() (set after the storage mount), and composites the canvases into the shadow. A normal window has no visible frame: its WM_TITLE_H title bar starts at the window origin and a resize band (WM_RESIZE_IN 1 px inside, WM_RESIZE_OUT 3 px outside every outer edge) is the edge/corner resize grab area. The focused title bar uses the toolkit highlight ngui_theme_dark.selection. The boot console stays visible until the WM attaches (wm_server_attach disables it), so a missing /ramfs/bin/wm leaves the kernel boot log on screen and the supervisor retries. wm_server_present flushes the damage rects; wm_server_key_wait/poll provide keys. The WM keeps a front-to-back order (focused first, then descending slot); every damage rectangle is painted by subtracting the windows in front, so an occluded window is never repainted and the stack is not drawn back-to-front. A focused-window drag copies its shadow block (usurf_copy) and repaints only the old strips the new rectangle does not cover; when either rectangle is partly off-screen the shadow has no valid pixels for the hidden part, so that step repaints the window rect instead of copying desktop background into it. Windows may be dragged past the left, right and bottom edges while at least WM_DRAG_VISIBLE (48 px) of the title bar stays on-screen; the top bar is never overlapped. Double-clicking the title bar toggles maximize/restore against the work area below the bar (0, WM_BAR_H, fbw, fbh - WM_BAR_H). Dropping a title-bar drag with the pointer on the left or right screen edge (WM_SNAP_EDGE, 2 px) snaps the window to that half of the work area at full height; on the top edge it maximizes. struct uwin.state is WIN_NORMAL/WIN_MAXIMIZED/ WIN_SNAP_LEFT/WIN_SNAP_RIGHT, and the restore geometry is saved only when leaving the normal state, so snap -> maximize -> restore returns to the original. Dragging a maximized or snapped window restores it first, keeping the grab point at the same fraction of the title bar. While dragging, screen edges and the facing edges of windows that overlap on the other axis resist the window: it stays flush until the pointer overshoots by WM_RESIST (24 px) (resist_geom() in ucmd_wm.c). A press in the resize band (1 px inside, 3 px outside) along any edge or corner starts a resize: the grabbed edges follow the pointer while the opposite edges stay put, clamped to the work area. The topmost window's band wins over a window behind it. While dragged or resized the WM owns the pointer (SYS_WM_MOUSE_CAPTURE), so canvas clients see no held button and cannot start a scrollbar drag. The kernel hit-test uses the same order. The right-aligned date/time text is itself a click target: draw_bar() records its rectangle, the pointer highlights it, and a click opens the control panel (the Clock launcher still opens the analog clock). The rightmost bar item is the AC/battery status icon: the Adwaita ac-adapter symbol while the adapter is online and the battery outline with our own level fill inside on battery. Hovering it paints a percentage tooltip below the bar, above every window; clicking it opens the control panel. To its left is the network status icon: the Adwaita network-wired symbol for a wired netdev, network-wireless-signal-* for a WiFi link (by RSSI), the phone symbol for RNDIS tethering, and network-wired-disconnected in red otherwise (network-wireless-offline when a WiFi card is present but not associated). The WM polls SYS_NET_INFO (and SYS_WIFI_STATUS only while WiFi is active) at 1 Hz. The whole right status area is one click target: the temperature, clock, network and AC/battery items and the gaps between them toggle one /ramfs/bin/netmenu control popover, anchored flush against the bottom of the top bar and the right screen edge (u_wm_set_geom). It opens collapsed: the battery/clock summary and the Quick settings pills are visible, while the network, power-mode and date/time settings are hidden until their pill is clicked. A pill toggles its section in place; the panel resizes itself to the content height (up to the screen) and scrolls when a section is taller. A popover is a chromeless WIN_F_POPOVER canvas window (u_win_create_popover): the WM skips the title bar/close/ resize chrome and treats it as always topmost in painting and hit-testing. The canvas fills the whole window rectangle: there is no outer shadow, rim or rounded corner, so it reads as a flat menu panel. The kernel uses the window origin for content-relative pointer and scroll coordinates (a normal window starts its content one title bar below the origin; a popover uses the origin directly). An outside press dismisses the popover and then continues with the normal click handling; a second click on a status target toggles it. Chat spawns /ramfs/bin/chat, Tasks spawns /ramfs/bin/process (the task manager) and the last launcher, Disks, spawns /ramfs/bin/disks (the storage manager); WM_BTN_END_X (wm_abi.h) is the launchers' right edge, and the bar notice and the right-aligned status never draw left of it. When the full date/time would cross that edge, 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 registry for the ring-3 terminal (SYS_SPAWN_KCMD / term_kcmd_spawn), but the kernel terminal entry/shell and the cell-window ABI are gone.
  • Window canvas API: gfx.c/h allocates the RGB565 front/back canvases; sys_wm.c is the ABI bridge. SYS_WIN_CREATE gives a command its window canvas mapped RW at USER_WIN_BASE (0x50000000); the WM maps each front canvas in its own 4 MB WM_CONTENT_SLOT, which covers a full-screen 1920x1080 RGB565 canvas (4.15 MB) minus the chrome. SYS_WIN_PRESENT optionally takes a content-relative struct wm_win_present; the kernel copies only that rectangle into the front canvas (with interrupts off, so a half-drawn frame can never reach the screen), unions it into canvas_dmg_*, and SYS_WM_INFO returns the union to the WM. A present with w/h zero means the whole canvas. The terminal tracks dirty rows and presents only those; uwm_lib.c uses row-based RGB565 conversion, rep stos/rep movs fills and copies, and counts composited pixels in usurf_pixels. The WM writes the last two-second interval to /share/wmstats (frames, ms, max, px) for on-target measurement. SYS_WIN_INFO, SYS_WIN_ACK_RESIZE, SYS_WIN_POINTER, SYS_WIN_EVENT, SYS_WIN_SCROLL, SYS_WIN_KEY_WAIT and the generic SYS_KEY_POLL handle input. SYS_WIN_SCROLL returns scroll accumulated for the canvas window under the pointer, in pixels (+dy = later content), so every client sees one unit independent of whether it came from the touchpad or a wheel. SYS_WIN_SET_CURSOR (117) sets the caller's content cursor, SYS_WM_SET_CURSOR (118) the WM's override and SYS_WM_MOUSE_CAPTURE (121) takes/releases the pointer for a WM drag or resize (see the Mouse cursors bullet). SYS_WIN_RESIZE_SELF (115) lets a canvas window grow or shrink itself and SYS_SCREEN_INFO (116) returns the framebuffer dimensions; the panel uses them to collapse to the pills or grow over an expanded section. The kernel refuses a self-resize while the WM owns a frame, and the caller retries. The WM composites the front canvas; presented frames carry monotonic seq counters, so the WM can never lose one. content_gen comes from a global counter and is unique per window creation, so a close followed by a new window in the same slot forces a remap instead of reusing a stale front canvas mapping. Closing a window kills its owner; the reaper frees the canvas. clock, colors, settime, term, files and the other apps are canvas clients. The old SYS_GFX_BEGIN/PRESENT/END terminal-takeover service and the kernel text-canvas renderer are removed. Pointer input: SYS_WIN_POINTER reports the content-relative position, buttons and focus, and SYS_WIN_EVENT queues press/release edges with a capture window, so a click that starts in a window still gets its release after the pointer leaves. The userland ngui.c/h immediate-mode toolkit builds on those: clipped RGB565 primitives, buttons, text input, the Adwaita symbolic icons and scrolling panes (ngui_scroll: an overlay scrollbar that is hidden while the pointer is outside the pane, slides in on hover over ~100 ms, and reserves no layout width; presses in its strip start the drag and do not reach the content; hide_bar suppresses it entirely). files (ucmd_files.c) is its first user (its toolbar's Disks button opens the storage manager); gallery (gallery.c) is the live showcase of every control and primitive the toolkit exports. Buttons fire on the release edge and keep active until ui->released: inferring release from the sampled ui->buttons races the WM event queue and drops clicks. The popover component (ngui_popover_begin/footer, a flat surface with a body and footer, no title bar or close button) is the shell of netmenu; ngui_section draws captioned section headers with an optional action button, ngui_list_row is a two-line hover/selected row with optional signal bars and trailing text, and ngui_signal_bars draws the four-bar strength icon. The WM draws no outer chrome, so a popover fills its whole window. Text fields use the proportional font with measured caret, selection and horizontal scrolling, and support mouse drag-selection, double-click select-all, Ctrl+Left/Right word jumps, Ctrl+Delete/Ctrl+Backspace word deletion and Ctrl+A select-all; typing or Backspace/Delete replaces a selection. At the end of the line Ctrl+Delete removes the word before the caret instead of doing nothing. A field with secret set is measured and painted from a * mask (the real text is swapped back only for the edit loop, so caret, selection and clicks follow the mask); Tab returns NGUI_INPUT_NEXT with NGUI_INPUT_CANCEL so forms move the focus themselves. NGUI_INPUT_MAX is 512 (511 characters).
  • Graphics: vga.c/h, vga_copy.S, blit.c/h, gpu.c, ati.c, nvidia.c, nv50.c, pci.h — VESA LFB + shadow buffer. Drawing goes into a struct surface render target: vga_target() is the screen's shadow buffer unless the running process set an override (vga_set_target(), stored in the PCB so a preempted draw can never leak), and the WM's pixel operations go through the blit vtable (blit.c/h: fill/copy/blend/canvas/present/flip, software only today) so an accelerator can replace single ops without touching the WM. vga_target_damage() is a no-op while the target is not the screen. cpu.c detects SSE2 (CPUID, with the EFLAGS ID-bit probe and the CR4.OSFXSR/OSXMMEXCPT enable, since the kernel is -mno-sse) and the software fill uses an SSE2 row store when it is there -- streaming (movntdq, one sfence per fill) for rows that do not fit the cache, which avoids the read-for-ownership traffic that makes big fills DRAM-bound on the Atom. gfxbench times the fill/copy/cell/canvas/flush paths and reports the bytes the presenter really copied (vga_present_copied). The flush trims a shared damage list, so vga_present_shadow() refuses to re-enter while another process is mid-flush (a full-screen copy is long enough to be preempted). The boot log prints blit backend: <name>. Drawing marks damage rectangles (a small list that merges rects when they overlap or touch, so a keystroke's cells collapse while unrelated damage stays apart); the main loop copies them to VRAM on every iteration under a byte budget (VGA_FLUSH_BUDGET_BYTES), no fixed frame rate. A rect that fits the budget is copied whole, so a window repaint never tears; only a bigger one (a full-screen redraw) is chunked, and its remaining rows continue after the newer damage. ATI Mach64 CRTC fixup; NVIDIA is VBE-only (never touch the legacy VGA CRTC). On the ION the framebuffer is stolen DRAM and the VBE LFB is a BAR3 window into it; the BIOS leaves a 512 MB uncacheable MTRR over the PCIe apertures, and since the lowest-numbered matching entry wins, the aperture can never be write-combining (~33 MB/s of separate PCIe writes). nvidia_lfb_in_vram() therefore locates the framebuffer in the stolen VRAM (marker through the LFB, page-granular scan of a cached mapping) and vga_shadow_init() writes through that alias once a WC MTRR covers the stolen range (only then -- a cached framebuffer would stop updating the screen). Everything else keeps the UC LFB: paging.c maps LFB pages cacheable only when mtrr_set_wc() says it covered them. On AMD family 15h, mtrr_set_wc() uses a separate path: at most eight variable MTRRs, only a free entry, a zero high mask (the LFB is below 4 GB) and no write to MSR_MTRRdefType. The Intel path's read-modify-write of MTRRdefType reset the 970A-DS3P during the first paging init; the AMD path is validated on the board and enables WC. vga_fb_lfb_wc() reports the effective path and gfxbench prints it. nvidia.c identifies the card, maps BAR0/BAR1/BAR3 and reads the MCP7x stolen-VRAM geometry; nv50.c probes the nv50-family display engine at boot (read-only, serial/netmon). The ION/AT3IONT-I hardware cursor is deliberately not driven: the VBIOS keeps the display engine (INTR_1 bit 8, 0x6194e8 = 0x803), EVO DMA channels never fetch until nouveau's full takeover (which re-programs the mode itself), the cursor staging registers are engine-only, and a channel that has run cannot be restarted — see the header of nv50.c.
  • Panel backlight: backlight.c/h — the Intel Cherryview/VLV display PWM for the internal panel (the HP Chromebook 11 G5's google/setzer VBT declares PWM controller 0, 200 Hz, active high). It matches Intel 8086:22b0/22b1, maps the graphics MMIO BAR, reads BLC_PWM_CTL2 (0x1E1250, +0x100 for pipe B) and BLC_PWM_CTL (0x1E1254), follows the pipe the firmware enabled and falls back to controller 0; the period comes from the firmware (6000 = 19.2 MHz / (200 Hz × 16) when it reads zero). The 10% steps clamp at 5..100% and the level is not persisted across a cold boot. io.c maps F6/F7 (the ChromeOS EC action row) and E0 14/E0 15 (standard brightness scancodes) to backlight_step() and consumes them. The backlight [0-100|up|down|probe] kernel command and SYS_BACKLIGHT (op 0 get, 1 set, 2 step) are the other interfaces. struct wm_status carries the level and a change counter (backlight_seq()); the ring-3 WM shows a centered 3 s bubble with a sun icon, the percentage and a bar after each change, and redraws it on every pass while visible so a window cannot cover it. The keytest kernel command drains the raw scancode tap in io.c (E0/make/break/decoded) for key mapping.
  • Text console: fbtext.c, font_8x8.c/h, io.c/h, screen.c/h — 8×8 font, framebuffer glyph blitting (fbtext_draw_cells) and the fallback cell screen (screen.c, used by io.c when no tty owns the output). The early bootcon.c draws 8×16 text (the same Terminus face as the terminal) directly into the LFB, top-left, with no heap/paging/shadow dependency; a full screen scrolls the console pixels up one 16-pixel cell instead of wrapping back to the top. The ring-3 terminal renders its own rows into its canvas; the kernel window manager has no text-cell content path. screen_damage_* remains for the fallback screen's own bookkeeping. fbtext and panic stay 8×8; userland proportional text uses ufont (below).
  • Wall clock: rtc.c/h reads and writes the CMOS RTC. Reads honour the register-B BCD/binary and 12/24-hour modes, retry around the update cycle, and expand the two-digit year with a 1970-2069 window (70-99 -> 1900s, 00-69 -> 2000s), so a dead-battery default such as 1980 or 1990 reads correctly. Writes use the RTC's SET bit, preserve its mode bits and validate leap years and 1970-2069; on ACPI machines the FADT century byte (exposed by acpi_rtc_century_reg()) is written too, so other software sees the right century. SYS_RTC_GET/SYS_RTC_SET (104/105) expose the full struct sys_datetime; SYS_RTC_HMS/SYS_RTC_DATETIME (56/69) stay the small read-only views. The WM top-bar date/time is a click target that spawns /ramfs/bin/settime, whose "Sync NTP" button fetches UTC through SYS_NTP_SYNC and writes it with SYS_RTC_SET; the date command prints the classic date line and a small +FORMAT subset.
  • Fonts: ufont.c/h, ufont_ttf.c, ufont_draw.c, ufont_file.c — a fixed-point (26.6, no FPU) TrueType parser and antialiased rasterizer for ring-3 text. The byte/Latin-1 path remains the default; cmap format 4 and format 12 are supported, and the new UTF-8 ngui_text_utf8*/ ngui_menu_item_utf8 APIs fall back per codepoint to the monochrome fonts/emoji.ttf subset (ngui_font_attach loads it lazily). The existing faces are the Arimo regular/bold/italic/bold-italic and Liberation Mono subsets plus Noto Emoji in fonts/, packed into /ramfs/fonts. The emoji subset is limited to common single-codepoint glyphs that fit the rasterizer (256 points / 16 contours); ZWJ sequences, flags, color glyphs and shaping are not supported. ufont owns one 512 KB malloc arena for face data and glyph masks; the built-in faces plus up to 11 @font-face faces share it. ngui_font_attach/detach (ngui) and usurf_font_attach (uwm_lib) load faces and leave the 8×16 bitmap fallback when they are absent. The browser calls ngui_font_detach before heap_reset() and reattaches after heap_start(), because its page heap is reset on every navigation. Terminal and editor cells deliberately keep the 8×16 bitmap grid; ngui text fields use the proportional face with measured caret, selection and horizontal scrolling. Host test: make test-font (ufont_test.c); make fonts regenerates the subsets. No hinting, CFF/variable fonts, shaping, bidi or full Unicode yet.
  • Shell: ucmd_term.c is the windowed shell (rows, scrollback, Tab, builtins cd, path, help, clear). terminal.c keeps the privileged kernel command registry and term_kcmd_spawn() used through SYS_SPAWN_KCMD; commands are files on the terminal PATH (/ramfs/bin by default), so a packed command can shadow a kernel one. The in-kernel terminal entry point (term_entry(), term_run()) is gone.
  • Fatal exception screen: panic.c/h, timer.S — on a ring-0 fault, dumps vector/error code, GPRs, CRs, EIP instruction bytes and stack return-address candidates straight into the LFB (and COM1) before halting; see the panic section below.
  • Filesystem: fat.c (FAT12/16/32 read/write, device-parameterized), vfs.c (mounts every FAT device under /), fatdetect.c/fatformat.c, blkdev.c (floppy + IDE + SATA + eMMC + USB registry), ata.c (ATA PIO, either the legacy ports or the PCI IDE interface's native BARs — ata_init_ports(); multi-sector PIO waits for DRQ before every sector, since drives drop it between sectors, polls the command-block status rather than the alt-status BAR, and falls back to single-sector commands when a bridge leaves DRQ pending after a multi-sector transfer), disk.c (FDC + ISA DMA ch2, retries). vfs.c exposes an fs_ops vtable (FAT and the ramfs implement it) so the file service and the shell never touch fat_* directly; vfs_resolve() normalizes the path relative to the mount (drops . components, collapses and trims slashes) so directory paths from Tab completion ("/ramfs/bin/") work. sys_fs.c is the file service for ring-3 commands: whole-file read/write, index-based directory listing, mount listing, unlink/mkdir/rmdir (writes to the ramfs return a read-only error). A file operation enters a non-preemptible section (preempt_disable, with interrupts on for the floppy's IRQ 6) because the FAT driver has static state; vfs_scan_busy and format_busy make it sleep first when a mount scan or a destructive format owns the disks. A format releases the BKL for its raw-sector loop, so the WM and terminals keep running; sys_fs_begin() applies the format_busy wait only to disk-backed mounts, so /ramfs and /share stay usable during a format. Expect a brief stall (not ticks — the PIT keeps running) while a command reads or writes a disk. Directory listings cache the first 64 entries of the last FAT directory (fat_cache in vfs.c), so the WebDAV server's index 0..N-1 sequence is one directory walk instead of N; any write/mkdir/rmdir/unlink invalidates it. A rescan (vfs_mount_all() from the boot bootscan thread or the storage command via sys_fs_scan()) re-adds /ramfs and /share first; their operations (and SYS_SPAWN of a RAM path, sys_fs_enter_path()) do not wait for vfs_scan_busy (vfs_mount_is_ram()), only disk paths do. The scan runs preemptible; the floppy/ATA/AHCI/SDHCI wait loops (including the SDHCI command, clock/reset and CMD1 power-up polls) call vfs_scan_poll(t0) / vfs_scan_relax(ms), which sleep (dropping the BKL) only for the scan's owning process, with interrupts on and preemption enabled, and only once a wait passes 2 ms; at boot in the idle context and in normal I/O they are no-ops. A USB disk read by the rescan claims the USB bus (usb_bus_claim() in usbmsc_read/write/flush), so its HCD waits yield as well (see the USB bullet). So storage no longer freezes the WM. disk_probe() skips a floppy whose CMOS drive type (register 0x10) is 0.
  • Installer: install.c/h — the privileged install <target> [source|self] command clones the live NebOS image or writes the running image. A clone detects a source by the MBR plus the LBA-63 boot-sector signature (NEBOS OEM string, kernel_lba 64, pack_lba 1088), computes the used length from the end of P1..P3 (P4 is the data volume and is never cloned), allocates a page buffer for the whole image and reads the source into RAM first (LBA 1..62 are synthesized as zeros instead of read). It prepares/keeps P4, writes the target from RAM in chunks with the source no longer active, merges the target's P4 entry into the source MBR, writes the MBR last, flushes and verifies by checksum before remounting the target. A source-read failure therefore leaves the target untouched. The source read keeps the BKL (a USB3 stick must stay active across chunks); the target writes release it per chunk so the WM/terminal stay responsive. It reuses format_busy. The source can be usb0 (USB mass storage), IDE, SATA or eMMC; the target is any non-floppy block device with enough sectors. install <target> self writes the retained gzip boot image and the kernel bundled at /ramfs/install/kernel.bin to P1/P2, patches the boot sector's exact kernel_sectors, keeps an existing P4 and creates/formats it when absent. It refuses a raw runtime pack (cmds-dev/net-cmds/ kernel-dev); use net-install for that. target=auto picks the only non-USB NebOS disk.
  • Storage manager / mount policies: ucmd_disks.c (disks, the top-bar Disks launcher and the Disks button in the files toolbar) is the ngui view of storage; the storage command stays the text view. It lists the present block devices (empty IDE/eMMC slots are hidden), reads sector 0 and each partition's first sector with SYS_BLK_READ (119, one 512-byte sector, under sys_fs_enter, copied through a kernel buffer) to show the MBR, NebOS boot partition, rootfs, FAT type and label, and lists every mount with its source volume (struct sys_mount now carries dev and key). Floppies are never read raw. SYS_MOUNT_CTL (120) sets/gets a struct sys_mount_policy keyed by the volume's default mount name (ide0p1, or the device name for a whole-device volume): a mount name, SYS_MOUNT_RO and SYS_MOUNT_NOAUTO. vfs.c keeps up to 16 policies in RAM; mount_one() applies them on every scan (a policy name loses to a name already in use) and a set remounts that device at once. Writes, unlink, mkdir and rmdir on a mount with ro set return SYS_EROFS before the backend (sys_fs_begin_w). The app saves the table as MOUNTS.CFG ("NBMNT1\n\0" + records) on the NEBOSDATA volume; the bootscan thread calls sys_mount_load_config() after vfs_mount_all() and applies /data/MOUNTS.CFG. The data volume itself is not editable from the app (it stores the file). Format and install run the kernel commands with -y (which skips their raw-keyboard y/n prompt; the app confirms in its own dialog) through SYS_SPAWN_KCMD on a private tty and show the output; success is read from the done line.
  • /share: share.c/h — writable, page-backed in-memory filesystem for network uploads (the netbooted board may have no writable disk). Entries are full relative paths (like the pack ramfs) plus explicit directory entries, so empty directories work; names are plain strings (up to 63 bytes), file data comes from mm_alloc_pages() and is freed on replace/delete. Limits: 64 entries and 16 MB, volatile across reboot/kexec. Mounted at /share by vfs_mount_all(), so it appears in ls / and the files GUI. SYS_FS_STAT exposes size/dir/read-only, and sys_dirent carries a display name (64 bytes) plus raw_83 so FAT's space-padded fields and the name-string filesystems share one ABI.
  • /data: the installed disk's partition 4 is a writable FAT volume with the label NEBOSDATA, created by install/install self at LBA 34816 (after P1 kernel, P2 rootfs pack and P3 ESP) and filling the rest of the disk. vfs.c mounts the first volume with that label as /data (not as <dev>p4); the mount table records its source device so remount/unmount works. Files are 8.3 only until FAT LFN write support exists. A reinstall replaces P1..P3 and keeps P4; net-install never touches it. The data volume is not available on the live USB unless that stick was installed.
  • SATA/AHCI: ahci.c/h — polled AHCI driver (first controller only, PCI class 01:06:01, no IRQs, no NCQ): port bring-up with COMRESET, IDENTIFY (shared ata_identify_parse() with ata.c) and READ/WRITE DMA EXT through a page-allocated bounce buffer (nothing large in BSS). Disks are registered as sata0..sataN (named by AHCI port index) and mount like IDE disks (sata0p1 for an MBR partition). >2 TB disks are clamped to 32-bit LBA; a disk added after boot needs a rescan (no COMRESET hotplug).
  • eMMC/SDHCI: sdhci.c/h — polled SDHCI driver for the Intel Braswell MMC function at PCI 00:10.0 (8086:2294, class 0805, the HP Chromebook eMMC). sdhci_init() resets the host, selects the 1.8 V rail from the capabilities and enables Host Control 2's 1.8 V signalling, runs a 400 kHz init clock, then CMD0/1/2/3/7/16 and CMD8 to read the 512-byte EXT_CSD (SEC_COUNT at 212, CACHE_SIZE at 249), and switches to a 25 MHz data clock. Sector I/O is CMD17/CMD24 over the polled PIO buffer port (one 512-byte block per command; no DMA, IRQ, CMD6 bus-width/high-speed switch or hotplug). The read/write loops call sched_yield() every 32 sectors so a long format does not starve the WM/terminal (a normal file read has preemption disabled, so the yield is a no-op there). blkdev.c registers it as mmc0, so storage, the VFS MBR+ FAT mount path and format mmc0 work exactly like an IDE/SATA disk; sdhci_flush() issues the CMD6 FLUSH_CACHE when the card reports a write-back cache. A stock eMMC holds the ChromeOS image, so formatting it is destructive.
  • Serial: serial.c, serial_ring_buf.c/h, serial_loop.c — 16550 UART with an IRQ-driven ring buffer and the serial test loopback check.
  • Network: netdev.c/h — NIC driver registry (struct netdev, first probe wins; drivers: e1000e.c Intel e1000/PCH LAN (82540EM emulated, 82577LM/82578/82579; polled, PCI INTx disabled before MMIO, PCH D0 and no BAR sizing so the ME/AMT cannot leave the BAR undecoded; skips the global MAC reset while the link is up, because the PCH/ME wedges on the CTRL_RST access; the PCIe GIO-master-disable handshake is skipped on the conventional-PCI 82540EM, whose STATUS bit 19 never clears in QEMU and used to cost the full 1 s timeout at every boot; extended RX descriptors only when RFCTL.EXTEN reads back set; the 82540EM (0x100E) is pinned to the legacy write-back layout, because it has no RFCTL but QEMU stores the register, so EXTEN reads back set while the device still writes legacy descriptors), r8168.c RTL8111/8168 family, including the RTL8111E on the Gigabyte 970A-DS3P (PCIe, polled, C+ mode, 64-entry RX ring), ne2000.c RTL8029 (QEMU/ISA), asix.c AX88772 USB Ethernet (bulk over the USB core, so an EHCI/xHCI dongle is usable) and rndis.c USB RNDIS tethering (Android phones and QEMU usb-net; device-level config scan, RNDIS INIT/QUERY/packet-filter, 44-byte packet header and an Ethernet netdev). netdev [name] is a kernel command that shows the active driver or switches it (netdev rndis, netdev asix, netdev e1000e, ...); it calls the selected driver's probe and leaves the current driver untouched on failure. Every receive/send goes through netdev_rx_frame()/ netdev_tx_frame(), which keep the 32-bit frame byte counters behind SYS_NET_INFO.rx_bytes/tx_bytes (the process monitor's network graph). The top-bar status area opens ucmd_netmenu.c, the control panel. It lists every present driver through SYS_NET_DEVLIST (111), selects one through SYS_NET_SELECT (112) and runs DHCP; the same popover lists scanned WiFi networks, marks the ones in /data/WIFI.CFG as saved, joins them with the stored passphrase, and has a Saved view that forgets individual networks. The panel is an ngui popover: a battery/AC and clock summary, a brightness slider (when a panel PWM exists), and a Quick settings grid of ngui_tiles for Network, the P-state power mode (SYS_CPUFREQ) and Date & Time. Clicking a tile expands that section in place: the network devices/Wi-Fi/connection area (built with ngui_section and ngui_list_row), three power-mode rows, or an inline date/time editor (fields, Set, Now, Sync NTP — no separate settime window). It opens as a WIN_F_POPOVER canvas window, not as a titled window. Hidden SSIDs are omitted, and BSSIDs that share an SSID/security collapse to the strongest entry (the active BSSID wins while connected). wifi.c (the Intel 7265D/3165 netdev, see the WiFi bullet) is last in the table; struct netdev has an optional link_up() hook (e1000e STATUS.LU, r8168 PHYstatus, ASIX probe-time BMSR, WiFi association state), the boot DHCP is skipped while it returns 0, and a physically linked wired NIC keeps wifi autoconnect from overriding it. net.c — ARP + ICMP echo, IPv4/UDP send + parse helpers, shared ARP resolution (net_arp_resolve) and routing (net_next_hop), frame decode, net_checksum()/net_checksum_tcp(). ARP entries expire after five minutes and their age slides on every hit, so a gateway or DNS entry is not lost during a long page load. dhcp.c — minimal DHCP client (DISCOVER → OFFER → REQUEST → ACK; runs at boot when a NIC is present, 4 s budget, keeps the static address when no server answers; dhcp re-runs it; learns the DNS server from option 6). netcmd.c — the netinfo/netrecv/netsend/netip/dhcp/pong/ping/netregs commands. dns.c/h — a minimal resolver (one recursive A query over UDP, name-compression aware, one query in flight plus a five-minute A-record cache for parallel stack callers; netdns shows/sets the server, host <name> resolves). ntp.c/h — a minimal SNTP client (RFC 4330): one 48-byte request to UDP port 123, three one-second tries, origin-timestamp validation and the reply's transmit timestamp converted from the 1900 epoch to UTC. SYS_NTP_SYNC exposes it to the Date & Time app; the default server is pool.ntp.org, the service takes the raw NIC receiver for the duration and is refused with SYS_NTP_EBUSY while another raw command or a TCP client is active. tcp.c/h — a minimal TCP client table (connect/send/recv/close, one connection per process, in-order receive with a per-connection receive queue (64 KB from the frame allocator when it can find a contiguous run, 32/16 KB fallbacks) so data arriving during a send is never lost, one segment of retransmit; net_pump() dispatches frames to every client). tcp_client_close() sends FIN and frees the slot at once (all sends are synchronous, so nothing is unacknowledged); the peer's late FIN matches no client and is dropped. curl — the ring-3 command: http:// or https:// GET with DNS, ARP, a dumped status/headers/body, chunked decoding (redirects are followed, up to 5 hops); TLS 1.3 via tls.c/h + tls_sha256.c, tls_chacha20.c, tls_x25519.c, tls_rng.c: TLS_CHACHA20_POLY1305_SHA256 + X25519, stream-oriented record layer, leaf SHA-256 fingerprint printed for a manual check. The same ClientHello also offers TLS 1.2 (RFC 5246) for servers without 1.3 (arstechnica.com's load balancer): ECDHE over X25519 or P-256 (tls_p256.c, Montgomery 8x32-bit limbs, ECDH only) with ChaCha20-Poly1305 (0xCCA8/0xCCA9) or AES-128-GCM (0xC02F/0xC02B; tls_gcm.c, 4-bit GHASH tables on wpa_crypto.c's AES), the extended master secret when echoed, an empty client Certificate on request and the P_SHA256 PRF (tls12_prf() in tls_sha256.c). The ServerHello's supported_versions picks the state machine; the TLS 1.3 middlebox CCS is sent before the client Finished, not after the ClientHello (a 1.2 server rejects it there). The 1.3 key share is X25519 only (no HelloRetryRequest), and the ServerKeyExchange signature is not checked. Certificates are not verified (phase A: encryption without authentication; a MITM is undetected) and the DRBG (tls_rng.c: RDTSC jitter + ticks + MAC) is deliberately weak. The crypto files are pure freestanding C and have host vectors (make test-crypto, tls_test.c); the TLS code lives in the command pack, so make net-cmds updates it without a kernel reload. Static IP default 192.168.178.240, mask/gateway learned from DHCP (off-subnet traffic goes via the router).
  • WiFi (Intel 7265D/3165, the HP Chromebook): iwl_trans.c/h — PCIe transport after Linux iwlwifi (7000 family): PCI scan for 8086:095a/095b/3165/3166, D0, BAR0 mapped with ioremap, APM init, one legacy RX queue (256 x 4 KB RBDs), gen1 128-byte TFD queues with dword byte-count tables, firmware TLV parse and section DMA through the FH service channel (128 KB bounce, LMPM_CHICK for the extended range), polled CSR_INT. Everything is page-allocated; the NIC is kept awake (MAC access request held) and INTx is disabled. Host commands use the wide header (legacy ids go out as group 1, like Linux's DEF_ID). iwl_mvm.c/h — firmware commands for the 7265D-29 API: INIT image (BT config, NVM HW section -> MAC at word 0x15, TX antennas, PHY config, CALIB_RES_NOTIF_PHY_DB collection until INIT_COMPLETE), runtime image (PHY-DB replay, PHY config, BT config, DQA enable, aux station 1 on queue 1, PHY context 0, CAM power, MCC ZZ, MAC context 0), LMAC scan (SCAN_OFFLOAD_REQUEST, wildcard active, 37 channels), connect (PHY context, binding + quota, SCD_QUEUE_CFG queue 4, AP station 0, time event), ADD_STA_KEY v1, TX_CMD v6 (fixed legacy rates: 1M CCK / 6M mgmt, 12M OFDM data), legacy RX_PHY/RX_MPDU parsing. wifi.c/h — 802.11 station: beacon/probe parsing (SSID, DS channel, TIM DTIM, RSN with PSK + CCMP pairwise/group), open-system auth and a non-QoS association request (no WMM/HT IEs), Ethernet <-> 802.11 data + LLC/SNAP + host-built CCMP header/PN, an EAPOL queue (ethertype 0x888e never reaches net_pump()), the wifi netdev and SYS_WIFI (110, multiplexed op). RX CCMP is decrypted in software (ccmp.c, AES-CCM, RFC 3610 vector in the host test) when the firmware reports SEC_ENC_ERR, because this 7265D-29 firmware does not use correctly installed ADD_STA_KEY keys for RX even though TX (which embeds the TK in TX_CMD) works; there is no software replay window yet. The firmware is loaded on first use (wifi or the boot autoconnect helper), not during kernel init. netdev_shutdown() always calls wifi_shutdown() before a kexec (the RX ring would keep writing into reused pages). The ring-3 side is ucmd_wifi.c (wifi, wifi up|scan|connect <ssid> [pass]|disconnect, wifi connectfile <path> for the control panel's staged SSID/pass/BSSID record, wifi saved to list the saved networks, wifi autoconnect for the boot helper and wifi forget [ssid]), wpa.c/h (4-way + group handshake, key descriptor v2) and wpa_crypto.c/h (SHA-1, HMAC, PBKDF2, PRF, AES-128, RFC 3394 unwrap; host test make test-wpa). After the handshake wifi connect installs the TK/GTK, calls SYS_WIFI_AUTHORIZE (data port open + netdev_select ("wifi")), runs DHCP and leaves wifi __keep running for group rekeys. A successful menu/CLI connect stores the SSID and passphrase through wifi_store.c/h in /data/WIFI.CFG (8.3, plaintext), a most-recently-used list of up to WIFI_CFG_MAX (16) fixed records behind a list header; the old one-record file is still read. Re-connecting a known SSID replaces its record and moves it to the front, and a full list drops the least recently used network. Each record leaves the BSSID zero so a mesh/repeater AP with the same SSID still works. After the storage scan and the boot DHCP attempt the bootscan thread spawns /ramfs/bin/wifi autoconnect when that file exists. Autoconnect leaves a wired link that is physically up alone, and an already-linked WiFi card too. Otherwise it scans once and joins the strongest network present whose SSID is in the saved list, moves on to the other saved networks found if one fails, and rescans after three seconds for a second pass. /data is the persistent FAT volume from the installer. wifi forget without an SSID removes the whole list, wifi forget <ssid> one record; the network menu marks saved SSIDs and its Saved view forgets them individually. A FAT read may write a final partial sector past the requested length, so the credential reader keeps 512 bytes of slack on the stack. The helper's PTK and EAPOL replay counter are kept in the kernel (SYS_WIFI_SET_PTK/SYS_WIFI_GET_PTK) and fetched by connection ID, so the 64-byte SYS_SPAWN argument limit cannot truncate the rekey state. There is no QEMU model: test on the Chromebook over make net-dev with the RNDIS phone/ASIX dongle as the management link and make netmon for the iwl:/wifi: trail.
  • WiFi (Intel 6200/6300, the ThinkPad X201): the same transport and wifi.c drive the 6000 family through iwl_dvm.c/h (Linux iwldvm, iwlwifi-6000-4.ucode, API 4). wifi_fw.c/h (formerly iwl_fw.c) dispatches every firmware call to iwl_mvm.c, iwl_dvm.c or the Realtek USB driver rtl8821au.c; the backend is picked when the radio comes up (a plugged-in RTL8821AU wins, otherwise the PCI family, iwl_is_dvm()) and stays fixed until wififw_down(). iwl_trans.c keeps per-family parameters in struct iwl_family (fam_7000/fam_6000): the 6000 family has 20 scheduler queues, the command queue on 4 (FIFO 7), 4-byte command headers, a byte-count table in bytes, the SCD chain-extension workaround, no shadow registers and the pre-TLV v2 .ucode (inst/data sections loaded at 0x0/0x800000). The DVM AC queues 0..3 (VO/VI/BE/BK, FIFOs 3/2/1/0) are programmed by the transport (iwl_txq_enable_fifo()), not by a firmware command. PCI IDs: 8086:4239/422c = 6200 (6000i, antennas B+C, 2x2 IPA radio SKU bit in CSR_GP_DRIVER_REG), 4238/422b = 6300 (6000, antennas from the EEPROM). iwl_dvm.c: the host reads the 2 KB OTP through CSR_EEPROM_REG (MAC at word 0x15, radio config at 0x48, crystal calibration at 0x128 behind the calibration link 0x67), nic_config() runs from the transport between APM init and ring setup; INIT image (ALIVE, AC queues, WiMAX coex off, crystal calibration, CALIBRATION_CFG_CMD, CALIBRATION_RES_NOTIFICATIONs stored by op code until CALIBRATION_COMPLETE), runtime image (stored results replayed as REPLY_PHY_CALIBRATION_CMD, DC calibration, TX antennas, RXON, TX power, CAM POWER_TABLE_CMD). A full RXON commit clears the association first, which wipes the firmware station table, so the broadcast station 15 and the AP station 0 are re-added with fixed-rate LINK_QUALITY tables after every unassociated RXON, and every retune is followed by REPLY_TX_POWER_DBM_CMD (15 dBm). Association is REPLY_RXON_TIMING, REPLY_QOS_PARAM, then RXON with RXON_FILTER_ASSOC. Scans are one REPLY_SCAN_CMD per band (2.4 GHz, then 5 GHz, kicked from the poll path because a synchronous command must not run inside the RX handler) over the channels the EEPROM regulatory tables mark valid (bands at 0x08, 0x42, 0x5c, 0x74 behind link 0x66); probes only where a channel is ACTIVE and not RADAR. On the X201's 6300 the earlier fixed 5 GHz list made the firmware SYSASSERT. Any firmware assert (CSR_INT SW_ERR) now drops wifi.c to DOWN (iwl_fatal()), so the next scan/connect reloads the firmware instead of timing out forever. Keys are REPLY_ADD_STA in modify mode on the AP station. RX is the same RX_PHY + RX_MPDU pair as the 7265D (RSSI from the AGC/in-band fields, IWLAGN_RSSI_OFFSET 44), so the software CCMP fallback covers both.
  • Hot-reload (kexec): kexec.c/h, kexec_tramp.S, entry.S, and the host-side kexec_send.c — reload the kernel over serial without rebooting (C-light: reuses the current framebuffer, re-runs kernel_main). The transfer entry is kernel_entry (entry.S), which re-points ESP before any stack use: the jumping kernel's trampoline stack address comes from the old build's memory map, so a reload between different maps (e.g. after the kernel region grew) would otherwise land the stack inside the new image. netkexec.c/h + host-side netkexec_send.c do the same over UDP (make net-dev BOARD_IP=…): the WM loop auto-detects the header, the board acks every datagram with the next expected offset, verifies the checksum and jumps. While idle the same loop answers ARP/ICMP for our IP, so the board is reachable (and MAC-resolvable) without running any command. The receive loop keeps answering ARP/ICMP for the receiving NIC as well, because a multi-megabyte upload outlives the host's neighbour entry: unanswered probes make the host drop datagrams while sendto() still succeeds. The host tool stops after 10 s without the offset advancing and reports an ACK_BADSUM as a failure instead of as completion. kexec_jump() calls smp_stop_aps() first: every AP gets an INIT and is parked in the wait-for-SIPI state before the trampoline overwrites the kernel they were executing. It runs with interrupts off, resets sched_lock (an AP may have been inside a scheduler critical section when INIT arrived) and then jumps; the new kernel starts the APs again from scratch.
  • WiFi (Realtek RTL8821AU/8811AU USB, e.g. TP-Link Archer T2U Nano 2357:011f): rtl8821au.c/h ports the Linux rtw88 8821A/USB bring-up (rtw88xxa_power_on(), __rtw_download_firmware_legacy(), rtw_parse_tbl_phy_cond(), rtw88xxa_set_channel()) behind the same entry points as iwl_mvm.c, so wifi.c, wifi, the netmenu and autoconnect work unchanged. The USB device probe (registered before RNDIS; USB_MAX_DEVICE_PROBES is 6) matches the Linux rtw88_8821au ID list, takes the bulk-IN and up to four bulk-OUT endpoints and sets the configuration; nothing is powered on until the first wifi command. Registers are vendor control requests (bRequest 5, wValue = address); the 8051 firmware goes to 0x1000 in 196-byte requests per 4 KB page. Bring-up: card-enable power sequence, 512-byte eFuse (MAC at logical 0x107, crystal cap, BB swing, RFE external LNA/PA flags, TX power base indices), power off, then the full power-on: LLT (256 pages, boundary 248), firmware + FW_READY 0xC6, MAC table, page reservation, EDCA/ beacon/USB burst setup, BB/AGC/RF-A tables, 2.4 GHz band switch, RCR, MAC address. The register tables and power sequences (~11 KB) are read from /ramfs/firmware/rtl8821a.tbl (layout rtl8821a_tbl.h, built by mkrtwtbl.c), so the kernel only carries the code (~12 KB). Every TX queue maps to one DMA queue/bulk-OUT endpoint (LOW with 3-4 OUT endpoints, NORMAL with 2), because the xHCI driver keeps one bulk-OUT ring and reconfigures it on every endpoint switch; a TX transfer that would be a multiple of 512 bytes gets the 8-byte PKT_OFFSET shift instead of a zero-length packet. RX aggregation is off; one 8 KB-aligned 8 KB buffer, up to 64 transfers drained per poll, RSSI from the PHY status. The chip's crypto engine is unused: wifi.c decrypts CCMP RX in software (status 0) and the driver encrypts CCMP TX with ccmp_tx_encrypt(). Fixed rates (1/6 Mb/s management, 12 Mb/s data, fallback off, hardware sequence numbers). The scan is a software channel hop driven by rtl8821au_poll() (2.4 GHz 1-13 and 36-48 active with a wildcard probe, 70 ms; DFS/UNII-3 passive, 120 ms). SYS_WIFI runs with interrupts off (syscall_stub.S), so get_ticks_ms() is frozen inside a call: every bring-up delay is a busy wait; only the dwell uses the tick. USB errors, a disconnected port or a re-enumeration set fatal, and wifi.c reloads on the next use. Tested by QEMU usb-host passthrough on xHCI (C-cut chip, firmware 42.4): 2.4 + 5 GHz scan, WPA2-PSK connect and DHCP through the control panel.
  • Mouse cursors: the set is GNOME's Adwaita theme (adwaita-cursors 51, LGPL-3 or CC-BY-SA-3.0). assets/cursors/adwaita/ holds its Xcursor files trimmed to the 24 px images (tools/xcursor_trim.py; the X11 alias symlinks and X_cursor are not copied); tools/mkcursors.c converts them into one NBCUR1 bundle (include/cursor_abi.h: header, per-shape w/h/hotspot/frames/delay/offset, premultiplied ARGB8888 frames), packed as cursors/adwaita24.cur in the full pack only (~146 KB, ~18 KB gzip; the floppy lite pack had ~2 KB of room left, so a floppy boot keeps the built-in 16x16 arrow of cursor_shape.h). CURSOR_LIST (an X-macro in cursor_abi.h) is the shape id order, the bundle order and the CSS name table: 35 CSS cursor names (move maps to Adwaita's all-resize, since its move is a symlink to the arrow). wait/progress keep every fourth of Adwaita's 60 x 16 ms frames (15 x 64 ms). cursor.c/h copies the bundle out of the ramfs into its own pages after ramfs_init() and in ramfs_replace() (which frees the old pack), calls mouse_cursor_reload() and only then frees the previous copy. wm.c resolves the shape in every SYS_WM_POLL: the WM override (SYS_WM_SET_CURSOR), else the cursor of the window holding the pointer capture, else the content cursor (SYS_WIN_SET_CURSOR, struct window.cursor) of the window under the pointer (not on a normal window's resize band), else CURSOR_DEFAULT; a WM restart clears the override. The ring-3 WM overrides with resize arrows on the resize band and while resizing, the move cross during a title-bar drag (once it moved), and a hand over launchers and the status area. ngui resets ui->cursor to the arrow for every redrawn frame (begin returned 1), ngui_text_input asks for the I-beam (not-allowed when disabled), apps use ngui_cursor_rect()/ngui_set_cursor(), and ngui_end_ex() sends it when it changed. The terminal sets the I-beam once; the browser parses the inherited CSS cursor (the keyword after the last comma; br_style.cursor is shape + 1, 0 = auto) and for auto uses a hand over links, the I-beam over text fields and progress while loading; the gallery's Cursors section shows every shape; browser-host maps the shapes to SDL system cursors.
  • UI icons: ngui's icons are GNOME Adwaita symbolic icons (adwaita-icon-theme 51, LGPL-3 or CC-BY-SA-3.0). assets/icons/adwaita/ holds the unchanged *-symbolic.svg files; ICON_LIST (an X-macro in include/icon_abi.h: enum suffix, short name, theme file) is the icon id order and the bundle order, so append only, and it generates enum ngui_icon (NGUI_ICON_FOLDER .. NGUI_ICON_NET_USB, NGUI_ICON_COUNT) and ngui_icon_name(). The same list generates enum uwm_icon in uwm_lib.h, so the ring-3 WM (which does not link ngui) uses the same ids for the bar's network and battery icons. tools/mkicons.c rasterizes each SVG with the browser's svg_raster.c into a 16x16 8-bit coverage mask and writes one NBICO1 bundle (16-byte header + masks, 24 icons, ~6.2 KB, ~1.3 KB gzip) packed as icons/adwaita16.icn in both packs. Its XML reader handles only what symbolic icons use (<svg viewBox>, <g>, <path>, <rect>, <circle>, <ellipse>, fill/fill-rule/opacity) and fails the build on transforms, strokes, style or unknown elements. ngui_icon() reads the bundle once per process into a BSS buffer (not the libc heap, so the browser's heap_reset() cannot free it; the read is capped at the ids this build knows, so a newer bundle with appended icons still works) and blends the mask tinted with the caller's colour, centred in the rectangle and clipped. usurf_icon() in uwm_lib.c does the same over the WM's bpp-aware shadow (returning 0 when the bundle is absent); the bar's battery clears the striped battery mask's interior to a dim shade of the state colour and draws its level fill over the lower part. There is no line-drawn fallback: without the bundle an icon is left blank (the old procedural drawings cost ~2 KB of code per app and the floppy has a few hundred bytes to spare). browser-host symlinks the repository's icons/ into its /ramfs like fonts/.
  • Mouse: mouse.c/h — cursor move/draw shared by the PS/2 path (IntelliMouse including the 4th-byte wheel, Cirrus/Radeon/Intel hardware cursor) and the USB backend. cur_x/cur_y are the hotspot; the image is drawn with its top-left at hotspot minus the image hotspot, so it can be partly off the top/left edge. The software cursor saves up to 32x32 pixels (CURSOR_MAX_DIM) and blends the premultiplied ARGB over them (decoding RGB565 or BGR from the saved background); a shape change presents the union of the old and new rectangles at once. Intel Ironlake and Radeon copy the image into their 64x64 ARGB planes (Intel's CURPOS takes sign-magnitude negatives; the Intel cursor gamma enable follows the matching primary plane's DSPxCNTR gamma enable, because the display palette sits after the plane blender and forcing cursor gamma on in a VBE mode whose primary bypasses it sends only the cursor through the palette and gives its antialiased edges a bright halo; Radeon clamps the position at 0 and skips the hidden part with HORZ_VERT_OFF and a CUR_OFFSET shifted by 256 bytes per row, like Linux's legacy path); Cirrus thresholds alpha at 50% into its AND/XOR planes (white/black by luminance) and clamps the position at 0. An image upload never runs from IRQ12, which only moves. Animated shapes advance from mouse_poll_update(). Scroll from every backend accumulates in mouse_scroll_y and mouse_scroll_take() hands it to the WM in pixels; one PS/2 wheel notch is 48 px. usbhid.c/h — USB HID boot devices: find
    • configure a mouse and/or keyboard, arm their interrupt endpoints, decode mouse reports and inject keyboard scancodes, watch for plug/unplug (boot protocol has no wheel field, so the USB wheel output stays 0 for now).
  • I2C touchpad: i2c.c/h — polled Synopsys DesignWare APB I2C master for the Braswell LPSS blocks (fast mode, component-type probe, explicit LPSS reset-release so the FIFO drains); touchpad.c/h — Elan HID-over-I2C touchpad on LPSS I2C6 at 0xD1327000, slave 0x15. touchpad_init() runs from mouse_init() at boot, only when cpu_family_model() is Airmont 0x64C (elsewhere the fixed-address LPSS scan would reset-cycle 32 MMIO windows that belong to nobody, ~64 ms, or to another device); it maps the I2C window before processes clone the page directory), resets the device, consumes the 2-byte acknowledgement, reads the HID descriptor, selects absolute mode (0x0300 = 1), wakes it (0x0800) and then queries the native max-X/Y commands (0x0106/0x0107). The report line is a GPIO with no driver, so touchpad_poll() reads the input register every 25 ms (back-to-back reads stall the device), parses the Elan 0x5D vendor report (finger bitmask plus five bytes per packed finger) and feeds the device-independent touchpad_gesture.c/h engine. The engine owns pointer scaling, taps, the physical-button latch and two-finger scrolling, so another touchpad backend only has to decode its own reports into up to two contacts. A short stationary tap synthesizes a button press: two fingers -> right click, one finger in the bottom-right zone (x >= 75%, y <= 25%) -> right click, one finger elsewhere -> left click. The device's raw Y axis grows upwards, so the bottom is the low end. A physical clickpad press is also latched at its leading edge: in the bottom-right zone it becomes the right button, elsewhere the left button, and the latch holds for the whole press. Two fingers that move their centroid by more than ~30 device units scroll; the pointer freezes while two or more fingers are down and re-anchors when one remains. Natural scrolling (two fingers up = later content) is the default. touchpad prints the probe/status and takes rightclick off|tap|corner|both, tapclick on|off and scroll on|off|natural|traditional; mouseinfo lists the Elan VID/PID.
  • USB: usb.c/h — controller-agnostic core: device enumeration, descriptor parsing, hub recursion, bus scans, per-controller addresses, the hotplug watcher and the interrupt-IN consumers (mouse + keyboard). It keeps a global controller table, so EHCI (high-speed) and its UHCI/OHCI companions (low/full-speed) are driven together; EHCI is scanned first so its port resets hand non-high-speed devices back to the companions. usb_hcd.h is the host-controller ops vtable; uhci.c (I/O-port UHCI, frame list at 0x3000, one instance), ohci.c (MMIO OHCI, up to 4 instances, HCCA + ED/TD lists, polling), ehci.c (MMIO EHCI, QH/qTD asynchronous schedule, up to 4 instances) and xhci.c (MMIO xHCI, USB2 and USB3 root ports; halt/HCH reset sequence and BIOS/OS handoff) implement it. lsusb.c — the lsusb command (lists every controller and its tree). A scan (usb_scan/usb_hotplug_poll) and every usbmsc command claim the controllers for the calling process (usb_bus_claim()/ usb_bus_release(), nesting). Every HCD delay, and the ASIX/RNDIS/ usbmsc probe delays, go through usb_delay_ms(), and every HCD completion/port-reset poll loop calls usb_poll_relax(t0) outside its spinlock. When the claim belongs to a sleepable scan — lsusb, the kworker's HID rescan/hotplug enumeration, or the storage rescan's vfs_mount_all() reading a USB disk — the delay sleeps and the poll yields once a wait passes 2 ms, both dropping the BKL; elsewhere (pid 0 at boot, preemption off, interrupts-off syscalls, normal file I/O, the installer) they busy-wait as before. The poll yields rather than sleeping 1 ms because a sleep on an idle CPU wakes on the 100 Hz idle tick, which made each slow transfer cost ~10 ms. So lsusb no longer freezes the WM (in QEMU the longest BKL hold dropped from ~105 ms in xHCI port_reset to under the 50 ms sampling threshold; on hardware the ASIX probe alone used to spin ~450 ms). While another context owns the bus, usb_scan_foreign() makes the usb.c wrappers refuse access (control/bulk transfers fail, interrupt polls return 0, usb_port_connected reports 1), usb_hotplug_poll skips its pass and usbhid_poll skips its tick; USB NICs, the RTL8821AU and USB disks see a transient error. usbmsc.c/h — USB mass-storage class driver (BOT/SCSI) exposed as usb0..; its device probe is registered next to ASIX and blk_scan() registers the devices in the block registry. The devices work on every controller type and can be plugged in at any time (root-port connect-change watcher); lsusb re-enumerates the bus, after which usbhid re-inits itself via a scan generation counter.
  • Power/idle: idle.c — idle auto (the default) asks power.c for the MWAIT hint. Nehalem/Westmere use C6 (0x20); Airmont/Braswell uses C6N (0x58) when CPUID.5:EDX advertises the C6 substates and the MWAIT interrupt-break extension is present; older Bonnell Atoms and APs without ARAT keep HLT because of the old USB-legacy SMM hang (the UHCI/OHCI 0xC0 legacy-SMI disable addresses it). idle hlt|c1e|c3|c6 (and the c3ap/c6ap AP-only variants) are explicit overrides for testing. Arrandale hints are C1 0x00, C1E 0x01, C3 0x10, C6 0x20; the Airmont auto path uses the Cherry Trail C6N hint. The BSP PIT and each AP's LAPIC timer run at 1 kHz while a process runs and drop to 100 Hz/10 ms while the CPU is idle (timer_set_hz, lapic_timer_set_ms); the PIT stub advances the global millisecond clock by timer_tick_advance(), and smp_resched_wake() shortens the idle period when new work arrives.
  • P-state/frequency power: power.c/h — two platform paths, gated on the model allowlist so the MSRs are not touched elsewhere. Nehalem/Westmere (0x1A/1E/1F/25/2C/2E/2F) enable SpeedStep (MISC_ENABLE bit 16) and C1E (POWER_CTL bit 1), raise the package C-state limit in PKG_CST_CONFIG_CONTROL to C6 only when it is unlocked (bit 15), read min/max ratios from PLATFORM_INFO, and start at the maximum non-turbo ratio. Their target ratio goes in bits 15:8 of IA32_PERF_CTL with the low byte zero (a preserved VID byte made the request silently ineffective); IA32_PERF_STATUS reports the current ratio in bits 7:0 (the X201 boot dump shows 0x12 at the 18x max non-turbo ratio). Airmont/Braswell (family 6 model 0x4C) reads MSR_ATOM_CORE_RATIOS 0x66A (min/max pstate), MSR_ATOM_CORE_VIDS 0x66B (VID range), MSR_ATOM_CORE_TURBO_RATIOS/VIDS 0x66C/0x66D, MSR_FSB_FREQ 0xCD (the Airmont BCLK table) and MSR_PLATFORM_INFO as a fallback. The N3060 reports pstates 6..20, BCLK 80 MHz (1600 MHz nominal), turbo pstate 31 (2480 MHz) and VID 0x2D..0x3C. It writes IA32_PERF_CTL as pstate in 15:8 and the Linux-interpolated VID in 7:0; the governor starts at max non-turbo (pstate 20) and drops to min (pstate 6, 480 MHz). Turbo is detected but deliberately not requested, so cpufreq max means max non-turbo. No C1E/package-CST/auto-demotion MSR writes (coreboot configures them) and no package-energy MSR reads; APERF/MPERF are used only when CPUID.06H:ECX[0] says they exist. C3/C6 residency is not read on Airmont. The per-CPU tick runs a race-to-idle governor: 100 ms windows pick min/max/linear target pstates (short busy streaks jump to max immediately) and each CPU writes its own IA32_PERF_CTL. The power command prints the platform, effective MHz (APERF/MPERF), current/requested pstate, and on Nehalem the C3/C6 and package residency; the Airmont line adds the FSB, nominal MHz, turbo pstate/VID, VID range and the live PERF_CTL. cpufreq [auto|min|max|off|<pstate>] overrides the governor on both; SYS_CPUFREQ exposes the same mode set/get to the control panel.
  • CPU temperature: thermal.c/h — Intel DTS through IA32_THERM_STATUS (MSR 0x19C). Each CPU samples itself once a second from its scheduler tick (struct cpu.temp_c), and SYS_CPU_TEMP (sys_info.c) exposes the hottest core plus TjMax to ring 3. The model allowlist follows coretemp (Core/Core 2, Nehalem/Westmere including the X201's Arrandale 0x25, Bonnell, and Airmont/Braswell model 0x4C) and is what keeps rdmsr away from CPUs that lack the MSR. Nehalem/Westmere read TjMax from IA32_TEMPERATURE_TARGET (MSR 0x1A2, bits 23:16; the X201's i5 M 520 reports 105 °C); Airmont uses the coretemp 90 °C table instead of reading 0x1A2 (a missing MSR before the IDT is installed would triple-fault); Bonnell has no such MSR, so its TjMax stays table-driven (Atom 330 = 125 °C, 230 = 100, other Bonnell = 90, otherwise 100). The 330's 125 °C is Linux coretemp's empirical value; Intel only specifies TJ = 90 °C and Tcase-max = 85.2 °C, so sensors prints the raw delta and the 90/100/125 °C scales as well as the top bar's bare 43C before the clock and, on ThinkPads and the HP Chromebook, the AC/battery icon at the far right (a plug while on AC, a level-filled battery on battery, with a percentage tooltip below it on hover) and cpuinfo's value plus EIST state. AMD family 15h models below 0x60 (Bulldozer/Piledriver, the FX-6350) read Tctl from D18F3xA4 at PCI 0:18.3: raw = val >> 21, raw * 125 m°C, minus 49 °C when bits 17:16 are both set, TjMax 70 °C. The probe runs on the BSP before the timer; the 1 Hz sample runs from the kworker's thermal_housekeeping() under the BKL (never from the per-CPU timer interrupt, where a PCI config access could race another CPU) and is published to every CPU. No AMD MSR is touched, so there is no early #GP risk. A platform with neither Intel DTS nor AMD D18F3xA4 hides the temperature.
  • Board sensors: it87.c/h — read-only probe of the IT87xx Super I/O (the AT3IONT-I and the 970A-DS3P's IT8728F expose temperatures and fan tachometers), used by SYS_SENSORS and the ring-3 sensors command to cross-check the DTS and show whether the fans turn. Nothing is written to the fan control. tpec.c/h adds the ThinkPad embedded controller of the X201 (SYS_TPEC_SENSORS for temperatures/fan, SYS_POWER_INFO for AC/battery): a _SM_ SMBIOS type 1 check gates the probe to Lenovo/IBM machines, then EC reads through ports 0x62/0x66 return the temperatures at EC 0x78..0x7F / 0xC0..0xC7 (0x80 = absent, 0x00 = unimplemented; revision 3+ at EC 0xEF only uses the first block), the fan tachometer at 0x84 (LSB, always read first) / 0x85 and the 0x2F fan mode. The power path reads 0x38/0x39 (bit 7 present, bit 6 discharging, bit 5 charging) and 0x46 bit 4 (AC online), then selects the 0x81 battery information page (high nibble battery, low nibble page: 0 dynamic, 1 mode, 2 design, 5 manufacturer, 6 model) and reads the 16-byte window at 0xA0..0xAF. A pending EC output byte (a hotkey event, since there is no SCI handler) is drained before every command, and every wait is bounded; the only EC write is the 0x81 page selector, restored when it changed. sensors labels the EC registers and decodes the fan mode (auto / full speed / level); the ring-3 powerinfo command prints AC/battery details and the WM top bar shows the AC adapter state plus the first present battery with a valid percentage. Machines without the EC show neither. ec.c/h is the shared ACPI EC protocol (ports 0x62/0x66, command 0x80 read / 0x81 write, OBF/IBF waits, stale-byte drain, bounded polls); both tpec.c and cros_ec.c use it. cros_ec.c/h probes the Chrome OS EC: ACPI memory version 2, the 'E','C' memmap id, the device feature bits, and skips the probe when the ThinkPad EC is present. The ACPI window 0x20..0xFF mirrors memmap 0x00..0xDF: temperature sensors 0x00..0x0f and 0x18..0x1f (raw - 73 °C), fans 0x10..0x17 (0xffff = absent), switches 0x30 (lid/power button), and the battery block 0x40..0x7f (AC/present/ charging/discharging flags at 0x4c, voltage 0x40, rate 0x44, remaining 0x48, design 0x50, design voltage 0x54, last full 0x58, cycle count 0x5c, and the 8-byte manufacturer/model/serial/type strings at 0x60..0x7f). EC_ACPI_MEM_BATTERY_INDEX 0x12 selects the battery and waits for BATT_INDEX 0x4e; EC_ACPI_MEM_STRINGS_FIFO 0x16 supplies longer strings when supported. The Cyan full-charge workaround is applied and the units are mAh/mA. SYS_CROS_EC_SENSORS (107) exposes temperatures, fans, fan duty and switches; SYS_POWER_INFO reports source SYS_POWER_SRC_CROS. power_src.c tries the ThinkPad backend first, then the Chrome EC, so the WM top bar and the powerinfo/sensors commands work on both.
  • Ring-3 address space: the ELF image and 128 KB (32-page) stack live in the 4 MB USER_BASE (0x40000000)..USER_STACK_TOP (0x40400000) window, which is too small for a full-frame image. Their frames, and the heap's, come from highmem when the machine has RAM above 1 GB. The 4 MB slot at 0x4FC00000, just below USER_WIN_BASE, is the kernel's kmap window (supervisor-only). SYS_MEM_ALLOC/SYS_MEM_GROW/SYS_MEM_FREE (sys_mem.c/h) map/grow/delete a single anonymous arena at USER_HEAP_BASE (0x60000000), capped at 64 MB (USER_HEAP_MAX; the browser's DOM arenas plus the QuickJS heap need ~30 MB before images); the initial allocation is zeroed but pages appended by SYS_MEM_GROW are not (decoders initialize what they use), which keeps large image arenas fast to map. The reaper frees it with the rest of the process and top counts its pages. Ring-3 commands use user/lib/libc/malloc.c (malloc/free/heap_reset), which owns this arena; the SYS_MEM_* calls are the libc backend (user/lib/libc/ucmd_mem.c) and are not called by application code. The canvas mapping at USER_GFX_BASE (0x50000000) and the WM mappings are separate.
  • Ring-3 libc: user/lib/libc/include/ (stddef/stdint/stdarg/stdlib/string/ctype/ assert/ucmd_heap, setjmp/errno/stdio/math/time/sys/time/sys/types, float/ limits/inttypes/alloca), user/lib/libc/malloc.c, user/lib/libc/string.c, user/lib/libc/strdup.c, user/lib/libc/stdlib.c, user/lib/libc/ucmd_mem.c, user/lib/libc/setjmp.S, user/lib/libc/errno.c, user/lib/libc/div64.c, user/lib/libc/dtoa.c, user/lib/libc/stdio.c, user/lib/libc/stdio_file.c, user/lib/libc/math.c, user/lib/libc/time.c, linked as libc.a only into commands that reference it. malloc is a boundary-tag first-fit allocator with immediate coalescing: 16-byte aligned, calloc zeroes, realloc grows in place when the next block is free, and the heap maps 64 KB lazily then grows in page-rounded steps with 64 KB slack up to the 64 MB arena cap. heap_reset() (ucmd_heap.h) discards every allocation and unmaps the arena for page-scoped apps such as the browser. There are no threads, so there is no lock; application code uses this heap, and the libc backend is the only caller of SYS_MEM_*. stdio provides integer/string/float printf/snprintf/sprintf formatting and a read-only whole-file FILE (fopen("rb"), fread, fseek, ftell, fclose; stdout/stderr are console streams; stdin is EOF). time uses SYS_RTC_GET/SYS_RTC_SET with UTC-only gmtime/localtime and 64-bit time_t; math is the x87 double set used by QuickJS (plus the C99 additions hypot, cbrt, log2, log1p, expm1, the hyperbolic functions and lrint, and memchr/malloc_usable_size). The archive plus -ffunction-sections/--gc-sections keeps unused code out of the legacy pack. Host tests: make test-libc (malloc, format/dtoa, math, div64, setjmp).
  • Ring-3 commands: ucmd_*.c, ucmd_lib.h, ucmd.ld, mkpack.c, rootfs.h, mkrootfs.c, ramfs.c/h — static ELFs linked at USER_BASE (0x40000000), packed by mkpack into cmds.pack (as bin/<name>), gzipped to cmds_pack_gz.bin and wrapped by mkrootfs with a NBROOT1 header. The pack is the system rootfs: the boot path loads it into RAM (legacy high-memory protected-mode copy / UEFI / kexec staging) and ramfs_init takes a private page-allocated copy, mounted read-only at /ramfs. The shell finds them through PATH (/ramfs/bin by default), loads the whole 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 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 the owning window. Each process inherits the spawning terminal's working directory (struct process.cwd, exposed as SYS_GETCWD), and the file syscalls resolve relative paths against it, so commands keep working after cd (the shell passes arguments verbatim). The one argument is passed as a C string on the top of the user stack (process_create_user(..., arg)), so _start(const char *arg) needs no crt0. ngui.c/h is the shared userland GUI toolkit linked into ucmd_files.c, ucmd_mines.c, ucmd_solitaire.c, ucmd_process.c and the external gallery.elf (buttons, menu items, text fields with a disabled state, icons, layout cuts and scroll panes); files opens the selected text file through /ramfs/bin/edit, image files through /ramfs/bin/view, and .htm/.html files through /ramfs/bin/browser. ngui_end_ex() is the variant that runs the bookkeeping without publishing the canvas, for apps that poll input without redrawing.
  • Gallery: gallery.c is the ngui widget gallery: typography and truncation, the drawing primitives and clip stack, the theme palette, every icon in ICON_LIST, live buttons/icon buttons, text fields (including a disabled, read-only field) with event feedback, a nested draggable scroll pane and the ngui_cut_* layout helpers. The real 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.
  • Process monitor: ucmd_process.c — the graphical task manager (process or the top bar's Tasks button), the ngui counterpart of top. It samples once per second and keeps 60 s 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.
  • 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 piles, stock/waste, drag-and-drop (or click a card and then its destination), double-click to send a card home, auto-flip, standard scoring, a score/time status bar and the bouncing-card win animation. The cards use pip layouts with mirrored corner indices, notched corners and pixel-art J/Q/K portraits; the back is the castle. The bar's "Cards" button launches /ramfs/bin/solitaire.
  • Browser: the real browser ships in the full pack as bin/browser.app (not in the floppy lite pack: floppy boots load BROWSER from root.img) (it links ngui, the full image library, inflate, TLS, uhttp and the vendored QuickJS engine in third_party/quickjs/, but the rootfs is no longer constrained by the kernel's low-memory window). 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. 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 and TLS; curl, the browser and chat use it. browser_html.c/h is a tolerant HTML tree + the CSS subset: external <link rel=stylesheet> sheets (in document order, inline <style> last), one selector engine shared by the cascade, querySelector(All) and matches (type/class/id, attribute presence and = ~= |= ^= $= *= values with the i flag, descendant/>/+/~ combinators with backtracking, :root, :link, the first/last/only child and of-type classes, :nth-child/:nth-last-child/:nth-of-type/ :nth-last-of-type (an+b, odd, even), :empty, :checked, :disabled/:enabled, :required/:optional, :not/:is/:where with selector lists, and :has with relative combinators; user-state pseudo-classes such as :hover never match and their rules are dropped at parse time), ::before/::after generated text (content strings, attr(), quotes; cascaded as an anonymous inline box per element by br_pseudo() and emitted as literal runs, so scripts never see it; an empty content: "" box with a size and a background -- an icon -- is one RUN_PBOX run that fills the background colour and draws a data: background image at its background-size/-position, clipped to the box and rotated by transform; a flex row reserves its first/ last column for such boxes (margin-left: auto pushes one to the right edge), intrinsic_width() counts them, and an empty <button> whose icon is such a box is laid out as an element), data: URLs (percent-encoded or base64; data_url_decode()) for background images, <img> sources and those icon boxes, colours/rgba(), legacy bgcolor attributes, solid backgrounds and background-image with repeat/position/size (auto keeps the legacy stretch, cover and contain scale the image), plus the background shorthand URL, font size (px/%/em/rem, resolved against the parent for em/%), the font shorthand, numeric weights, !important, line-height, alignment, margins, padding, per-side borders, list-style: none, text-transform: uppercase, display, explicit/percentage block width/height with min/max and box-sizing: border-box, margin: 0 auto, calc(percent ± px) in widths, margins/padding, heights and min/max, overflow: hidden box clipping, white-space: nowrap, position: relative/absolute/fixed/sticky, right/bottom, z-index, transform: translate/scale/rotate with transform-origin (paint-time box and inline-image transforms), flex rows with justify-content (including space-evenly)/align-items, two-column grids and repeat(N, 1fr)/repeat(N, minmax(0,1fr)) equal-column grids (Tailwind grid-cols-N; grid_auto = BR_GRID_FIXED + N), aspect-ratio as the preferred height of an auto-height box (aspect-video/ aspect-square frames), table colspan and percentage columns, and basic float: left/right columns. Inline and inline-block <svg> icons are line runs like <img> (RUN_SVG), and an inline-block holding only inline text with no box of its own stays in the text line instead of starting a row of boxes. An absolutely positioned or block <img> applies max-width/min-width against its containing block and keeps the attribute aspect ratio unless CSS sets a height. A sticky box with a z-index (a site header) is painted in the deferred stacked pass, above the content after it. Rules are indexed by their unescaped class (.md\:flex under md:flex), and class/style attributes keep up to 2 KB (BR_CLASS_MAX): Tailwind class lists are 300-600 bytes, and the old 120-byte cap silently dropped every responsive variant past it. A stylesheet whose helper fetch fails is retried once synchronously ([css] retry on the log) instead of leaving the page unstyled. @media blocks (min-width/max-width and the (width >= 997px) range form) are evaluated against the browser canvas width when the page is parsed, and window.matchMedia() gives scripts the same answers (br_media_matches()). @layer blocks are parsed and cascade in layer order (br_rule.layer, ranked by first appearance including @layer a, b; statements): precedence is a band per layer above raw specificity (cascade_rank()), unlayered rules above every layer, the style attribute above all, and !important reverses the layer order. Docusaurus/Infima ships its whole sheet in layers. @supports blocks apply unless negated or asking for selector(); @import/@keyframes are skipped. After var() expansion every calc() in a declaration block is folded (css_fold_calc(): *, /, nested parentheses, %, px, rem/em at the root size, vw, unitless) into a plain length or the calc(P% + Npx) form the property parsers read; var() substitution keeps token boundaries, so minified font:var(--w)var(--size) cannot glue into one token. A rule that uses or defines a custom property some non-root rule also defines (BR_VAR_SCOPED) keeps its raw block and is re-expanded per element in br_style_for() against the definitions of the element's own matched rules (css_env_build(); Infima's .col--3 sets --ifm-col-width, .col[class*=col--] uses it). The flex shorthand and flex-basis map a definite basis onto the item width, and flex items are clamped by min-width/max-width (a capped growing item leaves its space to the others). @font-face loads one regular TTF per family from a local path or HTTP URL (the browser fetches remote faces before layout). The compatibility ladder is testdata/browser/compat/ (make compat-serve); pages 010–070 and 030a pass (036a needs the POST echo server). Closed <details> are skipped and <video> gets a placeholder box. Inline <svg> is rendered by svg_raster.c/h (freestanding, host test make test-svg): every path command including curves and elliptical arcs, rect/circle/ellipse/line/polyline/ polygon, <g>/<a>/nested <svg>/<use> of a <symbol>, transform lists, viewBox + preserveAspectRatio, nonzero/even-odd fill, strokes, opacity/fill-opacity, currentColor, and a gradient url(#id) painted as the average of its stops. Coverage is antialiased (4 vertical subsamples, exact horizontal spans) into an RGB565 + alpha layer that is cached per node and size (SVG_CACHE_PIXELS, page heap, dropped before heap_reset()) and blitted on repaint; <text> is drawn on top each frame. SVG paint is its own inherited style state (fill_mode/fill/ stroke_mode/stroke/stroke_w, BR_PAINT_*): CSS fill/stroke on an HTML element no longer paint its background or border, and getComputedStyle exposes fill/stroke. line-height in rem is an absolute length, and an inline-flex box with only inline content stays in the text line. Up to BR_MAX_DEFERRED (256) absolute/fixed boxes are painted after the flow; past that a box is painted in place against its containing block. The default page canvas follows ngui_theme_dark (dark page, light text, theme.panel for <pre>), but the html/body background fills the whole page canvas, so a site's white page has no dark side gutters; other background-color/color CSS still overrides the theme. browser.c opens at 1100x700 (960x640 and 780x540 fallbacks on smaller screens), the layout/render, URL bar, history, status bar and inline <img> decoding. A dotted input without a scheme that is not a known local file extension (cloudron.io) is treated as a hostname and skips the local-file stat; it is tried as https:// first (skipping the usual http -> https redirect connection) and retried once over http:// when the https connection is refused, reset, times out or fails the TLS handshake (the history entry is replaced, not duplicated). uhttp drops a connection it redirects away from without a TLS close_notify, and keeps it for a same-origin redirect with a small length-delimited body. Origin-level redirects are remembered per process and in /share/borigins, so later visits to a bare domain go straight to its canonical scheme/host. Remote stylesheets are cached under /share/bcss-* for the current boot, so a reload or a fresh browser launch does not fetch the same CSS sheets again. Visit history and URL-bar autocomplete: every page that finishes loading (not about:, URLs under 512 bytes) is recorded in a 128-entry BSS table (hist_tab: URL, title, visit count, stamp; the page heap is reset per navigation, so it cannot live there). The stamp is a counter carried in the file (max + 1 per visit), so it orders visits across windows and reboots without a wall clock; a full table evicts the lowest stamp. The boot's windows share /share/bhist, rewritten on every visit after merging the current file in (max visits, newest title), and persist_tick() copies it to /data/BHIST.DAT (8.3, plaintext NBHIST1\n then <visits> <stamp> <url>\t<title>\n); startup reads /share first, else /data. While the address bar has the focus a dropdown lists up to six entries: an empty bar shows the top sites, typing ranks prefixes of the URL (also without scheme or www.) over URL and then title substrings, plus visits and recency. Typing at the end also completes inline to the next / of the best prefix match, selected, and Enter on that text opens the URL it came from (scheme included). Up/Down preview a row in the bar, Delete forgets the highlighted row, Esc closes the list (and drops the completion), a click opens a row. The in-session back/forward stack (history[], 16 entries) is separate. Images are prefetched up to four at a time and only when their measured position is within the viewport plus 160 px; deferred images are loaded as the page scrolls. Network work runs in up to FETCH_WORKERS (four) headless curl __serve helper processes (ucmd_curl.c), each with its own /share/bf<session>_<slot>* files (session comes from the browser pid, so two browser windows cannot collide). The browser starts jobs, harvests completed ones from its main loop and decodes them, so text and scrolling stay responsive while several TCP/TLS connections are in flight. Stylesheet and external-script bodies are downloaded in parallel but parsed/executed in document order; one above-fold image starts downloading before the script phase so it overlaps the script fetches and execution. Each helper keeps its own TCP/TLS connection (TLS stays per-process). Idle helpers stay warm across navigations, so a same-origin load reuses the TCP/TLS connection and a cross-origin job just drops the old one in uhttp_open; only busy helpers are killed when the page changes. The helpers' DNS/TLS log lines (and the browser's own [js] lines, since u_tty_create() rebinds its output) go to a private 4 KB tty that nobody renders; the browser drains and discards it from every poll loop (fetch_tty_drain), because a full tty ring blocks its writers, and tty_write drops rather than sleeps when the ring's owner writes to its own full ring. Helpers also exit after ten idle seconds, and the browser stops them at once when its window loses focus, so raw commands can acquire the NIC. A page fetch that fails with a DNS error is torn down and tried once more after half a second. The helper sends Accept-Encoding: gzip; the browser inflates with a progress hook that pumps the UI. While loading, the status bar reports the page fetch (headers and first-byte milliseconds); when the load is done it shows Loaded in N ms: page P (headers H), parse, css, paint, js for 12 s, the phase breakdown to read before optimizing a page. QuickJS is compiled -O1 (QJS_CFLAGS): faster than -Os and -O2 on the store's scripts and ~170 KB smaller than -O2. Page, CSS and image buffers come from the ring-3 libc heap; the DOM uses fixed static arenas (6144 nodes, 512 KB attributes, 4608 rules), and page bodies are capped at 2 MB with CSS sheets up to 832 KB (six sheets). Each image gets an img_estimate()-sized decode arena, freed as soon as the scaled bitmap exists. Decoding reuses one scratch arena per page (decode_arena_get; above 8 MB it is released after its image), because a per-image malloc/free fragmented the first-fit heap until a page of 200 icons ran out of memory. A background image is scaled to cover its laid-out box (an icon is decoded at 56 px, not 1000), and up to 256 bitmaps within a 4 M-pixel budget (BR_IMG_PIXEL_BUDGET; 1 MB files / 8 MP decodes) are kept until the page heap is reset. Background images load lazily like <img> (measure-pass block_top[] against the scroll position), an image job holds a fetch helper for at most BR_IMG_JOB_TIMEOUT_MS (30 s), in-flight nodes are marked -3 so rescans skip them, and a script that sets style/class/src later (Angular ng-style) re-arms a node the first scan had marked empty; DOM changes from scripts trigger a rescan. Rounded boxes paint their background image inside the corner arcs. Images with a CSS/attribute box decode at those bounds: img_options.max_w/h lets the JPEG decoder choose a 1/2, 1/4 or 1/8 scaled IDCT (Loeffler/IGJ 4x4/2x2/1x1) instead of decoding full size and then box-filtering to the 1000 px layout cap. For remote <img> the warm curl __serve helper does that decode (the request carries D <max_w> <max_h> and the bitmap arrives as /share/bf...px), so the UI thread only reads and copies it; local files and backgrounds still decode in-process. <img> uses its CSS/attribute width/height (or the parent layout box for max-width:100%), backgrounds use their box, so a 1200x800 photo painted at 400x267 decodes at roughly 600x400 and is scaled once. A per-image display-size bitmap (br_image.disp) is built lazily from the capped source and img_draw's 1:1 opaque-copy and integer-alpha paths make later paints memcpy. Image-driven repaints are coalesced to 100 ms; helper-decoded <img> jobs only copy their px file, while local and background jobs decode in a 40 ms batch per main-loop pass, so a page no longer does a full layout+paint per image; a background decode keeps the measured layout (only page_cache_valid is cleared) and a decode below the fold does not invalidate the screen. At batch end the status line and /share/IMGSTAT report wall, net (TLS), io, dec, scale, paint and reflow totals plus one line per image. Navigation calls heap_reset() and unmaps the whole arena, so a large image no longer reserves a fixed 24 MB. <script> blocks are collected by browser_html.c; inline bodies run directly and <script src> bodies are fetched through the same local/network path as pages and CSS (2 MB cap), in document order, through the vendored QuickJS engine (third_party/quickjs/, 2026-06-04, ES2025: classes, arrow functions, let/const, template literals, destructuring, spread, async/await, Promise, Map/Set, BigInt, optional chaining; linked only into browser.elf). js_mu.c/h keeps the MuJS-style value-stack API the DOM layer was written against (C functions see this at index 0, userdata has/put/delete hooks become QuickJS exotic-class methods with a backing object for expandos, js_try/js_typeerror longjmp to the innermost try or C-function boundary, js_ref registry keys), so js_browser.c/h is unchanged in structure. Outermost engine entries run on a private 1 MB stack from the page heap (mu_stack_call; the ring-3 stack is 128 KB and QuickJS recurses on the C stack per call), Promise jobs run after each script/timer/event (never while a script is still on the stack), and every C function has QuickJS's constructor bit so new Event(...)/new CustomEvent(...) work. js_browser.c/h is the DOM layer on top: one interned userdata wrapper per node, inheriting from Object.prototype (Angular calls node.toString()), (so === and library expando caches work) with getAttribute/setAttribute/hasAttribute, appendChild/ insertBefore/removeChild/replaceChild/cloneNode/remove, querySelector(All)/getElementsByTagName/getElementsByClassName, classList (including toggle's force argument), dataset, inline style (cssText, property get/set and getPropertyValue/ setProperty/removeProperty), innerHTML (fragment parser in browser_html.c), textContent/nodeValue, child/sibling/parent traversal, matches and getBoundingClientRect (real block/table/ absolute/image boxes; inline text boxes are still approximate). <a> elements expose the DOM URL components (href/protocol/host/hostname/port/ pathname/search/hash/origin) resolved against the page URL. document exposes createElement/createTextNode/createComment/ createDocumentFragment/createAttribute, documentElement/body/ head, readyState, currentScript (set by the browser before each classic script from br_script.node; null for modules) and the live scripts/images/forms/links/embeds collections; <template> is inert (BR_TAG_TEMPLATE, display none) and the prelude moves a parsed template's children into its content fragment before any page script runs (Alpine's x-for/x-if/x-teleport clone it); parentNode of a child of node 0 (the tree root is the <html> element itself when the page starts with one) is that element, not null (node_parent_idx), which jQuery/Sizzle need to remove their probe elements; navigator, history, matchMedia, getComputedStyle, setTimeout/setInterval/clearTimeout and requestAnimationFrame exist, and due timers run from js_browser_tick() in the browser loop. location carries the split protocol/host/hostname/port/pathname/search/hash/origin fields, so Angular-style URL code works. jQuery 1.11, Bootstrap 3.2 tooltips and AngularJS 1.3 with ngRoute/ngSanitize run the Cloudron app store (cloudron.io/store/: hero carousel, 26 sections, 308 cards from a 666 KB inline catalogue and an ES2015 controller). element.click() dispatches a bubbling, cancelable click before the default action. A state is created after heap_start(), shared by the page's scripts and freed before heap_reset(). js_setlimit() gives every script, timer and event a 20 s wall-clock budget (QuickJS's interrupt handler), so a runaway loop raises InternalError: interrupted instead of freezing the browser; errors are reported as Name: message plus the stack. Math, Date and JSON come from the engine plus the libc math/time layers. The parsed page is painted before scripts are fetched and run, and remote <script src> bodies are cached under /share/bjs-* for the current boot. Classic scripts run sloppy by default ("use strict" and private class fields work). <script type="module"> runs as an ES module (js_browser_run_module, js_ploadmodule): QuickJS's module loader resolves each specifier to an absolute URL (module name = URL, so every module is evaluated once) and loads it synchronously through host.load_script (the boot script cache, else one blocking helper fetch with input pumping off, since the loader runs inside JavaScript); import() and import.meta.url work, nomodule scripts are skipped, and the page's <link rel="modulepreload"> targets are downloaded on all helpers in parallel into the script cache before any script runs. The 20 s budget restarts after every blocking fetch, so it measures script time, not the network. Unhandled promise rejections are reported (JS_SetHostPromiseRejectionTracker), as Vite apps boot from an async IIFE. js_prelude.js (embedded by js_prelude.S, run once per state before the page's scripts) implements the Web APIs in JavaScript on three C primitives (__nb_http, __nb_storage, __nb_resolve): fetch/Request/Response/Headers, XMLHttpRequest, URL/ URLSearchParams, TextEncoder/TextDecoder, btoa/atob, Blob/ File/FormData (urlencoded only), AbortController, localStorage/sessionStorage (a Proxy, so localStorage.token = x works), crypto.getRandomValues/randomUUID/subtle.digest("SHA-256") (PKCE; queueMicrotask uses the engine's Promise captured at startup, because core-js swaps in a Promise polyfill that schedules through queueMicrotask, and PromiseRejectionEvent exists so it keeps the native one), inert MutationObserver/ResizeObserver, an IntersectionObserver that reports every observed target visible once (batched into one timer, capped at 400 per page; IntersectionObserverEntry exists so the common polyfill keeps it), Custom Elements (customElements.define/get/whenDefined/upgrade: HTMLElement as a base constructor returns the element being upgraded with its prototype switched to the subclass, as the polyfills do; upgrades run on createElement and from a scan after any DOM change (__nb_ce_scan, called from the tick when host.changed fired), connectedCallback runs once the element is connected, attributeChangedCallback only for the observed attributes present at upgrade), script-created <img> elements that fire load once they have a src (preload-then-swap code), DocumentType/Attr classes, document.dispatchEvent and window.dispatchEvent, instanceof-able DOM classes (HTMLElement, Node, ...), and Element methods (closest, append/prepend/before/after, replaceWith, insertAdjacentHTML, toggleAttribute, *AttributeNS) on the node wrappers' own prototype. A node wrapper resolves names through the C hook, then its own expandos (the backing object), then its real prototype chain with the wrapper as receiver (js_mu.c), so prototype getters/setters see the element and a Custom Element upgrade's prototype takes effect. innerHTML/outerHTML serialize the live tree (escaped text, raw script/style text, quoted attributes, no end tag for void elements; 2 MB cap). Attribute values in the getAttribute list are entity-decoded (&amp; &lt; &gt; &quot; &#39; &apos; and ASCII numeric references), and text set through innerHTML is decoded like the page parser's. isConnected is true when the top ancestor is a child of the document root. The timer table holds 1024 timers and a tick runs up to 32 due ones (heise's components each await setTimeout(0)). fetch()/XHR are synchronous inside a Promise: js_host_http submits X <method> <len> <ctype> <url> to a helper and returns the status and body whatever the HTTP status (2 MB response, 16 KB request body). Web Storage is stored in /share/bls<origin-hash> (local) and /share/bss<pid>-<origin-hash> (session, per window), outside the page heap that navigation resets. The helpers share one jar, /share/bcookies: h.jar is attached before every request (uhttp_init() after a POST clears it, which made the request after the OIDC login POST go out cookie-less: "authorization request has expired"), and a helper saves by re-reading the file and replaying only its own request's cookie additions/changes/deletions (jar_save() in ucmd_curl.c), so parallel helpers cannot clobber each other. When /data is mounted the browser also persists the helpers' cookie jar (/share/bcookies -> /data/BCOOKIES.BIN) and localStorage (every origin in one /data/BSTORE.DAT: NBLS1\n then <origin>\n<len>\n<json>\n records, 192 KB cap) across reboots: persist_restore() seeds /share from disk at start (a store missing from /share is looked up on disk on first use, and a cleared store is kept as {} so it cannot reappear), and persist_tick() in the main loop writes back what changed at most every 3 s (PERSIST_MS). The helpers only touch /share. Both files are plaintext bearer credentials, like CHAT.CFG; sessionStorage stays in RAM. Without /data the disk accesses just fail. console.* print Error stacks. location.assign/replace/reload navigate, except that a change of only the #fragment stays on the page: location.hash is a live accessor, href/hash/assign/replace and clicks on #... links update page_url, the address bar and history (host.set_hash), and a hashchange event fires on window from the next tick; back/forward between fragments of the same page do the same (hash-routed apps such as the Cloudron dashboard would otherwise reload on every menu click). Clicks on plain elements with listeners (div role="button") reach the innermost laid-out box under the pointer; a <button> with element content (an icon <svg>) is laid out like a normal element instead of a "Submit" control. An <img> reuses an already decoded bitmap with the same URL (br_image.url_hash), and .svg sources are no longer skipped. CSS gap/column-gap are parsed from the value (they used to be read from the block start and were ignored). <select> exposes options and multiple, and an <option> without value reports its text. offsetWidth/clientWidth of an element without a laid-out box report the viewport width (Vue apps measure on mount and picked a phone layout for 0), and window gets a resize event after the first layout of a scripted page and whenever the page width changes. The logged-in dashboard (sidebar with expandable groups, header, app grid, hash-routed views) was verified in QEMU against a local stand-in that proxies the public dashboard assets and mocks /api/v1 and the OIDC endpoints. The Cloudron dashboard (my.<domain>: a Vite/Vue 3 app, 12 modules / 3.5 MB) boots, builds its PKCE request, and its OIDC login form renders, submits through fetch() with the interaction cookie and shows the server's verdict; the authcallback.html code exchange runs the same way. cloneNode copies attributes to the clone (it used to stamp them onto the previous node, which broke every ng-repeat). addEventListener/removeEventListener/dispatchEvent dispatch real DOM events (capture/bubble, preventDefault, stopPropagation, Event and document.createEvent), and element .click() runs the default click action. Form controls render, focus, edit, toggle and select (text/password/textarea, checkbox/radio, buttons, select); GET submission builds a query from successful controls and POST sends the same encoded body through the fetch helper, native reset works, and the DOM value/checked/selectedIndex properties read/write the live control state. Forms expose elements/length/submit()/reset(); typing and checkbox/select changes fire input and change, and submit/reset fire their cancellable events. A control with author CSS (background, border or radius -- background:transparent;border:none counts, which is why background: transparent|none is a real cascaded value, PROP_BG_NONE) is painted with that background/border/radius and text colour and sized from its padding, height, min-width and margins (buttons border-box); unstyled controls keep the ngui theme look. Scripting is always on, so <noscript> is a raw-text, display:none element: google.com's noscript meta refresh plus table,div,span,p{display:none} used to hide the whole page. URLs (BR_URL_MAX, href/src attributes, the helper request/meta files, UHTTP_PATH_MAX) hold 4 KB: google.com's script URL is ~3.7 KB. Inline <style> text is collected up to 256 KB (BR_CSS_SIZE; google.com inlines ~94 KB). Media features with a known answer are evaluated (forced-colors: none, normal contrast, hover: hover, pointer: fine, prefers-reduced-motion: no-preference, display-mode: browser); unknown ones stay true. When the page starts with <html> (no whitespace after the doctype) that element is node 0: layout inherits from its cascade (root_style()), and selector combinators, style_for_node() and the preloader's node_hidden() treat node 0 as its children's parent (sel_parent()). An unquoted attribute value ending in / (<a href=/x/>) does not self-close the tag, and /> is ignored on non-void HTML elements outside SVG. <svg> is inline by default (an inline-block holding only an <svg> icon stays in the text line); an empty <button> has no label. font-weight 500 picks the regular face (CSS matching with only 400/700 faces), 600+ the bold one. Alpha without a leading zero (rgba(0,0,0,.05)) is parsed. A float's width is its content box (margins, and padding/border unless border-box, are added to the column). A fixed box's deferred background fill covers only its own columns, and a positioned box pushed past its containing block (left: 100%) keeps a one-line width instead of collapsing to 8 px. Percentage <img> heights resolve against the containing block's definite height. Flex/grid, basic tables, inline SVG and CSS variables are supported (see known issue 22 for the remaining CSS and DOM gaps). SYS_SPAWN loads FAT ELFs through kmalloc now (the old 16 KB fat_load_buf is gone) and wraps the load in sys_fs_enter/exit, since the floppy needs IRQ 6.
  • Chat client: ucmd_chat.c (chat [config-path], top-bar Chat button) is a native Cloudron Chat client on ngui: channel/DM sidebar with unread badges, presence dots and previews; a timeline with circular profile-picture avatars (initials until the picture loads, or when there is none), author grouping, UTC times, day headers, reply snippets, inline image attachments, link-preview cards (thumbnail, site, title and description, matching the web client; clicking one opens the link in the browser) and an attachments/thread/reaction line; a composer; browse/join and new-DM pickers. It talks to the Chat REST API (/api/me, /api/channels, /api/dms, /api/channels/public, /api/users, messages with ?limit=50, &before= and &after=, POST messages with a clientId, /read, /join, /api/dms) through one struct uhttp with a cookie jar. Message images and avatars are downloaded by a warm curl __serve helper (one worker, dispatched from chat_media_tick(); its DNS/TLS log lines go to a private tty), with the chat cookie jar written to /share/bchat.jar as the helper's optional jar-path argument. The main loop only submits a request file and polls a done marker, so the window no longer freezes for the download. Message images also carry D 480 320, so the helper decodes them and chat only copies the published bitmap; avatars still decode on the chat thread at 32x32 (img_options.max_w/h), which keeps the square source the circular mask expects while a large JPEG avatar gets a reduced IDCT instead of a full 512x512 decode. The in-tree image library (PNG/JPEG/GIF first frame/BMP/TGA/PNM/ICO/PAM) is the fallback for both. A link preview is a card under the message (Open Graph site name, bold title and description from the server's preview object) with an optional 120x72 thumbnail; a thumbnail that cannot be fetched or decoded (for example WebP/AVIF) is hidden and the text card stays. They live in a 16-entry, 6 MB message-image LRU plus a 64-entry avatar cache. The fetch is capped at 4 MB and the decoder at 4 MP / 12 MB of scratch. The helper is stopped when the window loses focus, so its TCP socket does not pause the net-dev watcher.

No WebSocket: the open conversation is polled every 2 s (5 s unfocused), the directory every 12 s (20 s), polling waits 1 s after input, and errors back off 2/5/10/30 s. An open TCP socket pauses the netkexec watcher (tcp_client_count()), so keep-alive is kept only while the window is focused and the user was active in the last 30 s. Up to 240 messages are held (Latin-1 bodies up to 4 KB via a UTF-8 mapping with ASCII stand-ins for common typography/emoji); the response buffer is 512 KB and the JSON pool 16384 nodes, all from the libc heap. chat_login.c/h is the native login: GET /auth/login (follows to the Cloudron OIDC /openid/interaction/<uid> page), the page's cloudron-config JSON submitUrl, POST {"username","password", "totpToken"} (401 / twoFactorRequired+totpRequired / passkey-only / redirectTo), then following redirectTo to /auth/callback (the consent interaction is a bare auto-submit form, so its <form action=.../confirm> is parsed and posted) and validating with /api/me. External SSO and passkey accounts use the pasted-cookie screen. The password is wiped after each attempt and never stored; the Chat host's cookie header and the server go to /data/CHAT.CFG when the persistent /data mount exists, otherwise /share/chat.cfg (or the given path), and are re-saved when the server rolls the cookie. A session left in the old /share/chat.cfg is copied to /data once. uhttp_cookie.c/h is the jar (48 host-only cookies, least-recently-set eviction, Path prefix match, Secure, Max-Age/1970-Expires deletion); uhttp stores every Set-Cookie (redirects too), sends matching cookies on each hop, splits requests/bodies into 1024-byte TLS records or MSS-sized TCP sends, takes accept/extra_headers, follows up to 8 redirects with 4 KB paths and 4.5 KB header lines, and treats 1xx/204/304 as bodyless. ujson.c/h is the arena JSON DOM parser (caller-owned node and string pools, \uXXXX/surrogates to UTF-8, depth 48). Host tests: make test-chat; tools/mock_chat.py mocks Chat + the OIDC provider on two ports and tools/qmp_chat_test.py (make test-chat-e2e) drives the app in QEMU.

  • Image library + viewer: img.h, img.c, img_mem.c, img_blit.c, img_png.c, img_bmp.c, img_gif.c, img_jpeg.c, img_tga.c, img_pnm.c, img_file.c/h — freestanding RGB565 decoders with an optional 8-bit alpha plane. The codecs are independent of the OS and ngui: they take an input buffer plus a caller-provided struct img_mem arena, so the browser and the chat client can link the same objects and decode HTTP bodies. inflate.c/h (DEFLATE, zlib, gzip, CRC32/Adler32) is shared with the boot pack. Its whole-buffer helpers (inflate_gzip_mem/_zlib_mem/_raw_mem, used by ramfs_init and the image decoders) are a separate fast path: 10-bit Huffman lookup tables in the caller's struct inflate workspace, the output buffer as the LZ77 history, and one checksum pass at the end (the 3.7 MB pack went from ~1.1 s to ~0.25 s in QEMU). The streaming API (inflate_gzip with a source/sink and progress hook) keeps the bit-at-a-time decoder. img_sniff() is a cheap header probe; img_decode() returns struct img_image; its struct img_options carries max_pixels and optional max_w/max_h output bounds. JPEG honours the bounds with a scaled IDCT (1/2 4x4, 1/4 2x2, 1/8 1x1, Loeffler/IGJ); other codecs ignore them and the caller scales with img_draw(). The 4x4/2x2 paths are validated by test_jpeg_scaled() against a box-filtered full decode. img_draw() is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha over a checkerboard or over the destination (for the browser and chat), with a straight row copy for a 1:1 opaque source and an integer 5/6/5 blend for a 1:1 alpha source. Progressive JPEG (successive approximation), EXIF orientation, ICO/CUR, PAM, SVG files in the browser (an SVG body is parsed into a detached subtree of the page and drawn by the inline-SVG renderer into an RGB565 + alpha bitmap: intrinsic size from width/height/viewBox, drawn at up to 4x for small icons (without a viewBox the user units are scaled to that raster), currentColor black, no <text>) and animated GIF frames are supported as well; arithmetic JPEG/CMYK are not. The viewer, ucmd_view.c, owns a canvas window and reads its file through SYS_READ_FILE; it uses fit/1:1/zoom/pan, shows format/dimensions/size, animates GIFs, and gives a clear error for unsupported variants. The chat client decodes fetched message images and avatars into a 480x320 / 32x32 cache (passing those bounds to img_options.max_w/h) and draws them with img_draw(). Host tests: make test-images (img_test.c, corpus in testdata/images/, generator tools/gen_img_tests.py).
  • Network service: sys_net.c/h — the NIC and the stack stay in the kernel; ring-3 commands get SYS_NET_INFO/config, the DNS, DHCP and NTP clients and the raw frame paths (NET_TX/RX/DECODE/REPLY/LOOPBACK/REGS/RESET), so the packet-level commands ported unchanged. Packet-level commands take the receiver exclusively through netdev_acquire; the background kexec watcher pauses while one owns it, and the reaper force-releases it if that process dies (sys_net_reap, driven by netdev_owner()/netdev_release_all()). TCP clients do NOT take that lease: tcp.c keeps a table of up to TCP_CLIENT_MAX (twelve) connections, one per process, each with its own receive queue (64 KB preferred, 32/16 KB fallback) and source port. TCP_CONNECT/PEER_MSS/SEND/RECV/CLOSE keep their ABI and look the connection up by calling pid; NET_NEXT_HOP/NET_ARP provide the route to the peer. Every stack syscall drains the NIC through net_pump() (netcore.c/h), which dispatches each frame to the client table, the WebDAV listener, a pending DNS query, the ARP cache and netkexec_capture_frame(), and answers ARP/ICMP. Stack waits use net_pump_burst(), repeated pump passes, because drivers return -1 both for an empty ring and after an overflow reset, and one pass would otherwise leave DNS/ARP/TCP waiting on a full ring. The pump runs under the BKL, so the shared receive scratch and protocol state stay serialized; waits yield with process_sleep_ms() and re-enable interrupts around driver TX timeouts (the syscall stub enters with them off). A raw acquire fails while any TCP socket is open, and SYS_TCP_CONNECT fails while a raw owner exists; DNS/ARP keep their direct-poll path when the caller is the raw owner. SYS_NET_ACQUIRE is still the gate for ping/netrecv/websrv; DHCP and NTP return busy while TCP clients are active. The background netkexec watcher and the netlog flush pause while a TCP socket or a stack DNS/ARP operation is active (net_stack_busy), so they cannot steal the replies or flood the small RX ring.

The server side is the WebDAV command: tcp.c has a small listener (one active connection + 3 backlog/closing slots, SYN-ACK/RST, and a fast FIN that keeps the tuple briefly so a late FIN/ACK is absorbed). The SYN-ACK advertises a zero window; a queued connection may hold 1 KB of early request (usually the HTTP headers), tcp_srv_accept() opens the window, and the update is repeated when the final ACK arrives, so parallel gvfs clients queue without RTO stalls. New SYNs/data are also handed to tcp_srv_input() from the active connection's tcp_recv/tcp_srv_send poll loops, not just between requests. SYS_TCP_LISTEN/ACCEPT/ SRV_RECV/SRV_SEND/SRV_CLOSE are called by /ramfs/bin/websrv, which serves HTTP/1.1 + WebDAV from the VFS (/ lists mounts, /ramfs is read-only, FAT mounts accept only names that round-trip to 8.3, /share is the writable target). While listening, SYS_TCP_ACCEPT also answers ARP/ICMP and captures a KXN2/KXNP header through netkexec_capture_frame(), so make net-dev/make net-cmds interrupts the server cleanly instead of waiting for header retries. The body is buffered whole (4 MB, or 1 MB when the heap alloc fails) from the per-process arena; the TCP receive path sends a window update whenever the application drains the queue (otherwise a full receive queue deadlocks until the peer's zero-window probe). No auth: it is a trusted-LAN service, and /share is writable by anyone who can reach it. Responses go out in up to four-segment bursts with a cumulative ACK (TCP_RETRY_MS 500 ms) rather than one segment per ACK, and PROPFIND XML is batched into 8 KB chunks instead of one chunk per entry. Keep-alive is deliberately not used: with one active connection an idle persistent connection would block the parallel connections Nautilus opens.

Shell commands

cd [path], ls [path], cat <path>, save <path> <text>, rm <path>, mkdir <path>, rmdir <path>, hello, 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), 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], 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).

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 switch it, e.g. netdev asix), pong (responds to ARP/ICMP for our IP for 30 s), ping <host|a.b.c.d> (active ARP + ICMP echo with RTT; resolves DNS names, goes via the gateway when the target is off-subnet), netloop (PHY loopback TX/RX self-test), netreset (full NIC re-init), netlog <text> (one UDP datagram to port 19290), netconsole on|off|host <a.b.c.d> (the debug-output mirror, see below) netregs (register dump, decoded ISR + counters), netdns [a.b.c.d] (show or set the resolver) and host <name> (one DNS A query). curl <url> fetches http:// or https:// host[:port]/path with a minimal HTTP GET and dumps the status line, headers and body (redirects are followed, up to 5 hops; numeric hosts skip DNS). https uses the phase-A TLS 1.3/1.2 client (no certificate verification; the leaf fingerprint is printed). On boot, if a NIC is present, a DHCP client runs with a 4 s budget (requesting the current address) and falls back to the static default when no server answers. The board also answers ARP/ICMP for its IP while idle. lspci lists every PCI function (one line each); with a filter (lspci 8168, lspci 02) it also prints BAR details, type and size for matching functions. peek <addr> [len] hex-dumps physical memory, MMIO registers too (through paging_debug_map(): highmem via kmap, MMIO via its ioremap mapping). poke <addr> <val> writes one 32-bit dword and prints the read-back (for driving MMIO experiments from the shell).

Each terminal has a current working directory (shown in the prompt as [dir] >), changed with cd; paths may be absolute (/floppy1/…) or relative (., .., nested). / is the read-only VFS root listing the mounted filesystems (the filesystem commands operate inside a mount, e.g. cat /floppy1/HELLO.TXT).

cpuinfo, ls, cat, save, rm, mkdir, rmdir, meminfo, top, process, spin, clock, colors, settime, date, files, disks, gallery, chat, view, sensors, powerinfo, mouseinfo, storage, netinfo, netip, netdns, host, dhcp, ping, pong, netsend, netrecv, netlog, netconsole, netregs, netloop, netreset, websrv, curl, wifi, netmenu, solitaire and hello are files in /ramfs/bin (packed by the Makefile), found through the shell's PATH; the rest are kernel commands spawned as processes, or builtins (cd, path, help, clear).

Serial hot-reload (kexec) workflow

Develop without reflashing the floppy. The serial link (COM1 ↔ /dev/ttyUSB0) runs at 115200 baud. The WM loop watches the serial ring buffer for the "KXE2" magic and auto-spawns the reload, so make dev alone boots a fresh kernel + rootfs. The manual kexec command is kept as a fallback that waits for the same image.

Wire protocol (host → target, sent immediately; no handshake): [magic "KXE2"][entry u32 LE][kernel_size u32 LE][pack_size u32 LE] [kernel][rootfs gzip][checksum u8]. pack_size == 0 tells the receiver to keep the running rootfs (kernel-only reload). A full reload stages both in one page-allocated buffer, copies only kernel_size bytes over 0x7E00, and publishes the pack range in boot info; the new kernel copies/inflates it and frees the staging tail. The rootfs-only runtime update (make cmds-dev) keeps the old framing [magic "KXNP"][entry u32][size u32][raw pack][checksum u8] and replaces /ramfs in place (see below). On SMP the APs are INIT-parked just before the jump, and the serial receive drops the BKL while it waits for bytes so the WM and the other CPU's syscalls stay responsive during a make dev.

Every iteration:

make dev            # kernel.bin + cmds_pack_gz.bin (atomic; ~46 s at 115200)
make kernel-dev     # kernel only; the new kernel keeps the running rootfs
make cmds-dev       # runtime raw-pack update, no reboot

The reload is automatic. On boot the kernel prints NebOS v<version> booted to COM1, so a serial monitor can confirm the new build headlessly:

make monitor       # tail the serial line (picocom; Ctrl-A Ctrl-X to exit)

Run it in a second terminal, then make dev in the first — each reload prints the ... booted line.

Notes: the kexec path rebuilds a flat GDT at 0x900 before jumping (the old GDT lives inside the overwritten kernel region), so it's safe to edit any file, including vesa_stage.S/boot.S layout — but the video mode itself is only re-applied on a full floppy/USB boot (C-light reuses the current LFB).

Command pack rootfs (cmds.pack / cmds.img / cmds-dev)

The commands live in cmds.pack (bin/<name> entries, built by mkpack), compressed with libdeflate-gzip -12 when it is installed (falling back to gzip -9) to cmds_pack_gz.bin and wrapped by mkrootfs with a one-sector NBROOT1 header (magic, version, exact pack_bytes, checksum, gzip flag). The build rejects a pack above the PACK_MAX cap (2 MB, CMDS_GZ_MAX in the Makefile, PACK_MAX in vesa_stage.S); libdeflate buys several KB over gzip -9 and is still preferred. The boot path loads the gz pack into RAM — the legacy stage copies it directly to 0x900000 with its protected-mode rep movsb, the UEFI loader into a loader-data buffer below 512 MB, kexec via its staging buffer — and ramfs_init() inflates it into page-allocated memory and mounts it read-only at /ramfs. The kernel image no longer contains it, so the pack no longer moves _end; the high-memory legacy path supports up to 2 MB (known issue 8). The UI font subsets live in the pack under fonts/, the WiFi firmware under firmware/, the mouse cursors at cursors/adwaita24.cur (full pack only), the UI icons at icons/adwaita16.icn (both packs) and the flat kernel at install/kernel.bin (full pack only; install self reads it). The floppy images use cmds-lite.pack (no firmware, cursor bundle, install/kernel.bin or bin/browser.app, to stay inside 1.44 MB; the browser launcher falls back to BROWSER on root.img).

rootfs.bin is the floppy append (header + lite pack); rootfs-full.bin is the header + full gzip pack used by make net-install; cmds.img is the 8 MB rootfs partition image written to USB partition 2. cmds-dev/net-cmds send the raw cmds.pack, which ramfs_replace() validates and installs directly in the running kernel. A running board can replace the pack without a kernel reload:

make cmds-dev       # serial:  ./kexec_send  --payload $(SERIAL_DEV) $(SERIAL_BAUD) cmds.pack
make net-cmds       # network: ./netkexec_send --payload $(BOARD_IP) $(NETKEXEC_PORT) cmds.pack

The pack is received into page-allocated memory (magic "KXNP" over serial, the same stop-and-wait protocol with a "KXNP" header over UDP), validated before the swap, so a truncated or corrupt transfer leaves the running commands untouched; a good one is installed by ramfs_replace() and the previous heap copy is freed. Existing processes are unaffected (they already loaded their ELF), and the next spawn picks up the new files. The WM idle loop auto-detects the kernel/rootfs (KXE2/KXN2) and the runtime pack (KXNP) transfers, so a plain make cmds-dev/make net-cmds is enough. Runtime updates are RAM-only; a cold boot uses the flashed rootfs (USB partition 2 or the floppy append), so reflash after changing the bundle.

Network hot-reload (net-dev) workflow

For boards without a serial console (the ASUS AT3IONT-I), the same reload runs over the network instead:

make net-dev                    # kernel + rootfs to BOARD_IP (default 192.168.178.240)
make net-dev BOARD_IP=192.168.178.42
make kernel-net-dev             # kernel only; keeps the running rootfs

The board must be idle at a shell prompt: the WM loop polls the NIC, answers ARP/ICMP for its IP, and auto-detects the "KXN2" header datagram (UDP port 19288). The header is magic, entry, kernel_size, pack_size, checksum; the host tool (netkexec_send.c) sends the kernel then the gz rootfs as one stop-and-wait stream, the board acks every datagram with the next expected offset, verifies the 32-bit checksum, writes boot info for the staging tail and jumps. pack_size == 0 keeps the running rootfs. ~480 KB takes a couple of seconds on a wired LAN. While a raw command owns the receiver (netrecv/ping/netloop), a TCP client or stack DNS/ARP wait is active, or a kexec is in progress, the auto-detect pauses.

The persistent variant uses a "KXI2" header: magic, entry, kernel_size, pack_size, checksum, target[16], with the kernel followed by a full NBROOT1 rootfs image (rootfs-full.bin). The board writes P2, then the P1 kernel, patches the P1 boot sector's exact kernel_sectors, verifies the result, acks ACK_INSTALLED, and jumps into the new kernel. It never touches P4 or the MBR. NETINSTALL_TARGET ?= auto picks the only non-USB NebOS disk; override it with mmc0, sata0, etc. install self refuses a raw runtime pack, so after cmds-dev/net-cmds/ kernel-dev use make net-install to persist. The UEFI loader reads the same P1/P2 image, so no ESP rewrite is needed after the first full install of this layout.

The old KXNU/KXEC magics are deliberately not understood by this kernel (and it uses KXN2/KXE2/KXI2), so a board still running a pre-rootfs build must be flashed once; the new make net-dev is then atomic.

The board's address comes from DHCP when a server is present (the DHCP client runs at boot; netinfo shows ip/mask/gateway and the lease), so use make net-dev BOARD_IP=<leased address> — or netip on the board to pin one.

Network console (make netmon)

The serial console is mirrored to UDP port 19290, so a board without a serial port gets the same visibility as make monitor:

  • everything written to COM1 (serial_puts — driver bring-up trails, MTRR dumps, kexec progress) and
  • everything written to a terminal screen (io_putstr — shell output, command results, netrecv dumps)

is buffered in RAM as it is produced and flushed from the WM loop as line-sized datagrams. On the host:

make netmon                 # builds + runs netmonitor (Ctrl-C to exit)
make netmon | tee board.log
./netmonitor 19290          # different port

The mirror is on by default and broadcasts; netconsole host <laptop-ip> narrows it to one host (datagrams carry the broadcast MAC, so the board needs no ARP entry for it), netconsole off/on toggles it, and netlog <text> sends an ad-hoc line. Nothing is sent before the NIC is up, the producer never blocks (a full buffer drops characters and reports it), and the flush pauses while a raw command owns the receiver or a TCP/stack network operation is active (its broadcast traffic would otherwise compete with the replies). The producer path is netlog_char (via screen_putchar/serial_putc) and is non-blocking; SYS_NETLOG is the direct-send command path — never call it from the WM or from any BKL holder, because a blocking NIC TX can wedge the whole board.

USB HID (mouse + keyboard) / host controllers

usb.c is controller-agnostic; the drivers implement the usb_hcd_ops vtable (usb_hcd.h): control transfers, root-port queries/reset, bulk transfers and up to six interrupt-IN slots. usb_hcd_init() brings up every controller type and builds one global controller table: EHCI first, then UHCI, OHCI and xHCI. A machine with EHCI and UHCI/OHCI companions therefore enumerates high-speed devices on EHCI and low/full-speed devices on the companions; a port reset hands a non-high-speed device back to its companion before the companion is scanned. A single device address is per-controller, so addresses do not collide. The first SET_ADDRESS/GET_DESCRIPTOR uses the USB default 8-byte EP0; the descriptor's real bMaxPacketSize0 is adopted afterwards (a full-speed device may have an 8-byte EP0, and the old 64-byte guess made the 970A's OHCI drop the mouse). A failed port enumeration is retried up to three times with a fresh port reset and a 20 ms settle, and the boot scan gives OHCI a second pass 60 ms after the EHCI-first walk, because the EHCI handback can leave a companion port briefly reporting disconnected.

  • EHCI: MMIO BAR0, page-allocated frame list/QH/qTD/bounce buffers, QH/ qTD descriptors in the identity-mapped kernel space. Control, bulk and interrupt endpoints all live in the asynchronous schedule (a circular QH list with the control QH after the reclamation head); the periodic list is not used. Polling only (no IRQs). Ports are claimed from the companions with CONFIGFLAG; port_reset holds PORT_RESET for 50 ms, then clears it (QEMU and hardware complete the reset on that write), waits for PED and sets PORT_OWNER for a non-high-speed device: a K line state before the reset (low speed), or no PED after it whatever the line state (EHCI 4.2.2; the ION's MCP79 reads SE0 there for a full-speed receiver, which used to loop through controller resets that also stole the companions' ports). Handed-off ports are remembered (cc_ports) so a later scan does not take them back; the stuck-reset controller-reset retry is only for controllers without companions (HCSPARAMS N_CC 0). ehci.c supports up to four PCI instances. The async schedule is enabled only while a control/bulk transfer or an armed interrupt endpoint needs it (ehci_sched_get/put); with nothing attached the controller stops fetching QHs and qTDs, which keeps package C-states reachable (the port watcher only reads PORTSC). Disabling clears ASE and acknowledges STS_IAA; leaving the IAA doorbell status set stalls the next enable. Bulk in/out use one qTD per call (up to five 4 KB buffer pages), which is enough for the ASIX AX88772 RX/TX path. There is no transaction translator: low/full-speed devices behind a high-speed hub stay invisible to EHCI (use the companion controller for them).
  • Hubs: usb.c sets a class-9 hub's configuration with SET_CONFIGURATION before issuing hub-class requests, powers every downstream port (honouring the hub descriptor's bPwrOn2PwrGood) and waits for PORT_ENABLE after the port reset. This is needed for the X201's PCH internal 8087:0020 hubs, which sit between the EHCI root ports and the external USB ports. Downstream devices are enumerated recursively; a full-speed device behind a USB 2.0 hub would need split transactions (not implemented).
  • OHCI: BAR0 MMIO (ioremap()), HCCA from the page allocator, static 16-byte-aligned ED/TD sets. Control transfers run on the control list (HcControlHeadED + CLF) and are polled via each TD's condition code — a NAKed TD stays queued and is retried by the controller. Both HID EDs (F = 0) are chained and referenced from all 32 HCCA interrupt-table slots, so their TDs are serviced every frame. No IRQs: software harvests retired TDs and acknowledges WDH (HcInterruptStatus + HCCA DoneHead) each pass. The ED/TD/setup and interrupt-buffer structures live in the dedicated ohci_dma_page, mapped uncacheable by paging_init() (PDE 0 is split before paging is enabled). The SB950's legacy OHCI DMA does not snoop dirty CPU lines: without the uncached page the controller sometimes read an empty ED, skipped the transfer and never re-armed the endpoint (the mouse cursor froze with no error). Control transfers still use wbinvd around their caller-supplied data buffers, which remain write-back. TDs must be initialized with CC = NotAccessed (0xF) — OHCI has no active bit, and a zero CC makes software think a fresh TD already completed. TD data toggles are explicit: DATA0 = 0x02000000, DATA1 = 0x03000000 (0 means "use the ED carry bit"); a wrong value makes the first control transfer fail with a toggle mismatch on real hardware while QEMU (which ignores toggles) is happy. Control queues use a dummy TD as the tail anchor; the data stage is one TD (the controller splits it into MPS-sized packets itself). Before the first reset, if HcControl.IR says the SMM owns the controller, the driver requests ownership (HcCommandStatus.OCR, clear HcControl.IR) with a bounded 200 ms wait. On AMD SB600/SB700/SB800/SB950 it also clears the southbridge USB SMI enable (SMBus device 1002:4385, config 0x64 bit 15) once, so the firmware cannot take the OHCI ports back after handoff. Both are no-ops on Intel/QEMU.
  • UHCI: I/O ports, frame list at 0x3000, control QH + two more QHs (one per interrupt slot) serviced every frame while the controller keeps running. The PCI scan checks all functions (real PIIX3/PIIX4/VIA layouts put the USB function at 0:07.2 / 0:01.2) and ignores controllers whose BARs the firmware left unassigned. One instance only.
  • xHCI: MMIO BAR0 (PCI class 0c03:30), one controller, polled. The Supported Protocol extended capabilities include both USB2 and USB3 protocol entries; direct SuperSpeed root-port devices are enumerated with a 512-byte EP0 and the port speed in the slot context. USB3 hub port-status decoding is not implemented. xhci_init() waits for CNR=0, clears RS and waits for USBSTS.HCH before HCRST (the xHC may ignore the reset while running), waits 1-2 ms after the HCRST write before touching any other register (Intel CherryView/Braswell requires this, or the reset can be left partially applied), does the BIOS/OS handoff with a bounded wait for the BIOS-owned semaphore to clear, and only programs CONFIG/DCBAAP/scratchpads/CRCR/ERST once the post-reset controller is halted. Port reset clears stale change latches, waits for PRC then PED, and adds the 10 ms USB2 reset-recovery delay. Only a USB2 port is disabled (PED write) before the reset: on a SuperSpeed port that puts the link into SS.Disabled, which a hot reset does not leave. Address Device programs the speed's fixed EP0 max packet size (8 low, 64 high, 512 SuperSpeed) whatever the core passes; only a full-speed EP0 takes the core's 8-byte first guess and is then corrected with an Evaluate Context once the core reads the real bMaxPacketSize0. Without that the VIA VL805 (1106:3483) on the 970A-DS3P kept an 8-byte EP0 for a high-speed stick, and the 18-byte descriptor read failed with Babble Detected, so a USB-booted stick never became usb0 for install. The Setup TRB's Transfer Type field is only set on xHCI >= 1.0 (reserved in 0.96). The init line (xhci: <pci id> hci <ver> ...) and every failed control transfer (request, completion code, PORTSC, slot/EP0 state) are always logged to COM1/netmon. Enumeration uses the traditional scheme: SET_ADDRESS before the first descriptor read. The xHCI SET_ADDRESS intercept creates the slot in the Enabled state and issues Address Device with BSR=0 directly (Enabled -> Addressed), never leaving the slot in the Default state; the Default-state EP0 transfer was unreliable on the Braswell. The input slot context's Device Address stays 0 — the xHC assigns the USB device address and reports it in the output context, which the driver stores for later Configure Endpoint commands (writing a target address there makes Address Device fail with Parameter Error). Control transfers wait 1 s, re-ringing the EP0 doorbell every 100 ms. EP0 stages are encoded the way EDK2's XhciDxe does it: each stage is its own TD (IOC on the Setup, Data and Status TRB, no CHAIN). This Braswell xHC never completes a chained multi-TRB control TD (CHAIN on setup+data, IOC on status only): the data stage hangs and no transfer event is ever posted, while the per-stage encoding completes and returns the descriptor. IN data stages also set TRB_ISP. PORTSC writes preserve only the read-only and RWS bits (portsc_neutral(), Linux's xhci_port_state_to_neutral): writing the raw read value back with just the RW1C bits masked re-asserts PR/WPR and resets the device after SET_ADDRESS, so the xHC then talks to an address the device no longer uses. Devices plugged in after boot bind through asix.c, which calls netdev_hotplug() so the dongle becomes the active NIC when the boot probe found none.
  • Mass storage (usbmsc.c/h): the device probe claims a class 8 / subclass 6 / protocol 0x50 (SCSI transparent, bulk-only) interface, parses its bulk IN/OUT endpoints, sets the configuration and identifies the disk with SCSI INQUIRY + READ CAPACITY. Commands use BOT CBW/CSW with LUN 0, 512-byte blocks and at most 62 sectors per data stage; READ(10), WRITE(10), SYNCHRONIZE CACHE, a BOT reset and endpoint-halt clear are implemented. Short bulk-IN chunks are accumulated within a BOT data stage; a failed READ(10) gets REQUEST SENSE, three retries and a 1-sector fallback. blk_scan() registers present devices as usb0.. (BLK_USB), so storage, the VFS mount path, format and install can use them. Bulk transfers exist only on EHCI and xHCI; a storage device on a UHCI/OHCI companion is left unclaimed. The xHCI bulk-IN path arms one transfer per call and does not auto re-arm, so a consumer can alternate CBW, data and CSW buffers. The installer reads the live image from usb0; direct USB3 root-port sticks work, while UHCI/OHCI bulk devices, USB3 hubs and UAS/4Kn sticks are not usable.
  • Devices (usbhid.c): every HID (class 3) interface with an interrupt-IN endpoint gets its own interrupt slot (USB_HCD_INT_SLOTS = 6). Boot interfaces (subclass 1, protocol 2/1) are used as-is in boot protocol; other class-3 interfaces are classified by reading their HID report descriptor (a mouse/pointer collection or relative X/Y input is a mouse, a keyboard collection is a keyboard; absolute pointers/tablets are ignored). Composite devices (keyboard + mouse behind one receiver) and several devices can therefore coexist; mouse reports from all slots are merged. Mouse reports are 3 bytes (b0&7 buttons, signed dx/dy; HID's +y is flipped to the PS/2 convention). Keyboard reports are 8 bytes (modifier byte + 6 keycodes); they are diffed against the previous report and decoded through a HID-usage → scancode-set-1 table (including 0xE0 extended keys), then injected with io_inject_scancode() so the terminal/WM see exactly what a PS/2 keyboard would produce. Since a boot keyboard only reports changes, io.c adds software typematic repeat (500 ms delay, 33 ms rate) for the last make code; real PS/2 hardware repeat keeps resetting the same timer. usbhid_poll() (from mouse_poll_update()) also runs the hotplug watcher: root-port connect changes are enumerated (throttled to 250 ms). A port read must report disconnected three times in a row before the device is detached, and the TD error threshold is 50, so a single CCS glitch or a short low-speed error burst cannot kill a working device. Any detach sets need_rescan, which runs a clean full usb_scan from the watcher: a false port-loss leaves no CSC to wake the per-port path, so this is the only reliable recovery on the SB950. A full scan (lsusb) also bumps usb_generation(), which makes usbhid detach and rescan, so lsusb can't leave the devices dead. The BIOS PS/2 legacy emulation is deliberately disabled (PCI config 0xC0) because the kernel now owns these devices.
  • Debug: ohci: / uhci: / ehci: / usbhid: lines go to COM1 (and through the netlog mirror on serial-less boards); mouseinfo shows the active mouse backend, the Elan VID/PID when the I2C touchpad is present, and whether a USB keyboard is attached; usb.c's USB_DEBUG and usbhid.c's USBHID_DEBUG (both default 0) add scan/report tracing. Headless tests: make test-usb runs tools/qmp_cursor_test.py (injects mouse motion with QMP input-send-event, verifies the cursor with screendump) and tools/qmp_keyboard_test.py (types with QMP send-key, verifies the screen output); the cursor test takes --uhci, --uhci72 and --multi, and both take --hotplug, --xhci and --ehci.
  • Limits: EHCI drives high-speed root-port devices only (no TT/split transactions for low/full-speed devices behind a high-speed hub), hotplug watches root ports only (a device behind a hub is only enumerated when a scan runs), HID report IDs are not handled (a device that prepends report IDs decodes as garbage), absolute pointers/tablets are ignored, no wheel events, and no USB keyboard means no keyboard at all if the BIOS legacy emulation was the only other source (make net-dev still reloads the kernel).

Serial debug monitor (dbg)

A ring-0 debugger driven over the serial link. On the PC type dbg, then drive commands from the host with make monitor (picocom):

r <addr> <len>          read len bytes at addr -> hex dump
w <addr> <b0> [b1 ...]  write bytes at addr
i <port>                inb (read I/O port)
o <port> <val>          outb (write I/O port)
h                       help
q                       quit

The monitor runs inline (blocks the terminal), so it owns the serial ring buffer and doesn't conflict with the kexec auto-detect. Reading arbitrary physical memory is safe (no paging); writing can corrupt the kernel, so the usual loop is inspect → q → make dev a fresh build.

Headless debugging via serial (no display, no keyboard)

The terminal is framebuffer-only, so a headless QEMU gives you no easy way to type commands or see output. The reliable workflow (used for lsusb) is to temporarily mirror io_putchar to COM1, and to invoke the code under test directly at boot — no keystroke injection needed:

  1. Echo the framebuffer to serial — in io.c add #include "serial.h" and a serial_putc(SERIAL_COM1, c); at the top of io_putchar. Every io_putstr/ io_putchar call (terminal prompt, echo, command output) now also lands on COM1. serial_puthex/serial_putdec (serial.h) are available for structured dumps inside drivers.
  2. Call the code at boot — temporarily call the function under test from kernel_main (e.g. usb_enumerate_and_print(); before terminal_run()), or process_create(...) from terminal_run() to exercise the process context. QMP send-key/input-send-event and HMP sendkey do not reliably reach the PS/2 keyboard in headless/VNC-without-a-client mode, so don't script keystrokes — script the call site instead.
  3. Run QEMU headless and read the log:

    qemu-system-i386 -M pc \
     -drive file=floppy.img,format=raw,if=floppy \
     -drive file=root.img,format=raw,if=floppy \
     -serial file:/tmp/opencode/serial.log \
     -display none -vga std
    # ...then: cat -A /tmp/opencode/serial.log
    

    The NebOS v<version> booted line is already written to COM1 at boot, so serial is live before the framebuffer is up — a crash in early init still shows.

  4. Revert before committing — remove the io.c echo and any boot-time call; git status should show io.c and kernel.c unchanged.

QEMU gotchas that bit once:

  • The default -M pc (QEMU ≥ 11) has no USB controller. The run-floppy and run-usb targets therefore add -device pci-ohci -device usb-mouse (the OHCI path, same controller type as the ASUS ION); make run-uhci runs the same images with -device piix3-usb-uhci -device usb-mouse to exercise the UHCI backend. To keep the controller but leave a device out (hotplug test), drop it and use QMP device_add/device_del. A USB keyboard can be added the same way (-device usb-kbd); QMP send-key then types on it while the QEMU window's own keys still go to the PS/2 keyboard, so the dev loop stays usable. Cross-check the guest's view of the tree with the monitor info usb.
  • pkill -f qemu-system-i386 matches your own shell command line (it contains the string) and kills your script; use pkill qemu (process-name match) or kill by PID.
  • When a harness drives a -serial unix:... chardev, connect before the guest boots (immediately after QEMU starts): QEMU discards guest output written while no client is attached, so a late-connecting reader misses the boot log (kexec tests that wait for it then mis-report a failed reload).

Fatal exception screen (panic)

The on-screen debug overlay (kdbg: live counters, heartbeat, boot info rows) has been removed. The one diagnostic screen left is the fatal exception banner: on a ring-0 fault, exc_handler() (kernel.c) calls panic_report() (panic.c/h), which draws straight into the VESA LFB (bypassing the shadow buffer and the WM) and mirrors the same data to COM1, then halts. Faults from ring 3 do not halt: the process is killed (with a short message in its terminal and on serial) and the kernel keeps running.

What the banner and the COM1 dump contain:

  • vector name/number and the CPU error code (#PF also decodes P/W/U/RSVD/ID),
  • EIP, CS (ring), EFLAGS, and the faulting ESP (ring 0) or user ESP/SS,
  • EAX..EDI and EBP,
  • CR0, CR2, CR3, CR4,
  • current pid/name and uptime ticks,
  • up to 16 bytes at EIP (read only from mapped RAM and clipped at the page boundary, so the dump cannot fault again),
  • a few stack dwords plus return-address candidates found by scanning the faulting stack page for values in the kernel image (0x7E00..__bss_end). -O2 omits frame pointers, so there is no EBP-chain backtrace; the candidates are hints, not a true trace.

COM1 additionally gets 32 stack dwords and every candidate, each with its offset from the faulting ESP. Addresses are raw kernel addresses: resolve them with nm kernel.elf / addr2line -e kernel.elf <addr>.

Wiring: timer.S builds a struct exc_state (GPRs via pusha and the CPU's exception frame, including the error code that the old stubs discarded) and passes it to exc_handler(); panic.h documents the layout. The banner caches the LFB geometry lazily, so no boot hook is needed. The MTRR dump and the NIC bring-up trail that used to fill the info rows now go to COM1 only (mtrr.c, r8168.c). The IRQ1 storm guard still masks a storming keyboard and the WM falls back to polling (io_keyboard_irq_masked()).

Conventions & gotchas

  • Freestanding C — the kernel has no libc, no malloc, no printf; use io_putstr / io_putchar / io_puthex (io.h). Ring-3 commands link the in-tree libc.a when they need allocation or standard string/stdlib functions; the SYS_MEM_* syscalls are internal to the libc backend.
  • Paging is on but flat — identity-mapped 4 MB pages (paging.c), so physical == virtual for lowmem (below 1 GB). A frame from mm_alloc_user_page() may be highmem: never dereference it by its physical address, use kmap()/kunmap(). Still no per-process address spaces or process isolation: everything runs ring-0 and shares the address space.
  • Fresh memory is not zeroed — mm_alloc_page/kmalloc hand out whatever RAM contained; QEMU starts guest RAM cleared, real hardware does not, so a structure whose fields are read before being written must be cleared on allocation. clear_proc() (process.c) exists for exactly this: a stale procs[i].cr3 made the boot-time MMIO mapping (then paging_map_mmio_cr3, now process_sync_kernel_pde) fault on the board while QEMU was fine. Anything between MM_MAX_PHYS (1 GB) and the user windows is unmapped, so a wild pointer there is an instant #PF.
  • All drawing goes into the current render target (the shadow buffer by default; vga_target(), see the graphics bullet); the main loop flushes the pending damage rects to VRAM on every iteration (byte budget, see VGA_FLUSH_BUDGET_BYTES) so small updates (cursor, a keystroke) reach the screen within a loop instead of waiting for a fixed tick. A window drag flushes its rectangles immediately (wm_drag_shadow) so each step is one consistent frame. Full-screen programs call vga_clear_rgb.
  • FAT is read/write — FAT12/16/32 read plus write/delete/mkdir/rmdir. FAT32 allocation uses an FSInfo-seeded free-cluster hint; the FSInfo free-count is not updated and a completely full FAT32 directory is not 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.
  • 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 returning to a ring-3 context: use IRQ_RETURN_DS <cs_offset> (irqret.inc), as switch.S, timer.S and syscall_stub.S do. QEMU does not model this nulling, so a missing restore only fails on real hardware (symptom: ring-3 #GP on its first data access, e.g. a store through a pointer).

Known issues (candidates for future tasks)

  1. power.c still has no AMD P-state path. The FX-6350 (family 15h model 2) runs at the BIOS P0 and power/cpufreq report unsupported; the CPU temperature is supported through D18F3xA4. A minimal family-15h governor would read MSRC001_0064..006B (COF = 100 * (FID + 0x10) >> DID) and write the 3-bit index to MSRC001_0062, but it is not required for boot or the desktop. The AMD WC MTRR path is supported through the separate free-entry/zero-high-mask path described above; the Intel/ION WC paths are unchanged.
  2. vga.c draw_flush_debug_square() — leftover debug artifact, still draws a color-cycling 32×32 square in the corner on every flush.
  3. No per-process address spaces or process isolation (paging is identity-mapped).
  4. FAT32: FSInfo free-count not updated, no directory-chain growth.
  5. disk.c fdc_reset() and fdc_init_once() overlap/duplicate logic.
  6. Highmem limits: RAM above 4 GB is ignored (it would need PAE), and on a 4 GB board the PCI hole leaves ~3-3.5 GB usable. Highmem only backs ring-3 pages, so the 1 GB lowmem zone (kernel structures, canvases, contiguous buffers) can still run out first. One process is still capped by USER_HEAP_MAX (64 MB) and the 4 MB image/stack window; raising that needs demand paging ([USER_BASE, IOMAP_BASE) is free for it now that MMIO lives in the ioremap window). The window is 1 GB of 4 KB pages with 96 mapping records and no unmap: a driver that keeps remapping would exhaust it (ioremap logs window full and returns 0).
  7. display (needs a GPU snapshot) and lsusb (a 45-byte wrapper around the USB tree printer) are the last non-privileged commands still living in the kernel, plus the privileged ones (peek, poke, dbg, serial, kexec, reboot, poweroff, format, install, ps/kill, backlight/keytest).
  8. The rootfs pack is inflated into one contiguous page-allocated run at boot, capped by RAMFS_MAX_DECOMPRESSED (8 MB); a larger pack fails to load (the USB rootfs partition is 8 MB, so this only bites if the cap is raised without a bigger partition). The legacy stage copies the compressed pack directly to 0x900000 with a protected-mode rep movsb, so the cap is PACK_MAX 2 MB (raised from 1 MB for the WiFi firmware). The browser and its ring-3 dependencies are compiled with function sections and linked with --gc-sections; the current full pack with the UI fonts, both WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes, ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668 bytes) and install/kernel.bin is ~1.88 MiB gzip (~120 KB under the cap), inflating to ~3.6 MB, which adds about half a second to the boot; the floppy lite pack is ~580 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 (3.5 MiB) now takes about four minutes; use net-cmds.
  9. SMP is ACPI/MADT only: no Intel MP-table fallback, so a Pentium II SMP board that exposes only MP tables stays UP (deliberate; there is no test hardware).
  10. There is no IOAPIC driver. The BSP keeps the 8259 PIC in LAPIC ExtINT mode; after ACPI init, ioapic_mask_all() masks every normal IOAPIC redirection entry (ExtINT entries are left alone in case the 8259 is routed through an IOAPIC pin). APs mask LINT0/LINT1 and only use their LAPIC timer/IPIs. Device IRQs never reach an AP, and pit_irq_stub should be treated as BSP-only.
  11. The BKL serializes all kernel execution: a long FAT/disk operation, a non-network driver wait or a big shadow-buffer operation can stall syscalls on the other CPUs for its duration. bkl_pause()/bkl_resume() is used for serial/raw-network waits, the format raw-sector loop and the installer's target writes; the installer keeps the BKL only for its source-read burst so a USB source cannot be re-enumerated mid-read.
  12. Kernel threads (kworker, kexec/payload, kernel commands) are pinned to the BSP. Only ring-3 processes use the APs, so a single CPU-bound kernel driver still limits throughput.
  13. Page-table updates for another CPU's running process (e.g. an MMIO mapping) rely on not-present TLB entries not being cached; there is no cross-CPU TLB shootdown. No process shares an address space with another, so normal process teardown is unaffected.
  14. Image library limits: arithmetic JPEG and CMYK are rejected; EXIF orientation is applied but ICC/gamma is ignored; animated GIF frames are composited (the viewer plays them), but APNG/WebP remain unsupported. The whole file is read into memory (4 MB cap in the viewer) and very large photos still need DCT-scaled/streamed decode before they fit the 64 MB arena.
  15. img_draw()'s box-filter downscale runs on the CPU. The browser now caches a display-size bitmap per image (br_image.disp) and paints 1:1; remote <img> decodes in the warm curl __serve helper at the CSS box (the UI only reads the published RGB565+alpha bitmap), so the UI thread no longer runs the IDCT. Local images and backgrounds still decode in-process; the viewer caches one image at its window size, and chat caches 480x320/32x32 bitmaps. The in-process paths are still limited by the full-size img_estimate() arena (24 MB browser, 12 MB chat), so an image above the arena cap is rejected before the reduced decode runs.
  16. files recognises images by file extension only (.png .jpg .jpeg .gif .bmp .tga .ppm .pgm .pbm .ico .cur .pam); a magic-based fallback would also open extensionless files in the viewer. Automatic decode-at-scale for oversized images is still missing.

  17. WebDAV limits: one request at a time (one active connection plus 3 backlog/closing slots; the queue holds each connection's first 1 KB with a zero window), files are buffered whole (4 MB cap; a larger PUT gets 413), directory MOVE is 501, PROPPATCH is answered 200 without persisting, and there is no authentication. Sends use a four-segment window, and keep-alive is off, so parallel gvfs clients serialize but do not wedge.

  18. FAT mounts are writable over WebDAV only for names that fat_name_to_8_3() can represent exactly; anything longer is refused with 409 instead of silently truncating (two long names could otherwise collide and overwrite each other). Use /share for long names.

  19. The WebDAV server and the packet-level net commands are mutually exclusive: both need the raw NIC receiver (netdev_acquire). Starting websrv while ping/netrecv/host owns the NIC fails; TCP clients (curl, browser workers) also fail while websrv owns the raw lease, and websrv cannot start while any TCP socket is open. Kill the other command first.

  20. /share is RAM only: a reboot/kexec starts empty, and the 16 MB cap is charged against the 1 GB lowmem zone.

  21. The TCP backlog's early-request buffers cost 8 KB of kernel BSS (8 slots x 1 KB), and the FAT listing cache another 5 KB. The command pack is out of the kernel now; after the WiFi/netmenu/install code and the per-connection TCP queues moved to the frame allocator, _end is ~0x8ef20 before (with the 6200/6300 DVM layer, the RTL8821AU driver, the 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 now that the frame bitmap moved out of BSS, ~16 KB below the 0x90000 wall, and the remaining limit is kernel code/buffers only.

  22. Browser limits: JavaScript runs inline and external classic scripts on QuickJS (ES2025) with the DOM surface described above (creation/mutation/selectors/ attributes/classList/dataset/style/innerHTML/timers/events). Event listeners support capture/bubble, preventDefault, stopPropagation, Event and document.createEvent; still missing: inline event attributes (onclick=), MouseEvent/CustomEvent and once/passive options. POST uses application/x-www-form-urlencoded; a redirected POST follows as GET, and enctype=multipart/form-data plus file inputs are unsupported. ES modules, fetch/XMLHttpRequest and Web Storage work (see the browser bullet) with these limits: fetch()/XHR block the page while they run (no streaming bodies, no upload progress), FormData is sent urlencoded (no multipart/files), only Content-Type is forwarded from request headers, response headers other than Content-Type are not exposed, bodies are text (Latin-1/UTF-8, no binary arrayBuffer), CORS is not enforced, Mutation/ResizeObservers never fire and the IntersectionObserver always reports "visible". Module loading is sequential apart from the modulepreload pass. crypto entropy is the weak Math.random/clock mix (fine for PKCE nonces, like the TLS DRBG). On QEMU's NE2000 the four parallel module downloads can overrun its small RX ring and stall TLS handshakes into a 10 s timeout; use e1000. DOMParser and document.implementation.createHTMLDocument return an inert detached document (its nodes live in the page arena; markup goes through the innerHTML fragment parser, head elements included), which is enough for jQuery's probe and parseHTML but not a separate XML parser. Also missing: defer/async ordering, document.implementation.createDocument, canvas/2D contexts, user-state pseudo-classes (:hover, :focus, ...), :nth-child(... of S) and pseudo-elements other than ::before/::after; generated content is text, or an empty icon box with a background colour and a data: background image (no borders/padding, counters, content: url() or remote background images on pseudo-elements; text pseudo-elements inside flex/grid containers are not emitted). getComputedStyle returns the engine's known properties (display, box metrics, colours, fonts, borders, background and transform state), and style/dataset cover inline state rather than computed style. Libraries that need those APIs (jQuery plugins beyond Bootstrap's tooltip, Angular apps that use $http) still log errors even though the static page renders. CSS also lacks multiple background layers, background-attachment, 3D/perspective transforms and transformed text/descendants (scale/rotate paint the element box and inline images; layout geometry is unchanged), border-radius clipping of descendant content, gradients/box-shadow/transitions (a gradient background falls back to its last solid colour), or CSS color-mix. A non-uniform background-size uses the width scale for both axes. CSS custom properties (var(): one document-wide table, expanded when a sheet is parsed; definitions on :root/html/body/*/:host win, a component-level definition applies only while no other rule gives the name a different value, otherwise var() uses its fallback -- Font Awesome's competing --fa-width values made every icon 100% wide; rules touching such names are re-expanded per element against that element's own matched rules, but values are not inherited from ancestors' rules), percentage heights (against the containing block's definite height, lay.cb_h, with the viewport for html/body; used as a minimum since there are no scrollable inner boxes, and auto when the containing height is indefinite -- they used to resolve against the width), flex rows with wrap/grow/gap/justify/ align, two-track, repeat(N, 1fr) and repeat(auto-fit, minmax(...)) grids (no grid-column spans), aspect-ratio, inline-block runs, basic proportional table columns, table rowspan/colspan/percentage columns and inline SVG (filled/stroked geometry, use/symbol, transforms; gradients, patterns, clip paths, masks, filters, markers and textPath are not rendered, a gradient paints its average stop colour) are supported. position:fixed/absolute boxes are deferred and painted above the flow; z-index sorts that deferred list; position:relative shifts painting without moving flow (and joins the deferred stack when it has a z-index), and position:sticky supports top and bottom offsets and clamps to the containing block. prefers-color-scheme media queries are ignored so the page's base palette is used, and forced-colors/prefers-contrast/hover/pointer are answered for a normal-contrast mouse screen. A flex row narrower than 160 px is still a row when its items fit, and align-self overrides the row's align-items; a clamped max-width makes margin: auto centre the box. Block width/max-width/min-width, content-box height with min/max, box-sizing: border-box, margin: 0 auto and calc(percent ± px) work in widths, margins/padding, heights and min/max; percentage widths resolve against the containing block. Float support is the basic Bootstrap-grid case: consecutive floated blocks are laid side by side with percentage/px widths, left floats pack from the row's left edge and right floats from its right edge, inline floats are blockified (Bootstrap floats the navbar brand and its text links), inline text following a float wraps beside it, clear advances past the active float, and a float without a width uses a text-width estimate. @media width blocks are evaluated against the canvas width at page-parse time, so a window resize does not re-evaluate them until the next load. An absolutely positioned box placed by bottom without an explicit height, or by a percentage left inside a nested positioned box, can land at the wrong place (the store's navbar search box). font-size maps to real pixel sizes (8..48), font-weight selects the bold face, font-style: italic selects the italic face, font-family: monospace selects Liberation Mono, and nested em/% font sizes, em/rem widths, and margin/padding percentages/em resolve against the containing width/element font (root for rem). Text is Latin-1 only (non-Latin-1 characters become ?); there is no shaping, bidi, WOFF/unicode-range or full-Unicode fallback. @font-face supports one regular TTF/OTF per family; bold/italic/inherited weights fall back to the installed faces, and the font shorthand does not resolve a custom family (use font-family). Pages that need multi-row grid templates, color-mix() or full transforms can still lay out imperfectly. Remote <img> decodes in the fetch helper at its CSS/attribute box (the helper request carries D <max_w> <max_h> and publishes an RGB565+alpha bitmap), so the UI only reads it; local images and backgrounds use a per-image img_estimate()-sized arena in-process (<img> passes its box through img_options.max_w/h, backgrounds decode at their box), and the browser keeps a lazily built display-size bitmap (br_image.disp) for 1:1 repaints (256 source images within a 4 M-pixel budget plus a 6 M-pixel display-cache budget, 1 MB files / 8 MP decodes). The in-process paths still size the arena for the full image, so a very large local or background photo can fail the 24 MB cap before the reduced decode runs; the scaled bitmaps live until navigation. Image repaints are coalesced (100 ms) and jobs decode in 40 ms batches; /share/IMGSTAT records net/io/dec/scale/paint/reflow. Lazy image loading uses the last measured positions; adding an image can reflow the content above it, and images below the viewport stay as [image] until scrolled into range. The browser keeps up to four curl __serve workers, each with its own TCP/TLS keep-alive connection and private /share/bf*N files; images are prefetched in parallel and decoded as jobs complete. Stylesheet and external-script bodies are downloaded in parallel but parsed/executed in document order, and one image starts before the script phase. Idle helpers stay warm across navigations (a cross-origin job drops the old connection); losing focus or ten idle seconds stops them, so their sockets do not block raw commands. The helper requests gzip; a page that is only small when compressed can exceed the 2 MB page/832 KB CSS caps. Video/audio elements are placeholders. Bare & characters are consumed by the entity decoder instead of looping forever. A page with no html/body background gets the dark default canvas unless its computed text colour is dark, in which case the canvas is white like a normal browser's. @layer ranks nested layers flat by first appearance (a parent layer's own rules lose to its sublayers, the spec says the reverse). TLS is phase A (no certificate verification); https is shown as unverified. The disk app is loaded from FAT at spawn time, so a cold floppy start takes a few seconds; the layout state is deliberately static.

  23. UEFI boot is x86-64 firmware only (no BOOTIA32.EFI yet) and the loader is unsigned, so Secure Boot must be off. The loader needs a GOP mode with BGRX or RGBX 32bpp, width ≤ 1920, pitch * height ≤ 8 MB (1920x1080 fits at 8.29 MB) and the framebuffer below 4 GB; otherwise the kernel starts headless (serial only). The same 2 M-pixel cap keeps a full-screen RGB565 canvas inside the 4 MB window slot. xHCI drives USB2 and USB3 root ports (USB3 hubs are not decoded), and EHCI only high-speed root ports (no transaction translator for low/full-speed devices behind a high-speed hub), so a full-speed device behind a USB2 hub can still leave the UI without input (PS/2 may still work). OVMF delivers the ISA IRQs through the 8259 path; the kernel nevertheless masks the IOAPIC's normal redirection entries after ACPI init, so firmware-left vectors cannot collide with the PIC or LAPIC timer. UEFI runtime services are not used, so reboot/poweroff still use the legacy ports. The image is 17 MB: the 9 MB kernel + rootfs disk and the 8 MB ESP. Maxwell GPUs such as the GTX 960 use the firmware VBE/GOP framebuffer only; there is no native NVIDIA driver, and nv50_probe() is gated to the ION/nv50 chipsets.

  24. ThinkPad EC sensor and battery access (tpec.c) runs in legacy/SMM mode because there is no ACPI interpreter: an SMI that touches the EC between our port accesses can produce an occasional bad sample (the battery reader validates its values and the next 1 Hz poll corrects the bar), and the 0x81 page-selector write can race the firmware's own battery poll. EC hotkey events are drained/discarded instead of handled. The PCH thermal sensor (8086:3B32, the intel_ips MMIO block) is not read because it needs the ME/BIOS to have enabled thermal reporting; the EC and DTS readings cover the package temperature.

  25. Ring-3 libc heap limits: one process owns the single 64 MB SYS_MEM_* arena, there is no free()-to-page unmap (only heap_reset()), no threads/locking and no double-free recovery beyond the block magic; a pointer into the middle of a block or a stale pointer is silently ignored by free(). The allocator is first-fit with immediate coalescing, so a pathological small/large lifetime mix can still fragment; the terminal, browser, viewer, websrv and curl use it for a handful of large buffers. Commands allocate through libc.a; the raw SYS_MEM_* calls are backend-only. Near-64 MB requests fail because the block headers are charged to the same cap. The libc.a members are only pulled into commands that reference them; the legacy pack still needs every added byte checked against CMDS_GZ_MAX.

  26. Fonts: ufont remains a fixed-point TrueType implementation with no shaping/bidi/kerning, CFF or variable-font support. UTF-8 rendering is opt-in through ngui_text_utf8*; the browser/terminal and other byte paths stay Latin-1. The emoji face is a curated monochrome Noto Emoji subset and only covers single-codepoint glyphs that fit the 256-point / 16-contour rasterizer: ZWJ sequences, flags, skin-tone sequences and color glyphs fall back to a tofu/?. Small sizes (below ~12 px) are softer than the bitmap font. The 512 KB arena is shared by the built-in faces (including emoji), up to 11 @font-face faces and glyph masks; a very text-heavy page can exhaust it and fall back to re-rasterizing evicted glyphs. The browser must detach/re-attach its font arena around heap_reset(); terminal/editor cell grids stay on the 8×16 bitmap font, while ngui text fields use the proportional face.

  27. Ring-3 stdio/time/math limits: FILE is read-only and whole-file (4 MB cap); there is no open/read/write/lseek/fd layer yet, and stdin is EOF. The TODO is in user/lib/libc/stdio_file.c; writable files and streaming need kernel SYS_OPEN/READ/WRITE/LSEEK/CLOSE plus offset fs_ops. time is UTC-only, time_t is 64-bit, and the RTC range is 1970-2069; there is no timezone database. math is an x87 double-rounding implementation, not a full fdlibm; long double, %a and some exact edge cases are not supported. Float printf supports %f/%e/%g with a 900-digit precision cap. These are sufficient for QuickJS but are not a complete POSIX libc.

  28. The Elan touchpad is polled at 40 Hz because its report GPIO (GPNC bank index 18, level-low on setzer) has no driver. The pointer follows one contact; two-finger scrolling uses the centroid of the first two contacts. There is no inertia, no horizontal scroll, no drag-lock or pressure/size handling, no distinct three-finger gesture (3+ fingers count as a two-finger right tap), and the 1/2 device-unit delta scale is fixed (no pointer-acceleration curve). Tap gestures are software-synthesized (two-finger and bottom-right-corner right click, one-finger left click) and need the contact to last at least two 25 ms samples; the corner zone also remaps a physical clickpad press to the right button and the tap/scroll thresholds are in touchpad_gesture.c. The device stalls if the input register is read back-to-back, so a GPIO interrupt (or a larger minimum gap) is the prerequisite for a higher report rate.

  29. Airmont/Braswell power management: the governor caps at the maximum non-turbo pstate (N3060: 20 = 1600 MHz) and never requests turbo pstate 31 (2480 MHz), so cpufreq max means max non-turbo. C6N is enabled but the kernel does not program package C-states/S0ix, does not read package RAPL energy, and does not write the package C-state/auto-demotion MSRs (coreboot/FSP configures them). The Airmont probe deliberately avoids package/power-SKU MSRs because an unsupported rdmsr before the IDT triple-faults; the first read-only build hung at power_init that way. C3/C6 residency is not reported on Airmont, and the explicit idle c6 override still uses the Nehalem 0x20 hint; use idle auto for the validated Airmont C6N (0x58) path.

  30. Chrome EC limits: only the ACPI v2 memmap interface is used; the MEC host-command/EMI interface, EC SCI events, charger current/voltage, charging limit and EC firmware version are not implemented. The battery/AC values are polled (WM at 1 Hz), so a plug event can take up to a second to appear. Battery strings fall back to the 8-byte memmap and can be truncated; fan entries may read 0 on fanless models instead of 0xffff. The lid/power-button switches are read by sensors but do not trigger a power-off or display blank; suspend/S0ix is not implemented.

  31. eMMC/SDHCI: the Chromebook eMMC is driven polled at 1-bit/25 MHz, with no DMA, IRQ, CMD6 bus-width/high-speed/DDR switch or hotplug; only the eMMC function (8086:2294) is handled, not the SDIO/SD functions or the SD card reader. The write path uses CMD24 PIO and the format command's cache flush uses CMD6 FLUSH_CACHE when EXT_CSD CACHE_SIZE is non-zero. The eMMC contains the stock ChromeOS image, so format mmc0 is destructive; the board boots from USB.

  32. Installer limits: install clones P1..P3 from the live image (~17 MB for usb-efi.img, ~8.5 MB for usb.img); the rest of the target becomes the /data partition and is not part of the clone. The source must be visible as a blkdev: USB mass storage is BOT/SCSI on EHCI and xHCI bulk, including direct USB3 root-port devices (no UHCI/OHCI bulk path, no USB3 hubs, no UAS or 4Kn), so an unsupported stick or controller leaves no source. The installer needs ~17 MB of free RAM for the source image (less for usb.img); a source-read failure leaves the target untouched, while a target-write failure can leave it incomplete (the MBR is written last). IDE, SATA and eMMC sources work without USB, but a target smaller than the image (plus a 1 MiB data partition) is refused. install self requires the full pack's /ramfs/install/kernel.bin and a gzip boot image; it refuses a raw runtime pack (use net-install). net-install needs an already-installed target (it does not create the boot sector/ESP) and a host that can reach the board.

  33. USB tethering is RNDIS only (rndis.c): Android phones and QEMU usb-net work, but CDC-ECM/CDC-NCM (many iPhones and some Android builds), IPv6, multiple phones and the RNDIS interrupt status endpoint are not implemented. The notification endpoint is ignored because responses are polled on the control channel; a phone that insists on RESPONSE_AVAILABLE needs an interrupt-slot allocator. A hotplugged phone becomes the active NIC but does not run DHCP automatically; use netdev rndis and then dhcp. Bulk transfers exist only on EHCI/xHCI; each bulk-IN transfer is capped at 2 KB and messages are reassembled in a 4 KB stream (a partial message larger than that is dropped). net_stop() only clears software state: it cannot cancel an already armed bulk-IN transfer, so kexec relies on the next USB controller reset. QEMU's usb-net is full-speed, so make run-rndis exercises full-speed bulk on xHCI rather than the phone's high-speed path.

  34. Chat client limits (ucmd_chat.c): REST polling instead of the WebSocket, so new messages appear within ~2 s, there are no typing indicators, and other clients see the NebOS user as offline (presence is WebSocket-driven). Native login covers Cloudron username/password + TOTP; passkeys and external SSO need the pasted connect.sid cookie. The login depends on Cloudron's cloudron-config login API (chat_login.c isolates it). TLS is not verified (the login screen says so), and the saved cookie in /data/CHAT.CFG (or /share/chat.cfg without a /data mount) is a bearer credential (persistent on /data, RAM-only on /share; concurrent chat windows share the file). No threads, reactions, polls, search, edits or deletes beyond what a reload shows; image attachments and link-preview thumbnails render up to the 4 MB fetch / 4 MP decode caps, a card whose thumbnail format is unsupported (WebP/AVIF/SVG) keeps its title and description, file attachments are still text-only, messages over 4 KB are truncated, history holds 240 messages, times are UTC and text is Latin-1. REST calls still block the UI for their duration; message images decode in the curl __serve helper (480x320 bounds) and chat only copies the bitmap, while avatars decode on the chat thread at 32x32.

  35. WiFi limits (iwl_trans.c, iwl_mvm.c, iwl_dvm.c, wifi.c): Intel 7265 rev D/3165 (iwlwifi-7265D-29) and 6200/6300 (iwlwifi-6000-4) only; a non-D 7265 is logged and will likely fail, and other 6000-family parts (6005/6030/6050/6150, which use different firmware files) are not probed. The 6200/6300 DVM path was written against Linux iwldvm without hardware in the loop at first; on the X201 (a 6300, 8086:4238) the firmware boots and the 2.4 GHz scan works, while the 5 GHz scan and connect are still being brought up. It has no sensitivity, chain-noise or temperature calibration and a fixed 15 dBm TX power. Open networks and WPA2-PSK with CCMP pairwise and group only: no WPA3/SAE, PMF/802.11w, 802.1X, TKIP, WEP or hidden-SSID connects. Legacy rates only (12 Mb/s data, no LQ/rate scaling, no HT/VHT, no aggregation, non-QoS association), no power save, roaming, background scan or scan while associated, no regulatory database beyond the firmware's MCC ZZ default. Polled RX (the WM idle loop and every stack call drain it). The connect and firmware load hold the BKL for up to a few seconds. Group rekeys need the background wifi __keep helper (it carries the PTK in its argument and memory); if it is killed the link drops at the next rekey. The SNonce comes from the weak TLS DRBG. RX CCMP is decrypted in software (ccmp.c) when the firmware reports SEC_ENC_ERR: on the tested 7265D-29 the firmware does not use keys that ADD_STA_KEY accepted, for either the PTK or the GTK, while TX (where the TK is embedded in TX_CMD) works. The software path has no replay window yet and uses a byte-oriented AES-CCM per frame, so high RX throughput is CPU-bound. The driver was written against the Linux iwlwifi sources without hardware in the loop; expect bring-up debugging on the Chromebook. The kernel budget is tight: WiFi added ~28 KB with both firmware layers, _end is ~0x85ca0 with the RTL8821AU driver (~41 KB below the 0x90000 wall).

  36. Control panel limits (ucmd_netmenu.c): building the device list probes every driver, so opening the menu on a machine with an unconfigured USB NIC can take a moment (USB control transfers) and may initialize a device that was not the boot-time winner. The panel shows at most four device rows plus a "+N more devices" line, one menu instance is kept open by the WM, and WiFi scanning is refused while associated (use Disconnect first). The panel opens at a compact height (the summary plus the Quick settings pills) and calls SYS_WIN_RESIZE_SELF to grow over an expanded section; it is clamped to the screen and the section scrolls when it is taller. The brightness card and the Power mode pill are hidden when the machine has no panel PWM / P-state control. The inline Date & Time editor writes the RTC and can block for a 5 s NTP sync. Closing the panel with an outside click kills the netmenu process without cancelling an already started wifi helper. The staged /share/netmenu.wifi record contains the WPA2 passphrase until the wifi helper reads and unlinks it; the path is fixed, so two concurrent netmenu instances (e.g. one launched from a terminal) would overwrite each other. The wifi helper is asynchronous: closing the menu does not cancel a connection attempt. Saved credentials live in plaintext /data/WIFI.CFG (8.3), hold up to 16 networks, and are retried at boot; wifi saved lists them, wifi forget [ssid] removes one and the menu's Saved view has a Forget button per network. A network saved with a wrong passphrase is tried again at every boot until it is forgotten (Saved view or wifi forget <ssid>) and joined again with the correct passphrase.

  37. /data limits: the data partition is a plain FAT volume, so file names are 8.3 until fat.c gains LFN write support; there is no fsck, resize or format-preserving migration. It starts at the fixed LBA 34816 (after the 8 MB ESP), so a BIOS-only install leaves an unpartitioned ~8.5 MB gap and the volume is not resized if the disk is later cloned to a larger one. The first install formats the rest of the disk and is destructive; old ChromeOS/other partitions are overwritten. An existing NEBOSDATA volume is identified by its label and fixed start LBA, so changing the label makes the installer treat it as foreign and reformat it. The partition is mounted read/write by every user, like the rest of this single-user OS. install self writes the gzip image the system booted from; a runtime raw pack replacement (cmds-dev/net-cmds/kernel-dev) is not retained for self-update, and net-install must be used instead. The initial install of this layout must still come from USB so the ESP gets the disk-reading BOOTX64.EFI; later updates do not touch the ESP. A power loss during install self/net-install can leave P1/P2 in an intermediate state: P2 is written first, then the kernel, then the boot sector; there is no A/B slot or journal. A later full install repairs it, and P4 is never touched by these updates.

  38. RTL8821AU USB WiFi limits (rtl8821au.c): only the 8821AU/8811AU (1x1) rtw88 IDs; no 8812AU/8814AU/8821CU. Bulk transfers need EHCI or xHCI (UHCI/OHCI companions have no bulk path). No IQ calibration, LC calibration, thermal power tracking, DIG, BT coexistence or by-rate/regulatory TX power tables: every rate uses the eFuse base index of the channel group. 20 MHz legacy rates only (no HT/VHT, aggregation or rate adaptation, no firmware H2C commands at all), no power save, and the same open/WPA2-PSK-CCMP limits as item 35; CCMP runs in software in both directions. The xHCI driver has one bulk-IN and one bulk-OUT ring, so the stick cannot stream at the same time as an ASIX dongle, an RNDIS phone or a mass-storage transfer on the same xHCI. Bring-up (eFuse + tables + firmware) is a few thousand control transfers with the BKL held and interrupts off, so the UI pauses for a few seconds on the first wifi command. A plugged-in stick always wins over the built-in Intel card; there is no command to pick the Intel card while it is attached.

  39. Mouse cursor limits: one fixed 24 px theme (no HiDPI size selection or user theme switch), no CSS url() cursors (the fallback keyword after the last comma is used) and no none/hidden cursor (it maps to the arrow). Floppy boots have only the built-in 16x16 arrow, because the lite pack has no room for the ~18 KB gzip bundle. Cirrus is two-colour, and its position cannot go negative, so near the top/left edge the hotspot is off by up to the image's hotspot offset. The Intel/Radeon image upload (16 KB, plus wbinvd on Intel) also runs 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 ~0x8bf20, ~16 KB below the 0x90000 wall.