Browse Source

Add a top command with per-process CPU and memory hints

top is a ring-3 command (bin/top) that paints a live process list in the
calling terminal and refreshes it in place once per second until Ctrl+C:
PID, STATE, CPU% (recent), TIME (lifetime CPU), MEM and NAME, with an
uptime/memory header and a legend for the wm idle-loop row.

Kernel side:
- struct process gains cpu_ticks/start_ticks; the PIT stub credits every
  tick to the interrupted process (PCB_SIZE 108 -> 116).  A _Static_assert
  in process.c keeps the switch.S offsets from drifting.
- SYS_PROCINFO enumerates live processes (pid/state/ticks/name + resident
  pages: kernel stack, page directory and a read-only page-table walk over
  the user range), SYS_GET_CURSOR/SYS_SET_CURSOR expose the caller's screen
  cursor for the in-place repaint.

Command side (ucmd_top.c, ucmd_lib.h):
- Each frame samples the tick counters twice, one second apart; CPU% is the
  share of that window (wm also shows idle/hlt time, noted in the footer)
  and TIME is the lifetime total.  MEM is pages * 4 KB.
- The frame has a fixed shape (23 rows x 63 columns + newlines) and repaints
  behind a scroll-corrected anchor (cursor - frame length), so stale text is
  erased and starting top on the bottom row stays put.

Verified on QEMU: frames refresh in place, Tab completes "to" -> "top",
Ctrl+C returns to the prompt, a start at the bottom row lands correctly,
and make test-usb (cursor + keyboard, including hotplug) stays green.

AGENTS.md: command list + multitasking bullet.
Johannes Zellner 1 tháng trước cách đây
mục cha
commit
5a348f6889
9 tập tin đã thay đổi với 455 bổ sung và 5 xóa
  1. 5 3
      AGENTS.md
  2. 1 1
      Makefile
  3. 72 0
      process.c
  4. 10 0
      process.h
  5. 8 1
      switch.S
  6. 8 0
      syscall.c
  7. 17 0
      syscall.h
  8. 12 0
      ucmd_lib.h
  9. 322 0
      ucmd_top.c

+ 5 - 3
AGENTS.md

@@ -67,7 +67,9 @@ below the run area), so adding code no longer moves any address.
   `ps`/`kill`. Context switch happens in the PIT stub. Each process carries a
   `ps`/`kill`. Context switch happens in the PIT stub. Each process carries a
   `struct text_screen *screen` output target (child processes inherit it, so
   `struct text_screen *screen` output target (child processes inherit it, so
   command output lands in the owning terminal). Exited processes are reaped and
   command output lands in the owning terminal). Exited processes are reaped and
-  their stacks freed by the scheduler.
+  their stacks freed by the scheduler. The PIT stub also credits every tick to
+  the running process (`cpu_ticks`/`start_ticks`; `process_procinfo()`, exposed
+  as `SYS_PROCINFO`), which the ring-3 `top` command turns into a live CPU%.
 - **Memory**: `mm.c/h` — INT 15h E820 detection (real-mode in `vesa_stage.S`,
 - **Memory**: `mm.c/h` — INT 15h E820 detection (real-mode in `vesa_stage.S`,
   map at `0x1000`) + a bitmap page-frame allocator (4 KB pages). Reserves low
   map at `0x1000`) + a bitmap page-frame allocator (4 KB pages). Reserves low
   1 MB and an 8 MB VGA-shadow region. `kmalloc.c/h` — a power-of-two heap
   1 MB and an 8 MB VGA-shadow region. `kmalloc.c/h` — a power-of-two heap
@@ -226,7 +228,7 @@ below the run area), so adding code no longer moves any address.
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `prog`,
 `prog`,
-`clock`, `colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `format <device>`,
+`clock`, `colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `format <device>`,
 `ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
 `ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
 
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
@@ -254,7 +256,7 @@ changed with `cd`; paths may be absolute (`/floppy1/…`) or relative (`.`, `..`
 nested). `/` is the read-only VFS root listing the mounted filesystems (the
 nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 
-`cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`,
+`cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`,
 `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `curl` and `hello` are files in `/ramfs/bin` (packed by the
 `netreset`, `curl` and `hello` are files in `/ramfs/bin` (packed by the

+ 1 - 1
Makefile

@@ -333,7 +333,7 @@ prog: prog.bin
 # mounted at /ramfs/bin (the shell's PATH default).  New command: add
 # mounted at /ramfs/bin (the shell's PATH default).  New command: add
 # ucmd_<name>.c to UCMDS; the pack is rebuilt automatically.
 # ucmd_<name>.c to UCMDS; the pack is rebuilt automatically.
 UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
 UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
-        ucmd_meminfo ucmd_mouseinfo ucmd_storage \
+        ucmd_meminfo ucmd_mouseinfo ucmd_storage ucmd_top \
         ucmd_netinfo ucmd_netip ucmd_netdns ucmd_host ucmd_dhcp \
         ucmd_netinfo ucmd_netip ucmd_netdns ucmd_host ucmd_dhcp \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_curl
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_curl

+ 72 - 0
process.c

@@ -10,6 +10,7 @@
 #include "serial.h"
 #include "serial.h"
 #include "sys_fs.h"
 #include "sys_fs.h"
 #include "sys_net.h"
 #include "sys_net.h"
+#include "syscall.h"
 #include "timer.h"
 #include "timer.h"
 
 
 struct process *procs;               /* dynamically-sized process table */
 struct process *procs;               /* dynamically-sized process table */
@@ -24,6 +25,11 @@ extern char __boot_stack_top[];
 
 
 #define INITIAL_PROC_CAP 16
 #define INITIAL_PROC_CAP 16
 
 
+/* switch.S addresses the table entries with an immediate PCB_SIZE/PCB_CPU_TICKS
+ * and cannot see this struct; keep the two in sync. */
+_Static_assert(sizeof(struct process) == 116,
+	       "struct process layout changed: update PCB_SIZE/PCB_CPU_TICKS in switch.S");
+
 /* ---- interrupt flag save/restore (for short critical sections) ---- */
 /* ---- interrupt flag save/restore (for short critical sections) ---- */
 static inline unsigned int irq_save_disable(void)
 static inline unsigned int irq_save_disable(void)
 {
 {
@@ -140,6 +146,8 @@ void process_init(void)
 	procs[0].stack_base = 0;  /* bootstrap stack, never freed */
 	procs[0].stack_base = 0;  /* bootstrap stack, never freed */
 	procs[0].cr3        = paging_current_cr3();
 	procs[0].cr3        = paging_current_cr3();
 	procs[0].kstack_top = (unsigned int)__boot_stack_top;
 	procs[0].kstack_top = (unsigned int)__boot_stack_top;
+	procs[0].cpu_ticks  = 0;
+	procs[0].start_ticks = 0;  /* the WM "starts" at boot */
 	name_copy(procs[0].name, "wm");
 	name_copy(procs[0].name, "wm");
 	current_pid = 0;
 	current_pid = 0;
 }
 }
@@ -228,6 +236,8 @@ static int setup_process(const char *name, unsigned int entry,
 	procs[slot].stack_base = owned ? base : 0;
 	procs[slot].stack_base = owned ? base : 0;
 	procs[slot].cr3        = cr3;
 	procs[slot].cr3        = cr3;
 	procs[slot].kstack_top = top;
 	procs[slot].kstack_top = top;
+	procs[slot].cpu_ticks  = 0;
+	procs[slot].start_ticks = get_ticks_ms();
 	name_copy(procs[slot].name, name);
 	name_copy(procs[slot].name, name);
 	/* Child inherits the parent's output screen (command output lands in the
 	/* Child inherits the parent's output screen (command output lands in the
 	   terminal that spawned it). */
 	   terminal that spawned it). */
@@ -292,6 +302,8 @@ int process_create_ptr(const char *name, void (*entry)(void *), void *arg)
 	procs[slot].stack_base = owned ? base : 0;
 	procs[slot].stack_base = owned ? base : 0;
 	procs[slot].cr3        = cr3;
 	procs[slot].cr3        = cr3;
 	procs[slot].kstack_top = top;
 	procs[slot].kstack_top = top;
+	procs[slot].cpu_ticks  = 0;
+	procs[slot].start_ticks = get_ticks_ms();
 	name_copy(procs[slot].name, name);
 	name_copy(procs[slot].name, name);
 	procs[slot].screen = procs[current_pid].screen;
 	procs[slot].screen = procs[current_pid].screen;
 	irq_restore(flags);
 	irq_restore(flags);
@@ -402,6 +414,8 @@ int process_create_user(const char *name, const void *image, unsigned int size,
 	procs[slot].stack_base = owned ? base : 0;
 	procs[slot].stack_base = owned ? base : 0;
 	procs[slot].cr3        = cr3;
 	procs[slot].cr3        = cr3;
 	procs[slot].kstack_top = top;
 	procs[slot].kstack_top = top;
+	procs[slot].cpu_ticks  = 0;
+	procs[slot].start_ticks = get_ticks_ms();
 	name_copy(procs[slot].name, name);
 	name_copy(procs[slot].name, name);
 	procs[slot].screen = procs[current_pid].screen;
 	procs[slot].screen = procs[current_pid].screen;
 	{
 	{
@@ -555,6 +569,64 @@ void process_ps(void)
 	}
 	}
 }
 }
 
 
+/* Count the 4 KB user pages mapped between USER_BASE and USER_STACK_TOP.
+ * A read-only page-directory walk (paging keeps everything identity-mapped,
+ * so the tables are directly addressable).  Used by `top` for the memory
+ * hint; ring-3 processes currently leak these pages on reap (known issue),
+ * but ex-processes are gone from the table by then anyway. */
+static unsigned int count_user_pages(unsigned int cr3)
+{
+	const unsigned int *pd;
+	unsigned int i, pages = 0;
+
+	if (!cr3)
+		return 0;
+	pd = (const unsigned int *)cr3;
+	for (i = USER_BASE >> 22; i <= (USER_STACK_TOP - 1) >> 22; i++) {
+		unsigned int pde = pd[i];
+		const unsigned int *pt;
+
+		if (!(pde & PTE_PRESENT) || (pde & 0x80))  /* 0x80: 4 MB page */
+			continue;
+		pt = (const unsigned int *)(pde & 0xFFFFF000u);
+		{
+			unsigned int j;
+			for (j = 0; j < 1024; j++)
+				if (pt[j] & PTE_PRESENT)
+					pages++;
+		}
+	}
+	return pages;
+}
+
+/* Snapshot of the index-th live process, for the `top` syscall.  Indexes over
+ * live processes in slot order, so callers iterate 0, 1, ... until 0. */
+int process_procinfo(unsigned int index, struct sys_procinfo *out)
+{
+	unsigned int i, seen = 0, life;
+
+	if (!out)
+		return 0;
+	for (i = 0; i < proc_cap; i++) {
+		if (procs[i].state == PROC_UNUSED || procs[i].state == PROC_DEAD)
+			continue;
+		if (seen++ != index)
+			continue;
+
+		life = get_ticks_ms() - procs[i].start_ticks;
+		out->pid        = procs[i].pid;
+		out->state      = procs[i].state;
+		out->cpu_ticks  = procs[i].cpu_ticks;
+		out->life_ticks = life ? life : 1;
+		/* Kernel stack page + page directory + user pages (the WM shares
+		 * the kernel directory; counting one is close enough). */
+		out->pages      = 2 + count_user_pages(procs[i].cr3);
+		name_copy(out->name, procs[i].name);
+		return 1;
+	}
+	return 0;
+}
+
 int process_kill(unsigned int pid)
 int process_kill(unsigned int pid)
 {
 {
 	unsigned int i;
 	unsigned int i;

+ 10 - 0
process.h

@@ -21,6 +21,7 @@
 #define PROC_CWD_MAX  64
 #define PROC_CWD_MAX  64
 
 
 struct text_screen;  /* forward decl (see screen.h) */
 struct text_screen;  /* forward decl (see screen.h) */
+struct sys_procinfo; /* forward decl (see syscall.h; `top` snapshot) */
 
 
 struct process {
 struct process {
 	unsigned int esp;
 	unsigned int esp;
@@ -33,6 +34,11 @@ struct process {
 	unsigned int kstack_top;     /* ring-0 stack top (for TSS esp0) */
 	unsigned int kstack_top;     /* ring-0 stack top (for TSS esp0) */
 	unsigned int wake_ms;        /* tick deadline when PROC_SLEEPING */
 	unsigned int wake_ms;        /* tick deadline when PROC_SLEEPING */
 	char cwd[PROC_CWD_MAX];      /* working directory (ring-3 commands) */
 	char cwd[PROC_CWD_MAX];      /* working directory (ring-3 commands) */
+	/* CPU accounting for `top`.  switch.S credits the running process on
+	 * every PIT tick, so the layout after cwd must match PCB_CPU_TICKS /
+	 * PCB_SIZE there (see the _Static_assert in process.c). */
+	unsigned int cpu_ticks;      /* ticks spent as the running process */
+	unsigned int start_ticks;    /* get_ticks_ms() at creation */
 };
 };
 
 
 /* User-mode virtual address layout (ring-3 processes). */
 /* User-mode virtual address layout (ring-3 processes). */
@@ -66,6 +72,10 @@ void process_map_mmio_all(unsigned int phys_base, unsigned int size);
 void process_exit(void);
 void process_exit(void);
 void schedule(void);
 void schedule(void);
 void process_ps(void);
 void process_ps(void);
+
+/* Fill *out with a snapshot of the index-th live process (slot order) for
+ * the `top` command.  Returns 1 when found, 0 at the end of the table. */
+int  process_procinfo(unsigned int index, struct sys_procinfo *out);
 int  process_kill(unsigned int pid);
 int  process_kill(unsigned int pid);
 int  process_is_alive(unsigned int pid);
 int  process_is_alive(unsigned int pid);
 void process_wait(unsigned int pid);
 void process_wait(unsigned int pid);

+ 8 - 1
switch.S

@@ -30,7 +30,8 @@
 .equ PCB_ESP,   0
 .equ PCB_ESP,   0
 .equ PCB_CR3,   32
 .equ PCB_CR3,   32
 .equ PCB_KSTACK_TOP, 36
 .equ PCB_KSTACK_TOP, 36
-.equ PCB_SIZE,  108     /* sizeof(struct process): 44 + cwd[64] */
+.equ PCB_CPU_TICKS, 108  /* after cwd[64] */
+.equ PCB_SIZE,  116     /* sizeof(struct process): 44 + cwd[64] + 2*4 */
 
 
 .equ TIMESLICE, 20
 .equ TIMESLICE, 20
 .equ FLUSH_INTERVAL, 33 /* 1000Hz PIT / 30Hz flush ≈ 33 ticks */
 .equ FLUSH_INTERVAL, 33 /* 1000Hz PIT / 30Hz flush ≈ 33 ticks */
@@ -54,6 +55,12 @@ pit_irq_stub:
 	movb  $0x20, %al
 	movb  $0x20, %al
 	outb  %al, $0x20
 	outb  %al, $0x20
 
 
+	/* Account this tick to the process that was interrupted (for `top`). */
+	movl  current_pid, %eax
+	imull $PCB_SIZE, %eax
+	addl  procs, %eax
+	incl  PCB_CPU_TICKS(%eax)
+
 	/* Poll UART for received serial data (prevents FIFO overflow). */
 	/* Poll UART for received serial data (prevents FIFO overflow). */
 	call  serial_poll
 	call  serial_poll
 
 

+ 8 - 0
syscall.c

@@ -135,6 +135,14 @@ int syscall_dispatch(int num, int a1, int a2, int a3)
 		out[i] = '\0';
 		out[i] = '\0';
 		return 0;
 		return 0;
 	}
 	}
+	case SYS_PROCINFO:
+		return process_procinfo((unsigned int)a1,
+					(struct sys_procinfo *)a2);
+	case SYS_GET_CURSOR:
+		return (int)io_get_cursor();
+	case SYS_SET_CURSOR:
+		io_set_cursor((unsigned int)a1);
+		return 0;
 	default:
 	default:
 		return -1;
 		return -1;
 	}
 	}

+ 17 - 0
syscall.h

@@ -69,6 +69,12 @@
 #define SYS_NET_CONFIGURED 47 /* () -> 1 when an IP address is set */
 #define SYS_NET_CONFIGURED 47 /* () -> 1 when an IP address is set */
 #define SYS_GETCWD       48  /* (char *buf, unsigned max) -> 0; the caller's cwd */
 #define SYS_GETCWD       48  /* (char *buf, unsigned max) -> 0; the caller's cwd */
 
 
+/* Process snapshot for the `top` command (see process.c). */
+#define SYS_PROCINFO     49  /* (unsigned int index, struct sys_procinfo *out)
+				-> 1 when found, 0 at the end of the table */
+#define SYS_GET_CURSOR   50  /* () -> cursor position of the caller's screen */
+#define SYS_SET_CURSOR   51  /* (unsigned int pos) -> 0 */
+
 struct sys_netinfo {
 struct sys_netinfo {
 	unsigned int present;
 	unsigned int present;
 	unsigned char mac[6];
 	unsigned char mac[6];
@@ -113,6 +119,17 @@ struct sys_meminfo {
 	unsigned int e820_count;
 	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. */
+struct sys_procinfo {
+	unsigned int pid;
+	unsigned int state;       /* PROC_*: 1 ready, 2 running, 4 sleeping */
+	unsigned int cpu_ticks;   /* ticks spent as the running process */
+	unsigned int life_ticks;  /* ticks since creation, >= 1 */
+	unsigned int pages;       /* resident 4 KB pages (stack + dir + user) */
+	char name[12];
+};
+
 struct sys_e820 {
 struct sys_e820 {
 	unsigned int base;      /* low 32 bits, as meminfo always printed */
 	unsigned int base;      /* low 32 bits, as meminfo always printed */
 	unsigned int length;
 	unsigned int length;

+ 12 - 0
ucmd_lib.h

@@ -157,6 +157,18 @@ static inline unsigned int u_ticks_ms(void)
 	return (unsigned int)u_syscall0(SYS_GET_TICKS_MS);
 	return (unsigned int)u_syscall0(SYS_GET_TICKS_MS);
 }
 }
 
 
+/* Cursor position of this process's terminal screen (linear cell index);
+ * used by `top` to repaint its frame in place. */
+static inline unsigned int u_get_cursor(void)
+{
+	return (unsigned int)u_syscall0(SYS_GET_CURSOR);
+}
+
+static inline void u_set_cursor(unsigned int pos)
+{
+	u_syscall1(SYS_SET_CURSOR, (int)pos);
+}
+
 static inline void u_sleep_ms(unsigned int ms)
 static inline void u_sleep_ms(unsigned int ms)
 {
 {
 	u_syscall1(SYS_SLEEP_MS, (int)ms);
 	u_syscall1(SYS_SLEEP_MS, (int)ms);

+ 322 - 0
ucmd_top.c

@@ -0,0 +1,322 @@
+/* top: ring-3 command.  Live process list with recent CPU and memory hints.
+ *
+ * The kernel credits every PIT tick to the process that was running it
+ * (SYS_PROCINFO exposes the counters), so each frame samples the counters
+ * twice, one second apart: CPU% is the share of ticks in that window.  The
+ * WM slot ("wm") runs the idle loop, so on an idle system it owns nearly
+ * every tick -- the footer says as much.
+ *
+ * The frame is repainted in place.  It has a fixed shape (23 rows x 63
+ * columns + newlines), so the number of characters written per frame is a
+ * constant; after the first paint the anchor is recomputed as
+ * (cursor - FRAME_CHARS), which also corrects a scroll when the first frame
+ * starts near the bottom of the screen.  Every row is padded to 63 columns,
+ * so stale text from a previous frame is erased, and the last row is written
+ * without a trailing newline so a frame that ends on the bottom row cannot
+ * scroll.  Ctrl+C quits: the terminal kills its foreground command.
+ */
+
+#include "ucmd_lib.h"
+
+#define FRAME_COLS  63            /* terminal screens are 64x32 (kernel screen.h) */
+#define COL_PID     4
+#define COL_STATE   7
+#define COL_CPU     6
+#define COL_TIME    6
+#define COL_MEM     6
+/* five single-space separators between the six columns */
+#define NAME_W      (FRAME_COLS - COL_PID - COL_STATE - COL_CPU - COL_TIME - COL_MEM - 5)
+#define PRINT_ROWS  20            /* process rows (header + footer excluded) */
+#define MAX_SAMPLE  32            /* processes captured per sample */
+#define FRAME_ROWS  (3 + PRINT_ROWS)
+#define FRAME_CHARS (FRAME_ROWS * 64 - 1)  /* 63 chars + '\n' per row, no final '\n' */
+
+/* CPUs ticks before the sampling window, matched by pid. */
+struct sample {
+	unsigned int pid;
+	unsigned int cpu_ticks;
+};
+
+static struct sample before[MAX_SAMPLE];
+static unsigned int nbefore;
+
+struct prow {
+	unsigned int pid;
+	unsigned int state;
+	unsigned int cpu_pm;     /* CPU per mille over the window */
+	unsigned int cpu_ticks;  /* total ticks spent running */
+	unsigned int pages;      /* resident pages */
+	char name[12];
+};
+
+static struct prow rows[PRINT_ROWS];
+static unsigned int nrows, ntotal;
+static unsigned int wall;                 /* sample window, ms */
+static unsigned int uptime_s;
+static unsigned int free_kb, total_kb;
+static unsigned int line_chars;           /* chars written into the current row */
+
+static void putc_(char c)
+{
+	u_putc(c);
+	line_chars++;
+}
+
+static void puts_(const char *s)
+{
+	while (*s)
+		putc_(*s++);
+}
+
+static void dec_(unsigned int v)
+{
+	char buf[10];
+	unsigned int n = 0;
+
+	if (v == 0)
+		buf[n++] = '0';
+	while (v) {
+		buf[n++] = (char)('0' + v % 10);
+		v /= 10;
+	}
+	while (n)
+		putc_(buf[--n]);
+}
+
+static void pad_(unsigned int n)
+{
+	while (n--)
+		putc_(' ');
+}
+
+/* Right-aligned decimal in `width` columns. */
+static void dec_w(unsigned int v, unsigned int width)
+{
+	unsigned int digits = 1, t = v;
+
+	while (t >= 10) {
+		t /= 10;
+		digits++;
+	}
+	if (digits < width)
+		pad_(width - digits);
+	dec_(v);
+}
+
+/* Left-aligned string, truncated/padded to exactly `width` columns. */
+static void str_w(const char *s, unsigned int width)
+{
+	unsigned int n = 0;
+
+	while (s[n] && n < width)
+		putc_(s[n++]);
+	if (n < width)
+		pad_(width - n);
+}
+
+/* Right-aligned string (for the column headers, to sit over right-aligned
+ * numbers). */
+static void str_wr(const char *s, unsigned int width)
+{
+	unsigned int n = 0, i;
+
+	while (s[n])
+		n++;
+	if (n < width)
+		pad_(width - n);
+	for (i = 0; i < n; i++)
+		putc_(s[i]);
+}
+
+/* Right-aligned "x.y%" in COL_CPU columns. */
+static void cpu_w(unsigned int per_mille)
+{
+	unsigned int whole = per_mille / 10;
+	unsigned int tenth = per_mille % 10;
+	unsigned int digits = 1, t = whole;
+
+	while (t >= 10) {
+		t /= 10;
+		digits++;
+	}
+	pad_(COL_CPU - (digits + 3));
+	dec_(whole);
+	putc_('.');
+	putc_((char)('0' + tenth));
+	putc_('%');
+}
+
+static const char *state_name(unsigned int s)
+{
+	if (s == 2)
+		return "run";
+	if (s == 1)
+		return "ready";
+	if (s == 4)
+		return "sleep";
+	return "?";
+}
+
+/* Pad the current row to full width; rows other than the last end with a
+ * newline, which combined with the padding keeps every frame the same size. */
+static void end_line(int last)
+{
+	while (line_chars < FRAME_COLS)
+		putc_(' ');
+	if (!last) {
+		u_putc('\n');
+		line_chars = 0;
+	}
+}
+
+/* Take the "after" sample and turn it into rows, CPU% = ticks during the
+ * window (a process that appeared during the window shows 0%). */
+static void gather(void)
+{
+	struct sys_procinfo p;
+	unsigned int i, j;
+
+	ntotal = 0;
+	nrows = 0;
+	for (i = 0; ; i++) {
+		if (u_syscall2(SYS_PROCINFO, (int)i, (int)&p) != 1)
+			break;
+		if (ntotal < PRINT_ROWS) {
+			struct prow *r = &rows[ntotal];
+			unsigned int delta = 0, pm = 0;
+
+			for (j = 0; j < nbefore; j++)
+				if (before[j].pid == p.pid) {
+					delta = p.cpu_ticks - before[j].cpu_ticks;
+					break;
+				}
+			if (j < nbefore) {
+				pm = delta * 1000u / wall;
+				if (pm > 1000u)
+					pm = 1000u;
+			}
+			r->pid = p.pid;
+			r->state = p.state;
+			r->cpu_pm = pm;
+			r->cpu_ticks = p.cpu_ticks;
+			r->pages = p.pages;
+			for (j = 0; j < sizeof(r->name); j++)
+				r->name[j] = p.name[j];
+			nrows++;
+		}
+		ntotal++;
+	}
+}
+
+static void paint(void)
+{
+	unsigned int i;
+
+	line_chars = 0;
+
+	/* status line */
+	puts_("top: up ");
+	dec_(uptime_s);
+	puts_("s  ");
+	dec_(ntotal);
+	puts_(ntotal == 1 ? " proc  " : " procs  ");
+	puts_("mem ");
+	dec_(free_kb);
+	puts_("K free / ");
+	dec_(total_kb);
+	puts_("K");
+	end_line(0);
+
+	/* column headers */
+	str_wr("PID", COL_PID);
+	putc_(' ');
+	str_w("STATE", COL_STATE);
+	putc_(' ');
+	str_wr("CPU%", COL_CPU);
+	putc_(' ');
+	str_wr("TIME", COL_TIME);
+	putc_(' ');
+	str_wr("MEM", COL_MEM);
+	putc_(' ');
+	str_w("NAME", NAME_W);
+	end_line(0);
+
+	for (i = 0; i < PRINT_ROWS; i++) {
+		if (i < nrows) {
+			const struct prow *r = &rows[i];
+
+			dec_w(r->pid, COL_PID);
+			putc_(' ');
+			str_w(state_name(r->state), COL_STATE);
+			putc_(' ');
+			cpu_w(r->cpu_pm);
+			putc_(' ');
+			dec_w(r->cpu_ticks / 1000, COL_TIME - 1);
+			putc_('s');
+			putc_(' ');
+			dec_w(r->pages * 4, COL_MEM - 1);
+			putc_('K');
+			putc_(' ');
+			str_w(r->name, NAME_W);
+		}
+		end_line(0);
+	}
+
+	if (ntotal > nrows) {
+		putc_('+');
+		dec_(ntotal - nrows);
+		puts_(" more  ");
+	}
+	puts_("Ctrl+C to quit - wm = idle loop");
+	end_line(1);
+}
+
+static void frame(void)
+{
+	gather();
+	paint();
+}
+
+void _start(const char *arg)
+{
+	struct sys_meminfo m;
+	struct sys_procinfo p;
+	unsigned int i, t0, t1, frame_pos = 0, have_frame = 0;
+
+	(void)arg;
+
+	u_syscall1(SYS_MEMINFO, (int)&m);
+	total_kb = m.total_kb;
+	free_kb = m.free_pages * (m.page_size / 1024);
+
+	for (;;) {
+		/* Sample before the wait, repaint after it. */
+		nbefore = 0;
+		for (i = 0; i < MAX_SAMPLE; i++) {
+			if (u_syscall2(SYS_PROCINFO, (int)i, (int)&p) != 1)
+				break;
+			before[nbefore].pid = p.pid;
+			before[nbefore].cpu_ticks = p.cpu_ticks;
+			nbefore++;
+		}
+		t0 = u_ticks_ms();
+		u_sleep_ms(1000);
+		t1 = u_ticks_ms();
+		wall = t1 - t0;
+		if (!wall)
+			wall = 1;
+		uptime_s = t1 / 1000;
+
+		if (!have_frame)
+			frame_pos = u_get_cursor();  /* the shell left us at a line start */
+		else
+			u_set_cursor(frame_pos);
+		frame();
+		if (!have_frame) {
+			/* If the first frame scrolled the screen, its content moved
+			 * up with it; the cursor tells us where it ended up. */
+			frame_pos = u_get_cursor() - FRAME_CHARS;
+			have_frame = 1;
+		}
+	}
+}