1
0

5 Incheckningar 11a74497bc ... ee904a6a3c

Upphovsman SHA1 Meddelande Datum
  Johannes Zellner ee904a6a3c Decode images at display size and fetch chat media asynchronously 1 vecka sedan
  Johannes Zellner 8d63339700 Bring up the Gigabyte 970A-DS3P and fix SB950 OHCI input 1 vecka sedan
  Johannes Zellner e762867916 Add a Linux SDL3 host harness for the browser 1 vecka sedan
  Johannes Zellner 4148a04a2b Load and lay out arstechnica.com: TLS 1.2, jQuery/Alpine DOM, Tailwind CSS 1 vecka sedan
  Johannes Zellner 70a4a22f0f Keep the WM running while lsusb and storage wait on hardware 1 vecka sedan
84 ändrade filer med 6957 tillägg och 517 borttagningar
  1. 3 0
      .gitignore
  2. 267 75
      AGENTS.md
  3. 132 13
      Makefile
  4. 24 0
      acpi.c
  5. 3 0
      acpi.h
  6. 3 3
      asix.c
  7. 671 44
      browser.c
  8. 169 24
      browser_html.c
  9. 8 2
      browser_html.h
  10. 2 2
      docs/boot.html
  11. 17 11
      docs/cpu.html
  12. 8 3
      docs/development.html
  13. 51 15
      docs/drivers.html
  14. 1 1
      docs/filesystems.html
  15. 25 13
      docs/graphics.html
  16. 1 1
      docs/index.html
  17. 12 8
      docs/network.html
  18. 5 1
      docs/userland.html
  19. 8 3
      efi/main.c
  20. 2 0
      ehci.c
  21. 22 0
      host/curl_main.c
  22. 239 0
      host/fs.c
  23. 18 0
      host/fs.h
  24. 46 0
      host/heap.c
  25. 79 0
      host/host.c
  26. 25 0
      host/host.h
  27. 9 0
      host/include/ucmd_heap.h
  28. 92 0
      host/main.c
  29. 237 0
      host/net.c
  30. 15 0
      host/net.h
  31. 149 0
      host/proc.c
  32. 10 0
      host/proc.h
  33. 343 0
      host/syscall.c
  34. 137 0
      host/window.c
  35. 54 0
      host/window.h
  36. 152 0
      host/window_headless.c
  37. 461 0
      host/window_sdl3.c
  38. 5 2
      img.c
  39. 4 0
      img.h
  40. 67 2
      img_blit.c
  41. 261 19
      img_jpeg.c
  42. 116 4
      img_test.c
  43. 82 0
      ioapic.c
  44. 11 0
      ioapic.h
  45. 52 8
      js_browser.c
  46. 3 0
      js_browser.h
  47. 103 3
      js_prelude.js
  48. 7 2
      kernel.c
  49. 108 0
      mtrr.c
  50. 4 2
      ngui.c
  51. 1 0
      ngui.h
  52. 7 4
      nvidia.c
  53. 243 46
      ohci.c
  54. 55 2
      paging.c
  55. 2 0
      paging.h
  56. 3 4
      rndis.c
  57. 9 1
      sdhci.c
  58. 98 6
      thermal.c
  59. 12 4
      thermal.h
  60. 427 31
      tls.c
  61. 212 0
      tls_gcm.c
  62. 42 0
      tls_gcm.h
  63. 442 0
      tls_p256.c
  64. 18 0
      tls_p256.h
  65. 35 0
      tls_sha256.c
  66. 8 0
      tls_sha256.h
  67. 109 1
      tls_test.c
  68. 341 25
      ucmd_chat.c
  69. 1 1
      ucmd_cpuinfo.c
  70. 182 8
      ucmd_curl.c
  71. 9 0
      ucmd_lib.h
  72. 19 17
      ucmd_netmenu.c
  73. 3 3
      ucmd_sensors.c
  74. 1 1
      ucmd_view.c
  75. 1 0
      uhci.c
  76. 53 20
      uhttp.c
  77. 1 1
      uhttp.h
  78. 190 61
      usb.c
  79. 18 6
      usb.h
  80. 14 2
      usbhid.c
  81. 48 9
      usbmsc.c
  82. 21 2
      vesa_stage.S
  83. 3 1
      vga.c
  84. 6 0
      xhci.c

+ 3 - 0
.gitignore

@@ -34,4 +34,7 @@ chat_login_test
 chat-test-out/
 wpa_test
 wifi_store_test
+host/build/
+browser-host
+host-curl
 firmware/

+ 267 - 75
AGENTS.md

@@ -63,11 +63,14 @@ 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)
@@ -94,6 +97,15 @@ 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.  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 512 MB (`QEMU_MEM`, e.g. `make run QEMU_MEM=1G`),
   matching `MM_MAX_PHYS` in `phys.h`; all run and UEFI targets pass `-m`.
 - The command pack is the system rootfs: `cmds.pack` (NBPAK1), gzip-compressed
@@ -139,6 +151,13 @@ make clean
   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
@@ -162,7 +181,9 @@ make clean
    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, ≤1280px), writes mode info to `0x600` and the
+   (≥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
@@ -283,8 +304,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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 list and
-  LAPIC base; 4 MB table page mapping; malformed tables are ignored), `lapic.c/h`
+- **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
@@ -403,7 +427,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `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
-  1280x1024 canvas minus the chrome.  `SYS_WIN_PRESENT`
+  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
@@ -435,7 +459,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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, procedural icons and scrolling panes.
+  primitives, buttons, text input, procedural icons and scrolling panes
+  (`ngui_scroll`; `hide_bar` keeps wheel/key scrolling without drawing a
+  scrollbar).
   `files` (`ucmd_files.c`) is its first user; `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
@@ -493,8 +519,13 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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.  `vga_fb_lfb_wc()` reports the effective path and
-  `gfxbench` prints it. `nvidia.c`
+  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:
@@ -610,11 +641,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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 call `vfs_scan_poll(t0)` /
+  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.  So `storage` no longer freezes the WM.  `disk_probe()` skips
+  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
@@ -691,7 +725,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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 (PCIe, polled, C+ mode, 64-entry RX ring), `ne2000.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
@@ -754,8 +789,19 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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 only, stream-oriented record
-  layer, leaf SHA-256 fingerprint printed for a manual check.  Certificates
+  `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
@@ -980,14 +1026,27 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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).
-  Every HCD delay goes through `usb_delay_ms()`: inside a scan
-  (`usb_scan`/`usb_hotplug_poll`) owned by a sleepable process — `lsusb`,
-  the kworker's HID rescan/hotplug enumeration — it sleeps and drops the
-  BKL, so port resets no longer stall the system; elsewhere it busy-waits.
-  While such a scan sleeps, `usb_scan_foreign()` makes the `usb.c`
-  wrappers refuse other contexts (control/bulk transfers fail, interrupt
-  polls return 0, `usb_port_connected` reports 1) and `usbhid_poll` skips
-  its tick; USB NICs, the RTL8821AU and USB disks see a transient error.
+  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.
@@ -1057,10 +1116,19 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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.  Platforms
-  without DTS (QEMU, Pentium) hide it.
+  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 exposes three temperatures and three fan tachometers), used
+  (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
@@ -1228,8 +1296,23 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `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, table colspan and percentage columns, and basic `float: left/right`
-  columns.
+  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 (min-width/max-width)` blocks are evaluated against the browser
   canvas width when the page is parsed; `@import`/`@keyframes` are skipped.
   `@font-face` loads one regular TTF per family from a local path or HTTP URL
@@ -1313,14 +1396,36 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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`; 512 KB files / 8 MP decodes) are
+  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.  Navigation calls `heap_reset()` and unmaps the whole
+  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
@@ -1354,7 +1459,15 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `pathname`/`search`/`hash`/`origin`) resolved against the page URL.
   `document` exposes `createElement`/`createTextNode`/`createComment`/
   `createDocumentFragment`/`createAttribute`, `documentElement`/`body`/
-  `head` and `readyState`; `navigator`, `history`, `matchMedia`,
+  `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
@@ -1499,12 +1612,22 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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 use the same
-  uhttp connection and cookie jar, are fetched one per main-loop pass, and
-  are decoded by the in-tree image library (PNG/JPEG/GIF first
-  frame/BMP/TGA/PNM/ICO/PAM).  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.
+  `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.  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
@@ -1550,9 +1673,16 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   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`; `img_draw()`
+  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).  Progressive
+  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
@@ -1563,7 +1693,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `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 and draws them with `img_draw()`.  Host
+  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
@@ -1641,7 +1772,7 @@ TX/RX self-test), `netreset`
 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 client (no certificate
+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.
@@ -1832,7 +1963,14 @@ 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.
+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
@@ -1866,15 +2004,29 @@ so addresses do not collide.
   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 and no DoneHead handling:
-  software just harvests retired TDs. **TDs must be initialized with
+  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).
+  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
@@ -1953,10 +2105,15 @@ so addresses do not collide.
   (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),
-  `CCS` low or a few TD errors detach a device.  A full scan (`lsusb`) bumps
-  `usb_generation()`, which makes `usbhid` detach and rescan, so `lsusb`
-  can't leave the devices dead.  The BIOS PS/2 legacy emulation is
+  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
@@ -2126,8 +2283,14 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 ## Known issues (candidates for future tasks)
 
-1. `serial_puthex` (`serial.c`) uses `"01234589ABCDEF"` — digits **6 and 7 are
-   missing** (bug).
+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).
@@ -2152,7 +2315,7 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    with `--gc-sections`; the current full pack with the UI fonts, both
    WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes,
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
-   bytes) and `install/kernel.bin` is ~1.75 MiB gzip (~260 KB under the
+   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 ~930 KiB gzip and
    deliberately omits the firmware and `install/kernel.bin`.  `libdeflate-gzip -12` is still preferred.  Over
@@ -2162,8 +2325,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     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;
-    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.
+    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
@@ -2183,10 +2349,15 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     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.  It is fine for the
-    viewer's static frames, but a browser showing many large inline images
-    should cache a scaled bitmap (or use decode-at-display-scale) instead of
-    rescaling on every repaint.
+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
@@ -2215,9 +2386,10 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     (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
-    ~0x897a0 (with the 6200/6300 DVM layer, the RTL8821AU driver and the
-    8×16 boot-console font), ~26 KB below the `0x90000` wall, and the
-    remaining limit is kernel code/buffers only.
+    ~0x8a440 (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), ~23 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/
@@ -2240,9 +2412,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     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.
-    Also missing: `defer`/`async` ordering, `DOMParser`/
-    `document.implementation.createDocument` (DOMPurify throws, so the
-    Cloudron login footer is not rendered), canvas/2D contexts, user-state
+    `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 only (no box, background, counters or `url()` images, and
@@ -2269,7 +2444,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     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 and `repeat(auto-fit, minmax(...))` grids, inline-block
+    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
@@ -2308,12 +2484,20 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     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.  Images are decoded into a per-image `img_estimate()`-sized
-    arena (reused per page) and kept as a box-sized display bitmap (256
-    images within a 4 M-pixel budget, 512 KB files / 8 MP decodes); large
-    screenshots still need a multi-megabyte decode arena that can fail on a
-    fragmented heap, and the scaled bitmaps live until navigation.  `img_draw` rescales the
-    cached bitmap on every repaint.  Lazy
+    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
@@ -2337,18 +2521,23 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 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 ≤ 1280, `pitch * height` ≤ 8 MB and the
-    framebuffer below 4 GB; otherwise the kernel starts headless (serial only).
+    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).
-    There is no IOAPIC setup: OVMF delivers the ISA IRQs through the 8259
-    path, but a platform that routes them through the IOAPIC may need a
-    mask-all step after ACPI init.  UEFI runtime services are not used, so
+    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.
+    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
@@ -2489,7 +2678,10 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     render inline up to the 4 MB fetch / 4 MP decode caps (first GIF frame;
     WebP/AVIF/SVG are not decoded), file attachments are still text-only,
     messages over 4 KB are truncated, history holds 240 messages, times are
-    UTC and text is Latin-1.  Network calls block the UI for their duration.
+    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`)

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 132 - 13
Makefile


+ 24 - 0
acpi.c

@@ -43,6 +43,8 @@ static unsigned int ids[ACPI_MAX_CPUS];
 static unsigned int ncpu;
 static unsigned int bsp_apic;
 static unsigned int lapic_base;
+static unsigned int ioapic_bases[ACPI_MAX_IOAPICS];
+static unsigned int nioapics;
 static int acpi_ok;
 /* FADT "century" register (offset 108), 0 when absent.  The RTC uses it to
  * keep the two-digit CMOS year in the right century; rtc.c only writes it
@@ -256,6 +258,12 @@ static void parse_madt(const struct acpi_sdt *madt)
 			/* Processor Local APIC: flags bit 0 = enabled. */
 			if ((p[i + 4] & 1) && ncpu < ACPI_MAX_CPUS)
 				ids[ncpu++] = p[i + 3];
+		} else if (type == 1 && elen >= 12) {
+			/* I/O APIC: id, 32-bit MMIO base, GSI base. */
+			unsigned int base = *(const unsigned int *)(p + i + 4);
+
+			if (base && nioapics < ACPI_MAX_IOAPICS)
+				ioapic_bases[nioapics++] = base;
 		} else if (type == 5 && elen >= 12) {
 			/* Local APIC Address Override (64-bit). */
 			unsigned int lo = *(const unsigned int *)(p + i + 4);
@@ -277,6 +285,7 @@ int acpi_init(void)
 
 	acpi_ok = 0;
 	ncpu = 0;
+	nioapics = 0;
 	rtc_century_reg = 0;
 	bsp_apic = cpuid_apic_id();
 	if (bsp_apic == 0xFFFFFFFFu)
@@ -333,6 +342,16 @@ unsigned int acpi_lapic_base(void)
 	return lapic_base;
 }
 
+unsigned int acpi_ioapic_count(void)
+{
+	return acpi_ok ? nioapics : 0;
+}
+
+unsigned int acpi_ioapic_base(unsigned int index)
+{
+	return (acpi_ok && index < nioapics) ? ioapic_bases[index] : 0;
+}
+
 unsigned int acpi_rtc_century_reg(void)
 {
 	return rtc_century_reg;
@@ -356,4 +375,9 @@ void acpi_dump(void)
 		serial_putdec(SERIAL_COM1, ids[i]);
 	}
 	serial_puts(SERIAL_COM1, "\n");
+	for (i = 0; i < nioapics; i++) {
+		serial_puts(SERIAL_COM1, "acpi: ioapic ");
+		serial_puthex(SERIAL_COM1, ioapic_bases[i]);
+		serial_puts(SERIAL_COM1, "\n");
+	}
 }

+ 3 - 0
acpi.h

@@ -7,6 +7,7 @@
 #define ACPI_H
 
 #define ACPI_MAX_CPUS 8
+#define ACPI_MAX_IOAPICS 4
 
 /* Returns 1 when a usable MADT with at least one local APIC entry was found.
  * acpi_cpu_count() then includes the BSP as entry 0. */
@@ -16,6 +17,8 @@ unsigned int acpi_cpu_count(void);
 unsigned int acpi_cpu_apic_id(unsigned int index);
 unsigned int acpi_bsp_apic_id(void);
 unsigned int acpi_lapic_base(void);
+unsigned int acpi_ioapic_count(void);
+unsigned int acpi_ioapic_base(unsigned int index);
 
 /* CMOS register holding the RTC century byte from the FADT, or 0 when the
  * firmware does not provide one (old non-ACPI hardware). */

+ 3 - 3
asix.c

@@ -96,11 +96,11 @@ static unsigned int rx_pos, rx_end;
 
 
 
+/* Sleeps inside a sleepable bus scan (the probe runs there); busy-waits
+ * in the netdev paths, which may run with interrupts off. */
 static void delay_ms(unsigned int ms)
 {
-	unsigned int t0 = get_ticks_ms();
-	while (get_ticks_ms() - t0 < ms)
-		;
+	usb_delay_ms(ms);
 }
 
 static int read_cmd(unsigned char cmd, unsigned short value,

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 671 - 44
browser.c


+ 169 - 24
browser_html.c

@@ -108,6 +108,7 @@ static const struct tag_name tag_names[] = {
 	{ "style", BR_TAG_STYLE }, { "script", BR_TAG_SCRIPT },
 	{ "meta", BR_TAG_META }, { "link", BR_TAG_LINK },
 	{ "base", BR_TAG_BASE }, { "noscript", BR_TAG_NOSCRIPT },
+	{ "template", BR_TAG_TEMPLATE },
 	{ "p", BR_TAG_P }, { "div", BR_TAG_DIV }, { "span", BR_TAG_SPAN },
 	{ "a", BR_TAG_A }, { "b", BR_TAG_B }, { "strong", BR_TAG_STRONG },
 	{ "i", BR_TAG_I }, { "em", BR_TAG_EM }, { "u", BR_TAG_U },
@@ -510,6 +511,12 @@ static unsigned int decode_text(const char *s, unsigned int len, char *out,
 
 /* Store an attribute string (entity-decoded) in the attr arena.  0 = no
  * space / empty. */
+/* Utility-class pages (Tailwind) carry 300-600 byte class lists; a short
+ * cap silently dropped every class past it (arstechnica's header lost its
+ * background, alignment and all responsive variants). */
+#define BR_CLASS_MAX      2048
+#define BR_STYLE_ATTR_MAX 2048
+
 static unsigned int store_attr(struct br_doc *d, const char *s,
 			       unsigned int len, unsigned int limit)
 {
@@ -1640,9 +1647,11 @@ static void attr_note_known(struct br_doc *d, struct br_node *n,
 	if (same_string(name, "id"))
 		n->id_off = len ? store_attr(d, value, len, 64) : 0;
 	else if (same_string(name, "class"))
-		n->class_off = len ? store_attr(d, value, len, 120) : 0;
+		n->class_off = len ? store_attr(d, value, len,
+						       BR_CLASS_MAX) : 0;
 	else if (same_string(name, "style"))
-		n->style_off = len ? store_attr(d, value, len, 240) : 0;
+		n->style_off = len ? store_attr(d, value, len,
+						       BR_STYLE_ATTR_MAX) : 0;
 	else if (same_string(name, "href"))
 		n->href_off = len ? store_attr(d, value, len, 480) : 0;
 	else if (same_string(name, "src"))
@@ -2197,11 +2206,13 @@ static void parse_attrs(struct br_doc *d, struct br_node *n,
 		if (str_eq(name, "href"))
 			n->href_off = store_attr(d, s + vstart, vlen, 480);
 		else if (str_eq(name, "class"))
-			n->class_off = store_attr(d, s + vstart, vlen, 120);
+			n->class_off = store_attr(d, s + vstart, vlen,
+						  BR_CLASS_MAX);
 		else if (str_eq(name, "id"))
 			n->id_off = store_attr(d, s + vstart, vlen, 64);
 		else if (str_eq(name, "style"))
-			n->style_off = store_attr(d, s + vstart, vlen, 240);
+			n->style_off = store_attr(d, s + vstart, vlen,
+						  BR_STYLE_ATTR_MAX);
 		else if (str_eq(name, "src"))
 			n->src_off = store_attr(d, s + vstart, vlen, 400);
 		else if (str_eq(name, "alt"))
@@ -2403,6 +2414,7 @@ enum {
 	PROP_VIS_HIDDEN, PROP_OPACITY_HIDDEN, PROP_OVERFLOW_HIDDEN,
 	PROP_FILL_MODE, PROP_FILL, PROP_STROKE_MODE, PROP_STROKE,
 	PROP_STROKE_W, PROP_FILL_RULE, PROP_CONTENT,
+	PROP_ASPECT_W, PROP_ASPECT_H,
 	PROP_COUNT
 };
 
@@ -3934,6 +3946,63 @@ static int parse_grid_track(const char *s, unsigned int len,
 	return 1;
 }
 
+/* N of "repeat(N, 1fr)" / "repeat(N, minmax(0, 1fr))", or of N >= 3
+ * space-separated "1fr" tracks; 0 for anything else (fixed or mixed tracks
+ * keep the two-column path). */
+static int grid_repeat_count(const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+	int n = 0;
+
+	while (i < len && is_space(s[i]))
+		i++;
+	if (i + 7 <= len && ci_eq_n(s + i, "repeat(", 7)) {
+		i += 7;
+		while (i < len && is_space(s[i]))
+			i++;
+		while (i < len && s[i] >= '0' && s[i] <= '9') {
+			n = n * 10 + (s[i] - '0');
+			i++;
+		}
+		if (n < 1 || n > 12)
+			return 0;
+		while (i < len && (is_space(s[i]) || s[i] == ','))
+			i++;
+		if (i + 3 <= len && ci_eq_n(s + i, "1fr", 3))
+			return n;
+		if (i + 7 <= len && ci_eq_n(s + i, "minmax(", 7)) {
+			i += 7;
+			while (i < len && is_space(s[i]))
+				i++;
+			if (i < len && s[i] == '0') {
+				i++;
+				while (i < len && (is_space(s[i]) ||
+						   s[i] == ',' || s[i] == 'p' ||
+						   s[i] == 'x'))
+					i++;
+				if (i + 3 <= len && ci_eq_n(s + i, "1fr", 3))
+					return n;
+			}
+		}
+		return 0;
+	}
+	/* "1fr 1fr 1fr" */
+	for (;;) {
+		while (i < len && is_space(s[i]))
+			i++;
+		if (i >= len)
+			break;
+		if (i + 3 <= len && ci_eq_n(s + i, "1fr", 3) &&
+		    (i + 3 == len || is_space(s[i + 3]))) {
+			n++;
+			i += 3;
+		} else {
+			return 0;
+		}
+	}
+	return n >= 3 ? n : 0;
+}
+
 static int parse_grid_cols(const char *s, unsigned int len,
 			   unsigned short val[2], unsigned char kind[2])
 {
@@ -5135,7 +5204,20 @@ static void parse_decls(struct br_doc *d, const char *s,
 						break;
 					}
 			}
-			if (contains_ci_len(v, vl, "auto-fit") ||
+			if (grid_repeat_count(v, vl) >= 1) {
+				/* repeat(N, 1fr) / repeat(N, minmax(0,1fr)):
+				 * Tailwind's grid-cols-N.  N equal columns
+				 * (GRID_FIXED + N); one column is plain block
+				 * flow, which also resets a smaller breakpoint's
+				 * count. */
+				int cnt = grid_repeat_count(v, vl);
+
+				decl_add(out, nout, PROP_GRID_AUTO,
+					 cnt >= 2 ? BR_GRID_FIXED + cnt : 0,
+					 important);
+				decl_add(out, nout, PROP_GRID_NCOLS, 0,
+					 important);
+			} else if (contains_ci_len(v, vl, "auto-fit") ||
 			    contains_ci_len(v, vl, "auto-fill")) {
 				unsigned int mp = 0;
 				int found = 0;
@@ -5314,6 +5396,48 @@ static void parse_decls(struct br_doc *d, const char *s,
 				 css_collect_only ? 0 :
 				 parse_content(d, s + vstart, vend - vstart),
 				 important);
+		} else if (str_eq(prop, "aspect-ratio")) {
+			/* "16/9", "16 / 9", "1.5" (hundredths), "auto": the
+			 * preferred height of an auto-height box. */
+			unsigned int q = vstart;
+			unsigned int a[2] = { 0, 1 }, k;
+
+			for (k = 0; k < 2; k++) {
+				unsigned int whole = 0, frac = 0, sc = 1;
+
+				while (q < vend && is_space(s[q]))
+					q++;
+				if (q >= vend || ((s[q] < '0' || s[q] > '9') &&
+						  s[q] != '.'))
+					break;
+				while (q < vend && s[q] >= '0' && s[q] <= '9')
+					whole = whole * 10 +
+						(unsigned int)(s[q++] - '0');
+				if (q < vend && s[q] == '.') {
+					q++;
+					while (q < vend && s[q] >= '0' &&
+					       s[q] <= '9') {
+						if (sc < 100) {
+							frac = frac * 10 +
+							    (unsigned int)(s[q] - '0');
+							sc *= 10;
+						}
+						q++;
+					}
+				}
+				a[k] = whole * 100 + frac * (100 / sc);
+				while (q < vend && is_space(s[q]))
+					q++;
+				if (k == 0 && (q >= vend || s[q] != '/')) {
+					a[1] = 100;
+					break;
+				}
+				q++;
+			}
+			if (a[0] > 32000 || a[1] > 32000 || !a[1])
+				a[0] = a[1] = 0;
+			decl_add(out, nout, PROP_ASPECT_W, (int)a[0], important);
+			decl_add(out, nout, PROP_ASPECT_H, (int)a[1], important);
 		} else if (str_eq(prop, "box-sizing")) {
 			int bb = (vend - vstart >= 10 &&
 				  ci_eq_n(s + vstart, "border-box", 10));
@@ -6018,38 +6142,49 @@ static unsigned int rule_hash(const char *s, unsigned int len)
  * possibly match a node instead of scanning every rule. */
 static unsigned int sel_skip_group(const char *s, unsigned int i,
 				   unsigned int len);
+static unsigned int sel_ident(const char *s, unsigned int i, unsigned int len,
+			      char *out, unsigned int cap, unsigned int *olen);
 
 static void rule_index_add(struct br_doc *d, unsigned int idx,
 			   const char *key, unsigned int len)
 {
-	unsigned int i, cpos = 0, clen = 0, ipos = 0, ilen = 0;
+	/* Unescaped names: Tailwind's ".md\:flex" must be filed under
+	 * "md:flex", the class the element carries, not under "md". */
+	char cname[96], iname[96];
+	unsigned int i, clen = 0, ilen = 0;
 	unsigned short *head;
 
 	for (i = 0; i < len; i++) {
+		if (key[i] == '\\') {
+			i++;
+			continue;
+		}
 		if (key[i] == '(' || key[i] == '[') {
 			/* :not(.x) / [href="a.b"] must not pick a bucket */
 			i = sel_skip_group(key, i, len) - 1;
 			continue;
 		}
 		if (key[i] == '.' || key[i] == '#') {
-			unsigned int st = i + 1, n = 0;
-
-			while (st + n < len && is_ident(key[st + n]))
-				n++;
-			if (key[i] == '#') {
-				ipos = st;
-				ilen = n;
-			} else if (n) {
-				cpos = st;
-				clen = n;
+			char tmp[96];
+			unsigned int n, e;
+
+			e = sel_ident(key, i + 1, len, tmp, sizeof(tmp), &n);
+			if (n && n + 1 < sizeof(tmp)) {
+				if (key[i] == '#') {
+					memcpy(iname, tmp, n);
+					ilen = n;
+				} else {
+					memcpy(cname, tmp, n);
+					clen = n;
+				}
 			}
-			i = st + n - 1;
+			i = e - 1;
 		}
 	}
 	if (ilen)
-		head = &d->rule_bucket[rule_hash(key + ipos, ilen)];
+		head = &d->rule_bucket[rule_hash(iname, ilen)];
 	else if (clen)
-		head = &d->rule_bucket[rule_hash(key + cpos, clen)];
+		head = &d->rule_bucket[rule_hash(cname, clen)];
 	else if (len == 5 && ci_eq_n(key, ":root", 5))
 		head = &d->rule_tag[BR_TAG_HTML];
 	else if (len && is_ident(key[0])) {
@@ -7594,6 +7729,12 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 	case PROP_CONTENT:
 		st->content = (unsigned short)dcl->val;
 		break;
+	case PROP_ASPECT_W:
+		st->aspect_w = (unsigned short)dcl->val;
+		break;
+	case PROP_ASPECT_H:
+		st->aspect_h = (unsigned short)dcl->val;
+		break;
 	case PROP_NOWRAP:
 		st->nowrap = (unsigned char)(dcl->val != 0);
 		break;
@@ -7691,7 +7832,7 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 		st->flex_col = (unsigned char)(dcl->val != 0);
 		break;
 	case PROP_FLEX_WRAP:
-		st->flex_wrap = (unsigned char)(dcl->val != 0);
+		st->flex_wrap = (unsigned char)(dcl->val == 1);  /* 2: nowrap */
 		break;
 	case PROP_JUSTIFY:
 		st->justify = (unsigned char)dcl->val;
@@ -7709,7 +7850,7 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 		st->grid_slot = (unsigned char)dcl->val;
 		break;
 	case PROP_GRID_AUTO:
-		st->grid_auto = (unsigned char)(dcl->val != 0);
+		st->grid_auto = (unsigned char)dcl->val;  /* 1 auto-fit, >16 fixed */
 		break;
 	case PROP_POS:
 		st->pos = (unsigned char)dcl->val;
@@ -7851,6 +7992,7 @@ void br_style_for(struct br_doc *d, unsigned int node,
 	out->justify = out->align_items = 0;
 	out->grid_ncols = out->grid_gap = out->grid_slot = 0;
 	out->grid_auto = 0;
+	out->aspect_w = out->aspect_h = 0;
 	out->pos = out->left_set = out->top_set = 0;
 	out->right_set = out->bottom_set = 0;
 	out->left = out->top = out->right = out->bottom = 0;
@@ -7886,6 +8028,7 @@ void br_style_for(struct br_doc *d, unsigned int node,
 	case BR_TAG_BASE:
 	case BR_TAG_SCRIPT:
 	case BR_TAG_STYLE:
+	case BR_TAG_TEMPLATE:                   /* inert until cloned by script */
 		out->display = BR_DISPLAY_NONE;
 		break;
 	case BR_TAG_BODY:
@@ -8496,16 +8639,16 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 				int p = find_ci(html, len, "</script", 8, i);
 				unsigned int end = p >= 0 ? (unsigned int)p : len;
 				unsigned int idx;
+				struct br_script *script = 0;
 
 				int kind = script_is_javascript(html + attr_start,
 							attr_end - attr_start);
 
 				if (kind) {
 					if (d->nscripts < BR_MAX_SCRIPTS) {
-						struct br_script *script =
-							&d->scripts[d->nscripts++];
-
+						script = &d->scripts[d->nscripts++];
 						script->module = kind == 2;
+						script->node = 0;
 						script->off = i;
 						script->len = end > i ? end - i : 0;
 						script->src_off = script_src_attr(
@@ -8525,6 +8668,8 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 					parse_attrs(d, &d->nodes[idx],
 						    html + attr_start,
 						    attr_end - attr_start);
+				if (script)
+					script->node = idx;
 				if (idx && !kind && end > i)
 					append_raw_text(d, idx, html + i, end - i);
 				i = p >= 0 ? (unsigned int)p + 8 : len;

+ 8 - 2
browser_html.h

@@ -57,6 +57,8 @@
 #define BR_DISPLAY_FLEX   3
 #define BR_DISPLAY_GRID   4
 #define BR_DISPLAY_INLINE_BLOCK 5
+
+#define BR_GRID_FIXED 16           /* grid_auto: fixed column count base */
 /* Decl-only bit: display:inline-flex is FLEX plus st->inline_flex. */
 #define BR_DISPLAY_INLINE_FLAG 0x40
 
@@ -101,7 +103,8 @@ enum br_tag {
 	BR_TAG_ADDRESS, BR_TAG_MARK, BR_TAG_TIME, BR_TAG_ABBR, BR_TAG_CITE,
 	BR_TAG_Q, BR_TAG_S, BR_TAG_STRIKE, BR_TAG_SUB, BR_TAG_SUP,
 	BR_TAG_BGSOUND, BR_TAG_EMBED, BR_TAG_PARAM, BR_TAG_SOURCE,
-	BR_TAG_TRACK, BR_TAG_WBR, BR_TAG_AREA, BR_TAG_COL, BR_TAG_COLGROUP
+	BR_TAG_TRACK, BR_TAG_WBR, BR_TAG_AREA, BR_TAG_COL, BR_TAG_COLGROUP,
+	BR_TAG_TEMPLATE
 };
 
 struct br_style {
@@ -138,7 +141,8 @@ struct br_style {
 	unsigned char grid_ncols;   /* 1 or 2 supported */
 	unsigned char grid_gap;     /* px */
 	unsigned char grid_slot;    /* 0 auto, 1 full, 2 left, 3 right */
-	unsigned char grid_auto;    /* repeat(auto-fit, minmax(width, 1fr)) */
+	unsigned char grid_auto;    /* 1: repeat(auto-fit, minmax(width, 1fr));
+				     * BR_GRID_FIXED + N: N equal columns */
 	unsigned char pos;          /* 0 static, 1 absolute, 2 fixed, 3 relative */
 	unsigned char left_set, top_set, right_set, bottom_set;
 	signed short left, top, right, bottom;
@@ -198,6 +202,7 @@ struct br_style {
 	unsigned short stroke_w;
 	unsigned char inline_flex;  /* display:inline-flex (not inherited) */
 	unsigned short content;     /* ::before/::after content: index + 1 */
+	unsigned short aspect_w, aspect_h; /* aspect-ratio (x100), 0 = auto */
 };
 
 #define BR_PAINT_UNSET   0    /* fill: black, stroke: none */
@@ -267,6 +272,7 @@ struct br_script {
 	unsigned int len;
 	unsigned int src_off;   /* src attribute in the attr arena, 0 if inline */
 	unsigned int module;    /* type="module": run as an ES module */
+	unsigned int node;      /* the <script> element (document.currentScript) */
 };
 
 struct br_doc {

+ 2 - 2
docs/boot.html

@@ -171,7 +171,7 @@
 			<li>Probe the <code>INT 15h</code> E820 memory map into <code>0x1000</code>.</li>
 			<li>Enable A20 and read the <code>NBROOT1</code> rootfs header at the boot sector's <code>pack_lba</code> field.</li>
 			<li>Copy the compressed pack directly to <code>0x900000</code> above the 8 MB VGA-shadow reserve, in 16 KB staging chunks at <code>0x3000</code> (one <code>INT 13h</code> per chunk: 32 sectors over EDD, or up to the end of the track over CHS, which never crosses a 64 KB DMA boundary; a BIOS that refuses a multi-sector request falls back to one sector per call), using a temporary flat protected-mode <code>rep movsb</code>. The X201 BIOS's <code>INT 15h AH=87h</code> block move silently copies zeros to this range, so the CPU copy is used instead.</li>
-			<li>Pick the best VBE mode: at least 16 bpp, a linear framebuffer, it must fit the card's VRAM, and the width must be at most 1280 pixels. Mode information is written to <code>0x600</code>; the 12-dword boot-info block goes to <code>0x500</code>.</li>
+			<li>Pick the best VBE mode: at least 16 bpp, a linear framebuffer, it must fit the card's VRAM, at most 1920 pixels wide, its pitch × height must fit the 8 MB VGA-shadow reserve, and it must stay within 2 M pixels so a full-screen RGB565 canvas fits the 4 MB window slot. Mode information is written to <code>0x600</code>; the 12-dword boot-info block goes to <code>0x500</code>.</li>
 			<li>Enter protected mode and jump to <code>kernel_entry</code>.</li>
 		</ol>
 		<p>
@@ -204,7 +204,7 @@
 			not execute any of the legacy boot chain. Instead it:
 		</p>
 		<ol>
-			<li>Selects a GOP mode with BGRX or RGBX 32bpp, width at most 1280, <code>pitch × height</code> at most 8 MB, and a framebuffer below 4 GB.</li>
+			<li>Selects a GOP mode with BGRX or RGBX 32bpp, width at most 1920, <code>pitch × height</code> at most 8 MB (1920×1080 fits at 8.29 MB), and a framebuffer below 4 GB. With 32bpp, that size limit also keeps a full-screen RGB565 canvas inside the 4 MB window slot; the VBE stage additionally checks 2 M pixels because a 24bpp 1920×1200 mode would otherwise pass the shadow check.</li>
 			<li>Calls <code>GetMemoryMap</code> and converts the firmware map into the kernel's E820 format at <code>0x1000</code>.</li>
 			<li>Locates the parent whole-disk Block I/O handle from the ESP device path, reads the P1 boot sector and P2 <code>NBROOT1</code> header, and stages the kernel below 4 GB and the gzip pack below the 512 MB identity window. The kernel/pack embedded in <code>BOOTX64.EFI</code> are a fallback only.</li>
 			<li>Writes the boot-info and framebuffer blocks, calls <code>ExitBootServices</code>, then copies a 192-byte trampoline to <code>0x800</code>.</li>

+ 17 - 11
docs/cpu.html

@@ -4,7 +4,7 @@
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>CPU &amp; Scheduling | NebOS Architecture</title>
-<meta name="description" content="NebOS CPU architecture: GDT/TSS, PIC/PIT and LAPIC interrupts, ACPI SMP bring-up, CFS-lite scheduling, wait queues, the big kernel lock, idle and power management.">
+<meta name="description" content="NebOS CPU architecture: GDT/TSS, PIC/PIT and LAPIC interrupts, IOAPIC masking, ACPI SMP bring-up, CFS-lite scheduling, wait queues, the big kernel lock, idle, power and AMD/Intel thermal management.">
 <link rel="icon" href="favicon.svg" type="image/svg+xml">
 <link rel="stylesheet" href="style.css">
 </head>
@@ -81,9 +81,12 @@
 	<section id="interrupts">
 		<h2>Interrupts &amp; timers</h2>
 		<p>
-			The BSP keeps the legacy 8259 PIC and PIT. Device IRQs stay on the
-			BSP because there is no IOAPIC driver. APs mask their LINT0/LINT1
-			inputs and use only their local APIC timer and IPIs.
+			The BSP keeps the legacy 8259 PIC and PIT; there is no IOAPIC
+			driver. After ACPI init the kernel masks every normal IOAPIC
+			redirection entry (leaving ExtINT entries alone, in case the 8259
+			is routed through an IOAPIC pin), so firmware-left vectors cannot
+			collide with the PIC vectors or the LAPIC timer. APs mask their
+			LINT0/LINT1 inputs and use only their local APIC timer and IPIs.
 		</p>
 		<div class="table-wrap">
 			<table>
@@ -169,9 +172,12 @@
 			drawing fast paths would <code>#UD</code>.
 		</p>
 		<div class="warn">
-			<p><strong>No IOAPIC.</strong> Device IRQs never reach an AP, and
-			<code>pit_irq_stub</code> is BSP-only. A platform that routes ISA IRQs
-			through the IOAPIC would need a mask-all setup step after ACPI init.</p>
+			<p><strong>No IOAPIC driver.</strong> Device IRQs never reach an AP,
+			and <code>pit_irq_stub</code> is BSP-only. The kernel masks the
+			IOAPIC's normal redirection entries after ACPI init
+			(<span class="file">ioapic.c</span>) and keeps the 8259 path on
+			LAPIC LINT0; ExtINT entries survive so firmware that routes the
+			8259 through an IOAPIC pin still works.</p>
 		</div>
 	</section>
 
@@ -349,8 +355,8 @@
 			<li><strong>Nehalem/Westmere P-states.</strong> <code>power_init</code> enables SpeedStep, raises the package C-state limit to C6 when unlocked, reads min/max ratios from <code>PLATFORM_INFO</code> and starts at the maximum non-turbo ratio. The target ratio goes in bits 15:8 of <code>IA32_PERF_CTL</code> with the low byte zero.</li>
 			<li><strong>Airmont/Braswell P-states.</strong> Family 6 model <code>0x4C</code> reads the Atom ratio/VID MSRs (<code>0x66A..0x66D</code>), <code>MSR_FSB_FREQ</code> and the FSB table. The N3060 reports pstates 6..20, BCLK 80 MHz (1600 MHz nominal), turbo pstate 31 (2480 MHz) and VID 0x2D..0x3C. <code>power_init</code> enters at max non-turbo and the governor drops to pstate 6 (480 MHz); <code>IA32_PERF_CTL</code> carries the pstate in 15:8 and the Linux-interpolated VID in 7:0. Turbo is detected but not requested. The probe deliberately avoids package/power-SKU MSRs; an unsupported <code>rdmsr</code> before the IDT triple-faults.</li>
 			<li><strong>Governor.</strong> A 100 ms window picks min/max/linear target pstates; short busy streaks jump to max immediately. Each CPU writes its own <code>IA32_PERF_CTL</code>; <code>cpufreq [auto|min|max|off|&lt;pstate&gt;]</code> overrides it, and <code>SYS_CPUFREQ</code> exposes the same auto/min/max/off mode to the control panel's Power mode tile.</li>
-			<li><strong>Telemetry.</strong> <code>power</code> prints effective MHz from APERF/MPERF, the current/requested pstate and, on Airmont, the FSB, nominal MHz, turbo pstate/VID, VID range and live <code>PERF_CTL</code>; <code>sensors</code> prints DTS, board sensors and both EC types; <code>powerinfo</code> prints the AC adapter and battery state, and the WM top bar shows the temperature plus a far-right AC plug or level-filled battery icon (percentage tooltip below it on hover) on ThinkPads and Chromebooks.</li>
-			<li><strong>Thermal.</strong> Each CPU samples its DTS once a second from its scheduler tick; the hottest core is exposed to ring 3. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem/Westmere, the coretemp 90 °C table on Airmont, and the Bonnell table on older Atoms.</li>
+			<li><strong>Telemetry.</strong> <code>power</code> prints effective MHz from APERF/MPERF, the current/requested pstate and, on Airmont, the FSB, nominal MHz, turbo pstate/VID, VID range and live <code>PERF_CTL</code>; <code>sensors</code> prints the CPU temperature, board sensors and both EC types; <code>powerinfo</code> prints the AC adapter and battery state, and the WM top bar shows the temperature plus a far-right AC plug or level-filled battery icon (percentage tooltip below it on hover) on ThinkPads and Chromebooks.</li>
+			<li><strong>Thermal.</strong> On Intel, each CPU samples its DTS once a second from its scheduler tick; the hottest core is exposed to ring 3. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem/Westmere, the coretemp 90 °C table on Airmont, and the Bonnell table on older Atoms. On AMD family 15h models below <code>0x60</code> (Bulldozer/Piledriver/Steamroller), <span class="file">thermal.c</span> reads the package Tctl from <code>D18F3xA4</code> at PCI <code>0:18.3</code> (k10temp's <code>(raw × 125) m°C</code>, with the 49 °C range offset when bits 17:16 are both set) and publishes it to every CPU from the kworker under the BKL; PCI config space is deliberately not touched from the per-CPU timer interrupt.</li>
 			<li><strong>Limits.</strong> Package C-states/S0ix remain firmware-managed; Airmont reports no C3/C6 residency and does not request the turbo pstate. The explicit <code>idle c6</code> override is the Nehalem <code>0x20</code> hint; use <code>idle auto</code> for the Airmont C6N (<code>0x58</code>) path.</li>
 		</ul>
 	</section>
@@ -362,10 +368,10 @@
 			<li><code>process.c</code>, <code>process.h</code> — PCBs and lifecycle</li>
 			<li><code>switch.S</code> — context switch</li>
 			<li><code>tss.c</code>, <code>tss.h</code> — per-CPU TSS</li>
-			<li><code>acpi.c</code>, <code>lapic.c</code>, <code>smp.c</code> — SMP</li>
+			<li><code>acpi.c</code>, <code>ioapic.c</code>, <code>lapic.c</code>, <code>smp.c</code> — SMP and IOAPIC masking</li>
 			<li><code>ap_tramp.S</code> — AP startup blob</li>
 			<li><code>timer.S</code>, <code>idle.c</code>, <code>power.c</code></li>
-			<li><code>thermal.c</code> — DTS sampling</li>
+			<li><code>thermal.c</code> — Intel DTS and AMD D18F3xA4 sampling</li>
 			<li><code>spinlock.h</code> — IRQ-safe spinlocks</li>
 		</ul>
 	</section>

+ 8 - 3
docs/development.html

@@ -168,6 +168,7 @@
 					<tr><td><code>make run-net</code></td><td>Add a PCI NE2000 on QEMU's slirp network with host port 8080 forwarded.</td></tr>
 					<tr><td><code>make run-rndis</code></td><td>Boot with <code>qemu-xhci</code> and QEMU's full-speed <code>usb-net</code> RNDIS device on slirp; the tethering link gets DHCP from QEMU.</td></tr>
 					<tr><td><code>make run-ahci</code></td><td>Add an ICH9 AHCI controller and a 512 MB SATA disk.</td></tr>
+					<tr><td><code>make run-amd</code> / <code>test-amd</code></td><td>Boot QEMU with <code>-cpu Opteron_G5 -smp 6</code> (the FX-6350's family 15h model 2), OHCI, six CPUs and an e1000; the headless test also checks <code>ioapic: masked</code>, <code>smp cpus: 6</code> and the PIT.</td></tr>
 					<tr><td><code>make uefi</code> / <code>run-uefi</code> / <code>test-uefi</code></td><td>Build the dual-boot image, boot it under OVMF, or run the headless serial check.</td></tr>
 					<tr><td><code>make rootfs</code></td><td>Rebuild <code>cmds.img</code> only.</td></tr>
 					<tr><td><code>make nowm</code></td><td>Diagnostic kernel with the WM disabled; the boot console stays visible.</td></tr>
@@ -179,8 +180,8 @@
 					<tr><td><code>make flash</code></td><td>Write the dual-boot image to a USB stick (needs mingw and prompts for the device).</td></tr>
 					<tr><td><code>make test-usb</code></td><td>Headless QEMU mouse/keyboard regression tests using QMP and screen dumps.</td></tr>
 					<tr><td><code>make test-install</code></td><td>Boots the dual image with a USB mass-storage source and a blank target, types <code>install ide1</code>, verifies the clone and boots the target in BIOS and UEFI.</td></tr>
-					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
-					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
+					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, including reduced-IDCT JPEG decode against a box-filtered reference; AddressSanitizer variant included.</td></tr>
+					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519, AES-128-GCM, P-256, the TLS 1.2 PRF and TLS helpers.</td></tr>
 					<tr><td><code>make test-wpa</code></td><td>Host vectors for the WPA2 supplicant: SHA-1, RFC 6070 PBKDF2, the 802.11 PSK and PRF examples, FIPS-197 AES, RFC 3394 unwrap, plus a simulated 4-way handshake, group rekey, replay and wrong-passphrase case.</td></tr>
 					<tr><td><code>make test-wifi-store</code></td><td>Host test for the saved-network file: newest-first ordering, passphrase update, LRU eviction at the 16-entry cap, per-SSID forget, the old one-record format and malformed or duplicate lists.</td></tr>
 					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>
@@ -191,6 +192,7 @@
 					<tr><td><code>make test-chat</code></td><td>Host tests (ASan/UBSan) for the chat client's JSON parser, cookie jar and the OIDC login page/reply/config parsers.</td></tr>
 					<tr><td><code>make test-chat-e2e</code></td><td>Boots QEMU with an NE2000 on slirp, starts <code>tools/mock_chat.py</code> and drives <code>chat</code> through QMP: native login, send, live poll, read marker, older paging, browse/join, new DM, saved-session resume and sign-out.  <code>CHAT_E2E=--totp|--consent|--passkey|--wrong</code> runs a login variant.</td></tr>
 					<tr><td><code>make compat-serve</code></td><td>Serve the browser compatibility ladder from <code>testdata/browser/compat/</code> on port 8000 for the board or QEMU guest.</td></tr>
+					<tr><td><code>make browser-host</code></td><td>Build the Linux SDL3 development harness (<code>browser-host</code> and its <code>host-curl</code> helper). It implements the ring-3 <code>SYS_*</code> ABI with host files, BSD sockets, <code>fork/exec</code> and an SDL3 window, so pages render and accept input without QEMU. Run <code>./browser-host [--size WxH] [--root DIR] URL|FILE</code>; <code>--headless --wait 3000 --shot out.ppm</code> writes the canvas without a display. Needs the 32-bit SDL3/Wayland libraries (<code>lib32-sdl3</code>, <code>lib32-wayland</code>, <code>lib32-libxkbcommon</code>).</td></tr>
 					<tr><td><code>make fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
 			</table>
@@ -297,7 +299,8 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Touchpad gestures.</strong> <code>make test-touchpad</code> feeds synthetic contact frames to <span class="file">touchpad_gesture.c</span> and checks one/two-finger taps, the corner and physical-button mapping, scroll start/direction, pointer freeze and re-anchoring, and the option switches.</li>
 			<li><strong>Chat client.</strong> <code>make test-chat</code> covers the pure modules on the host.  <code>tools/mock_chat.py</code> is a two-origin mock of Cloudron Chat (port 18080) and the Cloudron OIDC login (18081) with <code>test</code>, <code>totp</code> (code 123456), <code>passkey</code> and <code>consent</code> accounts (password <code>test</code>) and <code>/debug/state</code>, <code>/debug/inject</code> endpoints; run it alone and enter <code>http://10.0.2.2:18080</code> in a QEMU guest's chat, or let <code>make test-chat-e2e</code> drive it.  Screenshots land in <code>chat-test-out/</code>.</li>
 			<li><strong>Browser compatibility.</strong> <code>make compat-serve</code> serves the numbered A/B ladder in <code>testdata/browser/compat/</code>. Open the index on the board (or at <code>http://10.0.2.2:8000/</code> from a QEMU guest with user networking) and compare each pair; the index table records the current status.</li>
-			<li><strong>UEFI.</strong> <code>make test-uefi</code> boots the dual image under OVMF headless and greps the serial log for the boot line.</li>
+			<li><strong>Host browser harness.</strong> <code>make browser-host</code> builds the real browser, ngui, image/TLS code and QuickJS as a 32-bit Linux program against the same <code>SYS_*</code> ABI. <code>./browser-host testdata/browser/compat/010-block-width.html</code> opens an SDL3 window (native Wayland on this desktop); the address bar, wheel, links and keys use the normal browser paths. <code>./browser-host --headless --wait 3000 --shot /tmp/opencode/page.ppm URL</code> renders without a display for scripts and screenshots. The harness uses host sockets rather than the NebOS TCP stack, and an <code>mmap</code> arena with the ring-3 allocator, so it tests browser/HTML/CSS/JS/image/font/TLS logic rather than drivers.</li>
+			<li><strong>UEFI.</strong> <code>make test-uefi</code> boots the dual image under OVMF headless and greps the serial log for the boot line. <code>make test-amd</code> does the same with QEMU's Piledriver CPU model and checks the IOAPIC mask and six-core ACPI SMP.</li>
 			<li><strong>Compositor stats.</strong> The ring-3 WM overwrites <code>/share/wmstats</code> every two seconds with <code>frames</code>, total and worst compositing time in milliseconds, and the pixels drawn in the interval. Read it in a terminal or fetch it over WebDAV to measure a target.</li>
 		</ul>
 	</section>
@@ -307,6 +310,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 		<ul>
 			<li><strong>Serial log.</strong> <code>make monitor</code> shows the boot trace and printf-style driver output. The <code>NebOS v… booted</code> line is written before the framebuffer is ready.</li>
 			<li><strong>Boot time.</strong> Timestamp COM1 on the host (QEMU <code>-serial stdio</code>): the kernel starts at <code>NebOS v… booted</code>, the desktop at <code>wm: first frame</code>, and the terminal is on screen at <code>wm: first window frame (term) at N ms</code> (kernel uptime).  On QEMU the USB image reaches it about 0.4 s after the kernel starts; USB, the NIC and the disks are probed after that (<code>[boot] usb/net/storage</code> lines).</li>
+			<li><strong>No serial port.</strong> The boot console is the early log. After the desktop, <code>bootlog</code> prints the captured text and <code>bootlog save /usb0p3/BOOTLOG.TXT</code> writes it to the live stick's FAT ESP (mount that partition on the host to read it). Once DHCP works, <code>make netmon</code> mirrors serial and terminal output to UDP 19290, so it becomes the serial console.</li>
 			<li><strong>Network console.</strong> <code>make netmon</code> listens to UDP 19290 for serial and terminal output; <code>netconsole host &lt;ip&gt;</code> narrows the target.</li>
 			<li><strong>dbg.</strong> The ring-0 serial monitor accepts <code>r addr len</code>, <code>w addr b0 …</code>, <code>i port</code>, <code>o port val</code>, <code>h</code> and <code>q</code>.</li>
 			<li><strong>Keys.</strong> <code>keytest</code> drains the raw scancode tap in <span class="file">io.c</span> and prints every byte with its E0-prefix state, make/break kind and decoded <code>IO_KEY_*</code>/ASCII value; Ctrl+C stops it.  It sees releases and keys the decoder ignores, so an unknown action-row key is easy to identify.</li>
@@ -369,6 +373,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><code>Makefile</code> — targets and image rules</li>
 			<li><code>libc/</code>, <code>libc.a</code> — optional ring-3 libc and its host test</li>
 			<li><code>third_party/quickjs/</code> (see its <code>VENDOR</code>), <code>js_mu.c/h</code>, <code>js_browser.c/h</code> — vendored JavaScript engine, its MuJS-style stack API and the browser bindings; <code>js_test.c</code> host tests</li>
+			<li><code>host/</code> — Linux SDL3 browser harness: <code>syscall.c</code> implements the <code>SYS_*</code> ABI, <code>window_sdl3.c</code> the Wayland window/input, <code>fs.c</code>/<code>net.c</code>/<code>proc.c</code> the host file, socket and <code>curl __serve</code> services, and <code>window_headless.c</code> the screenshot mode; <span class="file">ucmd_lib.h</span> selects the host prototypes with <code>UCMD_HOST</code></li>
 			<li><code>ufont.c</code>, <code>ufont_ttf.c</code>, <code>fonts/</code> — UI font engine and subsets; <code>ufont_test.c</code> host test</li>
 			<li><code>kexec.c</code>, <code>kexec_send.c</code> — serial reload</li>
 			<li><code>netkexec.c</code>, <code>netkexec_send.c</code> — network reload</li>

+ 51 - 15
docs/drivers.html

@@ -84,7 +84,7 @@
 					<tr><td>SATA</td><td><span class="file">ahci.c</span></td><td>PCI AHCI MMIO</td><td>Polled, READ/WRITE DMA EXT</td></tr>
 					<tr><td>eMMC</td><td><span class="file">sdhci.c</span></td><td>Intel Braswell SDHCI, PCI <code>00:10.0</code> (<code>8086:2294</code>)</td><td>Polled PIO, 1-bit/25 MHz; no DMA/IRQ</td></tr>
 					<tr><td>USB</td><td><span class="file">usb.c</span> + <span class="file">uhci.c</span> <span class="file">ohci.c</span> <span class="file">ehci.c</span> <span class="file">xhci.c</span></td><td>PCI I/O ports or MMIO</td><td>Polled; hotplug watcher in the WM loop</td></tr>
-					<tr><td>Network</td><td><span class="file">e1000e.c</span> <span class="file">r8168.c</span> <span class="file">ne2000.c</span> <span class="file">asix.c</span> <span class="file">rndis.c</span></td><td>PCI or USB</td><td>Polled, one active receiver</td></tr>
+					<tr><td>Network</td><td><span class="file">e1000e.c</span> <span class="file">r8168.c</span> <span class="file">ne2000.c</span> <span class="file">asix.c</span> <span class="file">rndis.c</span></td><td>PCI or USB</td><td>Polled, one active receiver; <code>r8168</code> covers the RTL8111E/8168 family (970A-DS3P) as well as the AT3IONT-I's RTL8112L.</td></tr>
 					<tr><td>WiFi</td><td><span class="file">iwl_trans.c</span> <span class="file">iwl_mvm.c</span> <span class="file">iwl_dvm.c</span> <span class="file">wifi.c</span></td><td>PCIe, Intel 7265D/3165 (<code>8086:095a/095b/3165/3166</code>) and 6200/6300 (<code>8086:4239/422c</code>, <code>4238/422b</code>)</td><td>Polled RX ring; firmware from <code>/ramfs/firmware</code>, loaded on first use</td></tr>
 					<tr><td>USB WiFi</td><td><span class="file">rtl8821au.c</span> <span class="file">wifi.c</span></td><td>USB 2.0 high speed, Realtek RTL8821AU/8811AU (TP-Link Archer T2U Nano <code>2357:011f</code> and the other Linux <code>rtw88_8821au</code> IDs)</td><td>Vendor control requests for registers, one bulk-IN/one bulk-OUT endpoint; firmware + register tables from <code>/ramfs/firmware</code></td></tr>
 					<tr><td>Panel backlight</td><td><span class="file">backlight.c</span></td><td>Intel Braswell/Cherryview graphics MMIO, PCI <code>00:02.0</code> (<code>8086:22b0/22b1</code>)</td><td>Polled register writes; F6/F7 and <code>E0 14</code>/<code>E0 15</code> step 10%; <code>SYS_BACKLIGHT</code> drives the control-panel slider</td></tr>
@@ -284,13 +284,38 @@
 				</thead>
 				<tbody>
 					<tr><td>UHCI</td><td>PCI I/O ports</td><td>1</td><td>Frame list at <code>0x3000</code>; control QH plus one QH per interrupt slot.</td></tr>
-					<tr><td>OHCI</td><td>PCI MMIO</td><td>up to 4</td><td>HCCA from the page allocator, static ED/TD sets, TDs start at <code>CC = NotAccessed</code>.</td></tr>
+					<tr><td>OHCI</td><td>PCI MMIO</td><td>up to 4</td><td>HCCA from the page allocator, static ED/TD sets in the uncacheable <code>ohci_dma_page</code>, TDs start at <code>CC = NotAccessed</code>. Before reset it requests SMM ownership (<code>HcCommandStatus.OCR</code>, clear <code>HcControl.IR</code>) and disables the AMD southbridge USB SMI on <code>1002:4385</code>.</td></tr>
 					<tr><td>EHCI</td><td>PCI MMIO</td><td>up to 4</td><td>Async QH/qTD schedule, page-allocated descriptors, polling only, no periodic list.</td></tr>
 					<tr><td>xHCI</td><td>PCI MMIO</td><td>—</td><td>USB2 and USB3 root ports; direct SuperSpeed devices use a 512-byte EP0 and the port speed in the slot context (USB3 hubs are not decoded). Halts and waits for <code>HCH</code> around <code>HCRST</code>; EP0 max packet comes from the port speed; EP0 stages are encoded as one TD per stage (EDK2 style) because chained control TDs stall on Braswell.</td></tr>
 				</tbody>
 			</table>
 		</div>
 
+		<p>
+			AMD SB600/SB700/SB800/SB950 firmware can leave the OHCI controllers
+			owned by the SMM and keep the southbridge USB SMI enabled. The
+			driver requests ownership and clears the SMI enable before scanning
+			(<code>ohci.c</code>), so USB2 ports on the 970A-DS3P's SB950 work
+			after the firmware handoff. The SB950's legacy OHCI DMA does not
+			snoop dirty CPU cache lines, so the EDs, TDs, setup packet and
+			interrupt buffers live in one page that <code>paging_init</code>
+			maps uncacheable (PDE 0 is split before paging is enabled). Without
+			it the controller occasionally read an empty ED, skipped the
+			transfer and never re-armed the interrupt endpoint; the cursor
+			froze with no error. Control transfers still flush their
+			write-back data buffers around the transfer.
+		</p>
+		<p>
+			Enumeration starts every device on the USB default 8-byte EP0 and
+			adopts the descriptor's real <code>bMaxPacketSize0</code>
+			afterwards. A failed port attempt is retried three times with a
+			fresh port reset and a 20 ms settle, and OHCI gets a second boot
+			pass 60 ms after the EHCI-first walk so a companion handback
+			cannot leave a low-speed device unseen. HID detach is debounced
+			(three consecutive disconnected reads, 50 TD errors) and a detach
+			forces a clean full rescan, because a false port-loss leaves no
+			connect-change bit to wake the per-port path.
+		</p>
 		<p>
 			Hubs are class-9 devices: <code>usb.c</code> sets their configuration,
 			powers every downstream port (honouring <code>bPwrOn2PwrGood</code>),
@@ -298,17 +323,27 @@
 			recursively. This is what makes the X201's internal PCH hubs work.
 			Hotplug watches root ports; a device behind a hub is only found when a
 			full scan runs (<code>lsusb</code> also bumps the USB generation so
-			<code>usbhid</code> re-attaches).  Every HCD delay goes through
-			<code>usb_delay_ms()</code>: inside a scan owned by a sleepable
-			process (<code>lsusb</code>, the kworker's HID rescan/hotplug) it
-			sleeps and drops the BKL, so port resets and settle times no longer
-			freeze the system.  While such a scan sleeps, the
+			<code>usbhid</code> re-attaches).  A scan and every mass-storage
+			command claim the controllers for the calling process
+			(<code>usb_bus_claim()</code>/<code>usb_bus_release()</code>, nesting).
+			Every HCD delay and the ASIX/RNDIS/usbmsc probe delays go through
+			<code>usb_delay_ms()</code>, and every HCD completion and port-reset
+			poll loop calls <code>usb_poll_relax(t0)</code> outside its spinlock.
+			When the claim belongs to a sleepable scan (<code>lsusb</code>, the
+			kworker's HID rescan/hotplug, or the <code>storage</code> rescan
+			reading a USB disk), the delay sleeps and the poll yields once a wait
+			passes 2&nbsp;ms, both dropping the BKL, so port resets, NAKing
+			devices and settle times no longer freeze the WM; everywhere else
+			they busy-wait as before.  The poll yields instead of sleeping
+			because a 1&nbsp;ms sleep on an idle CPU wakes on the 100&nbsp;Hz idle
+			tick.  While another context owns the bus, the
 			<span class="file">usb.c</span> wrappers refuse controller access
-			from any other context (<code>usb_scan_foreign()</code>: control and
-			bulk transfers fail, interrupt polls return no data, ports read as
-			connected) and <code>usbhid_poll</code> skips its tick.  A USB NIC,
-			the RTL8821AU or a USB disk therefore sees a transient error during a
-			bus scan; the scan re-enumerates those devices anyway.
+			(<code>usb_scan_foreign()</code>: control and bulk transfers fail,
+			interrupt polls return no data, ports read as connected),
+			<code>usb_hotplug_poll</code> skips its pass and
+			<code>usbhid_poll</code> skips its tick.  A USB NIC, the RTL8821AU or
+			a USB disk therefore sees a transient error during a bus scan; the
+			scan re-enumerates those devices anyway.
 		</p>
 
 		<h3>Mass storage</h3>
@@ -584,14 +619,15 @@
 	<section id="sensors">
 		<h2>Sensors, power &amp; thermals</h2>
 		<ul>
-			<li><strong>DTS.</strong> <span class="file">thermal.c</span> reads <code>IA32_THERM_STATUS</code> on an allowlist of Core/Core 2, Nehalem/Westmere, Bonnell and Airmont/Braswell models. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem/Westmere; Airmont uses coretemp's 90 °C table (the kernel does not read the MSR before the IDT exists), and Bonnell uses the table.</li>
-			<li><strong>IT87xx.</strong> <span class="file">it87.c</span> reads the Super I/O temperatures and fan tachometers on the ASUS AT3IONT-I. Nothing is written to fan control.</li>
+			<li><strong>DTS / AMD Tctl.</strong> <span class="file">thermal.c</span> reads <code>IA32_THERM_STATUS</code> on an allowlist of Core/Core 2, Nehalem/Westmere, Bonnell and Airmont/Braswell models. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem/Westmere; Airmont uses coretemp's 90 °C table (the kernel does not read the MSR before the IDT exists), and Bonnell uses the table. AMD family 15h models below <code>0x60</code> (Bulldozer/Piledriver) read <code>D18F3xA4</code> at PCI <code>0:18.3</code>; the package value is sampled from the kworker under the BKL and copied to every CPU.</li>
+			<li><strong>IT87xx.</strong> <span class="file">it87.c</span> reads the Super I/O temperatures and fan tachometers on the ASUS AT3IONT-I and the Gigabyte 970A-DS3P (IT8728F). Nothing is written to fan control.</li>
 			<li><strong>ThinkPad EC.</strong> <span class="file">tpec.c</span> is gated on an SMBIOS Lenovo/IBM match and reads temperatures and fan mode through the shared ACPI EC protocol in <span class="file">ec.c</span> (ports <code>0x62/0x66</code>, command <code>0x80</code> read / <code>0x81</code> write, OBF/IBF waits, stale-byte drain, bounded polls). Battery/AC state comes from <code>0x38/0x39</code> (present, charging, discharging), <code>0x46</code> bit 4 (AC online), and the page-selected 16-byte window at <code>0xA0..0xAF</code>; <code>0x81</code> selects the battery and page (0 dynamic, 1 mode, 2 design, 5 manufacturer, 6 model). That page selector is the only EC write, and it is restored when it changed.</li>
 			<li><strong>Chrome EC.</strong> <span class="file">cros_ec.c</span> probes the Chrome OS EC, gated on the ACPI memory version, the <code>'E','C'</code> memmap id and the device feature bits; it skips the probe when the ThinkPad EC is present. Its ACPI window <code>0x20..0xFF</code> mirrors memmap <code>0x00..0xDF</code>: temperature sensors <code>0x00..0x0f</code>/<code>0x18..0x1f</code> (raw − 73 °C), fans <code>0x10..0x17</code> (<code>0xffff</code> absent), switches <code>0x30</code> (lid/power button), and the battery block <code>0x40..0x7f</code> (AC/present/charging flags at <code>0x4c</code>, voltage/rate/remaining/design/last-full/cycle count, and the 8-byte strings). <code>EC_ACPI_MEM_BATTERY_INDEX</code> <code>0x12</code> selects the battery and waits for <code>BATT_INDEX</code> <code>0x4e</code>; <code>EC_ACPI_MEM_STRINGS_FIFO</code> <code>0x16</code> returns longer strings when supported. The Cyan full-charge workaround is applied, and the units are mAh/mA. <span class="file">power_src.c</span> picks the ThinkPad backend first, then the Chrome EC; <code>SYS_CROS_EC_SENSORS</code> (107) exposes the EC temperature/fan/switch snapshot.</li>
 			<li><strong>MTRRs.</strong> <span class="file">mtrr.c</span> manages write-combining ranges for the framebuffer and reports the effective mapping.</li>
 		</ul>
 		<p>
-			<code>sensors</code> prints DTS values on the 90/100/125 °C scales,
+			<code>sensors</code> prints supported CPU temperatures (and the
+			Intel 90/100/125 °C delta scales when there is no published TjMax),
 			board sensors and both EC types; <code>powerinfo</code> prints the
 			source (<code>thinkpad</code> or <code>chrome ec</code>), the AC
 			adapter, battery model/manufacturer/serial, capacities, voltage,

+ 1 - 1
docs/filesystems.html

@@ -165,7 +165,7 @@
 			<li><strong>Read/write.</strong> Read, write, delete, mkdir and rmdir are implemented; FAT32 allocation uses an FSInfo-seeded free-cluster hint.</li>
 			<li><strong>8.3 names.</strong> The on-disk name is the canonical one. The shell and <code>files</code> display the space-padded form; a long name cannot be created.</li>
 			<li><strong>Directory cache.</strong> The last FAT directory's first 64 entries are cached in <code>vfs.c</code>, so WebDAV's index sequence is one walk instead of N. Any write invalidates the cache.</li>
-			<li><strong>Serialization.</strong> A file operation runs in a non-preemptible section because the FAT driver has static state and the floppy needs IRQ 6; <code>vfs_scan_busy</code>/<code>format_busy</code> make it sleep first while a mount scan or a format owns the disks. A format releases the BKL for its raw-sector loop, and only disk-backed mounts wait for it, so <code>/ramfs</code> and <code>/share</code> stay usable.  A rescan (the <code>bootscan</code> thread or the <code>storage</code> command) re-adds <code>/ramfs</code>/<code>/share</code> first and is skipped by their operations too (<code>vfs_mount_is_ram</code>); it runs preemptible, and the floppy/ATA/AHCI/SDHCI wait loops call <code>vfs_scan_poll</code>/<code>vfs_scan_relax</code>, which sleep (dropping the BKL) once a wait passes 2 ms and only for the scan's owning process, so <code>storage</code> no longer freezes the WM.  The floppy probe is skipped for a drive whose CMOS type (register <code>0x10</code>) is 0.</li>
+			<li><strong>Serialization.</strong> A file operation runs in a non-preemptible section because the FAT driver has static state and the floppy needs IRQ 6; <code>vfs_scan_busy</code>/<code>format_busy</code> make it sleep first while a mount scan or a format owns the disks. A format releases the BKL for its raw-sector loop, and only disk-backed mounts wait for it, so <code>/ramfs</code> and <code>/share</code> stay usable.  A rescan (the <code>bootscan</code> thread or the <code>storage</code> command) re-adds <code>/ramfs</code>/<code>/share</code> first and is skipped by their operations too (<code>vfs_mount_is_ram</code>); it runs preemptible, and the floppy/ATA/AHCI/SDHCI wait loops (including the SDHCI command and CMD1 power-up polls) call <code>vfs_scan_poll</code>/<code>vfs_scan_relax</code>, which sleep (dropping the BKL) once a wait passes 2 ms and only for the scan's owning process.  A USB disk read by the rescan claims the USB bus (<code>usb_bus_claim()</code>), so its host-controller waits yield too; <code>storage</code> no longer freezes the WM.  The floppy probe is skipped for a drive whose CMOS type (register <code>0x10</code>) is 0.</li>
 		</ul>
 		<p>
 			<span class="file">fatdetect.c</span> and <span class="file">fatformat.c</span>

+ 25 - 13
docs/graphics.html

@@ -73,14 +73,19 @@
 			<code>0x600</code>: LFB base, pitch, width, height, bits per pixel
 			and an RGBX flag for GOP's byte order. The legacy VESA stage chooses
 			a mode with at least 16 bpp, a linear framebuffer, it must fit the
-			card's VRAM, and width at most 1280 pixels. The UEFI loader imposes
-			its own GOP constraints.
+			card's VRAM, at most 1920 pixels wide, and its shadow (pitch ×
+			height) must fit the 8 MB reserve. 1920×1080 is the practical
+			maximum: its 8.29 MB shadow fits, and its 4.15 MB RGB565 canvas
+			fits the 4 MB window slot; 1920×1200 is rejected because its
+			canvas would need 4.6 MB. The UEFI loader applies the same GOP
+			limits.
 		</p>
 		<p>
 			<span class="file">vga.c</span> owns the visible surface. On a
 			normal boot the render target is a RAM shadow buffer at
-			<code>0x100000</code>, not the LFB; the 8 MB reserve leaves room for
-			future modes. A surface carries width, height, pitch, format and a
+			<code>0x100000</code>, not the LFB; the 8 MB reserve holds a
+			1920×1080×32 frame (8.29 MB) with about 94 KB to spare. A surface
+			carries width, height, pitch, format and a
 			pixel-pointer, so the same drawing code can target a window layer or
 			a canvas.
 		</p>
@@ -181,7 +186,9 @@
 			an inline date/time editor with Set, Now and Sync NTP (no separate
 			window).  <code>SYS_WIN_RESIZE_SELF</code> grows or shrinks the
 			popover to the section, clamped to <code>SYS_SCREEN_INFO</code>'s
-			framebuffer; the section scrolls when it is taller than the screen.
+			framebuffer; the section scrolls with the wheel, touchpad or page
+			keys when it is taller than the screen, without drawing a
+			scrollbar.
 		</p>
 		<p>
 			The WM is the ring-3 process loaded from
@@ -287,13 +294,17 @@
 			(<code>+dy</code> is later content). A click that starts
 			in a window still receives its release after the pointer leaves.
 			The ngui helper <code>ngui_scroll_wheel()</code> applies the delta
-			to a pane when the pointer is over it.
+			to a pane when the pointer is over it; a pane can set
+			<code>hide_bar</code> to keep wheel/key scrolling without a visible
+			scrollbar (the control panel does this so every card uses the full
+			width).
 			The WM process itself is special: it maps the screen shadow at
 			<code>0x58000000</code> and each front canvas at
 			<code>0x59000000 + index × 4 MB</code>, which is how it composites
 			without reading another process's memory. The 4 MB slot covers a
-			full-screen 1280×1024 canvas minus the chrome; the old 2 MB slot
-			capped a full-height window at roughly 1050 px wide.
+			full-screen 1920×1080 RGB565 canvas (4.15 MB) minus the chrome;
+			the old 2 MB slot capped a full-height window at roughly 1050 px
+			wide.
 			<code>SYS_WM_RESIZE</code> (WM side) and
 			<code>SYS_WIN_ACK_RESIZE</code> (client side) swap in a resized
 			canvas; the content size is bounded by the framebuffer, so a
@@ -391,7 +402,7 @@
 			</div>
 			<div class="card">
 				<h3>chat</h3>
-				<p>Cloudron Chat client: native OIDC login, channel/DM sidebar with unread badges and presence dots, a wrapped timeline with avatars, day headers and reply snippets, a composer and browse/new-DM pickers. The top-bar <em>Chat</em> button launches it.</p>
+				<p>Cloudron Chat client: native OIDC login, channel/DM sidebar with unread badges and presence dots, a wrapped timeline with avatars, day headers and reply snippets, a composer and browse/new-DM pickers. Media downloads use a warm <code>curl __serve</code> helper; message images are also decoded there (480&times;320 bounds), while avatars decode at 32&times;32 on the chat thread, so the window keeps drawing. Saved sessions resume from <code>/data</code>. The top-bar <em>Chat</em> button launches it.</p>
 			</div>
 			<div class="card">
 				<h3>solitaire</h3>
@@ -407,7 +418,7 @@
 			</div>
 			<div class="card">
 				<h3>browser</h3>
-				<p>HTML/CSS renderer with flex rows, auto-fit card grids, inline-block runs, basic tables and inline SVG diagrams. It decodes inline images and fetches through a headless helper; inline and external scripts run on the vendored QuickJS engine (ES2025), and forms render and submit natively. The largest ring-3 application in the tree.</p>
+				<p>HTML/CSS renderer with flex rows, auto-fit and <code>repeat(N, 1fr)</code> card grids, <code>aspect-ratio</code> frames, inline-block runs, inline SVG icons, basic tables and inline SVG diagrams. It decodes inline images at their laid-out bounds (a JPEG gets a reduced IDCT) in the fetch helper, caches a display-size bitmap per image so repaints are 1:1, and fetches through the same helper; image repaints are coalesced and <code>/share/IMGSTAT</code> reports where a load spent its time. Inline and external scripts run on the vendored QuickJS engine (ES2025), and forms render and submit natively. The largest ring-3 application in the tree.</p>
 			</div>
 		</div>
 	</section>
@@ -423,9 +434,10 @@
 		</p>
 		<ul>
 			<li><strong>Formats.</strong> PNG, baseline and progressive JPEG, animated GIF, BMP, TGA, PNM, ICO/CUR and PAM. The browser also takes SVG files (<code>&lt;img src="logo.svg"&gt;</code>, CSS backgrounds): the markup is parsed into a detached subtree and drawn by its inline-SVG renderer into an RGB565 + alpha bitmap.</li>
-			<li><strong>Drawing.</strong> <code>img_draw()</code> is a clipped, scaled RGB565 blit: box-filter downscale, bilinear upscale, alpha over a checkerboard or over the destination.</li>
+			<li><strong>Drawing.</strong> <code>img_draw()</code> is a clipped, scaled RGB565 blit: box-filter downscale, bilinear upscale, alpha over a checkerboard or over the destination.  A 1:1 opaque source takes a row copy, and a 1:1 alpha source blends in RGB565 without the 8-bit round trip.</li>
+			<li><strong>Display-size decode.</strong> <code>struct img_options</code> carries optional <code>max_w</code>/<code>max_h</code> bounds.  JPEG honours them with a scaled IDCT (1/2 4x4, 1/4 2x2, 1/8 1x1, Loeffler/IGJ), so a 1200x800 photo painted at 400&times;267 is decoded at roughly 600&times;400 instead of full size and then box-filtered.  PNG/GIF/other codecs ignore the bounds and the caller scales them with <code>img_draw()</code>.  The browser's <code>curl __serve</code> helper runs this decode for remote <code>&lt;img&gt;</code> and publishes the finished RGB565+alpha bitmap, so the UI thread only copies it.</li>
 			<li><strong>Orientation.</strong> EXIF orientation is applied; arithmetic JPEG and CMYK are rejected.</li>
-			<li><strong>Cost.</strong> Downscaling runs on the CPU. The viewer caches one image; the browser keeps a display bitmap but still rescales on repaint; the chat client caches up to 480x320 message images and 32x32 circular avatars.</li>
+			<li><strong>Cost.</strong> Downscaling runs on the CPU.  The browser decodes at the CSS/attribute box and caches one display-size bitmap per image, so a repaint is a 1:1 blit; the viewer caches one image; the chat client caches 480&times;320 message images and 32&times;32 circular avatars.  <code>/share/IMGSTAT</code> records the browser's net, io, decode, scale, paint and reflow times.</li>
 		</ul>
 	</section>
 
@@ -433,7 +445,7 @@
 		<h2>GPU quirks</h2>
 		<ul>
 			<li><strong>ATI Mach64.</strong> A CRTC fixup is applied after mode set. The legacy CRTC is skipped under UEFI.</li>
-			<li><strong>NVIDIA.</strong> VBE-only. The legacy VGA CRTC is never touched. On the ION, the framebuffer is stolen DRAM behind a BAR3 aperture; <span class="file">nvidia.c</span> finds the stolen range and writes through a cached alias once a WC MTRR covers it.</li>
+			<li><strong>NVIDIA.</strong> VBE/GOP only; the kernel never touches the legacy VGA CRTC. On the ION, the framebuffer is stolen DRAM behind a BAR3 aperture; <span class="file">nvidia.c</span> finds the stolen range and writes through a cached alias once a WC MTRR covers it. The nv50 display-engine probe is gated to the ION/nv50 chipsets so Maxwell parts (the GM206 GTX 960) are not poked through nv50 registers.  On AMD family 15h the WC MTRR path uses only a free variable entry, leaves <code>MTRRdefType</code> untouched and writes a zero high mask (the LFB is below 4 GB); this is validated on the 970A-DS3P.</li>
 			<li><strong>Intel.</strong> The Ironlake-era path supports a hardware cursor where available; the software cursor is the common fallback. Cherryview/Braswell also exposes the panel backlight (below).</li>
 			<li><strong>UEFI.</strong> <code>vga.c</code> honours the RGBX flag and skips the VBE-only ATI CRTC reset and NVIDIA stolen-VRAM alias. <span class="file">mouse.c</span> forces the software cursor.</li>
 		</ul>

+ 1 - 1
docs/index.html

@@ -217,7 +217,7 @@
 			</a>
 			<a class="card" href="network.html">
 				<h3>Networking</h3>
-				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, USB tethering, WiFi, the top-bar control panel, netconsole and netkexec.</p>
+				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3/1.2, USB tethering, WiFi, the top-bar control panel, netconsole and netkexec.</p>
 				<span class="card-tag">network.html</span>
 			</a>
 			<a class="card" href="drivers.html#wifi">

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 12 - 8
docs/network.html


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 5 - 1
docs/userland.html


+ 8 - 3
efi/main.c

@@ -253,7 +253,7 @@ static int gop_init(EFI_SYSTEM_TABLE *st, EFI_GRAPHICS_OUTPUT_PROTOCOL **out_gop
 		if (info->HorizontalResolution < 320 ||
 		    info->VerticalResolution < 200)
 			continue;
-		if (info->HorizontalResolution > 1280 ||
+		if (info->HorizontalResolution > 1920 ||
 		    info->VerticalResolution > 65535)
 			continue;
 		if (info->PixelsPerScanLine < info->HorizontalResolution)
@@ -286,7 +286,7 @@ static int gop_init(EFI_SYSTEM_TABLE *st, EFI_GRAPHICS_OUTPUT_PROTOCOL **out_gop
 	    info->PixelFormat != EFI_PIXEL_RGBX)
 		return 0;
 	if (info->HorizontalResolution < 320 ||
-	    info->HorizontalResolution > 1280 ||
+	    info->HorizontalResolution > 1920 ||
 	    info->VerticalResolution < 200 ||
 	    info->VerticalResolution > 65535 ||
 	    info->PixelsPerScanLine < info->HorizontalResolution ||
@@ -501,7 +501,10 @@ static void write_fbinfo(const struct fb_saved *fb)
 	info->bpp = (unsigned char)fb->bpp;
 	info->lfb_base = (unsigned int)fb->base;
 	{
-		UINT64 blocks = fb->size >> 16;
+		/* GOP reports the mode buffer size, not total VRAM.  Round up
+		 * so the kernel's VBE-era height clamp (vram_64k * 64K /
+		 * pitch) cannot shave rows off a 1920x1080 frame. */
+		UINT64 blocks = (fb->size + 0xFFFFull) >> 16;
 
 		info->vram_64k = (unsigned short)(blocks > 0xFFFF ? 0xFFFF :
 						  blocks);
@@ -728,6 +731,8 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st)
 		com1_puts("\n");
 	} else {
 		com1_puts("nebos-efi: no usable GOP mode, booting headless\n");
+		conout_puts(st,
+			    "NebOS EFI loader: no usable GOP mode, booting headless\n");
 	}
 
 	rsdp = find_rsdp(st);

+ 2 - 0
ehci.c

@@ -412,6 +412,7 @@ static int qtd_wait(struct ehci_qtd *qtd, struct ehci_qtd *early,
 			return -1;
 		if (get_ticks_ms() - t0 >= ms)
 			return -1;
+		usb_poll_relax(t0);
 		__asm__ volatile ("pause");
 	}
 	return 0;
@@ -959,6 +960,7 @@ static int ehci_port_reset_once(unsigned int ctrl, unsigned int port)
 	while (!(rd32(port_reg(c, port)) & PORT_PE)) {
 		if (get_ticks_ms() - t0 > 200)
 			break;
+		usb_poll_relax(t0);
 	}
 	ps = rd32(port_reg(c, port));
 

+ 22 - 0
host/curl_main.c

@@ -0,0 +1,22 @@
+/* host-curl: the browser's __serve helper, built for Linux. */
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "host.h"
+
+extern void curl_start(const char *arg);
+
+int main(int argc, char **argv)
+{
+	const char *root = getenv("NEBOS_HOST_ROOT");
+
+	memset(&host_opts, 0, sizeof(host_opts));
+	host_opts.headless = 1;
+	if (host_runtime_init(argv[0], root) != 0)
+		return 1;
+	signal(SIGPIPE, SIG_IGN);
+	curl_start(argc > 1 && argv[1] ? argv[1] : "");
+	return 0;
+}

+ 239 - 0
host/fs.c

@@ -0,0 +1,239 @@
+/* Guest path mapping and the small file service behind SYS_*_FILE. */
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "host.h"
+#include "fs.h"
+#include "syscall.h"
+
+static int mkdir_p(const char *path)
+{
+	char tmp[HOST_PATH_MAX];
+	size_t n;
+	size_t i;
+
+	n = strlen(path);
+	if (n == 0 || n >= sizeof(tmp))
+		return -1;
+	memcpy(tmp, path, n + 1);
+	if (tmp[n - 1] == '/')
+		tmp[n - 1] = '\0';
+	for (i = 1; tmp[i]; i++) {
+		if (tmp[i] != '/')
+			continue;
+		tmp[i] = '\0';
+		if (mkdir(tmp, 0755) != 0 && errno != EEXIST)
+			return -1;
+		tmp[i] = '/';
+	}
+	if (mkdir(tmp, 0755) != 0 && errno != EEXIST)
+		return -1;
+	return 0;
+}
+
+static int prefix(const char *path, const char *p)
+{
+	size_t n = strlen(p);
+
+	return strncmp(path, p, n) == 0 &&
+	       (path[n] == '\0' || path[n] == '/');
+}
+
+int host_guest_to_host(const char *guest, char *out, size_t cap)
+{
+	if (!guest || !guest[0])
+		return -1;
+	if (guest[0] != '/') {
+		/* Relative paths resolve against the harness cwd, like a
+		 * normal Linux program. */
+		snprintf(out, cap, "%s", guest);
+		return 0;
+	}
+	if (prefix(guest, "/ramfs") || prefix(guest, "/share") ||
+	    prefix(guest, "/data")) {
+		int n = snprintf(out, cap, "%s%s", host_root, guest);
+
+		return (n > 0 && (size_t)n < cap) ? 0 : -1;
+	}
+	/* Any other absolute path is a real host path (testdata pages,
+	 * /tmp files) and is passed through unchanged. */
+	snprintf(out, cap, "%s", guest);
+	return 0;
+}
+
+int host_fs_init(const char *root)
+{
+	char path[HOST_PATH_MAX];
+	char fonts[HOST_PATH_MAX];
+	char link[HOST_PATH_MAX];
+
+	if (mkdir_p(root) != 0)
+		return -1;
+	snprintf(path, sizeof(path), "%s/share", root);
+	if (mkdir_p(path) != 0)
+		return -1;
+	snprintf(path, sizeof(path), "%s/data", root);
+	if (mkdir_p(path) != 0)
+		return -1;
+	snprintf(path, sizeof(path), "%s/ramfs", root);
+	if (mkdir_p(path) != 0)
+		return -1;
+
+	snprintf(fonts, sizeof(fonts), "%s/fonts", host_repo);
+	if (access(fonts, R_OK) != 0) {
+		char cwd[HOST_PATH_MAX];
+
+		if (getcwd(cwd, sizeof(cwd)))
+			snprintf(fonts, sizeof(fonts), "%s/fonts", cwd);
+	}
+	snprintf(link, sizeof(link), "%s/ramfs/fonts", root);
+	if (access(fonts, R_OK) == 0) {
+		struct stat st;
+
+		if (lstat(link, &st) != 0)
+			symlink(fonts, link);
+	}
+	return 0;
+}
+
+int host_fs_stat(const char *path, unsigned int *size, unsigned int *is_dir)
+{
+	char host[HOST_PATH_MAX];
+	struct stat st;
+
+	if (host_guest_to_host(path, host, sizeof(host)) != 0)
+		return -1;
+	if (stat(host, &st) != 0)
+		return -1;
+	if (size)
+		*size = (unsigned int)st.st_size;
+	if (is_dir)
+		*is_dir = S_ISDIR(st.st_mode) ? 1u : 0u;
+	return 0;
+}
+
+int host_fs_read(const char *path, void *buf, unsigned int max)
+{
+	char host[HOST_PATH_MAX];
+	unsigned char *p = (unsigned char *)buf;
+	unsigned int done = 0;
+	int fd;
+
+	if (host_guest_to_host(path, host, sizeof(host)) != 0)
+		return -1;
+	fd = open(host, O_RDONLY);
+	if (fd < 0)
+		return -1;
+	while (done < max) {
+		ssize_t n = read(fd, p + done, max - done);
+
+		if (n < 0) {
+			if (errno == EINTR)
+				continue;
+			close(fd);
+			return -1;
+		}
+		if (n == 0)
+			break;
+		done += (unsigned int)n;
+	}
+	close(fd);
+	return (int)done;
+}
+
+int host_fs_write(const char *path, const void *buf, unsigned int len)
+{
+	char host[HOST_PATH_MAX];
+	const unsigned char *p = (const unsigned char *)buf;
+	unsigned int done = 0;
+	int fd;
+
+	if (host_guest_to_host(path, host, sizeof(host)) != 0)
+		return -1;
+	fd = open(host, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+	if (fd < 0)
+		return -1;
+	while (done < len) {
+		ssize_t n = write(fd, p + done, len - done);
+
+		if (n < 0) {
+			if (errno == EINTR)
+				continue;
+			close(fd);
+			return -1;
+		}
+		if (n == 0)
+			break;
+		done += (unsigned int)n;
+	}
+	close(fd);
+	return done == len ? 0 : -1;
+}
+
+int host_fs_unlink(const char *path)
+{
+	char host[HOST_PATH_MAX];
+
+	if (host_guest_to_host(path, host, sizeof(host)) != 0)
+		return -1;
+	return unlink(host) == 0 ? 0 : -1;
+}
+
+int host_fs_mkdir(const char *path)
+{
+	char host[HOST_PATH_MAX];
+
+	if (host_guest_to_host(path, host, sizeof(host)) != 0)
+		return -1;
+	return mkdir(host, 0755) == 0 ? 0 : -1;
+}
+
+int host_fs_rmdir(const char *path)
+{
+	char host[HOST_PATH_MAX];
+
+	if (host_guest_to_host(path, host, sizeof(host)) != 0)
+		return -1;
+	return rmdir(host) == 0 ? 0 : -1;
+}
+
+int host_fs_list(const char *path, unsigned int index, void *out)
+{
+	char host[HOST_PATH_MAX];
+	struct sys_dirent *de = (struct sys_dirent *)out;
+	struct dirent *d;
+	DIR *dir;
+	unsigned int n = 0;
+
+	if (host_guest_to_host(path, host, sizeof(host)) != 0)
+		return -1;
+	dir = opendir(host);
+	if (!dir)
+		return -1;
+	while ((d = readdir(dir)) != 0) {
+		char full[HOST_PATH_MAX];
+		struct stat st;
+
+		if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
+			continue;
+		if (n++ != index)
+			continue;
+		memset(de, 0, sizeof(*de));
+		snprintf(de->name, sizeof(de->name), "%s", d->d_name);
+		snprintf(full, sizeof(full), "%s/%s", host, d->d_name);
+		if (stat(full, &st) == 0) {
+			de->size = (unsigned int)st.st_size;
+			de->is_dir = S_ISDIR(st.st_mode) ? 1u : 0u;
+		}
+		closedir(dir);
+		return 1;
+	}
+	closedir(dir);
+	return 0;
+}

+ 18 - 0
host/fs.h

@@ -0,0 +1,18 @@
+#ifndef HOST_FS_H
+#define HOST_FS_H
+
+#include <stddef.h>
+
+#define HOST_PATH_MAX 1024
+
+int host_fs_init(const char *root);
+int host_guest_to_host(const char *guest, char *out, size_t cap);
+int host_fs_stat(const char *path, unsigned int *size, unsigned int *is_dir);
+int host_fs_read(const char *path, void *buf, unsigned int max);
+int host_fs_write(const char *path, const void *buf, unsigned int len);
+int host_fs_unlink(const char *path);
+int host_fs_mkdir(const char *path);
+int host_fs_rmdir(const char *path);
+int host_fs_list(const char *path, unsigned int index, void *dirent);
+
+#endif

+ 46 - 0
host/heap.c

@@ -0,0 +1,46 @@
+/* mmap backing for the ring-3 allocator reused by the host browser.
+ *
+ * libc/malloc.c reserves a 64 MB arena (its HEAP_MAX_BYTES) and grows it in
+ * place; reserve the whole range PROT_NONE up front so the grow is a
+ * mprotect and the arena can never move. */
+#include <stddef.h>
+#include <sys/mman.h>
+
+#define HOST_ARENA_BYTES (64u * 1024u * 1024u)
+
+static unsigned char *base;
+
+void *__heap_map(unsigned int bytes)
+{
+	if (base || bytes == 0 || bytes > HOST_ARENA_BYTES)
+		return 0;
+	base = (unsigned char *)mmap(0, HOST_ARENA_BYTES, PROT_NONE,
+				     MAP_PRIVATE | MAP_ANONYMOUS |
+				     MAP_NORESERVE, -1, 0);
+	if (base == MAP_FAILED) {
+		base = 0;
+		return 0;
+	}
+	if (mprotect(base, bytes, PROT_READ | PROT_WRITE) != 0) {
+		munmap(base, HOST_ARENA_BYTES);
+		base = 0;
+		return 0;
+	}
+	return base;
+}
+
+int __heap_grow(unsigned int total_bytes)
+{
+	if (!base || total_bytes > HOST_ARENA_BYTES)
+		return -1;
+	return mprotect(base, total_bytes, PROT_READ | PROT_WRITE) == 0 ?
+	       0 : -1;
+}
+
+void __heap_unmap(void)
+{
+	if (base) {
+		munmap(base, HOST_ARENA_BYTES);
+		base = 0;
+	}
+}

+ 79 - 0
host/host.c

@@ -0,0 +1,79 @@
+/* Shared runtime setup for browser-host and host-curl. */
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "host.h"
+#include "fs.h"
+
+struct host_options host_opts;
+char host_root[1024];
+char host_repo[1024];
+char host_curl_bin[1024];
+
+static void dirname_in_place(char *p)
+{
+	char *slash = strrchr(p, '/');
+
+	if (!slash) {
+		strcpy(p, ".");
+		return;
+	}
+	if (slash == p)
+		slash[1] = '\0';
+	else
+		*slash = '\0';
+}
+
+static void exe_dir(char *out, size_t cap, const char *argv0)
+{
+	ssize_t n = readlink("/proc/self/exe", out, cap - 1);
+
+	if (n > 0) {
+		out[n] = '\0';
+		dirname_in_place(out);
+		return;
+	}
+	if (argv0 && argv0[0]) {
+		snprintf(out, cap, "%s", argv0);
+		dirname_in_place(out);
+		return;
+	}
+	out[0] = '\0';
+}
+
+int host_runtime_init(const char *argv0, const char *root)
+{
+	const char *env_root = getenv("NEBOS_HOST_ROOT");
+	const char *env_curl = getenv("NEBOS_HOST_CURL");
+	char exe[1024];
+
+	if (!root || !root[0])
+		root = env_root && env_root[0] ? env_root :
+			"/tmp/opencode/nebos-browser-root";
+	snprintf(host_root, sizeof(host_root), "%s", root);
+	/* Drop a trailing slash except for "/". */
+	if (strlen(host_root) > 1 && host_root[strlen(host_root) - 1] == '/')
+		host_root[strlen(host_root) - 1] = '\0';
+
+	exe_dir(exe, sizeof(exe), argv0);
+	snprintf(host_repo, sizeof(host_repo), "%s", exe);
+
+	if (env_curl && env_curl[0])
+		snprintf(host_curl_bin, sizeof(host_curl_bin), "%s", env_curl);
+	else
+		snprintf(host_curl_bin, sizeof(host_curl_bin), "%s/host-curl",
+			 exe);
+
+	setenv("NEBOS_HOST_ROOT", host_root, 1);
+	setenv("NEBOS_HOST_CURL", host_curl_bin, 1);
+
+	if (host_fs_init(host_root) != 0) {
+		fprintf(stderr, "browser-host: cannot create profile root %s\n",
+			host_root);
+		return -1;
+	}
+	return 0;
+}

+ 25 - 0
host/host.h

@@ -0,0 +1,25 @@
+/* Shared state for the Linux browser harness. */
+#ifndef HOST_HOST_H
+#define HOST_HOST_H
+
+#include <stddef.h>
+
+struct host_options {
+	const char *root;
+	const char *shot;
+	unsigned int wait_ms;
+	int headless;
+	int width;
+	int height;
+};
+
+extern struct host_options host_opts;
+extern char host_root[1024];
+extern char host_repo[1024];
+extern char host_curl_bin[1024];
+
+/* Resolve the repo directory from /proc/self/exe, publish the profile root
+ * and create its /share, /data and /ramfs/fonts layout. */
+int host_runtime_init(const char *argv0, const char *root);
+
+#endif

+ 9 - 0
host/include/ucmd_heap.h

@@ -0,0 +1,9 @@
+/* Host copy of the ring-3 heap extension header.  The real one lives in
+ * libc/include/; the host build uses the system headers, so this keeps the
+ * single declaration available without shadowing libc. */
+#ifndef LIBC_UCMD_HEAP_H
+#define LIBC_UCMD_HEAP_H
+
+void heap_reset(void);
+
+#endif

+ 92 - 0
host/main.c

@@ -0,0 +1,92 @@
+/* browser-host: run the NebOS browser as a Linux/Wayland program.
+ *
+ * Usage: browser-host [--size WxH] [--root DIR] [--headless]
+ *                     [--wait MS] [--shot FILE] [URL|FILE]
+ */
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "host.h"
+
+extern void browser_start(const char *arg);
+
+static void usage(void)
+{
+	fprintf(stderr,
+		"usage: browser-host [--size WxH] [--root DIR] [--headless]\n"
+		"                    [--wait MS] [--shot|--screenshot FILE]\n"
+		"                    [URL|FILE]\n");
+}
+
+static int parse_size(const char *s, int *w, int *h)
+{
+	char *end;
+
+	*w = (int)strtol(s, &end, 10);
+	if (end == s || (*end != 'x' && *end != 'X'))
+		return -1;
+	s = end + 1;
+	*h = (int)strtol(s, &end, 10);
+	if (end == s || *end)
+		return -1;
+	return (*w > 0 && *h > 0) ? 0 : -1;
+}
+
+int main(int argc, char **argv)
+{
+	char argbuf[4096];
+	unsigned int arglen = 0;
+	const char *root = 0;
+	int i;
+
+	memset(&host_opts, 0, sizeof(host_opts));
+	host_opts.wait_ms = 4000;
+	argbuf[0] = '\0';
+
+	for (i = 1; i < argc; i++) {
+		const char *a = argv[i];
+
+		if (!strcmp(a, "--size") && i + 1 < argc) {
+			if (parse_size(argv[++i], &host_opts.width,
+				       &host_opts.height) != 0) {
+				usage();
+				return 1;
+			}
+		} else if (!strcmp(a, "--root") && i + 1 < argc) {
+			root = argv[++i];
+		} else if (!strcmp(a, "--headless")) {
+			host_opts.headless = 1;
+		} else if (!strcmp(a, "--wait") && i + 1 < argc) {
+			host_opts.wait_ms = (unsigned int)strtoul(argv[++i],
+								 0, 10);
+		} else if (!strcmp(a, "--shot") && i + 1 < argc) {
+			host_opts.shot = argv[++i];
+		} else if (!strcmp(a, "--screenshot") && i + 1 < argc) {
+			host_opts.shot = argv[++i];
+		} else if (!strcmp(a, "--help") || !strcmp(a, "-h")) {
+			usage();
+			return 0;
+		} else {
+			size_t n = strlen(a);
+
+			if (arglen && arglen + 1 < sizeof(argbuf))
+				argbuf[arglen++] = ' ';
+			if (arglen + n >= sizeof(argbuf))
+				n = sizeof(argbuf) - arglen - 1;
+			memcpy(argbuf + arglen, a, n);
+			arglen += (unsigned int)n;
+			argbuf[arglen] = '\0';
+		}
+	}
+	if (host_opts.headless && !host_opts.shot)
+		host_opts.shot = "/tmp/opencode/browser.ppm";
+
+	if (host_runtime_init(argv[0], root) != 0)
+		return 1;
+	signal(SIGPIPE, SIG_IGN);
+
+	browser_start(argbuf[0] ? argbuf : 0);
+	return 0;
+}

+ 237 - 0
host/net.c

@@ -0,0 +1,237 @@
+/* Host BSD-socket backend for the shared uhttp/TLS client. */
+#include <errno.h>
+#include <fcntl.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <poll.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "net.h"
+
+static int tcp_fd = -1;
+
+static int ms_left(unsigned long long deadline)
+{
+	unsigned long long now = 0;
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	now = (unsigned long long)ts.tv_sec * 1000ull +
+	      (unsigned long long)ts.tv_nsec / 1000000ull;
+	if (now >= deadline)
+		return 0;
+	return (int)(deadline - now);
+}
+
+static unsigned long long deadline_ms(unsigned int timeout_ms)
+{
+	struct timespec ts;
+	unsigned long long now;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	now = (unsigned long long)ts.tv_sec * 1000ull +
+	      (unsigned long long)ts.tv_nsec / 1000000ull;
+	return now + timeout_ms;
+}
+
+int host_net_dns(const char *name, unsigned char ip[4])
+{
+	struct addrinfo hints;
+	struct addrinfo *res = 0;
+	int rv;
+
+	if (!name || !name[0])
+		return -1;
+	memset(&hints, 0, sizeof(hints));
+	hints.ai_family = AF_INET;
+	hints.ai_socktype = SOCK_STREAM;
+	rv = getaddrinfo(name, 0, &hints, &res);
+	if (rv != 0 || !res)
+		return -1;
+	memcpy(ip, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4);
+	freeaddrinfo(res);
+	return 0;
+}
+
+int host_net_connect(const unsigned char mac[6], const unsigned char ip[4],
+		     unsigned int port)
+{
+	struct sockaddr_in sa;
+	int fd;
+	int flags;
+	int rv;
+	int err = 0;
+	socklen_t elen = sizeof(err);
+
+	(void)mac;
+	host_net_close();
+	fd = socket(AF_INET, SOCK_STREAM, 0);
+	if (fd < 0)
+		return -3;
+	memset(&sa, 0, sizeof(sa));
+	sa.sin_family = AF_INET;
+	memcpy(&sa.sin_addr, ip, 4);
+	sa.sin_port = htons((unsigned short)port);
+
+	flags = fcntl(fd, F_GETFL, 0);
+	if (flags >= 0)
+		fcntl(fd, F_SETFL, flags | O_NONBLOCK);
+
+	rv = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
+	if (rv != 0 && errno != EINPROGRESS) {
+		int e = errno;
+
+		close(fd);
+		return e == ECONNREFUSED ? -2 : -3;
+	}
+	if (rv != 0) {
+		struct pollfd pfd;
+
+		pfd.fd = fd;
+		pfd.events = POLLOUT;
+		pfd.revents = 0;
+		do {
+			rv = poll(&pfd, 1, 5000);
+		} while (rv < 0 && errno == EINTR);
+		if (rv == 0) {
+			close(fd);
+			return -1;
+		}
+		if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &elen) != 0)
+			err = errno;
+		if (err != 0) {
+			close(fd);
+			if (err == ECONNREFUSED)
+				return -2;
+			if (err == ETIMEDOUT)
+				return -1;
+			return -3;
+		}
+	}
+	{
+		int one = 1;
+		setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
+	}
+	tcp_fd = fd;
+	return 0;
+}
+
+int host_net_send(const void *buf, unsigned int len)
+{
+	const unsigned char *p = (const unsigned char *)buf;
+	unsigned int done = 0;
+
+	if (tcp_fd < 0)
+		return -3;
+	while (done < len) {
+		ssize_t n = send(tcp_fd, p + done, len - done, MSG_NOSIGNAL);
+
+		if (n < 0) {
+			if (errno == EINTR)
+				continue;
+			if (errno == EAGAIN || errno == EWOULDBLOCK) {
+				struct pollfd pfd;
+				int rv;
+
+				pfd.fd = tcp_fd;
+				pfd.events = POLLOUT;
+				pfd.revents = 0;
+				do {
+					rv = poll(&pfd, 1, 5000);
+				} while (rv < 0 && errno == EINTR);
+				if (rv <= 0)
+					return -1;
+				continue;
+			}
+			return (errno == EPIPE || errno == ECONNRESET) ? -2 : -3;
+		}
+		if (n == 0)
+			return -3;
+		done += (unsigned int)n;
+	}
+	return 0;
+}
+
+int host_net_recv(void *buf, unsigned int max, unsigned int timeout_ms)
+{
+	unsigned long long deadline = deadline_ms(timeout_ms);
+
+	if (tcp_fd < 0)
+		return -2;
+	if (max == 0)
+		return 0;
+	for (;;) {
+		struct pollfd pfd;
+		int left = ms_left(deadline);
+		int rv;
+
+		pfd.fd = tcp_fd;
+		pfd.events = POLLIN;
+		pfd.revents = 0;
+		rv = poll(&pfd, 1, left);
+		if (rv < 0) {
+			if (errno == EINTR)
+				continue;
+			return -2;
+		}
+		if (rv == 0)
+			return -1;
+		{
+			ssize_t n = recv(tcp_fd, buf, max, 0);
+
+			if (n > 0)
+				return (int)n;
+			if (n == 0)
+				return 0;
+			if (errno == EINTR)
+				continue;
+			if (errno == EAGAIN || errno == EWOULDBLOCK)
+				continue;
+			return -2;
+		}
+	}
+}
+
+void host_net_close(void)
+{
+	if (tcp_fd >= 0) {
+		close(tcp_fd);
+		tcp_fd = -1;
+	}
+}
+
+int host_net_peer_mss(void)
+{
+	int mss = 0;
+	socklen_t len = sizeof(mss);
+
+	if (tcp_fd >= 0 &&
+	    getsockopt(tcp_fd, IPPROTO_TCP, TCP_MAXSEG, &mss, &len) == 0 &&
+	    mss > 0)
+		return mss;
+	return 1460;
+}
+
+void host_net_info(struct sys_netinfo *out)
+{
+	memset(out, 0, sizeof(*out));
+	out->present = 1;
+	out->link = 1;
+	out->mac[0] = 0x02;
+	out->mac[5] = 0x01;
+	out->ip[0] = 127;
+	out->ip[3] = 1;
+	out->mask[0] = 255;
+	out->mask[1] = 255;
+	out->mask[2] = 255;
+	out->mask[3] = 255;
+	out->dns[0] = 127;
+	out->dns[3] = 1;
+	snprintf(out->name, sizeof(out->name), "host");
+	snprintf(out->chip, sizeof(out->chip), "linux");
+}

+ 15 - 0
host/net.h

@@ -0,0 +1,15 @@
+#ifndef HOST_NET_H
+#define HOST_NET_H
+
+#include "syscall.h"
+
+int host_net_dns(const char *name, unsigned char ip[4]);
+int host_net_connect(const unsigned char mac[6], const unsigned char ip[4],
+		     unsigned int port);
+int host_net_send(const void *buf, unsigned int len);
+int host_net_recv(void *buf, unsigned int max, unsigned int timeout_ms);
+void host_net_close(void);
+int host_net_peer_mss(void);
+void host_net_info(struct sys_netinfo *out);
+
+#endif

+ 149 - 0
host/proc.c

@@ -0,0 +1,149 @@
+/* Tiny process service: fake ttys for the browser's curl helpers. */
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "host.h"
+#include "fs.h"
+#include "proc.h"
+
+#define HOST_TTY_MAX 8
+
+struct host_tty {
+	int used;
+	int rfd;
+	int wfd;
+};
+
+static struct host_tty ttys[HOST_TTY_MAX];
+
+int host_tty_create(void)
+{
+	int i;
+	int fds[2];
+
+	for (i = 0; i < HOST_TTY_MAX; i++) {
+		if (ttys[i].used)
+			continue;
+		if (pipe2(fds, O_NONBLOCK | O_CLOEXEC) != 0)
+			return -1;
+		ttys[i].used = 1;
+		ttys[i].rfd = fds[0];
+		ttys[i].wfd = fds[1];
+		return i + 1;
+	}
+	return -1;
+}
+
+int host_tty_read(int id, char *buf, unsigned int max)
+{
+	ssize_t n;
+
+	if (id <= 0 || id > HOST_TTY_MAX)
+		return -1;
+	id--;
+	if (!ttys[id].used)
+		return -1;
+	n = read(ttys[id].rfd, buf, max);
+	if (n < 0)
+		return (errno == EAGAIN || errno == EWOULDBLOCK) ? 0 : -1;
+	return (int)n;
+}
+
+static const char *exec_path(const char *path, char *buf, size_t cap)
+{
+	if (!path || !path[0])
+		return 0;
+	if (!strcmp(path, "/ramfs/bin/curl") && host_curl_bin[0])
+		return host_curl_bin;
+	if (path[0] == '/') {
+		if (host_guest_to_host(path, buf, cap) != 0)
+			return 0;
+		if (access(buf, X_OK) == 0)
+			return buf;
+	}
+	if (access(path, X_OK) == 0)
+		return path;
+	return 0;
+}
+
+int host_spawn(const char *path, const char *arg, int tty, const char *cwd)
+{
+	char exe_buf[HOST_PATH_MAX];
+	char cwd_buf[HOST_PATH_MAX];
+	const char *exe;
+	const char *cwd_host = 0;
+	pid_t pid;
+
+	exe = exec_path(path, exe_buf, sizeof(exe_buf));
+	if (!exe) {
+		fprintf(stderr, "browser-host: cannot find helper %s\n", path);
+		return -1;
+	}
+	if (cwd && cwd[0] &&
+	    host_guest_to_host(cwd, cwd_buf, sizeof(cwd_buf)) == 0)
+		cwd_host = cwd_buf;
+
+	pid = fork();
+	if (pid < 0)
+		return -1;
+	if (pid == 0) {
+		prctl(PR_SET_PDEATHSIG, SIGKILL);
+		if (tty > 0 && tty <= HOST_TTY_MAX &&
+		    ttys[tty - 1].used) {
+			int wfd = ttys[tty - 1].wfd;
+
+			dup2(wfd, STDOUT_FILENO);
+			dup2(wfd, STDERR_FILENO);
+			close(ttys[tty - 1].rfd);
+			if (wfd > STDERR_FILENO)
+				close(wfd);
+		}
+		if (cwd_host)
+			chdir(cwd_host);
+		if (arg && arg[0]) {
+			char *const argv[] = { (char *)exe, (char *)arg, 0 };
+
+			execv(exe, argv);
+		} else {
+			char *const argv[] = { (char *)exe, 0 };
+
+			execv(exe, argv);
+		}
+		_exit(127);
+	}
+	return (int)pid;
+}
+
+int host_alive(unsigned int pid)
+{
+	int status;
+
+	if (pid == 0)
+		return 0;
+	for (;;) {
+		pid_t r = waitpid((pid_t)pid, &status, WNOHANG);
+
+		if (r == 0)
+			return 1;
+		if (r == (pid_t)pid)
+			return 0;
+		if (errno == EINTR)
+			continue;
+		return 0;
+	}
+}
+
+int host_kill(unsigned int pid)
+{
+	if (pid == 0)
+		return -1;
+	return kill((pid_t)pid, SIGKILL) == 0 ? 0 : -1;
+}

+ 10 - 0
host/proc.h

@@ -0,0 +1,10 @@
+#ifndef HOST_PROC_H
+#define HOST_PROC_H
+
+int host_tty_create(void);
+int host_tty_read(int id, char *buf, unsigned int max);
+int host_spawn(const char *path, const char *arg, int tty, const char *cwd);
+int host_alive(unsigned int pid);
+int host_kill(unsigned int pid);
+
+#endif

+ 343 - 0
host/syscall.c

@@ -0,0 +1,343 @@
+/* Host implementation of the tiny ring-3 syscall ABI.
+ *
+ * This is the whole "platform abstraction layer": the browser, ngui, uhttp
+ * and the image/font code keep calling u_syscall*(), but here they land in
+ * normal Linux calls instead of int 0x80. */
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "host.h"
+#include "fs.h"
+#include "net.h"
+#include "proc.h"
+#include "syscall.h"
+#include "window.h"
+
+static void *argp(int a)
+{
+	return (void *)(uintptr_t)(unsigned int)a;
+}
+
+static unsigned int host_ticks(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return (unsigned int)((unsigned long long)ts.tv_sec * 1000ull +
+			      (unsigned long long)ts.tv_nsec / 1000000ull);
+}
+
+static int rtc_now(struct sys_datetime *dt)
+{
+	time_t t = time(0);
+	struct tm tm;
+
+	if (!gmtime_r(&t, &tm))
+		return -1;
+	dt->year = (unsigned int)(tm.tm_year + 1900);
+	dt->month = (unsigned int)(tm.tm_mon + 1);
+	dt->day = (unsigned int)tm.tm_mday;
+	dt->hour = (unsigned int)tm.tm_hour;
+	dt->minute = (unsigned int)tm.tm_min;
+	dt->second = (unsigned int)tm.tm_sec;
+	dt->wday = (unsigned int)tm.tm_wday;
+	return 0;
+}
+
+static int unsupported(int num)
+{
+	fprintf(stderr, "browser-host: unsupported syscall %d\n", num);
+	return -1;
+}
+
+int u_syscall1(int num, int a1);
+int u_syscall3(int num, int a1, int a2, int a3);
+
+int u_syscall0(int num)
+{
+	return u_syscall1(num, 0);
+}
+
+int u_syscall1(int num, int a1)
+{
+	return u_syscall3(num, a1, 0, 0);
+}
+
+int u_syscall2(int num, int a1, int a2)
+{
+	return u_syscall3(num, a1, a2, 0);
+}
+
+int u_syscall3(int num, int a1, int a2, int a3)
+{
+	switch (num) {
+	case SYS_PUTSTR: {
+		const char *s = (const char *)argp(a1);
+
+		if (s)
+			fputs(s, stdout);
+		return 0;
+	}
+	case SYS_GET_TICKS_MS:
+		return (int)host_ticks();
+	case SYS_SLEEP_MS:
+		host_window_pump((unsigned int)a1);
+		return 0;
+	case SYS_EXIT:
+		fflush(stdout);
+		fflush(stderr);
+		exit(a1);
+		return 0;
+
+	case SYS_READ_FILE:
+		return host_fs_read((const char *)argp(a1), argp(a2),
+				    (unsigned int)a3);
+	case SYS_WRITE_FILE:
+		return host_fs_write((const char *)argp(a1), argp(a2),
+				     (unsigned int)a3);
+	case SYS_LIST_DIR:
+		return host_fs_list((const char *)argp(a1), (unsigned int)a2,
+				    argp(a3));
+	case SYS_UNLINK:
+		return host_fs_unlink((const char *)argp(a1));
+	case SYS_MKDIR:
+		return host_fs_mkdir((const char *)argp(a1));
+	case SYS_RMDIR:
+		return host_fs_rmdir((const char *)argp(a1));
+
+	case SYS_GETCWD: {
+		char *buf = (char *)argp(a1);
+
+		if (!buf || !a2)
+			return -1;
+		return getcwd(buf, (size_t)a2) ? 0 : -1;
+	}
+	case SYS_CHDIR: {
+		char host[HOST_PATH_MAX];
+
+		if (host_guest_to_host((const char *)argp(a1), host,
+				       sizeof(host)) != 0)
+			return -1;
+		return chdir(host) == 0 ? 0 : -1;
+	}
+	case SYS_FS_STAT: {
+		struct sys_stat *st = (struct sys_stat *)argp(a2);
+
+		if (!st)
+			return -1;
+		memset(st, 0, sizeof(*st));
+		if (host_fs_stat((const char *)argp(a1), &st->size,
+				 &st->is_dir) != 0)
+			return -1;
+		return 0;
+	}
+
+	case SYS_RTC_HMS: {
+		struct sys_time *out = (struct sys_time *)argp(a1);
+		struct sys_datetime dt;
+
+		if (!out || rtc_now(&dt) != 0)
+			return -1;
+		out->hour = dt.hour;
+		out->minute = dt.minute;
+		out->second = dt.second;
+		return 0;
+	}
+	case SYS_RTC_GET: {
+		struct sys_datetime *out = (struct sys_datetime *)argp(a1);
+
+		if (!out)
+			return -1;
+		return rtc_now(out);
+	}
+	case SYS_RTC_SET:
+		return -1;
+
+	case SYS_KEY_POLL:
+		return host_window_key();
+	case SYS_WIN_KEY_WAIT:
+		return host_window_key_wait((unsigned int)a1);
+
+	case SYS_WIN_CREATE: {
+		const struct win_create *in =
+			(const struct win_create *)argp(a1);
+		struct win_info *out = (struct win_info *)argp(a2);
+		int w, h;
+
+		if (!in || !out)
+			return -1;
+		w = host_opts.width ? host_opts.width : (int)in->w;
+		h = host_opts.height ? host_opts.height : (int)in->h;
+		if (w <= 0 || h <= 0)
+			return -1;
+		if (host_window_open((unsigned int)w, (unsigned int)h,
+				     in->title) != 0)
+			return -1;
+		out->fb = host_window_fb();
+		out->width = host_window_width();
+		out->height = host_window_height();
+		out->id = 1;
+		return 0;
+	}
+	case SYS_WIN_PRESENT:
+		host_window_present(0, 0, host_window_width(),
+				    host_window_height());
+		return 0;
+	case SYS_WIN_CLOSE:
+		host_window_close();
+		return 0;
+	case SYS_WIN_INFO: {
+		struct win_info *out = (struct win_info *)argp(a1);
+
+		if (!out || !host_window_fb())
+			return -1;
+		out->fb = host_window_fb();
+		out->width = host_window_width();
+		out->height = host_window_height();
+		out->id = 1;
+		return 0;
+	}
+	case SYS_WIN_ACK_RESIZE:
+		return 0;
+	case SYS_WIN_POINTER:
+		return host_window_pointer((struct win_pointer *)argp(a1));
+	case SYS_WIN_EVENT:
+		return host_window_event((struct win_event *)argp(a1));
+	case SYS_WIN_SCROLL:
+		return host_window_scroll((struct win_scroll *)argp(a1));
+	case SYS_WIN_RESIZE_SELF:
+		return -1;
+	case SYS_SCREEN_INFO: {
+		struct sys_screen *out = (struct sys_screen *)argp(a1);
+
+		if (!out)
+			return -1;
+		return host_window_screen(&out->width, &out->height);
+	}
+
+	case SYS_TTY_CREATE:
+		return host_tty_create();
+	case SYS_TTY_READ:
+		return host_tty_read(a1, (char *)argp(a2),
+				     (unsigned int)a3);
+	case SYS_SPAWN: {
+		const struct sys_spawn *sp =
+			(const struct sys_spawn *)argp(a1);
+
+		if (!sp)
+			return -1;
+		return host_spawn(sp->path, sp->arg, (int)sp->tty, sp->cwd);
+	}
+	case SYS_ALIVE:
+		return host_alive((unsigned int)a1);
+	case SYS_KILL:
+		return host_kill((unsigned int)a1);
+	case SYS_GETPID:
+		return (int)getpid();
+
+	case SYS_NET_INFO: {
+		struct sys_netinfo *out = (struct sys_netinfo *)argp(a1);
+
+		if (!out)
+			return 0;
+		host_net_info(out);
+		return 1;
+	}
+	case SYS_NET_CONFIGURED:
+		return 1;
+	case SYS_NET_ACQUIRE:
+	case SYS_NET_RELEASE:
+		return 0;
+	case SYS_NET_NEXT_HOP: {
+		const unsigned char *dst = (const unsigned char *)argp(a1);
+		unsigned char *hop = (unsigned char *)argp(a2);
+
+		if (dst && hop)
+			memcpy(hop, dst, 4);
+		return 0;
+	}
+	case SYS_NET_ARP: {
+		unsigned char *mac = (unsigned char *)argp(a2);
+
+		if (mac) {
+			mac[0] = 0x02;
+			mac[1] = mac[2] = mac[3] = mac[4] = 0;
+			mac[5] = 0x01;
+		}
+		return 0;
+	}
+	case SYS_DNS_RESOLVE:
+		return host_net_dns((const char *)argp(a1),
+				    (unsigned char *)argp(a2));
+	case SYS_TCP_CONNECT:
+		return host_net_connect((const unsigned char *)argp(a1),
+					(const unsigned char *)argp(a2),
+					(unsigned int)a3);
+	case SYS_TCP_PEER_MSS:
+		return host_net_peer_mss();
+	case SYS_TCP_SEND:
+		return host_net_send(argp(a1), (unsigned int)a2);
+	case SYS_TCP_RECV:
+		return host_net_recv(argp(a1), (unsigned int)a2,
+				     (unsigned int)a3);
+	case SYS_TCP_CLOSE:
+		host_net_close();
+		return 0;
+	case SYS_NET_GET_IP: {
+		unsigned char *ip = (unsigned char *)argp(a1);
+
+		if (ip) {
+			ip[0] = 127;
+			ip[1] = ip[2] = 0;
+			ip[3] = 1;
+		}
+		return 0;
+	}
+	case SYS_NET_GET_MASK: {
+		unsigned char *ip = (unsigned char *)argp(a1);
+
+		if (ip)
+			memset(ip, 0xFF, 4);
+		return 0;
+	}
+	case SYS_NET_GET_GW:
+	case SYS_NET_GET_DNS: {
+		unsigned char *ip = (unsigned char *)argp(a1);
+
+		if (ip) {
+			ip[0] = 127;
+			ip[1] = ip[2] = 0;
+			ip[3] = 1;
+		}
+		return 0;
+	}
+	case SYS_NET_MAC: {
+		unsigned char *mac = (unsigned char *)argp(a1);
+
+		if (mac) {
+			mac[0] = 0x02;
+			mac[1] = mac[2] = mac[3] = mac[4] = 0;
+			mac[5] = 0x01;
+		}
+		return 0;
+	}
+	case SYS_NET_PRINT_INFO:
+		fprintf(stderr, "browser-host: netdev host (linux)\n");
+		return 0;
+	case SYS_NETLOG: {
+		const char *s = (const char *)argp(a1);
+
+		if (s)
+			fprintf(stderr, "%s\n", s);
+		return 0;
+	}
+
+	default:
+		return unsupported(num);
+	}
+}

+ 137 - 0
host/window.c

@@ -0,0 +1,137 @@
+/* Backend selection for the host window. */
+#include <unistd.h>
+
+#include "host.h"
+#include "window.h"
+
+static int open;
+static int headless;
+
+int host_window_open(unsigned int w, unsigned int h, const char *title)
+{
+	int rv;
+
+	if (open) {
+		if ((unsigned int)host_window_width() == w &&
+		    (unsigned int)host_window_height() == h)
+			return 0;
+		return -1;
+	}
+	headless = host_opts.headless ? 1 : 0;
+	rv = headless ? host_headless_open(w, h, title) :
+			host_sdl_open(w, h, title);
+	if (rv == 0)
+		open = 1;
+	return rv;
+}
+
+void host_window_close(void)
+{
+	if (!open)
+		return;
+	if (headless)
+		host_headless_close();
+	else
+		host_sdl_close();
+	open = 0;
+}
+
+void *host_window_fb(void)
+{
+	if (!open)
+		return 0;
+	return headless ? host_headless_fb() : host_sdl_fb();
+}
+
+unsigned int host_window_width(void)
+{
+	if (!open)
+		return 0;
+	return headless ? host_headless_width() : host_sdl_width();
+}
+
+unsigned int host_window_height(void)
+{
+	if (!open)
+		return 0;
+	return headless ? host_headless_height() : host_sdl_height();
+}
+
+void host_window_present(int x, int y, unsigned int w, unsigned int h)
+{
+	(void)x;
+	(void)y;
+	(void)w;
+	(void)h;
+	if (!open)
+		return;
+	if (headless)
+		host_headless_present();
+	else
+		host_sdl_present();
+}
+
+void host_window_pump(unsigned int timeout_ms)
+{
+	if (!open) {
+		if (timeout_ms)
+			usleep(timeout_ms * 1000u);
+		return;
+	}
+	if (headless)
+		host_headless_pump(timeout_ms);
+	else
+		host_sdl_pump(timeout_ms);
+}
+
+int host_window_pointer(struct win_pointer *out)
+{
+	if (!open)
+		return -1;
+	return headless ? host_headless_pointer(out) : host_sdl_pointer(out);
+}
+
+int host_window_event(struct win_event *out)
+{
+	if (!open)
+		return 0;
+	return headless ? host_headless_event(out) : host_sdl_event(out);
+}
+
+int host_window_scroll(struct win_scroll *out)
+{
+	if (!open)
+		return 0;
+	return headless ? host_headless_scroll(out) : host_sdl_scroll(out);
+}
+
+int host_window_key(void)
+{
+	if (!open)
+		return 0;
+	return headless ? host_headless_key() : host_sdl_key();
+}
+
+int host_window_screen(unsigned int *w, unsigned int *h)
+{
+	if (!open)
+		return -1;
+	return headless ? host_headless_screen(w, h) : host_sdl_screen(w, h);
+}
+
+int host_window_key_wait(unsigned int timeout_ms)
+{
+	if (!open) {
+		host_window_pump(timeout_ms);
+		return 0;
+	}
+	return headless ? host_headless_key_wait(timeout_ms) :
+			 host_sdl_key_wait(timeout_ms);
+}
+
+const char *host_window_backend(void)
+{
+	if (!open)
+		return "none";
+	return headless ? host_headless_backend() : host_sdl_backend();
+}

+ 54 - 0
host/window.h

@@ -0,0 +1,54 @@
+/* Platform window backend for the host browser harness. */
+#ifndef HOST_WINDOW_H
+#define HOST_WINDOW_H
+
+#include "syscall.h"
+#include "wm_abi.h"
+
+int host_window_open(unsigned int w, unsigned int h, const char *title);
+void host_window_close(void);
+void *host_window_fb(void);
+unsigned int host_window_width(void);
+unsigned int host_window_height(void);
+void host_window_present(int x, int y, unsigned int w, unsigned int h);
+void host_window_pump(unsigned int timeout_ms);
+int host_window_pointer(struct win_pointer *out);
+int host_window_event(struct win_event *out);
+int host_window_scroll(struct win_scroll *out);
+int host_window_key(void);
+int host_window_screen(unsigned int *w, unsigned int *h);
+int host_window_key_wait(unsigned int timeout_ms);
+const char *host_window_backend(void);
+
+/* Active backend (window.c selects by host_opts.headless). */
+void host_sdl_close(void);
+int host_sdl_open(unsigned int w, unsigned int h, const char *title);
+void *host_sdl_fb(void);
+unsigned int host_sdl_width(void);
+unsigned int host_sdl_height(void);
+void host_sdl_present(void);
+void host_sdl_pump(unsigned int timeout_ms);
+int host_sdl_pointer(struct win_pointer *out);
+int host_sdl_event(struct win_event *out);
+int host_sdl_scroll(struct win_scroll *out);
+int host_sdl_key(void);
+int host_sdl_screen(unsigned int *w, unsigned int *h);
+int host_sdl_key_wait(unsigned int timeout_ms);
+const char *host_sdl_backend(void);
+
+void host_headless_close(void);
+int host_headless_open(unsigned int w, unsigned int h, const char *title);
+void *host_headless_fb(void);
+unsigned int host_headless_width(void);
+unsigned int host_headless_height(void);
+void host_headless_present(void);
+void host_headless_pump(unsigned int timeout_ms);
+int host_headless_pointer(struct win_pointer *out);
+int host_headless_event(struct win_event *out);
+int host_headless_scroll(struct win_scroll *out);
+int host_headless_key(void);
+int host_headless_screen(unsigned int *w, unsigned int *h);
+int host_headless_key_wait(unsigned int timeout_ms);
+const char *host_headless_backend(void);
+
+#endif

+ 152 - 0
host/window_headless.c

@@ -0,0 +1,152 @@
+/* Headless window backend: renders into the same RGB565 canvas and writes a
+ * PPM after the first present plus host_opts.wait_ms. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "host.h"
+#include "window.h"
+
+static unsigned short *fb;
+static int win_w, win_h;
+static int presented;
+static unsigned long long first_present;
+
+static unsigned long long now_ms(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return (unsigned long long)ts.tv_sec * 1000ull +
+	       (unsigned long long)ts.tv_nsec / 1000000ull;
+}
+
+static int write_ppm(const char *path)
+{
+	FILE *f;
+	int x, y;
+
+	if (!path || !path[0])
+		return -1;
+	f = fopen(path, "wb");
+	if (!f)
+		return -1;
+	fprintf(f, "P6\n%d %d\n255\n", win_w, win_h);
+	for (y = 0; y < win_h; y++) {
+		for (x = 0; x < win_w; x++) {
+			unsigned int v = fb[y * win_w + x];
+			unsigned char rgb[3];
+
+			rgb[0] = (unsigned char)(((v >> 11) & 31) * 255 / 31);
+			rgb[1] = (unsigned char)(((v >> 5) & 63) * 255 / 63);
+			rgb[2] = (unsigned char)((v & 31) * 255 / 31);
+			fwrite(rgb, 1, 3, f);
+		}
+	}
+	fclose(f);
+	fprintf(stderr, "browser-host: wrote %s (%dx%d)\n", path, win_w,
+		win_h);
+	return 0;
+}
+
+int host_headless_open(unsigned int w, unsigned int h, const char *title)
+{
+	(void)title;
+	fb = (unsigned short *)calloc((size_t)w * h, sizeof(unsigned short));
+	if (!fb)
+		return -1;
+	win_w = (int)w;
+	win_h = (int)h;
+	presented = 0;
+	first_present = 0;
+	return 0;
+}
+
+void host_headless_close(void)
+{
+	free(fb);
+	fb = 0;
+}
+
+void *host_headless_fb(void)
+{
+	return fb;
+}
+
+unsigned int host_headless_width(void)
+{
+	return (unsigned int)win_w;
+}
+
+unsigned int host_headless_height(void)
+{
+	return (unsigned int)win_h;
+}
+
+void host_headless_present(void)
+{
+	if (!presented) {
+		presented = 1;
+		first_present = now_ms();
+	}
+}
+
+void host_headless_pump(unsigned int timeout_ms)
+{
+	if (presented && host_opts.wait_ms) {
+		unsigned long long now = now_ms();
+
+		if (now - first_present >= host_opts.wait_ms) {
+			write_ppm(host_opts.shot);
+			fflush(stdout);
+			_exit(0);
+		}
+	}
+	if (timeout_ms)
+		usleep(timeout_ms * 1000u);
+}
+
+int host_headless_pointer(struct win_pointer *out)
+{
+	memset(out, 0, sizeof(*out));
+	out->focused = 1;
+	out->inside = 1;
+	return 0;
+}
+
+int host_headless_event(struct win_event *out)
+{
+	(void)out;
+	return 0;
+}
+
+int host_headless_scroll(struct win_scroll *out)
+{
+	(void)out;
+	return 0;
+}
+
+int host_headless_key(void)
+{
+	return 0;
+}
+
+int host_headless_screen(unsigned int *w, unsigned int *h)
+{
+	*w = (unsigned int)win_w;
+	*h = (unsigned int)win_h;
+	return 0;
+}
+
+int host_headless_key_wait(unsigned int timeout_ms)
+{
+	host_headless_pump(timeout_ms);
+	return 0;
+}
+
+const char *host_headless_backend(void)
+{
+	return "headless";
+}

+ 461 - 0
host/window_sdl3.c

@@ -0,0 +1,461 @@
+/* SDL3 window backend for the host browser harness.
+ *
+ * SDL3 selects the Wayland driver on this desktop (and falls back to X11 if
+ * it cannot connect); the browser still owns a plain RGB565 canvas and only
+ * sees the generic win_* ABI through host/syscall.c. */
+#include <SDL3/SDL.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "window.h"
+
+#define KEYQ_MAX 256
+#define EVQ_MAX  64
+
+static SDL_Window *win;
+static SDL_Renderer *ren;
+static SDL_Texture *tex;
+static unsigned short *fb;
+static int win_w, win_h;
+static int inited;
+static int focused;
+static int inside;
+static int close_sent;
+static int mouse_x, mouse_y;
+static unsigned mouse_buttons;
+static int scroll_x, scroll_y;
+static char backend[32] = "none";
+
+static int keyq[KEYQ_MAX];
+static unsigned int key_head, key_tail;
+static struct win_event evq[EVQ_MAX];
+static unsigned int ev_head, ev_tail;
+
+static void push_key(int k)
+{
+	unsigned int next = (key_head + 1) % KEYQ_MAX;
+
+	if (next == key_tail)
+		return;
+	keyq[key_head] = k;
+	key_head = next;
+}
+
+static int pop_key(void)
+{
+	int k;
+
+	if (key_tail == key_head)
+		return 0;
+	k = keyq[key_tail];
+	key_tail = (key_tail + 1) % KEYQ_MAX;
+	return k;
+}
+
+static void push_event(unsigned int type, int x, int y)
+{
+	unsigned int next = (ev_head + 1) % EVQ_MAX;
+	struct win_event *ev;
+
+	if (next == ev_tail)
+		return;
+	ev = &evq[ev_head];
+	ev->type = type;
+	ev->x = x;
+	ev->y = y;
+	ev->buttons = mouse_buttons;
+	ev_head = next;
+}
+
+static unsigned int neb_buttons(Uint32 state)
+{
+	unsigned int b = 0;
+
+	if (state & SDL_BUTTON_LMASK)
+		b |= 1;
+	if (state & SDL_BUTTON_RMASK)
+		b |= 2;
+	if (state & SDL_BUTTON_MMASK)
+		b |= 4;
+	return b;
+}
+
+static void set_mouse(float x, float y, Uint32 state)
+{
+	mouse_x = (int)x;
+	mouse_y = (int)y;
+	mouse_buttons = neb_buttons(state);
+	inside = mouse_x >= 0 && mouse_y >= 0 &&
+		 mouse_x < win_w && mouse_y < win_h;
+}
+
+static void key_down(const SDL_KeyboardEvent *e)
+{
+	SDL_Keycode k = e->key;
+	SDL_Keymod mod = e->mod;
+	int ctrl = (mod & SDL_KMOD_CTRL) != 0;
+
+	/* Ctrl+letter -> ASCII control code (Ctrl+L = 0x0C, Ctrl+R = 0x12). */
+	if (ctrl && k >= SDLK_A && k <= SDLK_Z) {
+		push_key((int)(k - SDLK_A + 1));
+		return;
+	}
+
+	switch (k) {
+	case SDLK_ESCAPE:
+		push_key(0x1B);
+		return;
+	case SDLK_BACKSPACE:
+		push_key(ctrl ? 0x10C : 0x08);
+		return;
+	case SDLK_TAB:
+		push_key(0x09);
+		return;
+	case SDLK_RETURN:
+	case SDLK_KP_ENTER:
+		push_key('\n');
+		return;
+	case SDLK_DELETE:
+		push_key(ctrl ? 0x10B : 0x108);
+		return;
+	case SDLK_LEFT:
+		push_key(ctrl ? 0x109 : 0x100);
+		return;
+	case SDLK_RIGHT:
+		push_key(ctrl ? 0x10A : 0x101);
+		return;
+	case SDLK_UP:
+		push_key(0x102);
+		return;
+	case SDLK_DOWN:
+		push_key(0x103);
+		return;
+	case SDLK_PAGEUP:
+		push_key(0x104);
+		return;
+	case SDLK_PAGEDOWN:
+		push_key(0x105);
+		return;
+	case SDLK_HOME:
+		push_key(0x106);
+		return;
+	case SDLK_END:
+		push_key(0x107);
+		return;
+	default:
+		break;
+	}
+	/* Printable characters arrive through SDL_EVENT_TEXT_INPUT, which
+	 * honours the keyboard layout and key repeat. */
+}
+
+static void text_utf8(const char *s)
+{
+	const unsigned char *p = (const unsigned char *)s;
+
+	while (p && *p) {
+		unsigned int cp;
+		int n;
+
+		if (*p < 0x80) {
+			cp = *p++;
+			n = 0;
+		} else if ((*p & 0xE0) == 0xC0) {
+			cp = *p++ & 0x1F;
+			n = 1;
+		} else if ((*p & 0xF0) == 0xE0) {
+			cp = *p++ & 0x0F;
+			n = 2;
+		} else if ((*p & 0xF8) == 0xF0) {
+			cp = *p++ & 0x07;
+			n = 3;
+		} else {
+			p++;
+			continue;
+		}
+		while (n-- > 0) {
+			if ((*p & 0xC0) != 0x80) {
+				cp = 0xFFFD;
+				break;
+			}
+			cp = (cp << 6) | (*p++ & 0x3F);
+		}
+		if (cp == '\r' || cp == '\n')
+			push_key('\n');
+		else if (cp >= 0x20 && cp <= 0xFF)
+			push_key((int)cp);
+		else if (cp > 0xFF)
+			push_key('?');
+	}
+}
+
+static void handle_event(SDL_Event *e)
+{
+	switch (e->type) {
+	case SDL_EVENT_QUIT:
+	case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
+		if (!close_sent) {
+			close_sent = 1;
+			push_key(0x1B);
+		}
+		break;
+	case SDL_EVENT_WINDOW_FOCUS_GAINED:
+		focused = 1;
+		break;
+	case SDL_EVENT_WINDOW_FOCUS_LOST:
+		focused = 0;
+		break;
+	case SDL_EVENT_WINDOW_MOUSE_ENTER:
+		inside = 1;
+		break;
+	case SDL_EVENT_WINDOW_MOUSE_LEAVE:
+		inside = 0;
+		break;
+	case SDL_EVENT_MOUSE_MOTION:
+		set_mouse(e->motion.x, e->motion.y, e->motion.state);
+		break;
+	case SDL_EVENT_MOUSE_BUTTON_DOWN:
+	case SDL_EVENT_MOUSE_BUTTON_UP: {
+		unsigned int bit = 0;
+
+		if (e->button.button == SDL_BUTTON_LEFT)
+			bit = 1;
+		else if (e->button.button == SDL_BUTTON_RIGHT)
+			bit = 2;
+		else if (e->button.button == SDL_BUTTON_MIDDLE)
+			bit = 4;
+		mouse_x = (int)e->button.x;
+		mouse_y = (int)e->button.y;
+		inside = mouse_x >= 0 && mouse_y >= 0 &&
+			 mouse_x < win_w && mouse_y < win_h;
+		if (bit) {
+			if (e->type == SDL_EVENT_MOUSE_BUTTON_DOWN)
+				mouse_buttons |= bit;
+			else
+				mouse_buttons &= ~bit;
+			push_event(e->type == SDL_EVENT_MOUSE_BUTTON_DOWN ?
+				   WIN_EV_POINTER_DOWN : WIN_EV_POINTER_UP,
+				   mouse_x, mouse_y);
+		}
+		break;
+	}
+	case SDL_EVENT_MOUSE_WHEEL:
+		/* SDL's y is positive away from the user; the browser wants
+		 * +dy = later content. */
+		scroll_x += (int)(-e->wheel.x * 48.0f);
+		scroll_y += (int)(-e->wheel.y * 48.0f);
+		break;
+	case SDL_EVENT_KEY_DOWN:
+		key_down(&e->key);
+		break;
+	case SDL_EVENT_TEXT_INPUT:
+		text_utf8(e->text.text);
+		break;
+	default:
+		break;
+	}
+}
+
+int host_sdl_open(unsigned int w, unsigned int h, const char *title)
+{
+	const char *drv;
+
+	if (inited)
+		return (win_w == (int)w && win_h == (int)h) ? 0 : -1;
+	if (!SDL_Init(SDL_INIT_VIDEO)) {
+		fprintf(stderr, "browser-host: SDL_Init: %s\n", SDL_GetError());
+		return -1;
+	}
+	drv = SDL_GetCurrentVideoDriver();
+	snprintf(backend, sizeof(backend), "%s", drv ? drv : "?");
+	win = SDL_CreateWindow(title ? title : "Browser", (int)w, (int)h, 0);
+	if (!win) {
+		fprintf(stderr, "browser-host: SDL_CreateWindow: %s\n",
+			SDL_GetError());
+		SDL_Quit();
+		return -1;
+	}
+	ren = SDL_CreateRenderer(win, 0);
+	if (!ren)
+		ren = SDL_CreateRenderer(win, "software");
+	if (!ren) {
+		fprintf(stderr, "browser-host: SDL_CreateRenderer: %s\n",
+			SDL_GetError());
+		SDL_DestroyWindow(win);
+		win = 0;
+		SDL_Quit();
+		return -1;
+	}
+	SDL_SetRenderVSync(ren, 0);
+	tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_RGB565,
+				SDL_TEXTUREACCESS_STREAMING, (int)w, (int)h);
+	if (!tex) {
+		fprintf(stderr, "browser-host: SDL_CreateTexture: %s\n",
+			SDL_GetError());
+		SDL_DestroyRenderer(ren);
+		ren = 0;
+		SDL_DestroyWindow(win);
+		win = 0;
+		SDL_Quit();
+		return -1;
+	}
+	SDL_SetTextureScaleMode(tex, SDL_SCALEMODE_NEAREST);
+	SDL_SetWindowResizable(win, false);
+	SDL_SetWindowMinimumSize(win, (int)w, (int)h);
+	SDL_SetWindowMaximumSize(win, (int)w, (int)h);
+	SDL_StartTextInput(win);
+
+	fb = (unsigned short *)calloc((size_t)w * h, sizeof(unsigned short));
+	if (!fb) {
+		SDL_DestroyTexture(tex);
+		tex = 0;
+		SDL_DestroyRenderer(ren);
+		ren = 0;
+		SDL_DestroyWindow(win);
+		win = 0;
+		SDL_Quit();
+		return -1;
+	}
+	win_w = (int)w;
+	win_h = (int)h;
+	focused = 1;
+	inside = 1;
+	inited = 1;
+	fprintf(stderr, "browser-host: video driver=%s window=%ux%u\n",
+		backend, w, h);
+	return 0;
+}
+
+void host_sdl_close(void)
+{
+	if (!inited)
+		return;
+	SDL_StopTextInput(win);
+	free(fb);
+	fb = 0;
+	SDL_DestroyTexture(tex);
+	tex = 0;
+	SDL_DestroyRenderer(ren);
+	ren = 0;
+	SDL_DestroyWindow(win);
+	win = 0;
+	SDL_Quit();
+	inited = 0;
+}
+
+void *host_sdl_fb(void)
+{
+	return fb;
+}
+
+unsigned int host_sdl_width(void)
+{
+	return (unsigned int)win_w;
+}
+
+unsigned int host_sdl_height(void)
+{
+	return (unsigned int)win_h;
+}
+
+void host_sdl_present(void)
+{
+	if (!inited || !tex)
+		return;
+	if (!SDL_UpdateTexture(tex, 0, fb, win_w * (int)sizeof(unsigned short)))
+		return;
+	SDL_SetRenderDrawColor(ren, 0, 0, 0, 255);
+	SDL_RenderClear(ren);
+	SDL_RenderTexture(ren, tex, 0, 0);
+	SDL_RenderPresent(ren);
+}
+
+void host_sdl_pump(unsigned int timeout_ms)
+{
+	SDL_Event e;
+
+	if (!inited) {
+		if (timeout_ms)
+			usleep(timeout_ms * 1000u);
+		return;
+	}
+	if (timeout_ms) {
+		if (SDL_WaitEventTimeout(&e, (Sint32)timeout_ms))
+			handle_event(&e);
+	} else {
+		SDL_PumpEvents();
+	}
+	while (SDL_PollEvent(&e))
+		handle_event(&e);
+}
+
+int host_sdl_pointer(struct win_pointer *out)
+{
+	SDL_WindowFlags flags;
+
+	if (!inited)
+		return -1;
+	flags = SDL_GetWindowFlags(win);
+	focused = (flags & SDL_WINDOW_INPUT_FOCUS) ? 1 : 0;
+	out->x = mouse_x;
+	out->y = mouse_y;
+	out->buttons = mouse_buttons;
+	out->inside = inside ? 1u : 0u;
+	out->focused = focused ? 1u : 0u;
+	return 0;
+}
+
+int host_sdl_event(struct win_event *out)
+{
+	if (ev_tail == ev_head)
+		return 0;
+	*out = evq[ev_tail];
+	ev_tail = (ev_tail + 1) % EVQ_MAX;
+	return 1;
+}
+
+int host_sdl_scroll(struct win_scroll *out)
+{
+	if (!scroll_x && !scroll_y)
+		return 0;
+	out->dx = scroll_x;
+	out->dy = scroll_y;
+	scroll_x = scroll_y = 0;
+	return 1;
+}
+
+int host_sdl_key(void)
+{
+	return pop_key();
+}
+
+int host_sdl_screen(unsigned int *w, unsigned int *h)
+{
+	SDL_Rect r;
+
+	if (SDL_GetDisplayBounds(SDL_GetPrimaryDisplay(), &r)) {
+		*w = (unsigned int)r.w;
+		*h = (unsigned int)r.h;
+	} else {
+		*w = (unsigned int)win_w;
+		*h = (unsigned int)win_h;
+	}
+	return 0;
+}
+
+int host_sdl_key_wait(unsigned int timeout_ms)
+{
+	int k = pop_key();
+
+	if (k)
+		return k;
+	host_sdl_pump(timeout_ms);
+	return pop_key();
+}
+
+const char *host_sdl_backend(void)
+{
+	return backend;
+}

+ 5 - 2
img.c

@@ -151,8 +151,11 @@ int img_decode(const void *data, unsigned int len,
 		r = IMG_ERR_UNSUPPORTED;
 		break;
 	}
-	if (r == 0 && (!out->px || out->w != info.width ||
-		       out->h != info.height))
+	if (r == 0 && (!out->px || out->w == 0 || out->h == 0))
+		return IMG_ERR_CORRUPT;
+	/* A decoder may legitimately return a reduced bitmap (the JPEG IDCT
+	 * scale); it must never be larger than the intrinsic size. */
+	if (r == 0 && (out->w > info.width || out->h > info.height))
 		return IMG_ERR_CORRUPT;
 	return r;
 }

+ 4 - 0
img.h

@@ -50,6 +50,10 @@ struct img_info {
 struct img_options {
 	/* 0 = no additional limit beyond the arena / sanity checks. */
 	unsigned int max_pixels;
+	/* Optional output bounds.  The JPEG decoder picks a reduced IDCT
+	 * scale when it can (1/2, 1/4, 1/8); other decoders ignore these and
+	 * are scaled by the caller.  0 = unbounded. */
+	unsigned int max_w, max_h;
 };
 
 struct img_mem {

+ 67 - 2
img_blit.c

@@ -94,9 +94,12 @@ void img_draw(const struct img_image *im, const struct img_blit *b)
 	if (lx >= rx || ty >= by)
 		return;
 
-	/* 1:1, opaque, neat copy. */
+	/* 1:1, opaque: a straight copy.  OVER_DST and CHECKER only describe
+	 * the colour behind transparent pixels, and an opaque source never
+	 * blends, so an image drawn over the page can still take this path
+	 * (the browser sets OVER_DST on every image). */
 	if (b->scale == 65536u && !im->alpha &&
-	    !(b->flags & (IMG_BLIT_CHECKER | IMG_BLIT_OVER_DST))) {
+	    !(b->flags & IMG_BLIT_SAVE_ALPHA)) {
 		for (y = ty; y < by; y++) {
 			int sy = y - b->y;
 			const unsigned short *src = im->px + (unsigned int)sy * im->w;
@@ -108,6 +111,68 @@ void img_draw(const struct img_image *im, const struct img_blit *b)
 		return;
 	}
 
+	/* 1:1 with alpha: blend in RGB565 directly.  get_px() and blend()
+	 * expand every channel to 8 bits and divide by 255; this path only
+	 * needs one multiply-add per channel and is what transparent logos
+	 * and icons hit on every scroll/paint once the bitmap is cached at
+	 * the display size. */
+	if (b->scale == 65536u && im->alpha &&
+	    !(b->flags & IMG_BLIT_SAVE_ALPHA)) {
+		for (y = ty; y < by; y++) {
+			int sy = y - b->y;
+			const unsigned short *src = im->px +
+				(unsigned int)sy * im->w;
+			const unsigned char *sa = im->alpha +
+				(unsigned int)sy * im->w;
+			unsigned short *dst = b->dst +
+				(unsigned int)y * b->dst_w;
+
+			for (x = lx; x < rx; x++) {
+				unsigned int a = sa[x - b->x];
+				unsigned short s = src[x - b->x];
+				unsigned short d;
+
+				if (b->flags & IMG_BLIT_OVER_DST)
+					d = dst[x];
+				else if (b->flags & IMG_BLIT_CHECKER)
+					d = ((x >> 3) ^ (y >> 3)) & 1 ?
+						(unsigned short)b->bg2 :
+						(unsigned short)b->bg;
+				else
+					d = (unsigned short)b->bg;
+				if (a == 0) {
+					dst[x] = d;
+					continue;
+				}
+				if (a == 255) {
+					dst[x] = s;
+					continue;
+				}
+				{
+					unsigned int sr = (s >> 11) & 31;
+					unsigned int sg = (s >> 5) & 63;
+					unsigned int sb = s & 31;
+					unsigned int dr = (d >> 11) & 31;
+					unsigned int dg = (d >> 5) & 63;
+					unsigned int db = d & 31;
+					unsigned int r = (sr * a +
+							  dr * (255 - a) +
+							  127) / 255;
+					unsigned int g = (sg * a +
+							  dg * (255 - a) +
+							  127) / 255;
+					unsigned int bl = (sb * a +
+							   db * (255 - a) +
+							   127) / 255;
+
+					dst[x] = (unsigned short)((r << 11) |
+								  (g << 5) | bl);
+				}
+			}
+		}
+		return;
+	}
+
 	for (y = ty; y < by; y++) {
 		unsigned long long sy_fp =
 			(unsigned long long)(y - b->y) * step;

+ 261 - 19
img_jpeg.c

@@ -29,6 +29,17 @@ static const unsigned char zigzag[64] = {
 #define FIX_2_053119869  16819
 #define FIX_2_562915447  20995
 #define FIX_3_072711026  25172
+/* Scaled (4x4/2x2) IDCT constants, IJG/Loeffler. */
+#define FIX_0_211164243  1730
+#define FIX_0_509795579  4176
+#define FIX_0_601344887  4926
+#define FIX_0_720959822  5906
+#define FIX_0_850430095  6967
+#define FIX_1_061594337  8697
+#define FIX_1_272758580  10426
+#define FIX_1_451774981  11893
+#define FIX_2_172734803  17799
+#define FIX_3_624509785  29692
 
 static int descale(int x, int n)
 {
@@ -187,6 +198,199 @@ static void idct_block(const int *in, unsigned char *out)
 	}
 }
 
+#define SCALED_OUT(v, n) do { \
+	int _v = descale((v), (n)) + 128; \
+	if (_v < 0) _v = 0; \
+	if (_v > 255) _v = 255; \
+	*out++ = (unsigned char)_v; \
+} while (0)
+
+/* Reduced 4x4 output from the low-frequency coefficients.  This is the
+ * Loeffler/IGJ scaled IDCT: an 8-point column pass and a 4-point row pass,
+ * ignoring the coefficients the 4x4 output cannot represent.  It is the
+ * same result as decoding to 8x8 and box-filtering, at roughly a quarter
+ * of the work. */
+static void idct_block_4x4(const int *in, unsigned char *out)
+{
+	int ws[8 * 4];
+	int ctr;
+
+	for (ctr = 0; ctr < 8; ctr++) {
+		int *w = ws + ctr;
+
+		if (ctr == 4)
+			continue;
+		if (in[1 * 8 + ctr] == 0 && in[2 * 8 + ctr] == 0 &&
+		    in[3 * 8 + ctr] == 0 && in[5 * 8 + ctr] == 0 &&
+		    in[6 * 8 + ctr] == 0 && in[7 * 8 + ctr] == 0) {
+			int dc = in[ctr] << PASS1_BITS;
+
+			w[0 * 8] = w[1 * 8] = w[2 * 8] = w[3 * 8] = dc;
+			continue;
+		}
+		{
+			int tmp0, tmp2, tmp10, tmp12;
+			int z1, z2, z3, z4;
+
+			tmp0 = in[0 * 8 + ctr] << (CONST_BITS + 1);
+			z2 = in[2 * 8 + ctr];
+			z3 = in[6 * 8 + ctr];
+			tmp2 = z2 * FIX_1_847759065 +
+			       z3 * -FIX_0_765366865;
+			tmp10 = tmp0 + tmp2;
+			tmp12 = tmp0 - tmp2;
+
+			z1 = in[7 * 8 + ctr];
+			z2 = in[5 * 8 + ctr];
+			z3 = in[3 * 8 + ctr];
+			z4 = in[1 * 8 + ctr];
+			tmp0 = z1 * -FIX_0_211164243 +
+			       z2 * FIX_1_451774981 +
+			       z3 * -FIX_2_172734803 +
+			       z4 * FIX_1_061594337;
+			tmp2 = z1 * -FIX_0_509795579 +
+			       z2 * -FIX_0_601344887 +
+			       z3 * FIX_0_899976223 +
+			       z4 * FIX_2_562915447;
+
+			w[0 * 8] = descale(tmp10 + tmp2,
+					   CONST_BITS - PASS1_BITS + 1);
+			w[3 * 8] = descale(tmp10 - tmp2,
+					   CONST_BITS - PASS1_BITS + 1);
+			w[1 * 8] = descale(tmp12 + tmp0,
+					   CONST_BITS - PASS1_BITS + 1);
+			w[2 * 8] = descale(tmp12 - tmp0,
+					   CONST_BITS - PASS1_BITS + 1);
+		}
+	}
+
+	for (ctr = 0; ctr < 4; ctr++) {
+		int *w = ws + ctr * 8;
+
+		if (w[1] == 0 && w[2] == 0 && w[3] == 0 &&
+		    w[5] == 0 && w[6] == 0 && w[7] == 0) {
+			int dc = descale(w[0], PASS1_BITS + 3) + 128;
+
+			if (dc < 0) dc = 0;
+			if (dc > 255) dc = 255;
+			out[0] = out[1] = out[2] = out[3] = (unsigned char)dc;
+			out += 4;
+			continue;
+		}
+		{
+			int tmp0, tmp2, tmp10, tmp12;
+			int z1, z2, z3, z4;
+
+			tmp0 = w[0] << (CONST_BITS + 1);
+			tmp2 = w[2] * FIX_1_847759065 +
+			       w[6] * -FIX_0_765366865;
+			tmp10 = tmp0 + tmp2;
+			tmp12 = tmp0 - tmp2;
+
+			z1 = w[7];
+			z2 = w[5];
+			z3 = w[3];
+			z4 = w[1];
+			tmp0 = z1 * -FIX_0_211164243 +
+			       z2 * FIX_1_451774981 +
+			       z3 * -FIX_2_172734803 +
+			       z4 * FIX_1_061594337;
+			tmp2 = z1 * -FIX_0_509795579 +
+			       z2 * -FIX_0_601344887 +
+			       z3 * FIX_0_899976223 +
+			       z4 * FIX_2_562915447;
+
+			SCALED_OUT(tmp10 + tmp2,
+				   CONST_BITS + PASS1_BITS + 3 + 1);
+			SCALED_OUT(tmp12 + tmp0,
+				   CONST_BITS + PASS1_BITS + 3 + 1);
+			SCALED_OUT(tmp12 - tmp0,
+				   CONST_BITS + PASS1_BITS + 3 + 1);
+			SCALED_OUT(tmp10 - tmp2,
+				   CONST_BITS + PASS1_BITS + 3 + 1);
+		}
+	}
+}
+
+/* 2x2 output (1/4 scale). */
+static void idct_block_2x2(const int *in, unsigned char *out)
+{
+	int ws[8 * 2];
+	int ctr;
+
+	for (ctr = 0; ctr < 8; ctr++) {
+		int *w = ws + ctr;
+		int tmp0, tmp10;
+
+		if (ctr == 2 || ctr == 4 || ctr == 6)
+			continue;
+		if (in[1 * 8 + ctr] == 0 && in[3 * 8 + ctr] == 0 &&
+		    in[5 * 8 + ctr] == 0 && in[7 * 8 + ctr] == 0) {
+			int dc = in[ctr] << PASS1_BITS;
+
+			w[0] = w[8] = dc;
+			continue;
+		}
+		tmp10 = in[0 * 8 + ctr] << (CONST_BITS + 2);
+		tmp0 = in[7 * 8 + ctr] * -FIX_0_720959822 +
+		       in[5 * 8 + ctr] * FIX_0_850430095 +
+		       in[3 * 8 + ctr] * -FIX_1_272758580 +
+		       in[1 * 8 + ctr] * FIX_3_624509785;
+		w[0] = descale(tmp10 + tmp0, CONST_BITS - PASS1_BITS + 2);
+		w[8] = descale(tmp10 - tmp0, CONST_BITS - PASS1_BITS + 2);
+	}
+
+	for (ctr = 0; ctr < 2; ctr++) {
+		int *w = ws + ctr * 8;
+
+		if (w[1] == 0 && w[3] == 0 && w[5] == 0 && w[7] == 0) {
+			int dc = descale(w[0], PASS1_BITS + 3) + 128;
+
+			if (dc < 0) dc = 0;
+			if (dc > 255) dc = 255;
+			out[0] = out[1] = (unsigned char)dc;
+			out += 2;
+			continue;
+		}
+		{
+			int tmp0, tmp10;
+
+			tmp10 = w[0] << (CONST_BITS + 2);
+			tmp0 = w[7] * -FIX_0_720959822 +
+			       w[5] * FIX_0_850430095 +
+			       w[3] * -FIX_1_272758580 +
+			       w[1] * FIX_3_624509785;
+			SCALED_OUT(tmp10 + tmp0,
+				   CONST_BITS + PASS1_BITS + 3 + 2);
+			SCALED_OUT(tmp10 - tmp0,
+				   CONST_BITS + PASS1_BITS + 3 + 2);
+		}
+	}
+}
+
+/* 1x1 output (1/8 scale): just the DC average. */
+static void idct_block_1x1(const int *in, unsigned char *out)
+{
+	int dc = descale(in[0], 3) + 128;
+
+	if (dc < 0) dc = 0;
+	if (dc > 255) dc = 255;
+	out[0] = (unsigned char)dc;
+}
+
+static void idct_block_out(unsigned int scale, const int *blk,
+			   unsigned char *p)
+{
+	if (scale == 1)
+		idct_block(blk, p);
+	else if (scale == 2)
+		idct_block_4x4(blk, p);
+	else if (scale == 4)
+		idct_block_2x2(blk, p);
+	else
+		idct_block_1x1(blk, p);
+}
+
 struct jpeg_huff {
 	unsigned char bits[17];
 	unsigned char vals[256];
@@ -211,7 +415,10 @@ struct jpeg {
 	const unsigned char *d;
 	unsigned int n, pos;
 	unsigned int w, h;        /* raw dimensions */
+	unsigned int sw, sh;      /* raw dimensions after the IDCT scale */
 	unsigned int out_w, out_h;/* after EXIF orientation */
+	unsigned int scale;       /* 1, 2, 4 or 8: output is w/scale */
+	unsigned int want_w, want_h; /* caller's fit bounds, 0 = none */
 	unsigned int ncomp;
 	struct jpeg_comp comp[3];
 	unsigned int max_h, max_v;
@@ -719,17 +926,20 @@ static int jpeg_scan(struct jpeg *j, unsigned int ns, const unsigned int *sc,
 								int blk[64];
 								unsigned char p[64];
 								unsigned int xx, yy;
+								unsigned int s =
+									8 / j->scale;
 
 								if (jpeg_block(j, c, blk))
 									return -1;
-								idct_block(blk, p);
-								for (yy = 0; yy < 8; yy++)
-									for (xx = 0; xx < 8; xx++) {
-										unsigned int px = mx * c->h * 8 + bx * 8 + xx;
-										unsigned int py = my * c->v * 8 + by * 8 + yy;
+								idct_block_out(j->scale,
+									       blk, p);
+								for (yy = 0; yy < s; yy++)
+									for (xx = 0; xx < s; xx++) {
+										unsigned int px = mx * c->h * s + bx * s + xx;
+										unsigned int py = my * c->v * s + by * s + yy;
 
 										c->plane[py * c->pw + px] =
-											p[yy * 8 + xx];
+											p[yy * s + xx];
 									}
 							}
 						}
@@ -823,6 +1033,33 @@ static int jpeg_sof(struct jpeg *j, unsigned int marker, int *error)
 	}
 	j->mcus_x = (j->w + 8 * j->max_h - 1) / (8 * j->max_h);
 	j->mcus_y = (j->h + 8 * j->max_v - 1) / (8 * j->max_v);
+	{
+		unsigned int d = 1;
+
+		if (j->want_w || j->want_h) {
+			unsigned int dmax = 8;
+
+			if (j->want_w) {
+				unsigned int q = j->w / j->want_w;
+
+				if (q < dmax)
+					dmax = q;
+			}
+			if (j->want_h) {
+				unsigned int q = j->h / j->want_h;
+
+				if (q < dmax)
+					dmax = q;
+			}
+			if (dmax >= 8)
+				d = 8;
+			else if (dmax >= 4)
+				d = 4;
+			else if (dmax >= 2)
+				d = 2;
+		}
+		j->scale = d;
+	}
 	for (i = 0; i < j->ncomp; i++) {
 		j->comp[i].bw = j->mcus_x * j->comp[i].h;
 		j->comp[i].bh = j->mcus_y * j->comp[i].v;
@@ -830,14 +1067,16 @@ static int jpeg_sof(struct jpeg *j, unsigned int marker, int *error)
 				(8 * j->max_h);
 		j->comp[i].sh = (j->h * j->comp[i].v + 8 * j->max_v - 1) /
 				(8 * j->max_v);
-		j->comp[i].pw = j->comp[i].bw * 8;
-		j->comp[i].ph = j->comp[i].bh * 8;
+		j->comp[i].pw = j->comp[i].bw * (8 / j->scale);
+		j->comp[i].ph = j->comp[i].bh * (8 / j->scale);
 	}
-	j->out_w = j->w;
-	j->out_h = j->h;
+	j->sw = (j->w + j->scale - 1) / j->scale;
+	j->sh = (j->h + j->scale - 1) / j->scale;
+	j->out_w = j->sw;
+	j->out_h = j->sh;
 	if (j->orientation >= 5) {
-		j->out_w = j->h;
-		j->out_h = j->w;
+		j->out_w = j->sh;
+		j->out_h = j->sw;
 	}
 	return 0;
 }
@@ -879,6 +1118,7 @@ static void jpeg_reconstruct(struct jpeg *j)
 	for (ci = 0; ci < j->ncomp; ci++) {
 		struct jpeg_comp *c = &j->comp[ci];
 		const unsigned char *q = j->qt[c->tq];
+		unsigned int s = 8 / j->scale;
 
 		for (by = 0; by < c->bh; by++) {
 			for (bx = 0; bx < c->bw; bx++) {
@@ -889,12 +1129,12 @@ static void jpeg_reconstruct(struct jpeg *j)
 
 				for (k = 0; k < 64; k++)
 					blk[zigzag[k]] = (int)coef[k] * q[k];
-				idct_block(blk, p);
-				for (yy = 0; yy < 8; yy++)
-					for (xx = 0; xx < 8; xx++)
-						c->plane[(by * 8 + yy) * c->pw +
-							 bx * 8 + xx] =
-							p[yy * 8 + xx];
+				idct_block_out(j->scale, blk, p);
+				for (yy = 0; yy < s; yy++)
+					for (xx = 0; xx < s; xx++)
+						c->plane[(by * s + yy) * c->pw +
+							 bx * s + xx] =
+							p[yy * s + xx];
 			}
 		}
 	}
@@ -924,7 +1164,7 @@ static void jpeg_output(struct jpeg *j, struct img_image *out)
 		for (ox = 0; ox < j->out_w; ox++) {
 			unsigned int x, y, yy, r, g, b;
 
-			jpeg_map_pixel(j->orientation, ox, oy, j->w, j->h,
+			jpeg_map_pixel(j->orientation, ox, oy, j->sw, j->sh,
 				       &x, &y);
 			yy = j->comp[0].plane[y * j->comp[0].pw + x];
 			if (j->ncomp == 1) {
@@ -1131,6 +1371,8 @@ int img_decode_jpeg(const unsigned char *d, unsigned int n,
 	j->pos = 2;
 	j->rst_next = 0;
 	j->orientation = jpeg_exif_orientation(d, n);
+	j->want_w = opt ? opt->max_w : 0;
+	j->want_h = opt ? opt->max_h : 0;
 
 	while (j->pos < n) {
 		int mk = jpeg_marker(j);

+ 116 - 4
img_test.c

@@ -64,7 +64,7 @@ static int test_lossless(const struct img_exp *e)
 	unsigned char *data = filebuf;
 	unsigned int n;
 	struct img_mem mem;
-	struct img_options opt;
+	struct img_options opt = {0};
 	struct img_info info;
 	struct img_image im;
 	int r;
@@ -161,7 +161,7 @@ static int test_jpeg(const char *name)
 	unsigned int n, rw, rh;
 	unsigned char *ref;
 	struct img_mem mem;
-	struct img_options opt;
+	struct img_options opt = {0};
 	struct img_info info;
 	struct img_image im;
 	int r, x, y;
@@ -224,12 +224,106 @@ static int test_jpeg(const char *name)
 	return 0;
 }
 
+static int test_jpeg_scaled(const char *name)
+{
+	char path[256];
+	unsigned int n, w, h;
+	unsigned short *full;
+	struct img_mem mem;
+	struct img_options opt = {0};
+	struct img_image im;
+	int r, div, x, y;
+
+	snprintf(path, sizeof(path), "testdata/images/%s", name);
+	if (read_file(path, filebuf, sizeof(filebuf), &n))
+		return 1;
+	img_mem_init(&mem, arena, sizeof(arena));
+	memset(&im, 0, sizeof(im));
+	if (img_decode(filebuf, n, &opt, &mem, &im) != 0)
+		return 1;
+	w = im.w;
+	h = im.h;
+	full = (unsigned short *)malloc((size_t)w * h * 2);
+	if (!full)
+		return 1;
+	memcpy(full, im.px, (size_t)w * h * 2);
+
+	for (div = 2; div <= 4; div *= 2) {
+		unsigned int ow = (w + div - 1) / div;
+		unsigned int oh = (h + div - 1) / div;
+		unsigned int mr = 0, mg = 0, mb = 0, mx = 0;
+		unsigned long long count = 0;
+
+		img_mem_init(&mem, arena, sizeof(arena));
+		opt.max_pixels = 0;
+		opt.max_w = w / div;
+		opt.max_h = h / div;
+		memset(&im, 0, sizeof(im));
+		r = img_decode(filebuf, n, &opt, &mem, &im);
+		if (r != 0 || im.w != ow || im.h != oh) {
+			printf("FAIL %s 1/%d: %s %ux%u (want %ux%u)\n",
+			       name, div, r ? img_error_string(r) : "size",
+			       im.w, im.h, ow, oh);
+			free(full);
+			return 1;
+		}
+		for (y = 0; y < (int)oh; y++) {
+			for (x = 0; x < (int)ow; x++) {
+				unsigned int sum[3] = {0, 0, 0};
+				unsigned int cnt = 0;
+				unsigned short p = im.px[y * im.w + x];
+				unsigned int sr = (p >> 11) & 31;
+				unsigned int sg = (p >> 5) & 63;
+				unsigned int sb = p & 31;
+				int dx, dy;
+
+				for (dy = 0; dy < div; dy++)
+					for (dx = 0; dx < div; dx++) {
+						unsigned int xx = x * div + dx;
+						unsigned int yy = y * div + dy;
+						unsigned short q;
+
+						if (xx >= w || yy >= h)
+							continue;
+						q = full[yy * w + xx];
+						sum[0] += (q >> 11) & 31;
+						sum[1] += (q >> 5) & 63;
+						sum[2] += q & 31;
+						cnt++;
+					}
+				{
+					unsigned int dr = (unsigned int)abs((int)sr - (int)(sum[0] / cnt));
+					unsigned int dg = (unsigned int)abs((int)sg - (int)(sum[1] / cnt));
+					unsigned int db = (unsigned int)abs((int)sb - (int)(sum[2] / cnt));
+
+					mr += dr; mg += dg; mb += db; count++;
+					if (dr > mx) mx = dr;
+					if (dg > mx) mx = dg;
+					if (db > mx) mx = db;
+				}
+			}
+		}
+		if (count) {
+			unsigned int mean = (mr + mg + mb) / (unsigned int)(count * 3);
+
+			if (mean > 3 || mx > 20) {
+				printf("FAIL %s 1/%d: mean %u max %u\n",
+				       name, div, mean, mx);
+				free(full);
+				return 1;
+			}
+		}
+	}
+	free(full);
+	return 0;
+}
+
 static void test_truncated(const char *name)
 {
 	char path[256];
 	unsigned int n, step, len;
 	struct img_mem mem;
-	struct img_options opt;
+	struct img_options opt = {0};
 	struct img_image im;
 	unsigned int i;
 
@@ -353,7 +447,7 @@ static int test_unsupported(void)
 {
 	unsigned int n;
 	struct img_mem mem;
-	struct img_options opt;
+	struct img_options opt = {0};
 	struct img_image im;
 
 	if (read_file("testdata/images/cmyk.jpg", filebuf, sizeof(filebuf), &n))
@@ -388,6 +482,24 @@ int main(void)
 			failures++;
 		test_truncated(img_jpeg[i]);
 	}
+	if (test_jpeg_scaled("j420.jpg"))
+		failures++;
+	if (test_jpeg_scaled("j422.jpg"))
+		failures++;
+	if (test_jpeg_scaled("j444.jpg"))
+		failures++;
+	if (test_jpeg_scaled("jgray.jpg"))
+		failures++;
+	if (test_jpeg_scaled("jrst.jpg"))
+		failures++;
+	if (test_jpeg_scaled("prog.jpg"))
+		failures++;
+	if (test_jpeg_scaled("progrst.jpg"))
+		failures++;
+	if (test_jpeg_scaled("prog444.jpg"))
+		failures++;
+	if (test_jpeg_scaled("prog422.jpg"))
+		failures++;
 	test_truncated("anim.gif");
 	if (failures) {
 		printf("%d image test(s) failed\n", failures);

+ 82 - 0
ioapic.c

@@ -0,0 +1,82 @@
+/* I/O APIC masking.
+ *
+ * This kernel has no IOAPIC driver: the BSP keeps the 8259 PIC and delivers
+ * its interrupts through LAPIC LINT0 in ExtINT mode (lapic.c).  Firmware may
+ * still leave IOAPIC redirection entries programmed, and their vectors can
+ * collide with the PIC vectors (0x20..0x2f) or the LAPIC timer vector 0x30.
+ * Masking every normal entry makes the 8259 path deterministic.
+ *
+ * ExtINT-delivery entries are deliberately left unmasked: a few boards route
+ * the 8259 output through an IOAPIC pin instead of LINT0, and that entry must
+ * keep working.  Entries that are already masked are skipped.
+ */
+#include "ioapic.h"
+#include "acpi.h"
+#include "paging.h"
+#include "serial.h"
+
+#define IOAPIC_REGSEL   0x00
+#define IOAPIC_IOWIN    0x10
+#define IOAPIC_VER      0x01
+#define IOAPIC_REDTBL   0x10
+
+#define IOAPIC_MASK          0x00010000u
+#define IOAPIC_DELMODE_MASK  0x00000700u
+#define IOAPIC_DELMODE_EXTINT 0x00000700u
+
+static unsigned int ioapic_read(volatile unsigned int *base, unsigned int reg)
+{
+	base[IOAPIC_REGSEL / 4] = reg;
+	return base[IOAPIC_IOWIN / 4];
+}
+
+static void ioapic_write(volatile unsigned int *base, unsigned int reg,
+			 unsigned int val)
+{
+	base[IOAPIC_REGSEL / 4] = reg;
+	base[IOAPIC_IOWIN / 4] = val;
+}
+
+void ioapic_mask_all(void)
+{
+	unsigned int n = acpi_ioapic_count();
+	unsigned int i;
+
+	for (i = 0; i < n; i++) {
+		unsigned int addr = acpi_ioapic_base(i);
+		volatile unsigned int *base;
+		unsigned int ver, entries, j, masked = 0;
+
+		if (!addr)
+			continue;
+		paging_map_mmio(addr, 0x1000);
+		base = (volatile unsigned int *)addr;
+
+		ver = ioapic_read(base, IOAPIC_VER);
+		if (ver == 0xFFFFFFFFu)
+			continue;
+		entries = ((ver >> 16) & 0xFFu) + 1u;
+
+		for (j = 0; j < entries; j++) {
+			unsigned int lo = ioapic_read(base,
+						      IOAPIC_REDTBL + 2u * j);
+
+			if (lo & IOAPIC_MASK)
+				continue;
+			if ((lo & IOAPIC_DELMODE_MASK) ==
+			    IOAPIC_DELMODE_EXTINT)
+				continue;
+			ioapic_write(base, IOAPIC_REDTBL + 2u * j,
+				     lo | IOAPIC_MASK);
+			masked++;
+		}
+
+		serial_puts(SERIAL_COM1, "ioapic: masked ");
+		serial_putdec(SERIAL_COM1, masked);
+		serial_puts(SERIAL_COM1, " of ");
+		serial_putdec(SERIAL_COM1, entries);
+		serial_puts(SERIAL_COM1, " entries at ");
+		serial_puthex(SERIAL_COM1, addr);
+		serial_puts(SERIAL_COM1, "\n");
+	}
+}

+ 11 - 0
ioapic.h

@@ -0,0 +1,11 @@
+/* I/O APIC masking (see ioapic.c). */
+#ifndef IOAPIC_H
+#define IOAPIC_H
+
+/* Mask every normal IOAPIC redirection entry so the kernel's 8259/PIC path
+ * (delivered through LAPIC LINT0 as ExtINT) is the only interrupt source.
+ * ExtINT entries are left alone in case the firmware routes the 8259
+ * through an IOAPIC pin instead.  A machine without an IOAPIC is a no-op. */
+void ioapic_mask_all(void);
+
+#endif

+ 52 - 8
js_browser.c

@@ -94,6 +94,8 @@ static void dom_changed(void)
 		host_changed_orig();
 }
 
+static int node_parent_idx(unsigned int node);
+
 /* One wrapper per DOM node: the same element must have the same object
  * identity on every access, or library caches (jQuery expando data, Sizzle)
  * silently split into disconnected copies. */
@@ -555,7 +557,6 @@ static int dispatch_object(js_State *state, unsigned int target,
 	unsigned int path[64];
 	char type[32];
 	int np = 0, slot, i, prevented;
-	struct br_node *nd;
 
 	if (supplied_idx)
 		js_copy(state, supplied_idx);
@@ -583,11 +584,13 @@ static int dispatch_object(js_State *state, unsigned int target,
 	path[np++] = target;
 	if (target != JS_TARGET_WINDOW && target != JS_TARGET_DOCUMENT &&
 	    D && target < D->nnode) {
-		nd = &D->nodes[target];
-		while (nd->parent && nd->parent < D->nnode &&
+		unsigned int cur = target;
+		int p;
+
+		while ((p = node_parent_idx(cur)) >= 0 &&
 		       np < (int)(sizeof(path) / sizeof(path[0]))) {
-			path[np++] = nd->parent;
-			nd = &D->nodes[nd->parent];
+			path[np++] = (unsigned int)p;
+			cur = (unsigned int)p;
 		}
 	}
 	if (target != JS_TARGET_WINDOW)
@@ -928,6 +931,25 @@ static void push_child_list(js_State *state, unsigned int node, int elements)
 	}
 }
 
+/* The parent element index of an attached node, or -1 when it has none
+ * (a detached subtree root, or a child of the document).  A parent field of
+ * 0 is ambiguous: node 0 is the tree root, which is the <html> element itself
+ * when the page starts with one, and detached roots also keep parent 0. */
+static int node_parent_idx(unsigned int node)
+{
+	const struct br_node *n;
+
+	if (!D || node >= D->nnode)
+		return -1;
+	n = &D->nodes[node];
+	if (n->parent)
+		return n->parent;
+	if (node == 0 || (n->flags & BR_NODE_DETACHED))
+		return -1;
+	return D->nodes[0].type == BR_NODE_ELEM &&
+	       D->nodes[0].tag == BR_TAG_HTML ? 0 : -1;
+}
+
 static unsigned int node_prev_sibling(unsigned int node)
 {
 	unsigned int p, c, prev = 0;
@@ -1344,7 +1366,7 @@ static int class_has(const char *classes, const char *name)
 static void class_add(unsigned int node, const char *name, int add)
 {
 	const char *old = node_attr(node, "class");
-	char buf[256];
+	char buf[2048];                 /* BR_CLASS_MAX: Tailwind class lists */
 	unsigned int n = 0, i = 0;
 
 	if (add) {
@@ -2050,8 +2072,15 @@ static int node_has(js_State *state, void *p, const char *name)
 		return 1;
 	}
 	if (!strcmp(name, "parentNode") || !strcmp(name, "parentElement")) {
-		unsigned int p = n->parent;
-		push_node(state, p ? p + 1 : 0);
+		int p = node_parent_idx(node);
+
+		if (p >= 0)
+			push_node(state, (unsigned int)p + 1);
+		else if (name[6] == 'N' && !(n->flags & BR_NODE_DETACHED) &&
+			 n->type == BR_NODE_ELEM && n->tag == BR_TAG_HTML)
+			js_getglobal(state, "document");  /* <html>'s parent */
+		else
+			js_pushnull(state);
 		return 1;
 	}
 	if (!strcmp(name, "childNodes")) {
@@ -3288,6 +3317,8 @@ static void install_globals(js_State *state)
 	js_setproperty(state, -2, "title");
 	js_pushstring(state, "complete");
 	js_setproperty(state, -2, "readyState");
+	js_pushnull(state);
+	js_setproperty(state, -2, "currentScript");
 	js_pushstring(state, "");
 	js_setproperty(state, -2, "cookie");
 	js_pushstring(state, current_url ? current_url : "");
@@ -3555,6 +3586,19 @@ void js_browser_tick(void)
 	js_runjobs(J);
 }
 
+void js_browser_set_current_script(unsigned int node)
+{
+	if (!J || !D)
+		return;
+	js_getglobal(J, "document");
+	if (node && node < D->nnode)
+		push_node(J, node);
+	else
+		js_pushnull(J);
+	js_setproperty(J, -2, "currentScript");
+	js_pop(J, 1);
+}
+
 int js_browser_run(const char *source, const char *url)
 {
 	int r;

+ 3 - 0
js_browser.h

@@ -68,6 +68,9 @@ void js_browser_stop(void);
 /* Run one script.  `url` is used in error messages and by location.href. */
 int js_browser_run(const char *source, const char *url);
 
+/* The <script> element node about to run (0: none); document.currentScript. */
+void js_browser_set_current_script(unsigned int node);
+
 /* Run one <script type="module">; its imports load through
  * host.load_script. */
 int js_browser_run_module(const char *source, const char *url);

+ 103 - 3
js_prelude.js

@@ -1104,6 +1104,18 @@ g.document.createElement = function (name, opts) {
 	if (n === "img") imgLoadShim(el);
 	return el;
 };
+/* Document collections (live: recomputed on every access). */
+[["scripts", "script"], ["images", "img"], ["forms", "form"],
+ ["embeds", "embed"], ["links", "a[href],area[href]"]].forEach(function (p) {
+	Object.defineProperty(g.document, p[0], {
+		configurable: true,
+		get: function () {
+			return p[1].indexOf("[") >= 0 ?
+				g.document.querySelectorAll(p[1]) :
+				g.document.getElementsByTagName(p[1]);
+		}
+	});
+});
 /* Script-created images never really load in the page's DOM; fire "load"
  * once a src is set so preload-then-swap code (load a detached <img>, then
  * copy its URL) proceeds.  The visible <img> is loaded by the browser. */
@@ -1129,6 +1141,22 @@ var NodeConst = g.Node;
 
 /* Methods every node wrapper inherits (the C has-hook answers the rest). */
 var doc = g.document;
+/* <template>.content: the parser keeps a template's children in the tree
+ * (hidden); the first access moves them into a fragment, which Alpine's
+ * x-for/x-if/x-teleport clone. */
+Object.defineProperty(nodeproto, "content", { configurable: true,
+	get: function () {
+		if (this.nodeType !== 1 || this.tagName !== "TEMPLATE")
+			return undefined;
+		if (!this.__nb_tc) {
+			var f = doc.createDocumentFragment();
+
+			while (this.firstChild)
+				f.appendChild(this.firstChild);
+			this.__nb_tc = f;
+		}
+		return this.__nb_tc;
+	} });
 function toNode(n) {
 	return typeof n === "object" && n !== null ? n : doc.createTextNode(String(n));
 }
@@ -1271,14 +1299,74 @@ doc.fonts = { ready: Promise.resolve(), add: function () {},
 	      load: function () { return Promise.resolve([]); },
 	      check: function () { return true; },
 	      addEventListener: function () {} };
+/* A separate inert document (jQuery's parseHTML context, DOMPurify): its
+ * nodes live in the page's node arena but are detached, so writing to its
+ * body never touches the page.  Returning the page document here made
+ * jQuery's support probe replace the whole page body with two <form>s. */
+function nbInertDocument(title) {
+	var html = doc.createElement("html"), head = doc.createElement("head");
+	var body = doc.createElement("body"), d;
+
+	html.appendChild(head);
+	html.appendChild(body);
+	if (title !== undefined) {
+		var t = doc.createElement("title");
+		t.textContent = String(title);
+		head.appendChild(t);
+	}
+	d = {
+		nodeType: 9, nodeName: "#document", documentElement: html,
+		head: head, body: body, readyState: "complete",
+		compatMode: "CSS1Compat", characterSet: "UTF-8",
+		contentType: "text/html", defaultView: null, location: null,
+		cookie: "", URL: "about:blank", baseURI: doc.URL,
+		addEventListener: function () {},
+		removeEventListener: function () {},
+		querySelector: function (s) { return html.querySelector(s); },
+		querySelectorAll: function (s) { return html.querySelectorAll(s); },
+		getElementsByTagName: function (s) {
+			return html.getElementsByTagName(s);
+		},
+		getElementsByClassName: function (s) {
+			return html.getElementsByClassName(s);
+		},
+		getElementById: function (id) {
+			return html.querySelector("[id=\"" +
+				String(id).replace(/"/g, "\\\"") + "\"]");
+		}
+	};
+	["createElement", "createTextNode", "createComment",
+	 "createDocumentFragment", "createAttribute", "createEvent"].forEach(
+		function (m) {
+			d[m] = function () { return doc[m].apply(doc, arguments); };
+		});
+	d.createElementNS = function (ns, n) { return doc.createElement(n); };
+	d.implementation = doc.implementation;
+	Object.defineProperty(d, "title", { configurable: true,
+		get: function () {
+			var t = head.querySelector("title");
+			return t ? t.textContent : "";
+		} });
+	return d;
+}
 doc.implementation = {
 	hasFeature: function () { return true; },
-	createHTMLDocument: function () { return doc; }
+	createHTMLDocument: function (title) { return nbInertDocument(title); }
 };
+/* DOMParser on the same inert document: the markup goes through the
+ * innerHTML fragment parser into the detached body (head elements included,
+ * as an approximation). */
+if (!g.DOMParser) {
+	g.DOMParser = function DOMParser() {};
+	g.DOMParser.prototype.parseFromString = function (str) {
+		var d = nbInertDocument();
+
+		d.body.innerHTML = String(str);
+		return d;
+	};
+}
 Object.defineProperty(doc, "activeElement", {
 	get: function () { return doc.body; }, configurable: true });
-Object.defineProperty(doc, "currentScript", {
-	get: function () { return null; }, configurable: true });
 Object.defineProperty(doc, "defaultView", {
 	get: function () { return g; }, configurable: true });
 
@@ -1312,4 +1400,16 @@ g.postMessage = function () {};
 g.confirm = function () { return true; };
 g.prompt = function () { return null; };
 
+/* Parsed <template> children are inert in a browser: move them into each
+ * template's content fragment before the page's scripts walk the tree
+ * (Alpine would otherwise initialise them in place, in the wrong scope). */
+(function () {
+	var tl = doc.getElementsByTagName("template"), a = [], i;
+
+	for (i = 0; i < tl.length; i++)
+		a.push(tl[i]);
+	for (i = 0; i < a.length; i++)
+		void a[i].content;
+})();
+
 })(globalThis);

+ 7 - 2
kernel.c

@@ -8,6 +8,7 @@
 #include "cros_ec.h"
 #include "idle.h"
 #include "io.h"
+#include "ioapic.h"
 #include "lapic.h"
 #include "panic.h"
 #include "kmalloc.h"
@@ -242,11 +243,12 @@ extern unsigned char __bss_start[], __bss_end[];
 static int kworker_pid = -1;
 
 /* Parts of the system that must keep running independently of the WM:
- * input routing, cursor blink, kexec recovery, netlog flushing, gfx-session
- * cleanup and the shadow-buffer flush. */
+ * input routing, thermal polling, cursor blink, kexec recovery, netlog
+ * flushing, gfx-session cleanup and the shadow-buffer flush. */
 static void system_housekeeping(void)
 {
 	process_reap_dead();
+	thermal_housekeeping();
 	mouse_poll_update();
 #ifndef NOWM
 	wm_pump_keyboard();
@@ -462,6 +464,9 @@ void kernel_main(void)
 	 * leaves the machine at one CPU. */
 	acpi_init();
 	acpi_dump();
+	/* The kernel keeps the 8259 on LAPIC LINT0; firmware-left IOAPIC
+	 * entries would otherwise deliver into the PIC/LAPIC vector space. */
+	ioapic_mask_all();
 	boot_trace("acpi");
 	boot_val("acpi cpus", acpi_cpu_count());
 	io_init();

+ 108 - 0
mtrr.c

@@ -56,6 +56,17 @@ static int cpu_has_mtrr(void)
 	return (edx & (1u << 12)) != 0;
 }
 
+static int cpu_is_amd(void)
+{
+	unsigned int eax = 0, ebx, ecx, edx;
+
+	__asm__ volatile ("cpuid"
+		: "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx));
+	/* "AuthenticAMD" */
+	return ebx == 0x68747541u && edx == 0x69746E65u &&
+	       ecx == 0x444D4163u;
+}
+
 /* Mask bits for physical address bits 32..35+.  Those are reserved (writing
  * 1 to an unimplemented bit faults) so ask CPUID for the real width.  All
  * ones for the implemented high bits means "must match PHYSBASE", which is
@@ -150,6 +161,97 @@ static void dump_mtrrs(unsigned int vcnt)
 	}
 }
 
+/* AMD family 15h WC path.  The Intel path's read-modify-write of
+ * MSR_MTRRdefType is what reset the 970A-DS3P during the first paging init.
+ * AMD only has eight variable MTRRs, and the LFB is below 4 GB, so this path
+ * never touches MTRRdefType and writes a zero high mask (all 32..63 address
+ * bits are don't-care); that avoids every reserved-bit write while still
+ * covering the framebuffer range.  Only a free entry is used. */
+static int mtrr_set_wc_amd(unsigned int base, unsigned int size,
+			   unsigned int *wc_base, unsigned int *wc_size)
+{
+	unsigned int lo, hi, mlo, mhi;
+	unsigned int vcnt, i, use = ~0u;
+	unsigned int region_size, align, physmask;
+
+	rdmsr(MSR_MTRRCAP, &lo, &hi);
+	vcnt = lo & 0xFF;
+	if (vcnt > 8)
+		vcnt = 8;
+	if (vcnt == 0)
+		return 0;
+
+	rdmsr(MSR_MTRR_DEF_TYPE, &lo, &hi);
+	if (!(lo & MTRR_VALID)) {
+		serial_puts(SERIAL_COM1, "mtrr: AMD MTRR disabled by BIOS\n");
+		return 0;
+	}
+
+	region_size = 0x1000;
+	while (region_size < size) {
+		region_size <<= 1;
+		if (region_size == 0)
+			return 0;
+	}
+	align = base & (~base + 1u);
+	if (align == 0 || align > 0x80000000u)
+		align = 0x80000000u;
+	if (region_size > align)
+		region_size = align;
+	if (region_size < 0x1000)
+		return 0;
+	base &= ~(region_size - 1);
+
+	for (i = 0; i < vcnt; i++) {
+		unsigned int esize;
+
+		rdmsr(MSR_MTRR_PHYSBASE0 + 2 * i, &lo, &hi);
+		rdmsr(MSR_MTRR_PHYSMASK0 + 2 * i, &mlo, &mhi);
+		if (!(mlo & MTRR_VALID) || (lo & 0xFF) != MTRR_TYPE_WC ||
+		    (lo & 0xFFFFF000u) != base)
+			continue;
+		esize = ((~mlo) & 0xFFFFF000u) + 0x1000;
+		if (esize < region_size)
+			continue;
+		serial_puts(SERIAL_COM1,
+			    "mtrr: AMD LFB already write-combining\n");
+		if (wc_base)
+			*wc_base = base;
+		if (wc_size)
+			*wc_size = esize;
+		return 1;
+	}
+
+	for (i = 0; i < vcnt; i++) {
+		rdmsr(MSR_MTRR_PHYSMASK0 + 2 * i, &mlo, &mhi);
+		if (!(mlo & MTRR_VALID)) {
+			use = i;
+			break;
+		}
+	}
+	if (use == ~0u) {
+		serial_puts(SERIAL_COM1,
+			    "mtrr: AMD no free variable entry; skipping WC\n");
+		return 0;
+	}
+
+	physmask = (~(region_size - 1) & 0xFFFFF000u) | MTRR_VALID;
+	wrmsr(MSR_MTRR_PHYSBASE0 + 2 * use, base | MTRR_TYPE_WC, 0);
+	wrmsr(MSR_MTRR_PHYSMASK0 + 2 * use, physmask, 0);
+
+	serial_puts(SERIAL_COM1, "mtrr: AMD LFB WC [");
+	serial_puthex(SERIAL_COM1, base);
+	serial_puts(SERIAL_COM1, " +");
+	serial_puthex(SERIAL_COM1, region_size);
+	serial_puts(SERIAL_COM1, "]\n");
+
+	if (wc_base)
+		*wc_base = base;
+	if (wc_size)
+		*wc_size = region_size;
+	return 1;
+}
+
 int mtrr_set_wc(unsigned int base, unsigned int size,
 		unsigned int *wc_base, unsigned int *wc_size)
 {
@@ -162,6 +264,12 @@ int mtrr_set_wc(unsigned int base, unsigned int size,
 	if (!cpu_has_mtrr() || size == 0)
 		return 0;
 
+	/* AMD's MTRR register layout and BIOS setup differ enough from the
+	 * Intel path that the latter reset the 970A-DS3P.  Use the separate
+	 * free-entry/zero-high-mask path. */
+	if (cpu_is_amd())
+		return mtrr_set_wc_amd(base, size, wc_base, wc_size);
+
 	rdmsr(MSR_MTRRCAP, &lo, &hi);
 	vcnt = lo & 0xFF;
 	if (vcnt > 16)

+ 4 - 2
ngui.c

@@ -2222,7 +2222,9 @@ void ngui_scroll_begin(struct ngui *ui, struct ngui_rect r,
 	scroll_clamp(s);
 	if (!ui->buttons)
 		s->dragging = 0;
-	if (scrolls) {
+	if (s->hide_bar)
+		s->dragging = 0;
+	if (!s->hide_bar && scrolls) {
 		int th = scroll_thumb_h(&r, s);
 		int ty = scroll_thumb_y(&r, s);
 
@@ -2295,7 +2297,7 @@ void ngui_scroll_end(struct ngui *ui, struct ngui_rect r,
 		     struct ngui_scroll *s)
 {
 	ngui_pop_clip(ui);
-	if (!scrollable(s))
+	if (s->hide_bar || !scrollable(s))
 		return;
 	{
 		struct ngui_rect bar = rect_make(r.x + r.w - 15, r.y, 14, r.h);

+ 1 - 0
ngui.h

@@ -98,6 +98,7 @@ struct ngui_scroll {
 	int view_h;
 	int dragging;
 	int drag_dy;
+	int hide_bar;                 /* wheel/keys only; draw no scrollbar */
 };
 
 struct ngui_slider {

+ 7 - 4
nvidia.c

@@ -197,9 +197,12 @@ void nvidia_init(unsigned int bus, unsigned int dev, unsigned int device_id)
 		serial_puts(SERIAL_COM1, "\n");
 	}
 
-	/* Read-only look at the display engine (EVO channels, object table,
-	 * cursor state) for boards with no serial console (netmon mirror). */
-	nv50_probe();
+	/* Read-only look at the nv50-family display engine (EVO channels,
+	 * object table, cursor state).  The register layout is nv50-specific;
+	 * Maxwell and later parts must not be poked through it. */
+	if (nv_present && (nv_chipset == 0xaa || nv_chipset == 0xac ||
+			    nv_chipset == 0xaf))
+		nv50_probe();
 }
 
 int nvidia_available(void)
@@ -275,7 +278,7 @@ unsigned int nvidia_lfb_in_vram(void)
 
 	paging_map_ram(vram, vsize);
 
-	/* Marker at LFB + 8 MB: past any 1280x1024x32 frame. */
+	/* Marker at LFB + 8 MB: past any 1920x1080x32 frame. */
 	{
 		volatile unsigned int *p =
 			(volatile unsigned int *)(lfb + 0x00800000u);

+ 243 - 46
ohci.c

@@ -50,13 +50,19 @@
 #define CTL_HCFS     0x000000C0u
 #define HCFS_RESUME  0x00000040u
 #define HCFS_OPER    0x00000080u
+#define CTL_IR       0x00000100u   /* SMM owns the controller */
 
 /* R_COMMAND bits. */
 #define CMD_HCR 0x00000001u
 #define CMD_CLF 0x00000002u
+#define CMD_OCR 0x00000008u   /* request ownership from the SMM */
 
 /* R_INT_STATUS bits. */
 #define INTR_WDH 0x00000002u
+#define INTR_RHSC 0x00000040u
+
+/* HCCA: DoneHead is the 33rd dword. */
+#define HCCA_DONE_HEAD 0x84u
 
 /* R_RH_DESC_A bits. */
 #define RHA_PSM    0x00000100u
@@ -143,18 +149,25 @@ struct ohci_ctrl {
 	int int_armed[USB_HCD_INT_SLOTS];
 };
 
-static struct ohci_ctrl ctrls[USB_HCD_MAX_CTRL];
 static unsigned int n_ctrls;
-
-/* Control-transfer scratch: transfers are serialized, so one ED/TD set for
-   all instances is enough.  A dummy TD anchors the tail of each queue (the
-   controller stops when HeadP == TailP; the dummy is never processed). */
-static struct ohci_ed ctrl_ed;
-static struct ohci_td ctrl_tds[OHCI_MAX_TD];
-static struct ohci_td ctrl_dummy;
-static unsigned char setup_buf[8] __attribute__((aligned(16)));
 static int ctl_busy;
 
+/* DMA structures are filled by the CPU and read/written by the controller.
+ * The SB950's OHCI does not snoop dirty CPU cache lines, so paging_init()
+ * maps this page uncacheable (see paging.c).  One ED/TD set is shared by
+ * all control transfers (they are serialized by ctl_busy). */
+struct ohci_dma {
+	struct ohci_ed ctrl_ed;
+	struct ohci_td ctrl_tds[OHCI_MAX_TD];
+	struct ohci_td ctrl_dummy;
+	unsigned char setup_buf[8] __attribute__((aligned(16)));
+	struct ohci_ctrl ctrls[USB_HCD_MAX_CTRL];
+};
+
+unsigned char ohci_dma_page[4096] __attribute__((aligned(4096)));
+static struct ohci_dma *const dma = (struct ohci_dma *)ohci_dma_page;
+typedef char ohci_dma_fits_page[(sizeof(struct ohci_dma) <= 4096) ? 1 : -1];
+
 static void ohci_int_in_stop(unsigned int slot);
 
 static unsigned int rd(struct ohci_ctrl *c, unsigned int ofs)
@@ -167,6 +180,27 @@ static void wr(struct ohci_ctrl *c, unsigned int ofs, unsigned int val)
 	c->regs[ofs >> 2] = val;
 }
 
+/* The EDs/TDs live in cacheable RAM while the controller DMAs them.  Store
+ * ordering against the MMIO doorbell is not free: without a full barrier the
+ * HC can read an ED before the (WB) head-pointer store is visible, see
+ * HeadP == TailP, skip the transfer and never retire the TD.  That was the
+ * SB950 mouse's intermittent "cursor stops, no error" failure.  MFENCE needs
+ * SSE2, so use the i486-compatible locked no-op. */
+static void ohci_barrier(void)
+{
+	__asm__ volatile ("lock; addl $0, 0(%%esp)" ::: "memory");
+}
+
+/* The descriptors are uncacheable, but the caller's control data buffer is
+ * ordinary write-back memory.  Flush dirty OUT data before the HC reads it
+ * and drop stale lines before reading the DMA-written IN data.  Control
+ * transfers are rare (enumeration, SCSI commands), so WBINVD is cheap here;
+ * the polled HID path never calls it. */
+static void ohci_flush(void)
+{
+	__asm__ volatile ("wbinvd" ::: "memory");
+}
+
 static void delay_ms(unsigned int ms)
 {
 	usb_delay_ms(ms);    /* sleeps inside a sleepable scan */
@@ -177,6 +211,66 @@ static unsigned int port_reg(unsigned int port)
 	return R_RH_PORT_FIRST + 4u * port;
 }
 
+/* Polled driver: retired TDs are harvested from their CC fields, so the
+ * done list itself is discarded.  WDH must still be acknowledged, or the
+ * HC stops refreshing HCCA.DoneHead and (on this SB950) occasionally
+ * stops fetching a freshly filled control list. */
+static void ohci_ack_done(struct ohci_ctrl *c)
+{
+	if (rd(c, R_INT_STATUS) & (INTR_WDH | INTR_RHSC)) {
+		if (rd(c, R_INT_STATUS) & INTR_WDH)
+			((volatile unsigned int *)c->hcca)[HCCA_DONE_HEAD / 4] = 0;
+		wr(c, R_INT_STATUS, INTR_WDH | INTR_RHSC);
+	}
+}
+
+/* AMD SB600/SB700/SB800/SB950 SMBus device.  Its config 0x64 bit 15 gates
+ * the southbridge USB SMI: the firmware keeps legacy USB emulation alive
+ * with it, and with it enabled the SMM can intercept/take back the OHCI
+ * controllers after the OS has programmed them.  Linux/FreeBSD disable it
+ * once the USB host drivers own the ports. */
+static void amd_sb_usb_smi_disable(void)
+{
+	static int done;
+	unsigned int bus, dev, func;
+
+	if (done)
+		return;
+	done = 1;
+
+	/* The southbridge SMBus function is always on PCI bus 0.  Scanning
+	 * only that bus keeps the probe cheap on Intel/QEMU machines, where
+	 * it finds nothing. */
+	bus = 0;
+	for (dev = 0; dev < 32; dev++) {
+		unsigned int id = pci_cfg_read32(bus, dev, 0, 0x00);
+		unsigned int htype, nfunc;
+
+		if (id == 0xFFFFFFFFu || id == 0)
+			continue;
+		htype = (pci_cfg_read32(bus, dev, 0, 0x0C) >> 16) & 0xFFu;
+		nfunc = (htype & 0x80u) ? 8u : 1u;
+		for (func = 0; func < nfunc; func++) {
+			unsigned int idf = pci_cfg_read32(bus, dev, func, 0x00);
+			unsigned int val;
+
+			if (idf == 0xFFFFFFFFu || idf == 0)
+				continue;
+			if ((idf & 0xFFFFu) != 0x1002u ||
+			    ((idf >> 16) & 0xFFFFu) != 0x4385u)
+				continue;
+			val = pci_cfg_read32(bus, dev, func, 0x64);
+			if (val & 0x8000u) {
+				pci_cfg_write32(bus, dev, func, 0x64,
+						val & ~0x8000u);
+				serial_puts(SERIAL_COM1,
+					"ohci: disabled AMD SB USB SMI\n");
+			}
+			return;
+		}
+	}
+}
+
 static int ohci_setup_one(unsigned int bus, unsigned int dev, unsigned int func)
 {
 	struct ohci_ctrl *c;
@@ -202,7 +296,7 @@ static int ohci_setup_one(unsigned int bus, unsigned int dev, unsigned int func)
 	/* Disable legacy SMI emulation (same idea as the UHCI driver). */
 	pci_cfg_write16(bus, dev, func, 0xC0, 0);
 
-	c = &ctrls[n_ctrls];
+	c = &dma->ctrls[n_ctrls];
 	c->regs = (volatile unsigned int *)bar;
 	c->bus = bus;
 	c->dev = dev;
@@ -218,6 +312,32 @@ static int ohci_setup_one(unsigned int bus, unsigned int dev, unsigned int func)
 		return -1;
 	}
 
+	/* On AMD southbridges the firmware SMM can still own the controller.
+	 * Request ownership (HcCommandStatus.OCR) and clear HcControl.IR
+	 * before resetting; otherwise the controller ignores our commands
+	 * until the SMM decides to release it.  On Intel/QEMU IR is already
+	 * clear, so this is a no-op. */
+	{
+		unsigned int ctl = rd(c, R_CONTROL);
+
+		if (ctl & CTL_IR) {
+			serial_puts(SERIAL_COM1,
+				    "ohci: SMM owns controller, requesting change\n");
+			wr(c, R_COMMAND, CMD_OCR);
+			wr(c, R_CONTROL, ctl & ~CTL_IR);
+			t0 = get_ticks_ms();
+			while (rd(c, R_CONTROL) & CTL_IR) {
+				if (get_ticks_ms() - t0 > 200)
+					break;
+				delay_ms(1);
+			}
+			serial_puts(SERIAL_COM1,
+				    (rd(c, R_CONTROL) & CTL_IR) ?
+				    "ohci: SMM did not release\n" :
+				    "ohci: ownership acquired\n");
+		}
+	}
+
 	c->hcca = mm_alloc_page();
 	if (!c->hcca) {
 		serial_puts(SERIAL_COM1, "ohci: no memory for HCCA\n");
@@ -243,6 +363,7 @@ static int ohci_setup_one(unsigned int bus, unsigned int dev, unsigned int func)
 	}
 	for (i = 0; i < 32; i++)
 		((unsigned int *)c->hcca)[i] = (unsigned int)&c->int_ed[0];
+	ohci_barrier();
 
 	/* Host controller reset. */
 	wr(c, R_COMMAND, CMD_HCR);
@@ -260,7 +381,7 @@ static int ohci_setup_one(unsigned int bus, unsigned int dev, unsigned int func)
 	wr(c, R_HCCA, c->hcca);
 	wr(c, R_INT_DISABLE, 0xFFFFFFFFu);
 	wr(c, R_INT_STATUS, 0xFFFFFFFFu);   /* clear pending */
-	wr(c, R_DONE_HEAD, 0);
+	((unsigned int *)c->hcca)[HCCA_DONE_HEAD / 4] = 0;
 
 	/* Root hub: port count and power. */
 	rha = rd(c, R_RH_DESC_A);
@@ -292,7 +413,9 @@ static int ohci_setup_one(unsigned int bus, unsigned int dev, unsigned int func)
 	   periodic + control lists enabled. */
 	wr(c, R_CONTROL, HCFS_RESUME);
 	delay_ms(20);
+	ohci_barrier();
 	wr(c, R_CONTROL, HCFS_OPER | CTL_PLE | CTL_CLE);
+	ohci_barrier();
 
 	n_ctrls++;
 
@@ -337,6 +460,8 @@ static int ohci_init(void)
 	if (n_ctrls)
 		return (int)n_ctrls;
 
+	amd_sb_usb_smi_disable();
+
 	for (bus = 0; bus < 256 && n_ctrls < USB_HCD_MAX_CTRL; bus++) {
 		for (dev = 0; dev < 32; dev++) {
 			for (func = 0; func < 8; func++) {
@@ -366,7 +491,7 @@ static unsigned int ohci_count(void)
 static void ohci_info(unsigned int ctrl, unsigned int *bus, unsigned int *dev,
 		      unsigned int *func, unsigned int *base, int *mmio)
 {
-	struct ohci_ctrl *c = &ctrls[ctrl];
+	struct ohci_ctrl *c = &dma->ctrls[ctrl];
 	*bus = c->bus;
 	*dev = c->dev;
 	*func = c->func;
@@ -376,22 +501,22 @@ static void ohci_info(unsigned int ctrl, unsigned int *bus, unsigned int *dev,
 
 static unsigned int ohci_port_count(unsigned int ctrl)
 {
-	return ctrls[ctrl].ports;
+	return dma->ctrls[ctrl].ports;
 }
 
 static int ohci_port_connected(unsigned int ctrl, unsigned int port)
 {
-	return (rd(&ctrls[ctrl], port_reg(port)) & PS_CCS) ? 1 : 0;
+	return (rd(&dma->ctrls[ctrl], port_reg(port)) & PS_CCS) ? 1 : 0;
 }
 
 static int ohci_port_low_speed(unsigned int ctrl, unsigned int port)
 {
-	return (rd(&ctrls[ctrl], port_reg(port)) & PS_LSDA) ? 1 : 0;
+	return (rd(&dma->ctrls[ctrl], port_reg(port)) & PS_LSDA) ? 1 : 0;
 }
 
 static int ohci_port_take_change(unsigned int ctrl, unsigned int port)
 {
-	struct ohci_ctrl *c = &ctrls[ctrl];
+	struct ohci_ctrl *c = &dma->ctrls[ctrl];
 	unsigned int ofs = port_reg(port);
 
 	if (!(rd(c, ofs) & PS_CSC))
@@ -402,7 +527,7 @@ static int ohci_port_take_change(unsigned int ctrl, unsigned int port)
 
 static int ohci_port_reset(unsigned int ctrl, unsigned int port)
 {
-	struct ohci_ctrl *c = &ctrls[ctrl];
+	struct ohci_ctrl *c = &dma->ctrls[ctrl];
 	unsigned int ofs = port_reg(port);
 	unsigned int t0, st;
 
@@ -421,6 +546,7 @@ static int ohci_port_reset(unsigned int ctrl, unsigned int port)
 			break;
 		if (get_ticks_ms() - t0 > 200)
 			return -1;
+		usb_poll_relax(t0);
 	}
 	delay_ms(10);
 
@@ -454,16 +580,16 @@ static int ohci_transfer(struct ohci_ctrl *c, unsigned int addr,
 		mps = 64;
 
 	for (i = 0; i < 8; i++)
-		setup_buf[i] = setup[i];
+		dma->setup_buf[i] = setup[i];
 
 	/* SETUP stage (DATA0). */
-	td_set(&ctrl_tds[n++], TD_DP(TD_DP_SETUP) | TD_T_DATA0,
-	       (unsigned int)setup_buf, (unsigned int)setup_buf + 7);
+	td_set(&dma->ctrl_tds[n++], TD_DP(TD_DP_SETUP) | TD_T_DATA0,
+	       (unsigned int)dma->setup_buf, (unsigned int)dma->setup_buf + 7);
 
 	/* DATA stage: one TD for the whole buffer, DATA1 (like Linux; the
 	   controller splits it into MPS-sized packets itself). */
 	if (len > 0) {
-		td_set(&ctrl_tds[n++],
+		td_set(&dma->ctrl_tds[n++],
 		       TD_R | TD_DP(dir_in ? TD_DP_IN : TD_DP_OUT) |
 		       TD_T_DATA1,
 		       (unsigned int)data, (unsigned int)(data + len - 1));
@@ -471,24 +597,27 @@ static int ohci_transfer(struct ohci_ctrl *c, unsigned int addr,
 	}
 
 	/* STATUS stage (DATA1, opposite direction, no data). */
-	td_set(&ctrl_tds[n++],
+	td_set(&dma->ctrl_tds[n++],
 	       TD_DP(dir_in ? TD_DP_OUT : TD_DP_IN) | TD_T_DATA1, 0, 0);
 
 	/* Chain the TDs and anchor the tail on the dummy TD. */
 	for (i = 0; i + 1 < n; i++)
-		ctrl_tds[i].next = (unsigned int)&ctrl_tds[i + 1];
-	ctrl_tds[n - 1].next = (unsigned int)&ctrl_dummy;
-	ctrl_dummy.flags = TD_NOTACCESSED << TD_CC_SHIFT;
-	ctrl_dummy.cbp = 0;
-	ctrl_dummy.next = 0;
-	ctrl_dummy.be = 0;
-
-	ctrl_ed.flags = ED_FA(addr) | ED_EN(0) | ED_MPS(mps) | (low ? ED_S : 0);
-	ctrl_ed.tail = (unsigned int)&ctrl_dummy;
-	ctrl_ed.head = (unsigned int)&ctrl_tds[0];
-	ctrl_ed.next = 0;
-
-	wr(c, R_CTRL_HEAD_ED, (unsigned int)&ctrl_ed);
+		dma->ctrl_tds[i].next = (unsigned int)&dma->ctrl_tds[i + 1];
+	dma->ctrl_tds[n - 1].next = (unsigned int)&dma->ctrl_dummy;
+	dma->ctrl_dummy.flags = TD_NOTACCESSED << TD_CC_SHIFT;
+	dma->ctrl_dummy.cbp = 0;
+	dma->ctrl_dummy.next = 0;
+	dma->ctrl_dummy.be = 0;
+
+	ohci_barrier();
+	dma->ctrl_ed.flags = ED_FA(addr) | ED_EN(0) | ED_MPS(mps) | (low ? ED_S : 0);
+	dma->ctrl_ed.tail = (unsigned int)&dma->ctrl_dummy;
+	dma->ctrl_ed.head = (unsigned int)&dma->ctrl_tds[0];
+	dma->ctrl_ed.next = 0;
+	ohci_barrier();
+	ohci_flush();
+
+	wr(c, R_CTRL_HEAD_ED, (unsigned int)&dma->ctrl_ed);
 	wr(c, R_COMMAND, CMD_CLF);
 
 	/* Poll until every TD has left "not accessed".  A NAKed TD stays
@@ -497,8 +626,10 @@ static int ohci_transfer(struct ohci_ctrl *c, unsigned int addr,
 	for (;;) {
 		int done = 1, err = 0;
 
+		ohci_flush();
+		ohci_ack_done(c);
 		for (i = 0; i < n; i++) {
-			unsigned int cc = (ctrl_tds[i].flags & TD_CC_MASK)
+			unsigned int cc = (dma->ctrl_tds[i].flags & TD_CC_MASK)
 					  >> TD_CC_SHIFT;
 			if (cc == TD_NOTACCESSED) {
 				done = 0;
@@ -514,26 +645,77 @@ static int ohci_transfer(struct ohci_ctrl *c, unsigned int addr,
 			}
 		}
 		if (err) {
-			ctrl_ed.head = (unsigned int)&ctrl_dummy;
+			serial_puts(SERIAL_COM1, "ohci: xfer err addr ");
+			serial_putdec(SERIAL_COM1, addr);
+			serial_puts(SERIAL_COM1, " mps ");
+			serial_putdec(SERIAL_COM1, mps);
+			serial_puts(SERIAL_COM1, " low ");
+			serial_putdec(SERIAL_COM1, (unsigned int)low);
+			serial_puts(SERIAL_COM1, "\n");
+			dma->ctrl_ed.head = (unsigned int)&dma->ctrl_dummy;
 			wr(c, R_CTRL_HEAD_ED, 0);
 			return -1;
 		}
 		if (done)
 			break;
 		if (get_ticks_ms() - t0 > 2000) {
-			serial_puts(SERIAL_COM1, "ohci: xfer timeout\n");
-			ctrl_ed.head = (unsigned int)&ctrl_dummy;
+			serial_puts(SERIAL_COM1, "ohci: xfer timeout addr ");
+			serial_putdec(SERIAL_COM1, addr);
+			serial_puts(SERIAL_COM1, " mps ");
+			serial_putdec(SERIAL_COM1, mps);
+			serial_puts(SERIAL_COM1, " low ");
+			serial_putdec(SERIAL_COM1, (unsigned int)low);
+			for (i = 0; i < n; i++) {
+				serial_puts(SERIAL_COM1, " td");
+				serial_putdec(SERIAL_COM1, i);
+				serial_puts(SERIAL_COM1, " cc ");
+				serial_putdec(SERIAL_COM1,
+					      (dma->ctrl_tds[i].flags & TD_CC_MASK) >>
+					      TD_CC_SHIFT);
+			}
+			/* Controller state: a frozen frame number or a
+			 * cleared CLE/IR says whether the HC is running and
+			 * owns the controller at all. */
+			serial_puts(SERIAL_COM1, " ctl ");
+			serial_puthex(SERIAL_COM1, rd(c, R_CONTROL));
+			serial_puts(SERIAL_COM1, " cmd ");
+			serial_puthex(SERIAL_COM1, rd(c, R_COMMAND));
+			serial_puts(SERIAL_COM1, " int ");
+			serial_puthex(SERIAL_COM1, rd(c, R_INT_STATUS));
+			serial_puts(SERIAL_COM1, " fm ");
+			serial_puthex(SERIAL_COM1, rd(c, R_FM_NUMBER));
+			serial_puts(SERIAL_COM1, " head ");
+			serial_puthex(SERIAL_COM1, rd(c, R_CTRL_HEAD_ED));
+			serial_puts(SERIAL_COM1, " ed ");
+			serial_puthex(SERIAL_COM1, dma->ctrl_ed.flags);
+			serial_putc(SERIAL_COM1, ' ');
+			serial_puthex(SERIAL_COM1, dma->ctrl_ed.tail);
+			serial_putc(SERIAL_COM1, ' ');
+			serial_puthex(SERIAL_COM1, dma->ctrl_ed.head);
+			serial_putc(SERIAL_COM1, ' ');
+			serial_puthex(SERIAL_COM1, dma->ctrl_ed.next);
+			serial_puts(SERIAL_COM1, " t0 ");
+			serial_puthex(SERIAL_COM1, dma->ctrl_tds[0].flags);
+			serial_putc(SERIAL_COM1, ' ');
+			serial_puthex(SERIAL_COM1, dma->ctrl_tds[0].cbp);
+			serial_putc(SERIAL_COM1, ' ');
+			serial_puthex(SERIAL_COM1, dma->ctrl_tds[0].next);
+			serial_putc(SERIAL_COM1, ' ');
+			serial_puthex(SERIAL_COM1, dma->ctrl_tds[0].be);
+			serial_puts(SERIAL_COM1, "\n");
+			dma->ctrl_ed.head = (unsigned int)&dma->ctrl_dummy;
 			wr(c, R_CTRL_HEAD_ED, 0);
 			return -1;
 		}
+		usb_poll_relax(t0);
 	}
-	ctrl_ed.head = (unsigned int)&ctrl_dummy;
+	dma->ctrl_ed.head = (unsigned int)&dma->ctrl_dummy;
 	wr(c, R_CTRL_HEAD_ED, 0);
 
 	/* Bytes actually received: the TD's CBP advances with the data
 	   (the controller clears it to 0 when the whole buffer arrived). */
 	if (len > 0 && dir_in && n_data == 1) {
-		unsigned int cbp = ctrl_tds[1].cbp;
+		unsigned int cbp = dma->ctrl_tds[1].cbp;
 
 		if (cbp == 0)
 			return (int)len;
@@ -553,7 +735,7 @@ static int ohci_control_transfer(unsigned int ctrl, unsigned int addr,
 	if (ctrl >= n_ctrls || ctl_busy)
 		return -1;
 	ctl_busy = 1;
-	r = ohci_transfer(&ctrls[ctrl], addr, mps, low_speed, setup, data, len,
+	r = ohci_transfer(&dma->ctrls[ctrl], addr, mps, low_speed, setup, data, len,
 			  dir_in);
 	ctl_busy = 0;
 	return r;
@@ -572,10 +754,14 @@ static void ohci_int_arm(struct ohci_ctrl *c, unsigned int slot)
 	c->int_td[slot].be = (unsigned int)c->int_buf[slot] +
 			     c->int_mps[slot] - 1;
 
+	/* Publish the TD before the ED points at it, and the new head before
+	 * the controller's next pass. */
+	ohci_barrier();
 	c->int_ed[slot].head = (unsigned int)&c->int_td[slot] |
 			       (c->int_toggle[slot] ? ED_C : 0);
 	c->int_ed[slot].tail = (unsigned int)&c->int_dummy[slot];
 	/* int_ed[slot].next keeps the chain to the other slots. */
+	ohci_barrier();
 
 	c->int_armed[slot] = 1;
 }
@@ -588,7 +774,7 @@ static int ohci_int_in_start(unsigned int ctrl, unsigned int slot,
 
 	if (ctrl >= n_ctrls || slot >= USB_HCD_INT_SLOTS)
 		return -1;
-	c = &ctrls[ctrl];
+	c = &dma->ctrls[ctrl];
 
 	ohci_int_in_stop(slot);
 
@@ -612,19 +798,24 @@ static int ohci_int_in_poll(unsigned int slot, unsigned char *buf,
 	if (slot >= USB_HCD_INT_SLOTS)
 		return 0;
 	for (i = 0; i < n_ctrls; i++) {
-		if (ctrls[i].int_armed[slot]) {
-			c = &ctrls[i];
+		if (dma->ctrls[i].int_armed[slot]) {
+			c = &dma->ctrls[i];
 			break;
 		}
 	}
 	if (!c)
 		return 0;
 
+	ohci_ack_done(c);
+	ohci_barrier();
 	cc = (c->int_td[slot].flags & TD_CC_MASK) >> TD_CC_SHIFT;
 	if (cc == TD_NOTACCESSED) {
 		if (c->int_ed[slot].head & ED_H) {
 			/* Halted by the controller without a CC update:
 			   clear it and stay armed. */
+			serial_puts(SERIAL_COM1, "ohci: int halt slot ");
+			serial_putdec(SERIAL_COM1, slot);
+			serial_puts(SERIAL_COM1, "\n");
 			ohci_int_arm(c, slot);
 			return -1;
 		}
@@ -632,6 +823,11 @@ static int ohci_int_in_poll(unsigned int slot, unsigned char *buf,
 	}
 	if (cc != 0) {
 		/* Report the error but stay armed (toggle preserved). */
+		serial_puts(SERIAL_COM1, "ohci: int err slot ");
+		serial_putdec(SERIAL_COM1, slot);
+		serial_puts(SERIAL_COM1, " cc ");
+		serial_putdec(SERIAL_COM1, cc);
+		serial_puts(SERIAL_COM1, "\n");
 		ohci_int_arm(c, slot);
 		return -1;
 	}
@@ -656,13 +852,14 @@ static void ohci_int_in_stop(unsigned int slot)
 	if (slot >= USB_HCD_INT_SLOTS)
 		return;
 	for (i = 0; i < n_ctrls; i++) {
-		struct ohci_ctrl *c = &ctrls[i];
+		struct ohci_ctrl *c = &dma->ctrls[i];
 
 		if (!c->int_armed[slot])
 			continue;
 		c->int_armed[slot] = 0;
 		c->int_ed[slot].head = (unsigned int)&c->int_dummy[slot];
 		c->int_ed[slot].tail = (unsigned int)&c->int_dummy[slot];
+		ohci_barrier();
 	}
 }
 

+ 55 - 2
paging.c

@@ -9,6 +9,7 @@
  */
 
 #include "paging.h"
+#include "bootcon.h"
 #include "cpu.h"
 #include "mm.h"
 #include "mtrr.h"
@@ -40,12 +41,14 @@
 #define PDE_PCD      0x010
 #define PDE_PS       0x080   /* 4 MB page */
 
-/* How much of the LFB to map.  16 MB covers any mode up to 1280x1024x32
- * (~5 MB) with margin, and is independent of the BIOS's VRAM report. */
+/* How much of the LFB to map.  16 MB covers any mode up to 1920x1080x32
+ * (~8.3 MB) with margin, and is independent of the BIOS's VRAM report. */
 #define LFB_MAP_SIZE 0x1000000
 
 static unsigned int *page_dir;
 
+static void uc_page_cr3(unsigned int cr3, unsigned int va);
+
 static void rdmsr(unsigned int msr, unsigned int *lo, unsigned int *hi)
 {
 	__asm__ volatile ("rdmsr" : "=a"(*lo), "=d"(*hi) : "c"(msr));
@@ -166,10 +169,12 @@ void paging_init(void)
 	unsigned int i;
 	const volatile struct vga_boot_fb_info *fb = VGA_BOOT_FB;
 
+	bootcon_puts("paging: prepare\n");
 	paging_prepare_cpu();
 	/* Opaque asm hides the fixed 0x600 pointer from -Warray-bounds. */
 	__asm__ volatile ("" : "+r"(fb));
 
+	bootcon_puts("paging: alloc\n");
 	page_dir = (unsigned int *)mm_alloc_page();
 	if (!page_dir) {
 		serial_puts(SERIAL_COM1, "paging: out of memory\n");
@@ -188,6 +193,18 @@ void paging_init(void)
 	for (i = 0; i < MM_MAX_PHYS / 0x400000; i++)
 		page_dir[i] = (i << 22) | PDE_PS | PDE_WRITABLE | PDE_PRESENT;
 
+	/* The OHCI ED/TD/interrupt-buffer page is DMA'd by the SB950's legacy
+	 * USB controller, which does not snoop dirty CPU cache lines.  Split
+	 * the containing 4 MB page now, before paging is enabled, so every
+	 * process directory clones the uncacheable mapping. */
+	{
+		extern unsigned char ohci_dma_page[];
+		unsigned int va = (unsigned int)ohci_dma_page;
+
+		if ((va >> 22) == 0)
+			uc_page_cr3((unsigned int)page_dir, va);
+	}
+
 	/* Identity-map the framebuffer and make VRAM writes batch.  Use the
 	 * actual framebuffer size (not the whole mapping) so the WC range
 	 * cannot swallow unrelated MMIO, and install the MTRR *before* choosing
@@ -200,8 +217,10 @@ void paging_init(void)
 
 		if (want == 0 || want > LFB_MAP_SIZE)
 			want = LFB_MAP_SIZE;
+		bootcon_puts("paging: mtrr\n");
 		lfb_wc_ok = mtrr_set_wc(fb->lfb_base, want,
 					&lfb_wc_base, &lfb_wc_size);
+		bootcon_puts("paging: map\n");
 		lfb_apply_pages(page_dir);
 		/* Tell the truth about VRAM writes: with cacheable pages the WC
 		 * MTRR applies (fast bursts); otherwise every dword is a separate
@@ -213,6 +232,7 @@ void paging_init(void)
 
 	/* Load CR3, enable PSE, then PG + WP.  The jump flushes the prefetch
 	 * queue after the paging flip. */
+	bootcon_puts("paging: enable\n");
 	__asm__ volatile (
 		"movl %0, %%cr3\n\t"
 		"movl %%cr4, %%eax\n\t"
@@ -227,6 +247,7 @@ void paging_init(void)
 		: "r"((unsigned int)page_dir)
 		: "eax", "memory");
 
+	bootcon_puts("paging: on\n");
 	serial_puts(SERIAL_COM1, "paging: enabled (identity map)\n");
 }
 
@@ -400,3 +421,35 @@ void paging_map_mmio(unsigned int phys_base, unsigned int size)
 {
 	paging_map_mmio_cr3((unsigned int)page_dir, phys_base, size);
 }
+
+/* Split the 4 MB page containing `va` in one directory and set PCD on that
+ * 4 KB page.  The kernel identity map is WB; legacy OHCI DMA on the SB950
+ * does not reliably snoop dirty descriptor lines, so the ED/TD page must
+ * bypass the cache. */
+static void uc_page_cr3(unsigned int cr3, unsigned int va)
+{
+	unsigned int *pd = (unsigned int *)cr3;
+	unsigned int pde = va >> 22;
+	unsigned int pte = (va >> 12) & 0x3FFu;
+	unsigned int entry = pd[pde];
+	unsigned int *pt;
+	unsigned int i;
+
+	if (!(entry & PDE_PRESENT))
+		return;
+	if (entry & PDE_PS) {
+		unsigned int base = entry & 0xFFC00000u;
+		unsigned int flags = (entry & 0xFFFu) & ~PDE_PS;
+		unsigned int table = mm_alloc_page();
+
+		if (!table)
+			return;
+		pt = (unsigned int *)table;
+		for (i = 0; i < 1024; i++)
+			pt[i] = (base + i * 0x1000u) | flags;
+		pd[pde] = table | flags;
+	} else {
+		pt = (unsigned int *)(entry & 0xFFFFF000u);
+	}
+	pt[pte] |= PDE_PCD;
+}

+ 2 - 0
paging.h

@@ -18,6 +18,8 @@ int paging_lfb_wc(void);
  * is whatever the MTRRs say (write-combining when we added an entry). */
 void paging_map_ram(unsigned int base, unsigned int size);
 
+
+
 /* Physical address of the page directory currently loaded in CR3.  On SMP this
  * is per-CPU; on one CPU it is the running process's directory. */
 unsigned int paging_current_cr3(void);

+ 3 - 4
rndis.c

@@ -223,12 +223,11 @@ static void wr32le(unsigned char *p, unsigned int v)
 	p[3] = (unsigned char)((v >> 24) & 0xFF);
 }
 
+/* Sleeps inside a sleepable bus scan (the probe runs there); busy-waits
+ * in the netdev paths, which may run with interrupts off. */
 static void rndis_delay(unsigned int ms)
 {
-	unsigned int t0 = get_ticks_ms();
-
-	while (get_ticks_ms() - t0 < ms)
-		;
+	usb_delay_ms(ms);
 }
 
 static void put_mac_serial(void)

+ 9 - 1
sdhci.c

@@ -242,6 +242,7 @@ static int sdhci_cmd(unsigned int cmd, unsigned int arg, unsigned int flags,
 			log_fail("command timeout", cmd, sts);
 			return -1;
 		}
+		vfs_scan_poll(t0);
 	}
 	wr32(SDHCI_INT_STATUS, SDHCI_INT_CMD_COMPLETE);
 
@@ -264,6 +265,7 @@ static int sdhci_cmd(unsigned int cmd, unsigned int arg, unsigned int flags,
 				log_fail("transfer timeout", cmd, sts);
 				return -1;
 			}
+			vfs_scan_poll(t0);
 		}
 		wr32(SDHCI_INT_STATUS, 0xFFFFFFFFu);
 	}
@@ -285,6 +287,7 @@ static int sdhci_clock_div(unsigned int div)
 	while (!(rd16(SDHCI_CLOCK_CONTROL) & SDHCI_CLOCK_INT_STABLE)) {
 		if (get_ticks_ms() - t0 > 100)
 			return -1;
+		vfs_scan_poll(t0);
 	}
 	wr16(SDHCI_CLOCK_CONTROL,
 	     (unsigned short)((div << 8) | SDHCI_CLOCK_INT_EN |
@@ -302,6 +305,7 @@ static int sdhci_reset_host(void)
 	while (rd8(SDHCI_SOFTWARE_RESET) & SDHCI_RESET_ALL) {
 		if (get_ticks_ms() - t0 > 100)
 			return -1;
+		vfs_scan_poll(t0);
 	}
 	return 0;
 }
@@ -486,7 +490,11 @@ static int sdhci_init(void)
 			serial_puts(SERIAL_COM1, "\n");
 			return -1;
 		}
-		tiny_delay(1);
+		/* The card can take up to ~1 s to leave its power-up busy
+		 * state: sleep between polls during the storage rescan
+		 * (tiny_delay(1) alone never reaches vfs_scan_poll's 2 ms). */
+		if (!vfs_scan_relax(1))
+			tiny_delay(1);
 	}
 	serial_puts(SERIAL_COM1, "sdhci: ocr 0x");
 	serial_puthex(SERIAL_COM1, ocr);

+ 98 - 6
thermal.c

@@ -14,6 +14,7 @@
  */
 #include "thermal.h"
 #include "cpu.h"
+#include "pci.h"
 #include "sched.h"
 #include "serial.h"
 #include "timer.h"
@@ -22,10 +23,19 @@
 #define MSR_IA32_TEMPERATURE_TARGET  0x1A2
 
 static int thermal_state = -1;  /* -1 unprobed, 0 unsupported, 1 DTS */
+static int thermal_amd;         /* 1 = AMD D18F3xA4 instead of Intel DTS */
 static int thermal_tjmax_c = 100;
 static unsigned int thermal_tjmax_raw;   /* last MSR 0x1A2 sample */
 static int thermal_tjmax_msr;            /* TjMax came from the MSR */
 
+/* AMD family 15h models below 60h (Bulldozer/Piledriver/Steamroller) report
+ * Tctl in D18F3xA4: bits 31:21 are the raw temperature in 0.125 C units and
+ * bits 17:16 select the -49 C range offset (k10temp's pre-Zen path). */
+#define AMD_NB_DEV        0x18
+#define AMD_NB_FUNC       3
+#define AMD_REPORTED_TEMP 0xA4
+#define AMD_TJMAX_C       70
+
 static void cpuid_leaf(unsigned int leaf, unsigned int sub,
 		       unsigned int *a, unsigned int *b, unsigned int *c,
 		       unsigned int *d)
@@ -134,6 +144,30 @@ static void read_brand(char out[49])
 	}
 }
 
+static int amd_temp_c(void)
+{
+	unsigned int id, val, raw, mc;
+
+	id = pci_cfg_read32(0, AMD_NB_DEV, AMD_NB_FUNC, 0x00);
+	if (id == 0xFFFFFFFFu || id == 0)
+		return -1;
+	val = pci_cfg_read32(0, AMD_NB_DEV, AMD_NB_FUNC, AMD_REPORTED_TEMP);
+	if (val == 0xFFFFFFFFu || val == 0)
+		return -1;
+	raw = (val >> 21) & 0x7FFu;
+	if (raw == 0 || raw == 0x7FFu)
+		return -1;
+	mc = raw * 125u;
+	if ((val & 0x30000u) == 0x30000u) {
+		if (mc < 49000u)
+			return -1;
+		mc -= 49000u;
+	}
+	if (mc > 125000u)
+		return -1;
+	return (int)((mc + 500u) / 1000u);
+}
+
 static int pick_tjmax(unsigned int model, unsigned int stepping,
 		      const char *brand)
 {
@@ -162,6 +196,7 @@ void thermal_init(void)
 	int msr_probed = 0;
 
 	thermal_state = 0;
+	thermal_amd = 0;
 	thermal_tjmax_c = 100;
 	if (!cpu_has_cpuid())
 		goto out;
@@ -171,12 +206,10 @@ void thermal_init(void)
 	((unsigned int *)vendor)[1] = d;
 	((unsigned int *)vendor)[2] = c;
 	vendor[12] = '\0';
-	if (!str_eq(vendor, "GenuineIntel") || max_leaf < 1)
+	if (max_leaf < 1)
 		goto out;
 
 	cpuid_leaf(1, 0, &a, &b, &c, &d);
-	if (!(d & (1u << 5)))          /* MSR support */
-		goto out;
 	family = (a >> 8) & 0xF;
 	model = (a >> 4) & 0xF;
 	stepping = a & 0xF;
@@ -184,6 +217,25 @@ void thermal_init(void)
 		family += (a >> 20) & 0xFF;
 	if (family == 0x6 || family == 0xF)
 		model += ((a >> 16) & 0xF) << 4;
+
+	if (str_eq(vendor, "AuthenticAMD")) {
+		int t;
+
+		if (family != 0x15 || model >= 0x60)
+			goto out;
+		t = amd_temp_c();
+		if (t < -20 || t > 125)
+			goto out;
+		thermal_tjmax_c = AMD_TJMAX_C;
+		thermal_amd = 1;
+		thermal_state = 1;
+		goto out;
+	}
+
+	if (!str_eq(vendor, "GenuineIntel"))
+		goto out;
+	if (!(d & (1u << 5)))          /* MSR support */
+		goto out;
 	if (family != 0x6 || !model_has_dts(model))
 		goto out;
 	if (max_leaf < 6)
@@ -209,7 +261,12 @@ void thermal_init(void)
 	thermal_state = 1;
 
 out:
-	if (thermal_state) {
+	if (thermal_state && thermal_amd) {
+		serial_puts(SERIAL_COM1,
+			    "thermal: AMD family 15h, D18F3xA4, TjMax ");
+		serial_putdec(SERIAL_COM1, (unsigned int)thermal_tjmax_c);
+		serial_puts(SERIAL_COM1, " C\n");
+	} else if (thermal_state) {
 		serial_puts(SERIAL_COM1, "thermal: Intel DTS, model ");
 		serial_putdec(SERIAL_COM1, model);
 		serial_puts(SERIAL_COM1, " stepping ");
@@ -227,7 +284,8 @@ out:
 		}
 		serial_puts(SERIAL_COM1, "\n");
 	} else {
-		serial_puts(SERIAL_COM1, "thermal: no Intel DTS, disabled\n");
+		serial_puts(SERIAL_COM1,
+			    "thermal: no supported temperature sensor, disabled\n");
 	}
 }
 
@@ -236,6 +294,12 @@ int thermal_read_this_cpu(void)
 	unsigned int raw;
 	int t;
 
+	if (thermal_state < 0)
+		thermal_init();
+	if (!thermal_state)
+		return -1;
+	if (thermal_amd)
+		return amd_temp_c();
 	if (thermal_status_this_cpu(&raw) != 0)
 		return -1;
 	t = thermal_tjmax_c - (int)((raw >> 16) & 0x7F);
@@ -250,7 +314,7 @@ int thermal_status_this_cpu(unsigned int *status)
 
 	if (thermal_state < 0)
 		thermal_init();
-	if (!thermal_state)
+	if (!thermal_state || thermal_amd)
 		return -1;
 	__asm__ volatile ("rdmsr" : "=a"(lo), "=d"(hi)
 			  : "c"(MSR_IA32_THERM_STATUS));
@@ -265,6 +329,11 @@ void thermal_tick(void)
 	struct cpu *c = this_cpu();
 	unsigned int ms = (c->id == 0) ? timer_tick_ms() : c->tick_ms;
 
+	if (thermal_state < 0)
+		thermal_init();
+	if (!thermal_state || thermal_amd)
+		return;
+
 	/* The timer period drops to 10 ms while a CPU is idle, so count
 	 * milliseconds rather than ticks to keep the 1 Hz sample rate. */
 	if ((c->temp_div += ms) < 1000)
@@ -273,6 +342,29 @@ void thermal_tick(void)
 	c->temp_c = thermal_read_this_cpu();
 }
 
+void thermal_housekeeping(void)
+{
+	static unsigned int last_ms;
+	unsigned int now, i;
+	int t;
+
+	if (thermal_state < 0)
+		thermal_init();
+	if (!thermal_state || !thermal_amd)
+		return;
+
+	now = get_ticks_ms();
+	if (last_ms && now - last_ms < 1000)
+		return;
+	last_ms = now;
+
+	/* D18F3xA4 is a package/northbridge value, not per core.  Publish it
+	 * to every CPU so thermal_max_c() and the top bar see it. */
+	t = amd_temp_c();
+	for (i = 0; i < cpu_count && i < MAX_CPUS; i++)
+		cpus[i].temp_c = t;
+}
+
 int thermal_max_c(void)
 {
 	int max = -1;

+ 12 - 4
thermal.h

@@ -1,4 +1,4 @@
-/* Intel digital thermal sensor (DTS) access. */
+/* CPU temperature sources: Intel DTS and AMD family 15h D18F3xA4. */
 #ifndef THERMAL_H
 #define THERMAL_H
 
@@ -6,13 +6,21 @@
 void thermal_init(void);
 
 /* Sample this CPU's DTS.  Called from the per-CPU scheduler tick, at most
- * once per second. */
+ * once per second.  The AMD package sensor is sampled from the kworker
+ * instead (under the BKL; PCI config space is not safe to touch from a
+ * timer interrupt on multiple CPUs). */
 void thermal_tick(void);
 
-/* Read this CPU's DTS now: degrees C, or -1 when unavailable. */
+/* Once-a-second AMD package sensor poll; called from system_housekeeping()
+ * under the BKL.  A no-op on Intel and when no sensor was found. */
+void thermal_housekeeping(void);
+
+/* Read this CPU's temperature now: degrees C, or -1 when unavailable.
+ * On AMD this reads the package sensor, so all CPUs report the same value. */
 int thermal_read_this_cpu(void);
 
-/* Read this CPU's raw IA32_THERM_STATUS: 0 on success, -1 when unavailable. */
+/* Read this CPU's raw IA32_THERM_STATUS (Intel only): 0 on success, -1 when
+ * unavailable. */
 int thermal_status_this_cpu(unsigned int *status);
 
 /* Hottest per-CPU reading cached by the ticks, or -1 when unavailable. */

+ 427 - 31
tls.c

@@ -2,6 +2,12 @@
  * X25519 key exchange, TLS_CHACHA20_POLY1305_SHA256, no certificate
  * verification (the leaf SHA-256 is printed for manual comparison).
  *
+ * TLS 1.2 (RFC 5246) fallback for servers without 1.3: ECDHE over X25519 or
+ * P-256 with ChaCha20-Poly1305 (RFC 7905) or AES-128-GCM (RFC 5289), the
+ * extended master secret (RFC 7627) when the server offers it, and the
+ * same unverified certificate handling.  The same ClientHello offers both;
+ * the ServerHello's supported_versions decides which state machine runs.
+ *
  * The record layer is a small state machine; incoming records are
  * decrypted in chunks straight from the TCP stream (SYS_TCP_RECV) so a
  * 16 KB record never needs more than one plaintext buffer.  Handshake
@@ -15,6 +21,8 @@
 #include "tls_sha256.h"
 #include "tls_chacha20.h"
 #include "tls_x25519.h"
+#include "tls_gcm.h"
+#include "tls_p256.h"
 #include "tls_rng.h"
 
 #define TLS_RAW_SIZE       2048
@@ -44,6 +52,19 @@ static unsigned char c_ap_key[32], s_ap_key[32], c_ap_iv[12], s_ap_iv[12];
 static unsigned char master_secret[32];
 static unsigned char x_priv[32];
 
+/* TLS 1.2 state */
+static int ver12;                      /* negotiated TLS 1.2 */
+static int rx_enc;                     /* 1.2: server CCS seen, records encrypted */
+static int ems;                        /* extended_master_secret echoed */
+static int cert_req;                   /* CertificateRequest received */
+static unsigned int suite;             /* negotiated cipher suite */
+static int use_gcm;                    /* AES-128-GCM (else ChaCha20-Poly1305) */
+static unsigned char client_random[32], server_random[32];
+static unsigned char ms12[48];
+static unsigned int ske_group, ske_plen;
+static unsigned char ske_buf[160];
+static struct gcm_key c_gcm, s_gcm;
+
 static struct sha256_ctx transcript;
 static unsigned char fin_data[32];
 static int eof, err;
@@ -191,6 +212,56 @@ static int send_plain(unsigned char type, const unsigned char *data,
 	return tcp_send_all(data, len);
 }
 
+static void seq_be(unsigned char *p, unsigned long long seq)
+{
+	unsigned int i;
+
+	for (i = 0; i < 8; i++)
+		p[i] = (unsigned char)(seq >> (56 - 8 * i));
+}
+
+/* TLS 1.2 AEAD record: the type is the outer type, AAD = seq || type ||
+ * version || length; GCM puts the 8-byte explicit nonce (= seq) first. */
+static int send_record12(unsigned char type, const unsigned char *data,
+			 unsigned int len)
+{
+	unsigned char nonce[12], aad[13], tag[16];
+	unsigned int ex = use_gcm ? 8 : 0, rl = ex + len + 16, i;
+
+	if (5 + rl > TLS_TX_MAX)
+		return -1;
+	tx_buf[0] = type;
+	tx_buf[1] = 3;
+	tx_buf[2] = 3;
+	tx_buf[3] = (unsigned char)(rl >> 8);
+	tx_buf[4] = (unsigned char)rl;
+	seq_be(aad, tx_seq);
+	aad[8] = type;
+	aad[9] = 3;
+	aad[10] = 3;
+	aad[11] = (unsigned char)(len >> 8);
+	aad[12] = (unsigned char)len;
+	for (i = 0; i < len; i++)
+		tx_buf[5 + ex + i] = data[i];
+	if (use_gcm) {
+		for (i = 0; i < 4; i++)
+			nonce[i] = c_ap_iv[i];
+		seq_be(nonce + 4, tx_seq);
+		for (i = 0; i < 8; i++)
+			tx_buf[5 + i] = nonce[4 + i];
+		gcm_seal(&c_gcm, nonce, aad, 13, tx_buf + 5 + ex, len,
+			 tx_buf + 5 + ex, tag);
+	} else {
+		nonce_for(nonce, c_ap_iv, tx_seq);
+		aead_seal(c_ap_key, nonce, aad, 13, tx_buf + 5, len,
+			  tx_buf + 5, tag);
+	}
+	for (i = 0; i < 16; i++)
+		tx_buf[5 + ex + len + i] = tag[i];
+	tx_seq++;
+	return tcp_send_all(tx_buf, 5 + rl);
+}
+
 static int send_record(unsigned char inner, const unsigned char *data,
 		       unsigned int len, int use_hs)
 {
@@ -199,6 +270,8 @@ static int send_record(unsigned char inner, const unsigned char *data,
 	unsigned char nonce[12], aad[5], tag[16];
 	unsigned int plen = len + 1, rl = plen + 16, i;
 
+	if (ver12)
+		return send_record12(inner, data, len);
 	if (5 + rl > TLS_TX_MAX)
 		return -1;
 	for (i = 0; i < len; i++)
@@ -223,6 +296,32 @@ static int send_record(unsigned char inner, const unsigned char *data,
 
 /* ---- handshake: ServerHello ---- */
 
+/* A ServerHello without supported_versions: TLS 1.2 (legacy_version 0x0303). */
+static void sh_parse12(unsigned int cipher)
+{
+	unsigned int i;
+
+	if (sh_buf[0] != 3 || sh_buf[1] != 3) {
+		u_puts("tls: server offered neither TLS 1.3 nor 1.2\n");
+		err = 4;
+		return;
+	}
+	if (cipher != 0xc02f && cipher != 0xc02b && cipher != 0xcca8 &&
+	    cipher != 0xcca9) {
+		u_puts("tls: server chose an unsupported TLS 1.2 cipher suite\n");
+		err = 4;
+		return;
+	}
+	for (i = 0; i < 32; i++)
+		server_random[i] = sh_buf[2 + i];
+	ver12 = 1;
+	suite = cipher;
+	use_gcm = (cipher == 0xc02f || cipher == 0xc02b);
+	u_puts("tls: server hello, TLS 1.2 ");
+	u_puts(use_gcm ? "ECDHE AES-128-GCM" : "ECDHE CHACHA20-POLY1305");
+	u_puts(ems ? " (extended master secret)\n" : "\n");
+}
+
 static void sh_parse(unsigned int len)
 {
 	const unsigned char *p = sh_buf;
@@ -233,7 +332,7 @@ static void sh_parse(unsigned int len)
 
 	if (err)
 		return;
-	if (len < 2 + 32 + 1 + 2 + 1 + 2) {
+	if (len < 2 + 32 + 1 + 2 + 1) {
 		err = 3;
 		return;
 	}
@@ -246,14 +345,12 @@ static void sh_parse(unsigned int len)
 	o += sid;
 	cipher = ((unsigned int)p[o] << 8) | p[o + 1];
 	o += 2;
-	if (cipher != 0x1303) {
-		u_puts("tls: server chose another cipher suite\n");
-		err = 4;
-		return;
-	}
 	o++;                                   /* legacy_compression_method */
-	elen = ((unsigned int)p[o] << 8) | p[o + 1];
-	o += 2;
+	elen = 0;
+	if (o + 2 <= len) {
+		elen = ((unsigned int)p[o] << 8) | p[o + 1];
+		o += 2;
+	}
 	if (o + elen != len) {
 		err = 3;
 		return;
@@ -276,10 +373,16 @@ static void sh_parse(unsigned int len)
 		}
 		if (et == 0x002b && el == 2 && d[0] == 3 && d[1] == 4)
 			have_ver = 1;
+		if (et == 0x0017)
+			ems = 1;
 		i += 4 + el;
 	}
 	if (!have_ver) {
-		u_puts("tls: server did not agree on TLS 1.3\n");
+		sh_parse12(cipher);
+		return;
+	}
+	if (cipher != 0x1303) {
+		u_puts("tls: server chose another cipher suite\n");
 		err = 4;
 		return;
 	}
@@ -333,6 +436,11 @@ static void cert_byte(unsigned char b)
 	switch (cert_stage) {
 	case 0:
 		sha256_init(&cert_hash);
+		if (ver12) {                     /* no request context */
+			cert_stage = 2;
+			cert_byte(b);
+			break;
+		}
 		cert_ctx_left = b;
 		cert_stage = cert_ctx_left ? 1 : 2;
 		break;
@@ -361,7 +469,7 @@ static void cert_byte(unsigned char b)
 			if (cert_cur_left == 0) {
 				cert_seen++;
 				cert_ext_got = 0;
-				cert_stage = 5;
+				cert_stage = ver12 ? (cert_list_left ? 3 : 9) : 5;
 			} else {
 				cert_stage = 4;
 			}
@@ -375,7 +483,7 @@ static void cert_byte(unsigned char b)
 		if (cert_cur_left == 0) {
 			cert_seen++;
 			cert_ext_got = 0;
-			cert_stage = 5;
+			cert_stage = ver12 ? (cert_list_left ? 3 : 9) : 5;
 		}
 		break;
 	case 5:                                  /* per-entry extensions */
@@ -439,6 +547,10 @@ static void hs_byte(unsigned char b)
 	case 11:
 		cert_byte(b);
 		break;
+	case 12:                                /* 1.2 ServerKeyExchange */
+		if (body_pos < sizeof(ske_buf))
+			ske_buf[body_pos] = b;
+		break;
 	case 15:
 		break;                          /* CertificateVerify: not checked */
 	case 20:
@@ -455,12 +567,17 @@ static void hs_byte(unsigned char b)
 }
 
 static void hs_finish(unsigned int len);
+static void hs_finish12(unsigned int len);
+static void ske_parse(unsigned int len);
+static void hello_done12(void);
 
 static void hs_msg_complete(void)
 {
 	unsigned int type = hm_type, len = hm_len;
 
 	hm_got = 0;
+	if (ver12 && phase == 2)
+		return;                         /* HelloRequest etc.: ignored */
 	switch (type) {
 	case 2:
 		sh_parse(len);
@@ -468,8 +585,23 @@ static void hs_msg_complete(void)
 	case 11:
 		cert_msg_done();
 		break;
+	case 12:
+		if (ver12)
+			ske_parse(len);
+		break;
+	case 13:
+		if (ver12)
+			cert_req = 1;
+		break;
+	case 14:
+		if (ver12)
+			hello_done12();
+		break;
 	case 20:
-		hs_finish(len);
+		if (ver12)
+			hs_finish12(len);
+		else
+			hs_finish(len);
 		break;
 	default:
 		break;
@@ -524,6 +656,11 @@ static void hs_finish(unsigned int len)
 		for (i = 0; i < 32; i++)
 			msg[4 + i] = expect[i];
 	}
+	{
+		static const unsigned char ccs[1] = { 1 };
+
+		send_plain(20, ccs, 1);        /* middlebox compatibility */
+	}
 	if (send_record(22, msg, 36, 1) != 0) {
 		err = 1;
 		return;
@@ -534,8 +671,162 @@ static void hs_finish(unsigned int len)
 	tx_seq = 0;
 }
 
+/* ---- TLS 1.2 handshake ---- */
+
+static void ske_parse(unsigned int len)
+{
+	const unsigned char *p = ske_buf;
+
+	if (err)
+		return;
+	if (len > sizeof(ske_buf))
+		len = sizeof(ske_buf);
+	if (len < 4 || p[0] != 3 || 4 + (unsigned int)p[3] > len) {
+		u_puts("tls: unsupported ServerKeyExchange (need named-curve ECDHE)\n");
+		err = 4;
+		return;
+	}
+	ske_group = ((unsigned int)p[1] << 8) | p[2];
+	ske_plen = p[3];
+	if (!((ske_group == 0x001d && ske_plen == 32) ||
+	      (ske_group == 0x0017 && ske_plen == 65))) {
+		u_puts("tls: server chose an unsupported ECDHE group\n");
+		err = 4;
+		return;
+	}
+	/* The signature over the parameters is not verified (phase A). */
+}
+
+static int send_hs12(const unsigned char *msg, unsigned int len)
+{
+	sha256_update(&transcript, msg, len);
+	return send_plain(22, msg, len);
+}
+
+static void hello_done12(void)
+{
+	unsigned char priv[32], pms[32], msg[4 + 1 + 65], th[32], kb[88];
+	unsigned char seed[64];
+	unsigned int publen, i;
+
+	if (err)
+		return;
+	if (ske_plen == 0) {
+		u_puts("tls: no ServerKeyExchange (RSA key exchange unsupported)\n");
+		err = 4;
+		return;
+	}
+	if (cert_req) {                         /* empty client Certificate */
+		static const unsigned char empty[7] = { 11, 0, 0, 3, 0, 0, 0 };
+
+		if (send_hs12(empty, 7) != 0) {
+			err = 1;
+			return;
+		}
+	}
+	tls_random(priv, 32);
+	if (ske_group == 0x001d) {
+		x25519(msg + 5, priv, x25519_base_point);
+		x25519(pms, priv, ske_buf + 4);
+		publen = 32;
+	} else {
+		priv[0] &= 0x7f;                /* keep the scalar below n */
+		if (p256_public(priv, msg + 5) != 0 ||
+		    p256_shared(priv, ske_buf + 4, 65, pms) != 0) {
+			u_puts("tls: bad P-256 server key\n");
+			err = 5;
+			return;
+		}
+		publen = 65;
+	}
+	msg[0] = 16;                            /* ClientKeyExchange */
+	msg[1] = 0;
+	msg[2] = 0;
+	msg[3] = (unsigned char)(1 + publen);
+	msg[4] = (unsigned char)publen;
+	if (send_hs12(msg, 5 + publen) != 0) {
+		err = 1;
+		return;
+	}
+
+	transcript_hash(th);                    /* session hash: CH .. CKE */
+	if (ems)
+		tls12_prf(pms, 32, "extended master secret", th, 32, 0, 0,
+			  ms12, 48);
+	else
+		tls12_prf(pms, 32, "master secret", client_random, 32,
+			  server_random, 32, ms12, 48);
+	tls12_prf(ms12, 48, "key expansion", server_random, 32, client_random,
+		  32, kb, sizeof(kb));
+	if (use_gcm) {
+		for (i = 0; i < 4; i++) {
+			c_ap_iv[i] = kb[32 + i];
+			s_ap_iv[i] = kb[36 + i];
+		}
+		gcm_setkey(&c_gcm, kb);
+		gcm_setkey(&s_gcm, kb + 16);
+	} else {
+		for (i = 0; i < 32; i++) {
+			c_ap_key[i] = kb[i];
+			s_ap_key[i] = kb[32 + i];
+		}
+		for (i = 0; i < 12; i++) {
+			c_ap_iv[i] = kb[64 + i];
+			s_ap_iv[i] = kb[76 + i];
+		}
+	}
+
+	{
+		static const unsigned char ccs[1] = { 1 };
+
+		if (send_plain(20, ccs, 1) != 0) {
+			err = 1;
+			return;
+		}
+	}
+	tx_seq = 0;
+	seed[0] = 20;                           /* client Finished */
+	seed[1] = 0;
+	seed[2] = 0;
+	seed[3] = 12;
+	tls12_prf(ms12, 48, "client finished", th, 32, 0, 0, seed + 4, 12);
+	sha256_update(&transcript, seed, 16);
+	if (send_record12(22, seed, 16) != 0) {
+		err = 1;
+		return;
+	}
+	phase = 1;                              /* waiting for CCS + Finished */
+	for (i = 0; i < 32; i++)
+		pms[i] = priv[i] = 0;
+}
+
+static void hs_finish12(unsigned int len)
+{
+	unsigned char th[32], expect[12];
+	unsigned int i, d = 0;
+
+	if (err)
+		return;
+	if (len != 12 || phase != 1 || !rx_enc) {
+		err = 3;
+		return;
+	}
+	transcript_hash(th);
+	tls12_prf(ms12, 48, "server finished", th, 32, 0, 0, expect, 12);
+	for (i = 0; i < 12; i++)
+		d |= expect[i] ^ fin_data[i];
+	if (d) {
+		u_puts("tls: bad server Finished (handshake mismatch)\n");
+		err = 5;
+		return;
+	}
+	phase = 2;
+}
+
 /* ---- record input ---- */
 
+static void rec_dispatch(unsigned char type, unsigned int len);
+
 static void inner_process(unsigned int len)
 {
 	unsigned int i = len;
@@ -548,7 +839,12 @@ static void inner_process(unsigned int len)
 		return;
 	}
 	type = rec_pt[i - 1];
-	len = i - 1;
+	rec_dispatch(type, i - 1);
+}
+
+static void rec_dispatch(unsigned char type, unsigned int len)
+{
+	unsigned int i;
 
 	switch (type) {
 	case 22:
@@ -576,6 +872,69 @@ static void inner_process(unsigned int len)
 	}
 }
 
+static int pump_record12(const unsigned char hdr[5], unsigned int len,
+			 unsigned int deadline)
+{
+	struct aead_open_ctx a;
+	struct gcm_ctx g;
+	unsigned char nonce[12], aad[13], tag[16], expect[16];
+	unsigned int ex = use_gcm ? 8 : 0, ptlen, off = 0, i, d = 0;
+
+	if ((hdr[0] != 22 && hdr[0] != 23 && hdr[0] != 21) ||
+	    len < ex + 16 || len - ex - 16 > TLS_REC_PT_MAX) {
+		err = 3;
+		return -1;
+	}
+	ptlen = len - ex - 16;
+	if (use_gcm) {
+		for (i = 0; i < 4; i++)
+			nonce[i] = s_ap_iv[i];
+		if (raw_read(nonce + 4, 8, deadline) != 0)
+			return -1;
+	} else {
+		nonce_for(nonce, s_ap_iv, rx_seq);
+	}
+	seq_be(aad, rx_seq);
+	aad[8] = hdr[0];
+	aad[9] = 3;
+	aad[10] = 3;
+	aad[11] = (unsigned char)(ptlen >> 8);
+	aad[12] = (unsigned char)ptlen;
+	if (use_gcm)
+		gcm_open_init(&g, &s_gcm, nonce, aad, 13);
+	else
+		aead_open_init(&a, s_ap_key, nonce, aad, 13);
+	while (off < ptlen) {
+		unsigned int n = ptlen - off;
+
+		if (n > 1024)
+			n = 1024;
+		if (raw_read(rec_pt + off, n, deadline) != 0)
+			return -1;
+		if (use_gcm)
+			gcm_open_update(&g, rec_pt + off, rec_pt + off, n);
+		else
+			aead_open_update(&a, rec_pt + off, rec_pt + off, n);
+		off += n;
+	}
+	if (raw_read(tag, 16, deadline) != 0)
+		return -1;
+	if (use_gcm)
+		gcm_open_tag(&g, expect);
+	else
+		aead_open_tag(&a, expect);
+	for (i = 0; i < 16; i++)
+		d |= tag[i] ^ expect[i];
+	if (d) {
+		u_puts("tls: record authentication failed\n");
+		err = 5;
+		return -1;
+	}
+	rx_seq++;
+	rec_dispatch(hdr[0], ptlen);
+	return 0;
+}
+
 static int pump_record(unsigned int deadline)
 {
 	unsigned char hdr[5], tag[16], expect[16];
@@ -592,6 +951,14 @@ static int pump_record(unsigned int deadline)
 			err = 3;
 			return -1;
 		}
+		if (ver12) {                    /* 1.2: server starts encrypting */
+			if (phase != 1 || rx_enc) {
+				err = 3;
+				return -1;
+			}
+			rx_enc = 1;
+			rx_seq = 0;
+		}
 		return 0;
 	}
 	if (hdr[0] == 21) {                     /* plaintext alert */
@@ -624,17 +991,21 @@ static int pump_record(unsigned int deadline)
 		err = 4;
 		return -1;
 	}
-	if (phase == 0) {
-		if (hdr[0] != 22 || len > TLS_SH_MAX) {
+	if (ver12 ? !rx_enc : phase == 0) {
+		/* Plaintext handshake: one ServerHello record for 1.3, the whole
+		 * 1.2 server flight (certificates included) otherwise. */
+		if (hdr[0] != 22 || len > TLS_REC_PT_MAX) {
 			err = 3;
 			return -1;
 		}
-		if (raw_read(sh_buf, len, deadline) != 0)
+		if (raw_read(rec_pt, len, deadline) != 0)
 			return -1;
 		for (i = 0; i < len && !err; i++)
-			hs_byte(sh_buf[i]);
+			hs_byte(rec_pt[i]);
 		return 0;
 	}
+	if (ver12)
+		return pump_record12(hdr, len, deadline);
 	if (hdr[0] != 23 || len < 17 || len > TLS_REC_PT_MAX) {
 		err = 3;
 		return -1;
@@ -726,12 +1097,21 @@ static int build_client_hello(const char *sni)
 	ch_u24(0);                             /* length (patched below) */
 	ch_u16(0x0303);                        /* legacy_version */
 	tls_random(cr, 32);
+	for (hostlen = 0; hostlen < 32; hostlen++)
+		client_random[hostlen] = cr[hostlen];
+	hostlen = 0;
+	while (sni[hostlen])
+		hostlen++;
 	ch_bytes(cr, 32);
 	tls_random(sid, 32);
 	ch_u8(32);                             /* legacy_session_id */
 	ch_bytes(sid, 32);
-	ch_u16(2);                             /* cipher suites */
-	ch_u16(0x1303);
+	ch_u16(10);                            /* cipher suites */
+	ch_u16(0x1303);                        /* TLS 1.3 */
+	ch_u16(0xcca9);                        /* 1.2 ECDHE-ECDSA-CHACHA20-POLY1305 */
+	ch_u16(0xcca8);                        /* 1.2 ECDHE-RSA-CHACHA20-POLY1305 */
+	ch_u16(0xc02b);                        /* 1.2 ECDHE-ECDSA-AES128-GCM-SHA256 */
+	ch_u16(0xc02f);                        /* 1.2 ECDHE-RSA-AES128-GCM-SHA256 */
 	ch_u8(1);                              /* compression */
 	ch_u8(0);
 
@@ -741,28 +1121,45 @@ static int build_client_hello(const char *sni)
 
 	/* supported_versions */
 	ch_u16(0x002b);
-	ch_u16(3);
-	ch_u8(2);
+	ch_u16(5);
+	ch_u8(4);
 	ch_u16(0x0304);
-	/* supported_groups */
+	ch_u16(0x0303);
+	/* supported_groups: P-256 only for TLS 1.2 servers without X25519
+	 * (the 1.3 key share stays X25519; there is no HelloRetryRequest). */
 	ch_u16(0x000a);
+	ch_u16(6);
 	ch_u16(4);
-	ch_u16(2);
 	ch_u16(0x001d);
+	ch_u16(0x0017);
+	/* ec_point_formats: uncompressed */
+	ch_u16(0x000b);
+	ch_u16(2);
+	ch_u8(1);
+	ch_u8(0);
+	/* extended_master_secret, renegotiation_info (empty) */
+	ch_u16(0x0017);
+	ch_u16(0);
+	ch_u16(0xff01);
+	ch_u16(1);
+	ch_u8(0);
 	/* signature_algorithms: advertise the ECDSA curves used by modern
 	 * site certificates (nd-aktuell.de uses a P-384 leaf) as well as the
 	 * RSA-PSS schemes.  Signatures are not verified in phase A, but the
 	 * server refuses the handshake when its certificate's scheme is not
 	 * listed. */
 	ch_u16(0x000d);
-	ch_u16(14);
-	ch_u16(12);
+	ch_u16(20);
+	ch_u16(18);
 	ch_u16(0x0403);                 /* ecdsa_secp256r1_sha256 */
 	ch_u16(0x0503);                 /* ecdsa_secp384r1_sha384 */
 	ch_u16(0x0603);                 /* ecdsa_secp521r1_sha512 */
 	ch_u16(0x0804);                 /* rsa_pss_rsae_sha256 */
 	ch_u16(0x0805);                 /* rsa_pss_rsae_sha384 */
 	ch_u16(0x0806);                 /* rsa_pss_rsae_sha512 */
+	ch_u16(0x0401);                 /* rsa_pkcs1_sha256 (TLS 1.2) */
+	ch_u16(0x0501);                 /* rsa_pkcs1_sha384 */
+	ch_u16(0x0601);                 /* rsa_pkcs1_sha512 */
 	/* key_share */
 	tls_random(x_priv, 32);
 	x25519(pub, x_priv, x25519_base_point);
@@ -812,6 +1209,10 @@ int tls_connect(const char *sni)
 	hm_got = 0;
 	cert_stage = cert_seen = 0;
 	cert_hdr_got = 0;
+	ver12 = rx_enc = ems = cert_req = 0;
+	suite = 0;
+	use_gcm = 0;
+	ske_plen = ske_group = 0;
 
 	peer_mss = (unsigned int)u_syscall0(SYS_TCP_PEER_MSS);
 	if (peer_mss < 64 || peer_mss > 1460)
@@ -830,11 +1231,6 @@ int tls_connect(const char *sni)
 		u_puts("tls: send failed\n");
 		return -1;
 	}
-	{
-		static const unsigned char ccs[1] = { 1 };
-
-		send_plain(20, ccs, 1);        /* middlebox compatibility */
-	}
 	u_puts("tls: client hello sent (");
 	u_putdec(n);
 	u_puts(" bytes)\n");
@@ -847,7 +1243,7 @@ int tls_connect(const char *sni)
 	if (phase != 2) {
 		u_puts("tls: handshake failed");
 		if (err == 4)
-			u_puts(" (server does not support TLS 1.3)");
+			u_puts(" (no common protocol version or cipher suite)");
 		else if (err == 2)
 			u_puts(" (timeout)");
 		else if (err == 1)

+ 212 - 0
tls_gcm.c

@@ -0,0 +1,212 @@
+/* AES-128-GCM for the TLS 1.2 client; see tls_gcm.h. */
+
+#include "tls_gcm.h"
+#include "wpa_crypto.h"
+
+/* ---- GHASH: GF(2^128) multiply by H with 4-bit tables (Shoup) ---- */
+
+/* Reduction constants for shifting a 128-bit value right by 4 bits. */
+static const unsigned int last4[16] = {
+	0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
+	0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0
+};
+
+static unsigned int be32(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
+	       ((unsigned int)p[2] << 8) | p[3];
+}
+
+static void put_be32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 24);
+	p[1] = (unsigned char)(v >> 16);
+	p[2] = (unsigned char)(v >> 8);
+	p[3] = (unsigned char)v;
+}
+
+void gcm_setkey(struct gcm_key *k, const unsigned char key[16])
+{
+	unsigned char zero[16] = { 0 }, h[16];
+	unsigned int v[4], i, j;
+
+	aes128_setkey(k->rk, key);
+	aes128_encrypt(k->rk, zero, h);
+	for (i = 0; i < 4; i++)
+		v[i] = be32(h + 4 * i);
+	/* hl[8] = H, hl[4] = H*x, hl[2] = H*x^2, hl[1] = H*x^3 (bit-reflected
+	 * GCM convention: multiplying by x is a right shift). */
+	for (j = 0; j < 4; j++)
+		k->hl[0][j] = 0;
+	for (j = 0; j < 4; j++)
+		k->hl[8][j] = v[j];
+	for (i = 4; i > 0; i >>= 1) {
+		unsigned int *s = k->hl[i * 2], *d = k->hl[i];
+		unsigned int lsb = s[3] & 1;
+
+		d[3] = (s[3] >> 1) | (s[2] << 31);
+		d[2] = (s[2] >> 1) | (s[1] << 31);
+		d[1] = (s[1] >> 1) | (s[0] << 31);
+		d[0] = (s[0] >> 1) ^ (lsb ? 0xe1000000u : 0);
+	}
+	for (i = 2; i < 16; i <<= 1)
+		for (j = 1; j < i; j++) {
+			unsigned int w;
+
+			for (w = 0; w < 4; w++)
+				k->hl[i + j][w] = k->hl[i][w] ^ k->hl[j][w];
+		}
+}
+
+/* y = (y ^ block) * H */
+static void ghash_block(const struct gcm_key *k, unsigned int y[4],
+			const unsigned char b[16])
+{
+	unsigned char x[16];
+	unsigned int z[4], i;
+	int n;
+
+	for (i = 0; i < 4; i++)
+		put_be32(x + 4 * i, y[i] ^ be32(b + 4 * i));
+	z[0] = z[1] = z[2] = z[3] = 0;
+	for (n = 15; n >= 0; n--) {
+		unsigned int nib, rem, w;
+
+		for (w = 0; w < 2; w++) {
+			nib = w == 0 ? (x[n] & 0x0f) : (x[n] >> 4);
+			if (!(n == 15 && w == 0)) {
+				rem = z[3] & 0x0f;
+				z[3] = (z[3] >> 4) | (z[2] << 28);
+				z[2] = (z[2] >> 4) | (z[1] << 28);
+				z[1] = (z[1] >> 4) | (z[0] << 28);
+				z[0] = (z[0] >> 4) ^ (last4[rem] << 16);
+			}
+			z[0] ^= k->hl[nib][0];
+			z[1] ^= k->hl[nib][1];
+			z[2] ^= k->hl[nib][2];
+			z[3] ^= k->hl[nib][3];
+		}
+	}
+	for (i = 0; i < 4; i++)
+		y[i] = z[i];
+}
+
+static void ghash_bytes(struct gcm_ctx *c, const unsigned char *p,
+			unsigned int len)
+{
+	while (len) {
+		c->part[c->part_len++] = *p++;
+		len--;
+		if (c->part_len == 16) {
+			ghash_block(c->k, c->y, c->part);
+			c->part_len = 0;
+		}
+	}
+}
+
+static void ghash_pad(struct gcm_ctx *c)
+{
+	if (c->part_len) {
+		while (c->part_len < 16)
+			c->part[c->part_len++] = 0;
+		ghash_block(c->k, c->y, c->part);
+		c->part_len = 0;
+	}
+}
+
+static void ctr_inc(unsigned char ctr[16])
+{
+	int i;
+
+	for (i = 15; i >= 12; i--)
+		if (++ctr[i])
+			break;
+}
+
+static void gcm_start(struct gcm_ctx *c, const struct gcm_key *k,
+		      const unsigned char nonce[12],
+		      const unsigned char *aad, unsigned int aad_len)
+{
+	unsigned int i;
+
+	c->k = k;
+	c->y[0] = c->y[1] = c->y[2] = c->y[3] = 0;
+	for (i = 0; i < 12; i++)
+		c->ctr[i] = nonce[i];
+	c->ctr[12] = c->ctr[13] = c->ctr[14] = 0;
+	c->ctr[15] = 1;
+	aes128_encrypt(k->rk, c->ctr, c->ej0);
+	c->ks_pos = 16;                 /* first data block uses inc32(J0) */
+	c->part_len = 0;
+	c->aad_len = aad_len;
+	c->ct_len = 0;
+	ghash_bytes(c, aad, aad_len);
+	ghash_pad(c);
+}
+
+static void gcm_xor(struct gcm_ctx *c, unsigned char *out,
+		    const unsigned char *in, unsigned int len)
+{
+	unsigned int i;
+
+	for (i = 0; i < len; i++) {
+		if (c->ks_pos == 16) {
+			ctr_inc(c->ctr);
+			aes128_encrypt(c->k->rk, c->ctr, c->ks);
+			c->ks_pos = 0;
+		}
+		out[i] = in[i] ^ c->ks[c->ks_pos++];
+	}
+}
+
+static void gcm_finish(struct gcm_ctx *c, unsigned char tag[16])
+{
+	unsigned char lens[16];
+	unsigned int i;
+
+	ghash_pad(c);
+	/* bit lengths: 64-bit AAD, 64-bit ciphertext (both < 2^29 bytes) */
+	put_be32(lens, 0);
+	put_be32(lens + 4, c->aad_len << 3);
+	put_be32(lens + 8, 0);
+	put_be32(lens + 12, c->ct_len << 3);
+	ghash_block(c->k, c->y, lens);
+	for (i = 0; i < 4; i++)
+		put_be32(tag + 4 * i, c->y[i]);
+	for (i = 0; i < 16; i++)
+		tag[i] ^= c->ej0[i];
+}
+
+void gcm_open_init(struct gcm_ctx *c, const struct gcm_key *k,
+		   const unsigned char nonce[12],
+		   const unsigned char *aad, unsigned int aad_len)
+{
+	gcm_start(c, k, nonce, aad, aad_len);
+}
+
+void gcm_open_update(struct gcm_ctx *c, unsigned char *out,
+		     const unsigned char *in, unsigned int len)
+{
+	ghash_bytes(c, in, len);        /* GHASH runs over the ciphertext */
+	c->ct_len += len;
+	gcm_xor(c, out, in, len);
+}
+
+void gcm_open_tag(struct gcm_ctx *c, unsigned char tag[16])
+{
+	gcm_finish(c, tag);
+}
+
+void gcm_seal(const struct gcm_key *k, const unsigned char nonce[12],
+	      const unsigned char *aad, unsigned int aad_len,
+	      const unsigned char *pt, unsigned int len,
+	      unsigned char *ct, unsigned char tag[16])
+{
+	struct gcm_ctx c;
+
+	gcm_start(&c, k, nonce, aad, aad_len);
+	gcm_xor(&c, ct, pt, len);
+	ghash_bytes(&c, ct, len);
+	c.ct_len = len;
+	gcm_finish(&c, tag);
+}

+ 42 - 0
tls_gcm.h

@@ -0,0 +1,42 @@
+/* AES-128-GCM (NIST SP 800-38D) for the TLS 1.2 client: 96-bit nonces,
+ * 16-byte tags.  The block cipher is wpa_crypto.c's AES-128; GHASH uses
+ * Shoup's 4-bit tables.  Same streaming shape as the ChaCha20-Poly1305
+ * AEAD in tls_chacha20.h, so the record pump can decrypt a record in
+ * chunks straight from the TCP stream.  Pure freestanding C with host
+ * vectors (make test-crypto). */
+#ifndef TLS_GCM_H
+#define TLS_GCM_H
+
+struct gcm_key {
+	unsigned int rk[44];            /* AES-128 round keys */
+	unsigned int hl[16][4];         /* GHASH 4-bit table: hl[i] = i*H */
+};
+
+struct gcm_ctx {
+	const struct gcm_key *k;
+	unsigned int y[4];              /* GHASH accumulator, big-endian words */
+	unsigned char ctr[16];          /* current counter block */
+	unsigned char ks[16];           /* key stream of ctr */
+	unsigned char ej0[16];          /* E_K(J0), XORed into the tag */
+	unsigned char part[16];         /* partial GHASH block */
+	unsigned int ks_pos, part_len;
+	unsigned int aad_len, ct_len;
+};
+
+void gcm_setkey(struct gcm_key *k, const unsigned char key[16]);
+
+/* Decryption, streamed: open_update may be called any number of times. */
+void gcm_open_init(struct gcm_ctx *c, const struct gcm_key *k,
+		   const unsigned char nonce[12],
+		   const unsigned char *aad, unsigned int aad_len);
+void gcm_open_update(struct gcm_ctx *c, unsigned char *out,
+		     const unsigned char *in, unsigned int len);
+void gcm_open_tag(struct gcm_ctx *c, unsigned char tag[16]);
+
+/* One-shot seal: ct[0..len-1] (may alias pt) and the 16-byte tag. */
+void gcm_seal(const struct gcm_key *k, const unsigned char nonce[12],
+	      const unsigned char *aad, unsigned int aad_len,
+	      const unsigned char *pt, unsigned int len,
+	      unsigned char *ct, unsigned char tag[16]);
+
+#endif

+ 442 - 0
tls_p256.c

@@ -0,0 +1,442 @@
+/* NIST P-256 ECDH; see tls_p256.h. */
+
+#include "tls_p256.h"
+
+typedef unsigned int fe[8];             /* little-endian 32-bit limbs */
+
+struct jac {
+	fe x, y, z;                     /* Montgomery form; z = 0: infinity */
+	int inf;
+};
+
+/* p = 2^256 - 2^224 + 2^192 + 2^96 - 1 */
+static const fe P = {
+	0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,
+	0x00000000, 0x00000000, 0x00000001, 0xffffffff
+};
+/* b, Gx, Gy (normal form, little-endian limbs) */
+static const fe B = {
+	0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0,
+	0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8
+};
+static const fe GX = {
+	0xd898c296, 0xf4a13945, 0x2deb33a0, 0x77037d81,
+	0x63a440f2, 0xf8bce6e5, 0xe12c4247, 0x6b17d1f2
+};
+static const fe GY = {
+	0x37bf51f5, 0xcbb64068, 0x6b315ece, 0x2bce3357,
+	0x7c0f9e16, 0x8ee7eb4a, 0xfe1a7f9b, 0x4fe342e2
+};
+
+static fe R2;                           /* R^2 mod p, R = 2^256 */
+static fe ONE_M;                        /* 1 in Montgomery form */
+static int ready;
+
+static void fe_copy(fe r, const fe a)
+{
+	int i;
+
+	for (i = 0; i < 8; i++)
+		r[i] = a[i];
+}
+
+static int fe_is_zero(const fe a)
+{
+	unsigned int d = 0;
+	int i;
+
+	for (i = 0; i < 8; i++)
+		d |= a[i];
+	return d == 0;
+}
+
+static int fe_eq(const fe a, const fe b)
+{
+	unsigned int d = 0;
+	int i;
+
+	for (i = 0; i < 8; i++)
+		d |= a[i] ^ b[i];
+	return d == 0;
+}
+
+/* r = a - b (raw); returns the borrow. */
+static unsigned int raw_sub(fe r, const fe a, const fe b)
+{
+	unsigned long long t;
+	unsigned int borrow = 0;
+	int i;
+
+	for (i = 0; i < 8; i++) {
+		t = (unsigned long long)a[i] - b[i] - borrow;
+		r[i] = (unsigned int)t;
+		borrow = (unsigned int)(t >> 63);
+	}
+	return borrow;
+}
+
+/* r = a + b (raw); returns the carry. */
+static unsigned int raw_add(fe r, const fe a, const fe b)
+{
+	unsigned long long t;
+	unsigned int carry = 0;
+	int i;
+
+	for (i = 0; i < 8; i++) {
+		t = (unsigned long long)a[i] + b[i] + carry;
+		r[i] = (unsigned int)t;
+		carry = (unsigned int)(t >> 32);
+	}
+	return carry;
+}
+
+static int fe_lt_p(const fe a)
+{
+	fe t;
+
+	return raw_sub(t, a, P) != 0;
+}
+
+static void fe_add(fe r, const fe a, const fe b)
+{
+	fe t;
+	unsigned int carry = raw_add(r, a, b);
+
+	if (carry || !fe_lt_p(r)) {
+		raw_sub(t, r, P);
+		fe_copy(r, t);
+	}
+}
+
+static void fe_sub(fe r, const fe a, const fe b)
+{
+	fe t;
+
+	if (raw_sub(r, a, b)) {
+		raw_add(t, r, P);
+		fe_copy(r, t);
+	}
+}
+
+/* Montgomery product r = a * b / R mod p (CIOS; -p^-1 mod 2^32 = 1). */
+static void fe_mul(fe r, const fe a, const fe b)
+{
+	unsigned int t[10];
+	unsigned long long c;
+	unsigned int m;
+	int i, j;
+
+	for (i = 0; i < 10; i++)
+		t[i] = 0;
+	for (i = 0; i < 8; i++) {
+		c = 0;
+		for (j = 0; j < 8; j++) {
+			c += (unsigned long long)t[j] +
+			     (unsigned long long)a[j] * b[i];
+			t[j] = (unsigned int)c;
+			c >>= 32;
+		}
+		c += t[8];
+		t[8] = (unsigned int)c;
+		t[9] = (unsigned int)(c >> 32);
+
+		m = t[0];
+		c = (unsigned long long)t[0] + (unsigned long long)m * P[0];
+		c >>= 32;
+		for (j = 1; j < 8; j++) {
+			c += (unsigned long long)t[j] +
+			     (unsigned long long)m * P[j];
+			t[j - 1] = (unsigned int)c;
+			c >>= 32;
+		}
+		c += t[8];
+		t[7] = (unsigned int)c;
+		t[8] = t[9] + (unsigned int)(c >> 32);
+	}
+	for (i = 0; i < 8; i++)
+		r[i] = t[i];
+	if (t[8] || !fe_lt_p(r)) {
+		fe s;
+
+		raw_sub(s, r, P);
+		fe_copy(r, s);
+	}
+}
+
+static void fe_sqr(fe r, const fe a)
+{
+	fe_mul(r, a, a);
+}
+
+static void fe_to_mont(fe r, const fe a)
+{
+	fe_mul(r, a, R2);
+}
+
+static void fe_from_mont(fe r, const fe a)
+{
+	fe one = { 1, 0, 0, 0, 0, 0, 0, 0 };
+
+	fe_mul(r, a, one);
+}
+
+/* r = a^(p-2) = a^-1 (Montgomery domain). */
+static void fe_inv(fe r, const fe a)
+{
+	fe pm2, acc;
+	int i;
+
+	fe_copy(pm2, P);
+	pm2[0] -= 2;
+	fe_copy(acc, ONE_M);
+	for (i = 255; i >= 0; i--) {
+		fe_sqr(acc, acc);
+		if ((pm2[i >> 5] >> (i & 31)) & 1)
+			fe_mul(acc, acc, a);
+	}
+	fe_copy(r, acc);
+}
+
+static void p256_init(void)
+{
+	fe x, t;
+	int i;
+
+	if (ready)
+		return;
+	/* R mod p = 2^256 - p, then double 256 times: R^2 mod p. */
+	for (i = 0; i < 8; i++)
+		t[i] = 0;
+	raw_sub(x, t, P);               /* 2^256 - p (wraps) */
+	for (i = 0; i < 256; i++)
+		fe_add(x, x, x);
+	fe_copy(R2, x);
+	{
+		fe one = { 1, 0, 0, 0, 0, 0, 0, 0 };
+
+		fe_to_mont(ONE_M, one);
+	}
+	ready = 1;
+}
+
+/* ---- points (Jacobian, a = -3) ---- */
+
+static void pt_double(struct jac *r, const struct jac *p)
+{
+	fe delta, gamma, beta, alpha, t1, t2, x3, y3, z3;
+
+	if (p->inf || fe_is_zero(p->y)) {
+		r->inf = 1;
+		return;
+	}
+	fe_sqr(delta, p->z);
+	fe_sqr(gamma, p->y);
+	fe_mul(beta, p->x, gamma);
+	fe_sub(t1, p->x, delta);
+	fe_add(t2, p->x, delta);
+	fe_mul(alpha, t1, t2);
+	fe_add(t1, alpha, alpha);
+	fe_add(alpha, t1, alpha);       /* 3 (x - d)(x + d) */
+	fe_sqr(x3, alpha);
+	fe_add(t1, beta, beta);
+	fe_add(t1, t1, t1);
+	fe_add(t2, t1, t1);             /* 8 beta */
+	fe_sub(x3, x3, t2);
+	fe_add(t2, p->y, p->z);
+	fe_sqr(z3, t2);
+	fe_sub(z3, z3, gamma);
+	fe_sub(z3, z3, delta);
+	fe_sub(t1, t1, x3);             /* 4 beta - x3 */
+	fe_mul(y3, alpha, t1);
+	fe_sqr(t2, gamma);
+	fe_add(t2, t2, t2);
+	fe_add(t2, t2, t2);
+	fe_add(t2, t2, t2);             /* 8 gamma^2 */
+	fe_sub(y3, y3, t2);
+	fe_copy(r->x, x3);
+	fe_copy(r->y, y3);
+	fe_copy(r->z, z3);
+	r->inf = 0;
+}
+
+static void pt_add(struct jac *r, const struct jac *a, const struct jac *b)
+{
+	fe z1z1, z2z2, u1, u2, s1, s2, h, rr, i, j, v, t, x3, y3, z3;
+
+	if (a->inf) {
+		*r = *b;
+		return;
+	}
+	if (b->inf) {
+		*r = *a;
+		return;
+	}
+	fe_sqr(z1z1, a->z);
+	fe_sqr(z2z2, b->z);
+	fe_mul(u1, a->x, z2z2);
+	fe_mul(u2, b->x, z1z1);
+	fe_mul(t, b->z, z2z2);
+	fe_mul(s1, a->y, t);
+	fe_mul(t, a->z, z1z1);
+	fe_mul(s2, b->y, t);
+	fe_sub(h, u2, u1);
+	fe_sub(rr, s2, s1);
+	if (fe_is_zero(h)) {
+		if (fe_is_zero(rr)) {
+			pt_double(r, a);
+			return;
+		}
+		r->inf = 1;
+		return;
+	}
+	fe_add(rr, rr, rr);
+	fe_add(t, h, h);
+	fe_sqr(i, t);
+	fe_mul(j, h, i);
+	fe_mul(v, u1, i);
+	fe_sqr(x3, rr);
+	fe_sub(x3, x3, j);
+	fe_sub(x3, x3, v);
+	fe_sub(x3, x3, v);
+	fe_sub(t, v, x3);
+	fe_mul(y3, rr, t);
+	fe_mul(t, s1, j);
+	fe_add(t, t, t);
+	fe_sub(y3, y3, t);
+	fe_add(t, a->z, b->z);
+	fe_sqr(z3, t);
+	fe_sub(z3, z3, z1z1);
+	fe_sub(z3, z3, z2z2);
+	fe_mul(z3, z3, h);
+	fe_copy(r->x, x3);
+	fe_copy(r->y, y3);
+	fe_copy(r->z, z3);
+	r->inf = 0;
+}
+
+static void pt_mul(struct jac *r, const unsigned char k[32],
+		   const struct jac *p)
+{
+	struct jac acc;
+	int i, bit;
+
+	acc.inf = 1;
+	for (i = 0; i < 256; i++) {
+		bit = (k[i >> 3] >> (7 - (i & 7))) & 1;   /* big-endian bits */
+		pt_double(&acc, &acc);
+		if (bit)
+			pt_add(&acc, &acc, p);
+	}
+	*r = acc;
+}
+
+/* Affine coordinates in normal form. */
+static int pt_affine(const struct jac *p, fe x, fe y)
+{
+	fe zi, zi2, t;
+
+	if (p->inf)
+		return -1;
+	fe_inv(zi, p->z);
+	fe_sqr(zi2, zi);
+	fe_mul(t, p->x, zi2);
+	fe_from_mont(x, t);
+	fe_mul(zi2, zi2, zi);
+	fe_mul(t, p->y, zi2);
+	fe_from_mont(y, t);
+	return 0;
+}
+
+static void fe_from_bytes(fe r, const unsigned char *b)
+{
+	int i;
+
+	for (i = 0; i < 8; i++)
+		r[i] = ((unsigned int)b[28 - 4 * i] << 24) |
+		       ((unsigned int)b[29 - 4 * i] << 16) |
+		       ((unsigned int)b[30 - 4 * i] << 8) | b[31 - 4 * i];
+}
+
+static void fe_to_bytes(unsigned char *b, const fe a)
+{
+	int i;
+
+	for (i = 0; i < 8; i++) {
+		b[28 - 4 * i] = (unsigned char)(a[i] >> 24);
+		b[29 - 4 * i] = (unsigned char)(a[i] >> 16);
+		b[30 - 4 * i] = (unsigned char)(a[i] >> 8);
+		b[31 - 4 * i] = (unsigned char)a[i];
+	}
+}
+
+static int scalar_zero(const unsigned char k[32])
+{
+	unsigned int d = 0, i;
+
+	for (i = 0; i < 32; i++)
+		d |= k[i];
+	return d == 0;
+}
+
+static void base_point(struct jac *g)
+{
+	fe_to_mont(g->x, GX);
+	fe_to_mont(g->y, GY);
+	fe_copy(g->z, ONE_M);
+	g->inf = 0;
+}
+
+int p256_public(const unsigned char priv[32], unsigned char pub[65])
+{
+	struct jac g, q;
+	fe x, y;
+
+	p256_init();
+	if (scalar_zero(priv))
+		return -1;
+	base_point(&g);
+	pt_mul(&q, priv, &g);
+	if (pt_affine(&q, x, y) != 0)
+		return -1;
+	pub[0] = 0x04;
+	fe_to_bytes(pub + 1, x);
+	fe_to_bytes(pub + 33, y);
+	return 0;
+}
+
+int p256_shared(const unsigned char priv[32], const unsigned char *peer,
+		unsigned int peer_len, unsigned char out[32])
+{
+	struct jac p, q;
+	fe x, y, xm, ym, lhs, rhs, t, three, bm;
+
+	p256_init();
+	if (peer_len != 65 || peer[0] != 0x04 || scalar_zero(priv))
+		return -1;
+	fe_from_bytes(x, peer + 1);
+	fe_from_bytes(y, peer + 33);
+	if (!fe_lt_p(x) || !fe_lt_p(y))
+		return -1;
+	/* On the curve: y^2 = x^3 - 3x + b. */
+	fe_to_mont(xm, x);
+	fe_to_mont(ym, y);
+	fe_sqr(lhs, ym);
+	fe_sqr(t, xm);
+	fe_mul(rhs, t, xm);
+	fe_add(three, xm, xm);
+	fe_add(three, three, xm);
+	fe_sub(rhs, rhs, three);
+	fe_to_mont(bm, B);
+	fe_add(rhs, rhs, bm);
+	if (!fe_eq(lhs, rhs))
+		return -1;
+	fe_copy(p.x, xm);
+	fe_copy(p.y, ym);
+	fe_copy(p.z, ONE_M);
+	p.inf = 0;
+	pt_mul(&q, priv, &p);
+	if (pt_affine(&q, x, y) != 0)
+		return -1;
+	fe_to_bytes(out, x);
+	return 0;
+}

+ 18 - 0
tls_p256.h

@@ -0,0 +1,18 @@
+/* NIST P-256 (secp256r1) ECDH for the TLS 1.2 client: servers behind older
+ * load balancers offer ECDHE only over P-256/P-384, never X25519.
+ * Montgomery field arithmetic on 8x32-bit limbs, Jacobian points.  ECDH
+ * only (certificates are not verified, so there is no ECDSA).  Not
+ * constant time.  Pure freestanding C with host vectors (make test-crypto). */
+#ifndef TLS_P256_H
+#define TLS_P256_H
+
+/* pub = 0x04 || X || Y (uncompressed, 65 bytes) for the private scalar.
+ * Returns 0, -1 for a zero scalar. */
+int p256_public(const unsigned char priv[32], unsigned char pub[65]);
+
+/* out = X coordinate of priv * peer.  Returns -1 when the peer point is not
+ * an uncompressed point on the curve. */
+int p256_shared(const unsigned char priv[32], const unsigned char *peer,
+		unsigned int peer_len, unsigned char out[32]);
+
+#endif

+ 35 - 0
tls_sha256.c

@@ -305,3 +305,38 @@ void hkdf_expand_label(const unsigned char secret[32], const char *label,
 
 	hkdf_expand(secret, info, o, out, out_len);
 }
+
+void tls12_prf(const unsigned char *secret, unsigned int secret_len,
+	       const char *label, const unsigned char *seed1,
+	       unsigned int seed1_len, const unsigned char *seed2,
+	       unsigned int seed2_len, unsigned char *out,
+	       unsigned int out_len)
+{
+	struct hmac_sha256_ctx h;
+	unsigned char a[32], blk[32];
+	unsigned int llen = 0, i, n;
+
+	while (label[llen])
+		llen++;
+	/* A(1) = HMAC(secret, label || seed) */
+	hmac_sha256_init(&h, secret, secret_len);
+	hmac_sha256_update(&h, label, llen);
+	hmac_sha256_update(&h, seed1, seed1_len);
+	if (seed2)
+		hmac_sha256_update(&h, seed2, seed2_len);
+	hmac_sha256_final(&h, a);
+	while (out_len) {
+		hmac_sha256_init(&h, secret, secret_len);
+		hmac_sha256_update(&h, a, 32);
+		hmac_sha256_update(&h, label, llen);
+		hmac_sha256_update(&h, seed1, seed1_len);
+		if (seed2)
+			hmac_sha256_update(&h, seed2, seed2_len);
+		hmac_sha256_final(&h, blk);
+		n = out_len < 32 ? out_len : 32;
+		for (i = 0; i < n; i++)
+			*out++ = blk[i];
+		out_len -= n;
+		hmac_sha256(secret, secret_len, a, 32, a);
+	}
+}

+ 8 - 0
tls_sha256.h

@@ -41,4 +41,12 @@ void hkdf_expand_label(const unsigned char secret[32], const char *label,
 		       const unsigned char *ctx, unsigned int ctx_len,
 		       unsigned char *out, unsigned int out_len);
 
+/* TLS 1.2 PRF with P_SHA256 (RFC 5246 section 5):
+ * out = P_SHA256(secret, label || seed1 || seed2); seed2 may be NULL. */
+void tls12_prf(const unsigned char *secret, unsigned int secret_len,
+	       const char *label, const unsigned char *seed1,
+	       unsigned int seed1_len, const unsigned char *seed2,
+	       unsigned int seed2_len, unsigned char *out,
+	       unsigned int out_len);
+
 #endif

+ 109 - 1
tls_test.c

@@ -2,7 +2,8 @@
  * tls_chacha20.c, tls_x25519.c).  Independent references: NIST/RFC 4231
  * for SHA-256/HMAC, RFC 5869 for HKDF, an independently generated TLS 1.3
  * expand-label chain, RFC 8439 for ChaCha20-Poly1305 and RFC 7748 for
- * X25519.  Build and run: make test-crypto */
+ * X25519, NIST SP 800-38D (GCM test cases 2/4), RFC 5903 (P-256 ECDH) and
+ * the IETF TLS 1.2 P_SHA256 PRF vector.  Build and run: make test-crypto */
 
 #include <stdio.h>
 #include <string.h>
@@ -10,6 +11,8 @@
 #include "tls_sha256.h"
 #include "tls_chacha20.h"
 #include "tls_x25519.h"
+#include "tls_gcm.h"
+#include "tls_p256.h"
 
 static int failures;
 static int checks;
@@ -231,6 +234,108 @@ static void test_x25519(void)
 	check("x25519 shared b", shared, shared_hex, 32);
 }
 
+static void test_gcm(void)
+{
+	struct gcm_key k;
+	struct gcm_ctx c;
+	unsigned char key[16], iv[12], aad[20], pt[60], ct[64], tag[16];
+	unsigned char out[60];
+	static const char *ct4 =
+		"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e"
+		"21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091";
+	unsigned int i;
+
+	memset(key, 0, 16);
+	memset(iv, 0, 12);
+	memset(pt, 0, 16);
+	gcm_setkey(&k, key);
+	gcm_seal(&k, iv, NULL, 0, pt, 16, ct, tag);
+	check("gcm tc2 ct", ct, "0388dace60b6a392f328c2b971b2fe78", 16);
+	check("gcm tc2 tag", tag, "ab6e47d42cec13bdf53a67b21257bddf", 16);
+
+	unhex("feffe9928665731c6d6a8f9467308308", key, 16);
+	unhex("cafebabefacedbaddecaf888", iv, 12);
+	unhex("feedfacedeadbeeffeedfacedeadbeefabaddad2", aad, 20);
+	unhex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72"
+	      "1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39", pt, 60);
+	gcm_setkey(&k, key);
+	gcm_seal(&k, iv, aad, 20, pt, 60, ct, tag);
+	check("gcm tc4 ct", ct, ct4, 60);
+	check("gcm tc4 tag", tag, "5bc94fbc3221a5db94fae95ae7121a47", 16);
+
+	/* Streamed open in odd-sized chunks. */
+	gcm_open_init(&c, &k, iv, aad, 20);
+	for (i = 0; i < 60; i += 7)
+		gcm_open_update(&c, out + i, ct + i, 60 - i < 7 ? 60 - i : 7);
+	gcm_open_tag(&c, tag);
+	check("gcm tc4 open pt", out,
+	      "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72"
+	      "1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39", 60);
+	check("gcm tc4 open tag", tag, "5bc94fbc3221a5db94fae95ae7121a47", 16);
+}
+
+static void test_p256(void)
+{
+	unsigned char a[32], b[32], pa[65], pb[65], s[32];
+	static const char *pa_hex =
+		"04dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c3772581180"
+		"5271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3";
+	static const char *pb_hex =
+		"04d12dfb5289c8d4f81208b70270398c342296970a0bccb74c736fc7554494bf63"
+		"56fbf3ca366cc23e8157854c13c58d6aac23f046ada30f8353e74f33039872ab";
+	static const char *sh =
+		"d6840f6b42f6edafd13116e0e12565202fef8e9ece7dce03812464d04b9442de";
+
+	unhex("c88f01f510d9ac3f70a292daa2316de544e9aab8afe84049c62a9c57862d1433",
+	      a, 32);
+	unhex("c6ef9c5d78ae012a011164acb397ce2088685d8f06bf9be0b283ab46476bee53",
+	      b, 32);
+	checks++;
+	if (p256_public(a, pa) != 0)
+		failures++;
+	check("p256 pub a", pa, pa_hex, 65);
+	p256_public(b, pb);
+	check("p256 pub b", pb, pb_hex, 65);
+	memset(s, 0, 32);
+	checks++;
+	if (p256_shared(a, pb, 65, s) != 0)
+		failures++;
+	check("p256 shared a", s, sh, 32);
+	memset(s, 0, 32);
+	p256_shared(b, pa, 65, s);
+	check("p256 shared b", s, sh, 32);
+	/* n - 1: the negated generator */
+	unhex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550",
+	      a, 32);
+	p256_public(a, pa);
+	check("p256 (n-1)G", pa,
+	      "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"
+	      "b01cbd1c01e58065711814b583f061e9d431cca994cea1313449bf97c840ae0a",
+	      65);
+	/* an off-curve point is refused */
+	unhex(pb_hex, pb, 65);
+	pb[64] ^= 1;
+	checks++;
+	if (p256_shared(b, pb, 65, s) != -1) {
+		failures++;
+		printf("FAIL p256 off-curve point accepted\n");
+	}
+}
+
+static void test_prf(void)
+{
+	unsigned char secret[16], seed[16], out[100];
+
+	unhex("9bbe436ba940f017b17652849a71db35", secret, 16);
+	unhex("a0ba9f936cda311827a6f796ffd5198c", seed, 16);
+	tls12_prf(secret, 16, "test label", seed, 8, seed + 8, 8, out, 100);
+	check("tls12 prf", out,
+	      "e3f229ba727be17b8d122620557cd453c2aab21d07c3d495329b52d4e61edb5a"
+	      "6b301791e90d35c9c9a46b4e14baf9af0fa022f7077def17abfd3797c0564bab"
+	      "4fbc91666e9def9b97fce34f796789baa48082d122ee42c5a72e5a5110fff701"
+	      "87347b66", 100);
+}
+
 int main(void)
 {
 	test_sha256();
@@ -238,6 +343,9 @@ int main(void)
 	test_hkdf();
 	test_chacha();
 	test_x25519();
+	test_gcm();
+	test_p256();
+	test_prf();
 
 	printf("%s: %d checks, %d failure(s)\n",
 	       failures ? "FAIL" : "ok", checks, failures);

+ 341 - 25
ucmd_chat.c

@@ -25,6 +25,7 @@
 #include "img.h"
 
 #include <stdlib.h>
+#include <stdio.h>
 #include <string.h>
 
 #define DEFAULT_CFG_DATA  "/data/CHAT.CFG"
@@ -52,6 +53,7 @@
 #define CHAT_IMG_URL_MAX (UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16)
 #define CHAT_PIC_QUEUED 0
 #define CHAT_PIC_READY  1
+#define CHAT_PIC_FETCHING 2
 #define CHAT_PIC_FAILED (-1)
 
 #define POLL_CONV_MS        2000
@@ -515,7 +517,8 @@ static struct chat_pic *chat_pic_slot(struct chat_pic *arr, int *count, int max,
 		(*count)++;
 	} else {
 		for (i = 0; i < *count; i++) {
-			if (arr[i].state == CHAT_PIC_QUEUED)
+			if (arr[i].state == CHAT_PIC_QUEUED ||
+			    arr[i].state == CHAT_PIC_FETCHING)
 				continue;
 			if (arr[i].last_used < best) {
 				best = arr[i].last_used;
@@ -618,7 +621,7 @@ static void chat_avatar_mask(unsigned char *alpha, unsigned int w,
 static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
 {
 	struct img_info info;
-	struct img_options opt;
+	struct img_options opt = {0};
 	struct img_mem mem;
 	struct img_image decoded;
 	struct img_blit blit;
@@ -637,6 +640,8 @@ static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
 		return -1;
 	img_mem_init(&mem, arena, est);
 	opt.max_pixels = 4u * 1024u * 1024u;
+	opt.max_w = avatar ? CHAT_AVATAR : CHAT_IMG_W;
+	opt.max_h = avatar ? CHAT_AVATAR : CHAT_IMG_H;
 	r = img_decode(chat_fetch_buf, len, &opt, &mem, &decoded);
 	if (r != 0 || !decoded.w || !decoded.h)
 		return -1;
@@ -706,33 +711,325 @@ static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
 	return 0;
 }
 
-static void chat_pic_load(struct chat_pic *p, int avatar)
+/* Install a message-image bitmap decoded by the fetch helper (the helper
+ * already applied the 480x320 bounds).  Avatars are still decoded here at
+ * 32x32 so the circular mask sees the same square source as before. */
+static int chat_pic_store_px(struct chat_pic *p, unsigned char *buf,
+			     unsigned int len, unsigned int dw,
+			     unsigned int dh, int has_alpha)
 {
-	unsigned int len = 0;
-	int st;
+	unsigned int npx = dw * dh, need;
+	unsigned short *px;
+	unsigned char *alpha = 0;
 
-	if (!chat_fetch_buf)
-		chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX);
-	if (!chat_fetch_buf) {
-		p->state = CHAT_PIC_FAILED;
+	if (!buf || !dw || !dh || len < npx * 2u)
+		return -1;
+	need = npx * 2u;
+	if (chat_image_room(need) != 0)
+		return -1;
+	px = (unsigned short *)malloc(need);
+	if (!px)
+		return -1;
+	memcpy(px, buf, need);
+	if (has_alpha && len >= need + npx) {
+		alpha = (unsigned char *)malloc(npx);
+		if (alpha)
+			memcpy(alpha, buf + need, npx);
+	}
+	p->img.format = 0;
+	p->img.w = dw;
+	p->img.h = dh;
+	p->img.px = px;
+	p->img.alpha = alpha;
+	p->img.flags = 0;
+	p->bytes = need;
+	chat_image_bytes += need;
+	return 0;
+}
+
+/* ---- asynchronous media fetch ----
+ *
+ * chat_http() blocks the UI for the whole body, so every image and avatar
+ * used to freeze the window for the download plus the decode.  Media now
+ * goes through the same curl __serve helper as the browser: the chat loop
+ * submits a request file and polls a small done marker, while a private tty
+ * absorbs the helper's DNS/TLS log lines.  Only the (short) decode runs on
+ * the chat thread. */
+static int chat_media_pid = -1;
+static int chat_media_tty = -1;
+static unsigned int chat_media_session;
+static unsigned int chat_media_seq;
+static unsigned int chat_media_deadline;
+static int chat_media_busy;
+static int chat_media_retried;
+static struct chat_pic *chat_media_pic;
+static int chat_media_avatar;
+static char chat_media_req[40], chat_media_body[40];
+static char chat_media_meta[40], chat_media_done[40];
+static char chat_media_px[40];
+
+static void chat_media_paths(void)
+{
+	if (chat_media_session)
+		return;
+	chat_media_session = ((unsigned int)u_getpid() << 16) ^
+			     (u_ticks_ms() & 0xFFFFu);
+	if (!chat_media_session)
+		chat_media_session = 1;
+	snprintf(chat_media_req, sizeof(chat_media_req), "/share/bf%u_0req",
+		 chat_media_session);
+	snprintf(chat_media_body, sizeof(chat_media_body), "/share/bf%u_0body",
+		 chat_media_session);
+	snprintf(chat_media_meta, sizeof(chat_media_meta), "/share/bf%u_0meta",
+		 chat_media_session);
+	snprintf(chat_media_done, sizeof(chat_media_done), "/share/bf%u_0done",
+		 chat_media_session);
+	snprintf(chat_media_px, sizeof(chat_media_px), "/share/bf%u_0px",
+		 chat_media_session);
+}
+
+static void chat_media_tty_drain(void)
+{
+	char sink[256];
+	int i;
+
+	if (chat_media_tty <= 0)
 		return;
+	for (i = 0; i < 8; i++)
+		if (u_tty_read(chat_media_tty, sink, sizeof(sink)) <= 0)
+			break;
+}
+
+static void chat_media_jar_sync(void)
+{
+	u_syscall3(SYS_WRITE_FILE, (int)"/share/bchat.jar", (int)&jar,
+		   (int)sizeof(jar));
+}
+
+static int chat_media_start(void)
+{
+	char arg[64];
+	int t;
+
+	chat_media_paths();
+	if (chat_media_pid > 0 && u_alive((unsigned int)chat_media_pid))
+		return 0;
+	chat_media_pid = -1;
+	if (chat_media_tty == -1) {
+		t = u_tty_create();
+		chat_media_tty = t > 0 ? t : 0;
+	}
+	chat_media_jar_sync();
+	snprintf(arg, sizeof(arg), "__serve %u 0 /share/bchat.jar",
+		 chat_media_session);
+	chat_media_pid = u_spawn("/ramfs/bin/curl", arg, chat_media_tty, "/");
+	if (chat_media_pid <= 0) {
+		chat_media_pid = -1;
+		return -1;
 	}
-	http.jar = &jar;
-	http.accept = "image/*,*/*";
-	st = chat_http(&http, 0, p->url, 0, (char *)chat_fetch_buf,
-		       CHAT_IMG_FETCH_MAX, &len);
-	if (st != 200 || len == 0 || chat_pic_store(p, len, avatar) != 0) {
-		p->state = CHAT_PIC_FAILED;
-	} else {
-		p->state = CHAT_PIC_READY;
-		p->last_used = ++chat_pic_clock;
-		if (!avatar) {
-			msgs_gen++;
-			if (at_bottom)
-				tl_scroll.offset = 1 << 28;
+	return 0;
+}
+
+static void chat_media_stop(void)
+{
+	chat_media_tty_drain();
+	if (chat_media_pid > 0)
+		u_kill((unsigned int)chat_media_pid);
+	chat_media_pid = -1;
+}
+
+static void chat_media_fail(void)
+{
+	if (chat_media_pic)
+		chat_media_pic->state = CHAT_PIC_FAILED;
+	chat_media_pic = 0;
+	chat_media_busy = 0;
+	chat_media_retried = 0;
+	u_syscall1(SYS_UNLINK, (int)chat_media_done);
+	u_syscall1(SYS_UNLINK, (int)chat_media_meta);
+	u_syscall1(SYS_UNLINK, (int)chat_media_body);
+	u_syscall1(SYS_UNLINK, (int)chat_media_px);
+	ngui_invalidate(&ui);
+}
+
+static int chat_media_submit(struct chat_pic *p, int avatar)
+{
+	char req[512];
+	int n;
+
+	if (!chat_fetch_buf) {
+		chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX);
+		if (!chat_fetch_buf)
+			return -1;
+	}
+	chat_media_paths();
+	if (chat_media_start() != 0)
+		return -1;
+	chat_media_jar_sync();
+	chat_media_seq++;
+	if (!chat_media_seq)
+		chat_media_seq = 1;
+	chat_media_retried = 0;
+	if (!avatar)
+		n = snprintf(req, sizeof(req), "%u %u D %u %u %s\n",
+			     chat_media_seq, CHAT_IMG_FETCH_MAX,
+			     CHAT_IMG_W, CHAT_IMG_H, p->url);
+	else
+		n = snprintf(req, sizeof(req), "%u %u %s\n",
+			     chat_media_seq, CHAT_IMG_FETCH_MAX, p->url);
+	if (n <= 0 || n >= (int)sizeof(req))
+		return -1;
+	u_syscall1(SYS_UNLINK, (int)chat_media_done);
+	u_syscall1(SYS_UNLINK, (int)chat_media_meta);
+	u_syscall1(SYS_UNLINK, (int)chat_media_body);
+	u_syscall1(SYS_UNLINK, (int)chat_media_px);
+	if (u_syscall3(SYS_WRITE_FILE, (int)chat_media_req, (int)req, n) < 0)
+		return -1;
+	p->state = CHAT_PIC_FETCHING;
+	chat_media_pic = p;
+	chat_media_avatar = avatar;
+	chat_media_busy = 1;
+	chat_media_deadline = u_ticks_ms() + 30000;
+	return 0;
+}
+
+/* 1 when the outstanding job finished (success or failure). */
+static unsigned int chat_meta_uint(char **pp)
+{
+	char *p = *pp;
+	unsigned int v = 0;
+
+	while (*p >= '0' && *p <= '9') {
+		v = v * 10 + (unsigned int)(*p - '0');
+		p++;
+	}
+	while (*p && *p != '\n')
+		p++;
+	if (*p)
+		p++;
+	*pp = p;
+	return v;
+}
+
+static int chat_media_poll(void)
+{
+	char done[24], meta[1200];
+	int rn, st = 0, err = 0;
+	unsigned int seq;
+	unsigned int dw = 0, dh = 0, nw = 0, nh = 0, alpha = 0;
+	unsigned int px_len = 0, dec_err = 0;
+
+	if (!chat_media_busy)
+		return 0;
+	chat_media_tty_drain();
+	rn = u_syscall3(SYS_READ_FILE, (int)chat_media_done, (int)done,
+			(int)(sizeof(done) - 1));
+	if (rn > 0) {
+		char *q;
+
+		done[rn] = '\0';
+		seq = (unsigned int)atoi(done);
+		if (seq != chat_media_seq)
+			return 0;
+		rn = u_syscall3(SYS_READ_FILE, (int)chat_media_meta, (int)meta,
+				(int)(sizeof(meta) - 1));
+		if (rn > 0) {
+			meta[rn] = '\0';
+			q = meta;
+			(void)chat_meta_uint(&q);       /* seq */
+			st = (int)chat_meta_uint(&q);
+			err = (int)chat_meta_uint(&q);
+			(void)chat_meta_uint(&q);       /* trunc */
+			while (*q && *q != '\n')         /* encoding */
+				q++;
+			if (*q)
+				q++;
+			while (*q && *q != '\n')         /* content type */
+				q++;
+			if (*q)
+				q++;
+			while (*q && *q != '\n')         /* final URL */
+				q++;
+			if (*q)
+				q++;
+			(void)chat_meta_uint(&q);       /* body bytes */
+			(void)chat_meta_uint(&q);       /* open */
+			(void)chat_meta_uint(&q);       /* first */
+			(void)chat_meta_uint(&q);       /* total */
+			dw = chat_meta_uint(&q);
+			dh = chat_meta_uint(&q);
+			nw = chat_meta_uint(&q);
+			nh = chat_meta_uint(&q);
+			alpha = chat_meta_uint(&q);
+			px_len = chat_meta_uint(&q);
+			dec_err = chat_meta_uint(&q);
+			(void)chat_meta_uint(&q);       /* dec ms */
 		}
+		if (st == 200 && !err && chat_media_pic) {
+			int stored = 0;
+
+			(void)nw;
+			(void)nh;
+			if (!chat_media_avatar && px_len && !dec_err &&
+			    dw && dh && px_len <= CHAT_IMG_FETCH_MAX) {
+				rn = u_syscall3(SYS_READ_FILE, (int)chat_media_px,
+						(int)chat_fetch_buf,
+						(int)CHAT_IMG_FETCH_MAX);
+				if (rn == (int)px_len &&
+				    chat_pic_store_px(chat_media_pic,
+						      chat_fetch_buf, px_len,
+						      dw, dh, (int)alpha) == 0)
+					stored = 1;
+			}
+			if (!stored) {
+				rn = u_syscall3(SYS_READ_FILE,
+						(int)chat_media_body,
+						(int)chat_fetch_buf,
+						(int)CHAT_IMG_FETCH_MAX);
+				if (rn > 0 &&
+				    chat_pic_store(chat_media_pic,
+						   (unsigned int)rn,
+						   chat_media_avatar) == 0)
+					stored = 1;
+			}
+			if (stored) {
+				chat_media_pic->state = CHAT_PIC_READY;
+				chat_media_pic->last_used = ++chat_pic_clock;
+				if (!chat_media_avatar) {
+					msgs_gen++;
+					if (at_bottom)
+						tl_scroll.offset = 1 << 28;
+				}
+			} else {
+				chat_media_pic->state = CHAT_PIC_FAILED;
+			}
+		} else if (chat_media_pic) {
+			chat_media_pic->state = CHAT_PIC_FAILED;
+		}
+		chat_media_pic = 0;
+		chat_media_busy = 0;
+		u_syscall1(SYS_UNLINK, (int)chat_media_done);
+		u_syscall1(SYS_UNLINK, (int)chat_media_meta);
+		u_syscall1(SYS_UNLINK, (int)chat_media_body);
+		u_syscall1(SYS_UNLINK, (int)chat_media_px);
+		ngui_invalidate(&ui);
+		return 1;
 	}
-	ngui_invalidate(&ui);
+	if (chat_media_pid > 0 && !u_alive((unsigned int)chat_media_pid)) {
+		chat_media_pid = -1;
+		if (!chat_media_retried && chat_media_start() == 0) {
+			chat_media_retried = 1;
+			return 0;
+		}
+		chat_media_fail();
+		return 1;
+	}
+	if ((int)(u_ticks_ms() - chat_media_deadline) >= 0) {
+		chat_media_stop();
+		chat_media_fail();
+		return 1;
+	}
+	return 0;
 }
 
 static void chat_media_tick(void)
@@ -741,15 +1038,30 @@ static void chat_media_tick(void)
 
 	if (screen != SCR_MAIN || offline)
 		return;
+	if (chat_media_busy) {
+		chat_media_poll();
+		return;
+	}
+	/* Holding a helper keeps a TCP socket open, which pauses the board's
+	 * net-dev watcher; release it when the window is not being used. */
+	if (!ui.focused) {
+		if (chat_media_pid > 0)
+			chat_media_stop();
+		return;
+	}
 	for (i = 0; i < nchat_images; i++) {
 		if (chat_images[i].state == CHAT_PIC_QUEUED) {
-			chat_pic_load(&chat_images[i], 0);
+			if (chat_media_submit(&chat_images[i], 0) != 0)
+				chat_images[i].state = CHAT_PIC_FAILED;
+			ngui_invalidate(&ui);
 			return;
 		}
 	}
 	for (i = 0; i < nchat_avatars; i++) {
 		if (chat_avatars[i].state == CHAT_PIC_QUEUED) {
-			chat_pic_load(&chat_avatars[i], 1);
+			if (chat_media_submit(&chat_avatars[i], 1) != 0)
+				chat_avatars[i].state = CHAT_PIC_FAILED;
+			ngui_invalidate(&ui);
 			return;
 		}
 	}
@@ -759,6 +1071,10 @@ static void chat_media_clear(void)
 {
 	int i;
 
+	chat_media_stop();
+	chat_media_pic = 0;
+	chat_media_busy = 0;
+	chat_media_retried = 0;
 	for (i = 0; i < nchat_images; i++)
 		chat_pic_free(&chat_images[i]);
 	for (i = 0; i < nchat_avatars; i++)

+ 1 - 1
ucmd_cpuinfo.c

@@ -300,7 +300,7 @@ void _start(void)
 			put_uint((unsigned int)ct.tjmax_c);
 			u_puts(" C)\n");
 		} else {
-			u_puts("temp unavailable (no Intel DTS)\n");
+			u_puts("temp unavailable (no supported sensor)\n");
 		}
 	}
 	u_puts("eist ");

+ 182 - 8
ucmd_curl.c

@@ -14,6 +14,7 @@
 #include "ucmd_lib.h"
 #include "uhttp.h"
 #include "uhttp_cookie.h"
+#include "img.h"
 
 #define LINE_MAX_C 320
 
@@ -63,7 +64,7 @@ static const struct uhttp_hooks hooks = {
 
 #define FETCH_PATH_MAX 32
 #define FETCH_POST_MAX 16384u
-#define FETCH_MAX   (2u * 1024u * 1024u)
+#define FETCH_MAX   (4u * 1024u * 1024u)
 
 /* Each browser worker gets its own set of /share files; slot -1 keeps the
  * historical single-helper names for the one-shot __fetch mode. */
@@ -73,6 +74,7 @@ struct fetch_paths {
 	char meta[FETCH_PATH_MAX];
 	char done[FETCH_PATH_MAX];
 	char post[FETCH_PATH_MAX];
+	char px[FETCH_PATH_MAX];
 };
 static struct fetch_paths fp;
 
@@ -123,6 +125,117 @@ static void fetch_paths_init(unsigned int session, int slot)
 	fetch_path(fp.meta, sizeof(fp.meta), "meta", session, slot);
 	fetch_path(fp.done, sizeof(fp.done), "done", session, slot);
 	fetch_path(fp.post, sizeof(fp.post), "post", session, slot);
+	fetch_path(fp.px, sizeof(fp.px), "px", session, slot);
+}
+
+/* Optional decode in the fetch helper.  The browser's UI thread only has
+ * to copy the finished RGB565 bitmap; the JPEG IDCT/box filter runs in the
+ * helper process (and several helpers can decode in parallel). */
+#define DECODE_ARENA_MAX (24u * 1024u * 1024u)
+#define DECODE_PX_MAX    (8u * 1024u * 1024u)
+
+struct fetch_px {
+	unsigned char *data;
+	unsigned int len, dw, dh, nw, nh, alpha, format;
+	unsigned int dec_ms;
+	int err;
+};
+
+static void fetch_decode(const unsigned char *data, unsigned int len,
+			 unsigned int max_w, unsigned int max_h,
+			 struct fetch_px *out)
+{
+	struct img_info info;
+	struct img_options opt = {0};
+	struct img_mem mem;
+	struct img_image im;
+	unsigned char *arena;
+	unsigned int est, dw, dh, outlen, n;
+	int r;
+
+	memset(out, 0, sizeof(*out));
+	if (img_sniff(data, len, &info) != 0) {
+		out->err = 1;
+		return;
+	}
+	est = img_estimate(&info);
+	if (est == 0xFFFFFFFFu || est > DECODE_ARENA_MAX) {
+		out->err = 2;
+		return;
+	}
+	arena = (unsigned char *)malloc(est);
+	if (!arena) {
+		out->err = 3;
+		return;
+	}
+	img_mem_init(&mem, arena, est);
+	opt.max_pixels = 8u * 1024u * 1024u;
+	opt.max_w = max_w;
+	opt.max_h = max_h;
+	r = img_decode(data, len, &opt, &mem, &im);
+	if (r != 0 || !im.w || !im.h) {
+		out->err = 4;
+		free(arena);
+		return;
+	}
+	dw = im.w;
+	dh = im.h;
+	if (max_w && dw > max_w) {
+		dh = (unsigned int)((unsigned long long)dh * max_w / dw);
+		dw = max_w;
+	}
+	if (max_h && dh > max_h) {
+		dw = (unsigned int)((unsigned long long)dw * max_h / dh);
+		dh = max_h;
+	}
+	if (!dw)
+		dw = 1;
+	if (!dh)
+		dh = 1;
+	if (dw > 4096 || dh > 4096) {
+		out->err = 5;
+		free(arena);
+		return;
+	}
+	outlen = dw * dh * 2u + (im.alpha ? dw * dh : 0);
+	if (outlen > DECODE_PX_MAX) {
+		out->err = 5;
+		free(arena);
+		return;
+	}
+	out->data = (unsigned char *)malloc(outlen);
+	if (!out->data) {
+		out->err = 6;
+		free(arena);
+		return;
+	}
+	if (dw == im.w && dh == im.h) {
+		n = dw * dh;
+		memcpy(out->data, im.px, n * 2u);
+		if (im.alpha)
+			memcpy(out->data + n * 2u, im.alpha, n);
+	} else {
+		struct img_blit b;
+
+		memset(&b, 0, sizeof(b));
+		b.dst = (unsigned short *)out->data;
+		b.dst_w = (int)dw;
+		b.dst_h = (int)dh;
+		b.clip_w = (int)dw;
+		b.clip_h = (int)dh;
+		b.scale = ((unsigned int)dw << 16) / im.w;
+		b.dst_a = im.alpha ? out->data + dw * dh * 2u : 0;
+		b.flags = im.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
+		img_draw(&im, &b);
+	}
+	out->len = outlen;
+	out->dw = dw;
+	out->dh = dh;
+	out->nw = info.width;
+	out->nh = info.height;
+	out->alpha = im.alpha ? 1 : 0;
+	out->format = info.format;
+	free(arena);
 }
 
 static void fetch_fail(unsigned int status, int err, const char *ctype,
@@ -146,11 +259,12 @@ static void fetch_fail(unsigned int status, int err, const char *ctype,
  * the parallel workers.  Re-read before each request and written back when
  * the response changed it; with several helpers the last writer wins. */
 #define FETCH_JAR_PATH "/share/bcookies"
+static char fetch_jar_path[64] = FETCH_JAR_PATH;
 static struct uhttp_jar fetch_jar;
 
 static void jar_load(void)
 {
-	int n = u_syscall3(SYS_READ_FILE, (int)FETCH_JAR_PATH,
+	int n = u_syscall3(SYS_READ_FILE, (int)fetch_jar_path,
 			   (int)&fetch_jar, (int)sizeof(fetch_jar));
 
 	if (n != (int)sizeof(fetch_jar))
@@ -203,7 +317,7 @@ static void jar_save(void)
 {
 	int i, n;
 
-	n = u_syscall3(SYS_READ_FILE, (int)FETCH_JAR_PATH, (int)&jar_file,
+	n = u_syscall3(SYS_READ_FILE, (int)fetch_jar_path, (int)&jar_file,
 		       (int)sizeof(jar_file));
 	if (n != (int)sizeof(jar_file))
 		uhttp_jar_init(&jar_file);
@@ -223,7 +337,7 @@ static void jar_save(void)
 		if (o->used && !jar_lookup(&fetch_jar, o))
 			jar_replay(o, 1);
 	}
-	u_syscall3(SYS_WRITE_FILE, (int)FETCH_JAR_PATH, (int)&jar_file,
+	u_syscall3(SYS_WRITE_FILE, (int)fetch_jar_path, (int)&jar_file,
 		   (int)sizeof(jar_file));
 }
 
@@ -235,7 +349,7 @@ struct fetch_times {
 
 static void write_meta(unsigned int seq, int with_seq, struct uhttp *h,
 		       int err, unsigned int body_len, unsigned int body_trunc,
-		       const struct fetch_times *t)
+		       const struct fetch_times *t, const struct fetch_px *px)
 {
 	char meta[1024];
 	unsigned int n = 0;
@@ -254,6 +368,16 @@ static void write_meta(unsigned int seq, int with_seq, struct uhttp *h,
 	app_dec(meta, &n, t ? t->open_ms : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
 	app_dec(meta, &n, t ? t->first_ms : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
 	app_dec(meta, &n, t ? t->total_ms : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	/* Optional decoded bitmap: dw, dh, native w/h, alpha, px bytes, error,
+	 * format. */
+	app_dec(meta, &n, px ? px->dw : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, px ? px->dh : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, px ? px->nw : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, px ? px->nh : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, px ? px->alpha : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, px ? px->len : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, px ? (unsigned int)px->err : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, px ? px->dec_ms : 0, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
 	u_syscall3(SYS_WRITE_FILE, (int)fp.meta, (int)meta, (int)n);
 }
 
@@ -375,7 +499,7 @@ static void fetch_once(void)
 	if (body_len)
 		u_syscall3(SYS_WRITE_FILE, (int)fp.body, (int)buf,
 			   (int)body_len);
-	write_meta(0, 0, &h, err, body_len, body_trunc, &times);
+	write_meta(0, 0, &h, err, body_len, body_trunc, &times, 0);
 	uhttp_close(&h);
 	free(buf);
 	u_exit(err ? 1 : 0);
@@ -411,6 +535,15 @@ static void fetch_serve(const char *arg)
 				slot = slot * 10 + (*arg++ - '0');
 		}
 	}
+	while (*arg == ' ')
+		arg++;
+	if (*arg == '/') {
+		unsigned int n = 0;
+
+		while (*arg && *arg != ' ' && n + 1 < sizeof(fetch_jar_path))
+			fetch_jar_path[n++] = *arg++;
+		fetch_jar_path[n] = '\0';
+	}
 	fetch_paths_init(session, slot);
 
 	buf = (unsigned char *)malloc(FETCH_MAX);
@@ -426,7 +559,10 @@ static void fetch_serve(const char *arg)
 	for (;;) {
 		unsigned int seq = 0, cap = 0, body_len = 0, body_trunc = 0;
 		unsigned int post_len = 0, jar_changes;
+		unsigned int dec_w = 0, dec_h = 0;
+		int decode = 0;
 		int is_post = 0;
+		struct fetch_px px;
 		char method[12], ctype[96];
 
 		method[0] = '\0';
@@ -457,9 +593,31 @@ static void fetch_serve(const char *arg)
 				i++;
 			method[0] = '\0';
 			ctype[0] = '\0';
+			/* "<seq> <cap> D <max_w> <max_h> <url>": decode the
+			 * response at the display bounds before publishing it. */
+			if (!strncmp(req + i, "D ", 2)) {
+				i += 2;
+				while (req[i] == ' ')
+					i++;
+				while (req[i] >= '0' && req[i] <= '9') {
+					dec_w = dec_w * 10 +
+						(unsigned int)(req[i] - '0');
+					i++;
+				}
+				while (req[i] == ' ')
+					i++;
+				while (req[i] >= '0' && req[i] <= '9') {
+					dec_h = dec_h * 10 +
+						(unsigned int)(req[i] - '0');
+					i++;
+				}
+				while (req[i] == ' ')
+					i++;
+				decode = 1;
+			}
 			/* "X <method> <body length> <content type or -> <url>":
 			 * any method, for the browser's fetch()/XHR. */
-			if (!strncmp(req + i, "X ", 2)) {
+			if (!decode && !strncmp(req + i, "X ", 2)) {
 				unsigned int k = 0;
 
 				i += 2;
@@ -546,7 +704,23 @@ static void fetch_serve(const char *arg)
 		if (body_len)
 			u_syscall3(SYS_WRITE_FILE, (int)fp.body, (int)buf,
 				   (int)body_len);
-		write_meta(seq, 1, &h, err, body_len, body_trunc, &times);
+		memset(&px, 0, sizeof(px));
+		if (decode) {
+			u_syscall1(SYS_UNLINK, (int)fp.px);
+			if (body_len && !body_trunc && !err &&
+			    h.resp.status == 200 && !is_post) {
+				unsigned int td = u_ticks_ms();
+
+				fetch_decode(buf, body_len, dec_w, dec_h, &px);
+				px.dec_ms = u_ticks_ms() - td;
+				if (!px.err && px.data && px.len)
+					u_syscall3(SYS_WRITE_FILE, (int)fp.px,
+						   (int)px.data, (int)px.len);
+			}
+		}
+		write_meta(seq, 1, &h, err, body_len, body_trunc, &times, &px);
+		if (px.data)
+			free(px.data);
 		app_dec(done, &dn, seq, sizeof(done));
 		u_syscall3(SYS_WRITE_FILE, (int)fp.done, (int)done, (int)dn);
 

+ 9 - 0
ucmd_lib.h

@@ -6,6 +6,14 @@
 #include "syscall.h"
 #include "wm_abi.h"
 
+#ifdef UCMD_HOST
+/* The Linux host harness implements the same little syscall ABI in
+ * host/syscall.c; no ring transition is involved. */
+int u_syscall0(int num);
+int u_syscall1(int num, int a1);
+int u_syscall2(int num, int a1, int a2);
+int u_syscall3(int num, int a1, int a2, int a3);
+#else
 static inline int u_syscall1(int num, int a1)
 {
 	int ret;
@@ -45,6 +53,7 @@ static inline int u_syscall3(int num, int a1, int a2, int a3)
 			  : "memory");
 	return ret;
 }
+#endif /* !UCMD_HOST */
 
 static inline void u_putc(char c)
 {

+ 19 - 17
ucmd_netmenu.c

@@ -1127,7 +1127,7 @@ static void draw_wifi_list(struct ngui_rect area, int *y)
 
 	for (i = 0; i < nbss; i++) {
 		struct sys_wifi_bss *b = &bss[i];
-		struct ngui_rect r = { area.x, *y, area.w - 18, WIFI_ROW_H };
+		struct ngui_rect r = { area.x, *y, area.w, WIFI_ROW_H };
 
 		if (r.y + r.h > area.y && r.y < area.y + area.h) {
 			ssid_name(b, ssid);
@@ -1344,10 +1344,10 @@ static void draw_tiles(struct ngui_rect area, int *yy)
 	n++;
 
 	nrows = (n + 1) / 2;
-	colw = (area.w - 18 - MENU_GAP) / 2;
+	colw = (area.w - MENU_GAP) / 2;
 	for (i = 0; i < n; i++) {
 		int col = i & 1;
-		int w = (i + 1 < n) ? colw : (col == 0 ? area.w - 18 :
+		int w = (i + 1 < n) ? colw : (col == 0 ? area.w :
 					      colw);
 		struct ngui_rect r = {
 			area.x + col * (colw + MENU_GAP),
@@ -1397,11 +1397,11 @@ static void draw_network_section(struct ngui_rect area, int *yy)
 	struct ngui_rect r;
 	int i, shown = 0, more, n, y = *yy;
 
-	r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
 	ngui_section(&ui, r, "Network", 0, 0);
 	y += SECTION_H;
 
-	r = (struct ngui_rect){ area.x, y, area.w - 18, 64 };
+	r = (struct ngui_rect){ area.x, y, area.w, 64 };
 	draw_status_card(r);
 	y += 64 + MENU_GAP;
 
@@ -1412,7 +1412,7 @@ static void draw_network_section(struct ngui_rect area, int *yy)
 	if (shown > 4)
 		shown = 4;
 
-	r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
 	if (ngui_section(&ui, r, "Devices", ID_REFRESH, "Refresh"))
 		actions |= ACT_REFRESH;
 	y += SECTION_H;
@@ -1421,7 +1421,7 @@ static void draw_network_section(struct ngui_rect area, int *yy)
 	for (i = 0; i < ndev && n < shown; i++) {
 		if (devs[i].kind == SYS_NETDEV_WIFI)
 			continue;
-		r = (struct ngui_rect){ area.x, y, area.w - 18, DEV_ROW_H };
+		r = (struct ngui_rect){ area.x, y, area.w, DEV_ROW_H };
 		if (r.y + r.h > area.y && r.y < area.y + area.h) {
 			row.title = devs[i].name;
 			row.subtitle = devs[i].chip;
@@ -1456,7 +1456,7 @@ static void draw_network_section(struct ngui_rect area, int *yy)
 	}
 
 	y += MENU_GAP;
-	r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
 	if (wifi_present && wst.state >= SYS_WIFI_ST_ASSOC) {
 		if (ngui_section(&ui, r, "Wi-Fi", ID_DISCONNECT,
 				 "Disconnect"))
@@ -1478,7 +1478,7 @@ static void draw_network_section(struct ngui_rect area, int *yy)
 		int di;
 
 		y += MENU_GAP;
-		r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+		r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
 		ngui_section(&ui, r, "Connection", 0, 0);
 		y += SECTION_H;
 		for (di = 0; di < 4; di++) {
@@ -1497,7 +1497,7 @@ static void draw_network_section(struct ngui_rect area, int *yy)
 				vp = put_mac(vp, net.mac);
 			*vp = '\0';
 
-			r = (struct ngui_rect){ area.x, y, area.w - 18, 30 };
+			r = (struct ngui_rect){ area.x, y, area.w, 30 };
 			if (r.y + r.h > area.y && r.y < area.y + area.h) {
 				row.title = labels[di];
 				row.subtitle = 0;
@@ -1514,7 +1514,7 @@ static void draw_network_section(struct ngui_rect area, int *yy)
 		char nbuf[12], *np = nbuf;
 
 		y += MENU_GAP;
-		r = (struct ngui_rect){ area.x, y, area.w - 18, SAVED_ROW_H };
+		r = (struct ngui_rect){ area.x, y, area.w, SAVED_ROW_H };
 		if (r.y + r.h > area.y && r.y < area.y + area.h) {
 			np = put_dec(np, (unsigned int)nsaved);
 			*np = '\0';
@@ -1555,11 +1555,11 @@ static void draw_power_section(struct ngui_rect area, int *yy)
 	struct ngui_rect r;
 	int i, y = *yy;
 
-	r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
 	ngui_section(&ui, r, "Power mode", 0, 0);
 	y += SECTION_H;
 	for (i = 0; i < 3; i++) {
-		r = (struct ngui_rect){ area.x, y, area.w - 18, 42 };
+		r = (struct ngui_rect){ area.x, y, area.w, 42 };
 		if (r.y + r.h > area.y && r.y < area.y + area.h) {
 			row.title = labels[i];
 			row.subtitle = subs[i];
@@ -1591,10 +1591,10 @@ static void date_field(struct ngui_rect area, int *yy, const char *label,
 	struct ngui_rect r;
 	int ev;
 
-	r = (struct ngui_rect){ area.x + 12, *yy, area.w - 42, 18 };
+	r = (struct ngui_rect){ area.x + 12, *yy, area.w - 24, 18 };
 	ngui_text(&ui, r.x, r.y, label, ui.theme.text_dim);
 	*yy += 18;
-	r = (struct ngui_rect){ area.x + 12, *yy, area.w - 42, 32 };
+	r = (struct ngui_rect){ area.x + 12, *yy, area.w - 24, 32 };
 	ev = ngui_text_input(&ui, id, r, in);
 	if (ev & NGUI_INPUT_SUBMIT)
 		actions |= id == ID_NTP_FIELD ? ACT_DATE_NTP : ACT_DATE_SET;
@@ -1611,7 +1611,7 @@ static void draw_date_section(struct ngui_rect area, int *yy)
 	char cur[64], *p;
 	int y = *yy;
 
-	r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
 	ngui_section(&ui, r, "Date & Time", 0, 0);
 	y += SECTION_H;
 
@@ -1924,7 +1924,7 @@ static void draw_saved(void)
 			row.x = list.x;
 			row.y = list.y - saved_scroll.offset +
 				i * SAVED_LIST_ROW_H;
-			row.w = list.w - 16;
+			row.w = list.w;
 			row.h = SAVED_LIST_ROW_H;
 			if (row.y + row.h <= list.y ||
 			    row.y >= list.y + list.h)
@@ -1999,6 +1999,8 @@ void _start(const char *arg)
 	view = VIEW_MAIN;
 	expanded = EXPAND_NONE;
 	main_scroll.offset = 0;
+	main_scroll.hide_bar = 1;
+	saved_scroll.hide_bar = 1;
 
 	load_devices();
 	load_status();

+ 3 - 3
ucmd_sensors.c

@@ -1,4 +1,4 @@
-/* sensors: CPU DTS plus the board's hardware monitor.
+/* sensors: CPU temperature plus the board's hardware monitor.
  *
  * Board sources: the IT87xx Super I/O (AT3IONT-I, three temperatures and fan
  * tachometers), the ThinkPad embedded controller (X201, temperatures at EC
@@ -53,9 +53,9 @@ static void show_dts(void)
 	struct sys_cputemp ct;
 	unsigned int i;
 
-	u_puts("dts ");
+	u_puts("cpu ");
 	if (u_cpu_temp(&ct) != 0 || ct.temp_c < 0) {
-		u_puts("unavailable (no Intel DTS)\n");
+		u_puts("unavailable (no supported sensor)\n");
 		return;
 	}
 	u_puts("max ");

+ 1 - 1
ucmd_view.c

@@ -467,7 +467,7 @@ void _start(const char *arg)
 {
 	struct img_info info;
 	struct win_info wi;
-	struct img_options opt;
+	struct img_options opt = {0};
 	struct sys_stat st;
 	unsigned int n, fcap, est;
 	int r;

+ 1 - 0
uhci.c

@@ -416,6 +416,7 @@ static int control_transfer(unsigned int dev_addr, unsigned int mps,
 			qh.element = 0x1u;
 			return -1;
 		}
+		usb_poll_relax(t0);
 	}
 
 	qh.element = 0x1u;

+ 53 - 20
uhttp.c

@@ -4,6 +4,8 @@
 #include "uhttp.h"
 #include "tls.h"
 
+#include <string.h>
+
 /* ---- tiny string helpers ---- */
 
 static unsigned int s_len(const char *s)
@@ -930,7 +932,6 @@ int uhttp_read(struct uhttp *h, void *vbuf, unsigned int max,
 {
 	unsigned char *out = (unsigned char *)vbuf;
 	unsigned int n = 0;
-	int c;
 
 	if (h->error)
 		return h->error;
@@ -987,17 +988,31 @@ int uhttp_read(struct uhttp *h, void *vbuf, unsigned int max,
 					h->chunk_state = 1;
 				}
 			} else if (h->chunk_state == 1) {
-				c = reader_getc(h, timeout_ms);
-				if (c < 0) {
-					if (h->eof)
-						h->peer_close = 1;
-					if (n)
-						break;
-					return h->error ? h->error : 0;
+				unsigned int avail, want;
+
+				if (h->pos >= h->len) {
+					if (!reader_fill(h, timeout_ms)) {
+						if (h->eof)
+							h->peer_close = 1;
+						if (n)
+							break;
+						return h->error ? h->error : 0;
+					}
 				}
-				out[n++] = (unsigned char)c;
-				h->body_read++;
-				if (--h->chunk_left == 0)
+				avail = h->len - h->pos;
+				want = max - n;
+				if (want > h->chunk_left)
+					want = h->chunk_left;
+				if (want > avail)
+					want = avail;
+				if (!want)
+					continue;
+				memcpy(out + n, h->buf + h->pos, want);
+				h->pos += want;
+				n += want;
+				h->body_read += want;
+				h->chunk_left -= want;
+				if (h->chunk_left == 0)
 					h->chunk_state = 2;
 			} else if (h->chunk_state == 2) {
 				(void)reader_getc(h, timeout_ms); /* CR */
@@ -1015,21 +1030,39 @@ int uhttp_read(struct uhttp *h, void *vbuf, unsigned int max,
 				}
 			}
 		} else {
+			unsigned int avail, want;
+
 			if (h->resp.have_length &&
 			    h->body_read >= h->resp.content_length) {
 				h->eof = 1;
 				break;
 			}
-			c = reader_getc(h, timeout_ms);
-			if (c < 0) {
-				if (h->eof)
-					h->peer_close = 1;
-				if (n)
-					break;
-				return h->error ? h->error : 0;
+			if (h->pos >= h->len) {
+				if (!reader_fill(h, timeout_ms)) {
+					if (h->eof)
+						h->peer_close = 1;
+					if (n)
+						break;
+					return h->error ? h->error : 0;
+				}
+			}
+			avail = h->len - h->pos;
+			want = max - n;
+			if (h->resp.have_length) {
+				unsigned int left = h->resp.content_length -
+						    h->body_read;
+
+				if (want > left)
+					want = left;
 			}
-			out[n++] = (unsigned char)c;
-			h->body_read++;
+			if (want > avail)
+				want = avail;
+			if (!want)
+				continue;
+			memcpy(out + n, h->buf + h->pos, want);
+			h->pos += want;
+			n += want;
+			h->body_read += want;
 		}
 	}
 	return (int)n;

+ 1 - 1
uhttp.h

@@ -18,7 +18,7 @@
 #define UHTTP_PATH_MAX       1024   /* path + query (OIDC URLs are long) */
 #define UHTTP_LOC_MAX        1280
 #define UHTTP_LINE_MAX       1536   /* Location / Set-Cookie header lines */
-#define UHTTP_READER_MAX     2048
+#define UHTTP_READER_MAX     16384
 #define UHTTP_REQ_MAX        4096   /* request line + headers */
 #define UHTTP_MAX_REDIRECTS  8
 #define UHTTP_IDLE_TIMEOUT_MS  10000

+ 190 - 61
usb.c

@@ -5,9 +5,11 @@
 #include "io.h"
 #include "process.h"
 #include "sched.h"
+#include "serial.h"
 #include "timer.h"
 #include "usb.h"
 #include "usb_hcd.h"
+#include "vfs.h"
 
 /* One global controller index space.  Each entry maps to one instance of
    one controller type; a machine with EHCI + UHCI companions gets several.
@@ -111,8 +113,12 @@ static usb_probe_fn current_probe;
 static usb_device_probe_fn device_probes[USB_MAX_DEVICE_PROBES];
 static unsigned int n_device_probes;
 static int print_devices;
-static int scan_busy;
-static unsigned int scan_owner_pid;     /* pid that set scan_busy */
+static int scan_busy;                   /* a usb_scan/hotplug pass runs */
+/* Bus ownership: a scan, or a mass-storage command issued by the storage
+ * rescan, claims the controllers for one process.  While the owner sleeps
+ * in a wait loop, the transfer wrappers refuse every other context. */
+static unsigned int bus_depth;
+static unsigned int bus_owner_pid;
 
 static unsigned int cur_pid(void)
 {
@@ -121,27 +127,53 @@ static unsigned int cur_pid(void)
 	return p ? p->pid : 0;
 }
 
-static void scan_begin(void)
+int usb_bus_claim(void)
 {
-	scan_busy = 1;
-	scan_owner_pid = cur_pid();
+	unsigned int pid = cur_pid();
+
+	if (bus_depth && pid != bus_owner_pid)
+		return -1;
+	if (!bus_depth++)
+		bus_owner_pid = pid;
+	return 0;
+}
+
+void usb_bus_release(void)
+{
+	if (bus_depth && !--bus_depth)
+		bus_owner_pid = 0;
 }
 
 int usb_scan_foreign(void)
 {
-	return scan_busy && cur_pid() != scan_owner_pid;
+	return bus_depth && cur_pid() != bus_owner_pid;
 }
 
-void usb_delay_ms(unsigned int ms)
+/* 1 when the caller may sleep inside a USB wait: it owns the bus for a scan
+ * (lsusb, the kworker's HID rescan/hotplug) or for a command issued by the
+ * storage rescan, and it is not the idle/boot context (pid 0), not inside a
+ * non-preemptible section and not in an interrupts-off syscall (SYS_WIFI
+ * runs with IF clear).  Other callers (normal file I/O, the installer, NIC
+ * paths) keep busy-waiting exactly as before. */
+static int usb_can_sleep(void)
 {
-	unsigned int t0, flags;
+	unsigned int flags, pid = cur_pid();
 
+	if (!bus_depth || !bus_owner_pid || pid != bus_owner_pid)
+		return 0;
+	if (!scan_busy && !(vfs_scan_busy && vfs_scan_owner_pid == pid))
+		return 0;
+	if (this_cpu()->preempt_count)
+		return 0;
 	__asm__ volatile ("pushfl; popl %0" : "=r"(flags));
-	/* Only the scan owner sleeps, never the idle/boot context (pid 0),
-	 * a non-preemptible section or an interrupts-off syscall (SYS_WIFI
-	 * runs with IF clear). */
-	if (scan_busy && scan_owner_pid && cur_pid() == scan_owner_pid &&
-	    !this_cpu()->preempt_count && (flags & 0x200u)) {
+	return (flags & 0x200u) != 0;
+}
+
+void usb_delay_ms(unsigned int ms)
+{
+	unsigned int t0;
+
+	if (usb_can_sleep()) {
 		process_sleep_ms(ms ? ms : 1);
 		return;
 	}
@@ -150,6 +182,17 @@ void usb_delay_ms(unsigned int ms)
 		;
 }
 
+/* A yield, not a sleep: it hands the BKL to a waiting process (the WM, a
+ * terminal) and returns at once when nothing else is runnable, so a
+ * completion that lands a few ms later is still seen promptly.  A 1 ms
+ * sleep would wake on the 100 Hz idle tick and made every slow transfer
+ * cost ~10 ms. */
+void usb_poll_relax(unsigned int t0)
+{
+	if (get_ticks_ms() - t0 >= 2 && usb_can_sleep())
+		sched_yield();
+}
+
 static unsigned char dev_desc[18];
 static unsigned char desc8[64];
 static unsigned char hub_desc[16];
@@ -295,11 +338,28 @@ int usb_control_out_data(unsigned int ctrl, unsigned int addr,
 				     len, 0);
 }
 
+/* Always-on failure trail (COM1/netmon): a device that never enumerates
+   must not be silent, since boot-time input may depend on it. */
+static void usb_fail(const char *what, unsigned int ctrl, unsigned int port,
+		     unsigned int addr)
+{
+	serial_puts(SERIAL_COM1, "usb: ");
+	serial_puts(SERIAL_COM1, what);
+	serial_puts(SERIAL_COM1, " ctrl ");
+	serial_putdec(SERIAL_COM1, ctrl);
+	serial_puts(SERIAL_COM1, " port ");
+	serial_putdec(SERIAL_COM1, port);
+	serial_puts(SERIAL_COM1, " addr ");
+	serial_putdec(SERIAL_COM1, addr);
+	serial_putc(SERIAL_COM1, '\n');
+}
+
 /* Read the configuration descriptor and hand every interface with an
-   interrupt-IN endpoint to the active probe. */
-static void probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
-			 int low, unsigned int port, unsigned int vendor,
-			 unsigned int product)
+   interrupt-IN endpoint to the active probe.  Returns 1 when the device
+   answered and its configuration was parsed. */
+static int probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
+			int low, unsigned int port, unsigned int vendor,
+			unsigned int product)
 {
 	struct usb_iface_info info;
 	unsigned int total, i;
@@ -309,20 +369,20 @@ static void probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
 			   REQ_GET_DESCRIPTOR,
 			   (unsigned short)(DESC_CONFIG << 8), 0,
 			   conf_hdr, 9) < 0) {
-		dbg("usb:   config descriptor header failed\n");
-		return;
+		usb_fail("config header failed", ctrl, port, addr);
+		return 0;
 	}
 	total = (unsigned int)conf_hdr[2] | ((unsigned int)conf_hdr[3] << 8);
 	if (total < 9)
-		return;
+		return 0;
 	if (total > USB_CONFIG_MAX)
 		total = USB_CONFIG_MAX;
 	if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_STD,
 			   REQ_GET_DESCRIPTOR,
 			   (unsigned short)(DESC_CONFIG << 8), 0,
 			   conf_buf, total) < 0) {
-		dbg("usb:   config descriptor read failed\n");
-		return;
+		usb_fail("config read failed", ctrl, port, addr);
+		return 0;
 	}
 	dbg_dec("usb:   config descriptor len ", total);
 
@@ -403,19 +463,20 @@ static void probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
 	}
 	if (have_iface && info.ep_addr && current_probe)
 		current_probe(&info);
+	return 1;
 }
 
 static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
 			  int low, unsigned int port, unsigned int depth);
-static void enumerate_device(unsigned int ctrl, unsigned int addr,
-			     unsigned int mps, int low, unsigned int port,
-			     unsigned int depth);
-static void enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
-				 unsigned int depth);
-
-static void enumerate_device(unsigned int ctrl, unsigned int addr,
-			     unsigned int mps, int low, unsigned int port,
-			     unsigned int depth)
+static int enumerate_device(unsigned int ctrl, unsigned int addr,
+			    unsigned int mps, int low, unsigned int port,
+			    unsigned int depth);
+static int enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
+				unsigned int depth);
+
+static int enumerate_device(unsigned int ctrl, unsigned int addr,
+			    unsigned int mps, int low, unsigned int port,
+			    unsigned int depth)
 {
 	unsigned int vendor, product, cls, subcls, proto;
 
@@ -423,12 +484,12 @@ static void enumerate_device(unsigned int ctrl, unsigned int addr,
 			   REQ_GET_DESCRIPTOR,
 			   (unsigned short)(DESC_DEVICE << 8), 0,
 			   dev_desc, 18) < 0) {
-		dbg("usb:   device descriptor read failed\n");
+		usb_fail("device descriptor failed", ctrl, port, addr);
 		if (print_devices) {
 			indent(depth);
 			io_putstr("(device descriptor read failed)\n");
 		}
-		return;
+		return 0;
 	}
 
 	vendor  = dev_desc[8]  | ((unsigned int)dev_desc[9]  << 8);
@@ -467,11 +528,15 @@ static void enumerate_device(unsigned int ctrl, unsigned int addr,
 		io_putstr("]\n");
 	}
 
-	if ((current_probe || print_devices) && cls != 0x09)
-		probe_config(ctrl, addr, mps, low, port, vendor, product);
-
-	if (cls == 0x09)
+	if (cls == 0x09) {
 		enumerate_hub(ctrl, addr, mps, low, port, depth + 1);
+		return 1;
+	}
+
+	if (current_probe || print_devices)
+		return probe_config(ctrl, addr, mps, low, port, vendor, product);
+
+	return 1;
 }
 
 static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
@@ -595,8 +660,8 @@ static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps
 	}
 }
 
-static void enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
-				 unsigned int depth)
+static int enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
+				unsigned int depth)
 {
 	unsigned int mps;
 	unsigned int addr = next_addr[ctrl];
@@ -606,38 +671,48 @@ static void enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
 			indent(depth);
 			io_putstr("(too many devices)\n");
 		}
-		return;
+		return 0;
 	}
 
+	/* Some low/full-speed devices need a little more settle time after
+	 * the port reset than the OHCI spec's 10 ms.  Without this the 970A's
+	 * OHCI mouse was intermittently dropped before its first control
+	 * transfer. */
+	msleep(20);
+
 	/* Traditional ("old") enumeration scheme: assign the address before
 	 * reading the descriptor.  The xHCI Default-state EP0 transfer is
 	 * unreliable on this hardware, while a slot in the Addressed state
-	 * works.  The device's real max packet size is not known yet, so the
-	 * high/full-speed guess is 64 (low speed is always 8). */
-	mps = low ? 8 : 64;
+	 * works.  The device's real max packet size is not known yet, so use
+	 * the default 8-byte pipe for the first SET_ADDRESS/GET_DESCRIPTOR.
+	 * A full-speed device may have an 8-byte EP0 (the 64-byte guess made
+	 * the 970A's OHCI drop a mouse during descriptor read), and a
+	 * high-speed device accepts the short transfer and reports its real
+	 * bMaxPacketSize0 in the descriptor. */
+	mps = 8;
 	if (usb_control_out(ctrl, 0, mps, low, RT_HOST2DEV_STD,
 			    REQ_SET_ADDRESS, (unsigned short)addr, 0) < 0) {
-		dbg("usb:   SET_ADDRESS failed\n");
+		usb_fail("SET_ADDRESS failed", ctrl, port, 0);
 		if (print_devices) {
 			indent(depth);
 			io_putstr("(SET_ADDRESS failed)\n");
 		}
-		return;
+		return 0;
 	}
 	next_addr[ctrl] = addr + 1;
-	msleep(5);
+	msleep(20);
 
 	/* First 8 bytes at the assigned address (learn max packet size). */
 	if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_STD,
 			   REQ_GET_DESCRIPTOR,
 			   (unsigned short)(DESC_DEVICE << 8), 0,
 			   desc8, 8) < 0) {
-		dbg("usb:   no response at the assigned address\n");
+		usb_fail("descriptor8 failed", ctrl, port, addr);
 		if (print_devices) {
 			indent(depth);
 			io_putstr("(device descriptor read failed)\n");
 		}
-		return;
+		return 0;
 	}
 
 	mps = desc8[7];
@@ -645,7 +720,30 @@ static void enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
 		mps = 8;
 
 	dbg_dec("usb:   enumerated device, addr ", addr);
-	enumerate_device(ctrl, addr, mps, low, port, depth);
+	return enumerate_device(ctrl, addr, mps, low, port, depth);
+}
+
+/* A port reset hands the device to its companion controller, and the first
+ * control transfer after it is occasionally ignored by the SB950 OHCI
+ * (every TD stays NotAccessed for the full 2 s timeout).  A fresh port
+ * reset and a short settle makes the retry work, so keep trying a couple
+ * of times instead of leaving the port without a device until the next
+ * connect-change. */
+static int enum_port_retry(unsigned int ctrl, unsigned int port,
+			   const struct usb_hcd_ops *ops, unsigned int local)
+{
+	unsigned int try;
+
+	for (try = 0;; try++) {
+		if (enumerate_new_device(ctrl, port,
+					 ops->port_low_speed(local, port), 1))
+			return 1;
+		if (try >= 2)
+			return 0;
+		msleep(30);
+		if (ops->port_reset(local, port) != 0)
+			return 0;
+	}
 }
 
 static void add_ctrl(const struct usb_hcd_ops *ops, unsigned int count)
@@ -794,21 +892,25 @@ int usb_bulk_supported(unsigned int ctrl)
 int usb_scan(usb_probe_fn probe)
 {
 	unsigned int c, p;
+	unsigned int seen[USB_MAX_CTRL];
 
-	if (scan_busy)
+	if (scan_busy || usb_bus_claim() != 0)
 		return -2;
-	/* Claim the bus before the first controller bring-up: the boot scan
-	 * runs while the WM and the first terminal are already up, and their
-	 * USB calls must see the scan (usb_scan_foreign) rather than half-
-	 * initialized controllers. */
-	scan_begin();
+	/* The bus is claimed before the first controller bring-up: the boot
+	 * scan runs while the WM and the first terminal are already up, and
+	 * their USB calls must see the scan (usb_scan_foreign) rather than
+	 * half-initialized controllers. */
+	scan_busy = 1;
 	if (usb_hcd_init() != 0) {
 		scan_busy = 0;
+		usb_bus_release();
 		return -1;
 	}
 	generation++;
 	current_probe = probe;
 	print_devices = (probe == 0);
+	for (c = 0; c < USB_MAX_CTRL; c++)
+		seen[c] = 0;
 
 	for (c = 0; c < n_usb_ctrls; c++) {
 		const struct usb_hcd_ops *ops = usb_ctrls[c].ops;
@@ -849,8 +951,8 @@ int usb_scan(usb_probe_fn probe)
 				continue;
 			}
 			dbg("usb:   port reset ok\n");
-			enumerate_new_device(c, p,
-					     ops->port_low_speed(local, p), 1);
+			if (enum_port_retry(c, p, ops, local) && p < 32)
+				seen[c] |= 1u << p;
 		}
 
 		if (print_devices && ops->print_ports) {
@@ -859,9 +961,35 @@ int usb_scan(usb_probe_fn probe)
 		}
 	}
 
+	/* EHCI is scanned first so it can hand low/full-speed devices back to
+	 * their OHCI companion.  That handback can leave the companion port
+	 * briefly reporting "disconnected" exactly while the OHCI pass runs
+	 * (the 970A's mouse was missed that way).  A delayed second OHCI-only
+	 * pass catches ports that stayed connected but produced no device. */
+	msleep(60);
+	for (c = 0; c < n_usb_ctrls; c++) {
+		const struct usb_hcd_ops *ops = usb_ctrls[c].ops;
+		unsigned int local = usb_ctrls[c].local;
+
+		if (ops != &usb_ohci_ops)
+			continue;
+		for (p = 0; p < ops->port_count(local) && p < 32; p++) {
+			if (seen[c] & (1u << p))
+				continue;
+			if (!ops->port_connected(local, p))
+				continue;
+			ops->port_take_change(local, p);
+			if (ops->port_reset(local, p) != 0)
+				continue;
+			dbg("usb:   companion retry\n");
+			enum_port_retry(c, p, ops, local);
+		}
+	}
+
 	current_probe = 0;
 	print_devices = 0;
 	scan_busy = 0;
+	usb_bus_release();
 	return 0;
 }
 
@@ -871,7 +999,7 @@ int usb_hotplug_poll(usb_probe_fn probe)
 	unsigned int now, c, p;
 	int n = 0;
 
-	if (!n_usb_ctrls || scan_busy)
+	if (!n_usb_ctrls || scan_busy || bus_depth)
 		return 0;
 
 	now = get_ticks_ms();
@@ -879,7 +1007,8 @@ int usb_hotplug_poll(usb_probe_fn probe)
 		return 0;
 	last = now;
 
-	scan_begin();
+	usb_bus_claim();
+	scan_busy = 1;
 	current_probe = probe;
 	for (c = 0; c < n_usb_ctrls; c++) {
 		const struct usb_hcd_ops *ops = usb_ctrls[c].ops;
@@ -892,13 +1021,13 @@ int usb_hotplug_poll(usb_probe_fn probe)
 				continue;
 			if (ops->port_reset(local, p) != 0)
 				continue;
-			enumerate_new_device(c, p,
-					     ops->port_low_speed(local, p), 1);
+			enum_port_retry(c, p, ops, local);
 			n++;
 		}
 	}
 	current_probe = 0;
 	scan_busy = 0;
+	usb_bus_release();
 	return n;
 }
 

+ 18 - 6
usb.h

@@ -23,13 +23,25 @@ const char *usb_hcd_name_ctrl(unsigned int ctrl);
 int usb_scan(usb_probe_fn probe);
 
 /* Delay used by the USB core and every HCD.  Inside a bus scan owned by a
- * sleepable process (lsusb, the kworker's HID rescan) it sleeps, which
- * drops the BKL so the WM and other processes keep running through port
- * resets and settle times; otherwise it busy-waits as before. */
+ * sleepable process (lsusb, the kworker's HID rescan), or a command the
+ * storage rescan issues with the bus claimed, it sleeps, which drops the
+ * BKL so the WM and other processes keep running through port resets and
+ * settle times; otherwise it busy-waits as before. */
 void usb_delay_ms(unsigned int ms);
-/* 1 while another context's scan owns the controllers (it is sleeping in
- * usb_delay_ms).  The transfer wrappers then refuse access; pollers such as
- * usbhid skip their tick. */
+/* Call from every HCD completion-poll loop (outside its spinlock) with the
+ * loop's start time: once the wait has run 2 ms, a sleepable bus owner
+ * yields (dropping the BKL for any waiter) instead of spinning with it
+ * held.  A no-op otherwise. */
+void usb_poll_relax(unsigned int t0);
+/* Claim the controllers for the calling process (nests).  Returns -1 when
+ * another context owns them.  Every USB transaction that may sleep in a
+ * wait loop must run inside a claim, so no other context can touch the
+ * controller while the owner sleeps. */
+int usb_bus_claim(void);
+void usb_bus_release(void);
+/* 1 while another context owns the controllers (a scan, or a claimed
+ * mass-storage command, possibly sleeping).  The transfer wrappers then
+ * refuse access; pollers such as usbhid skip their tick. */
 int usb_scan_foreign(void);
 
 /* Cheap periodic watcher: enumerates devices on root ports whose connect

+ 14 - 2
usbhid.c

@@ -44,6 +44,7 @@ struct hid_dev {
 	unsigned int ctrl, addr, ep, mps, port;
 	int low;
 	unsigned int err;         /* consecutive transfer errors */
+	unsigned int disc;        /* consecutive "port disconnected" reads */
 	/* keyboard report-diff state */
 	unsigned char prev[6];
 	unsigned char prev_mod;
@@ -267,6 +268,7 @@ static void dev_attach(struct hid_dev *d, unsigned int slot)
 	if (usb_int_in_start(d->ctrl, slot, d->addr, d->ep, d->mps, d->low) != 0)
 		return;
 	d->err = 0;
+	d->disc = 0;
 	d->present = 1;
 	d->prev_mod = 0;
 	for (i = 0; i < 6; i++)
@@ -288,6 +290,10 @@ static void dev_detach(struct hid_dev *d, unsigned int slot)
 	usb_int_in_stop(slot);
 	d->present = 0;
 	d->claimed = 0;
+	/* A false port-loss leaves the device attached but unreachable (no
+	 * CSC to wake the hotplug watcher).  A clean full rescan re-arms
+	 * everything, and is the only reliable recovery on this SB950. */
+	need_rescan = 1;
 	last_watch = get_ticks_ms() - WATCH_MS;   /* watch again soon */
 	serial_puts(SERIAL_COM1, d->kind == KIND_MOUSE
 				   ? "usbhid: mouse detached (addr "
@@ -365,13 +371,19 @@ static int dev_poll(struct hid_dev *d, unsigned int slot, unsigned char *buf,
 
 	if (!d->present)
 		return 0;
+	/* CCS can glitch for a frame on the SB950; a single read must not
+	 * detach a working device.  Require three consecutive misses. */
 	if (d->port != 0xFFu && !usb_port_connected(d->ctrl, d->port)) {
-		dev_detach(d, slot);
+		if (++d->disc >= 3)
+			dev_detach(d, slot);
 		return 0;
 	}
+	d->disc = 0;
 	n = usb_int_in_poll(slot, buf, len);
 	if (n < 0) {
-		if (++d->err >= 5)
+		/* The HCD re-arms on every error; a short burst is normal on
+		 * a marginal low-speed link and must not kill the device. */
+		if (++d->err >= 50)
 			dev_detach(d, slot);
 		return 0;
 	}

+ 48 - 9
usbmsc.c

@@ -78,12 +78,11 @@ static void put32be(unsigned char *p, unsigned int v)
 	p[3] = (unsigned char)(v & 0xFF);
 }
 
+/* Sleeps inside a bus scan or a claimed storage-rescan command (see
+ * usb_delay_ms); busy-waits everywhere else. */
 static void msc_delay(unsigned int ms)
 {
-	unsigned int t0 = get_ticks_ms();
-
-	while (get_ticks_ms() - t0 < ms)
-		;
+	usb_delay_ms(ms);
 }
 
 /* Bulk IN with a deadline.  Transfers larger than the host controller's
@@ -111,6 +110,8 @@ static int msc_bulk_in(struct usb_msc *m, unsigned char *buf, unsigned int len)
 			t0 = get_ticks_ms();
 		} else if (get_ticks_ms() - t0 > MSC_TIMEOUT_MS) {
 			return -1;
+		} else {
+			usb_poll_relax(t0);
 		}
 	}
 	return 0;
@@ -492,8 +493,8 @@ static int msc_get(unsigned int unit, struct usb_msc **out)
 	return 0;
 }
 
-int usbmsc_read(unsigned int unit, unsigned int lba, void *buf,
-		unsigned int count)
+static int msc_read_claimed(unsigned int unit, unsigned int lba, void *buf,
+			    unsigned int count)
 {
 	struct usb_msc *m;
 	unsigned char *p = (unsigned char *)buf;
@@ -544,8 +545,8 @@ int usbmsc_read(unsigned int unit, unsigned int lba, void *buf,
 	return 0;
 }
 
-int usbmsc_write(unsigned int unit, unsigned int lba, const void *buf,
-		 unsigned int count)
+static int msc_write_claimed(unsigned int unit, unsigned int lba,
+			     const void *buf, unsigned int count)
 {
 	struct usb_msc *m;
 	const unsigned char *p = (const unsigned char *)buf;
@@ -569,7 +570,7 @@ int usbmsc_write(unsigned int unit, unsigned int lba, const void *buf,
 	return 0;
 }
 
-int usbmsc_flush(unsigned int unit)
+static int msc_flush_claimed(unsigned int unit)
 {
 	struct usb_msc *m;
 
@@ -582,3 +583,41 @@ int usbmsc_flush(unsigned int unit)
 	}
 	return 0;
 }
+
+/* The block-layer entry points claim the bus for the whole command, so the
+ * storage rescan may sleep in the HCD wait loops (dropping the BKL) while
+ * no other context can start a transfer on the same controller. */
+int usbmsc_read(unsigned int unit, unsigned int lba, void *buf,
+		unsigned int count)
+{
+	int r;
+
+	if (usb_bus_claim() != 0)
+		return -1;
+	r = msc_read_claimed(unit, lba, buf, count);
+	usb_bus_release();
+	return r;
+}
+
+int usbmsc_write(unsigned int unit, unsigned int lba, const void *buf,
+		 unsigned int count)
+{
+	int r;
+
+	if (usb_bus_claim() != 0)
+		return -1;
+	r = msc_write_claimed(unit, lba, buf, count);
+	usb_bus_release();
+	return r;
+}
+
+int usbmsc_flush(unsigned int unit)
+{
+	int r;
+
+	if (usb_bus_claim() != 0)
+		return -1;
+	r = msc_flush_claimed(unit);
+	usb_bus_release();
+	return r;
+}

+ 21 - 2
vesa_stage.S

@@ -279,8 +279,9 @@ walk_modes:
 	cmpb  $16, 0x2219
 	jb    walk_modes
 
-	/* TODO: Remove this width cap when display scaling is improved. */
-	cmpw  $1280, 0x2212
+	/* 1920x1080x32 fits the 8 MB shadow reserve and the 4 MB window
+	 * canvas slot; wider modes would need a larger shadow. */
+	cmpw  $1920, 0x2212
 	ja    walk_modes
 
 	/* Check: fits in VRAM. */
@@ -292,6 +293,24 @@ walk_modes:
 2:	cmpw  vram_64k, %dx
 	ja    walk_modes
 
+	/* Keep the 32bpp shadow inside the 8 MB reserve at 0x100000:
+	 * pitch * height must not exceed 8 MB.  This rejects 1920x1200
+	 * (9.2 MB) while allowing 1920x1080 (8.29 MB). */
+	movzwl 0x2210, %eax	/* bytes per scanline */
+	movzwl 0x2214, %edx	/* height */
+	imull %edx, %eax
+	cmpl  $0x800000, %eax
+	ja    walk_modes
+
+	/* The WM maps every window's RGB565 canvas in a 4 MB slot.  A
+	 * 1920x1200 canvas needs 4.6 MB, so cap the mode at 2 M pixels
+	 * (1920x1080 = 2.07 M fits). */
+	movzwl 0x2212, %eax	/* width */
+	movzwl 0x2214, %edx	/* height */
+	imull %edx, %eax
+	cmpl  $0x200000, %eax
+	ja    walk_modes
+
 	/* Score = width * height + bpp. */
 	movzwl 0x2212, %eax
 	movzwl 0x2214, %edx

+ 3 - 1
vga.c

@@ -815,7 +815,9 @@ void vga_fb_flush(void)
 
 int vga_fb_lfb_wc(void)
 {
-	return lfb_is_wc;
+	/* `lfb_is_wc` only tracks the ION stolen-VRAM alias; the normal
+	 * MTRR-backed path is recorded in paging.c.  Report either. */
+	return lfb_is_wc || paging_lfb_wc();
 }
 
 int vga_shadow_is_active(void)

+ 6 - 0
xhci.c

@@ -508,6 +508,7 @@ static int xhci_cmd(unsigned int p0, unsigned int p1, unsigned int control,
 		spin_unlock_irqrestore(&xhci_lock, flags);
 		if (rc)
 			break;
+		usb_poll_relax(t0);
 		__asm__ volatile ("pause");
 	}
 
@@ -922,6 +923,7 @@ static int control_transfer(unsigned int ctrl, unsigned int addr,
 		spin_unlock_irqrestore(&xhci_lock, flags);
 		if (rc)
 			break;
+		usb_poll_relax(t0);
 		__asm__ volatile ("pause");
 	}
 
@@ -1216,6 +1218,7 @@ static int xhci_bulk_out(unsigned int ctrl, unsigned int addr, unsigned int ep,
 		spin_unlock_irqrestore(&xhci_lock, flags);
 		if (done)
 			break;
+		usb_poll_relax(t0);
 		__asm__ volatile ("pause");
 	}
 
@@ -1264,6 +1267,7 @@ static int port_reset(unsigned int ctrl, unsigned int port)
 			ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 			if (!(ps & PORTSC_PED))
 				break;
+			usb_poll_relax(t0);
 		}
 	}
 
@@ -1283,6 +1287,7 @@ static int port_reset(unsigned int ctrl, unsigned int port)
 		ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 		if (ps & PORTSC_PRC)
 			break;
+		usb_poll_relax(t0);
 	}
 	if (!(ps & PORTSC_PRC)) {
 		dbg_hex("xhci: port reset timeout ", port);
@@ -1296,6 +1301,7 @@ static int port_reset(unsigned int ctrl, unsigned int port)
 		ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 		if (ps & PORTSC_PED)
 			break;
+		usb_poll_relax(t0);
 	}
 	if (!(ps & PORTSC_PED)) {
 		dbg_hex("xhci: port not enabled ", port);

Vissa filer visades inte eftersom för många filer har ändrats