ソースを参照

Move shell commands to ring 3: registry, file syscalls, first commands

The shell's commands were kernel code linked into the image, dispatched
through ~50 hand-written parsers, with `help` and Tab completion as two
more hand-kept lists.  They are ring-3 processes now, and the kernel
keeps only the services they need.

- terminal.c has a table-driven command registry: cmds[] carries name,
  usage, spawn kind and handler and drives dispatch, `help` and Tab
  completion; CMD_USER rows launch an embedded ring-3 ELF, the remaining
  kinds spawn a kernel process and the custom handlers are the builtins
  and inline commands.  The is_cmd_* chain, the help table and the
  duplicated completion list are gone (~1150 lines).
- Ring-3 commands (ucmd_*.c, ucmd_lib.h, ucmd.ld): freestanding ELFs
  linked at USER_BASE, stripped, embedded with ld -r -b binary and
  listed in ucmds[].  One argument is placed as a C string at the top of
  the user stack (process_create_user(..., arg)), so `_start(const char
  *arg)` needs no crt0.  New commands: a ucmd_<name>.c, a CMD_USER row
  and a blob entry.
- File service (syscall.h + sys_fs.c/h): whole-file read/write,
  index-based dir listing, mount listing, unlink/mkdir/rmdir over vfs/fat,
  with an error-code set that keeps the commands' messages.  A FAT
  operation sets sys_fs_busy, which the scheduler honours: the FAT driver
  has static state, and a switch would corrupt it, while the interrupts
  must stay on for the floppy's IRQ.  Cost: a brief stall during I/O.
- Moved: cpuinfo, ls, cat, save, rm, mkdir, rmdir (their kernel .c files
  are deleted; kernel text shrinks ~8.5 KB, the ELFs ship inside the
  image instead).

Verified on QEMU (QMP keyboard + the netconsole mirror): mounts listing,
8.3 listing with sizes, mkdir/new dir/rmdir, save+cat round-trip, rm and
then "not found", relative cwd (`cd /floppy1` + `ls`), cpuinfo; plus the
USB test suite and a serial kexec reload of the (now bigger) image.

AGENTS.md: the registry, ring-3 commands, the file service and the
updated known issues.
Johannes Zellner 1 ヶ月 前
親
コミット
a97c7f5027
24 ファイル変更、1223 行追加、1266 行削除
  1. 38 10
      AGENTS.md
  2. 26 24
      Makefile
  3. 0 65
      cat.c
  4. 0 74
      ls.c
  5. 0 33
      mkdir.c
  6. 74 24
      process.c
  7. 4 2
      process.h
  8. 0 33
      rm.c
  9. 0 33
      rmdir.c
  10. 0 64
      save.c
  11. 254 0
      sys_fs.c
  12. 19 0
      sys_fs.h
  13. 17 3
      syscall.c
  14. 39 1
      syscall.h
  15. 269 840
      terminal.c
  16. 12 0
      ucmd.ld
  17. 52 0
      ucmd_cat.c
  18. 54 60
      ucmd_cpuinfo.c
  19. 108 0
      ucmd_lib.h
  20. 106 0
      ucmd_ls.c
  21. 31 0
      ucmd_mkdir.c
  22. 33 0
      ucmd_rm.c
  23. 31 0
      ucmd_rmdir.c
  24. 56 0
      ucmd_save.c

+ 38 - 10
AGENTS.md

@@ -100,14 +100,21 @@ below the run area), so adding code no longer moves any address.
   heartbeat, boot info rows, exception banner) for machines without serial; see
   the kdbg section below.
 - **Shell**: `terminal.c` — history, line editing (Tab completes command
-  names from the help table and VFS paths via `fat_list_dir`), command
-  dispatch (hand-rolled `is_cmd_*` parsers). Runs in a window (`term_run(struct term *)`); reads keys
-  from its per-terminal queue (filled by the WM).
+  names from the registry table and VFS paths via `fat_list_dir`), and a
+  table-driven command registry (`cmds[]`: name, usage, spawn kind/handler)
+  that drives dispatch, `help` and completion.  Runs in a window
+  (`term_run(struct term *)`); reads keys from its per-terminal queue
+  (filled by the WM).
 - **Filesystem**: `fat.c` (FAT12/16/32 read/write, device-parameterized),
   `vfs.c` (mounts every FAT device under `/`), `fatdetect.c`/`fatformat.c`,
   `blkdev.c` (floppy + IDE + SATA registry), `ata.c` (ATA PIO, either the
   legacy ports or the PCI IDE interface's native BARs — `ata_init_ports()`),
-  `disk.c` (FDC + ISA DMA ch2, retries).
+  `disk.c` (FDC + ISA DMA ch2, retries).  `sys_fs.c` is the file service for
+  ring-3 commands: whole-file read/write, index-based directory listing, mount
+  listing, unlink/mkdir/rmdir.  A FAT operation sets `sys_fs_busy`, which the
+  scheduler honours (no process switch during it): the FAT driver has static
+  state and the floppy still needs its IRQ.  So expect a brief system stall
+  (not ticks — the PIT keeps running) while a command reads or writes a disk.
 - **SATA/AHCI**: `ahci.c/h` — polled AHCI driver (first controller only, PCI
   class `01:06:01`, no IRQs, no NCQ): port bring-up with COMRESET, IDENTIFY
   (shared `ata_identify_parse()` with `ata.c`) and READ/WRITE DMA EXT through
@@ -173,6 +180,18 @@ below the run area), so adding code no longer moves any address.
   from FAT.  Rebuilds are wired (`space.c` -> `space.bin` -> `space_embed.o` ->
   `kernel.elf`).  Note: full-screen programs draw over the WM, which keeps
   repainting its desktop — running them windowed/cleanly is a follow-up.
+- **Ring-3 commands**: `ucmd_*.c`, `ucmd_lib.h`, `ucmd.ld` — freestanding
+  ELFs linked at `USER_BASE` (`0x40000000`), built by the Makefile, embedded
+  in the kernel image (`*_embed.o`) and listed as `CMD_USER` rows in the
+  terminal's command registry (`cmds[]` + `ucmds[]`).  Moved so far:
+  `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`.  They talk to the
+  kernel through `int 0x80` (`syscall.h`: putstr/ticks/sleep/exit plus the
+  whole-file service in `sys_fs.c`) and inherit the terminal's screen, so
+  their output lands in the owning window.  New commands: add `ucmd_<name>.c`,
+  a `CMD_USER` row in `cmds[]`, and a blob in `ucmds[]` (the Makefile picks
+  the file up via its `ucmd_%` pattern rules).  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.
 
 ## Shell commands
 
@@ -207,19 +226,25 @@ 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` and `rmdir` run as ring-3
+processes (embedded `ucmd_*.c`); the rest are kernel commands spawned as
+processes, or shell builtins (`cd`, `clear`, `help`).
+
 ## Serial hot-reload (kexec) workflow
 
 Develop without reflashing the floppy. The serial link (COM1 ↔ `/dev/ttyUSB0`)
 runs at **115200 baud**. Two paths exist:
 
-- **Auto-detect** (the normal loop) — the terminal's idle loop watches the serial
+- **Auto-detect** (the normal loop) — the WM loop watches the serial
   ring buffer for the `"KXEC"` magic and auto-spawns the reload, so `make dev`
   alone boots a fresh kernel. The manual `kexec` command is kept as a fallback
   that waits for the same image.
 - **`bootstrap`** (one-time, zero-reflash) — a ring-0 program loaded through the
   existing `serial recv` + `run serial` path that switches the UART to 115200,
   receives a new kernel, and jumps into it. Used only to install the first new
-  kernel onto a machine still running an old (9600 baud) build.
+  kernel onto a machine still running an old (9600 baud) build; `bootstrap.bin`
+  is linked by `bootstrap.ld` at the *old* program address (`0x4A000`) because
+  that is where the old build's `serial recv` writes it.
 
 Wire protocol (host → target, sent immediately; no handshake):
 `[magic "KXEC"][entry u32 LE][size u32 LE][data][checksum u8]`.
@@ -536,7 +561,10 @@ Caveats:
    color-cycling 32×32 square in the corner on every flush.
 3. No per-process address spaces or process isolation (paging is identity-mapped).
 4. FAT32: FSInfo free-count not updated, no directory-chain growth.
-5. Implicit, hardcoded memory map (see table above).
-6. `disk.c` `fdc_reset()` and `fdc_init_once()` overlap/duplicate logic.
-7. `terminal.c` command dispatch is ~30 near-identical `is_cmd_*` functions;
-   a table-driven parser would reduce this.
+5. `disk.c` `fdc_reset()` and `fdc_init_once()` overlap/duplicate logic.
+6. The ring-0 `run` area (`0x80000`) and the program API at `0x7FF00` are the
+   last fixed low-memory addresses; moving `prog`/`space` to ring-3 would let
+   the whole block go (see the roadmap).
+7. Killing/reaping a ring-3 process frees its kernel stack and page directory
+   but not the user pages mapped into it (a few pages leak per command run;
+   needs a page-table walk/unmap on reap).

+ 26 - 24
Makefile

@@ -56,12 +56,6 @@ disk.o: disk.c disk.h io.h timer.h
 fat.o: fat.c fat.h blkdev.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-ls.o: ls.c fat.h io.h vfs.h
-	$(CC) $(CFLAGS) -o $@ $<
-
-cat.o: cat.c fat.h io.h vfs.h
-	$(CC) $(CFLAGS) -o $@ $<
-
 run.o: run.c fat.h io.h fbtext.h run_api.h timer.h vga.h vfs.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -119,9 +113,6 @@ colors.o: colors.c fbtext.h io.h timer.h vga.h
 display.o: display.c io.h vga.h gpu.h ati.h nvidia.h radeon.h mouse.h fbtext.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-cpuinfo.o: cpuinfo.c io.h timer.h
-	$(CC) $(CFLAGS) -o $@ $<
-
 mousecmd.o: mousecmd.c io.h mouse.h usb.h usbhid.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -218,18 +209,6 @@ kexec_tramp.o: kexec_tramp.S
 dbg.o: dbg.c dbg.h serial.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-save.o: save.c fat.h io.h vfs.h
-	$(CC) $(CFLAGS) -o $@ $<
-
-rm.o: rm.c fat.h io.h vfs.h
-	$(CC) $(CFLAGS) -o $@ $<
-
-mkdir.o: mkdir.c fat.h io.h vfs.h
-	$(CC) $(CFLAGS) -o $@ $<
-
-rmdir.o: rmdir.c fat.h io.h vfs.h
-	$(CC) $(CFLAGS) -o $@ $<
-
 vfs.o: vfs.c vfs.h fat.h fatdetect.h blkdev.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -269,13 +248,16 @@ tss.o: tss.c tss.h
 syscall.o: syscall.c syscall.h io.h process.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-syscall_stub.o: syscall_stub.S
+sys_fs.o: sys_fs.c sys_fs.h syscall.h fat.h vfs.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
 mem.o: mem.c mm.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o ls.o cat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o curl.o hello_embed.o prog_embed.o space_embed.o
+kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o sys_fs.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o curl.o hello_embed.o prog_embed.o space_embed.o ucmd_cpuinfo_embed.o ucmd_ls_embed.o ucmd_cat_embed.o ucmd_save_embed.o ucmd_rm_embed.o ucmd_mkdir_embed.o ucmd_rmdir_embed.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -356,6 +338,26 @@ space: space.bin
 
 prog: prog.bin
 
+# Ring-3 commands (see the command registry in terminal.c): built as freestanding
+# ELFs at USER_BASE and embedded in the kernel image so `make dev`/`net-dev`
+# deliver them too.  New command: ucmd_<name>.c + a CMD_USER row in cmds[] and a
+# blob in ucmds[].
+UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir
+
+# Keep the linked ELFs around (make would treat them as disposable
+# intermediates between the pattern rules).
+.PRECIOUS: $(addprefix $(UCMDS),.elf)
+
+ucmd_%.o: ucmd_%.c ucmd_lib.h syscall.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ucmd_%.elf: ucmd_%.o ucmd.ld
+	$(LD) -T ucmd.ld -nostdlib -m elf_i386 -o $@ $<
+	$(OBJCOPY) --strip-all $@ $@
+
+ucmd_%_embed.o: ucmd_%.elf
+	$(LD) -m elf_i386 -r -b binary -o $@ $<
+
 space.o: space.c run_api.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -526,4 +528,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o ls.o cat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o curl.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o sys_fs.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o curl.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o $(addprefix $(UCMDS),.o) $(addprefix $(UCMDS),.elf) $(addsuffix _embed.o,$(UCMDS)) bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 0 - 65
cat.c

@@ -1,65 +0,0 @@
-/* cat command: print file contents to screen. Usage: cat /<device>/<file>. */
-
-#include "fat.h"
-#include "io.h"
-#include "vfs.h"
-
-#define DUMP_BUF_SIZE 4096
-
-void program_cat_main(const char *filename)
-{
-	static unsigned char buf[DUMP_BUF_SIZE];
-	fat_fs_t *fs;
-	const char *fs_path;
-	unsigned int dir_cluster;
-	char name_8_3[12];
-	int n;
-	unsigned int i;
-
-	if (!filename || !filename[0]) {
-		io_putstr("cat: usage cat /<device>/<file>\n");
-		return;
-	}
-
-	if (vfs_resolve(filename, &fs, &fs_path) != 0) {
-		if (vfs_device_known(filename))
-			io_putstr("cat: no filesystem on device\n");
-		else
-			io_putstr("cat: no such device\n");
-		return;
-	}
-
-	n = fat_resolve_path(fs, fs_path, &dir_cluster, name_8_3);
-	if (n == -2) {
-		io_putstr("cat: disk error\n");
-		return;
-	}
-	if (n != 0) {
-		io_putstr("cat: not found\n");
-		return;
-	}
-
-	n = fat_read_file_in(fs, dir_cluster, name_8_3, buf, DUMP_BUF_SIZE);
-	if (n == -2) {
-		io_putstr("cat: disk read error\n");
-		return;
-	}
-	if (n < 0) {
-		io_putstr("cat: file not found\n");
-		return;
-	}
-
-	for (i = 0; i < (unsigned int)n; i++) {
-		unsigned char c = buf[i];
-		if (c >= 0x20 && c < 0x7F)
-			io_putchar((char)c);
-		else if (c == '\n')
-			io_putchar('\n');
-		else if (c == '\t')
-			io_putchar('\t');
-		else
-			io_putchar('.');
-	}
-	if (n > 0 && buf[n - 1] != '\n')
-		io_putstr("\n");
-}

+ 0 - 74
ls.c

@@ -1,74 +0,0 @@
-/* ls command: list a directory. `ls` / `ls /` lists mounted filesystems;
- * `ls /<device>[/dir]` lists a directory on that filesystem. */
-
-#include "fat.h"
-#include "io.h"
-#include "vfs.h"
-
-#define BUF_SIZE 12
-
-static void list_cb(const char *name, int is_dir, unsigned int size)
-{
-	unsigned int i;
-	char buf[BUF_SIZE];
-	unsigned int n;
-
-	for (i = 0; i < 11 && name[i]; i++)
-		io_putchar(name[i] == ' ' ? ' ' : name[i]);
-	if (i < 11)
-		io_putchar(' ');
-	if (is_dir) {
-		io_putstr("  <DIR>\n");
-		return;
-	}
-	io_putstr(" ");
-	n = size;
-	if (n == 0) {
-		io_putchar('0');
-	} else {
-		buf[0] = '\0';
-		i = BUF_SIZE - 1;
-		buf[i] = '\0';
-		while (n && i > 0) {
-			buf[--i] = (char)('0' + (n % 10));
-			n /= 10;
-		}
-		io_putstr(buf + i);
-	}
-	io_putstr("\n");
-}
-
-void program_ls_main(const char *path)
-{
-	fat_fs_t *fs;
-	const char *fs_path;
-	unsigned int dir_cluster;
-	int r;
-
-	if (!path || !path[0] || (path[0] == '/' && path[1] == '\0')) {
-		vfs_list_root();
-		return;
-	}
-
-	if (vfs_resolve(path, &fs, &fs_path) != 0) {
-		if (vfs_device_known(path))
-			io_putstr("ls: no filesystem on device\n");
-		else
-			io_putstr("ls: no such device\n");
-		return;
-	}
-
-	r = fat_resolve_dir(fs, fs_path, &dir_cluster);
-	if (r == -2) {
-		io_putstr("ls: disk error\n");
-		return;
-	}
-	if (r != 0) {
-		io_putstr("ls: not a directory\n");
-		return;
-	}
-
-	r = fat_list_dir(fs, dir_cluster, list_cb);
-	if (r == -2)
-		io_putstr("ls: disk read error\n");
-}

+ 0 - 33
mkdir.c

@@ -1,33 +0,0 @@
-/* mkdir command: create a subdirectory. Usage: mkdir /<device>/<dir>. */
-
-#include "fat.h"
-#include "io.h"
-#include "vfs.h"
-
-void program_mkdir_main(const char *arg)
-{
-	fat_fs_t *fs;
-	const char *fs_path;
-	unsigned int dir_cluster;
-	char name_8_3[12];
-	int r;
-
-	if (!arg || !arg[0]) {
-		io_putstr("mkdir: usage mkdir /<device>/<dir>\n");
-		return;
-	}
-
-	if (vfs_resolve(arg, &fs, &fs_path) != 0) {
-		io_putstr("mkdir: unknown device or invalid path\n");
-		return;
-	}
-
-	r = fat_resolve_path(fs, fs_path, &dir_cluster, name_8_3);
-	if (r == -2) { io_putstr("mkdir: disk error\n"); return; }
-	if (r != 0) { io_putstr("mkdir: invalid path\n"); return; }
-
-	r = fat_mkdir(fs, dir_cluster, name_8_3);
-	if (r == -2) { io_putstr("mkdir: disk error\n"); return; }
-	if (r != 0) return;  /* fat_mkdir already printed */
-	io_putstr("mkdir ok\n");
-}

+ 74 - 24
process.c

@@ -8,6 +8,7 @@
 #include "mm.h"
 #include "paging.h"
 #include "serial.h"
+#include "sys_fs.h"
 #include "timer.h"
 
 struct process *procs;               /* dynamically-sized process table */
@@ -285,7 +286,8 @@ int process_create_ptr(const char *name, void (*entry)(void *), void *arg)
 }
 
 /* Load an ELF image into a fresh address space and run it as a ring-3 process. */
-int process_create_user(const char *name, const void *image, unsigned int size)
+int process_create_user(const char *name, const void *image, unsigned int size,
+			const char *arg)
 {
 	int slot, owned;
 	unsigned int base, top, *sp, cr3, entry;
@@ -313,35 +315,74 @@ int process_create_user(const char *name, const void *image, unsigned int size)
 		return -1;
 	}
 
-	/* Map the user stack just below USER_STACK_TOP. */
-	for (i = 0; i < USER_STACK_PAGES; i++) {
-		unsigned int phys = mm_alloc_page();
-		unsigned int va = USER_STACK_TOP - (unsigned int)(i + 1) * 0x1000;
-		if (!phys ||
-		    !paging_map_page(cr3, va, phys,
-				     PTE_USER | PTE_WRITABLE | PTE_PRESENT)) {
+	/* Map the user stack just below USER_STACK_TOP.  Keep the top page's
+	 * physical address: the argument string is written through it (identity
+	 * mapped) after it is mapped in `cr3`. */
+	{
+		unsigned int top_phys = 0;
+		unsigned int user_esp = USER_STACK_TOP;
+
+		for (i = 0; i < USER_STACK_PAGES; i++) {
+			unsigned int phys = mm_alloc_page();
+			unsigned int va = USER_STACK_TOP - (unsigned int)(i + 1) * 0x1000;
+			if (!phys ||
+			    !paging_map_page(cr3, va, phys,
+					     PTE_USER | PTE_WRITABLE | PTE_PRESENT)) {
+				mm_free_page(cr3);
+				irq_restore(flags);
+				return -1;
+			}
+			if (i == 0)
+				top_phys = phys;
+		}
+
+		/* One C string argument at the top of the user stack with a fake
+		 * return address below it, so `_start(const char *arg)` reads it
+		 * as its first parameter without needing a crt0.  The virtual
+		 * addresses go into the frame; the writes go through the identity
+		 * map at the same offset from the physical page top. */
+		{
+			unsigned int va_top = USER_STACK_TOP;
+			unsigned char *base_phys = (unsigned char *)(top_phys + 0x1000);
+			unsigned char *str_phys;
+			unsigned int *frame_phys;
+			unsigned int len = 0;
+			unsigned int va, k;
+
+			if (arg)
+				while (arg[len])
+					len++;
+			va = (va_top - (len + 1)) & ~15u;
+			if (va - 8 < USER_STACK_TOP - USER_STACK_PAGES * 0x1000) {
+				mm_free_page(cr3);
+				irq_restore(flags);
+				return -1;   /* argument does not fit the stack */
+			}
+			str_phys = base_phys - (va_top - va);
+			for (k = 0; k <= len; k++)
+				str_phys[k] = arg ? arg[k] : '\0';
+			frame_phys = (unsigned int *)(str_phys - 8);
+			frame_phys[0] = 0;   /* fake return address */
+			frame_phys[1] = va;  /* the argument pointer (user VA) */
+			user_esp = va - 8;
+		}
+		base = stack_alloc(&owned);
+		if (!base) {
 			mm_free_page(cr3);
 			irq_restore(flags);
 			return -1;
 		}
+		top = base + PROC_STACK_SIZE;
+		sp = (unsigned int *)top;
+		*--sp = 0x23;                 /* SS: user data */
+		*--sp = user_esp;             /* ESP: user stack + arg frame */
+		*--sp = 0x202;                /* EFLAGS: IF=1 */
+		*--sp = 0x1B;                 /* CS: user code */
+		*--sp = entry;                /* EIP */
+		*--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0;  /* EAX ECX EDX EBX */
+		*--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0;  /* ESP EBP ESI EDI */
 	}
 
-	base = stack_alloc(&owned);
-	if (!base) {
-		mm_free_page(cr3);
-		irq_restore(flags);
-		return -1;
-	}
-	top = base + PROC_STACK_SIZE;
-	sp = (unsigned int *)top;
-	*--sp = 0x23;                 /* SS: user data */
-	*--sp = USER_STACK_TOP;       /* ESP: user stack */
-	*--sp = 0x202;                /* EFLAGS: IF=1 */
-	*--sp = 0x1B;                 /* CS: user code */
-	*--sp = entry;                /* EIP */
-	*--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0;  /* EAX ECX EDX EBX */
-	*--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0;  /* ESP EBP ESI EDI */
-
 	procs[slot].esp        = (unsigned int)sp;
 	procs[slot].state      = PROC_READY;
 	procs[slot].pid        = next_pid_counter++;
@@ -405,6 +446,15 @@ void schedule(void)
 		}
 	}
 
+	/* A file syscall is in progress: stay on the current process so the FAT
+	 * driver's static state is never touched concurrently (see sys_fs.c).
+	 * Interrupts stay enabled, so the disk's IRQs are still serviced. */
+	if (sys_fs_busy) {
+		if (procs[current_pid].state == PROC_READY)
+			procs[current_pid].state = PROC_RUNNING;
+		return;
+	}
+
 	/* Wake sleeping processes whose deadline has passed. */
 	for (i = 0; i < proc_cap; i++) {
 		if (procs[i].state == PROC_SLEEPING &&

+ 4 - 2
process.h

@@ -48,8 +48,10 @@ int  process_create_arg(const char *name, void (*entry)(const char *),
 			const char *arg);
 int  process_create_ptr(const char *name, void (*entry)(void *), void *arg);
 /* Load an ELF image into a fresh address space and run it as a ring-3
- * process.  Returns the pid, or -1 on error. */
-int  process_create_user(const char *name, const void *image, unsigned int size);
+ * process, with `arg` (may be NULL) as the first C parameter of _start.
+ * Returns the pid, or -1 on error. */
+int process_create_user(const char *name, const void *image, unsigned int size,
+			const char *arg);
 void process_set_screen(struct text_screen *screen);
 
 /* Map an MMIO range into the kernel's page directory and every live process

+ 0 - 33
rm.c

@@ -1,33 +0,0 @@
-/* rm command: delete a file. Usage: rm /<device>/<file>. */
-
-#include "fat.h"
-#include "io.h"
-#include "vfs.h"
-
-void program_rm_main(const char *arg)
-{
-	fat_fs_t *fs;
-	const char *fs_path;
-	unsigned int dir_cluster;
-	char name_8_3[12];
-	int r;
-
-	if (!arg || !arg[0]) {
-		io_putstr("rm: usage rm /<device>/<file>\n");
-		return;
-	}
-
-	if (vfs_resolve(arg, &fs, &fs_path) != 0) {
-		io_putstr("rm: unknown device or invalid path\n");
-		return;
-	}
-
-	r = fat_resolve_path(fs, fs_path, &dir_cluster, name_8_3);
-	if (r == -2) { io_putstr("rm: disk error\n"); return; }
-	if (r != 0) { io_putstr("rm: not found\n"); return; }
-
-	r = fat_delete_file_in(fs, dir_cluster, name_8_3);
-	if (r == -2) { io_putstr("rm: disk error\n"); return; }
-	if (r != 0) { io_putstr("rm: file not found\n"); return; }
-	io_putstr("removed\n");
-}

+ 0 - 33
rmdir.c

@@ -1,33 +0,0 @@
-/* rmdir command: remove an empty subdirectory. Usage: rmdir /<device>/<dir>. */
-
-#include "fat.h"
-#include "io.h"
-#include "vfs.h"
-
-void program_rmdir_main(const char *arg)
-{
-	fat_fs_t *fs;
-	const char *fs_path;
-	unsigned int dir_cluster;
-	char name_8_3[12];
-	int r;
-
-	if (!arg || !arg[0]) {
-		io_putstr("rmdir: usage rmdir /<device>/<dir>\n");
-		return;
-	}
-
-	if (vfs_resolve(arg, &fs, &fs_path) != 0) {
-		io_putstr("rmdir: unknown device or invalid path\n");
-		return;
-	}
-
-	r = fat_resolve_path(fs, fs_path, &dir_cluster, name_8_3);
-	if (r == -2) { io_putstr("rmdir: disk error\n"); return; }
-	if (r != 0) { io_putstr("rmdir: invalid path\n"); return; }
-
-	r = fat_rmdir(fs, dir_cluster, name_8_3);
-	if (r == -2) { io_putstr("rmdir: disk error\n"); return; }
-	if (r != 0) return;  /* fat_rmdir already printed */
-	io_putstr("rmdir ok\n");
-}

+ 0 - 64
save.c

@@ -1,64 +0,0 @@
-/* save command: write a text string to a file.
- * Usage: save /<device>/<file> <text...>. */
-
-#include "fat.h"
-#include "io.h"
-#include "vfs.h"
-
-void program_save_main(const char *arg)
-{
-	char fn[64];
-	unsigned int i, fn_len, text_len;
-	fat_fs_t *fs;
-	const char *fs_path;
-	unsigned int dir_cluster;
-	char name_8_3[12];
-	const char *text;
-	int r;
-
-	if (!arg || !arg[0]) {
-		io_putstr("save: usage save /<device>/<file> <text>\n");
-		return;
-	}
-
-	/* filename = first token */
-	i = 0;
-	while (arg[i] == ' ')
-		i++;
-	fn_len = 0;
-	while (arg[i + fn_len] && arg[i + fn_len] != ' ' && fn_len < sizeof(fn) - 1)
-		fn_len++;
-	{
-		unsigned int j;
-		for (j = 0; j < fn_len; j++)
-			fn[j] = arg[i + j];
-	}
-	fn[fn_len] = '\0';
-	if (fn_len == 0) {
-		io_putstr("save: usage save /<device>/<file> <text>\n");
-		return;
-	}
-
-	/* text = the rest */
-	i += fn_len;
-	while (arg[i] == ' ')
-		i++;
-	text = arg + i;
-	text_len = 0;
-	while (text[text_len])
-		text_len++;
-
-	if (vfs_resolve(fn, &fs, &fs_path) != 0) {
-		io_putstr("save: unknown device or invalid path\n");
-		return;
-	}
-
-	r = fat_resolve_path(fs, fs_path, &dir_cluster, name_8_3);
-	if (r == -2) { io_putstr("save: disk error\n"); return; }
-	if (r != 0) { io_putstr("save: invalid path\n"); return; }
-
-	r = fat_write_file_in(fs, dir_cluster, name_8_3, text, text_len);
-	if (r == -2) { io_putstr("save: disk write error\n"); return; }
-	if (r != 0) { io_putstr("save: write failed\n"); return; }
-	io_putstr("saved\n");
-}

+ 254 - 0
sys_fs.c

@@ -0,0 +1,254 @@
+/* File service for ring-3 commands (see syscall.h for the ABI).
+ *
+ * The VFS/FAT layer and the disk drivers stay in the kernel; these calls
+ * expose whole-file operations on absolute paths.  Two properties shape how
+ * they run:
+ *   - the FAT driver keeps state in static buffers, so no other process may
+ *     run its FAT code concurrently;
+ *   - the floppy driver waits for IRQ6, so interrupts must stay enabled.
+ * So instead of a lock we set `sys_fs_busy` for the duration: the scheduler
+ * (schedule() in process.c) will not switch away from the running process
+ * while it is set.  That keeps each operation atomic (and immune to Ctrl+C
+ * killing the process mid-write) at the cost of a brief system stall during
+ * disk I/O.  Buffers point into the caller's address space, which is also the
+ * active one during the syscall, so no copy in/out is needed. */
+
+#include "syscall.h"
+#include "fat.h"
+#include "vfs.h"
+
+volatile int sys_fs_busy;
+
+static void fs_enter(void)
+{
+	sys_fs_busy = 1;
+	__asm__ volatile ("sti");   /* the disk may need its IRQ */
+}
+
+static void fs_exit(void)
+{
+	__asm__ volatile ("cli");
+	sys_fs_busy = 0;
+}
+
+static void copy_bounded(char *dst, const char *src, unsigned int size)
+{
+	unsigned int i = 0;
+
+	while (i + 1 < size && src[i]) {
+		dst[i] = src[i];
+		i++;
+	}
+	dst[i] = '\0';
+}
+
+static const char *fat_type_name(fat_type_t t)
+{
+	switch (t) {
+	case FAT12: return "FAT12";
+	case FAT16: return "FAT16";
+	case FAT32: return "FAT32";
+	default:    return "FAT";
+	}
+}
+
+/* Resolve `path` to (filesystem, parent directory cluster, final 8.3 name).
+ * Returns 0 or a SYS_E* code. */
+static int fs_parent(const char *path, fat_fs_t **fs_out,
+		     unsigned int *dir_cluster, char name_8_3[12])
+{
+	fat_fs_t *fs;
+	const char *fs_path;
+	int r;
+
+	if (!path || !path[0])
+		return SYS_ENODEV;
+	if (vfs_resolve(path, &fs, &fs_path) != 0)
+		return vfs_device_known(path) ? SYS_ENOFS : SYS_ENODEV;
+	r = fat_resolve_path(fs, fs_path, dir_cluster, name_8_3);
+	if (r == -2)
+		return SYS_EIO;
+	if (r != 0)
+		return SYS_ENOENT;
+	*fs_out = fs;
+	return 0;
+}
+
+/* Resolve `path` to (filesystem, directory cluster). */
+static int fs_dir(const char *path, fat_fs_t **fs_out, unsigned int *dir_cluster)
+{
+	fat_fs_t *fs;
+	const char *fs_path;
+	int r;
+
+	if (!path || !path[0])
+		return SYS_ENODEV;
+	if (vfs_resolve(path, &fs, &fs_path) != 0)
+		return vfs_device_known(path) ? SYS_ENOFS : SYS_ENODEV;
+	r = fat_resolve_dir(fs, fs_path, dir_cluster);
+	if (r == -2)
+		return SYS_EIO;
+	if (r != 0)
+		return SYS_EINVAL;      /* exists, but not a directory */
+	*fs_out = fs;
+	return 0;
+}
+
+int sys_read_file(const char *path, void *buf, unsigned int max)
+{
+	fat_fs_t *fs;
+	unsigned int dir;
+	char name[12];
+	int r;
+
+	fs_enter();
+	r = fs_parent(path, &fs, &dir, name);
+	if (r == 0) {
+		r = fat_read_file_in(fs, dir, name, buf, max);
+		if (r == -2)
+			r = SYS_EIO;
+		else if (r < 0)
+			r = SYS_ENOENT;
+	}
+	fs_exit();
+	return r;
+}
+
+int sys_write_file(const char *path, const void *buf, unsigned int len)
+{
+	fat_fs_t *fs;
+	unsigned int dir;
+	char name[12];
+	int r;
+
+	fs_enter();
+	r = fs_parent(path, &fs, &dir, name);
+	if (r == 0) {
+		r = fat_write_file_in(fs, dir, name, buf, len);
+		if (r == -2)
+			r = SYS_EIO;
+		else if (r != 0)
+			r = SYS_EWRITE;
+	}
+	fs_exit();
+	return r;
+}
+
+int sys_unlink(const char *path)
+{
+	fat_fs_t *fs;
+	unsigned int dir;
+	char name[12];
+	int r;
+
+	fs_enter();
+	r = fs_parent(path, &fs, &dir, name);
+	if (r == 0) {
+		r = fat_delete_file_in(fs, dir, name);
+		if (r == -2)
+			r = SYS_EIO;
+		else if (r != 0)
+			r = SYS_ENOENT;
+	}
+	fs_exit();
+	return r;
+}
+
+int sys_mkdir(const char *path)
+{
+	fat_fs_t *fs;
+	unsigned int dir;
+	char name[12];
+	int r;
+
+	fs_enter();
+	r = fs_parent(path, &fs, &dir, name);
+	if (r == 0) {
+		r = fat_mkdir(fs, dir, name);
+		if (r == -2)
+			r = SYS_EIO;
+		else if (r != 0)
+			r = SYS_EWRITE;
+	}
+	fs_exit();
+	return r;
+}
+
+int sys_rmdir(const char *path)
+{
+	fat_fs_t *fs;
+	unsigned int dir;
+	char name[12];
+	int r;
+
+	fs_enter();
+	r = fs_parent(path, &fs, &dir, name);
+	if (r == 0) {
+		r = fat_rmdir(fs, dir, name);
+		if (r == -2)
+			r = SYS_EIO;
+		else if (r != 0)
+			r = SYS_EWRITE;
+	}
+	fs_exit();
+	return r;
+}
+
+/* Directory listing: index-based, so the kernel keeps no per-process state.
+ * `fat_list_dir` walks from the start each call; directories are small. */
+static unsigned int list_index;
+static unsigned int list_seen;
+static struct sys_dirent *list_out;
+static int list_done;
+
+static void dirent_cb(const char *name, int is_dir, unsigned int size)
+{
+	unsigned int i;
+
+	if (list_done || list_seen < list_index) {
+		list_seen++;
+		return;
+	}
+	for (i = 0; i < 11; i++)
+		list_out->name[i] = name[i] ? name[i] : ' ';
+	list_out->name[11] = '\0';
+	list_out->size = size;
+	list_out->is_dir = (unsigned int)is_dir;
+	list_done = 1;
+	list_seen++;
+}
+
+int sys_list_dir(const char *path, unsigned int index, struct sys_dirent *out)
+{
+	fat_fs_t *fs;
+	unsigned int dir;
+	int r;
+
+	fs_enter();
+	r = fs_dir(path, &fs, &dir);
+	if (r == 0) {
+		list_index = index;
+		list_seen = 0;
+		list_out = out;
+		list_done = 0;
+		r = fat_list_dir(fs, dir, dirent_cb);
+		if (r == -2)
+			r = SYS_EIO;
+		else
+			r = list_done ? 1 : 0;   /* 1 = entry returned, 0 = end */
+	}
+	fs_exit();
+	return r;
+}
+
+int sys_list_mounts(unsigned int index, struct sys_mount *out)
+{
+	if (index >= vfs_mount_count)
+		return 0;
+	copy_bounded(out->name, vfs_mounts[index].name, sizeof(out->name));
+	copy_bounded(out->type, fat_type_name(vfs_mounts[index].fs.type),
+		     sizeof(out->type));
+	out->total_sectors = vfs_mounts[index].fs.total_sectors;
+	copy_bounded(out->label, vfs_mounts[index].fs.label, sizeof(out->label));
+	return 1;
+}

+ 19 - 0
sys_fs.h

@@ -0,0 +1,19 @@
+/* File-service syscalls (see sys_fs.c); used by syscall.c and the scheduler. */
+#ifndef SYS_FS_H
+#define SYS_FS_H
+
+#include "syscall.h"
+
+/* Set while a FAT operation is in progress: the scheduler must not switch
+ * away from the running process (see sys_fs.c). */
+extern volatile int sys_fs_busy;
+
+int sys_read_file(const char *path, void *buf, unsigned int max);
+int sys_write_file(const char *path, const void *buf, unsigned int len);
+int sys_unlink(const char *path);
+int sys_mkdir(const char *path);
+int sys_rmdir(const char *path);
+int sys_list_dir(const char *path, unsigned int index, struct sys_dirent *out);
+int sys_list_mounts(unsigned int index, struct sys_mount *out);
+
+#endif

+ 17 - 3
syscall.c

@@ -4,13 +4,11 @@
 #include "io.h"
 #include "process.h"
 #include "serial.h"
+#include "sys_fs.h"
 #include "timer.h"
 
 int syscall_dispatch(int num, int a1, int a2, int a3)
 {
-	(void)a2;
-	(void)a3;
-
 	switch (num) {
 	case SYS_PUTSTR:
 		io_putstr((const char *)a1);
@@ -23,6 +21,22 @@ int syscall_dispatch(int num, int a1, int a2, int a3)
 	case SYS_EXIT:
 		process_exit();   /* never returns */
 		return 0;
+	case SYS_READ_FILE:
+		return sys_read_file((const char *)a1, (void *)a2, (unsigned int)a3);
+	case SYS_WRITE_FILE:
+		return sys_write_file((const char *)a1, (const void *)a2,
+				      (unsigned int)a3);
+	case SYS_LIST_DIR:
+		return sys_list_dir((const char *)a1, (unsigned int)a2,
+				    (struct sys_dirent *)a3);
+	case SYS_UNLINK:
+		return sys_unlink((const char *)a1);
+	case SYS_MKDIR:
+		return sys_mkdir((const char *)a1);
+	case SYS_RMDIR:
+		return sys_rmdir((const char *)a1);
+	case SYS_LIST_MOUNTS:
+		return sys_list_mounts((unsigned int)a1, (struct sys_mount *)a2);
 	default:
 		return -1;
 	}

+ 39 - 1
syscall.h

@@ -1,4 +1,4 @@
-/* Syscall interface (int 0x80). */
+/* Syscall interface (int 0x80), shared by the kernel and ring-3 commands. */
 #ifndef SYSCALL_H
 #define SYSCALL_H
 
@@ -7,6 +7,44 @@
 #define SYS_SLEEP_MS     3
 #define SYS_EXIT         4
 
+/* File service (see sys_fs.c).  Paths are absolute VFS paths; buffers live in
+ * the calling process's address space (the kernel runs on its CR3, so no copy
+ * in/out is needed). */
+#define SYS_READ_FILE    5   /* (const char *path, void *buf, unsigned int max)
+				-> bytes read, or <0 (SYS_E*) */
+#define SYS_WRITE_FILE   6   /* (const char *path, const void *buf, unsigned int len)
+				-> 0, or <0 */
+#define SYS_LIST_DIR     7   /* (const char *path, unsigned int index,
+				struct sys_dirent *out) -> 1 entry, 0 end, <0 */
+#define SYS_UNLINK       8   /* (const char *path) -> 0, or <0 */
+#define SYS_MKDIR        9   /* (const char *path) -> 0, or <0 */
+#define SYS_RMDIR       10   /* (const char *path) -> 0, or <0 */
+#define SYS_LIST_MOUNTS 11   /* (unsigned int index, struct sys_mount *out)
+				-> 1 mount, 0 end */
+
+/* Error codes returned by the file syscalls. */
+#define SYS_EIO     (-1)     /* disk I/O error */
+#define SYS_ENODEV  (-2)     /* no such device / unusable path prefix */
+#define SYS_ENOFS   (-3)     /* device exists but has no mounted filesystem */
+#define SYS_ENOENT  (-4)     /* file/directory not found */
+#define SYS_EINVAL  (-5)     /* path is not valid for this operation */
+#define SYS_EWRITE  (-6)     /* write refused (full, or FAT rejected it) */
+
+/* One directory entry, raw 8.3 name exactly as stored (space padded). */
+struct sys_dirent {
+	char name[12];
+	unsigned int size;
+	unsigned int is_dir;
+};
+
+/* One mounted filesystem (for `ls /`). */
+struct sys_mount {
+	char name[16];
+	char type[8];           /* "FAT12", "FAT16", "FAT32" */
+	unsigned int total_sectors;
+	char label[12];
+};
+
 int syscall_dispatch(int num, int a1, int a2, int a3);
 
 #endif

ファイルの差分が大きいため隠しています
+ 269 - 840
terminal.c


+ 12 - 0
ucmd.ld

@@ -0,0 +1,12 @@
+/* Ring-3 command process: load at 0x40000000, same as process.h USER_BASE. */
+ENTRY(_start)
+
+SECTIONS
+{
+	. = 0x40000000;
+	.text : { *(.text .text.*) }
+	.rodata : { *(.rodata .rodata.*) }
+	.data : { *(.data .data.*) }
+	.bss : { *(.bss .bss.*) *(COMMON) }
+	_end = .;
+}

+ 52 - 0
ucmd_cat.c

@@ -0,0 +1,52 @@
+/* cat: ring-3 command.  Prints a file's contents. */
+
+#include "ucmd_lib.h"
+
+#define DUMP_BUF_SIZE 4096
+
+static unsigned char buf[DUMP_BUF_SIZE];
+
+void _start(const char *path)
+{
+	int n;
+	unsigned int i;
+
+	if (!path || !path[0]) {
+		u_puts("cat: usage cat /<device>/<file>\n");
+		u_exit(1);
+	}
+
+	n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, DUMP_BUF_SIZE);
+	if (n == SYS_ENODEV) {
+		u_puts("cat: no such device\n");
+		u_exit(1);
+	}
+	if (n == SYS_ENOFS) {
+		u_puts("cat: no filesystem on device\n");
+		u_exit(1);
+	}
+	if (n == SYS_EIO) {
+		u_puts("cat: disk read error\n");
+		u_exit(1);
+	}
+	if (n < 0) {
+		u_puts("cat: not found\n");
+		u_exit(1);
+	}
+
+	for (i = 0; i < (unsigned int)n; i++) {
+		unsigned char c = buf[i];
+
+		if (c >= 0x20 && c < 0x7F)
+			u_putc((char)c);
+		else if (c == '\n')
+			u_putc('\n');
+		else if (c == '\t')
+			u_putc('\t');
+		else
+			u_putc('.');
+	}
+	if (n > 0 && buf[n - 1] != '\n')
+		u_puts("\n");
+	u_exit(0);
+}

+ 54 - 60
cpuinfo.c → ucmd_cpuinfo.c

@@ -1,23 +1,15 @@
-/* cpuinfo command: print CPU vendor/model and estimated current clock speed. */
+/* cpuinfo: ring-3 command process.
+ *
+ * Prints CPU vendor/model and estimated current clock speed.  Moved out of the
+ * kernel (see the command registry): it only needs CPUID/RDTSC, which ring-3
+ * may execute, plus the output/timer syscalls.  The old kernel version lived
+ * in cpuinfo.c and is gone. */
 
-#include "io.h"
-#include "timer.h"
+#include "ucmd_lib.h"
 
 static void put_uint(unsigned int n)
 {
-	char buf[12];
-	char *p = buf + sizeof(buf) - 1;
-	*p = '\0';
-	if (n == 0) {
-		io_putchar('0');
-		return;
-	}
-	while (n) {
-		*--p = (char)('0' + (n % 10));
-		n /= 10;
-	}
-	while (*p)
-		io_putchar(*p++);
+	u_putdec(n);
 }
 
 static void cpuid(unsigned int leaf, unsigned int subleaf,
@@ -51,15 +43,15 @@ static void trim_right_spaces(char *s)
 static void print_flag(const char *name, int *printed_any)
 {
 	if (*printed_any)
-		io_putchar(' ');
-	io_putstr(name);
+		u_putc(' ');
+	u_puts(name);
 	*printed_any = 1;
 }
 
 static void print_features_leaf1(unsigned int ecx1, unsigned int edx1)
 {
 	int any = 0;
-	io_putstr("ext l1 ");
+	u_puts("ext l1 ");
 	if (edx1 & (1u << 0))  print_flag("FPU", &any);
 	if (edx1 & (1u << 4))  print_flag("TSC", &any);
 	if (edx1 & (1u << 5))  print_flag("MSR", &any);
@@ -90,8 +82,8 @@ static void print_features_leaf1(unsigned int ecx1, unsigned int edx1)
 	if (ecx1 & (1u << 29)) print_flag("F16C", &any);
 	if (ecx1 & (1u << 30)) print_flag("RDRAND", &any);
 	if (!any)
-		io_putstr("none");
-	io_putchar('\n');
+		u_puts("none");
+	u_putc('\n');
 }
 
 static void print_features_leaf7(unsigned int max_leaf)
@@ -104,7 +96,7 @@ static void print_features_leaf7(unsigned int max_leaf)
 	(void)eax7;
 	(void)ecx7;
 	(void)edx7;
-	io_putstr("ext l7 ");
+	u_puts("ext l7 ");
 	if (ebx7 & (1u << 0))  print_flag("FSGSBASE", &any);
 	if (ebx7 & (1u << 3))  print_flag("BMI1", &any);
 	if (ebx7 & (1u << 5))  print_flag("AVX2", &any);
@@ -116,8 +108,8 @@ static void print_features_leaf7(unsigned int max_leaf)
 	if (ebx7 & (1u << 23)) print_flag("CLFLUSHOPT", &any);
 	if (ebx7 & (1u << 29)) print_flag("SHA", &any);
 	if (!any)
-		io_putstr("none");
-	io_putchar('\n');
+		u_puts("none");
+	u_putc('\n');
 }
 
 static void print_features_ext(unsigned int max_ext_leaf)
@@ -129,7 +121,7 @@ static void print_features_ext(unsigned int max_ext_leaf)
 	cpuid(0x80000001u, 0, &eax, &ebx, &ecx, &edx);
 	(void)eax;
 	(void)ebx;
-	io_putstr("ext x ");
+	u_puts("ext x ");
 	if (edx & (1u << 11)) print_flag("SYSCALL", &any);
 	if (edx & (1u << 20)) print_flag("NX", &any);
 	if (edx & (1u << 27)) print_flag("RDTSCP", &any);
@@ -140,8 +132,8 @@ static void print_features_ext(unsigned int max_ext_leaf)
 	if (ecx & (1u << 6))  print_flag("SSE4A", &any);
 	if (ecx & (1u << 8))  print_flag("PREFETCHW", &any);
 	if (!any)
-		io_putstr("none");
-	io_putchar('\n');
+		u_puts("none");
+	u_putc('\n');
 }
 
 static void print_cpuid_frequency(unsigned int max_leaf)
@@ -151,28 +143,28 @@ static void print_cpuid_frequency(unsigned int max_leaf)
 	if (max_leaf >= 0x15u) {
 		cpuid(0x15u, 0, &eax, &ebx, &ecx, &edx);
 		if (eax != 0 && ebx != 0) {
-			io_putstr("cpuid15 ratio ");
+			u_puts("cpuid15 ratio ");
 			put_uint(ebx);
-			io_putchar('/');
+			u_putc('/');
 			put_uint(eax);
 			if (ecx != 0) {
-				io_putstr(" crystal ");
+				u_puts(" crystal ");
 				put_uint(ecx / 1000000u);
-				io_putstr(" MHz");
+				u_puts(" MHz");
 			}
-			io_putchar('\n');
+			u_putc('\n');
 		}
 	}
 	if (max_leaf >= 0x16u) {
 		cpuid(0x16u, 0, &eax, &ebx, &ecx, &edx);
 		if (eax != 0 || ebx != 0 || ecx != 0) {
-			io_putstr("cpuid16 base ");
+			u_puts("cpuid16 base ");
 			put_uint(eax);
-			io_putstr(" max ");
+			u_puts(" max ");
 			put_uint(ebx);
-			io_putstr(" bus ");
+			u_puts(" bus ");
 			put_uint(ecx);
-			io_putstr(" MHz\n");
+			u_puts(" MHz\n");
 		}
 	}
 }
@@ -194,7 +186,7 @@ static void parse_family_model(unsigned int eax1,
 	*stepping_out = stepping;
 }
 
-void program_cpuinfo_main(void)
+void _start(void)
 {
 	unsigned int eax, ebx, ecx, edx;
 	unsigned int ecx1, edx1, ebx1;
@@ -219,14 +211,14 @@ void program_cpuinfo_main(void)
 	vendor[12] = '\0';
 	cpuid(0x80000000u, 0, &max_ext_leaf, &ebx, &ecx, &edx);
 
-	io_putstr("vendor ");
-	io_putstr(vendor);
-	io_putchar('\n');
-	io_putstr("cpuid max ");
+	u_puts("vendor ");
+	u_puts(vendor);
+	u_putc('\n');
+	u_puts("cpuid max ");
 	put_uint(max_leaf);
-	io_putstr(" ext max ");
+	u_puts(" ext max ");
 	put_uint(max_ext_leaf & 0xFFFFu);
-	io_putchar('\n');
+	u_putc('\n');
 
 	cpuid(1, 0, &eax, &ebx, &ecx, &edx);
 	ebx1 = ebx;
@@ -234,13 +226,13 @@ void program_cpuinfo_main(void)
 	edx1 = edx;
 	parse_family_model(eax, &family, &model, &stepping);
 
-	io_putstr("family ");
+	u_puts("family ");
 	put_uint(family);
-	io_putstr(" model ");
+	u_puts(" model ");
 	put_uint(model);
-	io_putstr(" stepping ");
+	u_puts(" stepping ");
 	put_uint(stepping);
-	io_putchar('\n');
+	u_putc('\n');
 
 	if (max_ext_leaf >= 0x80000004u) {
 		for (i = 0; i < 48; i++)
@@ -259,9 +251,9 @@ void program_cpuinfo_main(void)
 			has_brand = 1;
 	}
 	if (has_brand) {
-		io_putstr("brand ");
-		io_putstr(brand);
-		io_putchar('\n');
+		u_puts("brand ");
+		u_puts(brand);
+		u_putc('\n');
 	}
 
 	/* Logical processors package-wide from leaf 1 EBX[23:16]. */
@@ -286,21 +278,21 @@ void program_cpuinfo_main(void)
 	if (threads_per_core == 0)
 		threads_per_core = 1;
 
-	io_putstr("topology ");
+	u_puts("topology ");
 	put_uint(logical_cpus);
-	io_putstr(" logical, ");
+	u_puts(" logical, ");
 	put_uint(cores);
-	io_putstr(" cores, ");
+	u_puts(" cores, ");
 	put_uint(threads_per_core);
-	io_putstr(" threads/core\n");
+	u_puts(" threads/core\n");
 
 	print_cpuid_frequency(max_leaf);
 
-	start_ms = get_ticks_ms();
+	start_ms = u_ticks_ms();
 	t0 = read_tsc_low();
 	do {
-		__asm__ volatile ("hlt");
-		end_ms = get_ticks_ms();
+		u_sleep_ms(1);          /* hlt is ring-0; yield instead */
+		end_ms = u_ticks_ms();
 	} while (end_ms - start_ms < 200);
 	t1 = read_tsc_low();
 	delta_ms = end_ms - start_ms;
@@ -310,13 +302,15 @@ void program_cpuinfo_main(void)
 
 	/* MHz with one decimal: cycles / (ms * 100). */
 	mhz_x10 = delta_cycles / (delta_ms * 100);
-	io_putstr("clock tsc ");
+	u_puts("clock tsc ");
 	put_uint(mhz_x10 / 10);
-	io_putchar('.');
+	u_putc('.');
 	put_uint(mhz_x10 % 10);
-	io_putstr(" MHz (sampled)\n");
+	u_puts(" MHz (sampled)\n");
 
 	print_features_leaf1(ecx1, edx1);
 	print_features_leaf7(max_leaf);
 	print_features_ext(max_ext_leaf);
+
+	u_exit(0);
 }

+ 108 - 0
ucmd_lib.h

@@ -0,0 +1,108 @@
+/* Tiny userland shim for ring-3 commands: syscall wrappers + string output.
+ * Freestanding (no libc); include "syscall.h" for the syscall numbers. */
+#ifndef UCMD_LIB_H
+#define UCMD_LIB_H
+
+#include "syscall.h"
+
+static inline int u_syscall1(int num, int a1)
+{
+	int ret;
+	__asm__ volatile ("int $0x80"
+			  : "=a"(ret)
+			  : "a"(num), "b"(a1)
+			  : "memory");
+	return ret;
+}
+
+static inline int u_syscall0(int num)
+{
+	int ret;
+	__asm__ volatile ("int $0x80"
+			  : "=a"(ret)
+			  : "a"(num)
+			  : "memory");
+	return ret;
+}
+
+static inline int u_syscall2(int num, int a1, int a2)
+{
+	int ret;
+	__asm__ volatile ("int $0x80"
+			  : "=a"(ret)
+			  : "a"(num), "b"(a1), "c"(a2)
+			  : "memory");
+	return ret;
+}
+
+static inline int u_syscall3(int num, int a1, int a2, int a3)
+{
+	int ret;
+	__asm__ volatile ("int $0x80"
+			  : "=a"(ret)
+			  : "a"(num), "b"(a1), "c"(a2), "d"(a3)
+			  : "memory");
+	return ret;
+}
+
+static inline void u_putc(char c)
+{
+	char b[2];
+
+	b[0] = c;
+	b[1] = '\0';
+	u_syscall1(SYS_PUTSTR, (int)b);
+}
+
+static inline void u_puts(const char *s)
+{
+	u_syscall1(SYS_PUTSTR, (int)s);
+}
+
+static inline void u_putdec(unsigned int n)
+{
+	char buf[12];
+	char *p = buf + sizeof(buf) - 1;
+
+	*p = '\0';
+	if (n == 0) {
+		u_putc('0');
+		return;
+	}
+	while (n) {
+		*--p = (char)('0' + (n % 10));
+		n /= 10;
+	}
+	u_puts(p);
+}
+
+static inline void u_puthex(unsigned int n)
+{
+	static const char hex[] = "0123456789ABCDEF";
+	char buf[11];
+	int i;
+
+	for (i = 0; i < 8; i++)
+		buf[i] = hex[(n >> (28 - i * 4)) & 0xF];
+	buf[8] = '\0';
+	u_puts(buf);
+}
+
+static inline unsigned int u_ticks_ms(void)
+{
+	return (unsigned int)u_syscall0(SYS_GET_TICKS_MS);
+}
+
+static inline void u_sleep_ms(unsigned int ms)
+{
+	u_syscall1(SYS_SLEEP_MS, (int)ms);
+}
+
+static inline void u_exit(int code)
+{
+	u_syscall1(SYS_EXIT, code);
+	for (;;)
+		;
+}
+
+#endif

+ 106 - 0
ucmd_ls.c

@@ -0,0 +1,106 @@
+/* ls: ring-3 command. `ls` / `ls /` lists mounted filesystems;
+ * `ls /<device>[/dir]` lists a directory on that filesystem. */
+
+#include "ucmd_lib.h"
+
+#define BUF_SIZE 12
+
+static void put_size_sectors(unsigned int sectors)
+{
+	if (sectors >= 2u * 1024u * 1024u) {           /* >= 1 GiB */
+		unsigned int gb = sectors >> 21;
+		unsigned int tenths = ((sectors & 0x1FFFFFu) * 10u) >> 21;
+		u_putdec(gb);
+		if (tenths) {
+			u_putc('.');
+			u_putdec(tenths);
+		}
+		u_puts(" GB");
+	} else if (sectors >= 2048u) {                 /* >= 1 MiB */
+		unsigned int mb = sectors >> 11;
+		unsigned int tenths = ((sectors & 0x7FFu) * 10u) >> 11;
+		u_putdec(mb);
+		if (tenths) {
+			u_putc('.');
+			u_putdec(tenths);
+		}
+		u_puts(" MB");
+	} else {
+		u_putdec(sectors / 2u);
+		u_puts(" KB");
+	}
+}
+
+static void print_entry(const struct sys_dirent *d)
+{
+	unsigned int i, n;
+	char buf[BUF_SIZE];
+
+	for (i = 0; i < 11 && d->name[i]; i++)
+		u_putc(d->name[i] == ' ' ? ' ' : d->name[i]);
+	if (i < 11)
+		u_putc(' ');
+	if (d->is_dir) {
+		u_puts("  <DIR>\n");
+		return;
+	}
+	u_puts(" ");
+	n = d->size;
+	if (n == 0) {
+		u_putc('0');
+	} else {
+		i = BUF_SIZE - 1;
+		buf[i] = '\0';
+		while (n && i > 0) {
+			buf[--i] = (char)('0' + (n % 10));
+			n /= 10;
+		}
+		u_puts(buf + i);
+	}
+	u_putc('\n');
+}
+
+void _start(const char *path)
+{
+	if (!path || !path[0] || (path[0] == '/' && path[1] == '\0')) {
+		struct sys_mount m;
+		unsigned int i = 0;
+
+		while (u_syscall2(SYS_LIST_MOUNTS, (int)i, (int)&m) == 1) {
+			u_puts(m.name);
+			u_puts("  ");
+			u_puts(m.type);
+			u_putc(' ');
+			put_size_sectors(m.total_sectors);
+			if (m.label[0]) {
+				u_puts("  \"");
+				u_puts(m.label);
+				u_putc('"');
+			}
+			u_putc('\n');
+			i++;
+		}
+		u_exit(0);
+	}
+
+	{
+		struct sys_dirent d;
+		unsigned int i = 0;
+		int r;
+
+		while ((r = u_syscall3(SYS_LIST_DIR, (int)path, (int)i,
+				       (int)&d)) == 1) {
+			print_entry(&d);
+			i++;
+		}
+		if (r == SYS_ENODEV)
+			u_puts("ls: no such device\n");
+		else if (r == SYS_ENOFS)
+			u_puts("ls: no filesystem on device\n");
+		else if (r == SYS_EINVAL)
+			u_puts("ls: not a directory\n");
+		else if (r == SYS_EIO)
+			u_puts("ls: disk error\n");
+	}
+	u_exit(0);
+}

+ 31 - 0
ucmd_mkdir.c

@@ -0,0 +1,31 @@
+/* mkdir: ring-3 command.  Creates a subdirectory. */
+
+#include "ucmd_lib.h"
+
+void _start(const char *path)
+{
+	int r;
+
+	if (!path || !path[0]) {
+		u_puts("mkdir: usage mkdir /<device>/<dir>\n");
+		u_exit(1);
+	}
+
+	r = u_syscall1(SYS_MKDIR, (int)path);
+	if (r == SYS_ENODEV || r == SYS_ENOFS) {
+		u_puts("mkdir: unknown device or invalid path\n");
+		u_exit(1);
+	}
+	if (r == SYS_EIO) {
+		u_puts("mkdir: disk error\n");
+		u_exit(1);
+	}
+	if (r == SYS_ENOENT || r == SYS_EINVAL) {
+		u_puts("mkdir: invalid path\n");
+		u_exit(1);
+	}
+	if (r != 0)
+		u_exit(1);   /* the FAT layer printed its own reason */
+	u_puts("mkdir ok\n");
+	u_exit(0);
+}

+ 33 - 0
ucmd_rm.c

@@ -0,0 +1,33 @@
+/* rm: ring-3 command.  Deletes a file. */
+
+#include "ucmd_lib.h"
+
+void _start(const char *path)
+{
+	int r;
+
+	if (!path || !path[0]) {
+		u_puts("rm: usage rm /<device>/<file>\n");
+		u_exit(1);
+	}
+
+	r = u_syscall1(SYS_UNLINK, (int)path);
+	if (r == SYS_ENODEV || r == SYS_ENOFS) {
+		u_puts("rm: unknown device or invalid path\n");
+		u_exit(1);
+	}
+	if (r == SYS_EIO) {
+		u_puts("rm: disk error\n");
+		u_exit(1);
+	}
+	if (r == SYS_ENOENT) {
+		u_puts("rm: not found\n");
+		u_exit(1);
+	}
+	if (r != 0) {
+		u_puts("rm: file not found\n");
+		u_exit(1);
+	}
+	u_puts("removed\n");
+	u_exit(0);
+}

+ 31 - 0
ucmd_rmdir.c

@@ -0,0 +1,31 @@
+/* rmdir: ring-3 command.  Removes an empty subdirectory. */
+
+#include "ucmd_lib.h"
+
+void _start(const char *path)
+{
+	int r;
+
+	if (!path || !path[0]) {
+		u_puts("rmdir: usage rmdir /<device>/<dir>\n");
+		u_exit(1);
+	}
+
+	r = u_syscall1(SYS_RMDIR, (int)path);
+	if (r == SYS_ENODEV || r == SYS_ENOFS) {
+		u_puts("rmdir: unknown device or invalid path\n");
+		u_exit(1);
+	}
+	if (r == SYS_EIO) {
+		u_puts("rmdir: disk error\n");
+		u_exit(1);
+	}
+	if (r == SYS_ENOENT || r == SYS_EINVAL) {
+		u_puts("rmdir: invalid path\n");
+		u_exit(1);
+	}
+	if (r != 0)
+		u_exit(1);   /* the FAT layer printed its own reason */
+	u_puts("rmdir ok\n");
+	u_exit(0);
+}

+ 56 - 0
ucmd_save.c

@@ -0,0 +1,56 @@
+/* save: ring-3 command.  Writes a text string to a file.
+ * The terminal resolves the path and passes "<absolute-path> <text...>" as the
+ * single argument, so this only splits it and calls the kernel service. */
+
+#include "ucmd_lib.h"
+
+void _start(const char *arg)
+{
+	char fn[64];
+	unsigned int i = 0, fn_len = 0, text_len = 0;
+	const char *text;
+	int r;
+
+	if (!arg || !arg[0]) {
+		u_puts("save: usage save /<device>/<file> <text>\n");
+		u_exit(1);
+	}
+
+	while (arg[i] == ' ')
+		i++;
+	while (arg[i + fn_len] && arg[i + fn_len] != ' ' && fn_len < sizeof(fn) - 1)
+		fn_len++;
+	{
+		unsigned int j;
+		for (j = 0; j < fn_len; j++)
+			fn[j] = arg[i + j];
+	}
+	fn[fn_len] = '\0';
+	if (fn_len == 0) {
+		u_puts("save: usage save /<device>/<file> <text>\n");
+		u_exit(1);
+	}
+
+	i += fn_len;
+	while (arg[i] == ' ')
+		i++;
+	text = arg + i;
+	while (text[text_len])
+		text_len++;
+
+	r = u_syscall3(SYS_WRITE_FILE, (int)fn, (int)text, (int)text_len);
+	if (r == SYS_ENODEV || r == SYS_ENOFS) {
+		u_puts("save: unknown device or invalid path\n");
+		u_exit(1);
+	}
+	if (r == SYS_EIO) {
+		u_puts("save: disk write error\n");
+		u_exit(1);
+	}
+	if (r != 0) {
+		u_puts("save: write failed\n");
+		u_exit(1);
+	}
+	u_puts("saved\n");
+	u_exit(0);
+}

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません