فهرست منبع

process: add a graphical task manager

Add the `process` ngui app: 60-second CPU, physical-memory and NIC-throughput graphs fed by one sample per second, plus a process table sortable by PID, state, CPU, memory, time or name.  A selected row can be ended after a second confirming click; kernel threads and the monitor itself are protected.

The network graph needs throughput counters, so every driver RX/TX now goes through netdev_rx_frame()/netdev_tx_frame(), which keep 32-bit frame byte totals for all NICs; SYS_NET_INFO exposes them as rx_bytes/tx_bytes.  SYS_PROCINFO gains kernel_thread, set from the PCB, so the GUI can disable End task for kernel threads.

The key ring is drained every frame, PgUp/PgDn are applied after ngui_scroll_begin() sets the view height, and a press on the overlay scrollbar no longer selects the row underneath.  Network rates use overflow-free scaling so gigabit links report the right throughput.

Verified in QEMU: window and all three graphs, header sorting, row selection, confirmed termination and Esc after typing an unrelated key.  `make all` succeeds and the full pack stays under the 2 MB cap.
Johannes Zellner 3 روز پیش
والد
کامیت
d459322876
19فایلهای تغییر یافته به همراه1553 افزوده شده و 37 حذف شده
  1. 24 9
      AGENTS.md
  2. 5 1
      Makefile
  3. 7 3
      docs/graphics.html
  4. 1 1
      docs/index.html
  5. 1 0
      docs/network.html
  6. 4 2
      docs/userland.html
  7. 6 2
      include/syscall.h
  8. 1 1
      kernel/dhcp.c
  9. 1 1
      kernel/dns.c
  10. 3 3
      kernel/net.c
  11. 2 2
      kernel/netcore.c
  12. 39 0
      kernel/netdev.c
  13. 11 0
      kernel/netdev.h
  14. 4 4
      kernel/netkexec.c
  15. 1 1
      kernel/ntp.c
  16. 1 0
      kernel/process.c
  17. 5 4
      kernel/sys_net.c
  18. 3 3
      kernel/tcp.c
  19. 1434 0
      user/apps/process/ucmd_process.c

+ 24 - 9
AGENTS.md

@@ -338,8 +338,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   is the only global-tick source.  APs do not start taking user work until
   `smp_enable_sched()`, i.e. after device/FS setup.  LAPIC IPIs (vector 0x31)
   request a reschedule; they must be EOIed on the target LAPIC.
-  `SYS_PROCINFO` exposes weight/state/CPU/ticks for the ring-3 `top` command,
-  and `sched`/`renice` plus `SYS_SCHEDINFO` expose the scheduler counters.
+  `SYS_PROCINFO` exposes weight/state/CPU/ticks and the `kernel_thread` flag
+  for the ring-3 `top` and `process` commands, and `sched`/`renice` plus
+  `SYS_SCHEDINFO` expose the scheduler counters.
   Ring 0 is preemptible at tick boundaries unless `preempt_count` is set (FAT
   and the shadow flush) or the BKL is held; voluntary blocks/yields go through
   the `int 0x81` gate.
@@ -845,7 +846,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `netdev [name]` is a kernel command that shows the active driver or
   switches it (`netdev rndis`, `netdev asix`, `netdev e1000e`, ...); it calls
   the selected driver's probe and leaves the current driver untouched on
-  failure.  The top-bar status area opens `ucmd_netmenu.c`, the control
+  failure.  Every receive/send goes through `netdev_rx_frame()`/
+  `netdev_tx_frame()`, which keep the 32-bit frame byte counters behind
+  `SYS_NET_INFO.rx_bytes/tx_bytes` (the `process` monitor's network graph).
+  The top-bar status area opens `ucmd_netmenu.c`, the control
   panel.  It lists every present driver through `SYS_NET_DEVLIST` (111),
   selects one
   through `SYS_NET_SELECT` (112) and runs DHCP; the same popover lists scanned
@@ -1423,10 +1427,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `cd` (the shell passes arguments verbatim).  The one argument is passed as a
   C string on the top of the user stack (`process_create_user(..., arg)`), so
   `_start(const char *arg)` needs no crt0.  `ngui.c/h` is the shared userland
-  GUI toolkit linked into `ucmd_files.c`, `ucmd_mines.c`, `ucmd_solitaire.c`
-  and the external `gallery.elf` (buttons, menu items, text fields with a
-  disabled state, icons, layout cuts and scroll panes); `files` opens
-  the selected text file through
+  GUI toolkit linked into `ucmd_files.c`, `ucmd_mines.c`, `ucmd_solitaire.c`,
+  `ucmd_process.c` and the external `gallery.elf` (buttons, menu items, text
+  fields with a disabled state, icons, layout cuts and scroll panes);
+  `files` opens the selected text file through
   `/ramfs/bin/edit`, image files through `/ramfs/bin/view`, and `.htm`/`.html`
   files through `/ramfs/bin/browser`.  `ngui_end_ex()`
   is the variant that runs the bookkeeping without publishing the canvas, for
@@ -1440,6 +1444,17 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `bin/gallery` launcher, which prefers `/share/GALLERY` (development upload
   via `make gallery-dev`), then the pack copy, then the `GALLERY` disk
   fallback on `root.img`/FAT mounts.
+- **Process monitor**: `ucmd_process.c` — the graphical task manager (`process`,
+  the ngui counterpart of `top`).  It samples once per second and keeps 60 s
+  histories of CPU busy (summed `SYS_SCHEDINFO` idle ticks over all CPUs),
+  physical memory in use (`SYS_MEMINFO`) and NIC throughput (the 32-bit frame
+  byte counters in `SYS_NET_INFO`).  Three cards draw the graphs with ngui
+  rectangles/lines; the process table below is sortable by PID, state, CPU,
+  memory, time or name (click a header) and scrolls with PgUp/PgDn or the
+  wheel.
+  Selecting a row shows its details; `End task` asks for a second click, then
+  calls `SYS_KILL`.  Kernel threads and the monitor itself are protected
+  (`sys_procinfo.kernel_thread`, `SYS_GETPID`).  Esc closes the window.
 - **Solitaire**: `ucmd_solitaire.c` — a Windows 95 style Klondike game on the
   canvas service: green felt, a Game/Help menu (ngui buttons and menu items:
   new game, draw one/three, blue or red deck), four foundations, seven tableau
@@ -2040,7 +2055,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`, `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),
+`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
 `ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), and `chat [config-path]` (Cloudron Chat client).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
@@ -2071,7 +2086,7 @@ changed with `cd`; paths may be absolute (`/floppy1/…`) or relative (`.`, `..`
 nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
-`cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `spin`,
+`cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `process`, `spin`,
 `clock`, `colors`, `settime`, `date`, `files`, `disks`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `websrv`, `curl`, `wifi`, `netmenu`, `solitaire` and `hello` are files in `/ramfs/bin`

+ 5 - 1
Makefile

@@ -379,7 +379,7 @@ $(UL)/wifi/wpa.o: XFLAGS = $(SECTION_CFLAGS)
 # single-file command needs nothing else; one that links libraries gets an
 # explicit .elf rule below.
 UCMDS = cpuinfo ls cat save rm mkdir rmdir \
-        meminfo mouseinfo storage top \
+        meminfo mouseinfo storage top process \
         clock colors edit wm term spin \
         netinfo netip netdns host dhcp \
         netsend netrecv ping pong netlog \
@@ -432,6 +432,10 @@ $(call app,term).elf: $(call app,term).o $(UWM) $(FONT16) $(UFONT_OBJS) $(UCMD_L
 $(call app,files).elf: $(call app,files).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 
+# Task manager: process table with CPU, memory and network history graphs.
+$(call app,process).elf: $(call app,process).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
+	$(ULINK)
+
 $(call app,mines).elf: $(call app,mines).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 

+ 7 - 3
docs/graphics.html

@@ -369,8 +369,8 @@
 			clipped RGB565 primitives, buttons, menu items, text fields, the
 			Adwaita symbolic icons (see <a href="#icons">UI icons</a>), a theme palette, layout cut helpers and scrolling
 			panes. It is linked into <code>files</code>, <code>mines</code>,
-			<code>solitaire</code>, <code>chat</code>, the control panel and
-			the real <code>gallery.elf</code>.
+			<code>solitaire</code>, <code>process</code>, <code>chat</code>,
+			the control panel and the real <code>gallery.elf</code>.
 		</p>
 		<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>
@@ -413,6 +413,10 @@
 				<h3>files</h3>
 				<p>File browser on the VFS: opens text in <code>edit</code>, images in <code>view</code> and HTML in <code>browser</code>. The first ngui user.</p>
 			</div>
+			<div class="card">
+				<h3>process</h3>
+				<p>Graphical task manager (<code>process</code>, the ngui counterpart of <code>top</code>): 60 s CPU, physical-memory and NIC-throughput graphs fed by one sample per second, and a sortable process table (PID, state, CPU%, memory, CPU time, name). A selected row shows its details and <em>End task</em> terminates it after a second confirming click; kernel threads and the monitor itself are protected. Headers sort, PgUp/PgDn and the wheel scroll, Esc closes.</p>
+			</div>
 			<div class="card">
 				<h3>gallery</h3>
 				<p>Live showcase of every ngui control and primitive. Ships in the pack as <code>bin/gallery.app</code>; a launcher prefers <code>/share/GALLERY</code> for development.</p>
@@ -561,7 +565,7 @@
 			<li><code>user/lib/ngui/ngui.c</code>, <code>user/lib/ngui/ngui.h</code> — toolkit</li>
 			<li><code>user/lib/ufont/ufont.c</code>, <code>user/lib/ufont/ufont_ttf.c</code>, <code>user/lib/ufont/ufont_draw.c</code> — fixed-point TrueType text</li>
 			<li><code>fonts/*.ttf</code> — Arimo / Liberation Mono / Noto Emoji subsets in the pack</li>
-			<li><code>user/apps/files/ucmd_files.c</code>, <code>user/apps/gallery/gallery.c</code>, <code>user/apps/solitaire/ucmd_solitaire.c</code>, <code>user/apps/chat/ucmd_chat.c</code></li>
+			<li><code>user/apps/files/ucmd_files.c</code>, <code>user/apps/process/ucmd_process.c</code>, <code>user/apps/gallery/gallery.c</code>, <code>user/apps/solitaire/ucmd_solitaire.c</code>, <code>user/apps/chat/ucmd_chat.c</code></li>
 			<li><code>user/lib/img/img*.c</code> — image codecs</li>
 			<li><code>kernel/ati.c</code>, <code>kernel/nvidia.c</code>, <code>kernel/intel.c</code>, <code>kernel/nv50.c</code></li>
 			<li><code>kernel/backlight.c</code>, <code>kernel/backlight.h</code> — Cherryview/VLV panel PWM</li>

+ 1 - 1
docs/index.html

@@ -78,7 +78,7 @@
 
 				<rect class="svg-box accent" x="100" y="8" width="720" height="72" rx="9"/>
 				<text class="svg-text" x="124" y="35">Ring 3 · commands &amp; GUI apps</text>
-				<text class="svg-sub" x="124" y="55">ls · cat · edit · view · files · browser · chat · gallery · solitaire</text>
+				<text class="svg-sub" x="124" y="55">ls · cat · edit · view · files · process · browser · chat · gallery · solitaire</text>
 				<text class="svg-tiny" x="796" y="35" text-anchor="end">0x40000000</text>
 
 				<path class="svg-line" d="M460 80v22"/>

+ 1 - 0
docs/network.html

@@ -379,6 +379,7 @@
 			<li><strong>Reaper safety.</strong> If a raw owner dies, <code>sys_net_reap</code> force-releases the receiver through <code>netdev_release_all()</code>; sockets and a pending DNS query owned by the dead process are closed separately.</li>
 			<li><strong>Wait semantics.</strong> Stack waits now yield with <code>process_sleep_ms()</code> and re-enable interrupts for driver TX timeouts; the syscall stub enters with interrupts off.</li>
 			<li><strong>One connection per process.</strong> The connection state lives in the kernel, keyed by the calling pid.  <code>SYS_TCP_CONNECT/SEND/RECV/CLOSE</code> keep their ABI, so uhttp and the TLS layer did not need a socket handle.</li>
+			<li><strong>Byte counters.</strong> <code>netdev_rx_frame()</code>/<code>netdev_tx_frame()</code> wrap every driver receive and send and maintain 32-bit frame byte totals for all NICs, including the management link (Ethernet header included; failed sends add nothing).  <code>SYS_NET_INFO</code> reports them as <code>rx_bytes</code>/<code>tx_bytes</code>, so the <code>process</code> monitor can graph throughput from deltas without touching the receiver.</li>
 		</ul>
 	</section>
 

+ 4 - 2
docs/userland.html

@@ -322,7 +322,7 @@
 			</div>
 			<div class="card">
 				<h3>System</h3>
-				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>mouseinfo</code> <code>touchpad</code> <code>sensors</code> <code>powerinfo</code> <code>date</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
+				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>process</code> <code>mouseinfo</code> <code>touchpad</code> <code>sensors</code> <code>powerinfo</code> <code>date</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
 			</div>
 			<div class="card">
 				<h3>Network</h3>
@@ -330,7 +330,7 @@
 			</div>
 			<div class="card">
 				<h3>GUI</h3>
-				<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>
+				<p><code>wm</code> <code>term</code> <code>files</code> <code>disks</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>process</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
 			</div>
 		</div>
 		<p>
@@ -347,6 +347,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>process</strong> — graphical task manager, the ngui counterpart of <code>top</code>. It samples once per second into 60 s histories of CPU busy (<code>SYS_SCHEDINFO</code> idle ticks summed over all CPUs), physical memory in use (<code>SYS_MEMINFO</code>) and NIC throughput (<code>SYS_NET_INFO.rx_bytes</code>/<code>tx_bytes</code> from the netdev frame counters), then draws the three graphs with ngui rectangles and lines. The table lists PID, state, CPU%, memory, total CPU time and name; clicking a header sorts by PID, state, CPU, memory, time or name, and PgUp/PgDn or the wheel scrolls. Selecting a row shows its details; <em>End task</em> asks for a second click and then calls <code>SYS_KILL</code>, while kernel threads (<code>kernel_thread</code> in the process snapshot) and the monitor itself are protected. Esc closes it.</li>
 			<li><strong>disks</strong> — storage manager (top-bar <em>Disks</em> button, or 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, link-preview cards (click one to open it in the browser) 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>
@@ -448,6 +449,7 @@
 			<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/process/ucmd_process.c</code> — graphical task manager and its history graphs</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>

+ 6 - 2
include/syscall.h

@@ -267,6 +267,8 @@ struct sys_netinfo {
 	char name[8];
 	char chip[16];
 	unsigned int link;       /* active netdev reports a usable link */
+	unsigned int rx_bytes;   /* frame bytes received since boot (wraps) */
+	unsigned int tx_bytes;   /* frame bytes sent since boot (wraps) */
 };
 
 /* One selectable NIC (see SYS_NET_DEVLIST). */
@@ -347,8 +349,9 @@ struct sys_meminfo {
 	unsigned int e820_count;
 };
 
-/* One live process, for `top` (PROC_NAME_LEN = 12).  cpu_ticks/life_ticks
- * are PIT ticks (1 kHz), so lifecycle percentages can be derived. */
+/* One live process, for `top`/`process` (PROC_NAME_LEN = 12).
+ * cpu_ticks/life_ticks are PIT ticks (1 kHz), so lifecycle percentages can be
+ * derived. */
 struct sys_procinfo {
 	unsigned int pid;
 	unsigned int state;       /* PROC_*: 1 ready, 2 running, 4 sleep, 5 block */
@@ -358,6 +361,7 @@ struct sys_procinfo {
 	unsigned int weight;      /* CFS weight, 1..SCHED_WEIGHT_MAX */
 	unsigned int cpu;         /* CPU id, or 0xFFFFFFFF when not running */
 	char name[12];
+	unsigned int kernel_thread; /* 1 = kernel thread (not a ring-3 program) */
 };
 
 /* Scheduler counters for `top` and the `sched` command. */

+ 1 - 1
kernel/dhcp.c

@@ -335,7 +335,7 @@ static int dhcp_wait(const struct netdev *nd, unsigned int xid,
 		unsigned char type;
 		unsigned char ryi[4], rmask[4], rgw[4], rdns[4], rserver[4];
 		unsigned int rlease;
-		int len = nd->rx(rxbuf, sizeof(rxbuf));
+		int len = netdev_rx_frame(nd, rxbuf, sizeof(rxbuf));
 
 		if (len < 0)
 			continue;

+ 1 - 1
kernel/dns.c

@@ -452,7 +452,7 @@ int dns_resolve(const char *name, unsigned char ip[4])
 
 		while ((int)(get_ticks_ms() - deadline) < 0) {
 			if (raw) {
-				int len = nd->rx(netdev_rx_scratch(),
+				int len = netdev_rx_frame(nd, netdev_rx_scratch(),
 						 NETDEV_FRAME_MAX);
 
 				if (len < 0)

+ 3 - 3
kernel/net.c

@@ -294,7 +294,7 @@ int net_udp_send_from_dev(const struct netdev *nd,
 	for (i = 0; i < len; i++)
 		udp[8 + i] = p[i];
 
-	return nd->tx(udp_frame, 14 + total);
+	return netdev_tx_frame(nd, udp_frame, 14 + total);
 }
 
 int net_udp_send_from(const unsigned char *src_ip,
@@ -552,7 +552,7 @@ int net_arp_resolve(const unsigned char *dst_ip, unsigned char mac[6])
 		 * alive even though the syscall gate entered with IF=0. */
 		if (!raw)
 			flags = net_irq_enter();
-		tx = nd->tx(req, reqlen);
+		tx = netdev_tx_frame(nd, req, reqlen);
 		if (!raw)
 			net_irq_exit(flags);
 		if (tx != 0) {
@@ -564,7 +564,7 @@ int net_arp_resolve(const unsigned char *dst_ip, unsigned char mac[6])
 		while ((int)(get_ticks_ms() - deadline) < 0) {
 			if (raw) {
 				unsigned char spa[4], sha[6];
-				int len = nd->rx(netdev_rx_scratch(),
+				int len = netdev_rx_frame(nd, netdev_rx_scratch(),
 						 NETDEV_FRAME_MAX);
 
 				if (len < 0)

+ 2 - 2
kernel/netcore.c

@@ -106,7 +106,7 @@ int net_pump(unsigned int budget)
 	flags = net_irq_enter();
 
 	for (n = 0; n < budget; n++) {
-		int len = nd->rx(rx, NETDEV_FRAME_MAX);
+		int len = netdev_rx_frame(nd, rx, NETDEV_FRAME_MAX);
 
 		if (len < 0)
 			break;
@@ -124,7 +124,7 @@ int net_pump(unsigned int budget)
 						   reply_buf, sizeof(reply_buf));
 
 			if (rlen > 0)
-				nd->tx(reply_buf, (unsigned int)rlen);
+				netdev_tx_frame(nd, reply_buf, (unsigned int)rlen);
 		}
 	}
 	net_irq_exit(flags);

+ 39 - 0
kernel/netdev.c

@@ -35,11 +35,50 @@ static unsigned int owner_pid;   /* process that took the NIC (busy > 0) */
  * command via netdev_acquire()). */
 static unsigned char rx_scratch[NETDEV_FRAME_MAX];
 
+/* Kernel-wide frame byte counters behind SYS_NET_INFO; every driver feeds
+ * them.  Only the Ethernet header and payload are counted, a failed send adds
+ * nothing and a zero-length receive leaves them alone. */
+static unsigned int rx_total, tx_total;
+
 unsigned char *netdev_rx_scratch(void)
 {
 	return rx_scratch;
 }
 
+int netdev_rx_frame(const struct netdev *nd, unsigned char *buf,
+		    unsigned int maxlen)
+{
+	int len;
+
+	if (!nd || !nd->rx)
+		return -1;
+	len = nd->rx(buf, maxlen);
+	if (len > 0)
+		rx_total += (unsigned int)len;
+	return len;
+}
+
+int netdev_tx_frame(const struct netdev *nd, const unsigned char *buf,
+		    unsigned int len)
+{
+	int ret;
+
+	if (!nd || !nd->tx)
+		return -1;
+	ret = nd->tx(buf, len);
+	if (ret == 0)
+		tx_total += len;
+	return ret;
+}
+
+void netdev_byte_counters(unsigned int *rx, unsigned int *tx)
+{
+	if (rx)
+		*rx = rx_total;
+	if (tx)
+		*tx = tx_total;
+}
+
 void netdev_acquire(void)
 {
 	if (busy == 0 && current_proc())

+ 11 - 0
kernel/netdev.h

@@ -89,6 +89,17 @@ const char *netdev_chip(const struct netdev *nd);
 /* Fill the active NIC's MAC; -1 (and a zero MAC) when there is no NIC. */
 int netdev_get_mac(unsigned char mac[6]);
 
+/* Frame I/O with the kernel-wide byte counters.  Every receive and send goes
+ * through these wrappers instead of calling nd->rx()/nd->tx() directly, so
+ * SYS_NET_INFO can report the totals to the process monitor.  The counters
+ * cover every NIC (including the management link), include the Ethernet
+ * header and wrap at 32 bits. */
+int netdev_rx_frame(const struct netdev *nd, unsigned char *buf,
+		    unsigned int maxlen);
+int netdev_tx_frame(const struct netdev *nd, const unsigned char *buf,
+		    unsigned int len);
+void netdev_byte_counters(unsigned int *rx, unsigned int *tx);
+
 /* One shared frame-receive scratch buffer (1518 bytes) for protocol code that
  * just needs somewhere for nd->rx() to land.  Only valid while the caller
  * owns the NIC, and only until the next rx().  Shared so the DNS/TCP/ARP

+ 4 - 4
kernel/netkexec.c

@@ -154,7 +154,7 @@ static int netkexec_poll_nd(const struct netdev *nd, int capture)
 	unsigned int n;
 
 	for (n = 0; n < 8; n++) {
-		int len = nd->rx(rxbuf, sizeof(rxbuf));
+		int len = netdev_rx_frame(nd, rxbuf, sizeof(rxbuf));
 
 		if (len < 0)
 			break;
@@ -176,7 +176,7 @@ static int netkexec_poll_nd(const struct netdev *nd, int capture)
 						       replybuf,
 						       sizeof(replybuf));
 			if (rlen > 0)
-				nd->tx(replybuf, (unsigned int)rlen);
+				netdev_tx_frame(nd, replybuf, (unsigned int)rlen);
 		}
 	}
 	return 0;
@@ -326,7 +326,7 @@ static int netkexec_recv(unsigned int stage_base)
 			continue;
 		}
 
-		len = nd->rx(rxbuf, sizeof(rxbuf));
+		len = netdev_rx_frame(nd, rxbuf, sizeof(rxbuf));
 		if (len < 0) {
 			/* Yield so the WM and terminal keep running while we
 			 * wait for the next datagram; this used to busy-spin
@@ -352,7 +352,7 @@ static int netkexec_recv(unsigned int stage_base)
 							       replybuf,
 							       sizeof(replybuf));
 				if (rlen > 0)
-					nd->tx(replybuf, (unsigned int)rlen);
+					netdev_tx_frame(nd, replybuf, (unsigned int)rlen);
 			}
 			/* Yield after a frame that was not ours (ARP/ICMP or
 			 * a stray datagram), so a broadcast storm cannot keep

+ 1 - 1
kernel/ntp.c

@@ -214,7 +214,7 @@ int ntp_sync(const char *server, unsigned int timeout_ms,
 			return SYS_NTP_ETX;
 
 		while ((int)(get_ticks_ms() - deadline) < 0) {
-			int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+			int len = netdev_rx_frame(nd, rxbuf, NETDEV_FRAME_MAX);
 
 			if (len < 0)
 				continue;

+ 1 - 0
kernel/process.c

@@ -818,6 +818,7 @@ int process_procinfo(unsigned int index, struct sys_procinfo *out)
 		out->pages      = 2 + count_user_pages(p->cr3) + p->heap_pages;
 		out->weight     = p->weight;
 		out->cpu        = p->on_cpu;
+		out->kernel_thread = p->kernel_thread ? 1 : 0;
 		name_copy(out->name, p->name);
 		sched_lock_release(flags);
 		return 1;

+ 5 - 4
kernel/sys_net.c

@@ -146,6 +146,7 @@ int sys_net_info(struct sys_netinfo *out)
 			out->chip[i] = chip[i];
 	}
 	out->link = (unsigned int)netdev_link(nd);
+	netdev_byte_counters(&out->rx_bytes, &out->tx_bytes);
 	return 1;
 }
 
@@ -264,7 +265,7 @@ int sys_net_tx(const unsigned char *buf, unsigned int len)
 
 	if (!nd || !owns_nic())
 		return -1;
-	return nd->tx(buf, len);
+	return netdev_tx_frame(nd, buf, len);
 }
 
 int sys_net_rx(unsigned char *buf, unsigned int max)
@@ -273,7 +274,7 @@ int sys_net_rx(unsigned char *buf, unsigned int max)
 
 	if (!nd || !owns_nic())
 		return -1;
-	return nd->rx(buf, max);
+	return netdev_rx_frame(nd, buf, max);
 }
 
 void sys_net_decode(const unsigned char *buf, unsigned int len)
@@ -485,7 +486,7 @@ int sys_tcp_accept(void)
 
 	net_enter();
 	for (i = 0; i < 16; i++) {
-		len = nd->rx(rx, NETDEV_FRAME_MAX);
+		len = netdev_rx_frame(nd, rx, NETDEV_FRAME_MAX);
 		if (len < 0)
 			break;
 		if (tcp_srv_input(rx, (unsigned int)len))
@@ -499,7 +500,7 @@ int sys_tcp_accept(void)
 						   srv_reply,
 						   sizeof(srv_reply));
 			if (rlen > 0)
-				nd->tx(srv_reply, (unsigned int)rlen);
+				netdev_tx_frame(nd, srv_reply, (unsigned int)rlen);
 		}
 	}
 	c = tcp_srv_accept();

+ 3 - 3
kernel/tcp.c

@@ -167,7 +167,7 @@ static int tcp_send_segment_wnd(struct tcp_conn *c, unsigned char flags,
 	cs = net_checksum_tcp(my_ip, c->dst_ip, tcp, 20 + optlen + len);
 	wr16(tcp + 16, cs);
 
-	return nd->tx(tx_frame, 14 + total);
+	return netdev_tx_frame(nd, tx_frame, 14 + total);
 }
 
 static int tcp_send_segment(struct tcp_conn *c, unsigned char flags,
@@ -735,7 +735,7 @@ int tcp_recv(struct tcp_conn *c, unsigned char *out, unsigned int maxlen,
 			return -1;
 
 		{
-			int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+			int len = netdev_rx_frame(nd, rxbuf, NETDEV_FRAME_MAX);
 
 			if (len < 0)
 				continue;
@@ -1214,7 +1214,7 @@ int tcp_srv_send(struct tcp_conn *c, const void *data, unsigned int len)
 
 			while ((int)(get_ticks_ms() - deadline) < 0) {
 				struct tcp_seg s;
-				int rlen = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+				int rlen = netdev_rx_frame(nd, rxbuf, NETDEV_FRAME_MAX);
 
 				if (rlen < 0)
 					continue;

+ 1434 - 0
user/apps/process/ucmd_process.c

@@ -0,0 +1,1434 @@
+/* process: graphical task manager, the ngui counterpart of `top`.
+ *
+ * One sample per second drives three history graphs (CPU busy, physical
+ * memory in use and NIC throughput) and a sortable live process table.
+ * CPU% comes from the per-process PIT counters (SYS_PROCINFO) sampled once
+ * per second; the overall CPU graph uses the summed idle ticks from
+ * SYS_SCHEDINFO, so it covers every CPU.  Network rates are the deltas of the
+ * netdev frame byte counters exposed through SYS_NET_INFO.
+ *
+ * The window is a normal canvas window.  ngui only redraws when input or a
+ * sample asks for it, so the app sleeps in 50 ms slices and wakes the
+ * renderer once per sample.  Esc closes it; column headers sort the table.
+ */
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+
+/* PROC_MAX in kernel/process.h (SYS_PROCINFO indexes live processes). */
+#define PMAX        64
+#define HIST        60
+#define SAMPLE_MS   1000
+#define LOOP_MS     50
+#define NET_KB_MAX  2000000u    /* ~2 GB/s history ceiling */
+#define ROW_H       20
+#define PAD         10
+#define GAP         8
+#define HEAD_H      24
+#define TABLE_HEAD  22
+#define FOOTER_H    22
+
+enum {
+	COL_PID,
+	COL_STATE,
+	COL_CPU,
+	COL_MEM,
+	COL_TIME,
+	COL_NAME,
+	COL_COUNT
+};
+
+enum {
+	SORT_CPU,
+	SORT_MEM,
+	SORT_PID,
+	SORT_TIME,
+	SORT_NAME,
+	SORT_STATE
+};
+
+enum {
+	ID_KILL = 1
+};
+
+struct prow {
+	unsigned int pid;
+	unsigned int state;
+	unsigned int weight;
+	unsigned int cpu_pm;
+	unsigned int cpu_ticks;
+	unsigned int pages;
+	unsigned int kernel;
+	char name[12];
+};
+
+static struct ngui ui;
+static struct ngui_scroll table_scroll;
+static int page_req;          /* PgUp/PgDn pages requested by the key ring */
+
+static struct sys_procinfo pinfo[PMAX];
+static struct sys_procinfo prev_info[PMAX];
+static unsigned int nprev;
+static struct prow rows[PMAX];
+static unsigned int nrows;
+static unsigned int ntotal;
+
+static unsigned int cpu_hist[HIST];
+static unsigned int mem_hist[HIST];
+static unsigned int rx_hist[HIST];
+static unsigned int tx_hist[HIST];
+
+static unsigned int last_sample_ms;
+static unsigned int last_idle_ticks;
+static unsigned int last_net_rx, last_net_tx;
+static int net_present;
+static int net_have_base;
+
+static unsigned int cpu_busy_pm;
+static unsigned int mem_used_pm;
+static unsigned int mem_used_kb;
+static unsigned int mem_total_kb;
+static unsigned int page_kb = 4;
+static unsigned int ncpus;
+static unsigned int runnable;
+static unsigned int net_rx_rate;
+static unsigned int net_tx_rate;
+
+static unsigned int selected_pid;
+static unsigned int own_pid;
+static int sort_mode = SORT_CPU;
+static int sort_desc = 1;
+
+static unsigned int kill_confirm_pid;
+static unsigned int kill_confirm_until;
+static char status_msg[128];
+static unsigned int status_until;
+static int status_error;
+
+/* ---- freestanding string/format helpers ---- */
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void s_copy(char *d, unsigned int cap, const char *s)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
+{
+	while (s && *s && *n + 1 < cap)
+		d[(*n)++] = *s++;
+	d[*n] = '\0';
+}
+
+static void s_append_ch(char *d, unsigned int *n, char c, unsigned int cap)
+{
+	if (*n + 1 < cap) {
+		d[(*n)++] = c;
+		d[*n] = '\0';
+	}
+}
+
+static void s_append_uint(char *d, unsigned int *n, unsigned int v,
+			  unsigned int cap)
+{
+	char tmp[12];
+	unsigned int i = 0, j;
+
+	do {
+		tmp[i++] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v && i < sizeof(tmp));
+	for (j = 0; j < i && *n + 1 < cap; j++)
+		d[(*n)++] = tmp[i - 1 - j];
+	d[*n] = '\0';
+}
+
+static void s_append_uint2(char *d, unsigned int *n, unsigned int v,
+			   unsigned int cap)
+{
+	if (v < 10)
+		s_append_ch(d, n, '0', cap);
+	s_append_uint(d, n, v, cap);
+}
+
+static void s_append_pm(char *d, unsigned int *n, unsigned int pm,
+			unsigned int cap)
+{
+	if (pm > 1000)
+		pm = 1000;
+	s_append_uint(d, n, pm / 10, cap);
+	s_append_ch(d, n, '.', cap);
+	s_append_ch(d, n, (char)('0' + pm % 10), cap);
+	s_append_ch(d, n, '%', cap);
+}
+
+static void fmt_pct(char *buf, unsigned int cap, unsigned int pm)
+{
+	unsigned int n = 0;
+
+	if (!cap)
+		return;
+	buf[0] = '\0';
+	s_append_pm(buf, &n, pm, cap);
+}
+
+/* 12345 KB -> "12.1 MB"; 456 KB -> "456 KB"; 2 GB -> "2.0 GB". */
+static void fmt_kb(char *buf, unsigned int cap, unsigned int kb)
+{
+	unsigned int n = 0, t;
+
+	if (!cap)
+		return;
+	buf[0] = '\0';
+	if (kb >= 1024u * 1024u) {
+		t = (kb * 10u + 524288u) / (1024u * 1024u);
+		s_append_uint(buf, &n, t / 10, cap);
+		s_append_ch(buf, &n, '.', cap);
+		s_append_ch(buf, &n, (char)('0' + t % 10), cap);
+		s_append(buf, &n, " GB", cap);
+	} else if (kb >= 1024) {
+		t = (kb * 10u + 512u) / 1024u;
+		s_append_uint(buf, &n, t / 10, cap);
+		s_append_ch(buf, &n, '.', cap);
+		s_append_ch(buf, &n, (char)('0' + t % 10), cap);
+		s_append(buf, &n, " MB", cap);
+	} else {
+		s_append_uint(buf, &n, kb, cap);
+		s_append(buf, &n, " KB", cap);
+	}
+}
+
+/* Bytes per second -> "812 B/s", "12.3 KB/s", "1.4 MB/s". */
+static void fmt_rate(char *buf, unsigned int cap, unsigned int bps)
+{
+	unsigned int n = 0, t;
+
+	if (!cap)
+		return;
+	buf[0] = '\0';
+	if (bps < 1024) {
+		s_append_uint(buf, &n, bps, cap);
+		s_append(buf, &n, " B/s", cap);
+	} else if (bps < 1024u * 1024u) {
+		t = (bps * 10u + 512u) / 1024u;
+		s_append_uint(buf, &n, t / 10, cap);
+		s_append_ch(buf, &n, '.', cap);
+		s_append_ch(buf, &n, (char)('0' + t % 10), cap);
+		s_append(buf, &n, " KB/s", cap);
+	} else {
+		unsigned int mb = bps / (1024u * 1024u);
+		unsigned int rem = bps % (1024u * 1024u);
+
+		t = mb * 10u + (rem * 10u + 524288u) / (1024u * 1024u);
+		s_append_uint(buf, &n, t / 10, cap);
+		s_append_ch(buf, &n, '.', cap);
+		s_append_ch(buf, &n, (char)('0' + t % 10), cap);
+		s_append(buf, &n, " MB/s", cap);
+	}
+}
+
+/* KB/s history value -> a compact graph scale label. */
+static void fmt_rate_kb(char *buf, unsigned int cap, unsigned int kb)
+{
+	fmt_rate(buf, cap, kb * 1024u);
+}
+
+static void fmt_span(char *buf, unsigned int cap, unsigned int ms)
+{
+	unsigned int n = 0;
+
+	if (!cap)
+		return;
+	buf[0] = '\0';
+	if (ms < 60000) {
+		unsigned int tenths = ms / 100;
+
+		s_append_uint(buf, &n, tenths / 10, cap);
+		s_append_ch(buf, &n, '.', cap);
+		s_append_ch(buf, &n, (char)('0' + tenths % 10), cap);
+		s_append_ch(buf, &n, 's', cap);
+	} else if (ms < 3600000) {
+		s_append_uint(buf, &n, ms / 60000, cap);
+		s_append_ch(buf, &n, 'm', cap);
+		s_append_uint2(buf, &n, (ms / 1000) % 60, cap);
+		s_append_ch(buf, &n, 's', cap);
+	} else {
+		s_append_uint(buf, &n, ms / 3600000, cap);
+		s_append_ch(buf, &n, 'h', cap);
+		s_append_uint2(buf, &n, (ms / 60000) % 60, cap);
+		s_append_ch(buf, &n, 'm', cap);
+	}
+}
+
+static void fmt_uptime(char *buf, unsigned int cap, unsigned int s)
+{
+	unsigned int n = 0;
+
+	if (!cap)
+		return;
+	buf[0] = '\0';
+	if (s >= 3600) {
+		s_append_uint(buf, &n, s / 3600, cap);
+		s_append_ch(buf, &n, 'h', cap);
+		s_append_ch(buf, &n, ' ', cap);
+		s_append_uint2(buf, &n, (s / 60) % 60, cap);
+		s_append_ch(buf, &n, 'm', cap);
+	} else if (s >= 60) {
+		s_append_uint(buf, &n, s / 60, cap);
+		s_append_ch(buf, &n, 'm', cap);
+		s_append_ch(buf, &n, ' ', cap);
+		s_append_uint2(buf, &n, s % 60, cap);
+		s_append_ch(buf, &n, 's', cap);
+	} else {
+		s_append_uint(buf, &n, s, cap);
+		s_append_ch(buf, &n, 's', cap);
+	}
+}
+
+static int s_ci_cmp(const char *a, const char *b)
+{
+	for (;;) {
+		unsigned char ca = (unsigned char)*a++;
+		unsigned char cb = (unsigned char)*b++;
+
+		if (ca >= 'A' && ca <= 'Z')
+			ca = (unsigned char)(ca + 32);
+		if (cb >= 'A' && cb <= 'Z')
+			cb = (unsigned char)(cb + 32);
+		if (ca != cb)
+			return (int)ca - (int)cb;
+		if (!ca)
+			return 0;
+	}
+}
+
+static const char *state_name(unsigned int s)
+{
+	if (s == 2)
+		return "running";
+	if (s == 1)
+		return "ready";
+	if (s == 4)
+		return "sleep";
+	if (s == 5)
+		return "block";
+	return "?";
+}
+
+/* Active first, then runnable, blocked, sleeping. */
+static unsigned int state_rank(unsigned int s)
+{
+	if (s == 2)
+		return 0;
+	if (s == 1)
+		return 1;
+	if (s == 5)
+		return 2;
+	if (s == 4)
+		return 3;
+	return 4;
+}
+
+/* ---- colour helpers ---- */
+
+static unsigned short shade(unsigned short c, unsigned int num,
+			    unsigned int den)
+{
+	unsigned int r = (c >> 11) & 0x1F;
+	unsigned int g = (c >> 5) & 0x3F;
+	unsigned int b = c & 0x1F;
+
+	r = r * num / den;
+	g = g * num / den;
+	b = b * num / den;
+	return (unsigned short)((r << 11) | (g << 5) | b);
+}
+
+static unsigned short mem_color(unsigned int pm)
+{
+	if (pm >= 900)
+		return ui.theme.error;
+	if (pm >= 700)
+		return ui.theme.warning;
+	return ui.theme.success;
+}
+
+/* ---- sampling ---- */
+
+static unsigned int snapshot_procs(struct sys_procinfo *out)
+{
+	struct sys_procinfo p;
+	unsigned int i, n = 0;
+
+	for (i = 0; i < PMAX; i++) {
+		if (u_syscall2(SYS_PROCINFO, (int)i, (int)&p) != 1)
+			break;
+		out[n++] = p;
+	}
+	return n;
+}
+
+/* Ascending comparator; `sort_desc` inverts the whole order below. */
+static int row_cmp(const struct prow *a, const struct prow *b)
+{
+	int c = 0;
+
+	switch (sort_mode) {
+	case SORT_MEM:
+		if (a->pages != b->pages)
+			c = a->pages < b->pages ? -1 : 1;
+		break;
+	case SORT_PID:
+		if (a->pid != b->pid)
+			c = a->pid < b->pid ? -1 : 1;
+		break;
+	case SORT_TIME:
+		if (a->cpu_ticks != b->cpu_ticks)
+			c = a->cpu_ticks < b->cpu_ticks ? -1 : 1;
+		break;
+	case SORT_NAME:
+		c = s_ci_cmp(a->name, b->name);
+		break;
+	case SORT_STATE:
+		if (state_rank(a->state) != state_rank(b->state))
+			c = state_rank(a->state) < state_rank(b->state) ?
+				-1 : 1;
+		break;
+	case SORT_CPU:
+	default:
+		if (a->cpu_pm != b->cpu_pm)
+			c = a->cpu_pm < b->cpu_pm ? -1 : 1;
+		break;
+	}
+	if (!c) {
+		if (a->pid != b->pid)
+			c = a->pid < b->pid ? -1 : 1;
+		else
+			c = s_ci_cmp(a->name, b->name);
+	}
+	return sort_desc ? -c : c;
+}
+
+static void sort_rows(void)
+{
+	unsigned int i, j;
+
+	for (i = 1; i < nrows; i++) {
+		struct prow key = rows[i];
+
+		j = i;
+		while (j > 0 && row_cmp(&rows[j - 1], &key) > 0) {
+			rows[j] = rows[j - 1];
+			j--;
+		}
+		rows[j] = key;
+	}
+}
+
+/* Turn a snapshot into table rows, computing CPU% from the previous sample. */
+static void build_rows(const struct sys_procinfo *cur, unsigned int n,
+		       unsigned int wall, int with_delta)
+{
+	unsigned int i, j;
+
+	nrows = n;
+	ntotal = n;
+	for (i = 0; i < n; i++) {
+		struct prow *r = &rows[i];
+		unsigned int pm = 0;
+
+		if (with_delta && wall) {
+			for (j = 0; j < nprev; j++)
+				if (prev_info[j].pid == cur[i].pid) {
+					unsigned int delta =
+						cur[i].cpu_ticks -
+						prev_info[j].cpu_ticks;
+
+					pm = delta * 1000u / wall;
+					if (pm > 1000u)
+						pm = 1000u;
+					break;
+				}
+		}
+		r->pid = cur[i].pid;
+		r->state = cur[i].state;
+		r->weight = cur[i].weight;
+		r->cpu_pm = pm;
+		r->cpu_ticks = cur[i].cpu_ticks;
+		r->pages = cur[i].pages;
+		r->kernel = cur[i].kernel_thread;
+		s_copy(r->name, sizeof(r->name), cur[i].name);
+	}
+	sort_rows();
+}
+
+/* Bytes over `wall` ms -> bytes per second without overflowing the
+ * intermediate product at gigabit rates. */
+static unsigned int net_rate(unsigned int bytes, unsigned int wall)
+{
+	if (!wall)
+		wall = 1;
+	return (bytes / wall) * 1000u + (bytes % wall) * 1000u / wall;
+}
+
+static void sample_net(unsigned int wall)
+{
+	struct sys_netinfo ni;
+	unsigned int drx, dtx;
+
+	if (u_net_info(&ni) != 1 || !ni.present) {
+		net_present = 0;
+		net_have_base = 0;
+		net_rx_rate = 0;
+		net_tx_rate = 0;
+		last_net_rx = 0;
+		last_net_tx = 0;
+		return;
+	}
+	net_present = 1;
+	if (!net_have_base) {
+		/* A NIC that appeared after the app started must not count its
+		 * whole boot-time traffic as one sample. */
+		net_have_base = 1;
+		last_net_rx = ni.rx_bytes;
+		last_net_tx = ni.tx_bytes;
+		net_rx_rate = 0;
+		net_tx_rate = 0;
+		return;
+	}
+	if (!wall)
+		wall = 1;
+	drx = ni.rx_bytes - last_net_rx;
+	dtx = ni.tx_bytes - last_net_tx;
+	last_net_rx = ni.rx_bytes;
+	last_net_tx = ni.tx_bytes;
+	net_rx_rate = net_rate(drx, wall);
+	net_tx_rate = net_rate(dtx, wall);
+}
+
+static void hist_push(unsigned int *h, unsigned int v)
+{
+	unsigned int i;
+
+	for (i = 0; i + 1 < HIST; i++)
+		h[i] = h[i + 1];
+	h[HIST - 1] = v;
+}
+
+static void sample(void)
+{
+	struct sys_schedinfo s;
+	struct sys_meminfo m;
+	unsigned int now = u_ticks_ms();
+	unsigned int wall = now - last_sample_ms;
+	unsigned int ncur, i, rx_kb, tx_kb;
+
+	if (!wall)
+		wall = 1;
+
+	/* Process table: compare this snapshot with the previous second. */
+	ncur = snapshot_procs(pinfo);
+	build_rows(pinfo, ncur, wall, 1);
+	for (i = 0; i < ncur; i++)
+		prev_info[i] = pinfo[i];
+	nprev = ncur;
+
+	/* CPU: summed idle ticks across all CPUs over the sample window. */
+	if (u_schedinfo(&s) == 0) {
+		unsigned int diedle = s.idle_ticks - last_idle_ticks;
+		unsigned int cpus = s.ncpus ? s.ncpus : 1;
+		unsigned int idle_pm = diedle * 1000u / (wall * cpus);
+
+		if (idle_pm > 1000u)
+			idle_pm = 1000u;
+		cpu_busy_pm = 1000u - idle_pm;
+		ncpus = s.ncpus;
+		runnable = s.runnable;
+		last_idle_ticks = s.idle_ticks;
+	}
+
+	/* Physical memory: total minus free pages. */
+	if (u_syscall1(SYS_MEMINFO, (int)&m) == 0) {
+		unsigned int free_kb = m.free_pages * (m.page_size / 1024);
+
+		if (m.page_size >= 1024)
+			page_kb = m.page_size / 1024;
+		mem_total_kb = m.total_kb;
+		mem_used_kb = mem_total_kb > free_kb ?
+			mem_total_kb - free_kb : 0;
+		mem_used_pm = mem_total_kb ?
+			mem_used_kb * 1000u / mem_total_kb : 0;
+		if (mem_used_pm > 1000u)
+			mem_used_pm = 1000u;
+	}
+
+	/* Network deltas are in bytes per second; the graph keeps KB/s. */
+	sample_net(wall);
+	rx_kb = (net_rx_rate + 1023u) / 1024u;
+	tx_kb = (net_tx_rate + 1023u) / 1024u;
+	if (rx_kb > NET_KB_MAX)
+		rx_kb = NET_KB_MAX;
+	if (tx_kb > NET_KB_MAX)
+		tx_kb = NET_KB_MAX;
+
+	hist_push(cpu_hist, cpu_busy_pm);
+	hist_push(mem_hist, mem_used_pm);
+	hist_push(rx_hist, rx_kb);
+	hist_push(tx_hist, tx_kb);
+
+	if (selected_pid) {
+		unsigned int i;
+		int found = 0;
+
+		for (i = 0; i < nrows; i++)
+			if (rows[i].pid == selected_pid) {
+				found = 1;
+				break;
+			}
+		if (!found) {
+			selected_pid = 0;
+			kill_confirm_pid = 0;
+		}
+	}
+	last_sample_ms = now;
+}
+
+/* ---- drawing helpers ---- */
+
+static void text_right(struct ngui *u, int right, int y, const char *s,
+		       unsigned short color)
+{
+	int w = (int)ngui_text_width_ui(u, s);
+
+	ngui_text(u, right - w, y, s, color);
+}
+
+
+static void fill_rect_(struct ngui *u, int x, int y, int w, int h,
+		       unsigned short c)
+{
+	struct ngui_rect r;
+
+	r.x = x;
+	r.y = y;
+	r.w = w;
+	r.h = h;
+	ngui_fill_rect(u, r, c);
+}
+
+static void draw_card(struct ngui *u, struct ngui_rect r, const char *caption,
+		      const char *right)
+{
+	ngui_fill_round_rect(u, r, 8, 8, 8, 8, u->theme.panel);
+	ngui_text(u, r.x + 10, r.y + 7, caption, u->theme.text_dim);
+	if (right && r.w > 160)
+		text_right(u, r.x + r.w - 10, r.y + 7, right,
+			   u->theme.text_dim);
+}
+
+static int value_y(const struct ngui_rect *r, unsigned int v,
+		   unsigned int max)
+{
+	unsigned int h;
+
+	if (!max)
+		max = 1;
+	if (v > max)
+		v = max;
+	h = v * (unsigned int)r->h / max;
+	return r->y + r->h - (int)h;
+}
+
+static void graph_grid(struct ngui *u, struct ngui_rect r)
+{
+	int i;
+
+	fill_rect_(u, r.x, r.y, r.w, r.h, NGUI_RGB(28, 32, 44));
+	for (i = 1; i < 4; i++)
+		fill_rect_(u, r.x, r.y + r.h * i / 4, r.w, 1,
+			   NGUI_RGB(46, 51, 66));
+	ngui_frame(u, r, NGUI_RGB(56, 62, 80));
+}
+
+/* Filled history bars with a 2 px bright cap. */
+static void graph_bars(struct ngui *u, struct ngui_rect r,
+		       const unsigned int *hist, unsigned int max,
+		       unsigned short color)
+{
+	int i;
+	unsigned short dim = shade(color, 45, 100);
+
+	if (max == 0)
+		max = 1;
+	for (i = 0; i < HIST; i++) {
+		int x0 = r.x + i * r.w / HIST;
+		int x1 = r.x + (i + 1) * r.w / HIST;
+		int bw = x1 - x0;
+		int y = value_y(&r, hist[i], max);
+		int bh = r.y + r.h - y;
+
+		if (bw < 1)
+			bw = 1;
+		if (bh <= 0)
+			continue;
+		fill_rect_(u, x0, y, bw - 1 > 0 ? bw - 1 : 1, bh, dim);
+		fill_rect_(u, x0, y, bw - 1 > 0 ? bw - 1 : 1,
+			   bh < 2 ? bh : 2, color);
+	}
+}
+
+/* A one-pixel history line (used for the TX overlay). */
+static void graph_line(struct ngui *u, struct ngui_rect r,
+		       const unsigned int *hist, unsigned int max,
+		       unsigned short color)
+{
+	int i, px = 0, py = 0;
+
+	if (max == 0)
+		max = 1;
+	for (i = 0; i < HIST; i++) {
+		int x = r.x + i * (r.w - 1) / (HIST - 1);
+		int y = value_y(&r, hist[i], max);
+
+		if (i)
+			ngui_line(u, px, py, x, y, color);
+		if (i)
+			ngui_line(u, px, py + 1, x, y + 1, color);
+		px = x;
+		py = y;
+	}
+}
+
+static unsigned int history_peak(const unsigned int *a,
+				 const unsigned int *b)
+{
+	unsigned int i, max = 0;
+
+	for (i = 0; i < HIST; i++) {
+		if (a[i] > max)
+			max = a[i];
+		if (b && b[i] > max)
+			max = b[i];
+	}
+	return max;
+}
+
+static unsigned int history_max(const unsigned int *a, const unsigned int *b)
+{
+	unsigned int max = history_peak(a, b);
+
+	return max + max / 4 + 1;
+}
+
+static void draw_cpu_card(struct ngui *u, struct ngui_rect r)
+{
+	struct ngui_rect g;
+	char b[16], right[24];
+	unsigned int n = 0;
+
+	right[0] = '\0';
+	if (ncpus) {
+		s_append_uint(right, &n, ncpus, sizeof(right));
+		s_append(right, &n, ncpus == 1 ? " CPU" : " CPUs", sizeof(right));
+	}
+	draw_card(u, r, "CPU", right);
+	fmt_pct(b, sizeof(b), cpu_busy_pm);
+	ngui_text_px(u, r.x + 10, r.y + 24, b, s_len(b), u->theme.accent,
+		     24, 1, 0, 0);
+	text_right(u, r.x + r.w - 10, r.y + 33, "busy", u->theme.text_dim);
+	g.x = r.x + 10;
+	g.y = r.y + 52;
+	g.w = r.w - 20;
+	g.h = r.h - g.y + r.y - 8;
+	if (g.w < 10 || g.h < 10)
+		return;
+	graph_grid(u, g);
+	graph_bars(u, g, cpu_hist, 1000, u->theme.accent);
+}
+
+static void draw_mem_card(struct ngui *u, struct ngui_rect r)
+{
+	struct ngui_rect g;
+	char b[16], used[16], total[16], detail[40];
+	unsigned int n = 0;
+	unsigned short color = mem_color(mem_used_pm);
+
+	fmt_pct(b, sizeof(b), mem_used_pm);
+	fmt_kb(used, sizeof(used), mem_used_kb);
+	fmt_kb(total, sizeof(total), mem_total_kb);
+	detail[0] = '\0';
+	s_append(detail, &n, used, sizeof(detail));
+	s_append(detail, &n, " / ", sizeof(detail));
+	s_append(detail, &n, total, sizeof(detail));
+	draw_card(u, r, "Memory", detail);
+	ngui_text_px(u, r.x + 10, r.y + 24, b, s_len(b), color,
+		     24, 1, 0, 0);
+	text_right(u, r.x + r.w - 10, r.y + 33, "in use",
+		   u->theme.text_dim);
+	g.x = r.x + 10;
+	g.y = r.y + 52;
+	g.w = r.w - 20;
+	g.h = r.h - g.y + r.y - 8;
+	if (g.w < 10 || g.h < 10)
+		return;
+	graph_grid(u, g);
+	graph_bars(u, g, mem_hist, 1000, color);
+}
+
+static void draw_net_card(struct ngui *u, struct ngui_rect r)
+{
+	struct ngui_rect g;
+	char rx[18], tx[18], scale[18];
+	unsigned int peak = history_peak(rx_hist, tx_hist);
+	unsigned int max = history_max(rx_hist, tx_hist);
+
+	fmt_rate(rx, sizeof(rx), net_rx_rate);
+	fmt_rate(tx, sizeof(tx), net_tx_rate);
+	if (!net_present)
+		s_copy(scale, sizeof(scale), "no NIC");
+	else if (!peak)
+		s_copy(scale, sizeof(scale), "idle");
+	else
+		fmt_rate_kb(scale, sizeof(scale), max);
+	draw_card(u, r, "Network", scale);
+
+	if (net_present) {
+		ngui_text(u, r.x + 10, r.y + 27, "RX", u->theme.success);
+		ngui_text(u, r.x + 34, r.y + 27, rx, u->theme.text);
+		{
+			int txw = (int)ngui_text_width_ui(u, rx) + 52;
+
+			ngui_text(u, r.x + txw, r.y + 27, "TX",
+				  u->theme.warning);
+			ngui_text(u, r.x + txw + 24, r.y + 27, tx,
+				  u->theme.text);
+		}
+	} else {
+		ngui_text(u, r.x + 10, r.y + 27, "no network device",
+			  u->theme.text_dim);
+	}
+	g.x = r.x + 10;
+	g.y = r.y + 50;
+	g.w = r.w - 20;
+	g.h = r.h - g.y + r.y - 8;
+	if (g.w < 10 || g.h < 10)
+		return;
+	graph_grid(u, g);
+	if (net_present) {
+		graph_bars(u, g, rx_hist, max, u->theme.success);
+		graph_line(u, g, tx_hist, max, u->theme.warning);
+	}
+}
+
+/* Column positions shared by the header, rows and click handling. */
+static void table_columns(const struct ngui_rect *r, int xs[COL_COUNT],
+			  int ws[COL_COUNT])
+{
+	static const int fixed[COL_COUNT] = { 54, 62, 58, 66, 74, 0 };
+	int x = r->x + 6;
+	int i;
+
+	for (i = 0; i < COL_COUNT; i++)
+		ws[i] = fixed[i];
+	ws[COL_NAME] = r->w - 6 - (54 + 62 + 58 + 66 + 74) - 20;
+	if (ws[COL_NAME] < 30)
+		ws[COL_NAME] = 30;
+	for (i = 0; i < COL_COUNT; i++) {
+		xs[i] = x;
+		x += ws[i];
+	}
+}
+
+static int sort_col(int col)
+{
+	if (col == COL_PID)
+		return SORT_PID;
+	if (col == COL_CPU)
+		return SORT_CPU;
+	if (col == COL_MEM)
+		return SORT_MEM;
+	if (col == COL_TIME)
+		return SORT_TIME;
+	if (col == COL_NAME)
+		return SORT_NAME;
+	if (col == COL_STATE)
+		return SORT_STATE;
+	return -1;
+}
+
+static int sort_default_desc(int mode)
+{
+	return mode == SORT_CPU || mode == SORT_MEM || mode == SORT_TIME;
+}
+
+static void set_sort(int col)
+{
+	int mode = sort_col(col);
+
+	if (mode < 0)
+		return;
+	if (mode == sort_mode)
+		sort_desc = !sort_desc;
+	else {
+		sort_mode = mode;
+		sort_desc = sort_default_desc(mode);
+	}
+	sort_rows();
+	ngui_invalidate(&ui);
+}
+
+static void draw_table_header(struct ngui *u, struct ngui_rect r)
+{
+	static const char *labels[COL_COUNT] = {
+		"PID", "STATE", "CPU%", "MEM", "TIME", "NAME"
+	};
+	int xs[COL_COUNT], ws[COL_COUNT], i;
+
+	fill_rect_(u, r.x, r.y, r.w, r.h, u->theme.panel_alt);
+	table_columns(&r, xs, ws);
+	for (i = 0; i < COL_COUNT; i++) {
+		struct ngui_rect hr;
+		char label[16];
+		unsigned int n = 0;
+		int mode = sort_col(i);
+		int active = mode >= 0 && sort_mode == mode;
+		int right = (i == COL_PID || i == COL_CPU || i == COL_MEM ||
+			     i == COL_TIME);
+
+		label[0] = '\0';
+		if (active && mode >= 0) {
+			s_copy(label, sizeof(label), labels[i]);
+			n = s_len(label);
+			s_append_ch(label, &n, ' ', sizeof(label));
+			s_append_ch(label, &n, sort_desc ? 'v' : '^',
+				    sizeof(label));
+		} else {
+			s_copy(label, sizeof(label), labels[i]);
+		}
+		hr.x = xs[i];
+		hr.y = r.y;
+		hr.w = ws[i];
+		hr.h = r.h;
+		if (mode >= 0)
+			ngui_cursor_rect(u, hr, CURSOR_POINTER);
+		if (right)
+			text_right(u, xs[i] + ws[i] - 8, r.y + 3, label,
+				   active ? u->theme.accent : u->theme.text_dim);
+		else
+			ngui_text(u, xs[i], r.y + 3, label,
+				  active ? u->theme.accent : u->theme.text_dim);
+		if (active)
+			fill_rect_(u, xs[i], r.y + r.h - 2, ws[i] - 8, 2,
+				   u->theme.accent);
+		if (mode >= 0 && u->pressed &&
+		    ngui_rect_contains(&hr, u->press_x, u->press_y))
+			set_sort(i);
+	}
+}
+
+static struct prow *selected_row(void)
+{
+	unsigned int i;
+
+	if (!selected_pid)
+		return 0;
+	for (i = 0; i < nrows; i++)
+		if (rows[i].pid == selected_pid)
+			return &rows[i];
+	return 0;
+}
+
+static void draw_process_row(struct ngui *u, const struct ngui_rect *list,
+			     int row_index, int y, int selected, int hover)
+{
+	int xs[COL_COUNT], ws[COL_COUNT];
+	const struct prow *p = &rows[row_index];
+	unsigned short fg = selected ? NGUI_RGB(255, 255, 255) :
+		u->theme.text;
+	char b[32];
+	unsigned int n = 0;
+
+	table_columns(list, xs, ws);
+	if (selected)
+		fill_rect_(u, list->x, y, list->w, ROW_H, u->theme.selection);
+	else if (hover)
+		fill_rect_(u, list->x, y, list->w, ROW_H,
+			   u->theme.panel_alt);
+
+	s_append_uint(b, &n, p->pid, sizeof(b));
+	ngui_text(u, xs[COL_PID] + ws[COL_PID] - 8 -
+		  (int)ngui_text_width_ui(u, b), y + 2, b, fg);
+
+	ngui_text(u, xs[COL_STATE], y + 2, state_name(p->state),
+		  selected ? fg : (p->state == 2 ? u->theme.success :
+				   p->state == 5 ? u->theme.warning :
+				   u->theme.text_dim));
+
+	b[0] = '\0';
+	n = 0;
+	s_append_pm(b, &n, p->cpu_pm, sizeof(b));
+	text_right(u, xs[COL_CPU] + ws[COL_CPU] - 8, y + 2, b, fg);
+
+	b[0] = '\0';
+	n = 0;
+	s_append_uint(b, &n, p->pages * page_kb, sizeof(b));
+	s_append_ch(b, &n, 'K', sizeof(b));
+	text_right(u, xs[COL_MEM] + ws[COL_MEM] - 8, y + 2, b, fg);
+
+	fmt_span(b, sizeof(b), p->cpu_ticks);
+	text_right(u, xs[COL_TIME] + ws[COL_TIME] - 8, y + 2, b, fg);
+
+	ngui_text(u, xs[COL_NAME], y + 2, p->name,
+		  p->kernel && !selected ? u->theme.text_dim : fg);
+}
+
+static void draw_table(struct ngui *u, struct ngui_rect list)
+{
+	unsigned int i;
+	int first, last, y;
+	int pressed_row = -1;
+
+	table_scroll.content_h = (int)nrows * ROW_H;
+	ngui_scroll_begin(u, list, &table_scroll);
+	ngui_scroll_wheel(u, list, &table_scroll);
+	if (page_req) {
+		int page = table_scroll.view_h - 22;
+
+		if (page < 22)
+			page = 22;
+		ngui_scroll_to(&table_scroll,
+			       table_scroll.offset + page_req * page);
+		page_req = 0;
+	}
+
+	/* After ngui_scroll_begin(): a press on the overlay bar has been
+	 * consumed, so it cannot also select the row underneath. */
+	if (u->pressed && ngui_rect_contains(&list, u->press_x, u->press_y)) {
+		int idx = (u->press_y - list.y + table_scroll.offset) / ROW_H;
+
+		if (idx >= 0 && (unsigned int)idx < nrows)
+			pressed_row = idx;
+	}
+	if (pressed_row >= 0) {
+		if (selected_pid != rows[pressed_row].pid) {
+			selected_pid = rows[pressed_row].pid;
+			kill_confirm_pid = 0;
+			ngui_invalidate(u);
+		}
+	}
+
+	fill_rect_(u, list.x, list.y, list.w, list.h, u->theme.panel);
+	first = table_scroll.offset / ROW_H;
+	if (first < 0)
+		first = 0;
+	last = (table_scroll.offset + list.h + ROW_H - 1) / ROW_H;
+	if (last > (int)nrows)
+		last = (int)nrows;
+	for (i = (unsigned int)first; i < (unsigned int)last; i++) {
+		int hover = u->inside &&
+			ngui_rect_contains(&list, u->mouse_x, u->mouse_y) &&
+			(u->mouse_y - list.y + table_scroll.offset) / ROW_H ==
+			(int)i;
+		int selected = rows[i].pid == selected_pid;
+
+		y = list.y + (int)i * ROW_H - table_scroll.offset;
+		draw_process_row(u, &list, (int)i, y, selected, hover);
+	}
+	ngui_scroll_end(u, list, &table_scroll);
+}
+
+static void draw_kill_button(struct ngui *u, struct ngui_rect r)
+{
+	struct prow *sel = selected_row();
+	struct ngui_rect br;
+	char label[32];
+	unsigned int now = u_ticks_ms();
+
+	br.x = r.x + r.w - 150;
+	br.y = r.y;
+	br.w = 150;
+	br.h = 24;
+
+	if (!sel) {
+		text_right(u, r.x + r.w, r.y + 4, "Select a process",
+			   u->theme.text_dim);
+		return;
+	}
+	if (sel->kernel || sel->pid == own_pid) {
+		ngui_fill_round_rect(u, br, 6, 6, 6, 6, u->theme.panel_alt);
+		text_right(u, br.x + br.w - 10, br.y + 4,
+			   sel->kernel ? "kernel thread" : "this window",
+			   u->theme.text_dim);
+		ngui_cursor_rect(u, br, CURSOR_NOT_ALLOWED);
+		return;
+	}
+
+	if (kill_confirm_pid == sel->pid &&
+	    (int)(now - kill_confirm_until) < 0) {
+		s_copy(label, sizeof(label), "Confirm end task");
+	} else {
+		s_copy(label, sizeof(label), "End task");
+	}
+	if (ngui_button(u, ID_KILL, br, label) == 1) {
+		if (kill_confirm_pid == sel->pid &&
+		    (int)(now - kill_confirm_until) < 0) {
+			if (u_kill(sel->pid) == 0) {
+				char sb[64];
+				unsigned int sn = 0;
+
+				sb[0] = '\0';
+				s_append(sb, &sn, "Ended ", sizeof(sb));
+				s_append(sb, &sn, sel->name, sizeof(sb));
+				s_append(sb, &sn, " (pid ", sizeof(sb));
+				s_append_uint(sb, &sn, sel->pid, sizeof(sb));
+				s_append_ch(sb, &sn, ')', sizeof(sb));
+				s_copy(status_msg, sizeof(status_msg), sb);
+				status_error = 0;
+				status_until = now + 4000u;
+				selected_pid = 0;
+			} else {
+				s_copy(status_msg, sizeof(status_msg),
+				       "Could not end that process");
+				status_error = 1;
+				status_until = now + 4000u;
+			}
+			kill_confirm_pid = 0;
+		} else {
+			kill_confirm_pid = sel->pid;
+			kill_confirm_until = now + 3000u;
+			s_copy(status_msg, sizeof(status_msg),
+			       "Press End task again to confirm");
+			status_error = 1;
+			status_until = now + 3000u;
+		}
+		ngui_invalidate(u);
+	}
+}
+
+static void draw_footer(struct ngui *u, struct ngui_rect r)
+{
+	struct ngui_rect text = r;
+	char line[192];
+	struct prow *sel = selected_row();
+
+	text.x += 2;
+	text.w -= 4;
+	fill_rect_(u, r.x, r.y, r.w, r.h, u->theme.panel);
+	if (status_until && (int)(u_ticks_ms() - status_until) < 0) {
+		ngui_text_ellipsis(u, text, text.x, text.y + 3, status_msg,
+				   status_error ? u->theme.warning :
+				   u->theme.success);
+		return;
+	}
+	if (sel) {
+		unsigned int n = 0;
+		char pct[16], mem[16], span[16];
+
+		fmt_pct(pct, sizeof(pct), sel->cpu_pm);
+		fmt_kb(mem, sizeof(mem), sel->pages * page_kb);
+		fmt_span(span, sizeof(span), sel->cpu_ticks);
+		line[0] = '\0';
+		s_append(line, &n, "pid ", sizeof(line));
+		s_append_uint(line, &n, sel->pid, sizeof(line));
+		s_append(line, &n, "  ", sizeof(line));
+		s_append(line, &n, sel->name, sizeof(line));
+		s_append(line, &n, "  ", sizeof(line));
+		s_append(line, &n, state_name(sel->state), sizeof(line));
+		s_append(line, &n, sel->kernel ? " (kernel thread)" : "",
+			 sizeof(line));
+		s_append(line, &n, "  cpu ", sizeof(line));
+		s_append(line, &n, pct, sizeof(line));
+		s_append(line, &n, "  mem ", sizeof(line));
+		s_append(line, &n, mem, sizeof(line));
+		s_append(line, &n, "  weight ", sizeof(line));
+		s_append_uint(line, &n, sel->weight, sizeof(line));
+		s_append(line, &n, "  time ", sizeof(line));
+		s_append(line, &n, span, sizeof(line));
+		ngui_text_ellipsis(u, text, text.x, text.y + 3, line,
+				   u->theme.text);
+	} else {
+		ngui_text_ellipsis(u, text, text.x, text.y + 3,
+				   "Click a header to sort  |  PgUp/PgDn scroll  |  Esc close",
+				   u->theme.text_dim);
+	}
+}
+
+static void draw_header(struct ngui *u, struct ngui_rect r)
+{
+	struct ngui_rect text = r;
+	unsigned int uptime = u_ticks_ms() / 1000u;
+	char up[24], line[128];
+	unsigned int n = 0;
+
+	fmt_uptime(up, sizeof(up), uptime);
+	line[0] = '\0';
+	s_append(line, &n, "up ", sizeof(line));
+	s_append(line, &n, up, sizeof(line));
+	s_append(line, &n, "   |   ", sizeof(line));
+	s_append_uint(line, &n, ntotal, sizeof(line));
+	s_append(line, &n, ntotal == 1 ? " process" : " processes",
+		 sizeof(line));
+	if (ncpus) {
+		s_append(line, &n, "   |   ", sizeof(line));
+		s_append_uint(line, &n, ncpus, sizeof(line));
+		s_append(line, &n, ncpus == 1 ? " CPU" : " CPUs", sizeof(line));
+	}
+	s_append(line, &n, "   |   runnable ", sizeof(line));
+	s_append_uint(line, &n, runnable, sizeof(line));
+	if (r.w > 560) {
+		text.w -= 100;
+		text_right(u, r.x + r.w, r.y, "1 s sample", u->theme.text_dim);
+	}
+	ngui_text_ellipsis(u, text, r.x, r.y, line, u->theme.text);
+}
+
+static void draw_graphs(struct ngui *u, int x, int y, int w, int h)
+{
+	int cw = (w - 2 * GAP) / 3;
+	int cw2 = w - 2 * (cw + GAP);
+	struct ngui_rect r;
+
+	r.x = x;
+	r.y = y;
+	r.w = cw;
+	r.h = h;
+	draw_cpu_card(u, r);
+	r.x = x + cw + GAP;
+	r.w = cw;
+	draw_mem_card(u, r);
+	r.x = x + 2 * (cw + GAP);
+	r.w = cw2;
+	draw_net_card(u, r);
+}
+
+static void draw(void)
+{
+	struct ngui_rect r;
+	int y, card_h, table_y, table_h;
+
+	fill_rect_(&ui, 0, 0, ui.w, ui.h, ui.theme.bg);
+
+	y = PAD;
+	r.x = PAD;
+	r.y = y;
+	r.w = ui.w - 2 * PAD;
+	r.h = HEAD_H;
+	draw_header(&ui, r);
+	y += HEAD_H;
+
+	card_h = ui.h < 470 ? 104 : 132;
+	if (ui.h < 390)
+		card_h = 84;
+	draw_graphs(&ui, PAD, y, ui.w - 2 * PAD, card_h);
+	y += card_h + 8;
+
+	r.x = PAD;
+	r.y = y;
+	r.w = ui.w - 2 * PAD;
+	r.h = 24;
+	draw_kill_button(&ui, r);
+	y += 28;
+
+	r.x = PAD;
+	r.y = y;
+	r.w = ui.w - 2 * PAD;
+	r.h = TABLE_HEAD;
+	draw_table_header(&ui, r);
+	y += TABLE_HEAD;
+
+	table_y = y;
+	table_h = ui.h - FOOTER_H - table_y - PAD / 2;
+	if (table_h < ROW_H)
+		table_h = ROW_H;
+	{
+		struct ngui_rect list;
+
+		list.x = PAD;
+		list.y = table_y;
+		list.w = ui.w - 2 * PAD;
+		list.h = table_h;
+		draw_table(&ui, list);
+	}
+
+	r.x = PAD;
+	r.y = ui.h - FOOTER_H;
+	r.w = ui.w - 2 * PAD;
+	r.h = FOOTER_H;
+	draw_footer(&ui, r);
+}
+
+/* ---- lifecycle ---- */
+
+static void clear_status(void)
+{
+	status_msg[0] = '\0';
+	status_until = 0;
+	status_error = 0;
+	kill_confirm_pid = 0;
+}
+
+static void tick_timers(void)
+{
+	unsigned int now = u_ticks_ms();
+
+	if (kill_confirm_pid && (int)(now - kill_confirm_until) >= 0) {
+		kill_confirm_pid = 0;
+		if (status_until && (int)(now - status_until) < 0)
+			clear_status();
+		ngui_invalidate(&ui);
+	}
+	if (status_until && (int)(now - status_until) >= 0) {
+		clear_status();
+		ngui_invalidate(&ui);
+	}
+}
+
+static void move_selection(int step)
+{
+	int sel = -1;
+	unsigned int j;
+
+	for (j = 0; j < nrows; j++)
+		if (rows[j].pid == selected_pid) {
+			sel = (int)j;
+			break;
+		}
+	if (sel < 0)
+		sel = step > 0 ? -1 : (int)nrows;
+	sel += step;
+	if (sel < 0)
+		sel = 0;
+	if ((unsigned int)sel >= nrows)
+		sel = nrows ? (int)nrows - 1 : 0;
+	if (!nrows)
+		return;
+	selected_pid = rows[sel].pid;
+	kill_confirm_pid = 0;
+	ngui_scroll_ensure_visible(&table_scroll, sel * ROW_H, ROW_H);
+	ngui_invalidate(&ui);
+}
+
+void _start(const char *arg)
+{
+	struct win_info wi;
+	struct sys_schedinfo s;
+	struct sys_meminfo m;
+	struct sys_netinfo ni;
+	unsigned int sw = 0, sh = 0;
+	unsigned int w = 780, h = 560;
+	unsigned int i, ncur;
+
+	(void)arg;
+	if (u_screen_size(&sw, &sh) == 0) {
+		if (sw && w > sw - 30)
+			w = sw - 30;
+		if (sh && h > sh - 40)
+			h = sh - 40;
+	}
+	if (w < 260)
+		w = 260;
+	if (h < 260)
+		h = 260;
+	if (u_win_create(w, h, "Processes", &wi) != 0) {
+		u_puts("process: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
+	table_scroll.hide_bar = 0;
+
+	own_pid = (unsigned int)u_getpid();
+	u_syscall1(SYS_MEMINFO, (int)&m);
+	if (m.page_size >= 1024)
+		page_kb = m.page_size / 1024;
+	mem_total_kb = m.total_kb;
+	{
+		unsigned int free_kb = m.free_pages * (m.page_size / 1024);
+
+		mem_used_kb = mem_total_kb > free_kb ?
+			mem_total_kb - free_kb : 0;
+		mem_used_pm = mem_total_kb ?
+			mem_used_kb * 1000u / mem_total_kb : 0;
+		if (mem_used_pm > 1000u)
+			mem_used_pm = 1000u;
+	}
+	for (i = 0; i < PMAX; i++)
+		prev_info[i].name[0] = '\0';
+	nprev = 0;
+	ncur = snapshot_procs(pinfo);
+	for (i = 0; i < ncur; i++)
+		prev_info[i] = pinfo[i];
+	nprev = ncur;
+	build_rows(prev_info, nprev, 1, 0);
+
+	if (u_schedinfo(&s) == 0) {
+		last_idle_ticks = s.idle_ticks;
+		ncpus = s.ncpus;
+		runnable = s.runnable;
+	}
+	if (u_net_info(&ni) == 1 && ni.present) {
+		net_present = 1;
+		net_have_base = 1;
+		last_net_rx = ni.rx_bytes;
+		last_net_tx = ni.tx_bytes;
+	}
+	last_sample_ms = u_ticks_ms();
+
+	for (;;) {
+		int quit = 0;
+
+		tick_timers();
+		if ((int)(u_ticks_ms() - last_sample_ms) >= SAMPLE_MS) {
+			sample();
+			ngui_invalidate(&ui);
+		}
+		if (!ngui_begin(&ui)) {
+			ngui_end_ex(&ui, 0);
+			u_sleep_ms(LOOP_MS);
+			continue;
+		}
+		{
+			int k;
+
+			/* Drain the key ring: a key left at the head would wedge
+			 * every later one and eventually fill the 32-entry ring. */
+			while ((k = ngui_key(&ui)) != 0) {
+				if (k == NGUI_KEY_ESC) {
+					quit = 1;
+					break;
+				}
+				if (k == NGUI_KEY_UP)
+					move_selection(-1);
+				else if (k == NGUI_KEY_DOWN)
+					move_selection(1);
+				else if (k == NGUI_KEY_PAGE_UP)
+					page_req--;
+				else if (k == NGUI_KEY_PAGE_DOWN)
+					page_req++;
+			}
+		}
+		draw();
+		ngui_end(&ui);
+		if (quit)
+			break;
+		u_sleep_ms(LOOP_MS);
+	}
+	u_win_close();
+	u_exit(0);
+}