Ver Fonte

Add WebDAV share, sensors and idle modes

- /share RAM filesystem, VFS stat/display-name ABI and the websrv WebDAV server
- TCP listener/accept and server-side send/receive support
- IT87 board sensors and thermal exposure in the top bar and sensors command
- runtime HLT/C2/C3 idle modes with idle-rate PIT/LAPIC ticks
- mines ngui demo plus the sensors and websrv commands
Johannes Zellner há 2 semanas atrás
pai
commit
f507d3bca5
47 ficheiros alterados com 4771 adições e 178 exclusões
  1. 78 12
      AGENTS.md
  2. 24 10
      Makefile
  3. 3 3
      cpu.c
  4. 3 0
      cpu.h
  5. 80 29
      idle.c
  6. 13 1
      idle.h
  7. 119 0
      it87.c
  8. 20 0
      it87.h
  9. 37 3
      kernel.c
  10. 15 0
      lapic.c
  11. 1 0
      lapic.h
  12. 39 24
      netkexec.c
  13. 5 0
      netkexec.h
  14. 37 7
      sched.c
  15. 7 0
      sched.h
  16. 461 0
      share.c
  17. 22 0
      share.h
  18. 17 1
      smp.c
  19. 1 0
      smp.h
  20. 7 5
      switch.S
  21. 35 0
      sys_fs.c
  22. 1 0
      sys_fs.h
  23. 43 0
      sys_info.c
  24. 2 0
      sys_info.h
  25. 115 1
      sys_net.c
  26. 6 0
      sys_net.h
  27. 26 0
      syscall.c
  28. 60 3
      syscall.h
  29. 390 1
      tcp.c
  30. 19 0
      tcp.h
  31. 54 0
      terminal.c
  32. 234 0
      thermal.c
  33. 24 0
      thermal.h
  34. 9 0
      timer.h
  35. 19 0
      ucmd_cpuinfo.c
  36. 9 33
      ucmd_files.c
  37. 68 0
      ucmd_lib.h
  38. 16 7
      ucmd_ls.c
  39. 677 0
      ucmd_mines.c
  40. 126 0
      ucmd_sensors.c
  41. 18 6
      ucmd_term.c
  42. 1658 0
      ucmd_websrv.c
  43. 101 27
      ucmd_wm.c
  44. 25 1
      vfs.c
  45. 8 3
      vfs.h
  46. 35 1
      wm.c
  47. 4 0
      wm_abi.h

+ 78 - 12
AGENTS.md

@@ -36,7 +36,7 @@ make clean
    `0x600`, enables A20, enters protected mode, jumps to `kernel_entry`
    (`entry.S`, re-points ESP to the current stack top, then `kernel_main`).
 3. `kernel.c` — `kernel_main` zeroes BSS then inits serial → memory/paging →
-   ACPI/MADT → I/O → idle → processes → timer (PIT 1 kHz + IDT) → SMP AP
+   ACPI/MADT → I/O → idle → processes → timer (PIT; 1 kHz busy, 100 Hz idle + IDT) → SMP AP
    bring-up → mouse → VGA shadow buffer → terminal.
 4. `mbr.S` — MBR (USB/HDD boot); loads partition boot sector at LBA 1.
 
@@ -95,7 +95,7 @@ below the run area), so adding code no longer moves any address.
   to the BSP; user processes may run on any CPU.  The idle fallback uses
   `bkl_trylock()` (never blocks); the kworker and kernel commands take the BKL
   normally and release it around their sleeps.
-  APs use their LAPIC timer (vector 0x30); the BSP keeps the 8259 PIC/PIT and
+  APs use their LAPIC timer (vector 0x30; 1 ms busy, 10 ms idle); the BSP keeps the 8259 PIC/PIT and
   is the only global-tick source.  APs do not start taking user work until
   `smp_enable_sched()`, i.e. after device/FS setup.  LAPIC IPIs (vector 0x31)
   request a reschedule; they must be EOIed on the target LAPIC.
@@ -126,9 +126,9 @@ below the run area), so adding code no longer moves any address.
   trampoline (`kexec_tramp.S`) clears CR0.PG before the copy so it can overwrite
   the old kernel's page tables safely.
 - **Window manager**: `wm.c/h` — slot 0 runs `wm_run()`; fixed-size draggable
-  terminal windows (64×32) with a system bar (banner + purple "+ New", "+ Clock",
-  "+ Colors" and "Files" buttons + clock + rainbow). Click-to-focus,
-  drag-by-title-bar, close (×). The "+ New"
+  terminal windows (64×32) with a system bar (banner + purple "New", "Clock",
+  "Colors" and "Files" buttons + clock + CPU temperature + rainbow). Click-to-focus,
+  drag-by-title-bar, close (×). The "New"
   button and first boot spawn terminals; there is no `term` command.  Content is
   repainted per damage rect (`wm_redraw_rect`: desktop fill + every intersecting
   window back-to-front, clipped by `wm_draw_window_clip`), not by full redraws —
@@ -218,7 +218,11 @@ below the run area), so adding code no longer moves any address.
 - **Filesystem**: `fat.c` (FAT12/16/32 read/write, device-parameterized),
   `vfs.c` (mounts every FAT device under `/`), `fatdetect.c`/`fatformat.c`,
   `blkdev.c` (floppy + IDE + SATA registry), `ata.c` (ATA PIO, either the
-  legacy ports or the PCI IDE interface's native BARs — `ata_init_ports()`),
+  legacy ports or the PCI IDE interface's native BARs — `ata_init_ports()`;
+  multi-sector PIO waits for DRQ before every sector, since drives drop it
+  between sectors, polls the command-block status rather than the alt-status
+  BAR, and falls back to single-sector commands when a bridge leaves DRQ
+  pending after a multi-sector transfer),
   `disk.c` (FDC + ISA DMA ch2, retries).  `vfs.c` exposes an `fs_ops` vtable
   (FAT and the ramfs implement it) so the file service and the shell never
   touch `fat_*` directly; `vfs_resolve()` normalizes the path relative to the
@@ -231,6 +235,16 @@ below the run area), so adding code no longer moves any address.
   during it): the FAT driver has static state and the floppy still needs its
   IRQ.  So expect a brief system stall (not ticks — the PIT keeps running)
   while a command reads or writes a disk.
+- **`/share`**: `share.c/h` — writable, page-backed in-memory filesystem for
+  network uploads (the netbooted board may have no writable disk).  Entries
+  are full relative paths (like the pack ramfs) plus explicit directory
+  entries, so empty directories work; names are plain strings (up to 63
+  bytes), file data comes from `mm_alloc_pages()` and is freed on
+  replace/delete.  Limits: 64 entries and 16 MB, volatile across reboot/kexec.
+  Mounted at `/share` by `vfs_mount_all()`, so it appears in `ls /` and the
+  `files` GUI.  `SYS_FS_STAT` exposes size/dir/read-only, and `sys_dirent`
+  carries a display name (64 bytes) plus `raw_83` so FAT's space-padded
+  fields and the name-string filesystems share one ABI.
 - **SATA/AHCI**: `ahci.c/h` — polled AHCI driver (first controller only, PCI
   class `01:06:01`, no IRQs, no NCQ): port bring-up with COMRESET, IDENTIFY
   (shared `ata_identify_parse()` with `ata.c`) and READ/WRITE DMA EXT through
@@ -301,7 +315,29 @@ below the run area), so adding code no longer moves any address.
   and can be plugged in at any time (root-port connect-change watcher);
   `lsusb` re-enumerates the bus, after which `usbhid` re-inits itself via a
   scan generation counter.
-- **Power/idle**: `idle.c` — `mwait` C-states, `hlt` fallback.
+- **Power/idle**: `idle.c` — HLT/C1 by default, `idle c2`/`idle c3`
+  (and the `c2ap`/`c3ap` AP-only variants) switch to MONITOR/MWAIT at runtime
+  (the old USB-legacy SMM hang is addressed by the UHCI/OHCI `0xC0`
+  legacy-SMI disable; test the keyboard before making it the default).  The
+  BSP PIT and each AP's LAPIC timer run at 1 kHz while a process runs and drop
+  to 100 Hz/10 ms while the CPU is idle (`timer_set_hz`,
+  `lapic_timer_set_ms`); the PIT stub advances the global millisecond clock by
+  `timer_tick_advance()`, and `smp_resched_wake()` shortens the idle period
+  when new work arrives.
+- **CPU temperature**: `thermal.c/h` — Intel DTS through `IA32_THERM_STATUS`
+  (MSR `0x19C`).  Each CPU samples itself once a second from its scheduler
+  tick (`struct cpu.temp_c`), and `SYS_CPU_TEMP` (`sys_info.c`) exposes the
+  hottest core plus TjMax to ring 3.  TjMax is table-driven (Atom 330 =
+  125 °C, 230 = 100, other Bonnell = 90, otherwise 100) because Bonnell has
+  no `IA32_TEMPERATURE_TARGET`.  The 330's 125 °C is Linux coretemp's
+  empirical value; Intel only specifies TJ = 90 °C and Tcase-max = 85.2 °C,
+  so `sensors` prints the raw delta and the 90/100/125 °C scales as well as
+  the top bar's `CPU 43C` before the clock and `cpuinfo`'s value plus EIST
+  state.  Platforms without DTS (QEMU, Pentium) hide it.
+- **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
+  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.
 - **User programs**: `run.c`, `run_api.h`, `prog.c`, `space.c` — raw binaries at
   `0x80000`, API function-pointer struct at `0x7FF00`.  `prog`/`space` are
   **embedded in the kernel image** (`prog_embed.o`/`space_embed.o`, like
@@ -371,13 +407,28 @@ below the run area), so adding code no longer moves any address.
   counter would never satisfy them.  The netdev ownership already serializes
   net users, so being preempted mid-wait is safe.
 
+  The server side is the WebDAV command: `tcp.c` has a small listener (one
+  active connection + a SYN backlog, SYN-ACK/RST, and a fast FIN that keeps
+  the tuple briefly so a late FIN/ACK is absorbed).  `SYS_TCP_LISTEN/ACCEPT/
+  SRV_RECV/SRV_SEND/SRV_CLOSE` are called by `/ramfs/bin/websrv`, which serves
+  HTTP/1.1 + WebDAV from the VFS (`/` lists mounts, `/ramfs` is read-only,
+  FAT mounts accept only names that round-trip to 8.3, `/share` is the
+  writable target).  While listening, `SYS_TCP_ACCEPT` also answers ARP/ICMP
+  and captures a KXNU/KXNP header through `netkexec_capture_frame()`, so
+  `make net-dev`/`make net-cmds` interrupts the server cleanly instead of
+  waiting for header retries.  The body is buffered whole (4 MB, or 1 MB when
+  the heap alloc fails) from the per-process arena; the TCP receive path sends
+  a window update whenever the application drains the queue (otherwise a full
+  receive queue deadlocks until the peer's zero-window probe).  No auth: it is
+  a trusted-LAN service, and `/share` is writable by anyone who can reach it.
+
 ## Shell commands
 
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `prog`,
-`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device>`,
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`, and `view <file>` (image viewer; PNG, baseline JPEG, GIF first frame, BMP, TGA, PNM).
+`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk),
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [hlt|c2|c3|c2ap|c3ap]`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`, and `view <file>` (image viewer; PNG, baseline JPEG, GIF first frame, BMP, TGA, PNM).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `pong` (responds to ARP/ICMP for our IP for 30 s),
@@ -407,9 +458,9 @@ nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `spin`,
-`clock`, `colors`, `files`, `view`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `files`, `view`, `sensors`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
-`netreset`, `curl` and `hello` are files in `/ramfs/bin` (packed by the
+`netreset`, `websrv`, `curl` and `hello` are files in `/ramfs/bin` (packed by the
 Makefile), found through the shell's PATH; the rest are kernel commands
 spawned as processes, or builtins (`cd`, `path`, `help`, `clear`).
 
@@ -789,7 +840,6 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     rely on not-present TLB entries not being cached; there is no cross-CPU
     TLB shootdown.  No process shares an address space with another, so normal
     process teardown is unaffected.
-
 15. Image library limits: progressive/arithmetic JPEG and CMYK are rejected;
     GIF shows only the first frame; EXIF orientation and ICC/gamma are ignored;
     the whole file is read into memory (4 MB cap in the viewer); decoding uses
@@ -801,3 +851,19 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     rescaling on every repaint.
 17. `files` recognises images by file extension only; a magic-based fallback
     would also open extensionless files in the viewer.
+
+18. WebDAV limits: one request at a time (a 2-deep SYN backlog only holds
+    handshakes), files are buffered whole (4 MB cap; a larger PUT gets 413),
+    directory `MOVE` is 501, `PROPPATCH` is answered 200 without persisting,
+    and there is no authentication.  TCP is stop-and-wait, so throughput is
+    roughly 0.5-4 MB/s depending on the link.
+19. FAT mounts are writable over WebDAV only for names that
+    `fat_name_to_8_3()` can represent exactly; anything longer is refused
+    with 409 instead of silently truncating (two long names could otherwise
+    collide and overwrite each other).  Use `/share` for long names.
+20. The WebDAV server and the packet-level net commands are mutually
+    exclusive: both need the single NIC receiver (`netdev_acquire`).  Starting
+    `websrv` while `ping`/`curl`/`netrecv` owns the NIC fails; kill the other
+    command first.
+21. `/share` is RAM only: a reboot/kexec starts empty, and the 16 MB cap is
+    charged against the 128 MB identity-mapped window.

+ 24 - 10
Makefile

@@ -29,7 +29,7 @@ screen.o: screen.c screen.h
 io.o: io.c io.h fbtext.h process.h screen.h tty.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-tty.o: tty.c tty.h process.h
+tty.o: tty.c tty.h mm.h netlog.h process.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 font_8x8.o: font_8x8.c font_8x8.h
@@ -95,6 +95,12 @@ blit.o: blit.c blit.h vga.h gfx.h cpu.h
 cpu.o: cpu.c cpu.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+thermal.o: thermal.c thermal.h cpu.h sched.h serial.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+it87.o: it87.c it87.h pci.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 gfxbench.o: gfxbench.c blit.h cpu.h fbtext.h gfx.h io.h mm.h timer.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -194,10 +200,10 @@ ahci.o: ahci.c ahci.h ata.h mm.h paging.h pci.h process.h serial.h timer.h
 fatdetect.o: fatdetect.c fatdetect.h fat.h blkdev.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
-fatformat.o: fatformat.c fatformat.h blkdev.h mm.h
+fatformat.o: fatformat.c fatformat.h blkdev.h io.h mm.h sched.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
-format.o: format.c blkdev.h disk.h fatformat.h io.h vga.h vfs.h
+format.o: format.c blkdev.h disk.h fatformat.h io.h process.h sched.h vga.h vfs.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
 mouse.o: mouse.c mouse.h cirrus.h radeon.h timer.h usbhid.h vga.h
@@ -233,7 +239,7 @@ switch.o: switch.S irqret.inc
 entry.o: entry.S
 	$(AS) $(ASFLAGS) -o $@ $<
 
-sched.o: sched.c sched.h process.h paging.h smp.h spinlock.h sys_fs.h timer.h tss.h vga.h
+sched.o: sched.c sched.h process.h paging.h smp.h spinlock.h sys_fs.h thermal.h timer.h tss.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 acpi.o: acpi.c acpi.h paging.h serial.h
@@ -287,7 +293,7 @@ sys_mem.o: sys_mem.c sys_mem.h mm.h paging.h process.h
 inflate.o: inflate.c inflate.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-sys_info.o: sys_info.c sys_info.h syscall.h ahci.h blkdev.h mm.h mouse.h usbhid.h vfs.h
+sys_info.o: sys_info.c sys_info.h syscall.h ahci.h blkdev.h it87.h mm.h mouse.h thermal.h usbhid.h vfs.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h process.h sched.h
@@ -296,7 +302,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h pr
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o prog_embed.o space_embed.o inflate.o cmds_pack.o ramfs.o payload.o
+kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o thermal.o it87.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o prog_embed.o space_embed.o inflate.o cmds_pack.o ramfs.o share.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -386,7 +392,7 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         ucmd_netinfo ucmd_netip ucmd_netdns ucmd_host ucmd_dhcp \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_curl \
-        ucmd_files ucmd_view
+        ucmd_files ucmd_view ucmd_sensors ucmd_mines ucmd_websrv
 
 # Keep the linked ELFs around (make would treat them as disposable
 # intermediates between the pattern rules).
@@ -436,6 +442,14 @@ ucmd_files.elf: ucmd_files.o ngui.o font_8x16.o ucmd.ld
 	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
+# mines is a second ngui canvas app; it links the same toolkit.
+ucmd_mines.o: ucmd_mines.c ucmd_lib.h syscall.h wm_abi.h ngui.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ucmd_mines.elf: ucmd_mines.o ngui.o font_8x16.o ucmd.ld
+	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
 # Image library: pure freestanding decoders + RGB565 compositing.  Only the
 # viewer links them today; a browser can link the same objects later.
 IMGLIB_OBJS = img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o \
@@ -605,8 +619,8 @@ run-uhci: floppy.img root.img
 # user-mode network (slirp).  DHCP/DNS come from slirp, the host is 10.0.2.2
 # (e.g. `python3 -m http.server` + `curl http://10.0.2.2:8000/` in a window).
 run-net: floppy.img root.img
-	qemu-system-i386 -M pc -device pci-ohci -device usb-mouse -device ne2k_pci,netdev=n0 -netdev user,id=n0 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
-	qemu-system-x86_64 -M pc -device pci-ohci -device usb-mouse -device ne2k_pci,netdev=n0 -netdev user,id=n0 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
+	qemu-system-i386 -M pc -device pci-ohci -device usb-mouse -device ne2k_pci,netdev=n0 -netdev user,id=n0,hostfwd=tcp::8080-:8080 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
+	qemu-system-x86_64 -M pc -device pci-ohci -device usb-mouse -device ne2k_pci,netdev=n0 -netdev user,id=n0,hostfwd=tcp::8080-:8080 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
 
 # SATA/AHCI variant: an ICH9 AHCI controller with a test disk on port 0.
 # The disk image lives outside the repo and is created on first use; boot
@@ -715,4 +729,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack_gz.bin cmds_pack.o ramfs.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_file.o img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o thermal.o it87.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack_gz.bin cmds_pack.o ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_file.o img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 3 - 3
cpu.c

@@ -5,7 +5,7 @@
 static int sse2 = -1;      /* -1 = not probed yet, 0 = no, 1 = yes */
 
 /* CPUID exists only if the ID bit in EFLAGS can be toggled (i586+). */
-static int cpuid_supported(void)
+int cpu_has_cpuid(void)
 {
 	unsigned int a, b;
 
@@ -20,7 +20,7 @@ void cpu_enable_sse(void)
 {
 	unsigned int eax, ebx, ecx, edx, cr4;
 
-	if (!cpuid_supported())
+	if (!cpu_has_cpuid())
 		return;
 	eax = 1;
 	__asm__ volatile ("cpuid"
@@ -39,7 +39,7 @@ int cpu_has_sse2(void)
 	if (sse2 >= 0)
 		return sse2;
 	sse2 = 0;
-	if (cpuid_supported()) {
+	if (cpu_has_cpuid()) {
 		eax = 1;
 		__asm__ volatile ("cpuid"
 				  : "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx));

+ 3 - 0
cpu.h

@@ -6,6 +6,9 @@
 #ifndef CPU_H
 #define CPU_H
 
+/* 1 when CPUID is available (has the ID bit in EFLAGS). */
+int cpu_has_cpuid(void);
+
 /* 1 when the CPU supports SSE2 (the ION does, the Pentium targets do not). */
 int cpu_has_sse2(void);
 

+ 80 - 29
idle.c

@@ -1,19 +1,19 @@
-/* CPU idle: HLT (C1) by default; optional MONITOR/MWAIT (C2).
+/* CPU idle: HLT (C1) by default; optional MONITOR/MWAIT C2/C3.
  *
- * NOTE: MWAIT is intentionally disabled.  On the ASUS AT3IONT-I (Atom 330 +
- * NVIDIA MCP79) a USB-legacy SMM event (the first key press) hangs the
- * machine when the CPU idles via MWAIT C2.  HLT is the path QEMU always used
- * (its default CPU has no MONITOR/MWAIT) and what every BIOS's legacy-USB
- * emulation expects, since DOS idles with HLT.
+ * MWAIT used to be left off entirely on the ASUS AT3IONT-I (Atom 330 +
+ * NVIDIA MCP79): a USB-legacy SMM event (the first key press) hung the
+ * machine in C2.  The UHCI/OHCI drivers now disable that legacy SMI
+ * emulation (PCI config 0xC0), so C2 is exposed through `idle c2` for a
+ * runtime test.  HLT stays the default until the board has been tested;
+ * `idle` with no argument shows the current mode.
  */
 #include "idle.h"
+#include "sched.h"
 
-#define IDLE_USE_MWAIT 0
-
-#if IDLE_USE_MWAIT
-static int has_mwait = 0;
-static int has_mwait_ext = 0;
-static unsigned int mwait_cstate_hint = 0x00;
+static int has_mwait;
+static int has_mwait_ext;
+static int current_mode = IDLE_C1;
+static unsigned int mwait_hint = 0x10;
 
 static void cpuid_idle(unsigned int leaf, unsigned int *eax, unsigned int *ebx,
 		       unsigned int *ecx, unsigned int *edx)
@@ -22,14 +22,16 @@ static void cpuid_idle(unsigned int leaf, unsigned int *eax, unsigned int *ebx,
 		: "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
 		: "a"(leaf), "c"(0));
 }
-#endif
 
 void idle_init(void)
 {
-#if IDLE_USE_MWAIT
 	unsigned int eax, ebx, ecx, edx;
 	unsigned int max_leaf;
 
+	has_mwait = 0;
+	has_mwait_ext = 0;
+	current_mode = IDLE_C1;
+
 	cpuid_idle(0, &max_leaf, &ebx, &ecx, &edx);
 	if (max_leaf < 1)
 		return;
@@ -41,28 +43,77 @@ void idle_init(void)
 		cpuid_idle(5, &eax, &ebx, &ecx, &edx);
 		has_mwait_ext = (ecx & 1u) ? 1 : 0;
 	}
+}
 
-	mwait_cstate_hint = 0x10;
-#endif
+int idle_set_mode(int mode)
+{
+	if (mode == IDLE_C1) {
+		current_mode = IDLE_C1;
+		return 0;
+	}
+	if (!has_mwait || !has_mwait_ext)
+		return -1;
+	if (mode == IDLE_C2) {
+		mwait_hint = 0x10;
+		current_mode = IDLE_C2;
+		return 0;
+	}
+	if (mode == IDLE_C3) {
+		mwait_hint = 0x20;
+		current_mode = IDLE_C3;
+		return 0;
+	}
+	if (mode == IDLE_C2_AP) {
+		mwait_hint = 0x10;
+		current_mode = IDLE_C2_AP;
+		return 0;
+	}
+	if (mode == IDLE_C3_AP) {
+		mwait_hint = 0x20;
+		current_mode = IDLE_C3_AP;
+		return 0;
+	}
+	return -1;
+}
+
+int idle_mode(void)
+{
+	return current_mode;
+}
+
+int idle_mwait_supported(void)
+{
+	return has_mwait && has_mwait_ext;
+}
+
+const char *idle_mode_name(int mode)
+{
+	switch (mode) {
+	case IDLE_C2:
+		return "mwait c2";
+	case IDLE_C3:
+		return "mwait c3";
+	case IDLE_C2_AP:
+		return "mwait c2 (APs)";
+	case IDLE_C3_AP:
+		return "mwait c3 (APs)";
+	default:
+		return "hlt";
+	}
 }
 
 void cpu_idle(void)
 {
-#if IDLE_USE_MWAIT
-	if (has_mwait && has_mwait_ext) {
+	int ap_only = (current_mode == IDLE_C2_AP ||
+		       current_mode == IDLE_C3_AP);
+
+	if (current_mode != IDLE_C1 && has_mwait && has_mwait_ext &&
+	    (!ap_only || this_cpu()->id != 0)) {
 		volatile unsigned int dummy = 0;
-		__asm__ volatile (
-			"monitor"
-			:
-			: "a"(&dummy), "c"(0), "d"(0)
-		);
-		__asm__ volatile (
-			"mwait"
-			:
-			: "a"(mwait_cstate_hint), "c"(1)
-		);
+
+		__asm__ volatile ("monitor" : : "a"(&dummy), "c"(0), "d"(0));
+		__asm__ volatile ("mwait" : : "a"(mwait_hint), "c"(1));
 		return;
 	}
-#endif
 	__asm__ volatile ("hlt");
 }

+ 13 - 1
idle.h

@@ -1,8 +1,20 @@
-/* CPU idle: deep C-state support via mwait when available. */
+/* CPU idle: HLT (C1) by default; optional MONITOR/MWAIT C2/C3. */
 #ifndef IDLE_H
 #define IDLE_H
 
+#define IDLE_C1 0
+#define IDLE_C2 1
+#define IDLE_C3 2
+#define IDLE_C2_AP 3
+#define IDLE_C3_AP 4
+
 void idle_init(void);
 void cpu_idle(void);
 
+/* Select a C-state; 0 on success, -1 when the CPU has no MWAIT. */
+int idle_set_mode(int mode);
+int idle_mode(void);
+int idle_mwait_supported(void);
+const char *idle_mode_name(int mode);
+
 #endif

+ 119 - 0
it87.c

@@ -0,0 +1,119 @@
+/* ITE IT87xx hardware monitor (read-only).
+ *
+ * The ASUS AT3IONT-I exposes CPU/MB temperatures and its three fan tach
+ * inputs through an IT87xx Super I/O.  This gives an independent cross-check
+ * for the CPU DTS (whose TjMax is not published for the Atom 330) and shows
+ * whether the CPU fan is actually turning.
+ *
+ * Only the standard config-space probe and the environment controller's
+ * read-only registers are touched; nothing is written to the fan control.
+ */
+#include "it87.h"
+#include "pci.h"   /* port_inb/port_outb */
+
+static unsigned short cfg_port;
+
+static unsigned char sio_inb(unsigned char reg)
+{
+	port_outb(cfg_port, reg);
+	return port_inb(cfg_port + 1);
+}
+
+static void sio_outb(unsigned char reg, unsigned char val)
+{
+	port_outb(cfg_port, reg);
+	port_outb(cfg_port + 1, val);
+}
+
+static void sio_enter(unsigned short port)
+{
+	cfg_port = port;
+	port_outb(cfg_port, 0x87);
+	port_outb(cfg_port, 0x01);
+	port_outb(cfg_port, 0x55);
+	port_outb(cfg_port, port == 0x4E ? 0xAA : 0x55);
+}
+
+static void sio_exit(void)
+{
+	port_outb(cfg_port, 0x02);
+	port_outb(cfg_port + 1, 0x02);
+}
+
+static int has_16bit_fans(unsigned int id)
+{
+	/* IT8705F/IT8712F use 8-bit tachometers; IT8716F and later have
+	 * 16-bit counters (low byte at 0x0D..0x0F, high at 0x18..0x1A). */
+	return id != 0x8705 && id != 0x8712;
+}
+
+void it87_read(struct it87_info *out)
+{
+	unsigned int i, base;
+	unsigned char div;
+
+	out->present = 0;
+	out->chip_id = 0;
+	out->base = 0;
+	out->temp_enable = 0;
+	out->temp_extra = 0;
+	for (i = 0; i < IT87_TEMP_COUNT; i++)
+		out->temp_c[i] = -128;
+	for (i = 0; i < IT87_FAN_COUNT; i++)
+		out->fan_rpm[i] = 0;
+
+	for (i = 0; i < 2; i++) {
+		unsigned short port = i ? 0x4E : 0x2E;
+		unsigned int id;
+
+		sio_enter(port);
+		id = ((unsigned int)sio_inb(0x20) << 8) | sio_inb(0x21);
+		if ((id & 0xFF00u) != 0x8700u) {
+			sio_exit();
+			continue;
+		}
+		/* Environment controller (logical device 4) base address. */
+		sio_outb(0x07, 0x04);
+		base = ((unsigned int)sio_inb(0x60) << 8) | sio_inb(0x61);
+		base &= ~7u;
+		if (sio_inb(0x30) != 0x01) {
+			sio_exit();
+			continue;
+		}
+		sio_exit();
+		if (base < 0x100 || base > 0xFFF0)
+			continue;
+		out->present = 1;
+		out->chip_id = id;
+		out->base = base;
+		break;
+	}
+	if (!out->present)
+		return;
+
+	for (i = 0; i < IT87_TEMP_COUNT; i++)
+		out->temp_c[i] =
+			(signed char)port_inb((unsigned short)(base + 0x29 + i));
+	out->temp_enable = port_inb((unsigned short)(base + 0x51));
+	out->temp_extra = port_inb((unsigned short)(base + 0x55));
+
+	div = port_inb((unsigned short)(base + 0x0B));
+	for (i = 0; i < IT87_FAN_COUNT; i++) {
+		unsigned int count, d;
+
+		count = port_inb((unsigned short)(base + 0x0D + i));
+		if (has_16bit_fans(out->chip_id)) {
+			count |= (unsigned int)port_inb((unsigned short)(base + 0x18 + i)) << 8;
+			if (count == 0 || count == 0xFFFF)
+				out->fan_rpm[i] = 0;
+			else
+				out->fan_rpm[i] = 1350000u / (count * 2);
+			continue;
+		}
+		d = 1u << ((div >> (2 + i * 2)) & 3u);
+		if (count == 0 || count >= 0xFF)
+			out->fan_rpm[i] = 0;
+		else
+			out->fan_rpm[i] = 1350000u / (count * d);
+	}
+}

+ 20 - 0
it87.h

@@ -0,0 +1,20 @@
+/* Read-only ITE IT87xx Super I/O hardware monitor (AT3IONT-I). */
+#ifndef IT87_H
+#define IT87_H
+
+#define IT87_TEMP_COUNT 3
+#define IT87_FAN_COUNT  3
+
+struct it87_info {
+	int present;
+	unsigned int chip_id;
+	unsigned int base;
+	unsigned int temp_enable;
+	unsigned int temp_extra;
+	int temp_c[IT87_TEMP_COUNT];
+	unsigned int fan_rpm[IT87_FAN_COUNT];
+};
+
+void it87_read(struct it87_info *out);
+
+#endif

+ 37 - 3
kernel.c

@@ -16,6 +16,7 @@
 #include "process.h"
 #include "ramfs.h"
 #include "sys_gfx.h"
+#include "thermal.h"
 #include "timer.h"
 #include "tss.h"
 #include "usbhid.h"
@@ -32,6 +33,8 @@ static inline void outb(unsigned short port, unsigned char v)
 }
 
 volatile unsigned int ticks;
+static unsigned int timer_hz;
+static unsigned int tick_ms = 1;
 
 struct idt_entry {
 	unsigned short offset_lo;
@@ -65,6 +68,36 @@ unsigned int get_ticks_ms(void)
 	return ticks;
 }
 
+unsigned int timer_tick_ms(void)
+{
+	return tick_ms;
+}
+
+void timer_tick_advance(void)
+{
+	ticks += tick_ms;
+}
+
+void timer_set_hz(unsigned int hz)
+{
+	unsigned int flags, divisor;
+
+	if (hz < 100 || hz > 1000)
+		hz = 1000;
+	if (hz == timer_hz)
+		return;
+	__asm__ volatile ("pushfl; popl %0" : "=r"(flags));
+	__asm__ volatile ("cli" ::: "memory");
+	timer_hz = hz;
+	tick_ms = 1000 / hz;
+	divisor = 1193182u / hz;
+	outb(0x43, 0x36);
+	outb(0x40, (unsigned char)(divisor & 0xFF));
+	outb(0x40, (unsigned char)((divisor >> 8) & 0xFF));
+	if (flags & (1u << 9))
+		__asm__ volatile ("sti" ::: "memory");
+}
+
 void exc_handler(struct exc_state *st);
 void exc_handler(struct exc_state *st)
 {
@@ -169,9 +202,9 @@ static void timer_init(void)
 	idtr.base  = (unsigned int)idt;
 	__asm__ volatile ("lidt %0" : : "m"(idtr));
 
-	outb(0x43, 0x36);
-	outb(0x40, (unsigned char)(1193 & 0xFF));
-	outb(0x40, (unsigned char)((1193 >> 8) & 0xFF));
+	/* Start the PIT at 1 kHz; schedule() drops it to 100 Hz while the BSP
+	 * is idle (see timer_set_hz). */
+	timer_set_hz(1000);
 
 	__asm__ volatile ("sti");
 }
@@ -263,6 +296,7 @@ void kernel_main(void)
 	acpi_dump();
 	io_init();
 	idle_init();
+	thermal_init();
 
 	/* process_init must run before timer_init: once the PIT is started (sti
 	 * in timer_init) the context-switch stub runs on every tick and reads

+ 15 - 0
lapic.c

@@ -20,6 +20,7 @@
 
 static volatile unsigned int *lapic_mmio;
 static unsigned int lapic_phys;
+static unsigned int lapic_per_ms;
 
 static inline unsigned int lapic_read(unsigned int off)
 {
@@ -173,10 +174,24 @@ int lapic_timer_start(unsigned int vector)
 		return 0;
 
 	lapic_write(LAPIC_LVT_TIMER, (vector & 0xFFu) | 0x00020000u);
+	lapic_per_ms = per_ms;
 	lapic_write(LAPIC_TIMER_INIT, per_ms);
 	return 1;
 }
 
+void lapic_timer_set_ms(unsigned int ms)
+{
+	unsigned int init;
+
+	if (!lapic_mmio || !lapic_per_ms)
+		return;
+	if (ms == 0)
+		ms = 1;
+	init = lapic_per_ms * ms;
+	if (init)
+		lapic_write(LAPIC_TIMER_INIT, init);
+}
+
 void lapic_timer_stop(void)
 {
 	if (lapic_mmio)

+ 1 - 0
lapic.h

@@ -20,5 +20,6 @@ void lapic_send_sipi(unsigned int apic_id, unsigned int vector);
 
 int  lapic_timer_start(unsigned int vector);
 void lapic_timer_stop(void);
+void lapic_timer_set_ms(unsigned int ms);
 
 #endif

+ 39 - 24
netkexec.c

@@ -141,12 +141,12 @@ static int parse_udp(const unsigned char *f, unsigned int len,
 int netkexec_pending(void)
 {
 	const struct netdev *nd;
-	const unsigned char *payload;
-	unsigned int plen, port;
 	int len;
 
 	if (kexec_busy || netdev_in_use())
 		return 0;
+	if (have_header)
+		return 1;
 	nd = netdev_active();
 	if (!nd)
 		return 0;
@@ -157,39 +157,54 @@ int netkexec_pending(void)
 	if (len < 0)
 		return 0;
 
-	if (!parse_udp(rxbuf, (unsigned int)len, &payload, &plen,
-		       peer_mac, peer_ip, &port)) {
-		/* Not a kexec datagram: stay reachable by answering ARP and ICMP
-		 * echo requests for our IP (so the board can be pinged, and a
-		 * host can resolve its MAC, without running a command).  Until
-		 * an address is configured there is nothing to answer for. */
-		int rlen;
-
-		if (!net_is_configured())
-			return 0;
-		rlen = net_build_reply(rxbuf, (unsigned int)len,
-				       replybuf, sizeof(replybuf));
+	if (netkexec_capture_frame(rxbuf, (unsigned int)len))
+		return 1;
+
+	/* Not a kexec datagram: stay reachable by answering ARP and ICMP echo
+	 * requests for our IP (so the board can be pinged, and a host can
+	 * resolve its MAC, without running a command).  Until an address is
+	 * configured there is nothing to answer for. */
+	if (net_is_configured()) {
+		int rlen = net_build_reply(rxbuf, (unsigned int)len,
+					   replybuf, sizeof(replybuf));
 		if (rlen > 0)
 			nd->tx(replybuf, (unsigned int)rlen);
-		return 0;
 	}
+	return 0;
+}
+
+/* Validate one received frame as a KXNU/KXNP header and stash the transfer.
+ * Returns 1 when it was captured.  The WebDAV server calls this while it
+ * owns the receiver, so `make net-dev` hands the NIC back without waiting
+ * for the host's header retransmits. */
+int netkexec_capture_frame(const unsigned char *frame, unsigned int len)
+{
+	const unsigned char *payload;
+	unsigned int plen, port, magic, i;
+	unsigned char p_mac[6], p_ip[4];
+
+	if (have_header)
+		return 0;
+	if (!parse_udp(frame, len, &payload, &plen, p_mac, p_ip, &port))
+		return 0;
 	if (plen < 16)
 		return 0;
-	{
-		/* KXNU: kernel image (jump after the checksum); KXNP: a command
-		 * pack for /ramfs (swap it in and stay running). */
-		unsigned int magic = rd32(payload);
-
-		if (magic != X_MAGIC_HDR && magic != X_MAGIC_PAY)
-			return 0;
-		payload_mode = (magic == X_MAGIC_PAY);
-	}
+
+	magic = rd32(payload);
+	if (magic != X_MAGIC_HDR && magic != X_MAGIC_PAY)
+		return 0;
+
 	x_entry = rd32(payload + 4);
 	x_size = rd32(payload + 8);
 	x_csum = rd32(payload + 12);
 	if (x_size == 0 || x_size > KEXEC_MAX)
 		return 0;
 
+	payload_mode = (magic == X_MAGIC_PAY);
+	for (i = 0; i < 6; i++)
+		peer_mac[i] = p_mac[i];
+	for (i = 0; i < 4; i++)
+		peer_ip[i] = p_ip[i];
 	peer_port = port;
 	have_header = 1;
 	return 1;

+ 5 - 0
netkexec.h

@@ -8,6 +8,11 @@
  * stays reachable without running a command. */
 int netkexec_pending(void);
 
+/* Feed one frame received by another poller (the WebDAV server).  Returns 1
+ * when it was a KXNU/KXNP header; netkexec_pending() then reports it without
+ * polling the NIC again. */
+int netkexec_capture_frame(const unsigned char *frame, unsigned int len);
+
 /* Process entry: receive the pending image into the kexec staging buffer,
  * verify it and jump.  Never returns on success. */
 void program_netkexec_main(void);

+ 37 - 7
sched.c

@@ -15,11 +15,13 @@
 
 #include "sched.h"
 #include "io.h"
+#include "lapic.h"
 #include "paging.h"
 #include "process.h"
 #include "smp.h"
 #include "spinlock.h"
 #include "syscall.h"
+#include "thermal.h"
 #include "timer.h"
 #include "tss.h"
 
@@ -75,7 +77,7 @@ _Static_assert(__builtin_offsetof(struct cpu, current) == 0,
 _Static_assert(__builtin_offsetof(struct process, esp) == 0,
 	       "switch.S saves the interrupted esp at offset 0");
 _Static_assert(__builtin_offsetof(struct cpu, need_resched) == 24,
-	       "switch.S sets need_resched at offset 24");
+	       "smp_resched_wake expects need_resched at offset 24");
 
 static inline unsigned long long weight_stride(unsigned int weight)
 {
@@ -238,8 +240,12 @@ static void wake_locked(struct process *p)
 	runq_add_locked(p);
 	wakeups++;
 	if (cur && (p->affinity & (1u << c->id)) &&
-	    (cur == c->idle || p->weight >= cur->weight))
+	    (cur == c->idle || p->weight >= cur->weight)) {
 		c->need_resched = 1;
+		/* The idle timer period is 10 ms; shorten it so the woken
+		 * process runs at the next millisecond instead. */
+		smp_resched_wake();
+	}
 }
 
 void sched_add_ready(struct process *p)
@@ -531,6 +537,9 @@ void sched_init(void)
 		cpus[i].switches = 0;
 		cpus[i].pending_zombie = 0;
 		cpus[i].deferred_unlock = 0;
+		cpus[i].temp_div = 0;
+		cpus[i].temp_c = -1;
+		cpus[i].tick_ms = 1;
 	}
 }
 
@@ -635,6 +644,18 @@ void schedule(void)
 	next->slice_start = get_ticks_ms();
 	c->current = next;
 	c->need_resched = 0;
+	/* The BSP PIT and each AP's LAPIC timer tick at 1 kHz while a process
+	 * runs; while a CPU is idle they drop to 100 Hz so MWAIT can hold C2
+	 * for 10 ms.  The global millisecond clock stays accurate because the
+	 * PIT stub adds tick_ms (see timer_tick_advance). */
+	if (c->id == 0) {
+		timer_set_hz(next == c->idle ? 100 : 1000);
+	} else {
+		unsigned int ms = (next == c->idle) ? 10 : 1;
+
+		c->tick_ms = ms;
+		lapic_timer_set_ms(ms);
+	}
 	sched_switch_to(next);
 	/* Keep the lock across the stack switch performed by switch.S; the
 	 * old process must not become runnable on another CPU while this CPU
@@ -688,12 +709,13 @@ void sched_sleep_ms(unsigned int ms)
  * assembly should call schedule(). */
 /* Common tail of the tick path: with the scheduler lock held, decide whether
  * the assembly stub should call schedule(). */
-static int tick_decide_locked(struct cpu *c, struct process *p, int ap)
+static int tick_decide_locked(struct cpu *c, struct process *p, int ap,
+			      unsigned int ms)
 {
 	if (p) {
-		p->cpu_ticks++;
+		p->cpu_ticks += ms;
 		if (p == c->idle)
-			c->idle_ticks++;
+			c->idle_ticks += ms;
 	}
 	/* A process inside the kernel holding the big lock must not be
 	 * preempted: the lock is not preemptible, and its owner may be in the
@@ -740,9 +762,10 @@ int sched_tick_bsp(void)
 	unsigned int flags = sched_lock_acquire();
 	int r;
 
+	thermal_tick();
 	p = c->current;
 	wake_sleepers_locked();
-	r = tick_decide_locked(c, p, 0);
+	r = tick_decide_locked(c, p, 0, timer_tick_ms());
 	sched_lock_release(flags);
 	return r;
 }
@@ -756,8 +779,15 @@ int sched_tick_ap(void)
 	unsigned int flags = sched_lock_acquire();
 	int r;
 
+	thermal_tick();
 	p = c->current;
-	r = tick_decide_locked(c, p, 1);
+	r = tick_decide_locked(c, p, 1, c->tick_ms);
+	if (!r && p == c->idle && c->tick_ms != 10) {
+		/* Entered idle without a schedule(): stretch this CPU's LAPIC
+		 * period so MWAIT can hold C2 for 10 ms. */
+		c->tick_ms = 10;
+		lapic_timer_set_ms(10);
+	}
 	sched_lock_release(flags);
 	return r;
 }

+ 7 - 0
sched.h

@@ -43,6 +43,13 @@ struct cpu {
 	 * on its kernel stack. */
 	unsigned int    deferred_unlock;
 	unsigned int    sched_flags;
+	/* Last DTS reading published by this CPU's tick, and the millisecond
+	 * divider that limits sampling to once per second (see thermal.c). */
+	unsigned int    temp_div;
+	int             temp_c;
+	/* This CPU's timer period: 1 ms while a process runs, 10 ms while
+	 * idle (see schedule()/sched_tick_ap). */
+	unsigned int    tick_ms;
 };
 
 extern struct cpu cpus[MAX_CPUS];

+ 461 - 0
share.c

@@ -0,0 +1,461 @@
+/* /share: a small writable in-memory filesystem.
+ *
+ * Files live in whole pages from the frame allocator (identity mapped, so a
+ * borrowed pointer works), and the directory namespace is the full relative
+ * path of every entry, like the pack ramfs.  That keeps mkdir/list/rmdir
+ * simple without an inode tree.  A directory exists as an entry of its own,
+ * so empty directories survive.  Everything is volatile.
+ */
+
+#include "vfs.h"
+#include "share.h"
+#include "kmalloc.h"
+#include "mm.h"
+
+struct share_ent {
+	char path[SHARE_PATH_MAX];
+	unsigned int base;     /* first page, 0 when the file is empty */
+	unsigned int size;
+	unsigned int is_dir;
+};
+
+static struct share_ent *ents;
+static unsigned int ent_count;
+static unsigned int used_bytes;
+
+static int s_eq(const char *a, const char *b)
+{
+	unsigned int i = 0;
+
+	while (a[i] && b[i] && a[i] == b[i])
+		i++;
+	return a[i] == '\0' && b[i] == '\0';
+}
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s[n])
+		n++;
+	return n;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	while (i + 1 < cap && s[i]) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static void mem_copy(void *d, const void *s, unsigned int n)
+{
+	unsigned char *dd = d;
+	const unsigned char *ss = s;
+
+	while (n--)
+		*dd++ = *ss++;
+}
+
+/* A relative path: components separated by '/', no leading/trailing slash,
+ * no "." or "..", no control characters, total length < SHARE_PATH_MAX. */
+static int path_ok(const char *path)
+{
+	unsigned int i = 0, comp = 0;
+
+	if (!path || !path[0])
+		return 0;
+	while (path[i]) {
+		char c = path[i];
+
+		if (c == '/') {
+			if (comp == 0)
+				return 0;
+			if (comp == 1 && path[i - 1] == '.')
+				return 0;
+			if (comp == 2 && path[i - 1] == '.' &&
+			    path[i - 2] == '.')
+				return 0;
+			comp = 0;
+		} else {
+			if ((unsigned char)c < 0x20)
+				return 0;
+			if (++comp > SHARE_PATH_MAX - 2)
+				return 0;
+		}
+		if (++i >= SHARE_PATH_MAX)
+			return 0;
+	}
+	if (comp == 0)
+		return 0;
+	if (comp == 1 && path[i - 1] == '.')
+		return 0;
+	if (comp == 2 && path[i - 1] == '.' && path[i - 2] == '.')
+		return 0;
+	return 1;
+}
+
+static void parent_of(const char *path, char *parent)
+{
+	int i = (int)s_len(path) - 1;
+
+	while (i >= 0 && path[i] != '/')
+		i--;
+	if (i < 0) {
+		parent[0] = '\0';
+		return;
+	}
+	s_copy(parent, path, (unsigned int)i + 1);
+	parent[i] = '\0';
+}
+
+static int lookup(const char *path)
+{
+	unsigned int i;
+
+	for (i = 0; i < ent_count; i++)
+		if (s_eq(ents[i].path, path))
+			return (int)i;
+	return -1;
+}
+
+static void free_data(unsigned int base, unsigned int size)
+{
+	unsigned int pages = (size + 0xFFFu) >> 12;
+	unsigned int i;
+
+	if (!base)
+		return;
+	for (i = 0; i < pages; i++)
+		mm_free_page(base + i * 0x1000);
+}
+
+static void remove_ent(unsigned int idx)
+{
+	free_data(ents[idx].base, ents[idx].size);
+	used_bytes -= ents[idx].size;
+	ent_count--;
+	if (idx != ent_count)
+		ents[idx] = ents[ent_count];
+}
+
+/* Full path of the child of `dir` containing `p`, into `name`.  Returns 0
+ * when the entry is not directly inside `dir`. */
+static int child_name(const char *p, const char *dir, char *name,
+		      unsigned int cap)
+{
+	unsigned int dl = s_len(dir), n = 0, i;
+	const char *rest;
+
+	if (dl) {
+		for (i = 0; i < dl; i++)
+			if (p[i] != dir[i])
+				return 0;
+		if (p[dl] != '/')
+			return 0;
+		rest = p + dl + 1;
+	} else {
+		rest = p;
+	}
+	if (!rest[0])
+		return 0;
+	while (rest[n] && rest[n] != '/')
+		n++;
+	if (n >= cap)
+		return 0;
+	mem_copy(name, rest, n);
+	name[n] = '\0';
+	return 1;
+}
+
+/* ---- fs_ops ---- */
+
+static int share_op_read_file(struct vfs_mount *m, const char *path,
+			      void *buf, unsigned int max)
+{
+	int idx;
+
+	(void)m;
+	idx = lookup(path);
+	if (idx < 0)
+		return VFS_ENOENT;
+	if (ents[idx].is_dir)
+		return VFS_EINVAL;
+	if (ents[idx].size > max)
+		return (int)max;
+	mem_copy(buf, (const void *)ents[idx].base, ents[idx].size);
+	return (int)ents[idx].size;
+}
+
+static int share_op_load_file(struct vfs_mount *m, const char *path,
+			      struct vfs_file *out)
+{
+	int idx;
+
+	(void)m;
+	idx = lookup(path);
+	if (idx < 0)
+		return VFS_ENOENT;
+	if (ents[idx].is_dir)
+		return VFS_EINVAL;
+	out->data = (const void *)ents[idx].base;
+	out->size = ents[idx].size;
+	return 0;
+}
+
+static void share_op_release_file(struct vfs_mount *m, struct vfs_file *f)
+{
+	(void)m;
+	(void)f;
+}
+
+static int share_op_stat(struct vfs_mount *m, const char *path,
+			 unsigned int *size, int *is_dir)
+{
+	int idx;
+
+	(void)m;
+	if (path[0] == '\0') {
+		if (size)
+			*size = 0;
+		if (is_dir)
+			*is_dir = 1;
+		return 0;
+	}
+	idx = lookup(path);
+	if (idx < 0)
+		return VFS_ENOENT;
+	if (size)
+		*size = ents[idx].is_dir ? 0 : ents[idx].size;
+	if (is_dir)
+		*is_dir = (int)ents[idx].is_dir;
+	return 0;
+}
+
+static int share_op_write_file(struct vfs_mount *m, const char *path,
+			       const void *buf, unsigned int len)
+{
+	char parent[SHARE_PATH_MAX];
+	unsigned int base = 0, old_size = 0;
+	int idx, pidx;
+
+	(void)m;
+	if (!path_ok(path))
+		return VFS_EINVAL;
+
+	idx = lookup(path);
+	if (idx >= 0 && ents[idx].is_dir)
+		return VFS_EINVAL;
+
+	parent_of(path, parent);
+	if (parent[0]) {
+		pidx = lookup(parent);
+		if (pidx < 0 || !ents[pidx].is_dir)
+			return VFS_EINVAL;
+	}
+
+	if (idx >= 0)
+		old_size = ents[idx].size;
+	if (used_bytes - old_size + len > SHARE_MAX_BYTES)
+		return VFS_ENOSPC;
+
+	if (len) {
+		unsigned int pages = (len + 0xFFFu) >> 12;
+
+		base = mm_alloc_pages(pages);
+		if (!base)
+			return VFS_ENOSPC;
+		mem_copy((void *)base, buf, len);
+	}
+
+	if (idx < 0) {
+		if (ent_count >= SHARE_MAX_ENTRIES) {
+			free_data(base, len);
+			return VFS_ENOSPC;
+		}
+		idx = (int)ent_count++;
+		s_copy(ents[idx].path, path, sizeof(ents[idx].path));
+		ents[idx].base = 0;
+		ents[idx].size = 0;
+		ents[idx].is_dir = 0;
+	}
+
+	free_data(ents[idx].base, ents[idx].size);
+	used_bytes -= ents[idx].size;
+	ents[idx].base = base;
+	ents[idx].size = len;
+	ents[idx].is_dir = 0;
+	used_bytes += len;
+	return 0;
+}
+
+static int share_op_unlink(struct vfs_mount *m, const char *path)
+{
+	int idx = lookup(path);
+
+	(void)m;
+	if (idx < 0)
+		return VFS_ENOENT;
+	if (ents[idx].is_dir)
+		return VFS_EINVAL;
+	remove_ent((unsigned int)idx);
+	return 0;
+}
+
+static int share_op_mkdir(struct vfs_mount *m, const char *path)
+{
+	char parent[SHARE_PATH_MAX];
+	unsigned int i;
+	int pidx;
+
+	(void)m;
+	if (!path_ok(path) || lookup(path) >= 0)
+		return VFS_EINVAL;
+
+	parent_of(path, parent);
+	if (parent[0]) {
+		pidx = lookup(parent);
+		if (pidx < 0 || !ents[pidx].is_dir)
+			return VFS_EINVAL;
+	}
+
+	/* Do not create a directory whose path is already a file prefix. */
+	for (i = 0; i < ent_count; i++) {
+		unsigned int pl = s_len(path);
+
+		if (s_len(ents[i].path) > pl &&
+		    ents[i].path[pl] == '/') {
+			unsigned int j;
+
+			for (j = 0; j < pl && ents[i].path[j] == path[j]; j++)
+				;
+			if (j == pl)
+				return VFS_EINVAL;
+		}
+	}
+
+	if (ent_count >= SHARE_MAX_ENTRIES)
+		return VFS_ENOSPC;
+	i = ent_count++;
+	s_copy(ents[i].path, path, sizeof(ents[i].path));
+	ents[i].base = 0;
+	ents[i].size = 0;
+	ents[i].is_dir = 1;
+	return 0;
+}
+
+static int share_op_rmdir(struct vfs_mount *m, const char *path)
+{
+	unsigned int i, pl;
+	int idx = lookup(path);
+
+	(void)m;
+	if (idx < 0)
+		return VFS_ENOENT;
+	if (!ents[idx].is_dir)
+		return VFS_EINVAL;
+
+	pl = s_len(path);
+	for (i = 0; i < ent_count; i++) {
+		unsigned int j;
+
+		if (s_len(ents[i].path) <= pl || ents[i].path[pl] != '/')
+			continue;
+		for (j = 0; j < pl && ents[i].path[j] == path[j]; j++)
+			;
+		if (j == pl)
+			return VFS_EINVAL;      /* not empty */
+	}
+	remove_ent((unsigned int)idx);
+	return 0;
+}
+
+static int share_op_list_dir(struct vfs_mount *m, const char *path,
+			     unsigned int index, struct vfs_dirent *out)
+{
+	char name[SHARE_PATH_MAX], seen_name[SHARE_PATH_MAX];
+	unsigned int i, seen = 0;
+	int idx;
+
+	(void)m;
+	if (path[0]) {
+		idx = lookup(path);
+		if (idx < 0)
+			return VFS_ENOENT;
+		if (!ents[idx].is_dir)
+			return VFS_EINVAL;
+	}
+
+	for (i = 0; i < ent_count; i++) {
+		unsigned int j;
+		int dup = 0, exact;
+		char full[SHARE_PATH_MAX];
+
+		if (!child_name(ents[i].path, path, name, sizeof(name)))
+			continue;
+		for (j = 0; j < i; j++) {
+			if (child_name(ents[j].path, path, seen_name,
+				       sizeof(seen_name)) &&
+			    s_eq(seen_name, name)) {
+				dup = 1;
+				break;
+			}
+		}
+		if (dup)
+			continue;
+		if (seen++ != index)
+			continue;
+
+		/* The child is a directory when its own entry says so. */
+		if (path[0]) {
+			unsigned int k = 0;
+
+			for (; path[k] && k + 1 < sizeof(full); k++)
+				full[k] = path[k];
+			if (k + 1 < sizeof(full))
+				full[k++] = '/';
+			for (j = 0; name[j] && k + 1 < sizeof(full); j++)
+				full[k++] = name[j];
+			full[k] = '\0';
+		} else {
+			s_copy(full, name, sizeof(full));
+		}
+		exact = lookup(full);
+		s_copy(out->name, name, sizeof(out->name));
+		out->size = (exact >= 0 && !ents[exact].is_dir) ?
+			    ents[exact].size : 0;
+		out->is_dir = (exact >= 0 && ents[exact].is_dir) ? 1 : 0;
+		out->raw_83 = 0;
+		return 1;
+	}
+	return 0;
+}
+
+const struct fs_ops share_ops = {
+	.raw_83 = 0,
+	.read_file = share_op_read_file,
+	.load_file = share_op_load_file,
+	.release_file = share_op_release_file,
+	.stat = share_op_stat,
+	.write_file = share_op_write_file,
+	.unlink = share_op_unlink,
+	.mkdir = share_op_mkdir,
+	.rmdir = share_op_rmdir,
+	.list_dir = share_op_list_dir,
+};
+
+int share_init(void)
+{
+	if (ents)
+		return 0;
+	ents = kmalloc(sizeof(*ents) * SHARE_MAX_ENTRIES);
+	if (!ents)
+		return -1;
+	ent_count = 0;
+	used_bytes = 0;
+	return 0;
+}

+ 22 - 0
share.h

@@ -0,0 +1,22 @@
+/* /share: writable, page-backed in-memory filesystem (see share.c).
+ *
+ * The board is usually netbooted without a writable disk, so the WebDAV
+ * server needs somewhere to put uploads.  Names are plain strings (not 8.3)
+ * and may contain spaces; everything is volatile (a reboot/kexec starts
+ * empty).  The VFS mounts it at /share. */
+#ifndef SHARE_H
+#define SHARE_H
+
+struct fs_ops;
+
+#define SHARE_PATH_MAX     64
+#define SHARE_MAX_ENTRIES  64
+#define SHARE_MAX_BYTES    (16u * 1024u * 1024u)
+
+/* Allocate the entry table.  Idempotent; 0 when ready, -1 when out of
+ * memory.  Files added before a second call are preserved. */
+int share_init(void);
+
+extern const struct fs_ops share_ops;
+
+#endif

+ 17 - 1
smp.c

@@ -180,12 +180,28 @@ void smp_ap_main(unsigned int cpu)
 		cpu_idle();
 }
 
+/* Called from the reschedule IPI stub (and from smp_resched_cpu when the
+ * target is the current CPU): mark the CPU and shorten its idle timer so the
+ * next tick schedules promptly even when the PIT/LAPIC period is 10 ms. */
+void smp_resched_wake(void)
+{
+	struct cpu *c = this_cpu();
+
+	c->need_resched = 1;
+	if (c->id == 0) {
+		timer_set_hz(1000);
+	} else {
+		c->tick_ms = 1;
+		lapic_timer_set_ms(1);
+	}
+}
+
 void smp_resched_cpu(unsigned int cpu)
 {
 	if (cpu >= cpu_count || cpu >= MAX_CPUS)
 		return;
 	if (cpu == this_cpu()->id) {
-		cpus[cpu].need_resched = 1;
+		smp_resched_wake();
 		return;
 	}
 	if (cpus[cpu].lapic_id == 0xFFFFFFFFu)

+ 1 - 0
smp.h

@@ -13,6 +13,7 @@ void smp_ap_main(unsigned int cpu);
 
 /* Ask another CPU to run its scheduler soon (LAPIC IPI). */
 void smp_resched_cpu(unsigned int cpu);
+void smp_resched_wake(void);
 
 /* Park APs before kexec overwrites the kernel image. */
 void smp_stop_aps(void);

+ 7 - 5
switch.S

@@ -17,13 +17,14 @@
 .code32
 .text
 
-.extern ticks
+.extern timer_tick_advance
 .extern schedule
 .extern sched_tick_bsp
 .extern sched_tick_ap
 .extern sched_finish_switch
 .extern serial_poll
 .extern lapic_eoi
+.extern smp_resched_wake
 
 .include "irqret.inc"
 
@@ -41,8 +42,10 @@ pit_irq_stub:
 	movw  $0x28, %ax
 	movw  %ax, %gs
 
-	/* ticks++ and send EOI -- always, even when we don't switch. */
-	incl  ticks
+	/* Advance the millisecond clock and send EOI -- always, even when we
+	 * don't switch.  The PIT period is 1 ms while the BSP runs a process
+	 * and 10 ms while it is idle (timer_tick_advance adds the period). */
+	call  timer_tick_advance
 	movb  $0x20, %al
 	outb  %al, $0x20
 
@@ -125,8 +128,7 @@ lapic_resched_stub:
 	movw  $0x28, %ax
 	movw  %ax, %gs
 
-	movl  %gs:0, %eax
-	movl  $1, 24(%eax)          /* struct cpu.need_resched */
+	call  smp_resched_wake
 
 	call  lapic_eoi
 	IRQ_RETURN_DS 36

+ 35 - 0
sys_fs.c

@@ -45,6 +45,7 @@ static int sys_err(int vfs_err)
 	case VFS_EIO:    return SYS_EIO;
 	case VFS_ENOENT: return SYS_ENOENT;
 	case VFS_EROFS:  return SYS_EROFS;
+	case VFS_ENOSPC: return SYS_ENOSPC;
 	default:         return SYS_EINVAL;
 	}
 }
@@ -177,6 +178,7 @@ int sys_list_dir(const char *path, unsigned int index, struct sys_dirent *out)
 			out->name[i] = '\0';
 			out->size = d.size;
 			out->is_dir = d.is_dir;
+			out->raw_83 = d.raw_83;
 			r = 1;
 		} else if (r < 0) {
 			r = sys_err(r);
@@ -207,5 +209,38 @@ int sys_list_mounts(unsigned int index, struct sys_mount *out)
 	copy_bounded(out->type, vfs_mounts[index].type, sizeof(out->type));
 	out->total_sectors = vfs_mounts[index].total_sectors;
 	copy_bounded(out->label, vfs_mounts[index].label, sizeof(out->label));
+	out->ro = (unsigned int)vfs_mounts[index].ro;
 	return 1;
 }
+
+/* Stat a path.  Unlike read_file this never touches the disk beyond the FAT
+ * directory walk, so the WebDAV server can probe a collection cheaply. */
+int sys_stat_path(const char *path, struct sys_stat *out)
+{
+	struct vfs_mount *m;
+	char rel[VFS_PATH_MAX];
+	unsigned int size = 0, ro = 0;
+	int is_dir = 0, r;
+
+	if (!out)
+		return SYS_EINVAL;
+	size = 0;
+	is_dir = 0;
+	ro = 0;
+	sys_fs_enter();
+	r = fs_resolve(path, &m, rel, sizeof(rel));
+	if (r == 0) {
+		r = m->ops->stat(m, rel, &size, &is_dir);
+		if (r < 0) {
+			r = sys_err(r);
+		} else {
+			ro = (unsigned int)m->ro;
+			out->size = size;
+			out->is_dir = (unsigned int)is_dir;
+			out->ro = ro;
+			r = 0;
+		}
+	}
+	sys_fs_exit();
+	return r;
+}

+ 1 - 0
sys_fs.h

@@ -16,5 +16,6 @@ int sys_mkdir(const char *path);
 int sys_rmdir(const char *path);
 int sys_list_dir(const char *path, unsigned int index, struct sys_dirent *out);
 int sys_list_mounts(unsigned int index, struct sys_mount *out);
+int sys_stat_path(const char *path, struct sys_stat *out);
 
 #endif

+ 43 - 0
sys_info.c

@@ -5,9 +5,12 @@
 #include "syscall.h"
 #include "ahci.h"
 #include "blkdev.h"
+#include "it87.h"
 #include "mm.h"
 #include "mouse.h"
+#include "sched.h"
 #include "sys_fs.h"
+#include "thermal.h"
 #include "usb.h"
 #include "usbhid.h"
 #include "vfs.h"
@@ -103,3 +106,43 @@ int sys_blkdev(unsigned int index, struct sys_blkdev *out)
 	out->total_sectors = d->total_sectors;
 	return 1;
 }
+
+int sys_cputemp(struct sys_cputemp *out)
+{
+	unsigned int i;
+
+	_Static_assert(MAX_CPUS <= SYS_CPU_MAX,
+		       "sys_cputemp.cpu_temp_c is too small");
+	if (!out)
+		return -1;
+	out->temp_c = thermal_max_c();
+	out->tjmax_c = thermal_tjmax();
+	out->delta_c = -1;
+	out->status = 0;
+	if (thermal_status_this_cpu(&out->status) == 0)
+		out->delta_c = (int)((out->status >> 16) & 0x7F);
+	out->ncpus = cpu_count;
+	for (i = 0; i < SYS_CPU_MAX; i++)
+		out->cpu_temp_c[i] = cpus[i].temp_c;
+	return 0;
+}
+
+int sys_sensors(struct sys_sensors *out)
+{
+	struct it87_info info;
+	unsigned int i;
+
+	if (!out)
+		return -1;
+	it87_read(&info);
+	out->present = info.present ? 1u : 0u;
+	out->chip_id = info.chip_id;
+	out->base = info.base;
+	out->temp_enable = info.temp_enable;
+	out->temp_extra = info.temp_extra;
+	for (i = 0; i < 3; i++) {
+		out->temp_c[i] = info.temp_c[i];
+		out->fan_rpm[i] = info.fan_rpm[i];
+	}
+	return 0;
+}

+ 2 - 0
sys_info.h

@@ -9,5 +9,7 @@ int sys_e820(unsigned int index, struct sys_e820 *out);
 int sys_mouseinfo(struct sys_mouseinfo *out);
 int sys_storage_info(struct sys_storage_info *out);
 int sys_blkdev(unsigned int index, struct sys_blkdev *out);
+int sys_cputemp(struct sys_cputemp *out);
+int sys_sensors(struct sys_sensors *out);
 
 #endif

+ 115 - 1
sys_net.c

@@ -14,6 +14,7 @@
 #include "io.h"
 #include "net.h"
 #include "netdev.h"
+#include "netkexec.h"
 #include "netlog.h"
 #include "process.h"
 #include "tcp.h"
@@ -23,6 +24,13 @@
  * receiver is owned by the process using it). */
 static struct tcp_conn tcp;
 
+/* Accepted server connection (NULL until SYS_TCP_ACCEPT returns one). */
+static struct tcp_conn *srv_conn;
+
+/* Reply buffer for ARP/ICMP answered while listening (the rx scratch is
+ * occupied by the received frame). */
+static unsigned char srv_reply[NETDEV_FRAME_MAX];
+
 /* Long waits inside the stack (ARP/DNS/DHCP/TCP) spin on get_ticks_ms(), so
  * they need interrupts: the syscall stub entered with them off, and a frozen
  * tick counter would never satisfy a deadline.  The netdev ownership already
@@ -51,8 +59,11 @@ static unsigned int caller_pid(void)
 /* Called from the scheduler's reap loop for every dead process. */
 void sys_net_reap(unsigned int pid)
 {
-	if (netdev_owner() == pid)
+	if (netdev_owner() == pid) {
 		netdev_release_all();
+		tcp_srv_reset();
+		srv_conn = 0;
+	}
 }
 
 int sys_net_info(struct sys_netinfo *out)
@@ -271,6 +282,109 @@ void sys_tcp_close(void)
 	net_exit();
 }
 
+/* ---- TCP server ---- */
+
+int sys_tcp_listen(unsigned int port)
+{
+	if (!owns_nic() || port == 0 || port > 65535)
+		return -1;
+	net_enter();
+	tcp_srv_init(port);
+	net_exit();
+	srv_conn = 0;
+	return 0;
+}
+
+/* Poll the receiver for new connections.  Also answers ARP/ICMP and hands a
+ * netkexec header back to the kworker (the server exits, the watcher picks
+ * the transfer up without waiting for the host's retry). */
+int sys_tcp_accept(void)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char *rx;
+	struct tcp_conn *c;
+	int i, len;
+
+	if (!nd || !owns_nic())
+		return -2;
+	rx = netdev_rx_scratch();
+
+	net_enter();
+	for (i = 0; i < 16; i++) {
+		len = nd->rx(rx, NETDEV_FRAME_MAX);
+		if (len < 0)
+			break;
+		if (tcp_srv_input(rx, (unsigned int)len))
+			continue;
+		if (netkexec_capture_frame(rx, (unsigned int)len)) {
+			net_exit();
+			return -3;
+		}
+		{
+			int rlen = net_build_reply(rx, (unsigned int)len,
+						   srv_reply,
+						   sizeof(srv_reply));
+			if (rlen > 0)
+				nd->tx(srv_reply, (unsigned int)rlen);
+		}
+	}
+	c = tcp_srv_accept();
+	net_exit();
+	if (!c)
+		return 0;
+	srv_conn = c;
+	return 1;
+}
+
+int sys_tcp_srv_recv(void *buf, unsigned int max, unsigned int timeout_ms)
+{
+	int r;
+
+	if (!owns_nic() || !srv_conn)
+		return -2;
+	net_enter();
+	r = tcp_recv(srv_conn, buf, max, get_ticks_ms() + timeout_ms);
+	net_exit();
+	return r;
+}
+
+int sys_tcp_srv_send(const void *buf, unsigned int len)
+{
+	int r;
+
+	if (!owns_nic() || !srv_conn)
+		return -3;
+	net_enter();
+	r = tcp_srv_send(srv_conn, buf, len);
+	net_exit();
+	return r;
+}
+
+void sys_tcp_srv_close(void)
+{
+	if (owns_nic() && srv_conn) {
+		net_enter();
+		tcp_srv_close(srv_conn);
+		net_exit();
+	}
+	srv_conn = 0;
+}
+
+/* Peer of the accepted connection (for the server's connection log). */
+int sys_tcp_peer(unsigned char ip[4], unsigned int *port)
+{
+	unsigned int i;
+
+	if (!srv_conn)
+		return -1;
+	if (ip)
+		for (i = 0; i < 4; i++)
+			ip[i] = srv_conn->dst_ip[i];
+	if (port)
+		*port = srv_conn->dport;
+	return 0;
+}
+
 int sys_net_next_hop(const unsigned char dst[4], unsigned char hop[4])
 {
 	net_next_hop(dst, hop);

+ 6 - 0
sys_net.h

@@ -37,6 +37,12 @@ int sys_tcp_peer_mss(void);
 int sys_tcp_send(const void *buf, unsigned int len);
 int sys_tcp_recv(void *buf, unsigned int max, unsigned int timeout_ms);
 void sys_tcp_close(void);
+int sys_tcp_listen(unsigned int port);
+int sys_tcp_accept(void);
+int sys_tcp_srv_recv(void *buf, unsigned int max, unsigned int timeout_ms);
+int sys_tcp_srv_send(const void *buf, unsigned int len);
+void sys_tcp_srv_close(void);
+int sys_tcp_peer(unsigned char ip[4], unsigned int *port);
 int sys_net_next_hop(const unsigned char dst[4], unsigned char hop[4]);
 int sys_net_arp(const unsigned char ip[4], unsigned char mac[6]);
 int sys_net_configured(void);

+ 26 - 0
syscall.c

@@ -61,6 +61,8 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_rmdir((const char *)a1);
 	case SYS_LIST_MOUNTS:
 		return sys_list_mounts((unsigned int)a1, (struct sys_mount *)a2);
+	case SYS_FS_STAT:
+		return sys_stat_path((const char *)a1, (struct sys_stat *)a2);
 	case SYS_MEMINFO:
 		return sys_meminfo((struct sys_meminfo *)a1);
 	case SYS_E820:
@@ -138,6 +140,20 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 	case SYS_TCP_CLOSE:
 		sys_tcp_close();
 		return 0;
+	case SYS_TCP_LISTEN:
+		return sys_tcp_listen((unsigned int)a1);
+	case SYS_TCP_ACCEPT:
+		return sys_tcp_accept();
+	case SYS_TCP_SRV_RECV:
+		return sys_tcp_srv_recv((void *)a1, (unsigned int)a2,
+					(unsigned int)a3);
+	case SYS_TCP_SRV_SEND:
+		return sys_tcp_srv_send((const void *)a1, (unsigned int)a2);
+	case SYS_TCP_SRV_CLOSE:
+		sys_tcp_srv_close();
+		return 0;
+	case SYS_TCP_PEER:
+		return sys_tcp_peer((unsigned char *)a1, (unsigned int *)a2);
 	case SYS_NET_NEXT_HOP:
 		return sys_net_next_hop((const unsigned char *)a1,
 					(unsigned char *)a2);
@@ -250,6 +266,16 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_mem_grow((unsigned int)a1);
 	case SYS_MEM_FREE:
 		return sys_mem_free();
+	case SYS_CPU_TEMP:
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)a1,
+					  sizeof(struct sys_cputemp), 1))
+			return -1;
+		return sys_cputemp((struct sys_cputemp *)a1);
+	case SYS_SENSORS:
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)a1,
+					  sizeof(struct sys_sensors), 1))
+			return -1;
+		return sys_sensors((struct sys_sensors *)a1);
 	case SYS_WIN_KEY_WAIT:
 		return sys_win_key_wait((unsigned int)a1);
 	case SYS_SCHEDINFO:

+ 60 - 3
syscall.h

@@ -116,6 +116,26 @@
 #define SYS_MEM_GROW       89  /* (unsigned total_bytes) -> 0/-1 */
 #define SYS_MEM_FREE       90  /* () -> 0/-1 */
 
+/* CPU temperature (see thermal.c): the hottest core's DTS reading. */
+#define SYS_CPU_TEMP       91  /* (struct sys_cputemp *out) -> 0/-1 */
+
+/* IT87xx Super I/O hardware monitor (see it87.c); read-only. */
+#define SYS_SENSORS        92  /* (struct sys_sensors *out) -> 0/-1 */
+
+/* TCP server (WebDAV listener).  The caller must own the NIC (SYS_NET_ACQUIRE).
+ * SYS_TCP_ACCEPT polls a few frames and returns 1 once a connection is ready,
+ * 0 when nothing arrived, or -3 when a netkexec header was captured (the
+ * command should exit and let the kworker take over). */
+#define SYS_TCP_LISTEN     93  /* (port) -> 0/-1 */
+#define SYS_TCP_ACCEPT     94  /* () -> 1/0/-2/-3 */
+#define SYS_TCP_SRV_RECV   95  /* (buf, max, timeout_ms) -> >0/0/-1/-2 */
+#define SYS_TCP_SRV_SEND   96  /* (buf, len) -> 0/-1/-2/-3 */
+#define SYS_TCP_SRV_CLOSE  97
+#define SYS_TCP_PEER       99  /* (ip[4], unsigned *port) -> 0/-1 (debug log) */
+
+/* Stat one path (the file service has no open handle). */
+#define SYS_FS_STAT        98  /* (path, struct sys_stat *out) -> 0/<0 */
+
 /* Terminal / process services used by the ring-3 shell. */
 #define SYS_TTY_CREATE     73  /* () -> tty id 1..TTY_MAX / -1 */
 #define SYS_TTY_READ       74  /* (id, buf, max) -> bytes / 0 / -1 */
@@ -155,20 +175,32 @@ struct sys_netinfo {
 #define SYS_EINVAL  (-5)     /* path is not valid for this operation */
 #define SYS_EWRITE  (-6)     /* write refused (full, or FAT rejected it) */
 #define SYS_EROFS   (-7)     /* read-only filesystem (ramfs) */
+#define SYS_ENOSPC  (-8)     /* no space left on the filesystem */
 
-/* One directory entry, raw 8.3 name exactly as stored (space padded). */
+/* One directory entry.  `name` is a display name: raw 8.3 for FAT mounts
+ * (space padded, `raw_83` set) or the plain name for name-string filesystems
+ * such as ramfs and /share. */
 struct sys_dirent {
-	char name[12];
+	char name[64];
 	unsigned int size;
 	unsigned int is_dir;
+	unsigned int raw_83;
 };
 
 /* One mounted filesystem (for `ls /`). */
 struct sys_mount {
 	char name[16];
-	char type[8];           /* "FAT12", "FAT16", "FAT32" */
+	char type[8];           /* "FAT12", "FAT16", "FAT32", "ramfs", "share" */
 	unsigned int total_sectors;
 	char label[12];
+	unsigned int ro;
+};
+
+/* Result of SYS_FS_STAT. */
+struct sys_stat {
+	unsigned int size;
+	unsigned int is_dir;
+	unsigned int ro;
 };
 
 struct sys_meminfo {
@@ -204,6 +236,31 @@ struct sys_schedinfo {
 	unsigned int slice_ticks;
 };
 
+/* CPU temperature snapshot (see thermal.c).  temp_c is the hottest core's
+ * last DTS sample; a negative value means no Intel DTS is available.  delta_c
+ * and status are from the CPU that serviced the syscall (for diagnostics).
+ * cpu_temp_c[] holds the per-logical-CPU cached samples. */
+#define SYS_CPU_MAX 8
+struct sys_cputemp {
+	int temp_c;
+	int tjmax_c;
+	int delta_c;
+	unsigned int status;
+	int cpu_temp_c[SYS_CPU_MAX];
+	unsigned int ncpus;
+};
+
+/* IT87xx hardware monitor snapshot (temps are signed; -128 = unconnected). */
+struct sys_sensors {
+	unsigned int present;
+	unsigned int chip_id;
+	unsigned int base;
+	unsigned int temp_enable;
+	unsigned int temp_extra;
+	int temp_c[3];
+	unsigned int fan_rpm[3];
+};
+
 /* Window canvas handed to a ring-3 graphics command (see sys_gfx.c). */
 struct sys_gfx_info {
 	unsigned int width;    /* canvas (= window content) size in pixels */

+ 390 - 1
tcp.c

@@ -137,7 +137,10 @@ static int tcp_send_segment(struct tcp_conn *c, unsigned char flags,
 	wr32(tcp + 8, ack);
 	tcp[12] = (unsigned char)((5 + optlen / 4) << 4);
 	tcp[13] = flags;
-	wr16(tcp + 14, TCP_WINDOW);
+	/* Advertise the space actually left in the receive queue (the SYN
+	 * uses the conservative constant, before the queue is reset). */
+	wr16(tcp + 14, with_mss ? TCP_WINDOW :
+	     (rxq_space() > 0xFFFFu ? 0xFFFFu : rxq_space()));
 	wr16(tcp + 16, 0);                /* checksum */
 	wr16(tcp + 18, 0);                /* urgent pointer */
 	for (i = 0; i < len; i++)
@@ -389,6 +392,11 @@ int tcp_recv(struct tcp_conn *c, unsigned char *out, unsigned int maxlen,
 			if (n > maxlen)
 				n = maxlen;
 			rxq_get(out, n);
+			/* Window update: ACKs sent while the queue was full may
+			 * have advertised zero, and without this the peer would
+			 * only recover on its next zero-window probe. */
+			tcp_send_segment(c, TCP_ACK, c->snd_nxt, c->rcv_nxt,
+					 0, 0, 0);
 			return (int)n;
 		}
 		if (c->peer_fin)
@@ -459,3 +467,384 @@ void tcp_close(struct tcp_conn *c)
 		}
 	}
 }
+
+/* ---- Server side ----
+ *
+ * One listening port, one active connection, two slots that hold a
+ * handshake-complete connection until the command gets around to accepting
+ * it.  A closed connection lingers for a few seconds so the peer's FIN/ACK
+ * is absorbed instead of answered with RST (libsoup treats a reset after a
+ * complete response as an error). */
+
+#define TCP_SRV_SLOTS      3          /* 1 active + 2 backlog/closing */
+#define TCP_SRV_CLOSE_MS   2000
+#define TCP_SRV_BACKLOG_MS 30000
+
+enum {
+	SRV_FREE = 0,
+	SRV_BACKLOG,
+	SRV_ACTIVE,
+	SRV_CLOSING
+};
+
+struct tcp_srv {
+	struct tcp_conn c;
+	int used;
+	int state;
+	unsigned int last_ms;
+};
+
+static struct tcp_srv srv[TCP_SRV_SLOTS];
+static unsigned int srv_port;
+static int srv_active = -1;
+
+struct tcp_rx {
+	unsigned int seq, ack;
+	unsigned char flags;
+	const unsigned char *data;
+	unsigned int len;
+	const unsigned char *tcp;
+	unsigned int doff;
+	unsigned char src_mac[6];
+	unsigned char src_ip[4];
+	unsigned int sport, dport;
+};
+
+/* Parse any IPv4/TCP frame addressed to us (no connection match). */
+static int tcp_parse_any(const unsigned char *f, unsigned int flen,
+			 struct tcp_rx *s)
+{
+	const unsigned char *ip = f + 14;
+	const unsigned char *tcp;
+	unsigned char my_ip[4];
+	unsigned int i, ihl, ip_len, doff;
+
+	if (flen < 14 + 20)
+		return 0;
+	if ((((unsigned int)f[12] << 8) | f[13]) != ET_IPV4)
+		return 0;
+	if ((ip[0] >> 4) != 4)
+		return 0;
+	ihl = (unsigned int)(ip[0] & 0x0F) * 4;
+	if (ihl < 20 || ip[9] != IPPROTO_TCP)
+		return 0;
+	if ((ip[6] & 0x3F) != 0 || ip[7] != 0)
+		return 0;
+	ip_len = rd16(ip + 2);
+	if (ip_len < ihl + 20 || ip_len > flen - 14)
+		return 0;
+
+	net_get_ip(my_ip);
+	for (i = 0; i < 4; i++)
+		if (ip[16 + i] != my_ip[i])
+			return 0;
+
+	tcp = ip + ihl;
+	doff = (unsigned int)(tcp[12] >> 4) * 4;
+	if (doff < 20 || ihl + doff > ip_len)
+		return 0;
+
+	for (i = 0; i < 6; i++)
+		s->src_mac[i] = f[6 + i];
+	for (i = 0; i < 4; i++)
+		s->src_ip[i] = ip[12 + i];
+	s->sport = rd16(tcp);
+	s->dport = rd16(tcp + 2);
+	s->seq = rd32(tcp + 4);
+	s->ack = rd32(tcp + 8);
+	s->flags = tcp[13];
+	s->data = tcp + doff;
+	s->len = ip_len - ihl - doff;
+	s->tcp = tcp;
+	s->doff = doff;
+	return 1;
+}
+
+static int srv_match(const struct tcp_conn *c, const struct tcp_rx *s)
+{
+	unsigned int i;
+
+	if (s->sport != c->dport || s->dport != c->sport)
+		return 0;
+	for (i = 0; i < 4; i++)
+		if (s->src_ip[i] != c->dst_ip[i])
+			return 0;
+	return 1;
+}
+
+static void srv_clear(int i)
+{
+	srv[i].used = 0;
+	srv[i].state = SRV_FREE;
+}
+
+static void srv_expire(void)
+{
+	unsigned int now = get_ticks_ms();
+	int i;
+
+	for (i = 0; i < TCP_SRV_SLOTS; i++) {
+		if (!srv[i].used)
+			continue;
+		if (srv[i].state == SRV_CLOSING &&
+		    now - srv[i].last_ms >= TCP_SRV_CLOSE_MS) {
+			srv_clear(i);
+			if (srv_active == i)
+				srv_active = -1;
+		} else if (srv[i].state == SRV_BACKLOG &&
+			   now - srv[i].last_ms >= TCP_SRV_BACKLOG_MS) {
+			srv_clear(i);
+		}
+	}
+}
+
+static unsigned int srv_isn(void)
+{
+	return (get_ticks_ms() * 1103515245u) ^ 0x5EED0000u;
+}
+
+static void srv_resend_synack(struct tcp_srv *e)
+{
+	tcp_send_segment(&e->c, TCP_SYN | TCP_ACK, e->c.snd_una - 1,
+			 e->c.rcv_nxt, 0, 0, 1);
+}
+
+/* Build a connection from a SYN and answer SYN-ACK. */
+static int srv_new(const struct tcp_rx *s)
+{
+	struct tcp_srv *e;
+	unsigned int mss = 536, i;
+	int slot = -1;
+
+	/* Retransmitted SYN: answer with the same ISN. */
+	for (i = 0; i < TCP_SRV_SLOTS; i++) {
+		if (!srv[i].used || srv[i].state == SRV_CLOSING)
+			continue;
+		if (srv_match(&srv[i].c, s)) {
+			srv_resend_synack(&srv[i]);
+			return 1;
+		}
+	}
+
+	srv_expire();
+	for (i = 0; i < TCP_SRV_SLOTS; i++) {
+		/* A connection that already sent its response is finished
+		 * as far as new clients are concerned: reuse the slot rather
+		 * than make the next SYN wait for the linger to expire. */
+		if (!srv[i].used || srv[i].state == SRV_CLOSING) {
+			slot = (int)i;
+			break;
+		}
+	}
+	if (slot < 0)
+		return 1;                 /* no room: drop, the client retries */
+
+	e = &srv[slot];
+	for (i = 0; i < 6; i++)
+		e->c.dst_mac[i] = s->src_mac[i];
+	for (i = 0; i < 4; i++)
+		e->c.dst_ip[i] = s->src_ip[i];
+	e->c.sport = srv_port;
+	e->c.dport = s->sport;
+	e->c.snd_una = e->c.snd_nxt = srv_isn();
+	e->c.rcv_nxt = s->seq + 1;
+	e->c.peer_fin = 0;
+	e->c.peer_mss = 536;
+	if (tcp_parse_mss(s->tcp, s->doff, &mss) &&
+	    mss >= 64 && mss <= TCP_MSS_OURS)
+		e->c.peer_mss = mss;
+	e->used = 1;
+	e->state = SRV_BACKLOG;
+	e->last_ms = get_ticks_ms();
+
+	tcp_send_segment(&e->c, TCP_SYN | TCP_ACK, e->c.snd_nxt, e->c.rcv_nxt,
+			 0, 0, 1);
+	/* The SYN consumed one sequence number. */
+	e->c.snd_nxt++;
+	e->c.snd_una = e->c.snd_nxt;
+	return 1;
+}
+
+static void srv_send_rst(const struct tcp_rx *s)
+{
+	struct tcp_conn c;
+	unsigned int ack = s->seq + s->len;
+	unsigned int i;
+
+	if (s->flags & TCP_SYN)
+		ack++;
+	if (s->flags & TCP_FIN)
+		ack++;
+
+	for (i = 0; i < 6; i++)
+		c.dst_mac[i] = s->src_mac[i];
+	for (i = 0; i < 4; i++)
+		c.dst_ip[i] = s->src_ip[i];
+	c.sport = s->dport;
+	c.dport = s->sport;
+	c.snd_una = c.snd_nxt = s->ack;
+	c.rcv_nxt = ack;
+	c.peer_mss = 536;
+	c.peer_fin = 0;
+	tcp_send_segment(&c, TCP_RST | TCP_ACK, s->ack, ack, 0, 0, 0);
+}
+
+static void srv_rx_data(struct tcp_conn *c, const struct tcp_rx *r)
+{
+	struct tcp_seg s;
+
+	s.seq = r->seq;
+	s.ack = r->ack;
+	s.flags = r->flags;
+	s.data = r->data;
+	s.len = r->len;
+	s.tcp = r->tcp;
+	s.doff = r->doff;
+	tcp_rx_data(c, &s);
+}
+
+void tcp_srv_init(unsigned int port)
+{
+	int i;
+
+	for (i = 0; i < TCP_SRV_SLOTS; i++)
+		srv[i].used = 0, srv[i].state = SRV_FREE;
+	srv_active = -1;
+	srv_port = port;
+}
+
+void tcp_srv_reset(void)
+{
+	tcp_srv_init(0);
+	rxq_head = rxq_tail = 0;
+}
+
+int tcp_srv_input(const unsigned char *f, unsigned int len)
+{
+	struct tcp_rx s;
+	int i;
+
+	if (!srv_port || !tcp_parse_any(f, len, &s))
+		return 0;
+
+	/* The accepted connection. */
+	if (srv_active >= 0 && srv_match(&srv[srv_active].c, &s)) {
+		struct tcp_conn *c = &srv[srv_active].c;
+
+		if (s.flags & TCP_RST) {
+			srv_clear(srv_active);
+			srv_active = -1;
+			return 1;
+		}
+		if ((unsigned)(s.ack - c->snd_una) <=
+		    (unsigned)(c->snd_nxt - c->snd_una))
+			c->snd_una = s.ack;
+		srv_rx_data(c, &s);
+		srv[srv_active].last_ms = get_ticks_ms();
+		return 1;
+	}
+
+	/* A pending, closing or duplicate connection. */
+	for (i = 0; i < TCP_SRV_SLOTS; i++) {
+		if (!srv[i].used || !srv_match(&srv[i].c, &s))
+			continue;
+		if (srv[i].state == SRV_CLOSING) {
+			if (s.flags & TCP_FIN) {
+				srv[i].c.rcv_nxt++;
+				tcp_send_segment(&srv[i].c, TCP_ACK,
+						 srv[i].c.snd_nxt,
+						 srv[i].c.rcv_nxt, 0, 0, 0);
+			}
+			if (s.flags & TCP_RST)
+				srv_clear(i);
+			return 1;
+		}
+		if (s.flags & TCP_RST) {
+			srv_clear(i);
+			return 1;
+		}
+		if ((s.flags & (TCP_SYN | TCP_ACK | TCP_RST)) == TCP_SYN) {
+			srv_resend_synack(&srv[i]);
+			return 1;
+		}
+		/* Early data on a not-yet-accepted connection.  Do not ACK
+		 * it: the client retransmits after tcp_srv_accept(). */
+		if (s.flags & TCP_ACK)
+			srv[i].last_ms = get_ticks_ms();
+		return 1;
+	}
+
+	/* A new connection. */
+	if ((s.flags & (TCP_SYN | TCP_ACK | TCP_RST)) == TCP_SYN &&
+	    s.dport == srv_port)
+		return srv_new(&s);
+
+	/* TCP for us on a port we do not serve: refuse it. */
+	srv_send_rst(&s);
+	return 1;
+}
+
+struct tcp_conn *tcp_srv_accept(void)
+{
+	int i, best = -1;
+
+	if (srv_active >= 0)
+		return &srv[srv_active].c;
+
+	srv_expire();
+	for (i = 0; i < TCP_SRV_SLOTS; i++) {
+		if (!srv[i].used || srv[i].state != SRV_BACKLOG)
+			continue;
+		if (best < 0 ||
+		    (int)(srv[i].last_ms - srv[best].last_ms) < 0)
+			best = i;
+	}
+	if (best < 0)
+		return 0;
+
+	srv[best].state = SRV_ACTIVE;
+	srv_active = best;
+	rxq_head = rxq_tail = 0;
+	return &srv[best].c;
+}
+
+int tcp_srv_send(struct tcp_conn *c, const void *data, unsigned int len)
+{
+	const unsigned char *p = data;
+
+	if (!c)
+		return -3;
+	if (c->peer_mss < 64)
+		c->peer_mss = 64;
+
+	while (len) {
+		unsigned int n = len > c->peer_mss ? c->peer_mss : len;
+		int r = tcp_send(c, p, n);
+
+		if (r != 0)
+			return r;
+		p += n;
+		len -= n;
+	}
+	return 0;
+}
+
+void tcp_srv_close(struct tcp_conn *c)
+{
+	int i;
+
+	if (!c)
+		return;
+	for (i = 0; i < TCP_SRV_SLOTS; i++) {
+		if (!srv[i].used || &srv[i].c != c)
+			continue;
+		tcp_send_segment(c, TCP_FIN | TCP_ACK, c->snd_nxt, c->rcv_nxt,
+				 0, 0, 0);
+		c->snd_nxt++;
+		srv[i].state = SRV_CLOSING;
+		srv[i].last_ms = get_ticks_ms();
+		if (srv_active == i)
+			srv_active = -1;
+		return;
+	}
+}

+ 19 - 0
tcp.h

@@ -38,4 +38,23 @@ int tcp_recv(struct tcp_conn *c, unsigned char *out, unsigned int maxlen,
 /* Send FIN and drain the close handshake briefly (best effort). */
 void tcp_close(struct tcp_conn *c);
 
+/* ---- Server side (WebDAV listener) ----
+ *
+ * One listening port, one active connection and a small SYN backlog.  The
+ * caller owns the NIC.  Incoming frames are fed to tcp_srv_input() (which
+ * also answers SYNs and RSTs unknown ports); tcp_srv_accept() promotes a
+ * backlog connection for send/recv with the normal tcp_send()/tcp_recv(). */
+void tcp_srv_init(unsigned int port);
+void tcp_srv_reset(void);
+/* Handle one frame.  Returns 1 when it was a TCP frame for us (consumed),
+ * 0 when it is not TCP / not addressed to us (the caller may answer ARP). */
+int  tcp_srv_input(const unsigned char *frame, unsigned int len);
+/* Promote the oldest pending connection (NULL when none is ready). */
+struct tcp_conn *tcp_srv_accept(void);
+/* Send len bytes, split to the peer's MSS.  0 / -1 / -2 / -3. */
+int  tcp_srv_send(struct tcp_conn *c, const void *data, unsigned int len);
+/* FIN once, then remember the tuple briefly so a late FIN/ACK is absorbed
+ * instead of answered with RST. */
+void tcp_srv_close(struct tcp_conn *c);
+
 #endif

+ 54 - 0
terminal.c

@@ -3,6 +3,7 @@
 
 #include "io.h"
 #include "dbg.h"
+#include "idle.h"
 #include "kexec.h"
 #include "kmalloc.h"
 #include "mm.h"
@@ -87,6 +88,7 @@ static int cmd_clear(struct term *t, const char *args);
 static int cmd_dbg(struct term *t, const char *args);
 static int cmd_format(struct term *t, const char *args);
 static int cmd_help(struct term *t, const char *args);
+static int cmd_idle(struct term *t, const char *args);
 static int cmd_path(struct term *t, const char *args);
 static int cmd_kexec(struct term *t, const char *args);
 static int cmd_kill(struct term *t, const char *args);
@@ -119,6 +121,7 @@ static const struct kcmd cmds[] = {
 	{ "poke",       "poke <addr> <val>",             CK_SPAWN_ARG, CMD_REQARG, 0, program_poke_main, 0, 0 },
 	{ "ps",         "ps",                            CK_CUSTOM, 0, 0, 0, 0, cmd_ps },
 	{ "sched",      "sched",                         CK_CUSTOM, 0, 0, 0, 0, cmd_sched },
+	{ "idle",       "idle [hlt|c2|c3|c2ap|c3ap]",    CK_CUSTOM, 0, 0, 0, 0, cmd_idle },
 	{ "renice",     "renice <pid> <weight>",         CK_CUSTOM, CMD_REQARG, 0, 0, 0, cmd_renice },
 	{ "kill",       "kill <pid>",                    CK_CUSTOM, 0, 0, 0, 0, cmd_kill },
 	{ "kexec",      "kexec",                         CK_CUSTOM, 0, 0, 0, 0, cmd_kexec },
@@ -474,6 +477,57 @@ static int cmd_sched(struct term *t, const char *args)
 	return 0;
 }
 
+static int arg_is(const char *args, const char *word)
+{
+	unsigned int i = 0;
+
+	while (word[i] && args[i] == word[i])
+		i++;
+	return word[i] == '\0' && args[i] == '\0';
+}
+
+static int cmd_idle(struct term *t, const char *args)
+{
+	(void)t;
+	if (!args[0] || arg_is(args, "status")) {
+		io_putstr("idle ");
+		io_putstr(idle_mode_name(idle_mode()));
+		if (!idle_mwait_supported())
+			io_putstr(" (mwait unsupported)");
+		io_putchar('\n');
+		return 0;
+	}
+	if (arg_is(args, "hlt")) {
+		idle_set_mode(IDLE_C1);
+		io_putstr("idle hlt\n");
+		return 0;
+	}
+	{
+		int mode = -1;
+
+		if (arg_is(args, "c2"))
+			mode = IDLE_C2;
+		else if (arg_is(args, "c3"))
+			mode = IDLE_C3;
+		else if (arg_is(args, "c2ap"))
+			mode = IDLE_C2_AP;
+		else if (arg_is(args, "c3ap"))
+			mode = IDLE_C3_AP;
+		if (mode >= 0) {
+			if (idle_set_mode(mode) < 0) {
+				io_putstr("idle: mwait not available\n");
+				return 0;
+			}
+			io_putstr("idle ");
+			io_putstr(idle_mode_name(mode));
+			io_putstr(" (test the keyboard; power-cycle if it hangs)\n");
+			return 0;
+		}
+	}
+	io_putstr("idle: usage idle [hlt|c2|c3|c2ap|c3ap]\n");
+	return 0;
+}
+
 static int cmd_renice(struct term *t, const char *args)
 {
 	unsigned int pid = 0, weight = 0;

+ 234 - 0
thermal.c

@@ -0,0 +1,234 @@
+/* Intel digital thermal sensor (see thermal.h).
+ *
+ * IA32_THERM_STATUS (MSR 0x19C) reports the core temperature as a delta
+ * below TjMax in bits 22:16.  Bonnell (Atom 230/330) has no
+ * IA32_TEMPERATURE_TARGET MSR, so TjMax has to come from a table; these are
+ * the same values Linux's coretemp uses (the 330's DTS is calibrated against
+ * 125 C, other Bonnell parts against 90 C).  The DTS "valid" bit is ignored
+ * on purpose: coretemp does the same because the delta stays meaningful (the
+ * bit can be clear at temperatures below the sensor's range).
+ */
+#include "thermal.h"
+#include "cpu.h"
+#include "sched.h"
+#include "serial.h"
+#include "timer.h"
+
+#define MSR_IA32_THERM_STATUS 0x19C
+
+static int thermal_state = -1;  /* -1 unprobed, 0 unsupported, 1 DTS */
+static int thermal_tjmax_c = 100;
+
+static void cpuid_leaf(unsigned int leaf, unsigned int sub,
+		       unsigned int *a, unsigned int *b, unsigned int *c,
+		       unsigned int *d)
+{
+	__asm__ volatile ("cpuid"
+			  : "=a"(*a), "=b"(*b), "=c"(*c), "=d"(*d)
+			  : "a"(leaf), "c"(sub));
+}
+
+static int str_eq(const char *a, const char *b)
+{
+	while (*a && *a == *b) {
+		a++;
+		b++;
+	}
+	return *a == *b;
+}
+
+static int str_has(const char *hay, const char *needle)
+{
+	unsigned int i, j;
+
+	for (i = 0; hay[i]; i++) {
+		for (j = 0; needle[j] && hay[i + j] == needle[j]; j++)
+			;
+		if (!needle[j])
+			return 1;
+	}
+	return 0;
+}
+
+/* Model allowlist from coretemp: only parts that really expose a DTS.  This
+ * keeps rdmsr(0x19C) away from CPUs (and emulators) that set CPUID.06H but
+ * do not implement the MSR, where it would raise #GP and panic. */
+static int model_has_dts(unsigned int model)
+{
+	switch (model) {
+	case 0x0E:   /* Core Solo/Duo (Yonah) */
+	case 0x0F:   /* Core 2 */
+	case 0x16:   /* Core 2 */
+	case 0x17:   /* Penryn */
+	case 0x1A:   /* Nehalem */
+	case 0x1C:   /* Atom 230/330 (Diamondville) */
+	case 0x1D:   /* Atom Pineview */
+	case 0x1E:   /* Lynnfield */
+	case 0x1F:   /* Nehalem */
+		return 1;
+	default:
+		return 0;
+	}
+}
+
+static void read_brand(char out[49])
+{
+	unsigned int max_ext, a, b, c, d, i;
+
+	for (i = 0; i < 49; i++)
+		out[i] = '\0';
+	cpuid_leaf(0x80000000u, 0, &max_ext, &b, &c, &d);
+	if (max_ext < 0x80000004u)
+		return;
+	for (i = 0; i < 3; i++) {
+		unsigned int *dst = (unsigned int *)(out + i * 16);
+
+		cpuid_leaf(0x80000002u + i, 0, &a, &b, &c, &d);
+		dst[0] = a;
+		dst[1] = b;
+		dst[2] = c;
+		dst[3] = d;
+	}
+}
+
+static int pick_tjmax(unsigned int model, unsigned int stepping,
+		      const char *brand)
+{
+	if (model == 0x1C || model == 0x1D) {
+		/* The brand string often has double spaces ("CPU  330"), so
+		 * match the number alone. */
+		if (str_has(brand, "330"))
+			return 125;
+		if (str_has(brand, "230"))
+			return 100;
+		if (stepping == 10)     /* N4xx/N5xx/D4xx/D5xx */
+			return 100;
+		return 90;
+	}
+	return 100;
+}
+
+void thermal_init(void)
+{
+	unsigned int max_leaf, a, b, c, d;
+	unsigned int family, model = 0, stepping = 0;
+	char vendor[13];
+	char brand[49];
+
+	thermal_state = 0;
+	thermal_tjmax_c = 100;
+	if (!cpu_has_cpuid())
+		goto out;
+
+	cpuid_leaf(0, 0, &max_leaf, &b, &c, &d);
+	((unsigned int *)vendor)[0] = b;
+	((unsigned int *)vendor)[1] = d;
+	((unsigned int *)vendor)[2] = c;
+	vendor[12] = '\0';
+	if (!str_eq(vendor, "GenuineIntel") || 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;
+	if (family == 0xF)
+		family += (a >> 20) & 0xFF;
+	if (family == 0x6 || family == 0xF)
+		model += ((a >> 16) & 0xF) << 4;
+	if (family != 0x6 || !model_has_dts(model))
+		goto out;
+	if (max_leaf < 6)
+		goto out;
+	cpuid_leaf(6, 0, &a, &b, &c, &d);
+	if (!(a & 1u))                  /* DTS capability */
+		goto out;
+
+	read_brand(brand);
+	thermal_tjmax_c = pick_tjmax(model, stepping, brand);
+	thermal_state = 1;
+
+out:
+	if (thermal_state) {
+		serial_puts(SERIAL_COM1, "thermal: Intel DTS, model ");
+		serial_putdec(SERIAL_COM1, model);
+		serial_puts(SERIAL_COM1, " stepping ");
+		serial_putdec(SERIAL_COM1, stepping);
+		serial_puts(SERIAL_COM1, ", TjMax ");
+		serial_putdec(SERIAL_COM1, (unsigned int)thermal_tjmax_c);
+		serial_puts(SERIAL_COM1, " C\n");
+	} else {
+		serial_puts(SERIAL_COM1, "thermal: no Intel DTS, disabled\n");
+	}
+}
+
+int thermal_read_this_cpu(void)
+{
+	unsigned int raw;
+	int t;
+
+	if (thermal_status_this_cpu(&raw) != 0)
+		return -1;
+	t = thermal_tjmax_c - (int)((raw >> 16) & 0x7F);
+	if (t < -20 || t > 150)
+		return -1;
+	return t;
+}
+
+int thermal_status_this_cpu(unsigned int *status)
+{
+	unsigned int lo, hi;
+
+	if (thermal_state < 0)
+		thermal_init();
+	if (!thermal_state)
+		return -1;
+	__asm__ volatile ("rdmsr" : "=a"(lo), "=d"(hi)
+			  : "c"(MSR_IA32_THERM_STATUS));
+	(void)hi;
+	if (status)
+		*status = lo;
+	return 0;
+}
+
+void thermal_tick(void)
+{
+	struct cpu *c = this_cpu();
+	unsigned int ms = (c->id == 0) ? timer_tick_ms() : c->tick_ms;
+
+	/* 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)
+		return;
+	c->temp_div = 0;
+	c->temp_c = thermal_read_this_cpu();
+}
+
+int thermal_max_c(void)
+{
+	int max = -1;
+	unsigned int i;
+
+	if (thermal_state < 0)
+		thermal_init();
+	if (!thermal_state)
+		return -1;
+	for (i = 0; i < cpu_count && i < MAX_CPUS; i++)
+		if (cpus[i].temp_c > max)
+			max = cpus[i].temp_c;
+	/* Before the first tick has published a value (or while a CPU is
+	 * still booting), read the CPU running the caller instead of showing
+	 * nothing for the first second. */
+	if (max < 0)
+		max = thermal_read_this_cpu();
+	return max;
+}
+
+int thermal_tjmax(void)
+{
+	if (thermal_state < 0)
+		thermal_init();
+	return thermal_state ? thermal_tjmax_c : 0;
+}

+ 24 - 0
thermal.h

@@ -0,0 +1,24 @@
+/* Intel digital thermal sensor (DTS) access. */
+#ifndef THERMAL_H
+#define THERMAL_H
+
+/* Probe once on the BSP (before the timer starts); logs the result to COM1. */
+void thermal_init(void);
+
+/* Sample this CPU's DTS.  Called from the per-CPU scheduler tick, at most
+ * once per second. */
+void thermal_tick(void);
+
+/* Read this CPU's DTS now: degrees C, or -1 when unavailable. */
+int thermal_read_this_cpu(void);
+
+/* Read this CPU's raw IA32_THERM_STATUS: 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. */
+int thermal_max_c(void);
+
+/* TjMax used for the conversion, or 0 when DTS is unavailable. */
+int thermal_tjmax(void);
+
+#endif

+ 9 - 0
timer.h

@@ -4,4 +4,13 @@
 
 unsigned int get_ticks_ms(void);
 
+/* The PIT and AP LAPIC timers run at 1 kHz while a process is running and
+ * drop to 100 Hz while a CPU is idle, so C2/C3 can be held for 10 ms.  The
+ * global tick counter still advances in milliseconds. */
+void timer_set_hz(unsigned int hz);
+unsigned int timer_tick_ms(void);
+
+/* Called from the PIT stub: advance the millisecond clock by one tick. */
+void timer_tick_advance(void);
+
 #endif

+ 19 - 0
ucmd_cpuinfo.c

@@ -66,8 +66,10 @@ static void print_features_leaf1(unsigned int ecx1, unsigned int edx1)
 	if (edx1 & (1u << 25)) print_flag("SSE", &any);
 	if (edx1 & (1u << 26)) print_flag("SSE2", &any);
 	if (edx1 & (1u << 28)) print_flag("HTT", &any);
+	if (edx1 & (1u << 29)) print_flag("TM", &any);
 	if (ecx1 & (1u << 0))  print_flag("SSE3", &any);
 	if (ecx1 & (1u << 1))  print_flag("PCLMULQDQ", &any);
+	if (ecx1 & (1u << 7))  print_flag("EST", &any);
 	if (ecx1 & (1u << 9))  print_flag("SSSE3", &any);
 	if (ecx1 & (1u << 12)) print_flag("FMA", &any);
 	if (ecx1 & (1u << 13)) print_flag("CX16", &any);
@@ -288,6 +290,23 @@ void _start(void)
 
 	print_cpuid_frequency(max_leaf);
 
+	{
+		struct sys_cputemp ct;
+
+		if (u_cpu_temp(&ct) == 0 && ct.temp_c >= 0) {
+			u_puts("temp ");
+			put_uint((unsigned int)ct.temp_c);
+			u_puts(" C (tjmax ");
+			put_uint((unsigned int)ct.tjmax_c);
+			u_puts(" C)\n");
+		} else {
+			u_puts("temp unavailable (no Intel DTS)\n");
+		}
+	}
+	u_puts("eist ");
+	u_puts((ecx1 & (1u << 7)) ? "yes" : "no");
+	u_puts("\n");
+
 	start_ms = u_ticks_ms();
 	t0 = read_tsc_low();
 	do {

+ 9 - 33
ucmd_files.c

@@ -45,7 +45,7 @@ enum {
 #define ACT_CLOSE    (1u << 10)
 
 struct fm_entry {
-	char name[16];
+	char name[64];
 	char detail[8];
 	unsigned int size;
 	unsigned int is_dir;
@@ -233,39 +233,15 @@ static void make_abs(const char *p, char *out, unsigned int cap)
 		path_join(cwd, p, out, cap);
 }
 
-static void format_name(const char *raw, char *out, unsigned int cap)
+static void format_name(const char *raw, unsigned int raw_83, char *out,
+			unsigned int cap)
 {
-	unsigned int n = 0, i, ext = 8;
-	int dotted = 0, lower = 0, space = 0;
-
-	/* ramfs names are plain strings (usually lowercase, sometimes with a
-	 * dot); FAT names are the raw 11-byte, space-padded 8.3 form. */
-	for (i = 0; i < 11 && raw[i]; i++) {
-		if (raw[i] == '.')
-			dotted = 1;
-		if (raw[i] >= 'a' && raw[i] <= 'z')
-			lower = 1;
-		if (raw[i] == ' ')
-			space = 1;
-	}
-	if (dotted || (lower && !space)) {
+	/* Name-string filesystems (ramfs, share) already give a display name;
+	 * FAT gives the raw 11-byte, space-padded 8.3 field. */
+	if (!raw_83)
 		s_copy(out, raw, cap);
-		return;
-	}
-	while (ext < 11 && raw[ext] == ' ')
-		ext++;
-	for (i = 0; i < 8 && raw[i] && raw[i] != ' ' && n + 1 < cap; i++)
-		out[n++] = raw[i];
-	if (ext < 11 && raw[ext]) {
-		if (n + 1 < cap)
-			out[n++] = '.';
-		for (i = ext; i < 11 && raw[i] && raw[i] != ' ' &&
-		     n + 1 < cap; i++)
-			out[n++] = raw[i];
-	}
-	out[n] = '\0';
-	if (!n && cap)
-		s_copy(out, "?", cap);
+	else
+		u_fat_name(raw, out, cap);
 }
 
 static void format_size(unsigned int bytes, char *out, unsigned int cap)
@@ -428,7 +404,7 @@ static int load_path(const char *path)
 			truncated = 1;
 			break;
 		}
-		format_name(d.name, load_entries[n].name,
+		format_name(d.name, d.raw_83, load_entries[n].name,
 			    sizeof(load_entries[n].name));
 		load_entries[n].detail[0] = '\0';
 		load_entries[n].size = d.size;

+ 68 - 0
ucmd_lib.h

@@ -387,6 +387,16 @@ static inline int u_schedinfo(struct sys_schedinfo *out)
 	return u_syscall1(SYS_SCHEDINFO, (int)out);
 }
 
+static inline int u_cpu_temp(struct sys_cputemp *out)
+{
+	return u_syscall1(SYS_CPU_TEMP, (int)out);
+}
+
+static inline int u_sensors(struct sys_sensors *out)
+{
+	return u_syscall1(SYS_SENSORS, (int)out);
+}
+
 /* Per-process anonymous heap: one growable arena, freed at exit. */
 static inline void *u_mem_alloc(unsigned int bytes)
 {
@@ -405,4 +415,62 @@ static inline int u_mem_free(void)
 	return u_syscall0(SYS_MEM_FREE);
 }
 
+/* Path metadata (size, directory flag, read-only mount). */
+static inline int u_stat(const char *path, struct sys_stat *out)
+{
+	return u_syscall2(SYS_FS_STAT, (int)path, (int)out);
+}
+
+/* TCP server (the caller owns the NIC). */
+static inline int u_tcp_listen(unsigned int port)
+{
+	return u_syscall1(SYS_TCP_LISTEN, (int)port);
+}
+
+static inline int u_tcp_accept(void)
+{
+	return u_syscall0(SYS_TCP_ACCEPT);
+}
+
+static inline int u_tcp_srv_recv(void *buf, unsigned int max,
+				 unsigned int timeout_ms)
+{
+	return u_syscall3(SYS_TCP_SRV_RECV, (int)buf, (int)max,
+			  (int)timeout_ms);
+}
+
+static inline int u_tcp_srv_send(const void *buf, unsigned int len)
+{
+	return u_syscall2(SYS_TCP_SRV_SEND, (int)buf, (int)len);
+}
+
+static inline void u_tcp_srv_close(void)
+{
+	u_syscall0(SYS_TCP_SRV_CLOSE);
+}
+
+static inline int u_tcp_peer(unsigned char ip[4], unsigned int *port)
+{
+	return u_syscall2(SYS_TCP_PEER, (int)ip, (int)port);
+}
+
+/* Raw FAT 8.3 field -> display name ("FOO     TXT" -> "FOO.TXT"). */
+static inline void u_fat_name(const char *raw, char *out, unsigned int cap)
+{
+	unsigned int n = 0, i, ext = 8;
+
+	while (ext < 11 && raw[ext] == ' ')
+		ext++;
+	for (i = 0; i < 8 && raw[i] && raw[i] != ' ' && n + 1 < cap; i++)
+		out[n++] = raw[i];
+	if (ext < 11 && raw[ext]) {
+		if (n + 1 < cap)
+			out[n++] = '.';
+		for (i = ext; i < 11 && raw[i] && raw[i] != ' ' &&
+		     n + 1 < cap; i++)
+			out[n++] = raw[i];
+	}
+	out[n] = '\0';
+}
+
 #endif

+ 16 - 7
ucmd_ls.c

@@ -38,15 +38,24 @@ static void print_entry(const struct sys_dirent *d)
 	unsigned int i, n;
 	char buf[BUF_SIZE];
 
-	for (i = 0; i < 11 && d->name[i]; i++)
-		u_putc(d->name[i] == ' ' ? ' ' : d->name[i]);
-	if (i < 11)
+	if (!d->raw_83) {
+		u_puts(d->name);
+		if (d->is_dir) {
+			u_puts("  <DIR>\n");
+			return;
+		}
 		u_putc(' ');
-	if (d->is_dir) {
-		u_puts("  <DIR>\n");
-		return;
+	} else {
+		for (i = 0; i < 11 && d->name[i]; i++)
+			u_putc(d->name[i] == ' ' ? ' ' : d->name[i]);
+		if (i < 11)
+			u_putc(' ');
+		if (d->is_dir) {
+			u_puts("  <DIR>\n");
+			return;
+		}
+		u_puts(" ");
 	}
-	u_puts(" ");
 	n = d->size;
 	if (n == 0) {
 		u_putc('0');

+ 677 - 0
ucmd_mines.c

@@ -0,0 +1,677 @@
+/* mines: a small Minesweeper for a canvas window.
+ *
+ * The board is 9x9 with 10 mines.  The first reveal is always safe: mines are
+ * placed after it, outside the clicked cell and its eight neighbours.  Left
+ * click reveals, right click toggles a flag, R starts a new game and ESC
+ * closes the window.  The window can be resized; the board is re-laid out.
+ */
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+
+#define MW              9
+#define MH              9
+#define MINE_COUNT      10
+#define TOTAL_CELLS     (MW * MH)
+
+#define START_W         300
+#define START_H         360
+#define PAD             10
+#define HEADER_H        42
+#define FOOTER_H        20
+
+#define C_BG            NGUI_RGB(24, 28, 40)
+#define C_PANEL         NGUI_RGB(38, 43, 58)
+#define C_TILE          NGUI_RGB(62, 72, 96)
+#define C_TILE_HOT      NGUI_RGB(78, 90, 120)
+#define C_TILE_HI       NGUI_RGB(112, 126, 160)
+#define C_TILE_LO       NGUI_RGB(28, 32, 44)
+#define C_OPEN          NGUI_RGB(42, 48, 62)
+#define C_GRID          NGUI_RGB(30, 35, 46)
+#define C_BORDER        NGUI_RGB(92, 99, 124)
+#define C_DIM           NGUI_RGB(145, 151, 170)
+#define C_FLAG          NGUI_RGB(238, 116, 116)
+#define C_MINE          NGUI_RGB(255, 110, 110)
+#define C_EXPLODED      NGUI_RGB(130, 36, 44)
+#define C_FACE          NGUI_RGB(238, 198, 88)
+#define C_FACE_DK       NGUI_RGB(125, 88, 20)
+#define C_WIN           NGUI_RGB(120, 220, 140)
+#define C_LOSE          NGUI_RGB(238, 116, 116)
+
+struct mines_layout {
+	int cell;
+	int bx, by, bw, bh;
+	int face_x, face_y, face_w, face_h;
+	int counter_x, counter_y;
+	int timer_x, timer_y;
+	int footer_y;
+};
+
+static unsigned char mine[TOTAL_CELLS];
+static unsigned char opened[TOTAL_CELLS];
+static unsigned char flagged[TOTAL_CELLS];
+static unsigned char adj[TOTAL_CELLS];
+
+static int started;
+static int over;
+static int won;
+static int exploded = -1;
+static int opened_count;
+static int flag_count;
+static int last_second;
+static int quit;
+
+static unsigned int start_ms;
+static unsigned int end_ms;
+static unsigned int rng_state = 0x6D2B79F5u;
+static unsigned int game_seq;
+static unsigned int prev_right;
+
+static struct ngui_rect rect_make(int x, int y, int w, int h)
+{
+	struct ngui_rect r;
+
+	r.x = x;
+	r.y = y;
+	r.w = w;
+	r.h = h;
+	return r;
+}
+
+static int point_in(const struct ngui_rect *r, int x, int y)
+{
+	return x >= r->x && y >= r->y &&
+	       x < r->x + r->w && y < r->y + r->h;
+}
+
+static unsigned int rng_next(void)
+{
+	unsigned int x = rng_state;
+
+	x ^= x << 13;
+	x ^= x >> 17;
+	x ^= x << 5;
+	rng_state = x ? x : 0x6D2B79F5u;
+	return rng_state;
+}
+
+static void reset_game(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < TOTAL_CELLS; i++) {
+		mine[i] = 0;
+		opened[i] = 0;
+		flagged[i] = 0;
+		adj[i] = 0;
+	}
+	started = 0;
+	over = 0;
+	won = 0;
+	exploded = -1;
+	opened_count = 0;
+	flag_count = 0;
+	last_second = 0;
+	start_ms = 0;
+	end_ms = 0;
+	game_seq++;
+	rng_state = (u_ticks_ms() * 2654435761u) ^
+		    (game_seq * 2246822519u) ^ 0x9E3779B9u;
+	if (!rng_state)
+		rng_state = 0x6D2B79F5u;
+}
+
+static void compute_adj(void)
+{
+	int y, x, dy, dx;
+
+	for (y = 0; y < MH; y++) {
+		for (x = 0; x < MW; x++) {
+			int n = 0;
+
+			for (dy = -1; dy <= 1; dy++) {
+				for (dx = -1; dx <= 1; dx++) {
+					int nx = x + dx;
+					int ny = y + dy;
+
+					if ((!dx && !dy) || nx < 0 || nx >= MW ||
+					    ny < 0 || ny >= MH)
+						continue;
+					if (mine[ny * MW + nx])
+						n++;
+				}
+			}
+			adj[y * MW + x] = (unsigned char)n;
+		}
+	}
+}
+
+static void place_mines(int safe)
+{
+	int sx = safe % MW;
+	int sy = safe / MW;
+	int placed = 0;
+	unsigned int guard = 0;
+
+	while (placed < MINE_COUNT && guard++ < 100000u) {
+		int idx = (int)(rng_next() % TOTAL_CELLS);
+		int x = idx % MW;
+		int y = idx / MW;
+
+		if (mine[idx])
+			continue;
+		if (x >= sx - 1 && x <= sx + 1 &&
+		    y >= sy - 1 && y <= sy + 1)
+			continue;
+		mine[idx] = 1;
+		placed++;
+	}
+	compute_adj();
+}
+
+static int reveal_cell(int idx)
+{
+	int queue[TOTAL_CELLS];
+	int head = 0, tail = 0;
+
+	if (idx < 0 || idx >= TOTAL_CELLS)
+		return 0;
+	if (over || opened[idx] || flagged[idx])
+		return 0;
+	if (!started) {
+		place_mines(idx);
+		started = 1;
+		start_ms = u_ticks_ms();
+		last_second = 0;
+	}
+	if (mine[idx]) {
+		over = 1;
+		exploded = idx;
+		end_ms = u_ticks_ms();
+		return 1;
+	}
+
+	opened[idx] = 1;
+	opened_count++;
+	queue[tail++] = idx;
+	while (head < tail) {
+		int cur = queue[head++];
+		int y = cur / MW;
+		int x = cur % MW;
+		int dy, dx;
+
+		if (adj[cur] != 0)
+			continue;
+		for (dy = -1; dy <= 1; dy++) {
+			for (dx = -1; dx <= 1; dx++) {
+				int nx = x + dx;
+				int ny = y + dy;
+				int n;
+
+				if ((!dx && !dy) || nx < 0 || nx >= MW ||
+				    ny < 0 || ny >= MH)
+					continue;
+				n = ny * MW + nx;
+				if (opened[n] || flagged[n] || mine[n])
+					continue;
+				opened[n] = 1;
+				opened_count++;
+				queue[tail++] = n;
+			}
+		}
+	}
+
+	if (opened_count >= TOTAL_CELLS - MINE_COUNT) {
+		int i;
+
+		over = 1;
+		won = 1;
+		end_ms = u_ticks_ms();
+		for (i = 0; i < TOTAL_CELLS; i++) {
+			if (mine[i] && !flagged[i]) {
+				flagged[i] = 1;
+				flag_count++;
+			}
+		}
+	}
+	return 1;
+}
+
+static int toggle_flag(int idx)
+{
+	if (idx < 0 || idx >= TOTAL_CELLS)
+		return 0;
+	if (over || opened[idx])
+		return 0;
+	if (flagged[idx]) {
+		flagged[idx] = 0;
+		flag_count--;
+	} else {
+		flagged[idx] = 1;
+		flag_count++;
+	}
+	return 1;
+}
+
+static int elapsed_seconds(void)
+{
+	unsigned int now, ms;
+
+	if (!started)
+		return 0;
+	now = over ? end_ms : u_ticks_ms();
+	ms = now - start_ms;
+	if (ms / 1000 > 999u)
+		return 999;
+	return (int)(ms / 1000);
+}
+
+static void format3(int v, char *out)
+{
+	if (v < 0) {
+		out[0] = '-';
+		if (v < -99)
+			v = -99;
+		v = -v;
+		out[1] = (char)('0' + v / 10);
+		out[2] = (char)('0' + v % 10);
+		out[3] = '\0';
+		return;
+	}
+	if (v > 999)
+		v = 999;
+	out[0] = (char)('0' + v / 100);
+	out[1] = (char)('0' + (v / 10) % 10);
+	out[2] = (char)('0' + v % 10);
+	out[3] = '\0';
+}
+
+static void compute_layout(struct ngui *ui, struct mines_layout *l)
+{
+	int region_h = ui->h - HEADER_H - FOOTER_H;
+	int avail_w = ui->w - 2 * PAD;
+	int avail_h = region_h - 2 * PAD;
+	int cell;
+
+	if (avail_w < 1)
+		avail_w = 1;
+	if (avail_h < 1)
+		avail_h = 1;
+	cell = avail_w / MW;
+	if (cell > avail_h / MH)
+		cell = avail_h / MH;
+	if (cell < 10)
+		cell = 10;
+	if (cell > 40)
+		cell = 40;
+
+	l->cell = cell;
+	l->bw = cell * MW;
+	l->bh = cell * MH;
+	l->bx = (ui->w - l->bw) / 2;
+	if (l->bx < 0)
+		l->bx = 0;
+	l->by = HEADER_H + (region_h - l->bh) / 2;
+	if (l->by < HEADER_H)
+		l->by = HEADER_H;
+
+	l->face_w = 28;
+	l->face_h = 28;
+	l->face_x = (ui->w - l->face_w) / 2;
+	l->face_y = (HEADER_H - l->face_h) / 2;
+	l->counter_x = PAD;
+	l->counter_y = (HEADER_H - 16) / 2;
+	l->timer_x = ui->w - PAD - 36;
+	if (l->timer_x < l->counter_x + 44)
+		l->timer_x = l->counter_x + 44;
+	l->timer_y = l->counter_y;
+	l->footer_y = ui->h - FOOTER_H + 2;
+}
+
+static struct ngui_rect face_rect(const struct mines_layout *l)
+{
+	return rect_make(l->face_x, l->face_y, l->face_w, l->face_h);
+}
+
+static int cell_at(const struct mines_layout *l, int px, int py)
+{
+	int cx, cy;
+
+	if (l->cell <= 0 || px < l->bx || py < l->by)
+		return -1;
+	cx = (px - l->bx) / l->cell;
+	cy = (py - l->by) / l->cell;
+	if (cx < 0 || cx >= MW || cy < 0 || cy >= MH)
+		return -1;
+	return cy * MW + cx;
+}
+
+static void fill_circle(struct ngui *ui, int cx, int cy, int r,
+			unsigned short color)
+{
+	int dy;
+
+	for (dy = -r; dy <= r; dy++) {
+		int dx = 0;
+
+		while ((dx + 1) * (dx + 1) + dy * dy <= r * r)
+			dx++;
+		if (dx > 0)
+			ngui_fill_rect(ui,
+				       rect_make(cx - dx, cy + dy,
+						 dx * 2 + 1, 1), color);
+	}
+}
+
+static void draw_mine_icon(struct ngui *ui, int cx, int cy, int r,
+			   unsigned short color)
+{
+	int s = r + 2;
+
+	ngui_line(ui, cx - s, cy, cx + s, cy, color);
+	ngui_line(ui, cx, cy - s, cx, cy + s, color);
+	ngui_line(ui, cx - s + 2, cy - s + 2, cx + s - 2, cy + s - 2, color);
+	ngui_line(ui, cx - s + 2, cy + s - 2, cx + s - 2, cy - s + 2, color);
+	fill_circle(ui, cx, cy, r, color);
+}
+
+static void draw_flag_icon(struct ngui *ui, struct ngui_rect r,
+			   unsigned short color)
+{
+	int cx = r.x + r.w / 2;
+	int top = r.y + r.h / 2 - 7;
+	int pole_h = 13;
+	int fh, i;
+
+	if (pole_h > r.h - 6)
+		pole_h = r.h - 6;
+	if (pole_h < 6)
+		pole_h = 6;
+	fh = pole_h * 3 / 4;
+	if (fh < 4)
+		fh = 4;
+	for (i = 0; i < fh; i++)
+		ngui_fill_rect(ui, rect_make(cx + 1, top + i,
+					     fh - i, 1), color);
+	ngui_line(ui, cx, top, cx, top + pole_h, color);
+	ngui_fill_rect(ui, rect_make(cx - 2, top + pole_h, 5, 2), color);
+}
+
+static void draw_cross(struct ngui *ui, struct ngui_rect r,
+		       unsigned short color)
+{
+	int x0 = r.x + r.w / 2 - 5;
+	int x1 = r.x + r.w / 2 + 5;
+	int y0 = r.y + r.h / 2 - 5;
+	int y1 = r.y + r.h / 2 + 5;
+
+	ngui_line(ui, x0, y0, x1, y1, color);
+	ngui_line(ui, x0, y1, x1, y0, color);
+}
+
+static unsigned short number_color(int n)
+{
+	switch (n) {
+	case 1: return NGUI_RGB(120, 180, 255);
+	case 2: return NGUI_RGB(120, 220, 140);
+	case 3: return NGUI_RGB(255, 120, 120);
+	case 4: return NGUI_RGB(180, 140, 255);
+	case 5: return NGUI_RGB(255, 180, 100);
+	case 6: return NGUI_RGB(100, 220, 220);
+	case 7: return NGUI_RGB(230, 230, 230);
+	default: return NGUI_RGB(160, 160, 170);
+	}
+}
+
+static void draw_hidden(struct ngui *ui, struct ngui_rect r, int hot)
+{
+	int b = (r.w < 20) ? 1 : 2;
+
+	ngui_fill_rect(ui, r, hot ? C_TILE_HOT : C_TILE);
+	ngui_fill_rect(ui, rect_make(r.x, r.y, r.w, b), C_TILE_HI);
+	ngui_fill_rect(ui, rect_make(r.x, r.y, b, r.h), C_TILE_HI);
+	ngui_fill_rect(ui, rect_make(r.x, r.y + r.h - b, r.w, b), C_TILE_LO);
+	ngui_fill_rect(ui, rect_make(r.x + r.w - b, r.y, b, r.h), C_TILE_LO);
+}
+
+static void draw_open(struct ngui *ui, struct ngui_rect r)
+{
+	ngui_fill_rect(ui, r, C_OPEN);
+	ngui_fill_rect(ui, rect_make(r.x, r.y, r.w, 1), C_GRID);
+	ngui_fill_rect(ui, rect_make(r.x, r.y, 1, r.h), C_GRID);
+}
+
+static void draw_face_icon(struct ngui *ui, struct ngui_rect r)
+{
+	int cx = r.x + r.w / 2;
+	int cy = r.y + r.h / 2;
+	int rad = (r.w < r.h ? r.w : r.h) / 2 - 3;
+
+	if (rad < 6)
+		rad = 6;
+	fill_circle(ui, cx, cy, rad, C_FACE);
+
+	if (won) {
+		ngui_fill_rect(ui, rect_make(cx - 7, cy - 5, 6, 4), C_FACE_DK);
+		ngui_fill_rect(ui, rect_make(cx + 1, cy - 5, 6, 4), C_FACE_DK);
+		ngui_fill_rect(ui, rect_make(cx - 1, cy - 4, 2, 1), C_FACE_DK);
+		ngui_line(ui, cx - 5, cy + 4, cx - 2, cy + 6, C_FACE_DK);
+		ngui_line(ui, cx - 2, cy + 6, cx + 2, cy + 6, C_FACE_DK);
+		ngui_line(ui, cx + 2, cy + 6, cx + 5, cy + 4, C_FACE_DK);
+	} else if (over) {
+		ngui_line(ui, cx - 6, cy - 5, cx - 2, cy - 1, C_FACE_DK);
+		ngui_line(ui, cx - 2, cy - 5, cx - 6, cy - 1, C_FACE_DK);
+		ngui_line(ui, cx + 2, cy - 5, cx + 6, cy - 1, C_FACE_DK);
+		ngui_line(ui, cx + 6, cy - 5, cx + 2, cy - 1, C_FACE_DK);
+		ngui_line(ui, cx - 5, cy + 6, cx - 2, cy + 4, C_FACE_DK);
+		ngui_line(ui, cx - 2, cy + 4, cx + 2, cy + 4, C_FACE_DK);
+		ngui_line(ui, cx + 2, cy + 4, cx + 5, cy + 6, C_FACE_DK);
+	} else {
+		ngui_fill_rect(ui, rect_make(cx - 5, cy - 4, 3, 4), C_FACE_DK);
+		ngui_fill_rect(ui, rect_make(cx + 3, cy - 4, 3, 4), C_FACE_DK);
+		ngui_line(ui, cx - 5, cy + 4, cx - 2, cy + 6, C_FACE_DK);
+		ngui_line(ui, cx - 2, cy + 6, cx + 2, cy + 6, C_FACE_DK);
+		ngui_line(ui, cx + 2, cy + 6, cx + 5, cy + 4, C_FACE_DK);
+	}
+}
+
+static void draw_header(struct ngui *ui, const struct mines_layout *l)
+{
+	struct ngui_rect fr = face_rect(l);
+	int hot = ui->inside && point_in(&fr, ui->mouse_x, ui->mouse_y);
+	int down = hot && (ui->buttons & 1);
+	unsigned short bg = down ? ui->theme.button_down :
+			    hot ? ui->theme.button_hot : ui->theme.button;
+	char buf[4];
+
+	ngui_fill_rect(ui, rect_make(0, 0, ui->w, HEADER_H), C_PANEL);
+	ngui_fill_rect(ui, rect_make(0, HEADER_H - 1, ui->w, 1), C_BORDER);
+
+	format3(MINE_COUNT - flag_count, buf);
+	ngui_text(ui, l->counter_x, l->counter_y, "M", C_DIM);
+	ngui_text(ui, l->counter_x + 12, l->counter_y, buf, C_FLAG);
+
+	format3(elapsed_seconds(), buf);
+	ngui_text(ui, l->timer_x, l->timer_y, buf, C_WIN);
+	ngui_text(ui, l->timer_x + 28, l->timer_y, "T", C_DIM);
+
+	ngui_fill_rect(ui, fr, bg);
+	ngui_frame(ui, fr, hot ? ui->theme.accent : C_BORDER);
+	draw_face_icon(ui, rect_make(fr.x + 2, fr.y + 2,
+				     fr.w - 4, fr.h - 4));
+}
+
+static void draw_board(struct ngui *ui, const struct mines_layout *l)
+{
+	int y, x;
+
+	ngui_push_clip(ui, rect_make(l->bx, l->by, l->bw, l->bh));
+	for (y = 0; y < MH; y++) {
+		for (x = 0; x < MW; x++) {
+			int idx = y * MW + x;
+			struct ngui_rect r = rect_make(l->bx + x * l->cell,
+						       l->by + y * l->cell,
+						       l->cell, l->cell);
+			int hot = ui->inside && point_in(&r, ui->mouse_x,
+							 ui->mouse_y);
+
+			if (opened[idx]) {
+				draw_open(ui, r);
+				if (mine[idx]) {
+					draw_mine_icon(ui, r.x + r.w / 2,
+						       r.y + r.h / 2,
+						       r.w / 5, C_MINE);
+				} else if (adj[idx]) {
+					char nb[2];
+
+					nb[0] = (char)('0' + adj[idx]);
+					nb[1] = '\0';
+					ngui_push_clip(ui, r);
+					ngui_text(ui, r.x + (r.w - 8) / 2,
+						  r.y + (r.h - 16) / 2, nb,
+						  number_color(adj[idx]));
+					ngui_pop_clip(ui);
+				}
+			} else {
+				draw_hidden(ui, r, hot);
+				if (flagged[idx]) {
+					draw_flag_icon(ui, r, C_FLAG);
+					if (over && !mine[idx])
+						draw_cross(ui, r, C_LOSE);
+				} else if (over && mine[idx]) {
+					if (idx == exploded)
+						ngui_fill_rect(ui, r, C_EXPLODED);
+					draw_mine_icon(ui, r.x + r.w / 2,
+						       r.y + r.h / 2,
+						       r.w / 5, C_MINE);
+				}
+			}
+		}
+	}
+	ngui_pop_clip(ui);
+}
+
+static void draw_footer(struct ngui *ui, const struct mines_layout *l)
+{
+	const char *msg;
+	unsigned short color;
+	int tw, x;
+
+	if (won) {
+		msg = "You win!  R: play again";
+		color = C_WIN;
+	} else if (over) {
+		msg = "Boom!  R: play again";
+		color = C_LOSE;
+	} else if (started) {
+		msg = "R: new   right-click: flag";
+		color = C_DIM;
+	} else {
+		msg = "left: reveal  right: flag";
+		color = C_DIM;
+	}
+	tw = (int)ngui_text_width(msg);
+	x = (ui->w - tw) / 2;
+	if (x < 4)
+		x = 4;
+	ngui_text(ui, x, l->footer_y, msg, color);
+}
+
+static void draw_app(struct ngui *ui, const struct mines_layout *l)
+{
+	ngui_fill_rect(ui, rect_make(0, 0, ui->w, ui->h), C_BG);
+	ngui_fill_rect(ui, rect_make(0, ui->h - FOOTER_H, ui->w, 1), C_BORDER);
+	draw_header(ui, l);
+	draw_board(ui, l);
+	draw_footer(ui, l);
+}
+
+static int handle_input(struct ngui *ui, const struct mines_layout *l)
+{
+	int changed = 0;
+	int k;
+
+	while ((k = ngui_key(ui)) != 0) {
+		if (k == NGUI_KEY_ESC) {
+			quit = 1;
+		} else if (k == 'r' || k == 'R') {
+			reset_game();
+			changed = 1;
+		}
+	}
+
+	if (ui->pressed) {
+		struct ngui_rect fr = face_rect(l);
+
+		if (point_in(&fr, ui->press_x, ui->press_y)) {
+			reset_game();
+			changed = 1;
+		} else {
+			int idx = cell_at(l, ui->press_x, ui->press_y);
+
+			if (idx >= 0 && reveal_cell(idx))
+				changed = 1;
+		}
+	}
+
+	{
+		unsigned int right = ui->buttons & 2u;
+
+		if (right && !prev_right && ui->inside) {
+			int idx = cell_at(l, ui->mouse_x, ui->mouse_y);
+
+			if (idx >= 0 && toggle_flag(idx))
+				changed = 1;
+		}
+		prev_right = right;
+	}
+
+	if (started && !over) {
+		int sec = elapsed_seconds();
+
+		if (sec != last_second) {
+			last_second = sec;
+			changed = 1;
+		}
+	}
+	return changed;
+}
+
+void _start(const char *arg)
+{
+	struct win_info info;
+	struct ngui ui;
+
+	(void)arg;
+	if (u_win_create(START_W, START_H, "mines", &info) != 0) {
+		u_puts("mines: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)info.fb, (int)info.width,
+		  (int)info.height);
+	reset_game();
+	quit = 0;
+	prev_right = 0;
+
+	for (;;) {
+		struct mines_layout l;
+		int want, changed;
+
+		want = ngui_begin(&ui);
+		if (quit)
+			break;
+		compute_layout(&ui, &l);
+		changed = handle_input(&ui, &l);
+		if (want || changed) {
+			draw_app(&ui, &l);
+			ngui_end(&ui);
+		} else {
+			ngui_end_ex(&ui, 0);
+		}
+		if (quit)
+			break;
+		u_sleep_ms(10);
+	}
+	u_win_close();
+	u_exit(0);
+}

+ 126 - 0
ucmd_sensors.c

@@ -0,0 +1,126 @@
+/* sensors: CPU DTS + IT87xx Super I/O temperatures and fan speeds.
+ *
+ * The DTS TjMax of the Atom 330 is not published; Intel only specifies
+ * TJ = 90 C and Tcase-max = 85.2 C, while Linux coretemp uses 125 C for this
+ * model.  This command prints the raw DTS delta and the resulting absolute
+ * temperature for each common TjMax, plus the Super I/O's independent diode
+ * readings and the fan tachometers.
+ */
+#include "ucmd_lib.h"
+
+static void put_temp(int t)
+{
+	if (t <= -50) {
+		u_puts("--");
+		return;
+	}
+	if (t < 0) {
+		u_putc('-');
+		u_putdec((unsigned int)(-t));
+	} else {
+		u_putdec((unsigned int)t);
+	}
+}
+
+static void put_hex16(unsigned int v)
+{
+	static const char hex[] = "0123456789ABCDEF";
+
+	u_putc(hex[(v >> 12) & 0xF]);
+	u_putc(hex[(v >> 8) & 0xF]);
+	u_putc(hex[(v >> 4) & 0xF]);
+	u_putc(hex[v & 0xF]);
+}
+
+static void put_scale(int tjmax, int delta)
+{
+	int t = tjmax - delta;
+
+	if (t < -20 || t > 150)
+		u_puts("--");
+	else {
+		u_putdec((unsigned int)t);
+		u_puts(" C");
+	}
+}
+
+void _start(void)
+{
+	struct sys_cputemp ct;
+	struct sys_sensors s;
+	unsigned int i;
+
+	u_puts("dts ");
+	if (u_cpu_temp(&ct) == 0 && ct.temp_c >= 0) {
+		u_puts("max ");
+		put_temp(ct.temp_c);
+		u_puts(" C (tjmax ");
+		u_putdec((unsigned int)ct.tjmax_c);
+		u_puts(" C)\n");
+		if (ct.delta_c >= 0) {
+			u_puts("this core delta ");
+			u_putdec((unsigned int)ct.delta_c);
+			u_puts(", status 0x");
+			u_puthex(ct.status);
+			u_puts("\nscale 90: ");
+			put_scale(90, ct.delta_c);
+			u_puts(", 100: ");
+			put_scale(100, ct.delta_c);
+			u_puts(", 125: ");
+			put_scale(125, ct.delta_c);
+			u_putc('\n');
+		}
+		u_puts("cores ");
+		for (i = 0; i < ct.ncpus && i < SYS_CPU_MAX; i++) {
+			put_temp(ct.cpu_temp_c[i]);
+			u_puts(" C");
+			if (i + 1 < ct.ncpus && i + 1 < SYS_CPU_MAX)
+				u_puts(", ");
+		}
+		u_putc('\n');
+	} else {
+		u_puts("unavailable (no Intel DTS)\n");
+	}
+
+	if (u_sensors(&s) != 0 || !s.present) {
+		u_puts("it87 not found\n");
+		u_exit(0);
+	}
+	u_puts("it87 chip 0x");
+	put_hex16(s.chip_id);
+	u_puts(" base 0x");
+	put_hex16(s.base);
+	u_puts(" enable 0x");
+	u_put_hex2(s.temp_enable);
+	u_puts(" extra 0x");
+	u_put_hex2(s.temp_extra);
+	u_putc('\n');
+	for (i = 0; i < 3; i++) {
+		int enabled = (s.temp_enable & (1u << i)) ||
+			      (s.temp_enable & (1u << (i + 3))) ||
+			      (i == 2 && (s.temp_enable & 0xC0) == 0xC0);
+
+		u_puts("temp");
+		u_putdec(i + 1);
+		u_puts(" ");
+		if (enabled)
+			put_temp(s.temp_c[i]);
+		else
+			u_puts("--");
+		u_puts(" C");
+		if (i < 2)
+			u_puts(", ");
+	}
+	u_putc('\n');
+	for (i = 0; i < 3; i++) {
+		u_puts("fan");
+		u_putdec(i + 1);
+		u_puts(" ");
+		u_putdec(s.fan_rpm[i]);
+		u_puts(" RPM");
+		if (i < 2)
+			u_puts(", ");
+	}
+	u_putc('\n');
+	u_exit(0);
+}

+ 18 - 6
ucmd_term.c

@@ -592,15 +592,26 @@ static void complete_line(void)
 			struct sys_dirent d;
 
 			for (i = 0;; i++) {
+				char disp[64];
+				unsigned int dl;
+
 				if (u_syscall3(SYS_LIST_DIR, (int)dir, (int)i,
 					       (int)&d) != 1)
 					break;
-				n = name_len(d.name, sizeof(d.name));
+				if (d.raw_83)
+					u_fat_name(d.name, disp, sizeof(disp));
+				else {
+					for (dl = 0; dl + 1 < sizeof(disp) &&
+						      d.name[dl]; dl++)
+						disp[dl] = d.name[dl];
+					disp[dl] = '\0';
+				}
+				n = name_len(disp, sizeof(disp));
 				if (n == 0 ||
-				    (n == 1 && d.name[0] == '.') ||
-				    (n == 2 && d.name[0] == '.' && d.name[1] == '.'))
+				    (n == 1 && disp[0] == '.') ||
+				    (n == 2 && disp[0] == '.' && disp[1] == '.'))
 					continue;
-				if (!prefix_is(base, bl, d.name, n))
+				if (!prefix_is(base, bl, disp, n))
 					continue;
 				matches++;
 				if (matches == 1) {
@@ -614,9 +625,10 @@ static void complete_line(void)
 						    cl + 1 < sizeof(cand))
 							cand[cl++] = '/';
 					}
-					for (n = 0; d.name[n] && n < sizeof(d.name) &&
+					for (n = 0; disp[n] &&
+						    n < sizeof(disp) &&
 						    cl + 1 < sizeof(cand); n++)
-						cand[cl++] = d.name[n];
+						cand[cl++] = disp[n];
 					cand[cl] = '\0';
 					cand_dir = d.is_dir ? 1 : 0;
 				}

+ 1658 - 0
ucmd_websrv.c

@@ -0,0 +1,1658 @@
+/* websrv: a minimal HTTP/1.1 + WebDAV server.
+ *
+ * The TCP stack and the NIC stay in the kernel (see tcp.c/sys_net.c); this
+ * command owns the receiver, parses one request per connection (always
+ * "Connection: close") and maps WebDAV onto the VFS:
+ *
+ *   /              the mounted filesystems (collections)
+ *   /ramfs/...     read-only (the command pack)
+ *   /floppy1/...   FAT, writable with 8.3 names only
+ *   /share/...     writable RAM store with long names
+ *
+ * Methods: OPTIONS, GET, HEAD, PUT, DELETE, MKCOL, PROPFIND, PROPPATCH,
+ * MOVE, LOCK, UNLOCK.  No authentication: this is a trusted-LAN service.
+ *
+ * A file body is buffered whole (4 MB, or 1 MB when the heap is small)
+ * because the VFS has no open/read/write-at interface.
+ */
+
+#include "ucmd_lib.h"
+
+#define REQ_MAX       4096u
+#define BODY_MAX      (4u * 1024u * 1024u)
+#define BODY_FALLBACK (1024u * 1024u)
+#define PATH_MAX      192u
+#define XML_MAX       3072u
+#define CHUNK_MAX     3072u
+#define SOCK_MS       1000u
+#define HDR_TIMEOUT_MS 10000u
+#define REQ_TIMEOUT_MS 60000u
+#define MAX_MOUNTS    24u
+
+static char hdr[REQ_MAX];
+static unsigned int hdr_len;
+static char rbuf[REQ_MAX];
+static unsigned char *body;
+static unsigned int body_max;
+static char resp[1024];
+static unsigned int resp_len;
+static char xml[XML_MAX];
+static unsigned int xml_len;
+static char cbuf[CHUNK_MAX];
+static struct sys_mount mounts[MAX_MOUNTS];
+static unsigned int mount_count;
+static unsigned int req_start;
+static int status;
+static const char *extra_hdrs;
+
+struct req {
+	char method[12];
+	char target[PATH_MAX];
+	char path[PATH_MAX];
+	char dest[PATH_MAX];
+	int  http11;
+	int  have_len;
+	unsigned int content_len;
+	int  chunked;
+	int  depth;
+	int  expect_continue;
+	int  overwrite;
+	int  have_dest;
+};
+
+static struct req rq;
+
+/* ---- small string helpers ---- */
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s[n])
+		n++;
+	return n;
+}
+
+static int s_eq(const char *a, const char *b)
+{
+	unsigned int i = 0;
+
+	while (a[i] && b[i] && a[i] == b[i])
+		i++;
+	return a[i] == '\0' && b[i] == '\0';
+}
+
+static int s_ieq(const char *a, const char *b)
+{
+	unsigned int i = 0;
+
+	for (;;) {
+		char ca = a[i], cb = b[i];
+
+		if (ca >= 'A' && ca <= 'Z')
+			ca = (char)(ca - 'A' + 'a');
+		if (cb >= 'A' && cb <= 'Z')
+			cb = (char)(cb - 'A' + 'a');
+		if (ca != cb)
+			return 0;
+		if (!ca)
+			return 1;
+		i++;
+	}
+}
+
+static int s_contains_ci(const char *hay, const char *needle)
+{
+	unsigned int i, j, n = s_len(needle);
+
+	if (!n)
+		return 1;
+	for (i = 0; hay[i]; i++) {
+		for (j = 0; j < n; j++) {
+			char a = hay[i + j], b = needle[j];
+
+			if (!a)
+				return 0;
+			if (a >= 'A' && a <= 'Z')
+				a = (char)(a - 'A' + 'a');
+			if (b >= 'A' && b <= 'Z')
+				b = (char)(b - 'A' + 'a');
+			if (a != b)
+				break;
+		}
+		if (j == n)
+			return 1;
+	}
+	return 0;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	while (i + 1 < cap && s[i]) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static void mem_copy(void *d, const void *s, unsigned int n)
+{
+	unsigned char *dd = d;
+	const unsigned char *ss = s;
+
+	while (n--)
+		*dd++ = *ss++;
+}
+
+static int hexval(int c)
+{
+	if (c >= '0' && c <= '9')
+		return c - '0';
+	if (c >= 'a' && c <= 'f')
+		return c - 'a' + 10;
+	if (c >= 'A' && c <= 'F')
+		return c - 'A' + 10;
+	return -1;
+}
+
+/* ---- response buffer ---- */
+
+static void ra(const char *s)
+{
+	while (*s && resp_len + 1 < sizeof(resp))
+		resp[resp_len++] = *s++;
+	resp[resp_len] = '\0';
+}
+
+static void rad(unsigned int v)
+{
+	char tmp[12];
+	unsigned int i = sizeof(tmp) - 1;
+
+	tmp[i] = '\0';
+	if (!v) {
+		ra("0");
+		return;
+	}
+	while (v && i > 0) {
+		tmp[--i] = (char)('0' + (v % 10));
+		v /= 10;
+	}
+	ra(tmp + i);
+}
+
+static const char *reason_phrase(int code)
+{
+	switch (code) {
+	case 100: return "Continue";
+	case 200: return "OK";
+	case 201: return "Created";
+	case 204: return "No Content";
+	case 207: return "Multi-Status";
+	case 301: return "Moved Permanently";
+	case 400: return "Bad Request";
+	case 403: return "Forbidden";
+	case 404: return "Not Found";
+	case 405: return "Method Not Allowed";
+	case 408: return "Request Timeout";
+	case 409: return "Conflict";
+	case 411: return "Length Required";
+	case 412: return "Precondition Failed";
+	case 413: return "Payload Too Large";
+	case 414: return "URI Too Long";
+	case 431: return "Request Header Fields Too Large";
+	case 500: return "Internal Server Error";
+	case 501: return "Not Implemented";
+	case 507: return "Insufficient Storage";
+	default:  return "Error";
+	}
+}
+
+/* Send the status line + headers.  `extra` is appended verbatim (or NULL). */
+static int send_headers(int code, const char *reason, const char *ctype,
+			unsigned int len)
+{
+	resp_len = 0;
+	ra("HTTP/1.1 ");
+	rad((unsigned int)code);
+	ra(" ");
+	ra(reason);
+	ra("\r\nServer: Nebs OS/0.2.0\r\n");
+	ra("Connection: close\r\nCache-Control: no-store\r\n");
+	if (extra_hdrs) {
+		ra(extra_hdrs);
+		ra("\r\n");
+	}
+	if (ctype) {
+		ra("Content-Type: ");
+		ra(ctype);
+		ra("\r\n");
+	}
+	ra("Content-Length: ");
+	rad(len);
+	ra("\r\n\r\n");
+	status = code;
+	return u_tcp_srv_send(resp, resp_len);
+}
+
+/* Small response with an optional body. */
+static int send_body(int code, const char *reason, const char *ctype,
+		     const void *data, unsigned int len)
+{
+	if (send_headers(code, reason, ctype, len) != 0)
+		return -1;
+	if (len && u_tcp_srv_send(data, len) != 0)
+		return -1;
+	return 0;
+}
+
+static int send_error(int code)
+{
+	char msg[64];
+	unsigned int n = 0;
+	const char *reason = reason_phrase(code);
+
+	msg[n++] = (char)('0' + (code / 100) % 10);
+	msg[n++] = (char)('0' + (code / 10) % 10);
+	msg[n++] = (char)('0' + code % 10);
+	msg[n++] = ' ';
+	while (*reason && n + 2 < sizeof(msg))
+		msg[n++] = *reason++;
+	msg[n++] = '\n';
+	return send_body(code, reason_phrase(code), "text/plain", msg, n);
+}
+
+static int send_empty(int code)
+{
+	return send_headers(code, reason_phrase(code), 0, 0);
+}
+
+/* Refuse a request and leave a human-readable reason in the terminal log
+ * (the WebDAV client only sees the status code). */
+static int send_refuse(int code, const char *why)
+{
+	u_puts("websrv: refused: ");
+	u_puts(why);
+	u_putc('\n');
+	return send_error(code);
+}
+
+/* ---- chunked response (PROPFIND) ---- */
+
+static int chunk_send(const char *p, unsigned int n)
+{
+	static const char hex[] = "0123456789abcdef";
+	unsigned int l = 0, shift = 0, started = 0;
+
+	if (n + 24 > sizeof(cbuf))
+		return -1;
+	if (!n) {
+		mem_copy(cbuf, "0\r\n\r\n", 5);
+		return u_tcp_srv_send(cbuf, 5);
+	}
+	/* hex size, most significant nibble first */
+	for (shift = 28; ; shift -= 4) {
+		unsigned int d = (n >> shift) & 0xF;
+
+		if (d || started || shift == 0) {
+			cbuf[l++] = hex[d];
+			started = 1;
+		}
+		if (shift == 0)
+			break;
+	}
+	cbuf[l++] = '\r';
+	cbuf[l++] = '\n';
+	mem_copy(cbuf + l, p, n);
+	l += n;
+	cbuf[l++] = '\r';
+	cbuf[l++] = '\n';
+	return u_tcp_srv_send(cbuf, l);
+}
+
+static const char multistatus_open[] =
+	"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+	"<D:multistatus xmlns:D=\"DAV:\">";
+
+static int send_multistatus_begin(void)
+{
+	resp_len = 0;
+	ra("HTTP/1.1 207 Multi-Status\r\n");
+	ra("Server: Nebs OS/0.2.0\r\n");
+	ra("Content-Type: text/xml; charset=\"utf-8\"\r\n");
+	ra("Transfer-Encoding: chunked\r\n");
+	ra("Connection: close\r\nCache-Control: no-store\r\n\r\n");
+	status = 207;
+	if (u_tcp_srv_send(resp, resp_len) != 0)
+		return -1;
+	return chunk_send(multistatus_open, s_len(multistatus_open));
+}
+
+static int end_multistatus(void)
+{
+	static const char close_tag[] = "</D:multistatus>";
+
+	if (chunk_send(close_tag, s_len(close_tag)) != 0)
+		return -1;
+	return chunk_send("", 0);
+}
+
+/* ---- XML building ---- */
+
+static void xa(const char *s)
+{
+	while (*s && xml_len + 1 < sizeof(xml))
+		xml[xml_len++] = *s++;
+	xml[xml_len] = '\0';
+}
+
+static void xa_esc(const char *s)
+{
+	while (*s && xml_len + 6 < sizeof(xml)) {
+		char c = *s++;
+
+		switch (c) {
+		case '&':  xa("&amp;"); break;
+		case '<':  xa("&lt;"); break;
+		case '>':  xa("&gt;"); break;
+		case '"':  xa("&quot;"); break;
+		case '\'': xa("&apos;"); break;
+		default:   xml[xml_len++] = c; break;
+		}
+	}
+	xml[xml_len] = '\0';
+}
+
+static void xa_dec(unsigned int v)
+{
+	char tmp[12];
+	unsigned int i = sizeof(tmp) - 1;
+
+	tmp[i] = '\0';
+	if (!v) {
+		xa("0");
+		return;
+	}
+	while (v && i > 0) {
+		tmp[--i] = (char)('0' + (v % 10));
+		v /= 10;
+	}
+	xa(tmp + i);
+}
+
+/* Percent-encode a path for an href (keep '/' and unreserved characters). */
+static void url_escape(const char *src, char *dst, unsigned int cap)
+{
+	static const char hex[] = "0123456789ABCDEF";
+	unsigned int n = 0;
+
+	while (*src && n + 4 < cap) {
+		unsigned char c = (unsigned char)*src++;
+
+		if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+		    (c >= '0' && c <= '9') || c == '/' || c == '-' ||
+		    c == '_' || c == '.' || c == '~') {
+			dst[n++] = (char)c;
+		} else {
+			dst[n++] = '%';
+			dst[n++] = hex[c >> 4];
+			dst[n++] = hex[c & 0xF];
+		}
+	}
+	dst[n] = '\0';
+}
+
+/* ---- request reader ---- */
+
+static unsigned char *rptr;
+static unsigned int rlen, rpos;
+
+static void rb_init(unsigned int off)
+{
+	rptr = (unsigned char *)hdr + off;
+	rlen = hdr_len - off;
+	rpos = 0;
+}
+
+static int rb_read(unsigned char *dst, unsigned int n)
+{
+	while (n) {
+		unsigned int avail = rlen - rpos;
+
+		if (!avail) {
+			int r = u_tcp_srv_recv(rbuf, sizeof(rbuf), SOCK_MS);
+
+			if (r <= 0)
+				return -1;
+			rptr = (unsigned char *)rbuf;
+			rlen = (unsigned int)r;
+			rpos = 0;
+			continue;
+		}
+		{
+			unsigned int k = avail < n ? avail : n;
+
+			mem_copy(dst, rptr + rpos, k);
+			rpos += k;
+			dst += k;
+			n -= k;
+		}
+		if (u_ticks_ms() - req_start > REQ_TIMEOUT_MS)
+			return -1;
+	}
+	return 0;
+}
+
+static int rb_line(char *out, unsigned int cap)
+{
+	unsigned int n = 0;
+
+	for (;;) {
+		unsigned char c;
+		int r = rb_read(&c, 1);
+
+		if (r != 0)
+			return -1;
+		if (c == '\n')
+			break;
+		if (n + 1 < cap)
+			out[n++] = (char)c;
+		else
+			return -1;
+	}
+	if (n && out[n - 1] == '\r')
+		n--;
+	out[n] = '\0';
+	return (int)n;
+}
+
+static int find_hdr_end(void)
+{
+	unsigned int i;
+
+	if (hdr_len < 4)
+		return -1;
+	for (i = 0; i + 3 < hdr_len; i++)
+		if (hdr[i] == '\r' && hdr[i + 1] == '\n' &&
+		    hdr[i + 2] == '\r' && hdr[i + 3] == '\n')
+			return (int)i;
+	return -1;
+}
+
+/* A URL/file target -> absolute VFS path, no trailing slash, "" for root.
+ * Accepts a path or an absolute URI (MOVE's Destination). */
+static int decode_path(const char *src, char *out, unsigned int cap)
+{
+	const char *p = src;
+	unsigned int o = 0;
+
+	out[0] = '\0';
+	if (p[0] != '/') {
+		const char *q = p;
+
+		while (*q && *q != ':' && *q != '/')
+			q++;
+		if (*q != ':')
+			return -1;
+		q++;
+		while (*q == '/')
+			q++;
+		while (*q && *q != '/')
+			q++;
+		if (!*q) {
+			out[0] = '\0';
+			return 0;
+		}
+		p = q;
+	}
+
+	while (*p && *p != '?' && *p != '#') {
+		char comp[PATH_MAX];
+		unsigned int cl = 0;
+
+		while (*p == '/')
+			p++;
+		while (*p && *p != '/' && *p != '?' && *p != '#') {
+			int c = (unsigned char)*p++;
+
+			if (c == '%') {
+				int hi = p[0] ? hexval(p[0]) : -1;
+				int lo = p[1] ? hexval(p[1]) : -1;
+
+				if (hi < 0 || lo < 0)
+					return -1;
+				c = hi * 16 + lo;
+				p += 2;
+				if (c == 0 || c == '/')
+					return -1;
+			}
+			if (cl + 1 >= sizeof(comp))
+				return -1;
+			comp[cl++] = (char)c;
+		}
+		comp[cl] = '\0';
+
+		if (cl == 0 || (cl == 1 && comp[0] == '.'))
+			continue;
+		if (cl == 2 && comp[0] == '.' && comp[1] == '.') {
+			while (o > 0 && out[o - 1] != '/')
+				o--;
+			if (o > 0)
+				o--;
+			out[o] = '\0';
+			continue;
+		}
+		if (o + 1 + cl + 1 >= cap)
+			return -1;
+		out[o++] = '/';
+		mem_copy(out + o, comp, cl);
+		o += cl;
+		out[o] = '\0';
+	}
+	return 0;
+}
+
+static void trim(char **s)
+{
+	char *p = *s;
+	unsigned int n;
+
+	while (*p == ' ' || *p == '\t')
+		p++;
+	n = s_len(p);
+	while (n && (p[n - 1] == ' ' || p[n - 1] == '\t'))
+		p[--n] = '\0';
+	*s = p;
+}
+
+/* Parse the request line and headers.  Returns 0 or an HTTP error code. */
+static int parse_request(void)
+{
+	char *line = hdr, *next;
+	char *sp1, *sp2;
+
+	/* request line */
+	next = line;
+	while (*next && *next != '\n')
+		next++;
+	if (*next == '\n')
+		*next++ = '\0';
+	if (s_len(line) && line[s_len(line) - 1] == '\r')
+		line[s_len(line) - 1] = '\0';
+
+	sp1 = line;
+	while (*sp1 && *sp1 != ' ')
+		sp1++;
+	if (!*sp1)
+		return 400;
+	*sp1++ = '\0';
+	sp2 = sp1;
+	while (*sp2 && *sp2 != ' ')
+		sp2++;
+	if (!*sp2)
+		return 400;
+	*sp2++ = '\0';
+
+	if (s_len(line) >= sizeof(rq.method))
+		return 414;
+	s_copy(rq.method, line, sizeof(rq.method));
+	if (s_len(sp1) >= sizeof(rq.target))
+		return 414;
+	s_copy(rq.target, sp1, sizeof(rq.target));
+	rq.http11 = s_eq(sp2, "HTTP/1.1");
+
+	if (s_eq(sp1, "*")) {
+		rq.path[0] = '\0';
+	} else if (decode_path(sp1, rq.path, sizeof(rq.path)) != 0) {
+		return 400;
+	}
+
+	/* headers */
+	rq.depth = 1;
+	rq.overwrite = 1;
+	for (line = next; *line; ) {
+		char *end = line;
+		char *colon, *value;
+
+		while (*end && *end != '\n')
+			end++;
+		if (*end == '\n')
+			*end++ = '\0';
+		if (s_len(line) && line[s_len(line) - 1] == '\r')
+			line[s_len(line) - 1] = '\0';
+		if (!line[0])
+			break;
+		colon = line;
+		while (*colon && *colon != ':')
+			colon++;
+		if (!*colon) {
+			line = end;
+			continue;
+		}
+		*colon++ = '\0';
+		value = colon;
+		trim(&value);
+
+		if (s_ieq(line, "Content-Length")) {
+			unsigned int v = 0;
+			char *q = value;
+
+			if (!*q)
+				return 400;
+			while (*q) {
+				if (*q < '0' || *q > '9')
+					return 400;
+				if (v > 0xFFFFFFFFu / 10)
+					return 413;
+				v = v * 10 + (unsigned int)(*q - '0');
+				q++;
+			}
+			rq.have_len = 1;
+			rq.content_len = v;
+		} else if (s_ieq(line, "Transfer-Encoding")) {
+			if (s_contains_ci(value, "chunked"))
+				rq.chunked = 1;
+		} else if (s_ieq(line, "Depth")) {
+			if (value[0] == '0')
+				rq.depth = 0;
+			else if (value[0] == '1')
+				rq.depth = 1;
+			else
+				rq.depth = 1;   /* infinity: serve one level */
+		} else if (s_ieq(line, "Destination")) {
+			if (decode_path(value, rq.dest, sizeof(rq.dest)) == 0)
+				rq.have_dest = 1;
+		} else if (s_ieq(line, "Overwrite")) {
+			rq.overwrite = !(value[0] == 'F' || value[0] == 'f');
+		} else if (s_ieq(line, "Expect")) {
+			if (s_contains_ci(value, "100-continue"))
+				rq.expect_continue = 1;
+		}
+		line = end;
+	}
+	return 0;
+}
+
+static int read_request(void)
+{
+	unsigned int start = u_ticks_ms();
+
+	req_start = start;
+	hdr_len = 0;
+	rq.method[0] = '\0';
+	rq.target[0] = '\0';
+	rq.path[0] = '\0';
+	rq.dest[0] = '\0';
+	rq.http11 = 0;
+	rq.have_len = 0;
+	rq.content_len = 0;
+	rq.chunked = 0;
+	rq.depth = 1;
+	rq.expect_continue = 0;
+	rq.overwrite = 1;
+	rq.have_dest = 0;
+
+	for (;;) {
+		int end = find_hdr_end();
+
+		if (end >= 0) {
+			hdr[end] = '\0';
+			{
+				int r = parse_request();
+
+				if (r != 0)
+					return r;
+			}
+			rb_init((unsigned int)end + 4);
+			return 0;
+		}
+		if (hdr_len >= REQ_MAX)
+			return 431;
+		if (u_ticks_ms() - start > HDR_TIMEOUT_MS)
+			return 408;
+		{
+			int n = u_tcp_srv_recv(hdr + hdr_len,
+					       REQ_MAX - hdr_len, SOCK_MS);
+
+			if (n > 0) {
+				hdr_len += (unsigned int)n;
+			} else if (n == 0 || n == -2) {
+				return hdr_len ? 400 : -2;
+			} else if (hdr_len == 0 &&
+				   u_ticks_ms() - start > 2000u) {
+				/* Speculative connection with no request. */
+				return -2;
+			}
+		}
+	}
+}
+
+/* ---- body reader ---- */
+
+/* 0 ok, -1 I/O/timeout, -2 larger than max.  Handles Content-Length and
+ * chunked transfer encoding. */
+static int read_content(unsigned char *dst, unsigned int max,
+			unsigned int *out_len)
+{
+	unsigned int off = 0;
+
+	*out_len = 0;
+	if (rq.chunked) {
+		for (;;) {
+			char line[32];
+			unsigned int sz = 0, i;
+			int ln = rb_line(line, sizeof(line));
+
+			if (ln <= 0)
+				return -1;
+			for (i = 0; line[i] && line[i] != ';'; i++) {
+				int v = hexval(line[i]);
+
+				if (v < 0)
+					return -1;
+				if (sz > (0xFFFFFFFFu >> 4))
+					return -2;
+				sz = (sz << 4) | (unsigned int)v;
+			}
+			if (sz == 0) {
+				for (;;) {
+					char t[32];
+					int tl = rb_line(t, sizeof(t));
+
+					if (tl < 0)
+						return -1;
+					if (tl == 0)
+						break;
+				}
+				break;
+			}
+			if (off > max || sz > max - off)
+				return -2;
+			if (rb_read(dst + off, sz) != 0)
+				return -1;
+			off += sz;
+			{
+				unsigned char crlf[2];
+
+				if (rb_read(crlf, 2) != 0)
+					return -1;
+				if (crlf[0] != '\r' || crlf[1] != '\n')
+					return -1;
+			}
+		}
+	} else if (rq.have_len) {
+		if (rq.content_len > max)
+			return -2;
+		if (rq.content_len && rb_read(dst, rq.content_len) != 0)
+			return -1;
+		off = rq.content_len;
+	}
+	*out_len = off;
+	return 0;
+}
+
+/* Read and discard a (small) request body so the response does not leave
+ * unread data behind on the connection. */
+static int drain_body(void)
+{
+	unsigned int n;
+	int r = read_content(body, body_max < 65536u ? body_max : 65536u, &n);
+
+	if (r == -2)
+		return send_error(413), -1;
+	if (r != 0)
+		return send_error(400), -1;
+	return 0;
+}
+
+/* Read and discard n bytes (a refused Content-Length body).  Responding 413
+ * while the client is still writing would make it see a reset, which some
+ * gvfs versions treat as a dead mount. */
+static void discard_body(unsigned int n)
+{
+	unsigned char tmp[512];
+
+	while (n) {
+		unsigned int k = n > sizeof(tmp) ? sizeof(tmp) : n;
+
+		if (rb_read(tmp, k) != 0)
+			return;
+		n -= k;
+	}
+}
+
+/* ---- mounts and paths ---- */
+
+static void load_mounts(void)
+{
+	mount_count = 0;
+	while (mount_count < MAX_MOUNTS &&
+	       u_syscall2(SYS_LIST_MOUNTS, (int)mount_count,
+			  (int)&mounts[mount_count]) == 1)
+		mount_count++;
+}
+
+static const char *vpath(const char *p)
+{
+	return p[0] ? p : "/";
+}
+
+/* Split "/mount/rel" into the mount name and the relative path.  Returns 0
+ * for the root, 1 for a mount path, -1 for a malformed path. */
+static int split_mount(const char *p, char *mount, unsigned int cap,
+		       const char **rel)
+{
+	unsigned int i = 1, n = 0;
+
+	if (p[0] != '/')
+		return -1;
+	if (!p[1])
+		return 0;
+	while (p[i] && p[i] != '/') {
+		if (n + 1 >= cap)
+			return -1;
+		mount[n++] = p[i++];
+	}
+	mount[n] = '\0';
+	*rel = p[i] ? p + i + 1 : p + i;
+	return 1;
+}
+
+static struct sys_mount *mount_by_name(const char *name)
+{
+	unsigned int i;
+
+	for (i = 0; i < mount_count; i++)
+		if (s_eq(mounts[i].name, name))
+			return &mounts[i];
+	return 0;
+}
+
+static struct sys_mount *mount_of(const char *p)
+{
+	char name[16];
+	const char *rel;
+
+	if (split_mount(p, name, sizeof(name), &rel) != 1)
+		return 0;
+	return mount_by_name(name);
+}
+
+static int path_ro(const char *p)
+{
+	struct sys_mount *m = mount_of(p);
+
+	return !m || m->ro;
+}
+
+static int path_on_fat(const char *p)
+{
+	struct sys_mount *m = mount_of(p);
+
+	return m && (s_ieq(m->type, "FAT12") || s_ieq(m->type, "FAT16") ||
+		     s_ieq(m->type, "FAT32"));
+}
+
+/* "/share", "/ramfs", "/floppy1": the mount itself, not a file in it. */
+static int is_mount_root(const char *p)
+{
+	char name[16];
+	const char *rel;
+
+	return split_mount(p, name, sizeof(name), &rel) == 1 && rel[0] == '\0';
+}
+
+static const char *base_name(const char *p)
+{
+	const char *b = p, *q = p;
+
+	while (*q) {
+		if (*q == '/')
+			b = q + 1;
+		q++;
+	}
+	return b;
+}
+
+static int join_path(const char *dir, const char *name, char *out,
+		     unsigned int cap)
+{
+	unsigned int n = 0;
+
+	if (dir[0]) {
+		while (dir[n] && n + 1 < cap) {
+			out[n] = dir[n];
+			n++;
+		}
+	}
+	if (n + 1 >= cap)
+		return -1;
+	out[n++] = '/';
+	{
+		unsigned int i = 0;
+
+		while (name[i] && n + 1 < cap)
+			out[n++] = name[i++];
+	}
+	out[n] = '\0';
+	return 0;
+}
+
+static void parent_path(const char *p, char *out, unsigned int cap)
+{
+	int i = (int)s_len(p) - 1;
+
+	while (i >= 0 && p[i] != '/')
+		i--;
+	if (i <= 0) {
+		out[0] = '\0';
+		return;
+	}
+	if ((unsigned int)i >= cap)
+		i = (int)cap - 1;
+	{
+		int j;
+
+		for (j = 0; j < i; j++)
+			out[j] = p[j];
+		out[i] = '\0';
+	}
+}
+
+/* FAT accepts names that fat_name_to_8_3() can represent without silently
+ * truncating: 1..8 base chars, optional 0..3 extension chars. */
+static int fat_char_ok(char c)
+{
+	if (c >= 'A' && c <= 'Z')
+		return 1;
+	if (c >= 'a' && c <= 'z')
+		return 1;
+	if (c >= '0' && c <= '9')
+		return 1;
+	switch (c) {
+	case '!': case '#': case '$': case '%': case '&': case '\'':
+	case '(': case ')': case '-': case '@': case '^': case '_':
+	case '`': case '{': case '}': case '~':
+		return 1;
+	}
+	return 0;
+}
+
+static int fat_name_ok(const char *name)
+{
+	unsigned int i, base = 0, ext = 0;
+	int dot = 0;
+
+	for (i = 0; name[i]; i++) {
+		if (name[i] == '.') {
+			if (dot)
+				return 0;
+			dot = 1;
+			continue;
+		}
+		if (!fat_char_ok(name[i]))
+			return 0;
+		if (dot)
+			ext++;
+		else
+			base++;
+	}
+	if (base == 0 || base > 8 || ext > 3)
+		return 0;
+	return 1;
+}
+
+/* The last component must be representable when creating a FAT name. */
+static int fat_path_ok(const char *p)
+{
+	const char *b = base_name(p);
+
+	return *b && fat_name_ok(b);
+}
+
+static const char *content_type(const char *p)
+{
+	const char *d = p, *q = p;
+
+	while (*q) {
+		if (*q == '.')
+			d = q;
+		q++;
+	}
+	if (!*d)
+		return "application/octet-stream";
+	if (s_ieq(d, ".txt") || s_ieq(d, ".md") || s_ieq(d, ".c") ||
+	    s_ieq(d, ".h") || s_ieq(d, ".log") || s_ieq(d, ".ini"))
+		return "text/plain; charset=utf-8";
+	if (s_ieq(d, ".html") || s_ieq(d, ".htm"))
+		return "text/html; charset=utf-8";
+	if (s_ieq(d, ".png"))
+		return "image/png";
+	if (s_ieq(d, ".jpg") || s_ieq(d, ".jpeg"))
+		return "image/jpeg";
+	if (s_ieq(d, ".gif"))
+		return "image/gif";
+	if (s_ieq(d, ".bmp"))
+		return "image/bmp";
+	if (s_ieq(d, ".tga"))
+		return "image/x-tga";
+	if (s_ieq(d, ".pnm") || s_ieq(d, ".ppm") || s_ieq(d, ".pgm"))
+		return "image/x-portable-anymap";
+	return "application/octet-stream";
+}
+
+static int http_from_vfs(int r)
+{
+	switch (r) {
+	case SYS_EROFS:  return 403;
+	case SYS_ENOENT: return 404;
+	case SYS_ENODEV: return 404;
+	case SYS_ENOFS:  return 404;
+	case SYS_EINVAL: return 409;
+	case SYS_ENOSPC: return 507;
+	case SYS_EWRITE: return 507;
+	default:         return 500;
+	}
+}
+
+/* ---- WebDAV helpers ---- */
+
+static int emit_prop(const char *p, int is_dir, unsigned int size,
+		     const char *display)
+{
+	char href[PATH_MAX * 3];
+
+	url_escape(p[0] ? p : "/", href, sizeof(href));
+	if (is_dir && href[s_len(href) - 1] != '/') {
+		unsigned int n = s_len(href);
+
+		if (n + 1 < sizeof(href)) {
+			href[n++] = '/';
+			href[n] = '\0';
+		}
+	}
+	xml_len = 0;
+	xa("<D:response><D:href>");
+	xa_esc(href);
+	xa("</D:href><D:propstat><D:prop><D:resourcetype>");
+	if (is_dir)
+		xa("<D:collection/>");
+	xa("</D:resourcetype>");
+	if (!is_dir) {
+		xa("<D:getcontentlength>");
+		xa_dec(size);
+		xa("</D:getcontentlength><D:getcontenttype>");
+		xa_esc(content_type(p));
+		xa("</D:getcontenttype>");
+	}
+	xa("<D:displayname>");
+	xa_esc(display);
+	xa("</D:displayname>");
+	xa("<D:getlastmodified>Thu, 01 Jan 2026 00:00:00 GMT</D:getlastmodified>");
+	xa("</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat>");
+	xa("</D:response>");
+	return chunk_send(xml, xml_len);
+}
+
+static int list_child(unsigned int index, const char *dir, char *out,
+		      int *is_dir, unsigned int *size)
+{
+	struct sys_dirent d;
+	char disp[64];
+
+	if (u_syscall3(SYS_LIST_DIR, (int)vpath(dir), (int)index,
+		       (int)&d) != 1)
+		return 0;
+	if (d.raw_83)
+		u_fat_name(d.name, disp, sizeof(disp));
+	else
+		s_copy(disp, d.name, sizeof(disp));
+	if (!disp[0])
+		return 0;
+	if (join_path(dir, disp, out, PATH_MAX) != 0)
+		return 0;
+	*is_dir = (int)d.is_dir;
+	*size = d.size;
+	return 1;
+}
+
+/* ---- method handlers ---- */
+
+static void do_options2(void)
+{
+	resp_len = 0;
+	ra("HTTP/1.1 200 OK\r\nServer: Nebs OS/0.2.0\r\n");
+	ra("DAV: 1, 2\r\nMS-Author-Via: DAV\r\n");
+	ra("Allow: OPTIONS, GET, HEAD, PUT, DELETE, MKCOL, PROPFIND, "
+	   "PROPPATCH, MOVE, LOCK, UNLOCK\r\n");
+	ra("Connection: close\r\nCache-Control: no-store\r\n");
+	ra("Content-Length: 0\r\n\r\n");
+	status = 200;
+	u_tcp_srv_send(resp, resp_len);
+}
+
+static void do_get(int head)
+{
+	struct sys_stat st;
+	unsigned int off;
+
+	if (!rq.path[0]) {
+		send_error(405);
+		return;
+	}
+	if (u_stat(vpath(rq.path), &st) != 0) {
+		send_error(404);
+		return;
+	}
+	if (st.is_dir) {
+		send_error(405);
+		return;
+	}
+	if (st.size > body_max) {
+		send_error(413);
+		return;
+	}
+	{
+		int n = u_syscall3(SYS_READ_FILE, (int)rq.path, (int)body,
+				   (int)body_max);
+
+		if (n < 0) {
+			send_error(http_from_vfs(n));
+			return;
+		}
+		if (send_headers(200, "OK", content_type(rq.path),
+				 (unsigned int)n) != 0)
+			return;
+		if (head)
+			return;
+		for (off = 0; off < (unsigned int)n; ) {
+			unsigned int k = (unsigned int)n - off;
+
+			if (k > 65536u)
+				k = 65536u;
+			if (u_tcp_srv_send(body + off, k) != 0)
+				return;
+			off += k;
+		}
+	}
+}
+
+static void do_put(void)
+{
+	struct sys_stat st;
+	char parent[PATH_MAX];
+	unsigned int len;
+	int existed = 0, r;
+
+	if (!rq.path[0]) {
+		send_error(403);
+		return;
+	}
+	if (!rq.have_len && !rq.chunked) {
+		send_error(411);
+		return;
+	}
+	if (rq.have_len && rq.content_len > body_max) {
+		/* Drain a body that is already on the wire (not when the client
+		 * is still waiting for 100 Continue), then refuse cleanly. */
+		if (!rq.expect_continue &&
+		    rq.content_len <= 64u * 1024u * 1024u)
+			discard_body(rq.content_len);
+		send_error(413);
+		return;
+	}
+	if (path_ro(rq.path)) {
+		send_error(403);
+		return;
+	}
+	if (path_on_fat(rq.path) && !fat_path_ok(rq.path)) {
+		send_refuse(409, "FAT name is not 8.3 (use /share)");
+		return;
+	}
+
+	parent_path(rq.path, parent, sizeof(parent));
+	if (parent[0]) {
+		if (u_stat(vpath(parent), &st) != 0 || !st.is_dir) {
+			send_refuse(409, "PUT parent directory is missing");
+			return;
+		}
+	}
+	if (u_stat(vpath(rq.path), &st) == 0) {
+		if (st.is_dir) {
+			send_refuse(409, "PUT target is a directory");
+			return;
+		}
+		existed = 1;
+	}
+
+	if (rq.expect_continue && rq.http11)
+		u_tcp_srv_send("HTTP/1.1 100 Continue\r\n\r\n", 25);
+
+	r = read_content(body, body_max, &len);
+	if (r == -2) {
+		send_error(413);
+		return;
+	}
+	if (r != 0) {
+		send_error(400);
+		return;
+	}
+	r = u_syscall3(SYS_WRITE_FILE, (int)rq.path, (int)body, (int)len);
+	if (r != 0) {
+		u_puts("websrv: write failed code ");
+		u_putdec((unsigned int)-r);
+		u_putc('\n');
+		send_error(http_from_vfs(r));
+		return;
+	}
+	send_empty(existed ? 204 : 201);
+}
+
+static void do_mkcol(void)
+{
+	struct sys_stat st;
+	char parent[PATH_MAX];
+	int r;
+
+	if (!rq.path[0] || path_ro(rq.path)) {
+		send_error(403);
+		return;
+	}
+	if (path_on_fat(rq.path) && !fat_path_ok(rq.path)) {
+		send_refuse(409, "MKCOL FAT name is not 8.3 (use /share)");
+		return;
+	}
+	if (u_stat(vpath(rq.path), &st) == 0) {
+		send_error(405);
+		return;
+	}
+	parent_path(rq.path, parent, sizeof(parent));
+	if (parent[0]) {
+		if (u_stat(vpath(parent), &st) != 0 || !st.is_dir) {
+			send_refuse(409, "MKCOL parent directory is missing");
+			return;
+		}
+	}
+	r = u_syscall1(SYS_MKDIR, (int)rq.path);
+	if (r != 0) {
+		u_puts("websrv: mkdir failed code ");
+		u_putdec((unsigned int)-r);
+		u_putc('\n');
+		send_error(http_from_vfs(r));
+		return;
+	}
+	send_empty(201);
+}
+
+static int delete_tree(const char *p, unsigned int depth)
+{
+	struct sys_stat st;
+	unsigned int i;
+	int r;
+
+	if (depth > 8)
+		return SYS_EINVAL;
+	if (u_stat(vpath(p), &st) != 0)
+		return SYS_ENOENT;
+	if (st.is_dir) {
+		for (i = 0; ; i++) {
+			char child[PATH_MAX];
+			int is_dir;
+			unsigned int size;
+
+			if (!list_child(i, p, child, &is_dir, &size))
+				break;
+			r = delete_tree(child, depth + 1);
+			if (r != 0)
+				return r;
+		}
+		return u_syscall1(SYS_RMDIR, (int)p);
+	}
+	return u_syscall1(SYS_UNLINK, (int)p);
+}
+
+static void do_delete(void)
+{
+	int r;
+
+	if (!rq.path[0] || is_mount_root(rq.path) || path_ro(rq.path)) {
+		send_error(403);
+		return;
+	}
+	r = delete_tree(rq.path, 0);
+	if (r != 0) {
+		send_error(http_from_vfs(r));
+		return;
+	}
+	send_empty(204);
+}
+
+static void do_move(void)
+{
+	struct sys_stat st, dst;
+	unsigned int len;
+	int existed = 0, r;
+
+	if (!rq.path[0] || path_ro(rq.path)) {
+		send_error(403);
+		return;
+	}
+	if (!rq.have_dest || !rq.dest[0]) {
+		send_error(400);
+		return;
+	}
+	if (s_eq(rq.path, rq.dest)) {
+		send_empty(204);
+		return;
+	}
+	if (path_ro(rq.dest)) {
+		send_error(403);
+		return;
+	}
+	if (path_on_fat(rq.dest) && !fat_path_ok(rq.dest)) {
+		send_refuse(409, "MOVE destination FAT name is not 8.3");
+		return;
+	}
+	if (u_stat(vpath(rq.path), &st) != 0) {
+		send_error(404);
+		return;
+	}
+	if (st.is_dir) {
+		send_error(501);   /* directory renames are not supported */
+		return;
+	}
+	if (st.size > body_max) {
+		send_error(413);
+		return;
+	}
+	{
+		char parent[PATH_MAX];
+
+		parent_path(rq.dest, parent, sizeof(parent));
+		if (parent[0] &&
+		    (u_stat(vpath(parent), &dst) != 0 || !dst.is_dir)) {
+			send_refuse(409, "MOVE destination parent is missing");
+			return;
+		}
+	}
+	if (u_stat(vpath(rq.dest), &dst) == 0) {
+		if (dst.is_dir) {
+			send_refuse(409, "MOVE destination is a directory");
+			return;
+		}
+		if (!rq.overwrite) {
+			send_error(412);
+			return;
+		}
+		existed = 1;
+	}
+	r = u_syscall3(SYS_READ_FILE, (int)rq.path, (int)body,
+		       (int)body_max);
+	if (r < 0) {
+		send_error(http_from_vfs(r));
+		return;
+	}
+	len = (unsigned int)r;
+	r = u_syscall3(SYS_WRITE_FILE, (int)rq.dest, (int)body, (int)len);
+	if (r != 0) {
+		send_error(http_from_vfs(r));
+		return;
+	}
+	r = u_syscall1(SYS_UNLINK, (int)rq.path);
+	if (r != 0 && r != SYS_ENOENT) {
+		send_error(http_from_vfs(r));
+		return;
+	}
+	send_empty(existed ? 204 : 201);
+}
+
+static void do_propfind(void)
+{
+	struct sys_stat st;
+	unsigned int i;
+
+	if (drain_body() != 0)
+		return;
+
+	if (!rq.path[0]) {
+		if (send_multistatus_begin() != 0)
+			return;
+		if (emit_prop("", 1, 0, "/") != 0) {
+			end_multistatus();
+			return;
+		}
+		if (rq.depth) {
+			for (i = 0; i < mount_count; i++) {
+				char mpath[32];
+
+				if (join_path("", mounts[i].name, mpath,
+					      sizeof(mpath)) != 0)
+					continue;
+				if (emit_prop(mpath, 1, 0, mounts[i].name) != 0)
+					break;
+			}
+		}
+		end_multistatus();
+		return;
+	}
+
+	if (u_stat(vpath(rq.path), &st) != 0) {
+		send_error(404);
+		return;
+	}
+	if (send_multistatus_begin() != 0)
+		return;
+	if (emit_prop(rq.path, st.is_dir, st.size, base_name(rq.path)) != 0) {
+		end_multistatus();
+		return;
+	}
+	if (st.is_dir && rq.depth) {
+		for (i = 0; ; i++) {
+			char child[PATH_MAX];
+			int is_dir;
+			unsigned int size;
+
+			if (!list_child(i, rq.path, child, &is_dir, &size))
+				break;
+			if (emit_prop(child, is_dir, size,
+				      base_name(child)) != 0)
+				break;
+		}
+	}
+	end_multistatus();
+}
+
+static void do_proppatch(void)
+{
+	char href[PATH_MAX * 3];
+	unsigned int n = 0;
+
+	if (drain_body() != 0)
+		return;
+	url_escape(rq.path[0] ? rq.path : "/", href, sizeof(href));
+	xml_len = 0;
+	xa("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
+	xa("<D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>");
+	xa_esc(href);
+	xa("</D:href><D:propstat><D:prop/>"
+	   "<D:status>HTTP/1.1 200 OK</D:status></D:propstat>"
+	   "</D:response></D:multistatus>");
+	n = xml_len;
+	send_body(207, "Multi-Status", "text/xml; charset=\"utf-8\"",
+		  xml, n);
+}
+
+static void do_lock(void)
+{
+	static const char lockbody[] =
+		"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+		"<D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock>"
+		"<D:locktype><D:write/></D:locktype>"
+		"<D:depth>infinity</D:depth>"
+		"<D:timeout>Second-3600</D:timeout>"
+		"<D:locktoken><D:href>opaquelocktoken:nebs</D:href>"
+		"</D:locktoken></D:activelock></D:lockdiscovery></D:prop>";
+
+	(void)drain_body();
+	extra_hdrs = "Lock-Token: <opaquelocktoken:nebs>";
+	send_body(200, "OK", "text/xml; charset=\"utf-8\"",
+		  lockbody, sizeof(lockbody) - 1);
+}
+
+/* ---- request dispatch ---- */
+
+static void serve(void)
+{
+	int r = read_request();
+
+	status = 0;
+	extra_hdrs = 0;
+	if (r == -2)
+		return;
+	if (r != 0) {
+		send_error(r);
+		u_puts("websrv: bad request (");
+		u_putdec((unsigned int)r);
+		u_puts(")\n");
+		return;
+	}
+
+	load_mounts();
+
+	if (s_eq(rq.method, "OPTIONS"))
+		do_options2();
+	else if (s_eq(rq.method, "GET"))
+		do_get(0);
+	else if (s_eq(rq.method, "HEAD"))
+		do_get(1);
+	else if (s_eq(rq.method, "PUT"))
+		do_put();
+	else if (s_eq(rq.method, "DELETE"))
+		do_delete();
+	else if (s_eq(rq.method, "MKCOL"))
+		do_mkcol();
+	else if (s_eq(rq.method, "PROPFIND"))
+		do_propfind();
+	else if (s_eq(rq.method, "PROPPATCH"))
+		do_proppatch();
+	else if (s_eq(rq.method, "MOVE"))
+		do_move();
+	else if (s_eq(rq.method, "LOCK"))
+		do_lock();
+	else if (s_eq(rq.method, "UNLOCK")) {
+		(void)drain_body();
+		send_empty(204);
+	} else {
+		(void)drain_body();
+		send_error(405);
+	}
+
+	if (status) {
+		u_puts("websrv: ");
+		u_puts(rq.method);
+		u_putc(' ');
+		u_puts(rq.path[0] ? rq.path : "/");
+		u_puts(" -> ");
+		u_putdec((unsigned int)status);
+		u_putc('\n');
+	}
+}
+
+static unsigned int parse_port(const char *arg)
+{
+	unsigned int p = 0;
+
+	if (!arg)
+		return 0;
+	while (*arg) {
+		if (*arg < '0' || *arg > '9')
+			return 0;
+		p = p * 10 + (unsigned int)(*arg - '0');
+		if (p > 65535)
+			return 0;
+		arg++;
+	}
+	return p;
+}
+
+void _start(const char *arg)
+{
+	unsigned int port = parse_port(arg);
+	unsigned char ip[4];
+
+	if (!port)
+		port = 8080;
+
+	if (u_syscall0(SYS_NET_ACQUIRE) != 0) {
+		u_puts("websrv: network busy (another command owns the NIC)\n");
+		u_exit(1);
+	}
+	u_syscall1(SYS_NET_GET_IP, (int)ip);
+
+	body = u_mem_alloc(BODY_MAX);
+	body_max = BODY_MAX;
+	if (!body) {
+		body = u_mem_alloc(BODY_FALLBACK);
+		body_max = BODY_FALLBACK;
+	}
+	if (!body) {
+		u_puts("websrv: no memory for the transfer buffer\n");
+		u_syscall0(SYS_NET_RELEASE);
+		u_exit(1);
+	}
+
+	load_mounts();
+	if (u_tcp_listen(port) != 0) {
+		u_puts("websrv: cannot listen\n");
+		u_syscall0(SYS_NET_RELEASE);
+		u_exit(1);
+	}
+
+	u_puts("websrv: transfer buffer ");
+	u_putdec(body_max / 1024u);
+	u_puts(" KB\n");
+
+	u_puts("websrv: serving http://");
+	u_put_ip(ip);
+	u_putc(':');
+	u_putdec(port);
+	u_puts("/ (WebDAV: dav://");
+	u_put_ip(ip);
+	u_putc(':');
+	u_putdec(port);
+	u_puts("/)\n");
+
+	for (;;) {
+		int r = u_tcp_accept();
+
+		if (r == 1) {
+			unsigned char peer[4];
+			unsigned int pport = 0;
+
+			if (u_tcp_peer(peer, &pport) == 0) {
+				u_puts("websrv: connection from ");
+				u_put_ip(peer);
+				u_putc(':');
+				u_putdec(pport);
+				u_putc('\n');
+			}
+			serve();
+			u_tcp_srv_close();
+			continue;
+		}
+		if (r == -3) {
+			u_puts("websrv: netkexec requested, stopping\n");
+			break;
+		}
+		if (r == -2)
+			break;
+		u_sleep_ms(2);
+	}
+
+	u_tcp_srv_close();
+	u_syscall0(SYS_NET_RELEASE);
+	u_puts("websrv: stopped\n");
+	u_exit(0);
+}

+ 101 - 27
ucmd_wm.c

@@ -32,6 +32,7 @@ static unsigned int resize_mx, resize_my, resize_ow, resize_oh;
 static unsigned int prev_buttons;
 static int full_redraw = 1;
 static unsigned int bar_kexec_busy, bar_kexec_progress, bar_kexec_total;
+static int bar_temp_c = -1;
 
 static unsigned int rgb16(unsigned int r, unsigned int g, unsigned int b)
 {
@@ -53,6 +54,46 @@ static void fill_clip(int x, int y, unsigned int w, unsigned int h,
 			   (unsigned int)(y1 - y0), rgb);
 }
 
+static void bar_button(unsigned int x, unsigned int y, unsigned int w,
+		       unsigned int h, const char *label)
+{
+	unsigned int n = 0;
+
+	usurf_fill(&screen, x, y, w, h, 0x963CD2u);
+	while (label[n])
+		n++;
+	usurf_text(&screen, (int)(x + (w - n * 8) / 2), (int)(y + 3),
+		   label, COL_WHITE, 0, 0, fbw, WM_BAR_H);
+}
+
+static unsigned int temp_color(int c)
+{
+	if (c >= 80)
+		return 0xFF5050u;
+	if (c >= 60)
+		return 0xFFD250u;
+	return 0x55FF55u;
+}
+
+/* "CPU 43C" (no libc printf here). */
+static unsigned int temp_text(char *b, int c)
+{
+	unsigned int n = 0, v = (unsigned int)c;
+
+	b[n++] = 'C';
+	b[n++] = 'P';
+	b[n++] = 'U';
+	b[n++] = ' ';
+	if (v >= 100)
+		b[n++] = (char)('0' + (v / 100) % 10);
+	if (v >= 10)
+		b[n++] = (char)('0' + (v / 10) % 10);
+	b[n++] = (char)('0' + v % 10);
+	b[n++] = 'C';
+	b[n] = '\0';
+	return n;
+}
+
 static void draw_bar(void)
 {
 	char dt[48];
@@ -61,21 +102,15 @@ static void draw_bar(void)
 	usurf_fill(&screen, 0, 0, fbw, WM_BAR_H, COL_BG);
 	usurf_text(&screen, 4, 5, OS_NAME " v" OS_VERSION, COL_BANNER,
 		   0, 0, fbw, WM_BAR_H);
-	usurf_fill(&screen, WM_BTN_X, WM_BTN_Y, WM_BTN_W, WM_BTN_H, 0x963CD2u);
-	usurf_text(&screen, WM_BTN_X + 4, WM_BTN_Y + 3, "+ New", COL_WHITE,
-		   0, 0, fbw, WM_BAR_H);
-	usurf_fill(&screen, WM_BTN_CLOCK_X, WM_BTN_CLOCK_Y, WM_BTN_CLOCK_W,
-		   WM_BTN_CLOCK_H, 0x963CD2u);
-	usurf_text(&screen, WM_BTN_CLOCK_X + 4, WM_BTN_CLOCK_Y + 3, "+ Clock",
-		   COL_WHITE, 0, 0, fbw, WM_BAR_H);
-	usurf_fill(&screen, WM_BTN_COLORS_X, WM_BTN_COLORS_Y, WM_BTN_COLORS_W,
-		   WM_BTN_COLORS_H, 0x963CD2u);
-	usurf_text(&screen, WM_BTN_COLORS_X + 4, WM_BTN_COLORS_Y + 3, "+ Colors",
-		   COL_WHITE, 0, 0, fbw, WM_BAR_H);
-	usurf_fill(&screen, WM_BTN_FILES_X, WM_BTN_FILES_Y, WM_BTN_FILES_W,
-		   WM_BTN_FILES_H, 0x963CD2u);
-	usurf_text(&screen, WM_BTN_FILES_X + 4, WM_BTN_FILES_Y + 3, "Files",
-		   COL_WHITE, 0, 0, fbw, WM_BAR_H);
+	bar_button(WM_BTN_X, WM_BTN_Y, WM_BTN_W, WM_BTN_H, "New");
+	bar_button(WM_BTN_CLOCK_X, WM_BTN_CLOCK_Y, WM_BTN_CLOCK_W,
+		   WM_BTN_CLOCK_H, "Clock");
+	bar_button(WM_BTN_COLORS_X, WM_BTN_COLORS_Y, WM_BTN_COLORS_W,
+		   WM_BTN_COLORS_H, "Colors");
+	bar_button(WM_BTN_FILES_X, WM_BTN_FILES_Y, WM_BTN_FILES_W,
+		   WM_BTN_FILES_H, "Files");
+	bar_button(WM_BTN_MINES_X, WM_BTN_MINES_Y, WM_BTN_MINES_W,
+		   WM_BTN_MINES_H, "Mines");
 
 	/* Rainbow separator (same y as the kernel's old bar). */
 	for (x = 0; x < fbw; x++) {
@@ -112,12 +147,28 @@ static void draw_bar(void)
 		dt[n] = '\0';
 		usurf_text(&screen, (int)fbw - (int)n * 8 - 4, 5, dt,
 			   0xFFC864u, 0, 0, fbw, WM_BAR_H);
-	} else if (u_rtc_datetime(dt, sizeof(dt)) == 0) {
-		n = 0;
-		while (dt[n] && n < sizeof(dt) - 1)
-			n++;
-		usurf_text(&screen, (int)fbw - (int)n * 8 - 4, 5, dt,
-			   COL_BANNER, 0, 0, fbw, WM_BAR_H);
+	} else {
+		unsigned int clock_chars = 0;
+
+		if (u_rtc_datetime(dt, sizeof(dt)) == 0) {
+			n = 0;
+			while (dt[n] && n < sizeof(dt) - 1)
+				n++;
+			usurf_text(&screen, (int)fbw - (int)n * 8 - 4, 5, dt,
+				   COL_BANNER, 0, 0, fbw, WM_BAR_H);
+			clock_chars = n;
+		}
+		if (bar_temp_c >= 0) {
+			char tb[12];
+			unsigned int tn = temp_text(tb, bar_temp_c);
+			int tx = (int)fbw - 4 - (int)clock_chars * 8 -
+				 (clock_chars ? 8 : 0) - (int)tn * 8;
+
+			if (tx >= WM_BTN_MINES_X + (int)WM_BTN_MINES_W + 4)
+				usurf_text(&screen, tx, 5, tb,
+					   temp_color(bar_temp_c), 0, 0,
+					   fbw, WM_BAR_H);
+		}
 	}
 }
 
@@ -328,14 +379,33 @@ static void do_update(struct wm_status *st)
 			}
 		}
 	}
-	if (u_rtc_datetime(dt, sizeof(dt)) == 0) {
-		for (i = 0; i < sizeof(dt); i++)
-			if (dt[i] != last_dt[i]) {
+	/* The RTC is slow (CMOS polling) and the temperature only changes
+	 * once a second; query both at 1 Hz instead of every 10 ms. */
+	{
+		static unsigned int last_rtc_ms;
+		unsigned int now_ms = u_ticks_ms();
+
+		if (full_redraw || now_ms - last_rtc_ms >= 1000) {
+			last_rtc_ms = now_ms;
+			if (u_rtc_datetime(dt, sizeof(dt)) == 0) {
 				for (i = 0; i < sizeof(dt); i++)
-					last_dt[i] = dt[i];
-				bar_dirty = 1;
-				break;
+					if (dt[i] != last_dt[i]) {
+						for (i = 0; i < sizeof(dt); i++)
+							last_dt[i] = dt[i];
+						bar_dirty = 1;
+						break;
+					}
 			}
+			{
+				struct sys_cputemp ct;
+
+				if (u_cpu_temp(&ct) == 0 &&
+				    ct.temp_c != bar_temp_c) {
+					bar_temp_c = ct.temp_c;
+					bar_dirty = 1;
+				}
+			}
+		}
 	}
 	if (full_redraw) {
 		if (u_wm_begin() != 0) {
@@ -459,6 +529,10 @@ static void handle_mouse(struct wm_status *st)
 			   mx < WM_BTN_FILES_X + WM_BTN_FILES_W &&
 			   my < WM_BTN_FILES_Y + WM_BTN_FILES_H) {
 			spawn_app("/ramfs/bin/files");
+		} else if (mx >= WM_BTN_MINES_X && my >= WM_BTN_MINES_Y &&
+			   mx < WM_BTN_MINES_X + WM_BTN_MINES_W &&
+			   my < WM_BTN_MINES_Y + WM_BTN_MINES_H) {
+			spawn_app("/ramfs/bin/mines");
 		} else {
 			int idx = window_at(mx, my);
 

+ 25 - 1
vfs.c

@@ -6,6 +6,7 @@
 #include "fatdetect.h"
 #include "io.h"
 #include "ramfs.h"
+#include "share.h"
 
 vfs_mount_t vfs_mounts[VFS_MAX_MOUNTS];
 unsigned int vfs_mount_count;
@@ -239,6 +240,7 @@ static void fat_list_cb(const char *name, int is_dir, unsigned int size)
 	fat_list_out->name[11] = '\0';
 	fat_list_out->size = size;
 	fat_list_out->is_dir = (unsigned int)is_dir;
+	fat_list_out->raw_83 = 1;
 	fat_list_done = 1;
 	fat_list_seen++;
 }
@@ -401,6 +403,7 @@ static int ramfs_op_list_dir(struct vfs_mount *m, const char *path,
 	copy_bounded(out->name, e.name, sizeof(out->name));
 	out->size = e.size;
 	out->is_dir = e.is_dir;
+	out->raw_83 = 0;
 	return 1;
 }
 
@@ -480,6 +483,25 @@ void vfs_refresh_ramfs(void)
 		m->total_sectors = (ramfs_pack_size() + 511u) / 512u;
 }
 
+/* Writable RAM store for network uploads.  Unlike the pack ramfs it is not a
+ * block device and its contents survive vfs_mount_all() refreshes. */
+void vfs_mount_share(void)
+{
+	vfs_mount_t *m;
+
+	if (share_init() != 0)
+		return;
+	m = mount_slot("share");
+	if (!m)
+		return;
+	m->ops = &share_ops;
+	m->ro = 0;
+	m->total_sectors = SHARE_MAX_BYTES / 512u;
+	copy_bounded(m->type, "share", sizeof(m->type));
+	m->label[0] = '\0';
+	vfs_mount_count++;
+}
+
 static void part_name(char *out, const char *base, unsigned int idx)
 {
 	unsigned int i = 0;
@@ -561,8 +583,10 @@ void vfs_mount_all(void)
 		mount_device(&blk_devs[i], buf);
 
 	/* The ramfs is not a block device; keep it mounted across a refresh
-	 * (the `storage` command calls vfs_mount_all()). */
+	 * (the `storage` command calls vfs_mount_all()).  /share is likewise
+	 * independent of the block devices. */
 	vfs_mount_ramfs();
+	vfs_mount_share();
 }
 
 static int device_is_mounted(const char *dev)

+ 8 - 3
vfs.h

@@ -18,12 +18,13 @@ struct vfs_file {
 	unsigned int size;
 };
 
-/* One directory entry: `name` is the raw 8.3 field for FAT (space padded) or
- * the plain file name for ramfs. */
+/* One directory entry.  `name` is the raw 8.3 field for FAT (space padded,
+ * `raw_83` set) or the plain file name for the name-string filesystems. */
 struct vfs_dirent {
-	char name[12];
+	char name[64];
 	unsigned int size;
 	unsigned int is_dir;
+	unsigned int raw_83;
 };
 
 /* Per-filesystem error codes (0 = success; the read/list calls additionally
@@ -32,6 +33,7 @@ struct vfs_dirent {
 #define VFS_ENOENT (-2)
 #define VFS_EINVAL (-3)
 #define VFS_EROFS  (-4)
+#define VFS_ENOSPC (-5)
 
 /* Per-filesystem operations.  Paths are relative to the mount (no leading
  * '/'); "" is the mount root.  Implementations never print; list_dir returns
@@ -78,6 +80,9 @@ void vfs_remount_device(blk_dev_t *d);
 /* Mount the command pack (ramfs) at /ramfs; no-op when no pack is loaded. */
 void vfs_mount_ramfs(void);
 
+/* Mount the writable in-memory /share store (no-op if it cannot be set up). */
+void vfs_mount_share(void);
+
 /* Update the ramfs mount's reported size after ramfs_replace(). */
 void vfs_refresh_ramfs(void);
 

+ 35 - 1
wm.c

@@ -19,6 +19,7 @@
 #include "rtc.h"
 #include "serial.h"
 #include "sys_gfx.h"
+#include "thermal.h"
 #include "timer.h"
 #include "version.h"
 #include "vga.h"
@@ -1561,7 +1562,8 @@ static void wm_draw_bar(void)
 
 	/* "+ New" button: purple box, white text. */
 	vga_fill_rect(WM_BTN_X, WM_BTN_Y, WM_BTN_W, WM_BTN_H, 150, 60, 210);
-	fbtext_draw_string_xy(WM_BTN_X + 4, WM_BTN_Y + 3, "+ New", 255, 255, 255, 1);
+	fbtext_draw_string_xy(WM_BTN_X + (WM_BTN_W - 3 * 8) / 2, WM_BTN_Y + 3,
+			      "New", 255, 255, 255, 1);
 
 	if (kexec_busy) {
 		/* Kexec progress, in place of the clock. */
@@ -1577,9 +1579,41 @@ static void wm_draw_bar(void)
 		buf[n] = '\0';
 		fbtext_draw_string_xy(fbw - n * 8 - 4, 5, buf, 255, 200, 100, 0);
 	} else {
+		int temp = thermal_max_c();
+
 		/* Live clock (light green, right-aligned). */
 		rtc_read_datetime(dt);
 		fbtext_draw_string_xy(fbw - 19 * 8 - 4, 5, dt, 85, 255, 85, 0);
+		if (temp >= 0) {
+			char tb[12];
+			unsigned int tn = 0;
+			unsigned int v = (unsigned int)temp;
+			int x;
+
+			tb[tn++] = 'C';
+			tb[tn++] = 'P';
+			tb[tn++] = 'U';
+			tb[tn++] = ' ';
+			if (v >= 100)
+				tb[tn++] = (char)('0' + (v / 100) % 10);
+			if (v >= 10)
+				tb[tn++] = (char)('0' + (v / 10) % 10);
+			tb[tn++] = (char)('0' + v % 10);
+			tb[tn++] = 'C';
+			tb[tn] = '\0';
+			x = (int)fbw - 19 * 8 - 4 - 8 - (int)tn * 8;
+			if (x >= WM_BTN_X + (int)WM_BTN_W + 4) {
+				if (temp >= 80)
+					fbtext_draw_string_xy((unsigned int)x, 5, tb,
+							      255, 80, 80, 0);
+				else if (temp >= 60)
+					fbtext_draw_string_xy((unsigned int)x, 5, tb,
+							      255, 210, 80, 0);
+				else
+					fbtext_draw_string_xy((unsigned int)x, 5, tb,
+							      85, 255, 85, 0);
+			}
+		}
 	}
 
 	/* Rainbow separator. */

+ 4 - 0
wm_abi.h

@@ -26,6 +26,10 @@
 #define WM_BTN_FILES_Y WM_BTN_Y
 #define WM_BTN_FILES_W 64
 #define WM_BTN_FILES_H WM_BTN_H
+#define WM_BTN_MINES_X (WM_BTN_FILES_X + WM_BTN_FILES_W + WM_BTN_GAP)
+#define WM_BTN_MINES_Y WM_BTN_Y
+#define WM_BTN_MINES_W 56
+#define WM_BTN_MINES_H WM_BTN_H
 #define WM_TITLE_H 22
 #define WM_CLOSE_W 16