1
0

5 Коммиты 4996d78353 ... 828cba05ea

Автор SHA1 Сообщение Дата
  Johannes Zellner 828cba05ea ngui: share one corner radius and fix its rounding 5 дней назад
  Johannes Zellner f3def28d01 mm: raise the physical ceiling to 1 GB, move the frame bitmap out of BSS 5 дней назад
  Johannes Zellner ed2d7f479a Follow the primary plane's gamma in the Intel cursor 5 дней назад
  Johannes Zellner da99a8231b ngui: hide scrollbars until the pointer enters a pane 5 дней назад
  Johannes Zellner a2c9570412 browser: fix unfocusable form fields and the external-link icon 5 дней назад

+ 44 - 23
AGENTS.md

@@ -138,10 +138,10 @@ make clean
   compat ladder without a display; `--keys 'clo{down}{enter}'` types into
   the headless window (100 ms per key from 300 ms after the first frame;
   `{enter} {esc} {tab} {bs} {del} {up} {down} {left} {right} {ctrl-l}
-  {wait}`).  It needs the multilib `lib32-sdl3`,
+  {wait}`, and `{click:X,Y}` for a left click at canvas coordinates).  It needs the multilib `lib32-sdl3`,
   `lib32-wayland` and `lib32-libxkbcommon`; host sockets replace the NebOS TCP
   stack and the kernel/WM paths are not exercised.
-- QEMU guests default to 512 MB (`QEMU_MEM`, e.g. `make run QEMU_MEM=1G`),
+- QEMU guests default to 1 GB (`QEMU_MEM`, e.g. `make run QEMU_MEM=512M`),
   matching `MM_MAX_PHYS` in `phys.h`; all run and UEFI targets pass `-m`.
 - The command pack is the system rootfs: `cmds.pack` (NBPAK1), gzip-compressed
   to `cmds_pack_gz.bin`, wrapped by `mkrootfs` with a one-sector `NBROOT1`
@@ -251,7 +251,7 @@ and `make net-dev`/`kernel-net-dev` reload over the network.  `bootlog save
 5. **UEFI (`boot/efi/`)** — an x86-64 PE32+ `BOOTX64.EFI` loads from the ESP. It
    picks a GOP mode, converts `GetMemoryMap` into the E820 map at `0x1000`,
    stages `kernel.bin` below 4 GB, allocates a loader-data buffer below the
-   512 MB identity window (above the low 1 MB) for the embedded gz rootfs
+   1 GB identity window (above the low 1 MB) for the embedded gz rootfs
    and copies it there, fills
    `0x500` (boot info) and `0x600` (framebuffer), calls `ExitBootServices`,
    copies a 192-byte trampoline to `0x800`,
@@ -285,7 +285,7 @@ a Pentium 1 (and a Pentium II board without ACPI) on the UP path.
 | `0x60000` | No longer a rootfs staging area: the legacy stage copies each 16 KB chunk straight to `0x900000`.  The kernel BSS/boot stack may use this range |
 | `_end`    | Kernel end (linker symbol; `kernel.ld` keeps `_end <= 0x90000` so the top of the low-memory gap and the EBDA stay untouched).  BSS and the boot stack may extend past `0x60000` |
 | (in-image) | Bootstrap/protected-mode stack: 8 KB `.stack` NOLOAD section, `__boot_stack_top`/`__boot_stack_bottom` (travels with the kernel) |
-| `0x900000`| Legacy boot-time rootfs pack written directly by `vesa_stage.S` (reserved by `mm_init` until `ramfs_init` takes its copy, then freed; process stacks and kexec staging also start here) |
+| `0x900000`| Legacy boot-time rootfs pack written directly by `vesa_stage.S` (reserved by `mm_init` until `ramfs_init` takes its copy, then freed); `mm_init` places the frame bitmap in the first RAM after it (`0xAF3000` with today's pack); process stacks and kexec staging also start here |
 | `0x100000`| VGA shadow buffer (`VGA_SHADOW_BASE`, `vga.h`) |
 
 The legacy stage uses `0x3000..0x6FFF` as a 16 KB-chunk rootfs staging
@@ -295,7 +295,7 @@ later.
 
 The boot-time rootfs pack placement depends on the boot path: the legacy
 stage copies it directly to `0x900000`, the UEFI loader puts it at the top of
-RAM below 512 MB, and kexec leaves it in the staging buffer
+RAM below 1 GB, and kexec leaves it in the staging buffer
 (≥ `0x900000`).  `mm_init` reserves `[pack_addr, pack_addr+pack_size)` from
 boot info when it is above the low 1 MB, so the legacy pack is protected
 from the frame allocator too.  `ramfs_init` copies/inflates it into fresh
@@ -353,10 +353,20 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   trampoline at `0x6000`), and `spinlock.h` (the IRQ-safe spinlocks).
   `cpu_enable_sse()` runs on every AP: an AP starts with firmware CR4, and the
   SSE2 drawing fast paths #UD until OSFXSR/OSXMMEXCPT are set.
-- **Memory**: `phys.h` — the shared 512 MB physical ceiling (`MM_MAX_PHYS`),
-  also used by the UEFI loader. `mm.c/h` — INT 15h E820 detection (real-mode in
+- **Memory**: `phys.h` — the shared 1 GB physical ceiling (`MM_MAX_PHYS`),
+  also used by the UEFI loader; it ends where ring-3 space starts
+  (`USER_BASE` = `0x40000000`), and `paging.c` statically asserts that the
+  identity map never reaches a user window.  RAM above 1 GB is ignored (no
+  highmem zone or PAE yet).  `mm.c/h` — INT 15h E820 detection (real-mode in
   `vesa_stage.S`, map at `0x1000`) + a bitmap page-frame allocator (4 KB
-  pages). Reserves low 1 MB and an 8 MB VGA-shadow region. `kmalloc.c/h` — a power-of-two heap
+  pages). Reserves low 1 MB and an 8 MB VGA-shadow region.  The bitmap is
+  sized to the highest E820 RAM address (32 KB at 1 GB) and is not in BSS:
+  `mm_init` places it in the first RAM run at or above `0x900000` that
+  avoids the boot pack and the LFB and marks its own pages used (a 512-byte
+  static array covers the 16 MB no-E820 fallback).  Allocation is lowest
+  address first: a `first_free` word hint skips the full low words,
+  `mm_alloc_page()` finds the bit with `bsf`, and `mm_alloc_pages()` steps
+  over full and empty words 32 pages at a time. `kmalloc.c/h` — a power-of-two heap
   allocator on top of the frame allocator (used for PCBs and command context).
   Process stacks (≥ `0x900000`) come from the frame allocator, with an 8-stack
   fallback pool (a static BSS array; no fixed address).
@@ -500,8 +510,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   window still gets its release after the pointer leaves.  The userland
   `ngui.c/h` immediate-mode toolkit builds on those: clipped RGB565
   primitives, buttons, text input, the Adwaita symbolic icons and scrolling panes
-  (`ngui_scroll`; `hide_bar` keeps wheel/key scrolling without drawing a
-  scrollbar).
+  (`ngui_scroll`: an overlay scrollbar that is hidden while the pointer is
+  outside the pane, slides in on hover over ~100 ms, and reserves no layout
+  width; presses in its strip start the drag and do not reach the content;
+  `hide_bar` suppresses it entirely).
   `files` (`ucmd_files.c`) is its first user (its toolbar's `Disks`
   button opens the storage manager); `gallery` (`gallery.c`) is the
   live showcase of every control and primitive the toolkit exports.  Buttons
@@ -1101,9 +1113,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   (decoding RGB565 or BGR from the saved background); a shape change
   presents the union of the old and new rectangles at once.  Intel
   Ironlake and Radeon copy the image into their 64x64 ARGB planes (Intel's
-  CURPOS takes sign-magnitude negatives; Radeon clamps the position at 0
-  and skips the hidden part with `HORZ_VERT_OFF` and a `CUR_OFFSET` shifted
-  by 256 bytes per row, like Linux's legacy path); Cirrus thresholds alpha
+  CURPOS takes sign-magnitude negatives; the Intel cursor gamma enable
+  follows the matching primary plane's `DSPxCNTR` gamma enable, because the
+  display palette sits after the plane blender and forcing cursor gamma on
+  in a VBE mode whose primary bypasses it sends only the cursor through the
+  palette and gives its antialiased edges a bright halo; Radeon clamps the
+  position at 0 and skips the hidden part with `HORZ_VERT_OFF` and a
+  `CUR_OFFSET` shifted by 256 bytes per row, like Linux's legacy path);
+  Cirrus thresholds alpha
   at 50% into its AND/XOR planes (white/black by luminance) and clamps the
   position at 0.  An image upload never runs from IRQ12, which only moves.
   Animated shapes advance from `mouse_poll_update()`.  Scroll from every backend accumulates in
@@ -2482,8 +2499,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
   structure whose fields are read before being written must be cleared on
   allocation.  `clear_proc()` (`process.c`) exists for exactly this: a stale
   `procs[i].cr3` made the boot-time MMIO mapping (`paging_map_mmio_cr3`) fault
-  on the board while QEMU was fine.  Anything above `MM_MAX_PHYS` (512 MB) is
-  also *unmapped*, so a wild pointer there is an instant #PF.
+  on the board while QEMU was fine.  Anything between `MM_MAX_PHYS` (1 GB) and
+  the user windows is *unmapped*, so a wild pointer there is an instant #PF.
 - **All drawing goes into the current render target** (the shadow buffer by
   default; `vga_target()`, see the graphics bullet); the main loop flushes the
   pending damage rects to VRAM on every iteration (byte
@@ -2521,9 +2538,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 3. No per-process address spaces or process isolation (paging is identity-mapped).
 4. FAT32: FSInfo free-count not updated, no directory-chain growth.
 5. `disk.c` `fdc_reset()` and `fdc_init_once()` overlap/duplicate logic.
-6. Killing/reaping a ring-3 process frees its kernel stack and page directory
-   but not the user pages mapped into it (a few pages leak per command run;
-   needs a page-table walk/unmap on reap).
+6. Physical RAM above 1 GB is unused: the identity map stops at `USER_BASE`
+   (`0x40000000`).  Using it needs a highmem zone (user-only frames plus a
+   per-CPU temporary kernel mapping for zeroing/ELF loads) and, for RAM above
+   4 GB, PAE.  MMIO is still mapped at its physical address, which also
+   blocks growing ring-3 space above the PCI hole.
 7. `display` (needs a GPU snapshot) and `lsusb` (a 45-byte wrapper around
    the USB tree printer) are the last non-privileged commands still living in
    the kernel, plus the privileged ones (`peek`, `poke`, `dbg`, `serial`,
@@ -2606,15 +2625,17 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `websrv` cannot start while any TCP socket is open.  Kill the other
     command first.
 20. `/share` is RAM only: a reboot/kexec starts empty, and the 16 MB cap is
-    charged against the 512 MB identity-mapped window.
+    charged against the 1 GB identity-mapped window.
 
 21. The TCP backlog's early-request buffers cost 8 KB of kernel BSS
     (8 slots x 1 KB), and the FAT listing cache another 5 KB.  The command
     pack is out of the kernel now; after the WiFi/netmenu/install code and the
     per-connection TCP queues moved to the frame allocator, `_end` is
-    ~0x8ef20 (with the 6200/6300 DVM layer, the RTL8821AU driver, the
+    ~0x8ef20 before (with the 6200/6300 DVM layer, the RTL8821AU driver, the
     8×16 boot-console font, the IOAPIC/AMD-thermal additions and the safe
-    AMD MTRR path, the 32x32 cursor save buffer and the mount-policy table), ~4 KB below the `0x90000` wall, and the remaining limit
+    AMD MTRR path, the 32x32 cursor save buffer and the mount-policy table)
+    ~0x8bf20 now that the frame bitmap moved out of BSS, ~16 KB below the
+    `0x90000` wall, and the remaining limit
     is kernel code/buffers only.
 
 22. Browser limits: JavaScript runs inline and external classic scripts on
@@ -3023,5 +3044,5 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     for every spinner frame; both paths were written from the Linux
     drivers and only Cirrus and the software cursor are tested in QEMU.
     The cursor shape follows the WM poll, so it can lag the pointer by
-    one WM loop.  The 4 KB save buffer and the cursor code (~8 KB in all) leave `_end` at
-    ~0x8ef20, ~4 KB below the `0x90000` wall.
+    one WM loop.  The 4 KB save buffer and the cursor code (~8 KB in all) are included in
+    `_end` ~0x8bf20, ~16 KB below the `0x90000` wall.

+ 3 - 3
Makefile

@@ -929,9 +929,9 @@ root.img: browser.elf gallery.elf testdata/browser/demo.html testdata/browser/js
 
 OVMF ?= $(firstword $(wildcard /usr/share/ovmf/x64/OVMF.4m.fd /usr/share/OVMF/OVMF.4m.fd))
 
-# Guest RAM for the QEMU targets.  The kernel ceiling is 512 MB (phys.h);
-# override with `make run QEMU_MEM=1G` for larger guests.
-QEMU_MEM ?= 512M
+# Guest RAM for the QEMU targets, matching the 1 GB kernel ceiling (phys.h);
+# override with e.g. `make run QEMU_MEM=512M` (RAM above 1 GB is ignored).
+QEMU_MEM ?= 1G
 
 # root.img is deliberately not attached: a running QEMU may hold its write
 # lock, and the UEFI boot test does not need a second filesystem.

+ 3 - 3
boot/efi/main.c

@@ -44,7 +44,7 @@ extern unsigned char tramp_blob_end[];
  * generous and keeps the retry loop simple. */
 static UINT8 memmap_buf[65536] __attribute__((aligned(8)));
 
-/* One bit per 4 KB page over the kernel's 512 MB identity window.  Starts
+/* One bit per 4 KB page over the kernel's 1 GB identity window.  Starts
  * all-used; only EfiConventional/BootServices memory is freed.  EfiLoader*
  * (this image and the staging buffer) stays reserved, which is safe and
  * costs only a few hundred KB. */
@@ -399,7 +399,7 @@ static void build_e820(EFI_MEMORY_DESCRIPTOR *map, UINTN map_size,
 	}
 
 	/* The scanout is MMIO, not RAM; make sure it can never be handed out
-	 * even when its BAR happens to sit below the 512 MB ceiling. */
+	 * even when its BAR happens to sit below the 1 GB ceiling. */
 	if (fb->valid)
 		use_range(fb->base, fb->size);
 
@@ -778,7 +778,7 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st)
 		fail_before(st, "cannot allocate kernel staging buffer");
 
 	/* Rootfs pack: allocate a writable loader-data buffer below the
-	 * kernel's 512 MB identity window (and above the low 1 MB it
+	 * kernel's 1 GB identity window (and above the low 1 MB it
 	 * reserves).  It must be below MAX_PHYS: the kernel only
 	 * identity-maps that much and ramfs_init() reads it after paging is
 	 * enabled. */

+ 1 - 1
docs/boot.html

@@ -206,7 +206,7 @@
 		<ol>
 			<li>Selects a GOP mode with BGRX or RGBX 32bpp, width at most 1920, <code>pitch × height</code> at most 8 MB (1920×1080 fits at 8.29 MB), and a framebuffer below 4 GB. With 32bpp, that size limit also keeps a full-screen RGB565 canvas inside the 4 MB window slot; the VBE stage additionally checks 2 M pixels because a 24bpp 1920×1200 mode would otherwise pass the shadow check.</li>
 			<li>Calls <code>GetMemoryMap</code> and converts the firmware map into the kernel's E820 format at <code>0x1000</code>.</li>
-			<li>Locates the parent whole-disk Block I/O handle from the ESP device path, reads the P1 boot sector and P2 <code>NBROOT1</code> header, and stages the kernel below 4 GB and the gzip pack below the 512 MB identity window. The kernel/pack embedded in <code>BOOTX64.EFI</code> are a fallback only.</li>
+			<li>Locates the parent whole-disk Block I/O handle from the ESP device path, reads the P1 boot sector and P2 <code>NBROOT1</code> header, and stages the kernel below 4 GB and the gzip pack below the 1 GB identity window. The kernel/pack embedded in <code>BOOTX64.EFI</code> are a fallback only.</li>
 			<li>Writes the boot-info and framebuffer blocks, calls <code>ExitBootServices</code>, then copies a 192-byte trampoline to <code>0x800</code>.</li>
 			<li>Leaves IA-32e mode (clears <code>CR0.PG</code>, <code>EFER.LME</code>, <code>CR4.PAE/PGE/PCIDE/SMEP/SMAP/LA57</code>), copies the kernel to <code>0x7E00</code>, and jumps to <code>kernel_entry</code>.</li>
 		</ol>

+ 3 - 3
docs/development.html

@@ -239,15 +239,15 @@
 					<tr><td><code>make test-chat</code></td><td>Host tests (ASan/UBSan) for the chat client's JSON parser, cookie jar and the OIDC login page/reply/config parsers.</td></tr>
 					<tr><td><code>make test-chat-e2e</code></td><td>Boots QEMU with an NE2000 on slirp, starts <code>tools/mock_chat.py</code> and drives <code>chat</code> through QMP: native login, send, live poll, read marker, older paging, browse/join, new DM, saved-session resume and sign-out.  <code>CHAT_E2E=--totp|--consent|--passkey|--wrong</code> runs a login variant.</td></tr>
 					<tr><td><code>make compat-serve</code></td><td>Serve the browser compatibility ladder from <code>testdata/browser/compat/</code> on port 8000 for the board or QEMU guest.</td></tr>
-					<tr><td><code>make browser-host</code></td><td>Build the Linux SDL3 development harness (<code>browser-host</code> and its <code>host-curl</code> helper). It implements the ring-3 <code>SYS_*</code> ABI with host files, BSD sockets, <code>fork/exec</code> and an SDL3 window, so pages render and accept input without QEMU. Run <code>./browser-host [--size WxH] [--root DIR] URL|FILE</code>; <code>--headless --wait 3000 --shot out.ppm</code> writes the canvas without a display, and <code>--keys 'clo{down}{enter}'</code> types into it (one key per 100 ms; <code>{enter}</code>, <code>{esc}</code>, <code>{tab}</code>, <code>{bs}</code>, <code>{del}</code>, arrows, <code>{ctrl-l}</code>, <code>{wait}</code>). Needs the 32-bit SDL3/Wayland libraries (<code>lib32-sdl3</code>, <code>lib32-wayland</code>, <code>lib32-libxkbcommon</code>).</td></tr>
+					<tr><td><code>make browser-host</code></td><td>Build the Linux SDL3 development harness (<code>browser-host</code> and its <code>host-curl</code> helper). It implements the ring-3 <code>SYS_*</code> ABI with host files, BSD sockets, <code>fork/exec</code> and an SDL3 window, so pages render and accept input without QEMU. Run <code>./browser-host [--size WxH] [--root DIR] URL|FILE</code>; <code>--headless --wait 3000 --shot out.ppm</code> writes the canvas without a display, and <code>--keys 'clo{down}{enter}'</code> types into it (one key per 100 ms; <code>{enter}</code>, <code>{esc}</code>, <code>{tab}</code>, <code>{bs}</code>, <code>{del}</code>, arrows, <code>{ctrl-l}</code>, <code>{wait}</code>, and <code>{click:X,Y}</code> for a left click at canvas coordinates). Needs the 32-bit SDL3/Wayland libraries (<code>lib32-sdl3</code>, <code>lib32-wayland</code>, <code>lib32-libxkbcommon</code>).</td></tr>
 					<tr><td><code>make fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
 			</table>
 		</div>
 		<p>
-			QEMU guests default to 512 MB, matching <code>MM_MAX_PHYS</code> in
+			QEMU guests default to 1 GB, matching <code>MM_MAX_PHYS</code> in
 			<span class="file">phys.h</span>. Override the size with
-			<code>QEMU_MEM</code>, for example <code>make run QEMU_MEM=1G</code>;
+			<code>QEMU_MEM</code>, for example <code>make run QEMU_MEM=512M</code>;
 			all run and UEFI targets pass it through.
 		</p>
 	</section>

+ 9 - 7
docs/graphics.html

@@ -189,8 +189,8 @@
 			window).  <code>SYS_WIN_RESIZE_SELF</code> grows or shrinks the
 			popover to the section, clamped to <code>SYS_SCREEN_INFO</code>'s
 			framebuffer; the section scrolls with the wheel, touchpad or page
-			keys when it is taller than the screen, without drawing a
-			scrollbar.
+			keys when it is taller than the screen, and its overlay scrollbar
+			slides in while the pointer is over the panel.
 		</p>
 		<p>
 			The WM is the ring-3 process loaded from
@@ -296,10 +296,11 @@
 			(<code>+dy</code> is later content). A click that starts
 			in a window still receives its release after the pointer leaves.
 			The ngui helper <code>ngui_scroll_wheel()</code> applies the delta
-			to a pane when the pointer is over it; a pane can set
-			<code>hide_bar</code> to keep wheel/key scrolling without a visible
-			scrollbar (the control panel does this so every card uses the full
-			width).
+			to a pane when the pointer is over it. A pane's scrollbar is an
+			overlay: an 8 px rounded pill at its right edge that stays hidden
+			while the pointer is outside, slides in over about 100 ms on
+			hover, and never reduces the content rectangle or reflows a row.
+			<code>hide_bar</code> suppresses it entirely.
 			The WM process itself is special: it maps the screen shadow at
 			<code>0x58000000</code> and each front canvas at
 			<code>0x59000000 + index × 4 MB</code>, which is how it composites
@@ -361,6 +362,7 @@
 		<ul>
 			<li><strong>Text fields</strong> support drag-selection, double-click select-all, Ctrl+Left/Right word jumps, Ctrl+Delete/Backspace word deletion and Ctrl+A. They use the proportional face with measured caret, selection and horizontal scrolling; a field marked <code>disabled</code> ignores pointer and keyboard input, drops the focus and paints its value dimmed in the same proportional face. A field marked <code>secret</code> is measured and painted from a <code>*</code> mask (caret, selection and click positions follow the mask, Ctrl+Left/Right jump to the ends), and Tab returns <code>NGUI_INPUT_NEXT</code> together with <code>NGUI_INPUT_CANCEL</code> so forms can move the focus. Fields hold up to 511 characters (<code>NGUI_INPUT_MAX</code> 512). The terminal and editor keep the 8×16 cell grid.</li>
 			<li><strong>Popover components</strong> give a menu panel its surface: <code>ngui_popover_begin()</code> fills the canvas and returns the body and footer rectangles (no title bar or close button); <code>ngui_section()</code> draws a captioned section header with an optional right-aligned action button; <code>ngui_list_row()</code> is a two-line hover/selected row with optional signal bars and trailing text; <code>ngui_tile()</code> is a rounded quick-settings tile and <code>ngui_slider()</code> a draggable horizontal slider. The WM draws no outer chrome, so the app paints the whole window.</li>
+			<li><strong>Scroll panes</strong> keep the wheel and page keys, and draw a Firefox-style overlay pill instead of a permanent track. It is hidden by default, animates in from the pane's right edge while the pointer is over the pane, brightens over the hit strip and turns accent-coloured while dragged. Presses in the strip start a drag (or jump the thumb) and do not reach the rows or buttons beneath it; content uses the full pane width in every app.</li>
 			<li><strong>Clip stack</strong> keeps nested panes and popups inside their parents.</li>
 			<li><strong>Layout cuts</strong> split a rectangle into rows, columns and fixed margins without a constraint solver.</li>
 			<li><strong>No retained widget tree.</strong> Apps redraw from state every frame, which keeps the toolkit small and predictable.</li>
@@ -494,7 +496,7 @@
 			<li><strong>Loading.</strong> <span class="file">cursor.c</span> copies the bundle out of the ramfs into its own pages after <code>ramfs_init()</code> and after every <code>ramfs_replace()</code> (the old pack is freed), then tells <span class="file">mouse.c</span> to re-fetch its image.</li>
 			<li><strong>Selection.</strong> On every <code>SYS_WM_POLL</code> the window server resolves the shape: the WM's override (<code>SYS_WM_SET_CURSOR</code>: resize arrows on the grip and while resizing, the move cross during a title-bar drag, a hand over launchers and the status area), else the cursor of the window holding the pointer capture, else the content cursor (<code>SYS_WIN_SET_CURSOR</code>) of the window under the pointer, else the arrow.</li>
 			<li><strong>Clients.</strong> ngui resets the cursor to the arrow for each redrawn frame, a hovered text field asks for the I-beam, <code>ngui_cursor_rect()</code>/<code>ngui_set_cursor()</code> serve apps, and <code>ngui_end_ex()</code> sends it when it changed.  The terminal uses the I-beam; the browser maps the inherited CSS <code>cursor</code> property and, for <code>auto</code>, a hand over links, an I-beam over text fields and the progress arrow while a page loads.  The gallery's Cursors section shows every shape.</li>
-			<li><strong>Drawing.</strong> <code>cur_x</code>/<code>cur_y</code> stay the hotspot; the image's top-left is the hotspot minus the image's hotspot and may be off-screen.  The software cursor saves up to 32&times;32 pixels under it and blends the premultiplied pixels over them.  Intel Ironlake and Radeon copy the ARGB image into their 64&times;64 planes (Intel uses CURPOS sign bits for negative positions, Radeon <code>HORZ_VERT_OFF</code> plus a shifted <code>CUR_OFFSET</code>); Cirrus reduces it to its two colours and clamps the position at 0.  Animated frames advance from <code>mouse_poll_update()</code>.</li>
+			<li><strong>Drawing.</strong> <code>cur_x</code>/<code>cur_y</code> stay the hotspot; the image's top-left is the hotspot minus the image's hotspot and may be off-screen.  The software cursor saves up to 32&times;32 pixels under it and blends the premultiplied pixels over them.  Intel Ironlake and Radeon copy the ARGB image into their 64&times;64 planes (Intel uses CURPOS sign bits for negative positions and follows the matching primary plane's gamma enable, because the display palette is after the plane blender and a cursor-only gamma pass brightens its antialiased edges on a VBE mode whose primary bypasses the palette; Radeon uses <code>HORZ_VERT_OFF</code> plus a shifted <code>CUR_OFFSET</code>); Cirrus reduces it to its two colours and clamps the position at 0.  Animated frames advance from <code>mouse_poll_update()</code>.</li>
 		</ul>
 	</section>
 

+ 1 - 1
docs/index.html

@@ -157,7 +157,7 @@
 			<li><strong>Freestanding C.</strong> The kernel has no libc, <code>malloc</code> or <code>printf</code>; ring-3 commands can link the in-tree <code>libc.a</code> (<code>malloc</code>, strings, stdlib). Formatting and allocation are in-tree either way.</li>
 			<li><strong>i586 baseline.</strong> Builds use <code>-march=i586 -mno-sse -mno-sse2 -mno-mmx</code>; SSE2 drawing paths are probed at runtime.</li>
 			<li><strong>Identity-mapped paging.</strong> Physical and virtual addresses are equal. There is no per-process address space or isolation.</li>
-			<li><strong>512 MB physical ceiling.</strong> The frame bitmap covers 512 MB; anything above that is unmapped.</li>
+			<li><strong>1 GB physical ceiling.</strong> The identity map ends where ring-3 space starts (<code>0x40000000</code>); RAM above it is ignored.</li>
 			<li><strong>Hardcoded low memory.</strong> Boot info, the E820 map, the framebuffer block and the AP trampoline have fixed addresses that every boot path must honour.</li>
 			<li><strong>No firmware runtime.</strong> <code>reboot</code> and <code>poweroff</code> use legacy ports; UEFI runtime services are not called after <code>ExitBootServices</code>.</li>
 		</ul>

+ 30 - 19
docs/memory.html

@@ -41,7 +41,7 @@
 			window canvases, the ring-3 heap and the rootfs copy — is dynamic.
 		</p>
 		<div class="meta">
-			<span class="pill">512 MB physical ceiling</span>
+			<span class="pill">1 GB physical ceiling</span>
 			<span class="pill">4 KB frames</span>
 			<span class="pill">4 MB PSE pages</span>
 			<span class="pill">identity map</span>
@@ -76,29 +76,32 @@
 		<figure class="figure">
 			<svg viewBox="0 0 920 180" role="img" aria-labelledby="phys-title phys-desc">
 				<title id="phys-title">Physical memory composition</title>
-				<desc id="phys-desc">Of the 512 MB addressable window, the low 1 MB and an 8 MB VGA shadow reserve are unavailable, leaving about 503 MB for the frame allocator.</desc>
+				<desc id="phys-desc">Of the 1 GB addressable window, the low 1 MB and an 8 MB VGA shadow reserve are unavailable, leaving about 1015 MB for the frame allocator.</desc>
 				<text class="svg-text" x="20" y="28">0x00000000</text>
-				<text class="svg-text" x="900" y="28" text-anchor="end">0x20000000 · 512 MB</text>
+				<text class="svg-text" x="900" y="28" text-anchor="end">0x40000000 · 1 GB</text>
 
-				<rect class="svg-box blue" x="40" y="44" width="2" height="34" rx="1"/>
-				<rect class="svg-box accent" x="42" y="44" width="13.5" height="34" rx="1"/>
-				<rect class="svg-box green" x="55.5" y="44" width="844.5" height="34" rx="2"/>
+				<rect class="svg-box blue" x="40" y="44" width="1.5" height="34" rx="1"/>
+				<rect class="svg-box accent" x="41.5" y="44" width="6.7" height="34" rx="1"/>
+				<rect class="svg-box green" x="48.2" y="44" width="851.8" height="34" rx="2"/>
 
 				<text class="svg-tiny" x="40" y="100">low 1 MB</text>
 				<text class="svg-tiny" x="64" y="100">VGA shadow · 8 MB</text>
-				<text class="svg-tiny" x="477" y="100" text-anchor="middle">frame allocator · ~503 MB</text>
+				<text class="svg-tiny" x="477" y="100" text-anchor="middle">frame allocator · ~1015 MB</text>
 
 				<line class="svg-line" x1="41" y1="78" x2="41" y2="88"/>
-				<line class="svg-line" x1="48" y1="78" x2="48" y2="88"/>
+				<line class="svg-line" x1="45" y1="78" x2="45" y2="88"/>
 				<line class="svg-line" x1="490" y1="78" x2="490" y2="88"/>
 
 				<text class="svg-tiny" x="40" y="130">boot structures · kernel image · BIOS/UMA · DMA buffers</text>
 				<text class="svg-tiny" x="40" y="150">The 8 MB reserve protects the shadow buffer; the allocator starts at 0x900000.</text>
 			</svg>
 			<figcaption>
-				<strong>512 MB is a hard ceiling.</strong> The frame bitmap covers
-				<code>[0, 0x20000000)</code>; addresses above it are not mapped by
-				the kernel page tables. The VGA shadow reserve is conservative: the
+				<strong>1 GB is a hard ceiling</strong> (<code>MM_MAX_PHYS</code>,
+				<code>include/phys.h</code>). The identity map covers
+				<code>[0, 0x40000000)</code> and ring-3 space starts at
+				<code>USER_BASE</code> = <code>0x40000000</code>, so RAM above 1 GB is
+				ignored until a highmem zone exists; <code>paging.c</code>
+				statically asserts the two never overlap. The VGA shadow reserve is conservative: the
 				actual buffer is smaller, but the gap keeps a future resolution bump
 				from colliding with allocated pages.
 			</figcaption>
@@ -132,7 +135,7 @@
 					<tr><td><code>0x6F00</code></td><td>AP startup info block</td><td>CR3, stack top, C entry, CPU index</td></tr>
 					<tr><td><code>0x60000</code></td><td>Former rootfs staging</td><td>No longer used by the loader; kernel BSS/stack may use it</td></tr>
 					<tr><td><code>_end</code></td><td>Kernel end</td><td><code>kernel.ld</code> asserts <code>_end ≤ 0x90000</code></td></tr>
-					<tr><td><code>0x900000</code></td><td>Boot pack (written directly by the legacy stage); dynamic stacks and kexec staging</td><td>Freed after <code>ramfs_init</code> takes its copy</td></tr>
+					<tr><td><code>0x900000</code></td><td>Boot pack (written directly by the legacy stage), then the frame bitmap right after it; dynamic stacks and kexec staging</td><td>The pack is freed after <code>ramfs_init</code> takes its copy; the bitmap stays</td></tr>
 					<tr><td><code>0x100000</code></td><td>VGA shadow buffer base</td><td><code>VGA_SHADOW_BASE</code>; 8 MB reserved</td></tr>
 					<tr><td><code>0x40000000</code></td><td>Ring-3 ELF link/load address</td><td><code>USER_BASE</code>, 4 MB window up to <code>0x40400000</code></td></tr>
 					<tr><td><code>0x50000000</code></td><td>Ring-3 window canvas</td><td><code>USER_WIN_BASE</code>, 4 MB slot</td></tr>
@@ -180,8 +183,17 @@
 		<h2>Frame allocator</h2>
 		<p>
 			<span class="file">mm.c</span> keeps one bit per 4 KB page for the
-			whole 512 MB window. The bitmap is not IRQ-safe; callers save and
-			disable interrupts around allocations. The allocator returns:
+			RAM below the 1 GB ceiling: the bitmap is sized to the highest E820 RAM
+			address (32 KB at 1 GB) and is not part of the kernel image.
+			<code>mm_init</code> places it in the first E820 RAM run at or above
+			<code>0x900000</code> that avoids the boot rootfs pack and the LFB, and
+			marks its own pages used (legacy boots put it right after the pack;
+			a 16 MB static fallback covers a missing E820 map).  The allocators
+			disable interrupts around the bitmap and hand out the lowest free
+			frames: a <code>first_free</code> word hint skips the full low part,
+			<code>mm_alloc_page()</code> finds the bit with <code>bsf</code>, and
+			<code>mm_alloc_pages(n)</code> steps over full and empty words 32 pages
+			at a time. The allocator returns:
 		</p>
 		<ul>
 			<li><code>mm_alloc_page()</code> — one zero-address-ambiguous page (physical address 0 means failure).</li>
@@ -190,7 +202,7 @@
 		</ul>
 		<p>
 			At boot, <code>mm_init</code> reserves the low 1 MB, the 8 MB VGA
-			shadow region, any LFB that happens to live below 512 MB, and the
+			shadow region, any LFB that happens to live below 1 GB, the bitmap itself and the
 			boot-time rootfs pack. The pack reservation is released by
 			<code>ramfs_init</code> after it copies/inflates the pack into fresh
 			pages.
@@ -296,7 +308,7 @@
 		<h2>Rootfs pack lifetime</h2>
 		<ol>
 			<li>The compressed pack is at most 2 MB (<code>PACK_MAX</code>), so the legacy copy ends below <code>0xB00000</code>; inflated it is about 2 MB with the WiFi firmware (the 8 MB <code>RAMFS_MAX_DECOMPRESSED</code> cap applies).</li>
-			<li>The boot path places the gzip pack in RAM: the legacy stage copies it directly to <code>0x900000</code> with <code>INT 15h AH=87h</code>, UEFI into a loader-data buffer below 512 MB, kexec in its staging buffer.</li>
+			<li>The boot path places the gzip pack in RAM: the legacy stage copies it directly to <code>0x900000</code> with a protected-mode <code>rep movsb</code>, UEFI into a loader-data buffer below 1 GB, kexec in its staging buffer.</li>
 			<li><code>mm_init</code> reserves <code>[pack_addr, pack_addr + pack_size)</code> so the frame allocator cannot reuse it.</li>
 			<li><code>ramfs_init</code> takes a private page-allocated copy, validates the <code>NBROOT1</code> header and inflates the pack into it.</li>
 			<li><code>mm_free_range</code> releases the boot region when it is above the VGA shadow reserve. The private copy lives until <code>ramfs_replace</code> or reboot.</li>
@@ -311,8 +323,7 @@
 		<h2>Limits &amp; leaks</h2>
 		<ul>
 			<li><strong>No per-process address spaces.</strong> Paging is identity-mapped; there is no memory protection between processes.</li>
-			<li><strong>512 MB ceiling.</strong> Physical memory above <code>0x20000000</code> is unmapped. A wild pointer there is an instant <code>#PF</code>.</li>
-			<li><strong>User page leak on reap.</strong> Killing a ring-3 process frees its kernel stack and page directory but not all user pages mapped into it; a few pages leak per command run.</li>
+			<li><strong>1 GB ceiling.</strong> Physical memory above <code>0x40000000</code> is not used: that address range is ring-3 space, so the kernel has no mapping for frames above it (a highmem zone with temporary kernel mappings, or PAE for RAM above 4 GB, would be needed). A wild kernel pointer between the identity map and the user windows is an instant <code>#PF</code>.</li>
 			<li><strong>Kernel heap fragmentation.</strong> <code>kmalloc</code>'s power-of-two size classes make long-running mixed-size kernel allocation wasteful; ring-3 commands use the separate first-fit libc heap described above.</li>
 			<li><strong>No TLB shootdown.</strong> Cross-CPU mapping changes rely on not-present entries not being cached.</li>
 		</ul>
@@ -322,7 +333,7 @@
 		<h2>Source map</h2>
 		<ul class="filelist">
 			<li><code>kernel/mm.c</code>, <code>kernel/mm.h</code> — E820 + bitmap allocator</li>
-			<li><code>include/phys.h</code> — shared 512 MB physical ceiling</li>
+			<li><code>include/phys.h</code> — shared 1 GB physical ceiling</li>
 			<li><code>kernel/kmalloc.c</code>, <code>kernel/kmalloc.h</code> — kernel heap</li>
 			<li><code>user/lib/libc/malloc.c</code>, <code>user/lib/libc/ucmd_mem.c</code> — ring-3 heap and <code>SYS_MEM_*</code> backend</li>
 			<li><code>user/lib/libc/string.c</code>, <code>user/lib/libc/stdlib.c</code> — ring-3 libc support</li>

+ 2 - 1
host/main.c

@@ -5,7 +5,8 @@
  *
  * --keys types into a headless window, one key every 100 ms from 300 ms
  * after the first frame: plain characters, plus {enter} {esc} {tab} {bs}
- * {del} {up} {down} {left} {right} {ctrl-l} and {wait} (a 1 s pause).
+ * {del} {up} {down} {left} {right} {ctrl-l}, {wait} (a 1 s pause) and
+ * {click:X,Y} (a left click at canvas coordinates X,Y).
  */
 #include <signal.h>
 #include <stdio.h>

+ 33 - 2
host/window_headless.c

@@ -108,9 +108,18 @@ void host_headless_pump(unsigned int timeout_ms)
 		usleep(timeout_ms * 1000u);
 }
 
+/* --keys `{click:X,Y}`: the pointer moves there and a left press is
+ * queued, its release on the next event poll. */
+static int ptr_x, ptr_y;
+static unsigned int ptr_buttons;
+static int click_pending;       /* 1 press queued, 2 release queued */
+
 int host_headless_pointer(struct win_pointer *out)
 {
 	memset(out, 0, sizeof(*out));
+	out->x = ptr_x;
+	out->y = ptr_y;
+	out->buttons = ptr_buttons;
 	out->focused = 1;
 	out->inside = 1;
 	return 0;
@@ -118,8 +127,21 @@ int host_headless_pointer(struct win_pointer *out)
 
 int host_headless_event(struct win_event *out)
 {
-	(void)out;
-	return 0;
+	if (!click_pending)
+		return 0;
+	out->x = ptr_x;
+	out->y = ptr_y;
+	if (click_pending == 1) {
+		out->type = WIN_EV_POINTER_DOWN;
+		ptr_buttons = 1;
+		click_pending = 2;
+	} else {
+		out->type = WIN_EV_POINTER_UP;
+		ptr_buttons = 0;
+		click_pending = 0;
+	}
+	out->buttons = ptr_buttons;
+	return 1;
 }
 
 int host_headless_scroll(struct win_scroll *out)
@@ -154,6 +176,15 @@ int host_headless_key(void)
 	if (!*key_pos || now < key_due)
 		return 0;
 	code = (unsigned char)*key_pos++;
+	if (code == '{' && !strncmp(key_pos, "click:", 6)) {
+		const char *end = strchr(key_pos, '}');
+
+		if (sscanf(key_pos + 6, "%d,%d", &ptr_x, &ptr_y) == 2)
+			click_pending = 1;
+		key_pos = end ? end + 1 : key_pos + strlen(key_pos);
+		key_due = now + 300;
+		return 0;
+	}
 	if (code == '{') {
 		const char *end = strchr(key_pos, '}');
 		unsigned int i;

+ 5 - 3
include/phys.h

@@ -2,8 +2,10 @@
 #ifndef PHYS_H
 #define PHYS_H
 
-/* 512 MB: enough for the browser and its JavaScript heap, while the 4 KB frame bitmap
- * stays 16 KB and the 4 MB identity map needs only 128 PDEs. */
-#define MM_MAX_PHYS      (512u * 1024 * 1024)
+/* 1 GB: the kernel identity-maps [0, MM_MAX_PHYS) with 4 MB pages, and ring-3
+ * address space starts at USER_BASE (0x40000000), so the identity map cannot
+ * grow past 1 GB without a highmem zone.  The frame bitmap (32 KB at 1 GB)
+ * is placed in RAM by mm_init(), not in the kernel's BSS. */
+#define MM_MAX_PHYS      (1024u * 1024 * 1024)
 
 #endif

+ 22 - 5
kernel/intel.c

@@ -12,8 +12,10 @@
  *  - 64x64 ARGB8888 cursor, MSB A:R:G:B, hotspot at (0,0); the mouse code
  *    positions the image's top-left, so CURPOS takes negative values in
  *    sign-magnitude form (bit 15 = X sign, bit 31 = Y sign).
- *  - CURCNTR bit 31 enables, mode 0x27 is 64x64 ARGB, bits 29:28 hold the
- *    pipe select.  CURBASE is written after CURPOS to arm the update.
+ *  - CURCNTR bit 31 enables, mode 0x27 is 64x64 ARGB.  Gen5 has one cursor
+ *    register per pipe, so bits 29:28 (the old pipe select) are reserved.
+ *    The cursor gamma enable follows the matching primary plane's gamma
+ *    enable; CURBASE is written after CURPOS to arm the update.
  *  - The GTT PTE is the physical page, its bits 35:32 in PTE bits 7:4, the
  *    uncached mapping type (0) and the valid bit (1).
  */
@@ -48,10 +50,10 @@
 #define CUR_PIPE_B       0x40
 
 #define DSP_PLANE_ENABLE       (1u << 31)
+#define DSP_PLANE_GAMMA_ENABLE (1u << 30)
 #define CURSOR_ENABLE          (1u << 31)
 #define CURSOR_GAMMA_ENABLE    (1u << 26)
 #define CURSOR_MODE_64_ARGB    0x27u
-#define CURSOR_PIPE_SEL_SHIFT  28
 
 #define CUR_SIZE   64
 #define CUR_BYTES  (CUR_SIZE * CUR_SIZE * 4)
@@ -222,10 +224,21 @@ static int intel_map_cursor(unsigned int slot)
 	return 0;
 }
 
+/* The display palette (gamma LUT) sits after the plane blender on
+ * Ironlake.  Enabling the cursor's gamma while the primary plane bypasses
+ * it sends only the cursor through the palette; on a VBE mode whose
+ * primary plane has gamma disabled that turns the antialiased cursor
+ * edges into a bright halo.  Follow the matching primary plane's gamma
+ * enable instead.  Gen5 has one cursor register per pipe, so the old
+ * (pre-Gen5) pipe-select field is reserved and must stay zero. */
 static unsigned int cursor_ctrl(unsigned int pipe)
 {
-	return CURSOR_ENABLE | CURSOR_GAMMA_ENABLE |
-	       CURSOR_MODE_64_ARGB | (pipe << CURSOR_PIPE_SEL_SHIFT);
+	unsigned int dsp = pipe ? DSPBCNTR : DSPACNTR;
+	unsigned int ctrl = CURSOR_ENABLE | CURSOR_MODE_64_ARGB;
+
+	if (mmio_read(dsp) & DSP_PLANE_GAMMA_ENABLE)
+		ctrl |= CURSOR_GAMMA_ENABLE;
+	return ctrl;
 }
 
 void intel_init(unsigned int bus, unsigned int dev, unsigned int device_id)
@@ -332,6 +345,10 @@ void intel_init(unsigned int bus, unsigned int dev, unsigned int device_id)
 	serial_puthex(SERIAL_COM1, intel_pipe_mask);
 	serial_puts(SERIAL_COM1, ", cursor ");
 	serial_puthex(SERIAL_COM1, intel_cursor_gtt);
+	serial_puts(SERIAL_COM1, ", dspa ");
+	serial_puthex(SERIAL_COM1, dspa);
+	serial_puts(SERIAL_COM1, ", dspb ");
+	serial_puthex(SERIAL_COM1, dspb);
 	serial_puts(SERIAL_COM1, "\n");
 
 	intel_probe_ok = 1;

+ 234 - 71
kernel/mm.c

@@ -5,11 +5,24 @@
 #include "serial.h"
 #include "vga.h"
 
-/* One bit per 4 KB page; bit set = in use. */
-#define MM_BITMAP_BITS  (MM_MAX_PHYS / PAGE_SIZE)
-#define MM_BITMAP_WORDS (MM_BITMAP_BITS / 32)
-
-static unsigned int bitmap[MM_BITMAP_WORDS];
+/* One bit per 4 KB page; bit set = in use.
+ *
+ * The bitmap covers [0, top of RAM) rounded up to 128 KB, at most
+ * MM_MAX_PHYS.  It is not in BSS (1 GB needs 32 KB, and the kernel image
+ * must end below 0x90000): mm_init() places it in the first E820 RAM run
+ * above the VGA-shadow reserve that avoids the boot rootfs pack and the
+ * LFB, then marks those pages used.  The small static array is only the
+ * fallback when no E820 map exists (the 16 MB guess) or nothing fits. */
+#define MM_FALLBACK_PHYS   0x1000000u      /* 16 MB */
+#define MM_FALLBACK_WORDS  (MM_FALLBACK_PHYS / PAGE_SIZE / 32)
+#define MM_PLACE_MIN       (MM_SHADOW_BASE + MM_SHADOW_RESERVE)
+
+static unsigned int fallback_bitmap[MM_FALLBACK_WORDS];
+static unsigned int *bitmap = fallback_bitmap;
+static unsigned int bitmap_words;   /* words covered by the bitmap */
+static unsigned int bitmap_bits;    /* bitmap_words * 32 */
+static unsigned int bitmap_bytes;   /* page-rounded size when placed in RAM */
+static unsigned int first_free;     /* lowest word that may hold a free bit */
 static unsigned int free_pages;
 static unsigned int total_ram_kb;
 
@@ -44,16 +57,22 @@ static inline void irq_restore(unsigned int flags)
 	__asm__ volatile ("pushl %0; popfl" : : "r"(flags));
 }
 
+static unsigned long long bitmap_limit(void)
+{
+	return (unsigned long long)bitmap_bits * PAGE_SIZE;
+}
+
 /* Mark a physical byte range [base, base+len) as used in the bitmap. */
 static void mark_used(unsigned long long base, unsigned long long len)
 {
 	unsigned long long end = base + len;
+	unsigned long long lim = bitmap_limit();
 	unsigned int p0, p1, p;
 
-	if (base >= MM_MAX_PHYS)
+	if (base >= lim)
 		return;
-	if (end > MM_MAX_PHYS)
-		end = MM_MAX_PHYS;
+	if (end > lim)
+		end = lim;
 
 	p0 = (unsigned int)(base >> 12);
 	p1 = (unsigned int)((end + PAGE_SIZE - 1) >> 12);
@@ -65,45 +84,159 @@ static void mark_used(unsigned long long base, unsigned long long len)
 static void mark_free(unsigned long long base, unsigned long long len)
 {
 	unsigned long long end = base + len;
+	unsigned long long lim = bitmap_limit();
 	unsigned int p0, p1, p;
 
-	if (base >= MM_MAX_PHYS)
+	if (base >= lim)
 		return;
-	if (end > MM_MAX_PHYS)
-		end = MM_MAX_PHYS;
+	if (end > lim)
+		end = lim;
 
-	p0 = (unsigned int)(base >> 12);
+	p0 = (unsigned int)((base + PAGE_SIZE - 1) >> 12);
 	p1 = (unsigned int)(end >> 12);
 	for (p = p0; p < p1; p++)
 		bit_clear(p);
 }
 
+static int e820_valid(const struct e820_map *map)
+{
+	return map->magic == E820_MAGIC && map->count <= E820_MAX_ENTRIES;
+}
+
+static int overlaps(unsigned long long a0, unsigned long long a1,
+		    unsigned long long b0, unsigned long long b1)
+{
+	return b1 > b0 && a0 < b1 && b0 < a1;
+}
+
+/* Boot-time regions that must stay out of the allocator (and out of the
+ * bitmap's own placement): the LFB when a BIOS put it in RAM, and the
+ * rootfs pack until ramfs_init() has copied it. */
+static unsigned long long lfb_lo, lfb_hi, pack_lo, pack_hi;
+
+static void find_boot_regions(void)
+{
+	const volatile struct vga_boot_fb_info *fb = VGA_BOOT_FB;
+	unsigned int sz, pa, ps;
+
+	__asm__ volatile ("" : "+r"(fb));
+	lfb_lo = lfb_hi = 0;
+	sz = (unsigned int)fb->pitch * fb->height;
+	if (!sz)
+		sz = 0x1000000;
+	if (fb->valid && fb->lfb_base && fb->lfb_base < MM_MAX_PHYS) {
+		lfb_lo = fb->lfb_base;
+		lfb_hi = lfb_lo + sz;
+	}
+
+	pack_lo = pack_hi = 0;
+	pa = bootinfo_pack_addr();
+	ps = bootinfo_pack_size();
+	if (pa >= MM_RESERVE_LOW && pa < MM_MAX_PHYS && ps != 0 &&
+	    ps <= MM_MAX_PHYS && pa + ps > pa && pa + ps <= MM_MAX_PHYS) {
+		pack_lo = pa;
+		pack_hi = (unsigned long long)pa + ps;
+	}
+}
+
+static unsigned long long page_up(unsigned long long a)
+{
+	return (a + PAGE_SIZE - 1) & ~(unsigned long long)(PAGE_SIZE - 1);
+}
+
+/* First E820 RAM address >= MM_PLACE_MIN where `bytes` fit without
+ * touching the pack or the LFB; 0 if there is none. */
+static unsigned int place_bitmap(const struct e820_map *map,
+				 unsigned int bytes)
+{
+	unsigned int i;
+
+	for (i = 0; i < map->count; i++) {
+		const struct e820_entry *e = &map->entry[i];
+		unsigned long long lo, hi, c;
+
+		if (e->type != E820_RAM || e->length == 0)
+			continue;
+		lo = page_up(e->base);
+		hi = e->base + e->length;
+		if (hi > MM_MAX_PHYS)
+			hi = MM_MAX_PHYS;
+		c = lo < MM_PLACE_MIN ? MM_PLACE_MIN : lo;
+		while (c + bytes <= hi) {
+			if (overlaps(c, c + bytes, pack_lo, pack_hi))
+				c = page_up(pack_hi);
+			else if (overlaps(c, c + bytes, lfb_lo, lfb_hi))
+				c = page_up(lfb_hi);
+			else
+				return (unsigned int)c;
+		}
+	}
+	return 0;
+}
+
 /* Mark the whole bitmap as used, then walk the E820 map and free RAM. */
 void mm_init(void)
 {
 	const struct e820_map *map = (const struct e820_map *)E820_MAP_ADDR;
-	unsigned int i, n;
+	unsigned long long top = 0;
+	unsigned int i, n, at = 0;
+
+	find_boot_regions();
+	total_ram_kb = 0;
+
+	/* Size the bitmap to the highest RAM address below the ceiling. */
+	if (e820_valid(map)) {
+		n = map->count;
+		for (i = 0; i < n; i++) {
+			const struct e820_entry *e = &map->entry[i];
+			unsigned long long end = e->base + e->length;
+
+			if (e->type != E820_RAM || e->length == 0)
+				continue;
+			if (end > MM_MAX_PHYS)
+				end = MM_MAX_PHYS;
+			if (end > e->base) {
+				total_ram_kb +=
+					(unsigned int)((end - e->base) >> 10);
+				if (end > top)
+					top = end;
+			}
+		}
+	}
+	if (top == 0)
+		top = MM_FALLBACK_PHYS;
+	bitmap_words = (unsigned int)((top + 32ull * PAGE_SIZE - 1) /
+				      (32ull * PAGE_SIZE));
+
+	bitmap = fallback_bitmap;
+	bitmap_bytes = 0;
+	if (bitmap_words > MM_FALLBACK_WORDS) {
+		unsigned int bytes = (bitmap_words * 4u + PAGE_SIZE - 1) &
+				     ~(PAGE_SIZE - 1u);
+
+		at = place_bitmap(map, bytes);
+		if (at) {
+			bitmap = (unsigned int *)at;
+			bitmap_bytes = bytes;
+		} else {
+			serial_puts(SERIAL_COM1,
+				    "mm: no room for the frame bitmap, using 16 MB\n");
+			bitmap_words = MM_FALLBACK_WORDS;
+		}
+	}
+	bitmap_bits = bitmap_words * 32u;
 
 	/* Everything starts in-use. */
-	for (i = 0; i < MM_BITMAP_WORDS; i++)
+	for (i = 0; i < bitmap_words; i++)
 		bitmap[i] = 0xFFFFFFFFu;
 
-	total_ram_kb = 0;
-
-	if (map->magic == E820_MAGIC && map->count <= E820_MAX_ENTRIES) {
+	if (e820_valid(map)) {
 		n = map->count;
 		for (i = 0; i < n; i++) {
 			const struct e820_entry *e = &map->entry[i];
-			if (e->type == E820_RAM && e->length != 0) {
-				unsigned long long end = e->base + e->length;
 
+			if (e->type == E820_RAM && e->length != 0)
 				mark_free(e->base, e->length);
-				if (end > MM_MAX_PHYS)
-					end = MM_MAX_PHYS;
-				if (end > e->base)
-					total_ram_kb +=
-						(unsigned int)((end - e->base) >> 10);
-			}
 		}
 	} else {
 		/* No E820 map (very old BIOS, or first kexec onto an old build):
@@ -121,63 +254,67 @@ void mm_init(void)
 	 * low RAM.  Never hand framebuffer pages to the allocator: the boot
 	 * console draws into the LFB, so an allocated page directory there
 	 * would be overwritten by its own progress line. */
-	{
-		const volatile struct vga_boot_fb_info *fb = VGA_BOOT_FB;
-		unsigned int sz;
-
-		__asm__ volatile ("" : "+r"(fb));
-		sz = (unsigned int)fb->pitch * fb->height;
-		if (!sz)
-			sz = 0x1000000;
-		if (fb->valid && fb->lfb_base && fb->lfb_base < MM_MAX_PHYS)
-			mark_used(fb->lfb_base, sz);
-	}
+	if (lfb_hi > lfb_lo)
+		mark_used(lfb_lo, lfb_hi - lfb_lo);
 
 	/* The boot path copied the command-pack rootfs into high RAM before
 	 * the kernel ran.  Keep it away from the allocator until ramfs_init()
 	 * has taken its own copy. */
-	{
-		unsigned int pa = bootinfo_pack_addr();
-		unsigned int ps = bootinfo_pack_size();
-
-		if (pa >= MM_RESERVE_LOW && pa < MM_MAX_PHYS && ps != 0 &&
-		    ps <= MM_MAX_PHYS && pa + ps > pa &&
-		    pa + ps <= MM_MAX_PHYS)
-			mark_used(pa, ps);
-	}
+	if (pack_hi > pack_lo)
+		mark_used(pack_lo, pack_hi - pack_lo);
+
+	/* The bitmap's own pages. */
+	if (bitmap_bytes)
+		mark_used((unsigned int)bitmap, bitmap_bytes);
 
 	/* Count free pages. */
 	free_pages = 0;
-	for (i = 0; i < MM_BITMAP_BITS; i++) {
-		if (!bit_test(i))
+	for (i = 0; i < bitmap_words; i++) {
+		unsigned int w = ~bitmap[i];
+
+		while (w) {
+			w &= w - 1;
 			free_pages++;
+		}
 	}
+	first_free = 0;
+
+	serial_puts(SERIAL_COM1, "mm: bitmap ");
+	serial_putdec(SERIAL_COM1, bitmap_words * 4u);
+	serial_puts(SERIAL_COM1, " B covers ");
+	serial_putdec(SERIAL_COM1, bitmap_bits / 256u);
+	serial_puts(SERIAL_COM1, " MB at ");
+	serial_puthex(SERIAL_COM1, (unsigned int)bitmap);
+	serial_puts(SERIAL_COM1, "\n");
 }
 
+/* Lowest free page.  Words below first_free are known to be full, so a
+ * steady stream of allocations does not rescan the low, busy part. */
 unsigned int mm_alloc_page(void)
 {
-	unsigned int i, w;
+	unsigned int w;
 	unsigned int flags = irq_disable_save();
 
-	for (w = 0; w < MM_BITMAP_WORDS; w++) {
-		if (bitmap[w] != 0xFFFFFFFFu) {
-			unsigned int word = bitmap[w];
-			for (i = 0; i < 32; i++) {
-				if (!(word & (1u << i))) {
-					unsigned int idx = w * 32 + i;
-					bitmap[w] |= (1u << i);
-					free_pages--;
-					irq_restore(flags);
-					return idx * PAGE_SIZE;
-				}
-			}
+	for (w = first_free; w < bitmap_words; w++) {
+		unsigned int word = bitmap[w];
+
+		if (word != 0xFFFFFFFFu) {
+			unsigned int i = (unsigned int)__builtin_ctz(~word);
+
+			bitmap[w] = word | (1u << i);
+			free_pages--;
+			first_free = w;
+			irq_restore(flags);
+			return (w * 32u + i) * PAGE_SIZE;
 		}
 	}
-
+	first_free = bitmap_words;
 	irq_restore(flags);
 	return 0;
 }
 
+/* Lowest run of n free pages.  Full words break a run and empty words
+ * extend it 32 pages at a time; only mixed words are walked bit by bit. */
 unsigned int mm_alloc_pages(unsigned int n)
 {
 	unsigned int start = 0, run = 0;
@@ -188,23 +325,47 @@ unsigned int mm_alloc_pages(unsigned int n)
 		return 0;
 
 	flags = irq_disable_save();
-	for (p = 0; p < MM_BITMAP_BITS; p++) {
+	p = first_free * 32u;
+	while (p < bitmap_bits) {
+		if ((p & 31u) == 0) {
+			unsigned int word = bitmap[p / 32u];
+
+			if (word == 0xFFFFFFFFu) {
+				run = 0;
+				p += 32;
+				continue;
+			}
+			if (word == 0) {
+				if (run == 0)
+					start = p;
+				run += 32;
+				p += 32;
+				if (run >= n)
+					break;
+				continue;
+			}
+		}
 		if (!bit_test(p)) {
 			if (run == 0)
 				start = p;
 			run++;
-			if (run == n) {
-				unsigned int i;
-				for (i = start; i < start + n; i++)
-					bit_set(i);
-				free_pages -= n;
-				irq_restore(flags);
-				return start * PAGE_SIZE;
-			}
+			p++;
+			if (run == n)
+				break;
 		} else {
 			run = 0;
+			p++;
 		}
 	}
+	if (run >= n) {
+		unsigned int i;
+
+		for (i = start; i < start + n; i++)
+			bit_set(i);
+		free_pages -= n;
+		irq_restore(flags);
+		return start * PAGE_SIZE;
+	}
 	irq_restore(flags);
 	return 0;
 }
@@ -214,13 +375,15 @@ void mm_free_page(unsigned int addr)
 	unsigned int idx = addr / PAGE_SIZE;
 	unsigned int flags;
 
-	if (addr == 0 || idx >= MM_BITMAP_BITS)
+	if (addr == 0 || idx >= bitmap_bits)
 		return;
 
 	flags = irq_disable_save();
 	if (bit_test(idx)) {
 		bit_clear(idx);
 		free_pages++;
+		if (idx / 32u < first_free)
+			first_free = idx / 32u;
 	}
 	irq_restore(flags);
 }

+ 11 - 0
kernel/paging.c

@@ -13,8 +13,19 @@
 #include "cpu.h"
 #include "mm.h"
 #include "mtrr.h"
+#include "process.h"
 #include "serial.h"
 #include "vga.h"
+#include "wm_abi.h"
+
+/* The RAM identity map is made of supervisor 4 MB PDEs; the ring-3 windows
+ * (program/stack, canvases, WM slots, heap) are user page tables above it.
+ * They must never share a PDE. */
+_Static_assert(MM_MAX_PHYS <= USER_BASE, "identity map overlaps user space");
+_Static_assert(MM_MAX_PHYS <= USER_WIN_BASE &&
+	       MM_MAX_PHYS <= WM_CONTENT_VA_BASE &&
+	       MM_MAX_PHYS <= USER_HEAP_BASE,
+	       "identity map overlaps a ring-3 window");
 
 /* CR4 bits that must not survive a BIOS protected-mode call.  A BIOS that
  * returns with CR4.PAE or EFER.LME set makes the first CR0.PG enable either

+ 44 - 9
user/apps/browser/browser.c

@@ -400,6 +400,8 @@ static unsigned int form_option_text(unsigned int node, unsigned int idx,
 	return 0;
 }
 
+static int form_is_control(unsigned int node);
+
 static struct form_state *form_get(unsigned int node, int create)
 {
 	struct form_state *slot = 0;
@@ -413,6 +415,22 @@ static struct form_state *form_get(unsigned int node, int create)
 			slot = &form_states[i];
 		}
 	}
+	if (create && !slot) {
+		/* Full: a client-side router (Docusaurus' React Router)
+		 * replaces page content without a navigation, so slots of
+		 * controls that left the document pile up until no new
+		 * control can be drawn or focused.
+		 * Reuse those first, then slots of nodes that are no longer
+		 * controls. */
+		for (i = 0; i < FORM_MAX && !slot; i++)
+			if (form_states[i].node != form_focus &&
+			    br_node_detached(&doc, form_states[i].node))
+				slot = &form_states[i];
+		for (i = 0; i < FORM_MAX && !slot; i++)
+			if (form_states[i].node != form_focus &&
+			    !form_is_control(form_states[i].node))
+				slot = &form_states[i];
+	}
 	if (!create || !slot)
 		return 0;
 	slot->node = node;
@@ -8282,10 +8300,14 @@ static void svg_draw_node(struct svgr_layer *L, unsigned int node,
 			double ow = svg_vp_w, oh = svg_vp_h;
 
 			if (svg_viewbox4(tgt, vb)) {
-				double w = svg_attr_num(node, "width", vb[2],
-							ow);
-				double h = svg_attr_num(node, "height", vb[3],
-							oh);
+				/* A <use> without width/height sizes the
+				 * symbol to 100% of the viewport: Docusaurus'
+				 * 13.5px external-link icon references a
+				 * 24-unit symbol and showed only its corner. */
+				double w = svg_attr_num(node, "width",
+							ow > 0 ? ow : vb[2], ow);
+				double h = svg_attr_num(node, "height",
+							oh > 0 ? oh : vb[3], oh);
 				double vm[6];
 
 				svg_viewport_matrix(tgt, vb, w, h, vm);
@@ -12454,6 +12476,10 @@ static void draw_status(struct ngui_rect r)
 	ngui_fill_rect(&ui, r, ui.theme.panel);
 	ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
 		       ui.theme.border);
+	/* A form control under the pointer is not a link. */
+	if (hover && !br_href(&doc, (unsigned int)hover) &&
+	    form_is_control((unsigned int)hover))
+		hover = 0;
 	if (hover) {
 		const char *href = br_href(&doc, (unsigned int)hover);
 		char url[BR_URL_MAX];
@@ -12843,14 +12869,26 @@ static void form_click(unsigned int node)
 		return;
 	if (form_focus != node)
 		form_blur();
-	if (!js_browser_event(node, "click", 1, 1))
-		return;
 	fs = form_get(node, 1);
 	if (!fs)
 		return;
 	kind = form_kind_of(node);
+	/* Focus moves on the press, before `click` is dispatched: a page
+	 * that cancels the click (a framework's root listener) suppresses
+	 * the activation behaviour below, never the focus (as in other
+	 * browsers, where focus follows mousedown). */
 	form_focus = node;
 	form_dirty = 0;
+	if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
+	    kind == FORM_TEXTAREA)
+		fs->caret = fs->len;
+	layout_valid = 0;
+	ngui_invalidate(&ui);
+	if (!js_browser_event(node, "click", 1, 1))
+		return;
+	fs = form_get(node, 0);     /* the handler may have changed the DOM */
+	if (!fs)
+		return;
 	if (kind == FORM_CHECKBOX) {
 		fs->checked = !fs->checked;
 		changed = 1;
@@ -12889,9 +12927,6 @@ static void form_click(unsigned int node)
 	} else if (kind == FORM_RESET) {
 		form_reset_event(form_ancestor(node));
 		return;
-	} else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
-		   kind == FORM_TEXTAREA) {
-		fs->caret = fs->len;
 	}
 	if (changed) {
 		js_browser_event(node, "input", 1, 0);

+ 38 - 2
user/apps/browser/browser_html.c

@@ -980,6 +980,11 @@ static void doc_reset(struct br_doc *d)
 		d->nodes[i].type = BR_NODE_ELEM;
 		d->nodes[i].tag = BR_TAG_UNKNOWN;
 		d->nodes[i].flags = 0;
+		/* The cached disabled/open/inert bits must not survive into
+		 * the next page: a slot that held a disabled control made
+		 * Docusaurus' search field unfocusable after navigating (and
+		 * real hardware does not hand out zeroed memory). */
+		d->nodes[i].attr_flags = 0;
 		d->nodes[i].parent = 0;
 		d->nodes[i].first = d->nodes[i].last = 0;
 		d->nodes[i].next = 0;
@@ -1002,6 +1007,8 @@ static void doc_reset(struct br_doc *d)
 	}
 }
 
+static void node_zero(struct br_node *n);
+
 static unsigned int node_append(struct br_doc *d, unsigned int parent,
 				unsigned char type, unsigned char tag)
 {
@@ -1014,11 +1021,10 @@ static unsigned int node_append(struct br_doc *d, unsigned int parent,
 	}
 	idx = d->nnode++;
 	n = &d->nodes[idx];
+	node_zero(n);           /* every field, attr_flags included */
 	n->type = type;
 	n->tag = tag;
 	n->parent = (unsigned short)parent;
-	n->img_index = -1;
-	n->bg_img_index = -1;
 	if (d->nodes[parent].last)
 		d->nodes[d->nodes[parent].last].next = (unsigned short)idx;
 	else
@@ -1116,6 +1122,11 @@ static int node_detached(struct br_doc *d, unsigned int node)
 	return 0;
 }
 
+int br_node_detached(struct br_doc *d, unsigned int node)
+{
+	return !d || node >= d->nnode || node_detached(d, node);
+}
+
 unsigned int br_find_id(struct br_doc *d, const char *id)
 {
 	unsigned int i;
@@ -1781,6 +1792,8 @@ int br_set_attr(struct br_doc *d, unsigned int node, const char *name,
 	return 0;
 }
 
+static void clear_attr_flag(struct br_node *n, const char *name);
+
 int br_remove_attr(struct br_doc *d, unsigned int node, const char *name)
 {
 	struct br_node *n;
@@ -1825,6 +1838,8 @@ int br_remove_attr(struct br_doc *d, unsigned int node, const char *name)
 	n->style_valid = 0;
 	n->pe_state = 0;
 	attr_note_known(d, n, name, "", 0);
+	if (found)
+		clear_attr_flag(n, name);
 	return found ? 0 : -1;
 }
 
@@ -2053,6 +2068,27 @@ static int parse_svg_viewbox(const char *s, unsigned int len,
 	return *w && *h;
 }
 
+/* The inverse of note_attr_flag() for a removed attribute.  The cached
+ * bit used to outlive the attribute: `input.disabled = false` removed
+ * `disabled` but left BR_ATTR_DISABLED set, so a field a script disabled
+ * once (Docusaurus' search box while its index loads) never took focus
+ * again. */
+static void clear_attr_flag(struct br_node *n, const char *name)
+{
+	if (str_eq(name, "data-collapse-target"))
+		n->attr_flags &= (unsigned char)~BR_ATTR_COLLAPSE_TARGET;
+	else if (str_eq(name, "data-collapse-trigger"))
+		n->attr_flags &= (unsigned char)~BR_ATTR_COLLAPSE_TRIGGER;
+	else if (str_eq(name, "is-open"))
+		n->attr_flags &= (unsigned char)~BR_ATTR_IS_OPEN;
+	else if (str_eq(name, "disabled"))
+		n->attr_flags &= (unsigned char)~BR_ATTR_DISABLED;
+	else if (str_eq(name, "open"))
+		n->attr_flags &= (unsigned char)~BR_ATTR_OPEN;
+	else if (str_eq(name, "inert"))
+		n->attr_flags &= (unsigned char)~BR_ATTR_INERT;
+}
+
 static void note_attr_flag(struct br_node *n, const char *name)
 {
 	if (str_eq(name, "data-collapse-target"))

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

@@ -398,6 +398,8 @@ void br_set_font_base(const char *base);
  * text nodes into out and returns the (possibly truncated) length. */
 unsigned int br_find_id(struct br_doc *d, const char *id);
 unsigned int br_find_tag(struct br_doc *d, unsigned int tag);
+/* 1 when the node is not in the document (removed, or never inserted). */
+int br_node_detached(struct br_doc *d, unsigned int node);
 unsigned int br_text_content(struct br_doc *d, unsigned int node,
 			     char *out, unsigned int cap);
 int br_set_text_content(struct br_doc *d, unsigned int node,

+ 4 - 10
user/apps/chat/ucmd_chat.c

@@ -2666,7 +2666,7 @@ static void draw_login(void)
 static void draw_sidebar(struct ngui_rect r)
 {
 	struct ngui_rect list, btns, b;
-	int y, i, section, row_w, scrolls;
+	int y, i, section, row_w;
 	int lh = line_h();
 
 	ngui_fill_rect(&ui, r, ui.theme.panel);
@@ -2683,8 +2683,7 @@ static void draw_sidebar(struct ngui_rect r)
 	side_scroll.content_h = 2 * SIDE_HEAD + nconv * SIDE_ROW + 8;
 	ngui_scroll_begin(&ui, list, &side_scroll);
 	ngui_scroll_wheel(&ui, list, &side_scroll);
-	scrolls = side_scroll.content_h > side_scroll.view_h;
-	row_w = list.w - (scrolls ? 16 : 0);
+	row_w = list.w;
 	y = list.y - side_scroll.offset;
 	for (section = 0; section < 2; section++) {
 		ngui_text_px(&ui, list.x + 10, y + 6,
@@ -2854,19 +2853,14 @@ static void draw_timeline(struct ngui_rect r)
 			  ui.theme.text_dim);
 		return;
 	}
-	tl_width = r.w - 16;
+	tl_width = r.w;
 	total = content_height();
 	tl_scroll.content_h = total;
 	ngui_scroll_begin(&ui, r, &tl_scroll);
 	if (ngui_scroll_wheel(&ui, r, &tl_scroll))
 		last_input_ms = u_ticks_ms();
 	scrolls = total > r.h;
-	width = r.w - (scrolls ? 16 : 0);
-	if (width != tl_width) {
-		tl_width = width;
-		total = content_height();
-		tl_scroll.content_h = total;
-	}
+	width = r.w;
 	/* Scrolling to the very top pages in older history by itself (the
 	 * button stays for the pointer).  Rate-limited so a failing request
 	 * cannot spin. */

+ 8 - 22
user/apps/disks/ucmd_disks.c

@@ -609,18 +609,6 @@ static void draw_toolbar(struct ngui_rect r)
 	}
 }
 
-/* ngui's scroll pane paints its bar over the right edge of the pane, so the
- * content must leave that strip free while the pane scrolls. */
-#define SCROLLBAR_ROOM 20
-
-static struct ngui_rect scroll_content(struct ngui_rect area,
-				       const struct ngui_scroll *s)
-{
-	if (!s->hide_bar && s->content_h > s->view_h)
-		area.w -= SCROLLBAR_ROOM;
-	return area;
-}
-
 /* Empty IDE channels and absent eMMC/USB slots are registered as devices
  * but have nothing to show; a floppy drive is listed without media too. */
 static int listed(const struct disk *d)
@@ -642,7 +630,7 @@ static void draw_device_list(struct ngui_rect area)
 	list_scroll.content_h = (y + 1) * ROW_H + 2 * SECTION_H;
 	ngui_scroll_begin(&ui, area, &list_scroll);
 	ngui_scroll_wheel(&ui, area, &list_scroll);
-	col = scroll_content(area, &list_scroll);
+	col = area;
 	y = area.y - list_scroll.offset;
 
 	r = (struct ngui_rect){ col.x, y, col.w, SECTION_H };
@@ -999,17 +987,14 @@ static int draw_disk(struct ngui_rect area, int y, struct disk *d)
 static void draw_details(struct ngui_rect area)
 {
 	struct ngui_rect col;
-	int y, top, had_bar;
+	int y, top;
 
 	ngui_inset(&area, 14);
 	ngui_scroll_begin(&ui, area, &detail_scroll);
 	ngui_scroll_wheel(&ui, area, &detail_scroll);
 	if (!ui.focus)
 		ngui_scroll_keys(&ui, &detail_scroll);
-	/* The height is only known after drawing, so the bar decision uses
-	 * the previous frame's; redraw once when it flips. */
-	col = scroll_content(area, &detail_scroll);
-	had_bar = col.w != area.w;
+	col = area;
 	top = area.y - detail_scroll.offset;
 	if (sel_disk < 0)
 		y = draw_overview(col, top);
@@ -1017,8 +1002,6 @@ static void draw_details(struct ngui_rect area)
 		y = draw_disk(col, top, &disks[sel_disk]);
 	detail_scroll.content_h = y - top;
 	ngui_scroll_end(&ui, area, &detail_scroll);
-	if (had_bar != (scroll_content(area, &detail_scroll).w != area.w))
-		ngui_invalidate(&ui);
 }
 
 /* ---- dialogs ---- */
@@ -1032,9 +1015,12 @@ static struct ngui_rect dialog_rect(int w, int h)
 	r.x = (ui.w - r.w) / 2;
 	r.y = (ui.h - r.h) / 2;
 	ngui_fill_round_rect(&ui, (struct ngui_rect){ r.x - 1, r.y - 1,
-				  r.w + 2, r.h + 2 }, 9, 9, 9, 9,
+				  r.w + 2, r.h + 2 },
+			     NGUI_RADIUS + 1, NGUI_RADIUS + 1,
+			     NGUI_RADIUS + 1, NGUI_RADIUS + 1,
 			     ui.theme.border);
-	ngui_fill_round_rect(&ui, r, 8, 8, 8, 8, ui.theme.panel);
+	ngui_fill_round_rect(&ui, r, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
 	return r;
 }
 

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

@@ -16,7 +16,6 @@
 #define FM_PATH_H       26
 #define FM_STATUS_H     18
 #define FM_SIDEBAR_W    140
-#define FM_SCROLL_W     9
 #define FM_EDIT_MAX     16384
 #define FM_STATUS_MS    3000
 
@@ -815,7 +814,6 @@ static void draw_sidebar(struct ngui *g, struct ngui_rect r, unsigned int *actio
 static void draw_list(struct ngui *g, struct ngui_rect r, unsigned int *action)
 {
 	unsigned int i;
-	int scrolls;
 	int row_w;
 	int hover_idx = -1;
 	int press_idx = -1;
@@ -824,8 +822,7 @@ static void draw_list(struct ngui *g, struct ngui_rect r, unsigned int *action)
 	list_scroll.content_h = (int)(entry_count * FM_ROW_H);
 	ngui_scroll_begin(g, r, &list_scroll);
 	ngui_scroll_wheel(g, r, &list_scroll);
-	scrolls = list_scroll.content_h > list_scroll.view_h;
-	row_w = r.w - (scrolls ? FM_SCROLL_W : 0);
+	row_w = r.w;
 
 	if (g->inside && g->mouse_x >= r.x && g->mouse_x < r.x + row_w &&
 	    g->mouse_y >= r.y && g->mouse_y < r.y + r.h &&

+ 5 - 7
user/apps/gallery/gallery.c

@@ -914,7 +914,7 @@ static void draw_scroll(struct ngui *g, struct ngui_rect card)
 	scroll_pane_valid = 1;
 	ngui_text_ellipsis(g, rect_make(x, top, card.w - 2 * CARD_PAD, 16),
 			   x, top,
-			   "A nested pane: click a row, drag its scrollbar.",
+			   "A nested pane: hover for its scrollbar, then drag it.",
 			   g->theme.text_dim);
 
 	list_scroll.content_h = LIST_ROWS * LIST_ROW_H;
@@ -922,8 +922,7 @@ static void draw_scroll(struct ngui *g, struct ngui_rect card)
 	ngui_scroll_begin(g, pane, &list_scroll);
 	ngui_scroll_wheel(g, pane, &list_scroll);
 
-	if (g->pressed && ngui_rect_contains(&pane, g->press_x, g->press_y) &&
-	    g->press_x < pane.x + pane.w - 9) {
+	if (g->pressed && ngui_rect_contains(&pane, g->press_x, g->press_y)) {
 		int idx = (g->press_y - pane.y + list_scroll.offset) /
 			LIST_ROW_H;
 
@@ -947,14 +946,13 @@ static void draw_scroll(struct ngui *g, struct ngui_rect card)
 
 	for (i = 0; i < LIST_ROWS; i++) {
 		int ry = pane.y + i * LIST_ROW_H - list_scroll.offset;
-		struct ngui_rect row = rect_make(pane.x, ry, pane.w - 9,
+		struct ngui_rect row = rect_make(pane.x, ry, pane.w,
 						 LIST_ROW_H);
 		char label[64];
 		unsigned int n = 0;
 		unsigned short bg;
 		int hover = g->inside &&
 			ngui_rect_contains(&pane, g->mouse_x, g->mouse_y) &&
-			g->mouse_x < pane.x + pane.w - 9 &&
 			(g->mouse_y - pane.y + list_scroll.offset) /
 				LIST_ROW_H == i;
 
@@ -976,7 +974,7 @@ static void draw_scroll(struct ngui *g, struct ngui_rect card)
 			s_append(label, &n, " ", sizeof(label));
 		s_append(label, &n, list_items[i], sizeof(label));
 		ngui_text_ellipsis(g, rect_make(pane.x + 32, ry + 4,
-						pane.w - 9 - 44, 16),
+						pane.w - 44, 16),
 				   pane.x + 32, ry + 4, label,
 				   i == list_selected ? g->theme.text :
 							g->theme.text_dim);
@@ -1123,7 +1121,7 @@ static void draw_cursors(struct ngui *g, struct ngui_rect card)
 static void draw_body(struct ngui *g, struct ngui_rect body)
 {
 	int x = body.x + PAGE_PAD;
-	int w = body.w - PAGE_PAD * 2 - 9;
+	int w = body.w - PAGE_PAD * 2;
 	int i;
 
 	page.content_h = sec_content_h;

+ 10 - 7
user/apps/netmenu/ucmd_netmenu.c

@@ -1054,8 +1054,10 @@ static void draw_status_card(struct ngui_rect r)
 	else
 		dot_color = ui.theme.success;
 
-	ngui_fill_round_rect(&ui, r, 8, 8, 8, 8, ui.theme.panel);
-	ngui_frame_round(&ui, r, 8, 8, 8, 8, 1, ui.theme.panel_alt);
+	ngui_fill_round_rect(&ui, r, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
+	ngui_frame_round(&ui, r, NGUI_RADIUS, NGUI_RADIUS,
+			 NGUI_RADIUS, NGUI_RADIUS, 1, ui.theme.panel_alt);
 	ngui_fill_round_rect(&ui, dot, 5, 5, 5, 5, dot_color);
 
 	p = line;
@@ -1208,7 +1210,8 @@ static void draw_summary(struct ngui_rect r)
 		dot = ui.theme.warning;
 	}
 
-	ngui_fill_round_rect(&ui, r, 10, 10, 10, 10, ui.theme.panel);
+	ngui_fill_round_rect(&ui, r, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
 	ngui_fill_round_rect(&ui,
 		(struct ngui_rect){ r.x + 14, r.y + 23, 10, 10 },
 		5, 5, 5, 5, dot);
@@ -1245,7 +1248,8 @@ static void draw_brightness(struct ngui_rect r)
 	int v = brightness;
 	int tw;
 
-	ngui_fill_round_rect(&ui, r, 10, 10, 10, 10, ui.theme.panel);
+	ngui_fill_round_rect(&ui, r, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
 	ngui_text_px(&ui, r.x + 14, r.y + 6, "Brightness", 10,
 		     ui.theme.text, 14, 1, 0, 0);
 	p = put_dec(b, (unsigned int)(v < 0 ? 0 : v));
@@ -1853,7 +1857,8 @@ static void draw_connect(void)
 	 * the popover footer. */
 	log = body;
 	log.h -= 38;
-	ngui_fill_round_rect(&ui, log, 6, 6, 6, 6, ui.theme.panel);
+	ngui_fill_round_rect(&ui, log, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
 	ngui_push_clip(&ui, (struct ngui_rect){ log.x + 8, log.y + 8,
 						log.w - 16, log.h - 16 });
 
@@ -1999,8 +2004,6 @@ void _start(const char *arg)
 	view = VIEW_MAIN;
 	expanded = EXPAND_NONE;
 	main_scroll.offset = 0;
-	main_scroll.hide_bar = 1;
-	saved_scroll.hide_bar = 1;
 
 	load_devices();
 	load_status();

+ 206 - 81
user/lib/ngui/ngui.c

@@ -598,23 +598,28 @@ static int ngui_isqrt(int v)
 	return r;
 }
 
-/* Horizontal inset of one scanline of a corner with the given radius. */
+/* Horizontal inset of one scanline of a corner with the given radius.
+ * Samples the pixel centre, so a corner is as wide as it is tall. */
 static int round_inset(int y, int h, int r)
 {
-	int dy, d2;
+	int dy2, d2;
 
 	if (r <= 0)
 		return 0;
 	if (y < r)
-		dy = r - y - 1;
+		dy2 = 2 * r - 2 * y - 1;
 	else if (y >= h - r)
-		dy = y - (h - r);
+		dy2 = 2 * (y - (h - r)) + 1;
 	else
 		return 0;
-	d2 = r * r - dy * dy;
+	/* d2 = (2r)^2 - dy2^2 = 4 * (r^2 - dy^2).  The inset is
+	 * r - floor(sqrt(d2) / 2 + 0.5), i.e. r - (isqrt(d2) + 1) / 2.
+	 * d2 is 3 or 7 mod 8, never a perfect square, so the rounded
+	 * square root is exact. */
+	d2 = 4 * r * r - dy2 * dy2;
 	if (d2 < 0)
 		d2 = 0;
-	return r - ngui_isqrt(d2);
+	return r - (ngui_isqrt(d2) + 1) / 2;
 }
 
 void ngui_fill_round_rect(struct ngui *ui, struct ngui_rect r,
@@ -1546,7 +1551,8 @@ static int ngui_list_row_common(struct ngui *ui, unsigned int id,
 	else if (hot || ui->active == id)
 		bg = ui->theme.panel_alt;
 	if (bg)
-		ngui_fill_round_rect(ui, r, 6, 6, 6, 6, bg);
+		ngui_fill_round_rect(ui, r, NGUI_RADIUS, NGUI_RADIUS,
+				     NGUI_RADIUS, NGUI_RADIUS, bg);
 	title_h = ngui_text_line_height(ui, ui->font_px, 0);
 	fg = ui->theme.text;
 	sub_fg = row->selected ? ui->theme.text : ui->theme.text_dim;
@@ -1662,7 +1668,8 @@ int ngui_tile(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		bg = ui->theme.button_hot;
 	else
 		bg = ui->theme.panel_alt;
-	ngui_fill_round_rect(ui, r, 10, 10, 10, 10, bg);
+	ngui_fill_round_rect(ui, r, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, bg);
 	fg = ui->theme.text;
 	sub_fg = on ? ui->theme.text : ui->theme.text_dim;
 
@@ -2290,81 +2297,188 @@ void ngui_scroll_ensure_visible(struct ngui_scroll *s, int y, int h)
 	scroll_clamp(s);
 }
 
+#define SCROLLBAR_W       8
+#define SCROLLBAR_INSET   2
+#define SCROLLBAR_HIT_W   14
+#define SCROLLBAR_STEPS   8
+#define SCROLLBAR_STEP_MS 14
+
+static struct ngui_rect scroll_track_rect(const struct ngui_rect *r)
+{
+	struct ngui_rect t;
+	int inset = SCROLLBAR_INSET;
+
+	if (r->w < SCROLLBAR_W + 2 * inset || r->h <= 2 * inset)
+		inset = 0;
+	t.x = r->x + r->w - SCROLLBAR_W - inset;
+	t.y = r->y + inset;
+	t.w = SCROLLBAR_W;
+	t.h = r->h - 2 * inset;
+	return t;
+}
+
+static struct ngui_rect scroll_hit_rect(const struct ngui_rect *r)
+{
+	struct ngui_rect h = *r;
+	int w = SCROLLBAR_HIT_W;
+
+	if (w > r->w)
+		w = r->w;
+	h.x = r->x + r->w - w;
+	h.w = w;
+	return h;
+}
+
+static int pointer_in_rect(struct ngui *ui, const struct ngui_rect *r)
+{
+	if (!ui->inside || !ngui_rect_contains(r, ui->mouse_x, ui->mouse_y))
+		return 0;
+	if (ui->nclip > 0 &&
+	    !ngui_rect_contains(&ui->clip[ui->nclip - 1], ui->mouse_x,
+				ui->mouse_y))
+		return 0;
+	return 1;
+}
+
+/* Width of the pill for one animation step.  The bar grows into the pane
+ * from its right edge, so the animation needs no alpha compositing. */
+static int scroll_bar_w(int vis)
+{
+	if (vis <= 0)
+		return 0;
+	if (vis >= SCROLLBAR_STEPS)
+		return SCROLLBAR_W;
+	return 1 + (vis - 1) * (SCROLLBAR_W - 1) / (SCROLLBAR_STEPS - 1);
+}
+
+/* Advance the overlay bar animation.  The bar stays hidden while the pointer
+ * is outside the pane and slides in on hover; a drag pins it open.  Setting
+ * ui->dirty while steps remain makes the app draw the next frame. */
+static void scroll_bar_update(struct ngui *ui, const struct ngui_rect *r,
+			      struct ngui_scroll *s)
+{
+	int hover, target, steps;
+	unsigned int now, due;
+
+	if (s->hide_bar || !scrollable(s)) {
+		s->dragging = 0;
+		s->bar_vis = 0;
+		s->bar_target = 0;
+		s->bar_hot = 0;
+		return;
+	}
+
+	{
+		struct ngui_rect hit = scroll_hit_rect(r);
+
+		hover = pointer_in_rect(ui, r);
+		s->bar_hot = hover &&
+			     ngui_rect_contains(&hit, ui->mouse_x, ui->mouse_y);
+	}
+	target = (hover || s->dragging) ? SCROLLBAR_STEPS : 0;
+	now = u_ticks_ms();
+	if (target != s->bar_target) {
+		s->bar_target = target;
+		s->bar_ms = now;
+		if (s->bar_vis != target)
+			ui->dirty = 1;
+		return;
+	}
+	if (s->bar_vis == target)
+		return;
+
+	due = now - s->bar_ms;
+	steps = (int)(due / SCROLLBAR_STEP_MS);
+	if (steps > 0) {
+		if (target > s->bar_vis) {
+			s->bar_vis += steps;
+			if (s->bar_vis > target)
+				s->bar_vis = target;
+		} else {
+			s->bar_vis -= steps;
+			if (s->bar_vis < target)
+				s->bar_vis = target;
+		}
+		s->bar_ms += (unsigned int)steps * SCROLLBAR_STEP_MS;
+	}
+	if (s->bar_vis != target)
+		ui->dirty = 1;
+}
+
+static void scroll_bar_press(struct ngui_scroll *s,
+			     const struct ngui_rect *track, int th, int y)
+{
+	int ty = scroll_thumb_y(track, s);
+
+	if (y >= ty && y < ty + th) {
+		s->dragging = 1;
+		s->drag_dy = y - ty;
+	} else {
+		int rel = y - track->y - th / 2;
+		int avail = track->h - th;
+		int max = s->content_h - s->view_h;
+
+		if (rel < 0)
+			rel = 0;
+		if (rel > avail)
+			rel = avail;
+		if (avail > 0)
+			s->offset = rel * max / avail;
+		s->dragging = 1;
+		s->drag_dy = th / 2;
+		scroll_clamp(s);
+	}
+}
+
+static void scroll_bar_drag(struct ngui_scroll *s,
+			    const struct ngui_rect *track, int th, int y)
+{
+	int rel = y - track->y - s->drag_dy;
+	int avail = track->h - th;
+	int max = s->content_h - s->view_h;
+
+	if (rel < 0)
+		rel = 0;
+	if (rel > avail)
+		rel = avail;
+	if (avail > 0)
+		s->offset = rel * max / avail;
+	scroll_clamp(s);
+}
+
 void ngui_scroll_begin(struct ngui *ui, struct ngui_rect r,
 		       struct ngui_scroll *s)
 {
-	struct ngui_rect bar;
-	int scrolls = scrollable(s);
+	struct ngui_rect track, hit;
+	int th;
 
 	s->view_h = r.h;
 	scroll_clamp(s);
 	if (!ui->buttons)
 		s->dragging = 0;
-	if (s->hide_bar)
-		s->dragging = 0;
-	if (!s->hide_bar && scrolls) {
-		int th = scroll_thumb_h(&r, s);
-		int ty = scroll_thumb_y(&r, s);
+	scroll_bar_update(ui, &r, s);
 
-		bar = rect_make(r.x + r.w - 15, r.y, 14, r.h);
+	if (!s->hide_bar && scrollable(s)) {
+		track = scroll_track_rect(&r);
+		hit = scroll_hit_rect(&r);
+		th = scroll_thumb_h(&track, s);
 		if (ui->pressed &&
-		    ngui_rect_contains(&bar, ui->press_x, ui->press_y)) {
-			if (ui->press_y >= ty && ui->press_y < ty + th) {
-				s->dragging = 1;
-				s->drag_dy = ui->press_y - ty;
-			} else {
-				int rel = ui->press_y - r.y - th / 2;
-				int avail = r.h - th;
-				int max = s->content_h - s->view_h;
-
-				if (rel < 0)
-					rel = 0;
-				if (rel > avail)
-					rel = avail;
-				if (avail > 0)
-					s->offset = rel * max / avail;
-				s->dragging = 1;
-				s->drag_dy = th / 2;
-				scroll_clamp(s);
-			}
+		    ngui_rect_contains(&hit, ui->press_x, ui->press_y)) {
+			scroll_bar_press(s, &track, th, ui->press_y);
+			/* The bar is on top of the content: a drag must not
+			 * also activate a row or button below it. */
+			ui->pressed = 0;
+			ui->clicked = 0;
 		}
-		/* Sampled buttons are authoritative while held: some event paths
-		 * deliver the press late or coalesce it with the release.  Start
-		 * the drag from the current pointer position as well. */
+		/* Sampled buttons are authoritative while held: some event
+		 * paths deliver the press late or coalesce it with the
+		 * release.  Start the drag from the current pointer position
+		 * as well, but only once the bar is fully visible. */
 		if (!s->dragging && (ui->buttons & 1) &&
-		    ngui_rect_contains(&bar, ui->mouse_x, ui->mouse_y)) {
-			if (ui->mouse_y >= ty && ui->mouse_y < ty + th) {
-				s->dragging = 1;
-				s->drag_dy = ui->mouse_y - ty;
-			} else {
-				int rel = ui->mouse_y - r.y - th / 2;
-				int avail = r.h - th;
-				int max = s->content_h - s->view_h;
-
-				if (rel < 0)
-					rel = 0;
-				if (rel > avail)
-					rel = avail;
-				if (avail > 0)
-					s->offset = rel * max / avail;
-				s->dragging = 1;
-				s->drag_dy = th / 2;
-				scroll_clamp(s);
-			}
-		}
-		if (s->dragging && (ui->buttons & 1)) {
-			int rel = ui->mouse_y - r.y - s->drag_dy;
-			int avail = r.h - th;
-			int max = s->content_h - s->view_h;
-
-			if (rel < 0)
-				rel = 0;
-			if (rel > avail)
-				rel = avail;
-			if (avail > 0)
-				s->offset = rel * max / avail;
-			scroll_clamp(s);
-		}
+		    s->bar_hot && s->bar_vis == SCROLLBAR_STEPS)
+			scroll_bar_press(s, &track, th, ui->mouse_y);
+		if (s->dragging && (ui->buttons & 1))
+			scroll_bar_drag(s, &track, th, ui->mouse_y);
 		if (ui->released)
 			s->dragging = 0;
 	}
@@ -2374,19 +2488,30 @@ void ngui_scroll_begin(struct ngui *ui, struct ngui_rect r,
 void ngui_scroll_end(struct ngui *ui, struct ngui_rect r,
 		     struct ngui_scroll *s)
 {
+	struct ngui_rect track, thumb;
+	int bw, th, ty;
+	unsigned short color;
+
 	ngui_pop_clip(ui);
-	if (s->hide_bar || !scrollable(s))
+	/* content_h is often known only after drawing, so advance the state
+	 * here as well; a new target requests a follow-up frame. */
+	scroll_bar_update(ui, &r, s);
+	if (s->hide_bar || !scrollable(s) || s->bar_vis <= 0)
 		return;
-	{
-		struct ngui_rect bar = rect_make(r.x + r.w - 15, r.y, 14, r.h);
-		int th = scroll_thumb_h(&r, s);
-		int ty = scroll_thumb_y(&r, s);
-		struct ngui_rect thumb = rect_make(bar.x, ty, 14, th);
 
-		ngui_fill_rect(ui, bar, ui->theme.panel_alt);
-		ngui_fill_rect(ui, thumb, s->dragging ?
-			       ui->theme.accent : ui->theme.text_dim);
-	}
+	track = scroll_track_rect(&r);
+	bw = scroll_bar_w(s->bar_vis);
+	if (bw <= 0)
+		return;
+	th = scroll_thumb_h(&track, s);
+	ty = scroll_thumb_y(&track, s);
+	thumb = rect_make(r.x + r.w - SCROLLBAR_INSET - bw, ty, bw, th);
+	color = s->dragging ? ui->theme.accent :
+		s->bar_hot ? ui->theme.text_dim : ui->theme.border;
+	ngui_fill_round_rect(ui, thumb, bw / 2, bw / 2, bw / 2, bw / 2,
+			     color);
+	if (s->bar_hot)
+		ngui_set_cursor(ui, CURSOR_DEFAULT);
 }
 
 int ngui_scroll_wheel(struct ngui *ui, struct ngui_rect r,

+ 9 - 0
user/lib/ngui/ngui.h

@@ -13,6 +13,9 @@
 #define NGUI_INPUT_MAX 512
 #define NGUI_MOTION_REDRAW_MS 33
 
+/* Corner radius shared by cards, tiles, list rows and dialogs. */
+#define NGUI_RADIUS 6
+
 #define NGUI_INPUT_CHANGED 1
 #define NGUI_INPUT_SUBMIT  2
 #define NGUI_INPUT_CANCEL  4
@@ -104,6 +107,12 @@ struct ngui_scroll {
 	int dragging;
 	int drag_dy;
 	int hide_bar;                 /* wheel/keys only; draw no scrollbar */
+	/* The bar is an overlay: it reserves no layout width, stays hidden
+	 * while the pointer is outside the pane and slides in on hover. */
+	int bar_vis;                  /* 0 hidden .. animation target shown */
+	int bar_target;               /* requested visibility (0 or full) */
+	int bar_hot;                  /* pointer is over the scrollbar strip */
+	unsigned int bar_ms;          /* last animation step (u_ticks_ms) */
 };
 
 struct ngui_slider {