Răsfoiți Sursa

Add the disks storage manager with mount policies

A new ngui app, `disks` (also a Disks button in the files toolbar), lists
the block devices with their MBR partitions and every mount, formats a
device and installs or updates NebOS on it, and configures how each FAT
volume is mounted.

Kernel:
- SYS_BLK_READ (119) reads one raw sector for the partition view.
- SYS_MOUNT_CTL (120) sets/gets per-volume mount policies (mount name,
  read-only, do not mount), keyed by the default mount name; vfs.c applies
  them on every scan and remounts the device when one changes.
- Read-only mounts now refuse write/unlink/mkdir/rmdir with SYS_EROFS.
- The boot scan applies the policies saved in /data/MOUNTS.CFG.
- struct sys_mount carries the source device and the volume key.
- `format -y` and `install -y` skip the keyboard prompt; the app confirms
  in its own dialog and shows the command output from a private tty.

Docs: filesystems/userland/index pages and AGENTS.md.

Co-Authored-By: Claude <noreply@anthropic.com>
Johannes Zellner 3 zile în urmă
părinte
comite
a258507718
16 a modificat fișierele cu 1679 adăugiri și 20 ștergeri
  1. 30 6
      AGENTS.md
  2. 5 1
      Makefile
  3. 28 2
      docs/filesystems.html
  4. 1 1
      docs/index.html
  5. 6 1
      docs/userland.html
  6. 31 0
      include/syscall.h
  7. 15 1
      kernel/format.c
  8. 14 0
      kernel/install.c
  9. 2 0
      kernel/kernel.c
  10. 104 4
      kernel/sys_fs.c
  11. 3 0
      kernel/sys_fs.h
  12. 4 0
      kernel/syscall.c
  13. 108 4
      kernel/vfs.c
  14. 11 0
      kernel/vfs.h
  15. 1302 0
      user/apps/disks/ucmd_disks.c
  16. 15 0
      user/apps/files/ucmd_files.c

+ 30 - 6
AGENTS.md

@@ -501,7 +501,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   primitives, buttons, text input, the Adwaita symbolic icons and scrolling panes
   (`ngui_scroll`; `hide_bar` keeps wheel/key scrolling without drawing a
   scrollbar).
-  `files` (`ucmd_files.c`) is its first user; `gallery` (`gallery.c`) is the
+  `files` (`ucmd_files.c`) is its first user (its toolbar's `Disks`
+  button opens the storage manager); `gallery` (`gallery.c`) is the
   live showcase of every control and primitive the toolkit exports.  Buttons
   fire on the release edge and keep `active` until `ui->released`: inferring
   release from the sampled `ui->buttons` races the WM event queue and drops
@@ -710,6 +711,29 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   it when absent.  It refuses a raw runtime pack (`cmds-dev`/`net-cmds`/
   `kernel-dev`); use `net-install` for that.  `target=auto` picks the only
   non-USB NebOS disk.
+- **Storage manager / mount policies**: `ucmd_disks.c` (`disks`, and the
+  `Disks` button in the `files` toolbar) is the ngui view of storage; the
+  `storage` command stays the text view.  It lists the present block
+  devices (empty IDE/eMMC slots are hidden), reads sector 0 and each
+  partition's first sector with `SYS_BLK_READ` (119, one 512-byte sector,
+  under `sys_fs_enter`, copied through a kernel buffer) to show the MBR,
+  NebOS boot partition, rootfs, FAT type and label, and lists every mount
+  with its source volume (`struct sys_mount` now carries `dev` and `key`).
+  Floppies are never read raw.  `SYS_MOUNT_CTL` (120) sets/gets a
+  `struct sys_mount_policy` keyed by the volume's default mount name
+  (`ide0p1`, or the device name for a whole-device volume): a mount name,
+  `SYS_MOUNT_RO` and `SYS_MOUNT_NOAUTO`.  `vfs.c` keeps up to 16 policies in
+  RAM; `mount_one()` applies them on every scan (a policy name loses to a
+  name already in use) and a set remounts that device at once.  Writes,
+  unlink, mkdir and rmdir on a mount with `ro` set return `SYS_EROFS`
+  before the backend (`sys_fs_begin_w`).  The app saves the table as
+  `MOUNTS.CFG` (`"NBMNT1\n\0"` + records) on the `NEBOSDATA` volume; the
+  `bootscan` thread calls `sys_mount_load_config()` after `vfs_mount_all()`
+  and applies `/data/MOUNTS.CFG`.  The data volume itself is not editable
+  from the app (it stores the file).  Format and install run the kernel
+  commands with `-y` (which skips their raw-keyboard y/n prompt; the app
+  confirms in its own dialog) through `SYS_SPAWN_KCMD` on a private tty and
+  show the output; success is read from the `done` line.
 - **`/share`**: `share.c/h` — writable, page-backed in-memory filesystem for
   network uploads (the netbooted board may have no writable disk).  Entries
   are full relative paths (like the pack ramfs) plus explicit directory
@@ -1935,7 +1959,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
-`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk), `install <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
+`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
 `ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), and `chat [config-path]` (Cloudron Chat client).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
@@ -1967,7 +1991,7 @@ 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`, `settime`, `date`, `files`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `settime`, `date`, `files`, `disks`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `websrv`, `curl`, `wifi`, `netmenu`, `solitaire` and `hello` are files in `/ramfs/bin`
 (packed by the Makefile), found through the shell's PATH; the rest are kernel
@@ -2577,9 +2601,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     (8 slots x 1 KB), and the FAT listing cache another 5 KB.  The command
     pack is out of the kernel now; after the WiFi/netmenu/install code and the
     per-connection TCP queues moved to the frame allocator, `_end` is
-    ~0x8eb20 (with the 6200/6300 DVM layer, the RTL8821AU driver, the
+    ~0x8ef20 (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 and the 32x32 cursor save buffer), ~5 KB below the `0x90000` wall, and the remaining limit
+    AMD MTRR path, the 32x32 cursor save buffer and the mount-policy table), ~4 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
@@ -2987,4 +3011,4 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     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
-    ~0x8eb20, ~5 KB below the `0x90000` wall.
+    ~0x8ef20, ~4 KB below the `0x90000` wall.

+ 5 - 1
Makefile

@@ -386,7 +386,7 @@ UCMDS = cpuinfo ls cat save rm mkdir rmdir \
         netconsole netregs netloop netreset net100 netmac curl \
         files view sensors powerinfo mines solitaire \
         settime date gallery websrv browser chat \
-        wifi netmenu
+        wifi netmenu disks
 
 app = $(U)/apps/$(1)/ucmd_$(1)
 UCMD_ELFS = $(foreach a,$(UCMDS),$(call app,$(a)).elf)
@@ -454,6 +454,10 @@ $(call app,wifi).elf: $(call app,wifi).o $(WIFI_STORE) $(WPA_OBJS) $(UL)/tls/tls
 $(call app,netmenu).elf: $(call app,netmenu).o $(WIFI_STORE) $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 
+# Storage manager: devices, partitions, mount policies, format/install.
+$(call app,disks).elf: $(call app,disks).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
+	$(ULINK)
+
 # chat: native Cloudron Chat client (ngui + uhttp/TLS + cookie jar + JSON +
 # the native OIDC login driver).
 CHAT_LOGIN = $(U)/apps/chat/chat_login.o

+ 28 - 2
docs/filesystems.html

@@ -59,6 +59,7 @@
 			<li><a href="#ramfs">ramfs &amp; the command pack</a></li>
 			<li><a href="#share">/share</a></li>
 			<li><a href="#data">/data</a></li>
+			<li><a href="#disks">Storage manager &amp; mount policies</a></li>
 			<li><a href="#sysfs">File service ABI</a></li>
 			<li><a href="#webdav">WebDAV</a></li>
 			<li><a href="#capacity">Capacity chart</a></li>
@@ -315,10 +316,31 @@
 			<li><strong>WiFi credentials.</strong> A successful WiFi connect adds the network to a most-recently-used list of up to 16 SSID/passphrase records in <code>WIFI.CFG</code>; the boot-time <code>wifi autoconnect</code> helper scans and joins the strongest saved network it finds. <code>wifi saved</code> lists them and <code>wifi forget [ssid]</code> removes one. The file is plaintext and 8.3, like the rest of the volume.</li>
 			<li><strong>Chat session.</strong> The Chat client stores its server and session cookie in <code>CHAT.CFG</code> when this volume is mounted; without it the client falls back to the RAM-only <code>/share/chat.cfg</code>. The cookie is a bearer credential, and the password is never stored.</li>
 			<li><strong>Fixed start.</strong> P4 starts at LBA 34816. A BIOS-only install leaves the space between P2 and P4 unpartitioned, and a later disk clone does not resize P4.</li>
+			<li><strong>Mount settings.</strong> The <code>disks</code> app saves the mount policies in <code>MOUNTS.CFG</code>; the boot scan applies them (see below).</li>
 			<li><strong>No fsck.</strong> Like the other FAT mounts, the volume has no journal, repair tool or permissions; it is writable by every process.</li>
 		</ul>
 	</section>
 
+	<section id="disks">
+		<h2>Storage manager &amp; mount policies</h2>
+		<p>
+			<code>disks</code> (<span class="file">ucmd_disks.c</span>, also the
+			<em>Disks</em> button in <code>files</code>) is the ngui front end to
+			storage; <code>storage</code> stays the text view. It lists every
+			present block device (<code>SYS_BLKDEV</code>), reads sector 0 and
+			each partition's first sector through <code>SYS_BLK_READ</code>
+			(119) to show the MBR, the NebOS boot partition, the rootfs, FAT
+			types and labels, and shows all mounts with their source volume.
+			Floppies are never read raw (no media means seconds of retries).
+		</p>
+		<ul>
+			<li><strong>Mount policies.</strong> <code>SYS_MOUNT_CTL</code> (120) sets or reads a <code>struct sys_mount_policy</code>: a mount name, <code>SYS_MOUNT_RO</code> and <code>SYS_MOUNT_NOAUTO</code>, keyed by the volume's default name (<code>ide0p1</code>, or <code>usb0</code>/<code>floppy1</code> for a whole-device volume). <span class="file">vfs.c</span> keeps up to 16 in RAM; <code>mount_one()</code> honours them on every scan and a set remounts the device at once. Names are 1–15 of <code>[a-z0-9_-]</code>; <code>ramfs</code>/<code>share</code> are refused and a name already in use falls back to the default.</li>
+			<li><strong>Read-only.</strong> Write, unlink, mkdir and rmdir on a mount with <code>ro</code> set return <code>SYS_EROFS</code> before reaching the backend (this also covers the ramfs).</li>
+			<li><strong>Persistence.</strong> The app writes the table to <code>MOUNTS.CFG</code> on the <code>NEBOSDATA</code> volume (<code>"NBMNT1\n\0"</code> then the records); the <code>bootscan</code> thread reads <code>/data/MOUNTS.CFG</code> after <code>vfs_mount_all()</code> and applies it. Without <code>/data</code> the settings last until reboot. The data volume itself cannot be edited, since it stores the file.</li>
+			<li><strong>Format and install.</strong> The app confirms in its own dialog, then runs <code>format -y &lt;dev&gt; [size]</code> or <code>install -y &lt;dev&gt; [self]</code> through <code>SYS_SPAWN_KCMD</code> on a private tty and shows the output; <code>-y</code> skips the commands' raw-keyboard y/n prompt. An installed disk offers <em>Update</em> (<code>self</code>) and <em>Reinstall</em> (clone), a blank one <em>Install</em>.</li>
+		</ul>
+	</section>
+
 	<section id="sysfs">
 		<h2>File service ABI</h2>
 		<p>
@@ -326,7 +348,10 @@
 			<code>SYS_WRITE_FILE</code>, <code>SYS_LIST_DIR</code>,
 			<code>SYS_LIST_MOUNTS</code>, <code>SYS_UNLINK</code>,
 			<code>SYS_MKDIR</code>, <code>SYS_RMDIR</code>,
-			<code>SYS_FS_STAT</code> and <code>SYS_GETCWD</code>.
+			<code>SYS_FS_STAT</code> and <code>SYS_GETCWD</code>; the storage
+			manager adds <code>SYS_BLK_READ</code> and
+			<code>SYS_MOUNT_CTL</code>. <code>struct sys_mount</code> carries the
+			source device and the volume key.
 			<span class="file">sys_fs.c</span> validates the path, resolves it
 			against the caller's cwd, calls the VFS and maps backend errors to
 			the stable <code>SYS_E*</code> values.
@@ -420,7 +445,8 @@
 			<li><code>kernel/fat.c</code>, <code>kernel/fat.h</code> — FAT12/16/32</li>
 			<li><code>kernel/ramfs.c</code>, <code>kernel/ramfs.h</code> — pack inflate</li>
 			<li><code>kernel/share.c</code>, <code>kernel/share.h</code> — /share</li>
-			<li><code>kernel/sys_fs.c</code> — ring-3 file service</li>
+			<li><code>kernel/sys_fs.c</code> — ring-3 file service, raw sector read, mount policies and <code>MOUNTS.CFG</code> loader</li>
+			<li><code>user/apps/disks/ucmd_disks.c</code> — storage manager app</li>
 			<li><code>tools/mkpack.c</code>, <code>tools/mkrootfs.c</code>, <code>include/rootfs.h</code></li>
 			<li><code>common/inflate.c</code> — DEFLATE/gzip</li>
 			<li><code>user/apps/websrv/ucmd_websrv.c</code> — HTTP/WebDAV</li>

+ 1 - 1
docs/index.html

@@ -207,7 +207,7 @@
 			</a>
 			<a class="card" href="filesystems.html">
 				<h3>Storage &amp; filesystems</h3>
-				<p>VFS vtable, FAT12/16/32, the ramfs pack pipeline, persistent <code>/data</code>, <code>/share</code> and the WebDAV view of the VFS.</p>
+				<p>VFS vtable, FAT12/16/32, the ramfs pack pipeline, persistent <code>/data</code>, <code>/share</code>, the <code>disks</code> manager with its mount policies and the WebDAV view of the VFS.</p>
 				<span class="card-tag">filesystems.html</span>
 			</a>
 			<a class="card" href="graphics.html">

+ 6 - 1
docs/userland.html

@@ -230,6 +230,7 @@
 					<tr><td>NIC menu</td><td>111–112</td><td><code>SYS_NET_DEVLIST</code> (present drivers with kind/active/link) and <code>SYS_NET_SELECT</code> (make a named netdev active)</td></tr>
 					<tr><td>Hardware settings</td><td>113–114</td><td><code>SYS_BACKLIGHT(op, value)</code> get/set/step the panel PWM, <code>SYS_CPUFREQ(mode)</code> get/set the P-state mode (control panel sliders/tiles)</td></tr>
 					<tr><td>Popover layout</td><td>115–116</td><td><code>SYS_WIN_RESIZE_SELF(w, h)</code> resizes the caller's canvas, <code>SYS_SCREEN_INFO(out)</code> returns the framebuffer dimensions (the control panel collapses/grows)</td></tr>
+					<tr><td>Storage</td><td>119–120</td><td><code>SYS_BLK_READ(index, lba, buf)</code> reads one raw sector, <code>SYS_MOUNT_CTL(op, ...)</code> sets/gets a mount policy (name, read-only, no automount); used by <code>disks</code></td></tr>
 					<tr><td>Mouse cursor</td><td>117–118</td><td><code>SYS_WIN_SET_CURSOR(shape)</code> sets the caller's content cursor, <code>SYS_WM_SET_CURSOR(shape | -1)</code> is the WM's override for its chrome (shapes in <span class="file">cursor_abi.h</span>)</td></tr>
 				</tbody>
 			</table>
@@ -287,6 +288,8 @@
 		<p>
 			<code>format &lt;device&gt; [size]</code> creates a FAT filesystem.
 			<code>install &lt;target&gt; [source|self]</code> installs NebOS.
+			Both take a leading <code>-y</code> that skips the y/n prompt; the
+			<code>disks</code> app confirms in its own dialog and passes it.
 			With a source it auto-detects a disk whose MBR and LBA-63 boot
 			sector carry the NebOS signature (preferring <code>usb0</code>),
 			reads P1..P3 into RAM, creates or keeps the <code>NEBOSDATA</code>
@@ -326,7 +329,7 @@
 			</div>
 			<div class="card">
 				<h3>GUI</h3>
-				<p><code>wm</code> <code>term</code> <code>files</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
+				<p><code>wm</code> <code>term</code> <code>files</code> <code>disks</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
 			</div>
 		</div>
 		<p>
@@ -343,6 +346,7 @@
 		<h2>GUI applications</h2>
 		<ul>
 			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
+			<li><strong>disks</strong> — storage manager (also the <em>Disks</em> button in <code>files</code>): devices, MBR partitions and mounts; per-volume mount name, read-only and automount saved to <code>/data/MOUNTS.CFG</code>; Format and Install NebOS dialogs that run <code>format -y</code>/<code>install -y</code> on a private tty and show the log. See <a href="filesystems.html#disks">Filesystems → Storage manager</a>.</li>
 			<li><strong>gallery</strong> — live widget and primitive showcase; the real app ships in the pack.</li>
 			<li><strong>chat</strong> — native Cloudron Chat client (top-bar <em>Chat</em> button, or <code>chat [config-path]</code>): username/password/TOTP login through the Cloudron OIDC API or a pasted session cookie, channels and DMs with unread badges and presence, history with older paging, inline image attachments and profile-picture avatars, sending, REST polling, read markers, browse/join and new DM.  The session cookie (never the password) is saved in <code>/data/CHAT.CFG</code> when the persistent volume is mounted, or in the RAM-only <code>/share/chat.cfg</code> otherwise.  Keys: Enter sends, PgUp/PgDn scroll, Home at the top pages in older history, Ctrl+B browse, Ctrl+N new DM, Ctrl+R refresh, and with the composer unfocused (Esc) Up/Down switch conversations.  See <a href="network.html#chat">Network → Chat client</a>.</li>
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
@@ -442,6 +446,7 @@
 			<li><code>user/apps/browser/browser.c</code>, <code>user/apps/browser/browser_html.c</code>, <code>user/apps/browser/svg_raster.c/h</code> (+ <code>user/apps/browser/svg_test.c</code>), <code>user/apps/browser/js_browser.c/h</code>, <code>user/apps/browser/js_prelude.js</code> + <code>user/apps/browser/js_prelude.S</code>, <code>user/apps/browser/js_mu.c/h</code>, <code>third_party/quickjs/</code>, <code>user/apps/gallery/gallery.c</code></li>
 			<li><code>user/apps/chat/ucmd_chat.c</code>, <code>user/apps/chat/chat_login.c</code>, <code>user/lib/ujson/ujson.c</code>, <code>user/lib/uhttp/uhttp_cookie.c</code> — chat client</li>
 			<li><code>user/apps/wifi/ucmd_wifi.c</code>, <code>user/lib/wifi/wpa.c</code>, <code>user/lib/tls/wpa_crypto.c</code> — <code>wifi</code> command and the WPA2-PSK supplicant</li>
+			<li><code>user/apps/disks/ucmd_disks.c</code> — storage manager</li>
 			<li><code>user/apps/netmenu/ucmd_netmenu.c</code>, <code>include/wifi_cfg.h</code>, <code>user/lib/wifi/wifi_store.c/h</code> — top-bar control panel, staged WiFi connect record and saved-network list</li>
 		</ul>
 	</section>

+ 31 - 0
include/syscall.h

@@ -121,6 +121,17 @@
 				  cursor (enum cursor_shape, cursor_abi.h) */
 #define SYS_WM_SET_CURSOR 118 /* (int shape | CURSOR_NO_OVERRIDE) -> 0/-1;
 				  WM only: cursor for its chrome/drags */
+
+/* Storage management (see sys_fs.c, the `disks` app).  SYS_BLK_READ reads one
+ * raw 512-byte sector of block device `index` (SYS_BLKDEV order) so ring 3
+ * can show the partition table; it waits for a format/rescan like a file
+ * operation.  SYS_MOUNT_CTL sets the per-volume mount policy (mount point
+ * name, read-only, not mounted) and remounts the device at once.  Policies
+ * live in RAM; the boot scan loads SYS_MOUNT_CFG_PATH from /data. */
+#define SYS_BLK_READ      119 /* (index, lba, void *buf512) -> 0/<0 */
+#define SYS_MOUNT_CTL     120 /* (op, a2, a3) */
+#define SYS_MOUNT_POLICY_SET 0 /* (const struct sys_mount_policy *) -> 0/<0 */
+#define SYS_MOUNT_POLICY_GET 1 /* (index, struct sys_mount_policy *out) -> 1/0 */
 #define SYS_BACKLIGHT     113 /* (int op, int value) -> percent / -1.
 				  op 0 = get, 1 = set (5..100), 2 = step */
 #define SYS_BACKLIGHT_GET  0
@@ -298,8 +309,28 @@ struct sys_mount {
 	unsigned int total_sectors;
 	char label[12];
 	unsigned int ro;
+	char dev[16];           /* source block device ("" for ramfs/share) */
+	char key[16];           /* default name of the volume ("ide0p1"); the
+				   mount-policy key */
+};
+
+/* Mount policy of one volume, keyed by its default mount name: "ide0p1" for
+ * MBR partition 1 of ide0, "floppy0"/"usb0" for a whole-device volume.  A
+ * policy with no name and no flags is removed. */
+#define SYS_MOUNT_NOAUTO 0x1    /* do not mount this volume */
+#define SYS_MOUNT_RO     0x2    /* mount read-only */
+#define SYS_MOUNT_POLICY_MAX 16
+struct sys_mount_policy {
+	char key[16];
+	char name[16];          /* mount point override; "" = default */
+	unsigned int flags;     /* SYS_MOUNT_* */
 };
 
+/* Saved policies: an 8-byte "NBMNT1\n\0" header and up to
+ * SYS_MOUNT_POLICY_MAX struct sys_mount_policy records. */
+#define SYS_MOUNT_CFG_PATH  "/data/MOUNTS.CFG"
+#define SYS_MOUNT_CFG_MAGIC "NBMNT1\n"
+
 /* Result of SYS_FS_STAT. */
 struct sys_stat {
 	unsigned int size;

+ 15 - 1
kernel/format.c

@@ -106,7 +106,7 @@ void program_format_main(const char *arg)
 	char name[16];
 	const char *p;
 	unsigned int i = 0, j, limit = 0;
-	int k, r;
+	int k, r, yes = 0;
 
 	if (format_busy && process_is_alive(format_owner_pid)) {
 		io_putstr("format: another format is in progress\n");
@@ -121,6 +121,15 @@ void program_format_main(const char *arg)
 
 	while (arg[i] == ' ')
 		i++;
+	/* `-y` skips the prompt: the `disks` app confirms in its own dialog
+	 * and runs the command on a private tty with no keyboard. */
+	if (arg[i] == '-' && arg[i + 1] == 'y' &&
+	    (arg[i + 2] == ' ' || !arg[i + 2])) {
+		yes = 1;
+		i += 2;
+		while (arg[i] == ' ')
+			i++;
+	}
 	j = 0;
 	while (arg[i] && arg[i] != ' ' && j < sizeof(name) - 1)
 		name[j++] = arg[i++];
@@ -201,6 +210,10 @@ void program_format_main(const char *arg)
 		io_putstr(" (whole disk)");
 	}
 	io_putstr("? this destroys all data (y/n) ");
+	if (yes) {
+		io_putstr("y\n");
+		goto confirmed;
+	}
 	vga_fb_flush();
 
 	/* Keep the WM from draining the keyboard ring while we poll for the
@@ -224,6 +237,7 @@ void program_format_main(const char *arg)
 	io_set_raw_keyboard(0);
 	io_putchar('\n');
 
+confirmed:
 	io_putstr("formatting ");
 	io_putstr(d->name);
 	io_putstr("...\n");

+ 14 - 0
kernel/install.c

@@ -426,6 +426,9 @@ static blk_dev_t *resolve_target(const char *name)
 	return found;
 }
 
+/* Set by `install -y ...` (the `disks` app confirms in its own dialog). */
+static int install_yes;
+
 static int ask_continue(blk_dev_t *target, int have_data)
 {
 	int k;
@@ -439,6 +442,10 @@ static int ask_continue(blk_dev_t *target, int have_data)
 		io_putstr(target->name);
 		io_putstr("? (y/n) ");
 	}
+	if (install_yes) {
+		io_putstr("y\n");
+		return 1;
+	}
 	vga_fb_flush();
 
 	/* The confirmation loop yields so the kworker can poll the USB HID
@@ -839,6 +846,13 @@ void program_install_main(const char *arg)
 	i = 0;
 	while (arg[i] == ' ')
 		i++;
+	install_yes = 0;
+	if (arg[i] == '-' && arg[i + 1] == 'y' && arg[i + 2] == ' ') {
+		install_yes = 1;
+		i += 3;
+		while (arg[i] == ' ')
+			i++;
+	}
 	j = 0;
 	while (arg[i] && arg[i] != ' ' && j < sizeof(target_name) - 1)
 		target_name[j++] = arg[i++];

+ 2 - 0
kernel/kernel.c

@@ -26,6 +26,7 @@
 #include "rndis.h"
 #include "rtl8821au.h"
 #include "sched.h"
+#include "sys_fs.h"
 #include "sys_wm.h"
 #include "thermal.h"
 #include "timer.h"
@@ -407,6 +408,7 @@ static volatile int boot_dhcp_done;
 static void boot_storage_main(void)
 {
 	vfs_mount_all();
+	sys_mount_load_config();
 	boot_trace("storage");
 	/* As before, WiFi only starts after the boot DHCP attempt on the
 	 * wired NIC, so two DHCP clients never overlap. */

+ 104 - 4
kernel/sys_fs.c

@@ -19,6 +19,8 @@
 
 #include "syscall.h"
 #include "fatformat.h"
+#include "kmalloc.h"
+#include "paging.h"
 #include "process.h"
 #include "vfs.h"
 
@@ -169,6 +171,20 @@ static int sys_fs_begin(const char *path, struct vfs_mount **m,
 	return 0;
 }
 
+/* sys_fs_begin() for a modifying operation: a read-only mount (the ramfs,
+ * or a volume with the SYS_MOUNT_RO policy) refuses it up front. */
+static int sys_fs_begin_w(const char *path, struct vfs_mount **m,
+			  char *rel, unsigned int rel_size)
+{
+	int r = sys_fs_begin(path, m, rel, rel_size);
+
+	if (r == 0 && (*m)->ro) {
+		sys_fs_exit();
+		return SYS_EROFS;
+	}
+	return r;
+}
+
 int sys_read_file(const char *path, void *buf, unsigned int max)
 {
 	struct vfs_mount *m;
@@ -188,7 +204,7 @@ int sys_write_file(const char *path, const void *buf, unsigned int len)
 {
 	struct vfs_mount *m;
 	char rel[VFS_PATH_MAX];
-	int r = sys_fs_begin(path, &m, rel, sizeof(rel));
+	int r = sys_fs_begin_w(path, &m, rel, sizeof(rel));
 
 	if (r != 0)
 		return r;
@@ -203,7 +219,7 @@ int sys_unlink(const char *path)
 {
 	struct vfs_mount *m;
 	char rel[VFS_PATH_MAX];
-	int r = sys_fs_begin(path, &m, rel, sizeof(rel));
+	int r = sys_fs_begin_w(path, &m, rel, sizeof(rel));
 
 	if (r != 0)
 		return r;
@@ -218,7 +234,7 @@ int sys_mkdir(const char *path)
 {
 	struct vfs_mount *m;
 	char rel[VFS_PATH_MAX];
-	int r = sys_fs_begin(path, &m, rel, sizeof(rel));
+	int r = sys_fs_begin_w(path, &m, rel, sizeof(rel));
 
 	if (r != 0)
 		return r;
@@ -233,7 +249,7 @@ int sys_rmdir(const char *path)
 {
 	struct vfs_mount *m;
 	char rel[VFS_PATH_MAX];
-	int r = sys_fs_begin(path, &m, rel, sizeof(rel));
+	int r = sys_fs_begin_w(path, &m, rel, sizeof(rel));
 
 	if (r != 0)
 		return r;
@@ -292,9 +308,93 @@ int sys_list_mounts(unsigned int index, struct sys_mount *out)
 	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;
+	copy_bounded(out->dev, vfs_mounts[index].dev, sizeof(out->dev));
+	copy_bounded(out->key, vfs_mounts[index].key, sizeof(out->key));
 	return 1;
 }
 
+/* One raw sector of a block device for the `disks` partition view.  Read
+ * into a kernel buffer (some drivers DMA through their own bounce buffers,
+ * others write the destination directly), then copy out. */
+int sys_blk_read(unsigned int index, unsigned int lba, void *buf)
+{
+	unsigned char sec[512];
+	blk_dev_t *d;
+	unsigned int i;
+	int r;
+
+	if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)buf,
+				  sizeof(sec), 1))
+		return SYS_EINVAL;
+	sys_fs_enter();
+	if (index >= blk_dev_count) {
+		sys_fs_exit();
+		return SYS_ENODEV;
+	}
+	d = &blk_devs[index];
+	r = SYS_EIO;
+	if (d->present && lba < d->total_sectors && blk_read(d, lba, sec, 1) == 0)
+		r = 0;
+	sys_fs_exit();
+	if (r == 0)
+		for (i = 0; i < sizeof(sec); i++)
+			((unsigned char *)buf)[i] = sec[i];
+	return r;
+}
+
+int sys_mount_ctl(int op, int a2, int a3)
+{
+	struct sys_mount_policy p;
+	int r;
+
+	if (op == SYS_MOUNT_POLICY_GET) {
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)a3,
+					  sizeof(p), 1))
+			return SYS_EINVAL;
+		return vfs_policy_get((unsigned int)a2,
+				      (struct sys_mount_policy *)a3);
+	}
+	if (op != SYS_MOUNT_POLICY_SET ||
+	    !paging_user_range_ok(current_proc()->cr3, (unsigned int)a2,
+				  sizeof(p), 0))
+		return SYS_EINVAL;
+	p = *(const struct sys_mount_policy *)a2;
+	sys_fs_enter();
+	r = vfs_policy_set(&p) == 0 ? 0 : SYS_EINVAL;
+	sys_fs_exit();
+	return r;
+}
+
+/* Boot: apply the policies saved by the `disks` app on /data (the boot
+ * scan's kernel thread, after vfs_mount_all()).  A missing file is normal. */
+struct mount_cfg {
+	char magic[8];
+	struct sys_mount_policy p[SYS_MOUNT_POLICY_MAX];
+	unsigned char slack[512];   /* a FAT read may fill a whole last sector */
+};
+
+void sys_mount_load_config(void)
+{
+	struct mount_cfg *cfg = (struct mount_cfg *)kmalloc(sizeof(*cfg));
+	int n, i;
+
+	if (!cfg)
+		return;
+	n = sys_read_file(SYS_MOUNT_CFG_PATH, cfg,
+			  sizeof(*cfg) - sizeof(cfg->slack));
+	for (i = 0; n >= 8 && i < 8; i++)
+		if (cfg->magic[i] != SYS_MOUNT_CFG_MAGIC[i])
+			n = 0;
+	n = n >= 8 ? (n - 8) / (int)sizeof(cfg->p[0]) : 0;
+	for (i = 0; i < n; i++) {
+		cfg->p[i].key[sizeof(cfg->p[i].key) - 1] = '\0';
+		sys_fs_enter();
+		vfs_policy_set(&cfg->p[i]);
+		sys_fs_exit();
+	}
+	kfree(cfg);
+}
+
 /* 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)

+ 3 - 0
kernel/sys_fs.h

@@ -19,5 +19,8 @@ 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);
+int sys_blk_read(unsigned int index, unsigned int lba, void *buf);
+int sys_mount_ctl(int op, int a2, int a3);
+void sys_mount_load_config(void);
 
 #endif

+ 4 - 0
kernel/syscall.c

@@ -76,6 +76,10 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_storage_info((struct sys_storage_info *)a1);
 	case SYS_BLKDEV:
 		return sys_blkdev((unsigned int)a1, (struct sys_blkdev *)a2);
+	case SYS_BLK_READ:
+		return sys_blk_read((unsigned int)a1, (unsigned int)a2, (void *)a3);
+	case SYS_MOUNT_CTL:
+		return sys_mount_ctl(a1, a2, a3);
 	case SYS_NET_INFO:
 		return sys_net_info((struct sys_netinfo *)a1);
 	case SYS_NET_PRINT_INFO:

+ 108 - 4
kernel/vfs.c

@@ -12,6 +12,7 @@
 #include "rootfs.h"
 #include "serial.h"
 #include "share.h"
+#include "syscall.h"
 #include "timer.h"
 
 vfs_mount_t vfs_mounts[VFS_MAX_MOUNTS];
@@ -591,6 +592,7 @@ static vfs_mount_t *mount_slot(const char *name, const char *dev)
 				m->dev[i] = dev[i];
 			m->dev[i] = '\0';
 		}
+		m->key[0] = '\0';
 		m->mounted = 1;
 		return m;
 	}
@@ -628,13 +630,106 @@ static int is_nebos_boot_partition(blk_dev_t *d, unsigned int start_lba)
 	return i == ROOTFS_LBA;
 }
 
+/* ---- mount policies ---- */
+
+static struct sys_mount_policy vfs_policies[SYS_MOUNT_POLICY_MAX];
+static unsigned int vfs_policy_count;
+
+static struct sys_mount_policy *policy_find(const char *key)
+{
+	unsigned int i;
+
+	for (i = 0; i < vfs_policy_count; i++)
+		if (name_eq(vfs_policies[i].key, key))
+			return &vfs_policies[i];
+	return 0;
+}
+
+/* A mount name or key: 1..15 of [a-z0-9_-]. */
+static int policy_name_ok(const char *s)
+{
+	unsigned int i;
+
+	for (i = 0; s[i]; i++) {
+		char c = s[i];
+
+		if (i >= 15 || !((c >= 'a' && c <= 'z') ||
+				 (c >= '0' && c <= '9') || c == '_' || c == '-'))
+			return 0;
+	}
+	return i > 0;
+}
+
+/* The block device a policy key names: "<dev>" or "<dev>p<1-4>". */
+static blk_dev_t *policy_device(const char *key)
+{
+	unsigned int i, n;
+
+	for (i = 0; i < blk_dev_count; i++) {
+		const char *d = blk_devs[i].name;
+
+		for (n = 0; d[n] && key[n] == d[n]; n++)
+			;
+		if (d[n])
+			continue;
+		if (key[n] == '\0' ||
+		    (key[n] == 'p' && key[n + 1] >= '1' && key[n + 1] <= '4' &&
+		     key[n + 2] == '\0'))
+			return &blk_devs[i];
+	}
+	return 0;
+}
+
+static void remount(blk_dev_t *d);
+
+int vfs_policy_set(const struct sys_mount_policy *p)
+{
+	struct sys_mount_policy *e;
+	blk_dev_t *d;
+
+	if (!policy_name_ok(p->key) || p->name[sizeof(p->name) - 1] ||
+	    (p->name[0] && (!policy_name_ok(p->name) ||
+			    name_eq(p->name, "ramfs") ||
+			    name_eq(p->name, "share"))) ||
+	    (p->flags & ~(SYS_MOUNT_NOAUTO | SYS_MOUNT_RO)))
+		return -1;
+	d = policy_device(p->key);
+	if (!d)
+		return -1;
+	e = policy_find(p->key);
+	if (!p->name[0] && !p->flags) {
+		if (e)
+			*e = vfs_policies[--vfs_policy_count];
+	} else {
+		if (!e) {
+			if (vfs_policy_count >= SYS_MOUNT_POLICY_MAX)
+				return -1;
+			e = &vfs_policies[vfs_policy_count++];
+		}
+		*e = *p;
+	}
+	remount(d);
+	return 0;
+}
+
+int vfs_policy_get(unsigned int index, struct sys_mount_policy *out)
+{
+	if (index >= vfs_policy_count)
+		return 0;
+	*out = vfs_policies[index];
+	return 1;
+}
+
 static void mount_one(blk_dev_t *dev, unsigned int part_lba, const char *name)
 {
 	fat_fs_t fs;
 	vfs_mount_t *m;
+	const struct sys_mount_policy *pol = policy_find(name);
 	const char *use_name = name;
 	int r;
 
+	if (pol && (pol->flags & SYS_MOUNT_NOAUTO))
+		return;
 	fat_cache_clear();
 
 	r = fat_mount(dev, part_lba, &fs);
@@ -648,12 +743,16 @@ static void mount_one(blk_dev_t *dev, unsigned int part_lba, const char *name)
 	 * device name.  Only the first NEBOSDATA volume becomes /data. */
 	if (name_eq(fs.label, "NEBOSDATA") && !vfs_find("data"))
 		use_name = "data";
+	/* A policy name wins unless another volume already holds it. */
+	if (pol && pol->name[0] && !vfs_find(pol->name))
+		use_name = pol->name;
 	m = mount_slot(use_name, dev->name);
 	if (!m)
 		return;
+	copy_bounded(m->key, name, sizeof(m->key));
 	m->ops = &fat_ops;
 	m->fs = fs;
-	m->ro = 0;
+	m->ro = (pol && (pol->flags & SYS_MOUNT_RO)) ? 1 : 0;
 	m->total_sectors = fs.total_sectors;
 	copy_bounded(m->type, fat_name(fs.type), sizeof(m->type));
 	copy_bounded(m->label, fs.label, sizeof(m->label));
@@ -825,15 +924,20 @@ static int device_is_mounted(const char *dev)
 	return 0;
 }
 
-void vfs_remount_device(blk_dev_t *d)
+static void remount(blk_dev_t *d)
 {
 	unsigned char buf[512];
 
-	if (!d)
-		return;
 	fat_cache_clear();
 	unmount_device(d->name);
 	mount_device(d, buf);
+}
+
+void vfs_remount_device(blk_dev_t *d)
+{
+	if (!d)
+		return;
+	remount(d);
 	if (!device_is_mounted(d->name)) {
 		io_putstr("vfs: remount of ");
 		io_putstr(d->name);

+ 11 - 0
kernel/vfs.h

@@ -61,6 +61,7 @@ struct fs_ops {
 typedef struct vfs_mount {
 	char name[16];
 	char dev[16];                /* block device name for pN mounts */
+	char key[16];                /* default name (mount-policy key) */
 	const struct fs_ops *ops;
 	int mounted;
 	int ro;
@@ -82,6 +83,16 @@ void vfs_mount_all(void);
 /* Re-mount only one block device after it was formatted. */
 void vfs_remount_device(blk_dev_t *d);
 
+/* Mount policies (SYS_MOUNT_CTL): per-volume mount point name, read-only and
+ * "do not mount", keyed by the default mount name ("ide0p1").  mount_one()
+ * applies them on every (re)scan.  vfs_policy_set() validates and stores
+ * one (an empty policy deletes it) and remounts its device; -1 on a bad
+ * policy, an unknown device or a full table.  The caller holds the fs
+ * section (sys_fs_enter).  vfs_policy_get() copies entry `index`. */
+struct sys_mount_policy;
+int vfs_policy_set(const struct sys_mount_policy *p);
+int vfs_policy_get(unsigned int index, struct sys_mount_policy *out);
+
 /* Set while vfs_mount_all() owns the mount table and the FAT sector buffer.
  * sys_fs.c waits for it; the owner (the calling `storage` syscall) is exempt. */
 extern volatile int vfs_scan_busy;

+ 1302 - 0
user/apps/disks/ucmd_disks.c

@@ -0,0 +1,1302 @@
+/* disks: the ngui storage manager.
+ *
+ * Lists every block device (SYS_BLKDEV) with its MBR partitions, read as raw
+ * sectors through SYS_BLK_READ, and every mounted filesystem.  A FAT volume
+ * can be mounted/unmounted, renamed and made read-only (SYS_MOUNT_CTL; the
+ * policies are saved to /data/MOUNTS.CFG and applied again by the boot
+ * scan).  A device can be formatted or have NebOS installed on it: those run
+ * the privileged `format -y` / `install -y` kernel commands on a private tty
+ * and show their output, after this window asked for confirmation.  The
+ * `storage` command remains the text view. */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "ngui.h"
+#include "ucmd_lib.h"
+
+#define MAX_DISKS   16
+#define MAX_MOUNTS  24                  /* VFS_MAX_MOUNTS */
+#define MAX_VOLS    5
+
+#define TOOLBAR_H   40
+#define LIST_W      230
+#define SECTION_H   28
+#define ROW_H       42
+#define GAP         10
+
+#define KIND_FLOPPY 0
+
+enum {
+	ID_RESCAN = 1,
+	ID_OVERVIEW,
+	ID_FORMAT,
+	ID_INSTALL,
+	ID_MOUNT_TOGGLE,
+	ID_RO,
+	ID_AUTO,
+	ID_NAME,
+	ID_APPLY,
+	ID_RESET,
+	ID_OPEN,
+	ID_DLG_SIZE,
+	ID_DLG_CANCEL,
+	ID_DLG_OK,
+	ID_DLG_OK2,
+	ID_DLG_CLOSE,
+	ID_DISK_BASE = 100,
+	ID_PART_BASE = 200,
+	ID_MOUNT_BASE = 300,
+};
+
+/* One MBR partition (or the whole device for a floppy/superfloppy). */
+struct part {
+	int slot;                       /* MBR slot 0..3, -1 = whole device */
+	unsigned char type, active;
+	unsigned int start, sectors;
+	int fat;                        /* has a FAT boot sector */
+	int nebos_boot;                 /* the NebOS boot sector + kernel */
+	char fs[8];
+	char label[12];
+	char key[16];                   /* default mount name */
+};
+
+struct disk {
+	struct sys_blkdev bd;
+	unsigned int index;             /* SYS_BLKDEV / SYS_BLK_READ index */
+	int read_ok;                    /* sector 0 was readable */
+	int mbr;                        /* a valid partition table */
+	int nparts;
+	struct part parts[4];
+	int nebos;                      /* boot partition + rootfs partition */
+	int has_data;                   /* a NEBOSDATA partition */
+};
+
+enum dialog { DLG_NONE, DLG_FORMAT, DLG_INSTALL, DLG_JOB };
+
+static struct ngui ui;
+static struct disk disks[MAX_DISKS];
+static int ndisks;
+static struct sys_mount mounts[MAX_MOUNTS];
+static int nmounts;
+static struct sys_mount_policy pols[SYS_MOUNT_POLICY_MAX];
+static int npols;
+
+static int sel_disk = -1;               /* -1 = mount overview */
+static char sel_key[16];                /* selected volume */
+static char edit_key[16];               /* volume the editor was loaded for */
+static struct ngui_input name_in;
+static int edit_ro, edit_auto;
+static struct ngui_scroll detail_scroll, list_scroll;
+
+static char status[128];
+static int status_err;
+static unsigned int status_until;
+
+static enum dialog dialog;
+static int rescan_pending;
+static struct ngui_input size_in;
+static int dlg_disk;
+
+/* The running format/install. */
+static int job_tty = -1, job_pid = -1;
+static int job_done, job_ok;
+static char job_title[64];
+static char job_log[4096];
+static unsigned int job_len;
+
+/* ---- helpers ---- */
+
+static void set_status(const char *msg, int err)
+{
+	snprintf(status, sizeof(status), "%s", msg);
+	status_err = err;
+	status_until = u_ticks_ms() + 8000;
+	ngui_invalidate(&ui);
+}
+
+static unsigned int rd32(const unsigned char *p)
+{
+	return p[0] | (p[1] << 8) | (p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+static void fmt_size(char *out, unsigned int n, unsigned int sectors)
+{
+	if (sectors >= 2u * 1024u * 1024u)
+		snprintf(out, n, "%u.%u GB", sectors >> 21,
+			 ((sectors & 0x1FFFFFu) * 10u) >> 21);
+	else if (sectors >= 2048u)
+		snprintf(out, n, "%u.%u MB", sectors >> 11,
+			 ((sectors & 0x7FFu) * 10u) >> 11);
+	else
+		snprintf(out, n, "%u KB", sectors / 2u);
+}
+
+static const char *kind_name(unsigned int kind)
+{
+	static const char *names[] = { "Floppy", "IDE", "SATA", "eMMC", "USB" };
+
+	return kind < 5 ? names[kind] : "Disk";
+}
+
+static const char *type_name(unsigned char t)
+{
+	switch (t) {
+	case 0x01: return "FAT12";
+	case 0x04: case 0x06: case 0x0E: return "FAT16";
+	case 0x0B: case 0x0C: return "FAT32";
+	case 0x05: case 0x0F: return "Extended";
+	case 0x07: return "NTFS/exFAT";
+	case 0x7F: return "NebOS rootfs";
+	case 0x82: return "Linux swap";
+	case 0x83: return "Linux";
+	case 0xEE: return "GPT";
+	case 0xEF: return "EFI System";
+	default:   return "Unknown";
+	}
+}
+
+/* Copy a space-padded BPB field and trim it. */
+static void bpb_str(char *out, const unsigned char *p, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++)
+		out[i] = (p[i] >= 0x20 && p[i] < 0x7F) ? (char)p[i] : ' ';
+	while (i > 0 && out[i - 1] == ' ')
+		i--;
+	out[i] = '\0';
+}
+
+/* Classify a partition's (or a superfloppy's) first sector. */
+static void probe_boot_sector(struct part *p, const unsigned char *s)
+{
+	unsigned int bps = s[11] | (s[12] << 8);
+
+	p->fat = 0;
+	p->nebos_boot = 0;
+	p->fs[0] = p->label[0] = '\0';
+	if (s[510] != 0x55 || s[511] != 0xAA)
+		return;
+	if (s[3] == 'N' && s[4] == 'E' && s[5] == 'B' && s[6] == 'O' &&
+	    s[7] == 'S') {
+		p->nebos_boot = 1;
+		snprintf(p->fs, sizeof(p->fs), "NebOS");
+		return;
+	}
+	if (bps != 512 || (s[0] != 0xEB && s[0] != 0xE9) || s[13] == 0)
+		return;
+	p->fat = 1;
+	if ((s[0x16] | (s[0x17] << 8)) == 0) {          /* FAT32 BPB */
+		snprintf(p->fs, sizeof(p->fs), "FAT32");
+		bpb_str(p->label, s + 0x47, 11);
+	} else {
+		bpb_str(p->fs, s + 0x36, 5);
+		if (strncmp(p->fs, "FAT", 3) != 0)
+			snprintf(p->fs, sizeof(p->fs), "FAT");
+		bpb_str(p->label, s + 0x2B, 11);
+	}
+	if (!strcmp(p->label, "NO NAME"))
+		p->label[0] = '\0';
+}
+
+static int blk_read(unsigned int index, unsigned int lba, unsigned char *buf)
+{
+	return u_syscall3(SYS_BLK_READ, (int)index, (int)lba, (int)buf);
+}
+
+/* Read the partition table and the first sector of every partition.  A
+ * floppy is never read here: without a disk the controller retries for
+ * seconds, and it has no partitions anyway. */
+static void probe_disk(struct disk *d)
+{
+	static unsigned char s[512];
+	unsigned int i;
+
+	d->read_ok = d->mbr = d->nparts = d->nebos = d->has_data = 0;
+	if (!d->bd.present)
+		return;
+	if (d->bd.kind == KIND_FLOPPY) {
+		struct part *p = &d->parts[d->nparts++];
+
+		memset(p, 0, sizeof(*p));
+		p->slot = -1;
+		p->sectors = d->bd.total_sectors;
+		p->fat = 1;
+		snprintf(p->key, sizeof(p->key), "%s", d->bd.name);
+		return;
+	}
+	if (blk_read(d->index, 0, s) != 0)
+		return;
+	d->read_ok = 1;
+	if (s[510] == 0x55 && s[511] == 0xAA) {
+		int ok = 1, n = 0;
+
+		for (i = 0; i < 4; i++) {
+			const unsigned char *e = s + 0x1BE + i * 16;
+			unsigned int start = rd32(e + 8), cnt = rd32(e + 12);
+
+			if (e[4] == 0)
+				continue;
+			if ((e[0] != 0 && e[0] != 0x80) || start == 0 ||
+			    cnt == 0 || start > d->bd.total_sectors ||
+			    cnt > d->bd.total_sectors - start)
+				ok = 0;
+			n++;
+		}
+		d->mbr = ok && n > 0;
+	}
+	if (!d->mbr) {
+		struct part *p = &d->parts[0];
+
+		memset(p, 0, sizeof(*p));
+		p->slot = -1;
+		p->sectors = d->bd.total_sectors;
+		probe_boot_sector(p, s);
+		snprintf(p->key, sizeof(p->key), "%s", d->bd.name);
+		if (p->fat)
+			d->nparts = 1;
+		return;
+	}
+	for (i = 0; i < 4; i++) {
+		const unsigned char *e = s + 0x1BE + i * 16;
+		struct part *p;
+
+		if (e[4] == 0)
+			continue;
+		p = &d->parts[d->nparts++];
+		memset(p, 0, sizeof(*p));
+		p->slot = (int)i;
+		p->type = e[4];
+		p->active = e[0] == 0x80;
+		p->start = rd32(e + 8);
+		p->sectors = rd32(e + 12);
+		snprintf(p->key, sizeof(p->key), "%sp%u", d->bd.name, i + 1);
+	}
+	for (i = 0; i < (unsigned int)d->nparts; i++) {
+		struct part *p = &d->parts[i];
+
+		if (p->type == 0x05 || p->type == 0x0F || p->type == 0xEE ||
+		    p->type == 0x7F)
+			continue;
+		if (blk_read(d->index, p->start, s) == 0)
+			probe_boot_sector(p, s);
+		if (p->nebos_boot && p->slot == 0)
+			d->nebos |= 1;
+		if (p->fat && !strcmp(p->label, "NEBOSDATA"))
+			d->has_data = 1;
+	}
+	for (i = 0; i < (unsigned int)d->nparts; i++)
+		if (d->parts[i].type == 0x7F)
+			d->nebos |= 2;
+	d->nebos = d->nebos == 3;
+}
+
+static void load_mounts(void)
+{
+	int i;
+
+	nmounts = 0;
+	for (i = 0; i < MAX_MOUNTS; i++) {
+		if (u_syscall2(SYS_LIST_MOUNTS, i, (int)&mounts[nmounts]) != 1)
+			break;
+		nmounts++;
+	}
+	npols = 0;
+	for (i = 0; i < SYS_MOUNT_POLICY_MAX; i++) {
+		if (u_syscall3(SYS_MOUNT_CTL, SYS_MOUNT_POLICY_GET, i,
+			       (int)&pols[npols]) != 1)
+			break;
+		npols++;
+	}
+}
+
+/* USB INQUIRY strings are space-padded vendor/product fields. */
+static void squeeze(char *s)
+{
+	char *o = s;
+	const char *p;
+
+	for (p = s; *p; p++)
+		if (*p != ' ' || (o > s && o[-1] != ' '))
+			*o++ = *p;
+	if (o > s && o[-1] == ' ')
+		o--;
+	*o = '\0';
+}
+
+static void load_all(void)
+{
+	int i;
+
+	ndisks = 0;
+	for (i = 0; i < MAX_DISKS; i++) {
+		struct disk *d = &disks[ndisks];
+
+		if (u_syscall2(SYS_BLKDEV, i, (int)&d->bd) != 1)
+			break;
+		d->index = (unsigned int)i;
+		squeeze(d->bd.model);
+		probe_disk(d);
+		ndisks++;
+	}
+	if (sel_disk >= ndisks)
+		sel_disk = -1;
+	load_mounts();
+	edit_key[0] = '\0';         /* reload the editor from the new state */
+}
+
+static const struct sys_mount *mount_by_key(const char *key)
+{
+	int i;
+
+	for (i = 0; i < nmounts; i++)
+		if (mounts[i].dev[0] && !strcmp(mounts[i].key, key))
+			return &mounts[i];
+	return 0;
+}
+
+static const struct sys_mount *mount_by_label(const char *label)
+{
+	int i;
+
+	for (i = 0; i < nmounts; i++)
+		if (mounts[i].dev[0] && !strcmp(mounts[i].label, label))
+			return &mounts[i];
+	return 0;
+}
+
+static const struct sys_mount_policy *policy_by_key(const char *key)
+{
+	int i;
+
+	for (i = 0; i < npols; i++)
+		if (!strcmp(pols[i].key, key))
+			return &pols[i];
+	return 0;
+}
+
+/* The volume carrying the saved policies: never edited from here, since an
+ * unmounted, renamed or read-only /data could not store the change. */
+static int is_data_volume(const struct part *p)
+{
+	const struct sys_mount *m = mount_by_key(p->key);
+
+	return !strcmp(p->label, "NEBOSDATA") ||
+	       (m && !strcmp(m->name, "data"));
+}
+
+/* ---- mount policies ---- */
+
+static int save_policies(void)
+{
+	static struct {
+		char magic[8];
+		struct sys_mount_policy p[SYS_MOUNT_POLICY_MAX];
+	} cfg;
+	const struct sys_mount *data = mount_by_label("NEBOSDATA");
+	char path[48];
+
+	if (!data)
+		return 0;
+	memcpy(cfg.magic, SYS_MOUNT_CFG_MAGIC, 8);
+	memcpy(cfg.p, pols, sizeof(pols[0]) * (unsigned int)npols);
+	snprintf(path, sizeof(path), "/%s/MOUNTS.CFG", data->name);
+	return u_syscall3(SYS_WRITE_FILE, (int)path, (int)&cfg,
+			  8 + (int)sizeof(pols[0]) * npols) == 0 ? 1 : -1;
+}
+
+static int name_valid(const char *s)
+{
+	unsigned int i;
+
+	for (i = 0; s[i]; i++)
+		if (i >= 15 || !((s[i] >= 'a' && s[i] <= 'z') ||
+				 (s[i] >= '0' && s[i] <= '9') ||
+				 s[i] == '_' || s[i] == '-'))
+			return 0;
+	return 1;
+}
+
+static void apply_policy(const char *key, const char *name, unsigned int flags)
+{
+	struct sys_mount_policy p;
+	const struct sys_mount *cur = mount_by_key(key);
+	char msg[96];
+	int i, saved;
+
+	if (!name_valid(name)) {
+		set_status("Mount name: up to 15 of a-z, 0-9, _ and -", 1);
+		return;
+	}
+	if (!strcmp(name, "ramfs") || !strcmp(name, "share") ||
+	    !strcmp(name, "data")) {
+		set_status("That mount name is reserved", 1);
+		return;
+	}
+	for (i = 0; name[0] && i < nmounts; i++)
+		if (!strcmp(mounts[i].name, name) && &mounts[i] != cur) {
+			set_status("Another volume is mounted with that name", 1);
+			return;
+		}
+	memset(&p, 0, sizeof(p));
+	snprintf(p.key, sizeof(p.key), "%s", key);
+	if (strcmp(name, key) != 0)
+		snprintf(p.name, sizeof(p.name), "%s", name);
+	p.flags = flags;
+	if (u_syscall3(SYS_MOUNT_CTL, SYS_MOUNT_POLICY_SET, (int)&p, 0) != 0) {
+		set_status("The kernel refused the mount settings", 1);
+		return;
+	}
+	load_mounts();
+	edit_key[0] = '\0';
+	saved = save_policies();
+	cur = mount_by_key(key);
+	if (flags & SYS_MOUNT_NOAUTO)
+		snprintf(msg, sizeof(msg), "%s is unmounted", key);
+	else if (cur)
+		snprintf(msg, sizeof(msg), "%s is mounted at /%s%s", key,
+			 cur->name, cur->ro ? " (read-only)" : "");
+	else
+		snprintf(msg, sizeof(msg), "%s has no readable filesystem", key);
+	if (saved == 0)
+		snprintf(msg + strlen(msg), sizeof(msg) - strlen(msg), "; not saved (no /data)");
+	else if (saved < 0)
+		snprintf(msg + strlen(msg), sizeof(msg) - strlen(msg), "; saving failed");
+	set_status(msg, !cur && !(flags & SYS_MOUNT_NOAUTO));
+	/* Applied, but only until the next boot: a warning, not an error. */
+	if (saved == 0 && (cur || (flags & SYS_MOUNT_NOAUTO)))
+		status_err = 2;
+}
+
+/* ---- format / install jobs ---- */
+
+static void start_job(const char *cmd, const char *arg, const char *title)
+{
+	if (job_tty < 0)
+		job_tty = u_tty_create();
+	if (job_tty < 0) {
+		set_status("No terminal for the command", 1);
+		return;
+	}
+	job_len = 0;
+	job_log[0] = '\0';
+	job_done = job_ok = 0;
+	snprintf(job_title, sizeof(job_title), "%s", title);
+	job_pid = u_spawn_kcmd(cmd, arg, job_tty);
+	if (job_pid < 0) {
+		set_status("Could not start the command", 1);
+		dialog = DLG_NONE;
+		return;
+	}
+	dialog = DLG_JOB;
+	ngui_invalidate(&ui);
+}
+
+/* The log is drawn in a 13 px monospace face; longer lines are wrapped
+ * here so the dialog never clips them. */
+#define JOB_LOG_COLS 66
+
+static void job_append(const char *s, int n)
+{
+	static unsigned int col;
+	int i;
+
+	for (i = 0; i < n; i++) {
+		if (s[i] == '\r')
+			continue;
+		if (s[i] != '\n' && col >= JOB_LOG_COLS) {
+			job_append("\n", 1);
+		}
+		col = s[i] == '\n' ? 0 : col + 1;
+		if (job_len + 1 >= sizeof(job_log)) {
+			/* Keep the newest half of the log. */
+			unsigned int keep = sizeof(job_log) / 2;
+
+			memmove(job_log, job_log + job_len - keep, keep);
+			job_len = keep;
+		}
+		job_log[job_len++] = s[i];
+	}
+	job_log[job_len] = '\0';
+}
+
+static void job_poll(void)
+{
+	char buf[256];
+	int n, any = 0;
+
+	if (job_tty < 0)
+		return;
+	while ((n = u_tty_read(job_tty, buf, sizeof(buf))) > 0) {
+		if (dialog == DLG_JOB && !job_done)
+			job_append(buf, n);
+		any = 1;
+	}
+	if (dialog == DLG_JOB && !job_done && job_pid > 0 &&
+	    !u_alive((unsigned int)job_pid)) {
+		while ((n = u_tty_read(job_tty, buf, sizeof(buf))) > 0)
+			job_append(buf, n);
+		job_done = 1;
+		job_pid = -1;
+		job_ok = strstr(job_log, "done") && !strstr(job_log, "failed") &&
+			 !strstr(job_log, "aborted");
+		load_all();
+		any = 1;
+	}
+	if (any)
+		ngui_invalidate(&ui);
+}
+
+/* ---- drawing ---- */
+
+/* Widgets drawn under a dialog must not react: hide the pointer edges. */
+struct input_save {
+	unsigned int pressed, released;
+	int inside, scroll_y;
+};
+
+static void input_mute(struct input_save *s)
+{
+	s->pressed = ui.pressed;
+	s->released = ui.released;
+	s->inside = ui.inside;
+	s->scroll_y = ui.scroll_y;
+	ui.pressed = ui.released = 0;
+	ui.inside = 0;
+	ui.scroll_y = 0;
+}
+
+static void input_restore(const struct input_save *s)
+{
+	ui.pressed = s->pressed;
+	ui.released = s->released;
+	ui.inside = s->inside;
+	ui.scroll_y = s->scroll_y;
+}
+
+static int visible(struct ngui_rect r, struct ngui_rect area)
+{
+	return r.y + r.h > area.y && r.y < area.y + area.h;
+}
+
+static void text_dim(int x, int y, const char *s)
+{
+	ngui_text(&ui, x, y, s, ui.theme.text_dim);
+}
+
+static void draw_toolbar(struct ngui_rect r)
+{
+	struct ngui_rect b;
+	unsigned short c;
+
+	ngui_fill_rect(&ui, r, ui.theme.panel);
+	ngui_inset(&r, 6);
+	b = ngui_cut_left(&r, 92);
+	if (ngui_button(&ui, ID_RESCAN, b, "Rescan")) {
+		set_status("Scanning devices...", 0);
+		rescan_pending = 1;
+	}
+	ngui_cut_left(&r, 12);
+	if (status[0]) {
+		c = status_err == 2 ? ui.theme.warning :
+		    status_err ? ui.theme.error : ui.theme.success;
+		ngui_text_ellipsis(&ui, r, r.x, r.y + (r.h - 16) / 2, status, c);
+	} else {
+		ngui_text_ellipsis(&ui, r, r.x, r.y + (r.h - 16) / 2,
+				   "Storage devices, volumes and mounts",
+				   ui.theme.text_dim);
+	}
+}
+
+/* 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)
+{
+	return d->bd.present || d->bd.kind == KIND_FLOPPY;
+}
+
+static void draw_device_list(struct ngui_rect area)
+{
+	struct ngui_row row;
+	struct ngui_rect r;
+	char sub[64], size[16];
+	int i, y;
+
+	ngui_fill_rect(&ui, area, ui.theme.panel);
+	ngui_inset(&area, 6);
+	for (i = 0, y = 0; i < ndisks; i++)
+		y += listed(&disks[i]);
+	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);
+	y = area.y - list_scroll.offset;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Overview", 0, 0);
+	y += SECTION_H;
+	r = (struct ngui_rect){ area.x, y, area.w, ROW_H };
+	if (visible(r, area)) {
+		snprintf(sub, sizeof(sub), "%d filesystem%s", nmounts,
+			 nmounts == 1 ? "" : "s");
+		row.title = "All mounts";
+		row.subtitle = sub;
+		row.trailing = 0;
+		row.bars = -1;
+		row.selected = sel_disk < 0;
+		if (ngui_list_row(&ui, ID_OVERVIEW, r, &row)) {
+			sel_disk = -1;
+			detail_scroll.offset = 0;
+			ngui_invalidate(&ui);
+		}
+	}
+	y += ROW_H;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Devices", 0, 0);
+	y += SECTION_H;
+	for (i = 0; i < ndisks; i++) {
+		const struct disk *d = &disks[i];
+
+		if (!listed(d))
+			continue;
+		r = (struct ngui_rect){ area.x, y, area.w, ROW_H };
+		y += ROW_H;
+		if (!visible(r, area))
+			continue;
+		fmt_size(size, sizeof(size), d->bd.total_sectors);
+		if (!d->bd.present)
+			snprintf(sub, sizeof(sub), "%s, not present",
+				 kind_name(d->bd.kind));
+		else
+			snprintf(sub, sizeof(sub), "%s %s",
+				 kind_name(d->bd.kind),
+				 d->bd.kind == KIND_FLOPPY ? "" : size);
+		row.title = d->bd.name;
+		row.subtitle = sub;
+		row.trailing = d->nebos ? "NebOS" : 0;
+		row.bars = -1;
+		row.selected = sel_disk == i;
+		if (ngui_list_row(&ui, ID_DISK_BASE + i, r, &row) &&
+		    sel_disk != i) {
+			sel_disk = i;
+			sel_key[0] = '\0';
+			detail_scroll.offset = 0;
+			ngui_invalidate(&ui);
+		}
+	}
+	ngui_scroll_end(&ui, area, &list_scroll);
+}
+
+/* The overview: one line per mount. */
+static int draw_overview(struct ngui_rect area, int y)
+{
+	static const int col[] = { 0, 96, 156, 230, 330, 404 };
+	static const char *hdr[] = { "Mount", "Type", "Size", "Label",
+				     "Device", "Mode" };
+	char size[16];
+	int i, j;
+
+	ngui_text_px(&ui, area.x, y, "All mounts", 10, ui.theme.text, 18, 1, 0, 0);
+	y += 32;
+	for (j = 0; j < 6; j++)
+		text_dim(area.x + col[j], y, hdr[j]);
+	y += 22;
+	ngui_fill_rect(&ui, (struct ngui_rect){ area.x, y - 4, area.w, 1 },
+		       ui.theme.border);
+	for (i = 0; i < nmounts; i++) {
+		const struct sys_mount *m = &mounts[i];
+		struct ngui_rect r = { area.x, y, area.w, 26 };
+		char name[20];
+
+		if (visible(r, area)) {
+			snprintf(name, sizeof(name), "/%s", m->name);
+			fmt_size(size, sizeof(size), m->total_sectors);
+			ngui_text(&ui, area.x + col[0], y + 4, name, ui.theme.text);
+			ngui_text(&ui, area.x + col[1], y + 4, m->type, ui.theme.text);
+			ngui_text(&ui, area.x + col[2], y + 4, size, ui.theme.text);
+			ngui_text(&ui, area.x + col[3], y + 4, m->label, ui.theme.text);
+			ngui_text(&ui, area.x + col[4], y + 4,
+				  m->dev[0] ? m->key : "RAM", ui.theme.text_dim);
+			ngui_text(&ui, area.x + col[5], y + 4,
+				  m->ro ? "read-only" : "read-write",
+				  m->ro ? ui.theme.warning : ui.theme.text_dim);
+			if (m->dev[0] && ngui_button(&ui, ID_MOUNT_BASE + i,
+				(struct ngui_rect){ area.x + area.w - 60, y + 1,
+						    60, 24 }, "Show")) {
+				for (j = 0; j < ndisks; j++)
+					if (!strcmp(disks[j].bd.name, m->dev))
+						sel_disk = j;
+				snprintf(sel_key, sizeof(sel_key), "%s", m->key);
+				detail_scroll.offset = 0;
+				ngui_invalidate(&ui);
+			}
+		}
+		y += 28;
+	}
+	y += GAP;
+	text_dim(area.x, y,
+		 "Select a device to format it, install NebOS or change how");
+	y += 18;
+	text_dim(area.x, y, "its volumes are mounted.");
+	return y + 24;
+}
+
+static void load_editor(const struct part *p)
+{
+	const struct sys_mount_policy *pol = policy_by_key(p->key);
+	const struct sys_mount *m = mount_by_key(p->key);
+
+	snprintf(edit_key, sizeof(edit_key), "%s", p->key);
+	if (pol && pol->name[0])
+		ngui_input_set(&name_in, pol->name);
+	else
+		ngui_input_set(&name_in, m ? m->name : p->key);
+	edit_ro = pol && (pol->flags & SYS_MOUNT_RO);
+	edit_auto = !(pol && (pol->flags & SYS_MOUNT_NOAUTO));
+}
+
+static int draw_mount_editor(struct ngui_rect area, int y, const struct part *p)
+{
+	const struct sys_mount *m = mount_by_key(p->key);
+	struct ngui_rect r, b;
+	char line[96], name[16];
+	unsigned int flags;
+
+	if (strcmp(edit_key, p->key) != 0)
+		load_editor(p);
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	snprintf(line, sizeof(line), "Volume %s", p->key);
+	ngui_section(&ui, r, line, 0, 0);
+	y += SECTION_H;
+
+	if (m)
+		snprintf(line, sizeof(line), "Mounted at /%s, %s, %s", m->name,
+			 m->type, m->ro ? "read-only" : "read-write");
+	else
+		snprintf(line, sizeof(line), "Not mounted");
+	ngui_text(&ui, area.x, y + 2, line, m ? ui.theme.success : ui.theme.text_dim);
+	y += 24;
+
+	if (is_data_volume(p)) {
+		text_dim(area.x, y,
+			 "This is the NebOS data volume (/data).  It holds the");
+		y += 18;
+		text_dim(area.x, y,
+			 "saved settings, so it is always mounted read-write.");
+		y += 26;
+		if (m && ngui_button(&ui, ID_OPEN,
+				     (struct ngui_rect){ area.x, y, 130, 28 },
+				     "Open in Files"))
+			goto open_files;
+		return y + 38;
+	}
+
+	text_dim(area.x, y + 6, "Mount name");
+	r = (struct ngui_rect){ area.x + 110, y, 180, 28 };
+	if (visible(r, area))
+		ngui_text_input(&ui, ID_NAME, r, &name_in);
+	y += 34;
+
+	r = (struct ngui_rect){ area.x, y, 290, 26 };
+	if (visible(r, area) &&
+	    ngui_menu_item(&ui, ID_AUTO, r, "Mount automatically", 0, edit_auto))
+		edit_auto = !edit_auto;
+	y += 28;
+	r = (struct ngui_rect){ area.x, y, 290, 26 };
+	if (visible(r, area) &&
+	    ngui_menu_item(&ui, ID_RO, r, "Read-only", 0, edit_ro))
+		edit_ro = !edit_ro;
+	y += 34;
+
+	ngui_input_value(&name_in, name, sizeof(name));
+	flags = (edit_ro ? SYS_MOUNT_RO : 0) | (edit_auto ? 0 : SYS_MOUNT_NOAUTO);
+
+	b = (struct ngui_rect){ area.x, y, 90, 28 };
+	if (visible(b, area) && ngui_button(&ui, ID_APPLY, b, "Apply"))
+		apply_policy(p->key, name, flags);
+	b.x += 98;
+	b.w = 100;
+	if (visible(b, area) &&
+	    ngui_button(&ui, ID_MOUNT_TOGGLE, b, m ? "Unmount" : "Mount")) {
+		if (m)
+			apply_policy(p->key, name, flags | SYS_MOUNT_NOAUTO);
+		else
+			apply_policy(p->key, name, flags & ~SYS_MOUNT_NOAUTO);
+	}
+	b.x += 108;
+	b.w = 90;
+	if (visible(b, area) && ngui_button(&ui, ID_RESET, b, "Defaults"))
+		apply_policy(p->key, "", 0);
+	b.x += 98;
+	b.w = 130;
+	if (m && visible(b, area) && ngui_button(&ui, ID_OPEN, b, "Open in Files"))
+		goto open_files;
+	y += 38;
+	text_dim(area.x, y,
+		 "Settings apply at once and are saved to /data/MOUNTS.CFG,");
+	y += 18;
+	text_dim(area.x, y, "so the boot scan uses them too.");
+	return y + 26;
+
+open_files:
+	{
+		char cwd[24];
+
+		snprintf(cwd, sizeof(cwd), "/%s", m->name);
+		if (u_spawn("/ramfs/bin/files", "", 0, cwd) < 0)
+			set_status("Could not start files", 1);
+	}
+	return y + 38;
+}
+
+static int draw_disk(struct ngui_rect area, int y, struct disk *d)
+{
+	struct ngui_row row;
+	struct ngui_rect r, b;
+	char line[128], size[16], title[48], sub[80];
+	const struct part *sel = 0;
+	int i;
+
+	snprintf(title, sizeof(title), "%s", d->bd.name);
+	ngui_text_px(&ui, area.x, y, title, (unsigned int)strlen(title),
+		     ui.theme.text, 18, 1, 0, 0);
+	y += 30;
+	fmt_size(size, sizeof(size), d->bd.total_sectors);
+	if (d->bd.kind == KIND_FLOPPY)
+		snprintf(line, sizeof(line), "%s drive", kind_name(d->bd.kind));
+	else
+		snprintf(line, sizeof(line), "%s%s%s, %s (%u sectors)",
+			 kind_name(d->bd.kind), d->bd.model[0] ? " " : "",
+			 d->bd.model, size, d->bd.total_sectors);
+	text_dim(area.x, y, line);
+	y += 20;
+	if (!d->bd.present) {
+		ngui_text(&ui, area.x, y, "Not present", ui.theme.warning);
+		return y + 30;
+	}
+	if (d->nebos) {
+		ngui_text(&ui, area.x, y, d->has_data ?
+			  "NebOS installed, with a /data partition" :
+			  "NebOS installed", ui.theme.success);
+		y += 20;
+	}
+	y += GAP;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, d->mbr ? "Partitions" : "Volume", 0, 0);
+	y += SECTION_H;
+	if (d->bd.kind != KIND_FLOPPY && !d->read_ok) {
+		ngui_text(&ui, area.x, y + 4, "The device could not be read",
+			  ui.theme.error);
+		y += 30;
+	} else if (!d->nparts) {
+		text_dim(area.x, y + 4,
+			 "No partition table and no FAT filesystem");
+		y += 30;
+	}
+	for (i = 0; i < d->nparts; i++) {
+		const struct part *p = &d->parts[i];
+		const struct sys_mount *m = mount_by_key(p->key);
+		const struct sys_mount_policy *pol = policy_by_key(p->key);
+		const char *what;
+		char trail[24];
+		int selectable = p->fat && !p->nebos_boot;
+
+		r = (struct ngui_rect){ area.x, y, area.w, ROW_H };
+		y += ROW_H;
+		if (selectable && !sel_key[0])
+			snprintf(sel_key, sizeof(sel_key), "%s", p->key);
+		if (selectable && !strcmp(sel_key, p->key))
+			sel = p;
+		if (!visible(r, area))
+			continue;
+		if (p->nebos_boot)
+			what = "NebOS boot + kernel";
+		else if (p->fat)
+			what = p->fs;
+		else
+			what = type_name(p->type);
+		fmt_size(size, sizeof(size), p->sectors);
+		if (p->slot >= 0)
+			snprintf(title, sizeof(title), "%d   %s%s%s", p->slot + 1,
+				 what, p->label[0] ? "  " : "", p->label);
+		else
+			/* A floppy is never read here; its mount has the label. */
+			snprintf(title, sizeof(title), "%s%s%s",
+				 d->bd.kind == KIND_FLOPPY ? "Floppy disk" : what,
+				 (p->label[0] || (m && m->label[0])) ? "  " : "",
+				 p->label[0] ? p->label : (m ? m->label : ""));
+		if (p->slot >= 0)
+			snprintf(sub, sizeof(sub), "%s, type 0x%02X, LBA %u%s",
+				 size, p->type, p->start,
+				 p->active ? ", active" : "");
+		else
+			snprintf(sub, sizeof(sub), "%s, whole device",
+				 d->bd.kind == KIND_FLOPPY ? "1.4 MB" : size);
+		if (m)
+			snprintf(trail, sizeof(trail), "/%s%s", m->name,
+				 m->ro ? " (ro)" : "");
+		else if (pol && (pol->flags & SYS_MOUNT_NOAUTO))
+			snprintf(trail, sizeof(trail), "unmounted");
+		else
+			snprintf(trail, sizeof(trail), "%s",
+				 selectable ? "not mounted" : "");
+		row.title = title;
+		row.subtitle = sub;
+		row.trailing = trail[0] ? trail : 0;
+		row.bars = -1;
+		row.selected = sel == p;
+		if (ngui_list_row(&ui, ID_PART_BASE + d->index * 4 +
+				  (unsigned int)(p->slot < 0 ? 0 : p->slot),
+				  r, &row) && selectable) {
+			snprintf(sel_key, sizeof(sel_key), "%s", p->key);
+			ngui_invalidate(&ui);
+		}
+	}
+	y += GAP;
+	if (sel)
+		y = draw_mount_editor(area, y, sel) + GAP;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Device", 0, 0);
+	y += SECTION_H;
+	b = (struct ngui_rect){ area.x, y, 120, 28 };
+	if (visible(b, area) && ngui_button(&ui, ID_FORMAT, b, "Format...")) {
+		dialog = DLG_FORMAT;
+		dlg_disk = sel_disk;
+		ngui_input_set(&size_in, "");
+		ngui_set_focus(&ui, ID_DLG_SIZE);
+	}
+	b.x += 128;
+	b.w = 150;
+	if (d->bd.kind != KIND_FLOPPY && visible(b, area) &&
+	    ngui_button(&ui, ID_INSTALL, b, "Install NebOS...")) {
+		dialog = DLG_INSTALL;
+		dlg_disk = sel_disk;
+	}
+	y += 36;
+	text_dim(area.x, y, d->bd.kind == KIND_FLOPPY ?
+		 "Format writes a fresh FAT12 filesystem." :
+		 "Format writes one FAT partition (MBR) over the whole disk.");
+	return y + 26;
+}
+
+static void draw_details(struct ngui_rect area)
+{
+	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);
+	top = area.y - detail_scroll.offset;
+	if (sel_disk < 0)
+		y = draw_overview(area, top);
+	else
+		y = draw_disk(area, top, &disks[sel_disk]);
+	detail_scroll.content_h = y - top;
+	ngui_scroll_end(&ui, area, &detail_scroll);
+}
+
+/* ---- dialogs ---- */
+
+static struct ngui_rect dialog_rect(int w, int h)
+{
+	struct ngui_rect r;
+
+	r.w = w < ui.w - 20 ? w : ui.w - 20;
+	r.h = h < ui.h - 20 ? h : ui.h - 20;
+	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,
+			     ui.theme.border);
+	ngui_fill_round_rect(&ui, r, 8, 8, 8, 8, ui.theme.panel);
+	return r;
+}
+
+static void dialog_title(struct ngui_rect *r, const char *s)
+{
+	struct ngui_rect t = ngui_cut_top(r, 34);
+
+	ngui_text_px(&ui, t.x, t.y + 6, s, (unsigned int)strlen(s),
+		     ui.theme.text, 16, 1, 0, 0);
+}
+
+static void dialog_line(struct ngui_rect *r, const char *s, unsigned short c)
+{
+	struct ngui_rect t = ngui_cut_top(r, 20);
+
+	ngui_text_ellipsis(&ui, t, t.x, t.y, s, c);
+}
+
+static int key_pressed(int key)
+{
+	if (ngui_key_peek(&ui) == key) {
+		ngui_key(&ui);
+		return 1;
+	}
+	return 0;
+}
+
+static void draw_format_dialog(void)
+{
+	const struct disk *d = &disks[dlg_disk];
+	struct ngui_rect r = dialog_rect(460, 260), b;
+	char line[96], size[16], arg[48], val[24];
+	int floppy = d->bd.kind == KIND_FLOPPY, go = 0, i;
+
+	ngui_inset(&r, 18);
+	snprintf(line, sizeof(line), "Format %s", d->bd.name);
+	dialog_title(&r, line);
+	fmt_size(size, sizeof(size), d->bd.total_sectors);
+	snprintf(line, sizeof(line), "%s%s%s, %s", kind_name(d->bd.kind),
+		 d->bd.model[0] ? " " : "", d->bd.model,
+		 floppy ? "1.4 MB" : size);
+	dialog_line(&r, line, ui.theme.text_dim);
+	dialog_line(&r, "Every file and partition on this device is erased.",
+		    ui.theme.warning);
+	if (d->nebos)
+		dialog_line(&r, "This removes the NebOS installation as well.",
+			    ui.theme.warning);
+	ngui_cut_top(&r, 8);
+	if (!floppy) {
+		b = ngui_cut_top(&r, 30);
+		text_dim(b.x, b.y + 6, "Size");
+		b.x += 60;
+		b.w = 140;
+		size_in.placeholder = "whole disk";
+		if (ngui_text_input(&ui, ID_DLG_SIZE, b, &size_in) &
+		    NGUI_INPUT_SUBMIT)
+			go = 1;
+		text_dim(b.x + b.w + 10, b.y + 6, "e.g. 100mb, 2gb");
+	}
+	b = ngui_cut_bottom(&r, 30);
+	b.x = r.x + r.w - 110;
+	b.w = 110;
+	if (ngui_button(&ui, ID_DLG_OK, b, "Erase disk"))
+		go = 1;
+	b.x -= 100;
+	b.w = 92;
+	if (ngui_button(&ui, ID_DLG_CANCEL, b, "Cancel") ||
+	    key_pressed(NGUI_KEY_ESC)) {
+		dialog = DLG_NONE;
+		return;
+	}
+	if (!go)
+		return;
+	ngui_input_value(&size_in, val, sizeof(val));
+	for (i = 0; val[i]; i++)
+		if (val[i] == ' ' || (val[i] >= 'A' && val[i] <= 'Z'))
+			val[i] = val[i] == ' ' ? '\0' : (char)(val[i] + 32);
+	snprintf(arg, sizeof(arg), "-y %s%s%s", d->bd.name,
+		 (!floppy && val[0]) ? " " : "", floppy ? "" : val);
+	snprintf(line, sizeof(line), "Formatting %s", d->bd.name);
+	ngui_set_focus(&ui, 0);
+	start_job("format", arg, line);
+}
+
+static void draw_install_dialog(void)
+{
+	const struct disk *d = &disks[dlg_disk];
+	struct ngui_rect r = dialog_rect(520, d->nebos ? 290 : 250), b;
+	char line[96], arg[48], size[16];
+	int mode = 0;
+
+	ngui_inset(&r, 18);
+	snprintf(line, sizeof(line), "Install NebOS on %s", d->bd.name);
+	dialog_title(&r, line);
+	fmt_size(size, sizeof(size), d->bd.total_sectors);
+	snprintf(line, sizeof(line), "%s%s%s, %s", kind_name(d->bd.kind),
+		 d->bd.model[0] ? " " : "", d->bd.model, size);
+	dialog_line(&r, line, ui.theme.text_dim);
+	if (d->nebos) {
+		dialog_line(&r, "NebOS is already installed here.", ui.theme.text);
+		dialog_line(&r, "Update writes the running kernel and rootfs to "
+			    "partitions 1-2.", ui.theme.text_dim);
+		dialog_line(&r, "Reinstall clones the live image (partitions 1-3).",
+			    ui.theme.text_dim);
+		dialog_line(&r, "Both keep the /data partition.",
+			    ui.theme.success);
+	} else {
+		dialog_line(&r, "Clones the live NebOS image (boot, rootfs, EFI) and",
+			    ui.theme.text_dim);
+		dialog_line(&r, "creates a /data partition on the rest of the disk.",
+			    ui.theme.text_dim);
+		dialog_line(&r, "Everything else on this device is erased.",
+			    ui.theme.warning);
+	}
+	b = ngui_cut_bottom(&r, 30);
+	b.x = r.x + r.w - 110;
+	b.w = 110;
+	if (ngui_button(&ui, ID_DLG_OK, b, d->nebos ? "Update" : "Install"))
+		mode = d->nebos ? 2 : 1;
+	if (d->nebos) {
+		b.x -= 118;
+		b.w = 110;
+		if (ngui_button(&ui, ID_DLG_OK2, b, "Reinstall"))
+			mode = 1;
+	}
+	b.x -= 100;
+	b.w = 92;
+	if (ngui_button(&ui, ID_DLG_CANCEL, b, "Cancel") ||
+	    key_pressed(NGUI_KEY_ESC)) {
+		dialog = DLG_NONE;
+		return;
+	}
+	if (!mode)
+		return;
+	snprintf(arg, sizeof(arg), "-y %s%s", d->bd.name,
+		 mode == 2 ? " self" : "");
+	snprintf(line, sizeof(line), "%s NebOS on %s",
+		 mode == 2 ? "Updating" : "Installing", d->bd.name);
+	start_job("install", arg, line);
+}
+
+static void draw_job_dialog(void)
+{
+	struct ngui_rect r = dialog_rect(600, 380), b, log;
+	int lh = 16, lines, n, i, start;
+	const char *p;
+
+	ngui_inset(&r, 18);
+	dialog_title(&r, job_title);
+	if (!job_done)
+		dialog_line(&r, "Running... keep the devices connected.",
+			    ui.theme.warning);
+	else
+		dialog_line(&r, job_ok ? "Finished." : "Failed; see the output below.",
+			    job_ok ? ui.theme.success : ui.theme.error);
+	ngui_cut_top(&r, 6);
+	b = ngui_cut_bottom(&r, 30);
+	ngui_cut_bottom(&r, 10);
+	log = r;
+	ngui_fill_rect(&ui, log, ui.theme.bg);
+	ngui_inset(&log, 6);
+	ngui_push_clip(&ui, log);
+	/* Show the newest lines that fit. */
+	lines = log.h / lh;
+	n = 0;
+	for (p = job_log; *p; p++)
+		if (*p == '\n')
+			n++;
+	if (job_len && job_log[job_len - 1] != '\n')
+		n++;
+	start = n > lines ? n - lines : 0;
+	p = job_log;
+	for (i = 0; *p && i < start; p++)
+		if (*p == '\n')
+			i++;
+	for (i = 0; *p && i < lines; i++) {
+		const char *e = strchr(p, '\n');
+		unsigned int len = e ? (unsigned int)(e - p) : (unsigned int)strlen(p);
+
+		ngui_text_px(&ui, log.x, log.y + i * lh, p, len, ui.theme.text,
+			     13, 0, 0, 1);
+		p += len;
+		if (*p == '\n')
+			p++;
+	}
+	ngui_pop_clip(&ui);
+	if (job_done) {
+		b.x = r.x + r.w - 92;
+		b.w = 92;
+		if (ngui_button(&ui, ID_DLG_CLOSE, b, "Close") ||
+		    key_pressed(NGUI_KEY_ESC) || key_pressed('\n'))
+			dialog = DLG_NONE;
+	}
+}
+
+static void draw(void)
+{
+	struct ngui_rect all = { 0, 0, ui.w, ui.h }, body, list;
+	struct input_save save;
+
+	int muted = dialog != DLG_NONE;
+
+	if (muted)
+		input_mute(&save);
+	ngui_fill_rect(&ui, all, ui.theme.bg);
+	body = all;
+	draw_toolbar(ngui_cut_top(&body, TOOLBAR_H));
+	list = ngui_cut_left(&body, LIST_W);
+	draw_device_list(list);
+	ngui_fill_rect(&ui, ngui_cut_left(&body, 1), ui.theme.border);
+	draw_details(body);
+	if (dialog == DLG_NONE)
+		return;
+	if (muted)
+		input_restore(&save);
+	if (dialog == DLG_FORMAT)
+		draw_format_dialog();
+	else if (dialog == DLG_INSTALL)
+		draw_install_dialog();
+	else if (dialog == DLG_JOB)
+		draw_job_dialog();
+}
+
+void _start(const char *arg)
+{
+	struct win_info wi;
+	unsigned int cw, ch;
+	int quit = 0;
+
+	(void)arg;
+	if (u_win_create(800, 560, "Disks", &wi) != 0) {
+		u_puts("disks: no graphics window\n");
+		u_exit(1);
+	}
+	cw = wi.width;
+	ch = wi.height;
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)cw, (int)ch);
+	ngui_font_attach(&ui);
+	name_in.placeholder = "mount name";
+	load_all();
+
+	for (;;) {
+		struct win_info cur;
+
+		if (u_win_info(&cur) == 0 &&
+		    (cur.width != cw || cur.height != ch) &&
+		    u_win_ack_resize() == 0) {
+			cw = cur.width;
+			ch = cur.height;
+			ui.px = (unsigned short *)cur.fb;
+			ui.w = (int)cw;
+			ui.h = (int)ch;
+			ngui_invalidate(&ui);
+		}
+		job_poll();
+		if (status_until && (int)(u_ticks_ms() - status_until) >= 0) {
+			status[0] = '\0';
+			status_until = 0;
+			ngui_invalidate(&ui);
+		}
+		if (!ngui_begin(&ui)) {
+			u_sleep_ms(dialog == DLG_JOB ? 20 : 10);
+			continue;
+		}
+		draw();
+		if (dialog == DLG_NONE && !ui.focus && key_pressed(NGUI_KEY_ESC))
+			quit = 1;
+		ngui_end(&ui);
+		if (quit)
+			break;
+		if (rescan_pending) {
+			/* The frame above showed "Scanning..."; the rescan
+			 * blocks this window while it probes the disks. */
+			struct sys_storage_info si;
+
+			rescan_pending = 0;
+			u_syscall1(SYS_STORAGE_INFO, (int)&si);
+			load_all();
+			set_status("Devices rescanned", 0);
+		}
+		u_sleep_ms(10);
+	}
+	u_win_close();
+	u_exit(0);
+}

+ 15 - 0
user/apps/files/ucmd_files.c

@@ -30,6 +30,7 @@ enum {
 	ID_NEW_INPUT,
 	ID_CREATE,
 	ID_CANCEL,
+	ID_DISKS,
 };
 
 #define ACT_UP       (1u << 0)
@@ -43,6 +44,7 @@ enum {
 #define ACT_CREATE   (1u << 8)
 #define ACT_CANCEL   (1u << 9)
 #define ACT_CLOSE    (1u << 10)
+#define ACT_DISKS    (1u << 11)
 
 struct fm_entry {
 	char name[64];
@@ -611,6 +613,9 @@ static void do_action(unsigned int action)
 		refresh();
 	if (action & ACT_NEW)
 		new_folder();
+	if ((action & ACT_DISKS) &&
+	    u_spawn("/ramfs/bin/disks", "", 0, "/") < 0)
+		set_status("Cannot start disks", 1);
 	if (action & ACT_OPEN)
 		open_selected();
 	if (action & ACT_CREATE) {
@@ -658,6 +663,11 @@ static void draw_toolbar(struct ngui *g, struct ngui_rect r, unsigned int *actio
 				     (struct ngui_rect){x, y, 30, h},
 				     NGUI_ICON_PLUS))
 			*action |= ACT_NEW;
+		/* Storage manager, right-aligned. */
+		if (ngui_icon_button(g, ID_DISKS,
+				     (struct ngui_rect){r.x + r.w - 36, y, 30, h},
+				     NGUI_ICON_DISK))
+			*action |= ACT_DISKS;
 	} else {
 		int w;
 
@@ -679,6 +689,11 @@ static void draw_toolbar(struct ngui *g, struct ngui_rect r, unsigned int *actio
 		if (ngui_button(g, ID_NEW, (struct ngui_rect){x, y, w, h},
 				"New Folder"))
 			*action |= ACT_NEW;
+		w = (int)ngui_text_width_ui(g, "Disks") + 18;
+		if (ngui_button(g, ID_DISKS,
+				(struct ngui_rect){r.x + r.w - 6 - w, y, w, h},
+				"Disks"))
+			*action |= ACT_DISKS;
 	}
 }