Przeglądaj źródła

Add storage and format commands

Johannes Zellner 1 miesiąc temu
rodzic
commit
86eba3044c
13 zmienionych plików z 1092 dodań i 3 usunięć
  1. 1 1
      AGENTS.md
  2. 20 2
      Makefile
  3. 223 0
      ata.c
  4. 13 0
      ata.h
  5. 95 0
      blkdev.c
  6. 32 0
      blkdev.h
  7. 120 0
      fatdetect.c
  8. 33 0
      fatdetect.h
  9. 252 0
      fatformat.c
  10. 11 0
      fatformat.h
  11. 92 0
      format.c
  12. 147 0
      storage.c
  13. 53 0
      terminal.c

+ 1 - 1
AGENTS.md

@@ -79,7 +79,7 @@ make clean
 
 `hello`, `reboot`, `poweroff`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `run <file>`, `space`, `clock`,
-`colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`,
+`colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `storage`, `format <device>`,
 `ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
 
 ## Serial hot-reload (kexec) workflow

+ 20 - 2
Makefile

@@ -116,6 +116,24 @@ usb.o: usb.c usb.h io.h timer.h uhci.h
 lsusb.o: lsusb.c io.h usb.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+blkdev.o: blkdev.c blkdev.h ata.h disk.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ata.o: ata.c ata.h pci.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+fatdetect.o: fatdetect.c fatdetect.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+storage.o: storage.c blkdev.h fatdetect.h disk.h io.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+fatformat.o: fatformat.c fatformat.h blkdev.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+format.o: format.c blkdev.h disk.h fatformat.h io.h vga.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 mouse.o: mouse.c mouse.h timer.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -158,7 +176,7 @@ switch.o: switch.S
 process.o: process.c process.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o io.o rtc.o terminal.o hello.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 nvidia.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o
+kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o io.o rtc.o terminal.o hello.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 nvidia.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o blkdev.o ata.o fatdetect.o storage.o fatformat.o format.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -307,4 +325,4 @@ dev: kernel.bin kexec_send
 	./kexec_send $(SERIAL_DEV) $(SERIAL_BAUD) $$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o io.o rtc.o terminal.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 nvidia.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.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 bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send
+	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o io.o rtc.o terminal.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 nvidia.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o blkdev.o ata.o fatdetect.o storage.o fatformat.o format.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.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 bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send

+ 223 - 0
ata.c

@@ -0,0 +1,223 @@
+/* ATA PIO driver: IDENTIFY + LBA28/LBA48 read/write, polled (no IRQ).
+ * The ATA IRQs (14/15) stay masked at boot, so we poll BSY/DRQ/ERR. */
+
+#include "ata.h"
+#include "pci.h"
+#include "timer.h"
+
+static const unsigned short ata_base[2] = { 0x1F0, 0x170 };
+static const unsigned short ata_ctrl[2] = { 0x3F6, 0x376 };
+
+/* Register offsets from the I/O base. */
+#define REG_DATA    0
+#define REG_ERROR   1
+#define REG_COUNT   2
+#define REG_LBA_LO  3
+#define REG_LBA_MID 4
+#define REG_LBA_HI  5
+#define REG_DRIVE   6
+#define REG_CMD     7
+
+/* Status bits (status = base+7, alt-status = ctrl+0). */
+#define SR_BSY 0x80
+#define SR_DRDY 0x40
+#define SR_DRQ 0x08
+#define SR_ERR 0x01
+
+/* Commands. */
+#define CMD_IDENTIFY  0xEC
+#define CMD_READ      0x20   /* LBA28 */
+#define CMD_WRITE     0x30   /* LBA28 */
+#define CMD_READ_EXT  0x24   /* LBA48 */
+#define CMD_WRITE_EXT 0x34   /* LBA48 */
+
+/* Delay 400 ns by reading the alt-status register a few times. */
+static void ata_400ns(unsigned short ctrl)
+{
+	(void)port_inb(ctrl);
+	(void)port_inb(ctrl);
+	(void)port_inb(ctrl);
+	(void)port_inb(ctrl);
+}
+
+static int ata_wait_not_busy(unsigned short ctrl, unsigned int timeout_ms)
+{
+	unsigned int t0 = get_ticks_ms();
+	while (get_ticks_ms() - t0 < timeout_ms) {
+		if (!(port_inb(ctrl) & SR_BSY))
+			return 0;
+	}
+	return -1;
+}
+
+static int ata_wait_drq(unsigned short base, unsigned int timeout_ms)
+{
+	unsigned int t0 = get_ticks_ms();
+	while (get_ticks_ms() - t0 < timeout_ms) {
+		unsigned char st = port_inb(base + REG_CMD);
+		if (st & SR_ERR)
+			return -1;
+		if (st & SR_DRQ)
+			return 0;
+	}
+	return -1;
+}
+
+static int ata_identify(int bus, int unit, unsigned short *id)
+{
+	unsigned short base = ata_base[bus];
+	unsigned short ctrl = ata_ctrl[bus];
+	unsigned char st;
+	unsigned int t0;
+	unsigned int i;
+
+	port_outb(base + REG_DRIVE, (unsigned char)(0xA0 | (unit << 4)));
+	port_outb(base + REG_COUNT, 0);
+	port_outb(base + REG_LBA_LO, 0);
+	port_outb(base + REG_LBA_MID, 0);
+	port_outb(base + REG_LBA_HI, 0);
+	port_outb(base + REG_CMD, CMD_IDENTIFY);
+
+	ata_400ns(ctrl);
+
+	t0 = get_ticks_ms();
+	for (;;) {
+		st = port_inb(base + REG_CMD);
+		if (st == 0 || st == 0xFF)   /* floating bus: no device */
+			return -1;
+		if (!(st & SR_BSY))
+			break;
+		if (get_ticks_ms() - t0 > 4000)
+			return -1;
+	}
+	if (!(st & SR_DRQ))
+		return -1;
+
+	for (i = 0; i < 256; i++)
+		id[i] = port_inw(base + REG_DATA);
+	return 0;
+}
+
+int ata_probe(int bus, int unit, unsigned int *total_sectors, char model[41])
+{
+	static unsigned short id[256];
+	unsigned int sectors, lo, hi, i;
+
+	if (ata_identify(bus, unit, id) != 0)
+		return -1;
+
+	if (id[0] & 0x8000)     /* ATAPI (cdrom/zip): not a data disk */
+		return -1;
+
+	/* Model string: words 27..46, byte-swapped. */
+	for (i = 0; i < 20; i++) {
+		unsigned short w = id[27 + i];
+		model[i * 2]     = (char)(w >> 8);
+		model[i * 2 + 1] = (char)(w & 0xFF);
+	}
+	model[40] = '\0';
+	for (i = 40; i > 0; i--) {
+		if (model[i - 1] == ' ')
+			model[i - 1] = '\0';
+		else
+			break;
+	}
+
+	sectors = (unsigned int)id[60] | ((unsigned int)id[61] << 16);
+	if (id[83] & 0x0400) {  /* LBA48 supported */
+		lo = (unsigned int)id[100] | ((unsigned int)id[101] << 16);
+		hi = (unsigned int)id[102] | ((unsigned int)id[103] << 16);
+		if (lo || hi)
+			sectors = lo;
+	}
+	*total_sectors = sectors;
+	return 0;
+}
+
+static inline void ata_insw(unsigned short port, void *dst, unsigned int count)
+{
+	__asm__ volatile ("rep insw"
+		: "+D"(dst), "+c"(count)
+		: "d"(port)
+		: "memory");
+}
+
+static inline void ata_outsw(unsigned short port, const void *src, unsigned int count)
+{
+	__asm__ volatile ("rep outsw"
+		: "+S"(src), "+c"(count)
+		: "d"(port)
+		: "memory");
+}
+
+static int ata_xfer(int bus, int unit, unsigned int lba, void *buf,
+		    unsigned int count, int write)
+{
+	unsigned short base = ata_base[bus];
+	unsigned short ctrl = ata_ctrl[bus];
+	unsigned char *p = buf;
+	unsigned int done = 0;
+
+	while (done < count) {
+		unsigned int chunk = count - done;
+		int lba48;
+		unsigned int cur = lba + done;
+
+		if (chunk > 255)
+			chunk = 255;
+		lba48 = ((cur + chunk - 1) >= 0x10000000u);
+
+		if (lba48) {
+			port_outb(base + REG_DRIVE, (unsigned char)(0x40 | (unit << 4)));
+			port_outb(base + REG_COUNT, (unsigned char)(chunk >> 8));
+			port_outb(base + REG_LBA_LO, (unsigned char)(cur >> 24));
+			port_outb(base + REG_LBA_MID, 0);
+			port_outb(base + REG_LBA_HI, 0);
+			port_outb(base + REG_COUNT, (unsigned char)(chunk & 0xFF));
+			port_outb(base + REG_LBA_LO, (unsigned char)(cur & 0xFF));
+			port_outb(base + REG_LBA_MID, (unsigned char)((cur >> 8) & 0xFF));
+			port_outb(base + REG_LBA_HI, (unsigned char)((cur >> 16) & 0xFF));
+			port_outb(base + REG_CMD, (unsigned char)(write ? CMD_WRITE_EXT : CMD_READ_EXT));
+		} else {
+			port_outb(base + REG_DRIVE,
+				  (unsigned char)(0xE0 | (unit << 4) | ((cur >> 24) & 0x0F)));
+			port_outb(base + REG_COUNT, (unsigned char)(chunk & 0xFF));
+			port_outb(base + REG_LBA_LO, (unsigned char)(cur & 0xFF));
+			port_outb(base + REG_LBA_MID, (unsigned char)((cur >> 8) & 0xFF));
+			port_outb(base + REG_LBA_HI, (unsigned char)((cur >> 16) & 0xFF));
+			port_outb(base + REG_CMD, (unsigned char)(write ? CMD_WRITE : CMD_READ));
+		}
+
+		ata_400ns(ctrl);
+		if (ata_wait_not_busy(ctrl, 4000) != 0)
+			return -1;
+		if (ata_wait_drq(base, 4000) != 0)
+			return -1;
+
+		if (write) {
+			ata_outsw(base + REG_DATA, p, chunk * 256);
+			/* Wait for the drive to finish writing to media (BSY clears
+			 * after the data transfer) before issuing the next command. */
+			if (ata_wait_not_busy(ctrl, 4000) != 0)
+				return -1;
+			if (port_inb(base + REG_CMD) & SR_ERR)
+				return -1;
+		} else {
+			ata_insw(base + REG_DATA, p, chunk * 256);
+		}
+
+		p += chunk * 512;
+		done += chunk;
+	}
+	return 0;
+}
+
+int ata_read_sectors(int bus, int unit, unsigned int lba, void *buf, unsigned int count)
+{
+	return ata_xfer(bus, unit, lba, buf, count, 0);
+}
+
+int ata_write_sectors(int bus, int unit, unsigned int lba, const void *buf, unsigned int count)
+{
+	return ata_xfer(bus, unit, lba, (void *)buf, count, 1);
+}

+ 13 - 0
ata.h

@@ -0,0 +1,13 @@
+/* ATA PIO driver (polling, no IRQ). Primary 0x1F0 / secondary 0x170. */
+#ifndef ATA_H
+#define ATA_H
+
+/* Probe an ATA device (bus 0=primary,1=secondary; unit 0=master,1=slave).
+ * Returns 0 and fills total_sectors/model if an ATA disk is present, else -1. */
+int ata_probe(int bus, int unit, unsigned int *total_sectors, char model[41]);
+
+/* Read/write sectors via ATA PIO. Return 0 on success, -1 on error. */
+int ata_read_sectors(int bus, int unit, unsigned int lba, void *buf, unsigned int count);
+int ata_write_sectors(int bus, int unit, unsigned int lba, const void *buf, unsigned int count);
+
+#endif

+ 95 - 0
blkdev.c

@@ -0,0 +1,95 @@
+/* Block device registry: floppy (via FDC) + IDE (via ATA). */
+
+#include "blkdev.h"
+#include "ata.h"
+#include "disk.h"
+
+blk_dev_t blk_devs[BLKDEV_MAX];
+unsigned int blk_dev_count;
+
+static blk_dev_t *add(const char *name, blk_kind_t kind,
+		      unsigned int bus, unsigned int unit)
+{
+	blk_dev_t *d;
+	if (blk_dev_count >= BLKDEV_MAX)
+		return 0;
+	d = &blk_devs[blk_dev_count++];
+	d->name = name;
+	d->kind = kind;
+	d->bus = bus;
+	d->unit = unit;
+	d->present = 0;
+	d->total_sectors = 0;
+	d->model[0] = '\0';
+	return d;
+}
+
+void blk_scan(void)
+{
+	blk_dev_t *d;
+
+	blk_dev_count = 0;
+
+	/* Floppy drive 0 (the FDC layer is single-drive). */
+	d = add("floppy0", BLK_FLOPPY, 0, 0);
+	if (d) { d->present = 1; d->total_sectors = 2880; }
+
+	/* IDE: primary + secondary, master + slave. */
+	{
+		static const char *names[4] = { "ide0", "ide1", "ide2", "ide3" };
+		unsigned int i;
+		for (i = 0; i < 4; i++) {
+			unsigned int sectors = 0;
+			char model[41];
+			d = add(names[i], BLK_IDE, i / 2, i % 2);
+			if (!d)
+				continue;
+			if (ata_probe(i / 2, i % 2, &sectors, model) == 0) {
+				unsigned int j;
+				d->present = 1;
+				d->total_sectors = sectors;
+				for (j = 0; j < 40; j++)
+					d->model[j] = model[j];
+				d->model[40] = '\0';
+			}
+		}
+	}
+}
+
+static int name_eq(const char *a, const char *b)
+{
+	while (*a && *b) {
+		if (*a != *b)
+			return 0;
+		a++;
+		b++;
+	}
+	return (*a == *b);
+}
+
+blk_dev_t *blk_find(const char *name)
+{
+	unsigned int i;
+	for (i = 0; i < blk_dev_count; i++)
+		if (name_eq(blk_devs[i].name, name))
+			return &blk_devs[i];
+	return 0;
+}
+
+int blk_read(blk_dev_t *d, unsigned int lba, void *buf, unsigned int count)
+{
+	if (!d || count == 0)
+		return -1;
+	if (d->kind == BLK_FLOPPY)
+		return disk_read_sectors(lba, buf, count);
+	return ata_read_sectors(d->bus, d->unit, lba, buf, count);
+}
+
+int blk_write(blk_dev_t *d, unsigned int lba, const void *buf, unsigned int count)
+{
+	if (!d || count == 0)
+		return -1;
+	if (d->kind == BLK_FLOPPY)
+		return disk_write_sectors(lba, buf, count);
+	return ata_write_sectors(d->bus, d->unit, lba, buf, count);
+}

+ 32 - 0
blkdev.h

@@ -0,0 +1,32 @@
+/* Block device registry: floppy + IDE. Shared by the `storage` and `format`
+ * commands so they agree on device names and read/write paths. */
+#ifndef BLKDEV_H
+#define BLKDEV_H
+
+typedef enum { BLK_FLOPPY, BLK_IDE } blk_kind_t;
+
+typedef struct {
+	const char *name;          /* "floppy0","floppy1","ide0".."ide3" */
+	blk_kind_t kind;
+	unsigned int bus;          /* floppy: drive #; ide: 0=primary,1=secondary */
+	unsigned int unit;         /* ide: 0=master,1=slave */
+	int present;               /* IDE: set by IDENTIFY; floppy: always listed */
+	unsigned int total_sectors;/* 0 if unknown (floppy) */
+	char model[41];            /* IDE model string */
+} blk_dev_t;
+
+#define BLKDEV_MAX 8
+extern blk_dev_t blk_devs[BLKDEV_MAX];
+extern unsigned int blk_dev_count;
+
+/* Probe devices and populate the registry. */
+void blk_scan(void);
+
+/* Find a device by name (NULL if not found). */
+blk_dev_t *blk_find(const char *name);
+
+/* Read/write count sectors at lba. Return 0 on success, -1 on error. */
+int blk_read(blk_dev_t *d, unsigned int lba, void *buf, unsigned int count);
+int blk_write(blk_dev_t *d, unsigned int lba, const void *buf, unsigned int count);
+
+#endif

+ 120 - 0
fatdetect.c

@@ -0,0 +1,120 @@
+/* FAT boot-sector + MBR detection (FAT12/16/32). */
+
+#include "fatdetect.h"
+
+static unsigned int rd16(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8);
+}
+
+static unsigned int rd32(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8) |
+	       ((unsigned int)p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+static int is_pow2(unsigned int v)
+{
+	return v != 0 && (v & (v - 1)) == 0;
+}
+
+int fat_detect(const unsigned char *boot, fat_info_t *info)
+{
+	unsigned int bps, spc, reserved, num_fats, root_entries;
+	unsigned int total, sec_per_fat16, sec_per_fat32, sec_per_fat;
+	unsigned int root_dir_sectors, data_sectors, clusters;
+	unsigned int label_off, i;
+
+	if (boot[510] != 0x55 || boot[511] != 0xAA)
+		return -1;
+
+	bps = rd16(boot + 0x0B);
+	if (bps != 512)
+		return -1;
+	spc = boot[0x0D];
+	if (!is_pow2(spc) || spc > 128)
+		return -1;
+	reserved = rd16(boot + 0x0E);
+	if (reserved < 1)
+		return -1;
+	num_fats = boot[0x10];
+	if (num_fats < 1 || num_fats > 2)
+		return -1;
+	root_entries = rd16(boot + 0x11);
+
+	total = rd16(boot + 0x13);
+	if (total == 0)
+		total = rd32(boot + 0x20);
+	if (total == 0)
+		return -1;
+
+	sec_per_fat16 = rd16(boot + 0x16);
+	sec_per_fat32 = rd32(boot + 0x24);
+	sec_per_fat = sec_per_fat16 ? sec_per_fat16 : sec_per_fat32;
+	if (sec_per_fat == 0)
+		return -1;
+
+	root_dir_sectors = (root_entries * 32 + bps - 1) / bps;
+	if (total < reserved + num_fats * sec_per_fat + root_dir_sectors)
+		return -1;
+	data_sectors = total - reserved - num_fats * sec_per_fat - root_dir_sectors;
+	if (data_sectors < spc)
+		return -1;
+	clusters = data_sectors / spc;
+
+	if (clusters < 4085)
+		info->type = FAT12;
+	else if (clusters < 65525)
+		info->type = FAT16;
+	else
+		info->type = FAT32;
+
+	info->bytes_per_sector = bps;
+	info->sectors_per_cluster = spc;
+	info->total_sectors = total;
+	info->cluster_count = clusters;
+
+	/* Volume label (11 bytes): 0x2B for FAT12/16, 0x47 for FAT32. */
+	label_off = (info->type == FAT32) ? 0x47 : 0x2B;
+	for (i = 0; i < 11; i++)
+		info->label[i] = (char)boot[label_off + i];
+	info->label[11] = '\0';
+	for (i = 11; i > 0 && (info->label[i - 1] == ' ' || info->label[i - 1] == '\0'); i--)
+		;
+	info->label[i] = '\0';
+
+	return 0;
+}
+
+int mbr_is_fat_type(unsigned char type)
+{
+	switch (type) {
+	case 0x01: case 0x04: case 0x06:
+	case 0x0B: case 0x0C: case 0x0E:
+		return 1;
+	default:
+		return 0;
+	}
+}
+
+int mbr_parse(const unsigned char *mbr, mbr_part_t parts[4])
+{
+	int n = 0, i;
+
+	if (mbr[510] != 0x55 || mbr[511] != 0xAA)
+		return 0;
+
+	for (i = 0; i < 4; i++) {
+		const unsigned char *e = mbr + 0x1BE + (unsigned int)i * 16;
+		unsigned char type = e[4];
+		if (type == 0)
+			continue;
+		parts[n].index = (unsigned char)i;
+		parts[n].type = type;
+		parts[n].start_lba = rd32(e + 8);
+		parts[n].sectors = rd32(e + 12);
+		parts[n].is_fat = mbr_is_fat_type(type);
+		n++;
+	}
+	return n;
+}

+ 33 - 0
fatdetect.h

@@ -0,0 +1,33 @@
+/* Standalone FAT boot-sector + MBR detection, independent of the read/write
+ * fat.c. Used by the `storage` command to identify filesystems on any device. */
+#ifndef FATDETECT_H
+#define FATDETECT_H
+
+typedef enum { FAT_NONE, FAT12, FAT16, FAT32 } fat_type_t;
+
+typedef struct {
+	fat_type_t type;
+	unsigned int bytes_per_sector;
+	unsigned int sectors_per_cluster;
+	unsigned int total_sectors;   /* filesystem total sectors */
+	unsigned int cluster_count;
+	char label[12];               /* trimmed 8.3 volume label + NUL */
+} fat_info_t;
+
+/* Parse a 512-byte boot sector. Returns 0 and fills info, or -1. */
+int fat_detect(const unsigned char *boot, fat_info_t *info);
+
+typedef struct {
+	unsigned char index;      /* 0..3 (original partition slot) */
+	unsigned char type;       /* 0 = empty */
+	unsigned int start_lba;
+	unsigned int sectors;
+	int is_fat;               /* 1 if type is a FAT partition type */
+} mbr_part_t;
+
+/* Parse an MBR (512 bytes). Returns number of non-empty partitions (0..4). */
+int mbr_parse(const unsigned char *mbr, mbr_part_t parts[4]);
+
+int mbr_is_fat_type(unsigned char type);
+
+#endif

+ 252 - 0
fatformat.c

@@ -0,0 +1,252 @@
+/* Create a fresh FAT filesystem on a block device.
+ * Floppy: FAT12 superfloppy (no MBR). IDE: MBR + single FAT16/32 partition. */
+
+#include "fatformat.h"
+
+#define SEC_SIZE 512
+
+static void put16(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v & 0xFF);
+	p[1] = (unsigned char)((v >> 8) & 0xFF);
+}
+
+static void put32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v & 0xFF);
+	p[1] = (unsigned char)((v >> 8) & 0xFF);
+	p[2] = (unsigned char)((v >> 16) & 0xFF);
+	p[3] = (unsigned char)((v >> 24) & 0xFF);
+}
+
+static void zero_sector(unsigned char *s)
+{
+	unsigned int i;
+	for (i = 0; i < SEC_SIZE; i++)
+		s[i] = 0;
+}
+
+static unsigned int fat_sec_per_fat(unsigned int type, unsigned int clusters)
+{
+	unsigned int entries = clusters + 2;
+	if (type == 12)
+		return (entries * 3 + 1023) / 1024;
+	if (type == 16)
+		return (entries * 2 + 511) / 512;
+	return (entries * 4 + 511) / 512;
+}
+
+static void choose_layout(unsigned int fs_sectors, unsigned int *type,
+			  unsigned int *spc, unsigned int *root_entries)
+{
+	if (fs_sectors < 4085) {
+		*type = 12;
+		*spc = 1;
+		*root_entries = (fs_sectors <= 2880) ? 224 : 512;
+	} else if (fs_sectors <= 4193536u) {   /* ~2 GB */
+		*type = 16;
+		*spc = 1;
+		while (fs_sectors / *spc >= 65525u)
+			*spc <<= 1;
+		*root_entries = 512;
+	} else {
+		*type = 32;
+		*spc = 8;
+		while (fs_sectors / *spc >= 268435445u)
+			*spc <<= 1;
+		*root_entries = 0;
+	}
+}
+
+static void build_boot_sector(unsigned char *s, unsigned int type, unsigned int spc,
+			      unsigned int reserved, unsigned int num_fats,
+			      unsigned int root_entries, unsigned int sec_per_fat,
+			      unsigned int fs_sectors, unsigned int hidden,
+			      unsigned int media)
+{
+	unsigned int i;
+	zero_sector(s);
+
+	s[0] = 0xEB;
+	s[1] = (type == 32) ? 0x58 : 0x3C;
+	s[2] = 0x90;
+	s[3] = 'M'; s[4] = 'S'; s[5] = 'D'; s[6] = 'O'; s[7] = 'S';
+	s[8] = '5'; s[9] = '.'; s[10] = '0';
+
+	put16(s + 0x0B, 512);
+	s[0x0D] = (unsigned char)spc;
+	put16(s + 0x0E, reserved);
+	s[0x10] = (unsigned char)num_fats;
+	put16(s + 0x11, root_entries);
+	put16(s + 0x13, (fs_sectors < 0x10000) ? fs_sectors : 0);
+	s[0x15] = (unsigned char)media;
+	put16(s + 0x16, (type != 32) ? sec_per_fat : 0);
+	put16(s + 0x18, (hidden == 0) ? 18 : 63);   /* sectors per track */
+	put16(s + 0x1A, (hidden == 0) ? 2 : 255);   /* heads */
+	put32(s + 0x1C, hidden);
+	put32(s + 0x20, fs_sectors);
+
+	if (type == 32) {
+		put32(s + 0x24, sec_per_fat);
+		s[0x28] = 0; s[0x29] = 0;               /* ext flags */
+		s[0x2A] = 0; s[0x2B] = 0;               /* fs version */
+		put32(s + 0x2C, 2);                     /* root cluster */
+		put16(s + 0x30, 1);                     /* FSInfo sector */
+		put16(s + 0x32, 6);                     /* backup boot sector */
+		s[0x40] = 0x80;                         /* drive number */
+		s[0x42] = 0x29;                         /* boot signature */
+		put32(s + 0x43, 0x12345678);            /* volume id */
+		for (i = 0; i < 11; i++) s[0x47 + i] = ' ';
+		s[0x52] = 'F'; s[0x53] = 'A'; s[0x54] = 'T'; s[0x55] = '3';
+		s[0x56] = '2'; s[0x57] = ' '; s[0x58] = ' '; s[0x59] = ' ';
+	} else {
+		s[0x24] = (hidden == 0) ? 0x00 : 0x80;  /* drive number */
+		s[0x26] = 0x29;                         /* boot signature */
+		put32(s + 0x27, 0x12345678);            /* volume id */
+		for (i = 0; i < 11; i++) s[0x2B + i] = ' ';
+		s[0x36] = 'F'; s[0x37] = 'A'; s[0x38] = 'T'; s[0x39] = '1';
+		s[0x3A] = (type == 12) ? '2' : '6';
+		s[0x3B] = ' '; s[0x3C] = ' '; s[0x3D] = ' ';
+	}
+
+	s[510] = 0x55;
+	s[511] = 0xAA;
+}
+
+static void build_fat_first_sector(unsigned char *s, unsigned int type,
+				   unsigned int media)
+{
+	zero_sector(s);
+	s[0] = (unsigned char)media;
+	if (type == 12) {
+		s[1] = 0xFF;
+		s[2] = 0xFF;
+	} else if (type == 16) {
+		s[1] = 0xFF;
+		s[2] = 0xFF;
+		s[3] = 0xFF;
+	} else { /* FAT32 */
+		s[1] = 0xFF; s[2] = 0xFF; s[3] = 0x0F;   /* entry 0 */
+		s[4] = 0xFF; s[5] = 0xFF; s[6] = 0xFF; s[7] = 0x0F;   /* entry 1 */
+		s[8] = 0xFF; s[9] = 0xFF; s[10] = 0xFF; s[11] = 0x0F;  /* entry 2 (root) */
+	}
+}
+
+static void build_fsinfo_sector(unsigned char *s)
+{
+	zero_sector(s);
+	put32(s + 0x000, 0x41615252u);   /* LeadSig "RRaA" */
+	put32(s + 0x1E4, 0x61417272u);   /* StrucSig "rrAa" */
+	put32(s + 0x1E8, 0xFFFFFFFFu);   /* free cluster count: unknown */
+	put32(s + 0x1EC, 0xFFFFFFFFu);   /* next free cluster: unknown */
+	put32(s + 0x1FC, 0xAA550000u);   /* TrailSig */
+}
+
+int fat_format(blk_dev_t *d)
+{
+	static unsigned char sec[SEC_SIZE];
+	static unsigned char fat_sec[SEC_SIZE];
+	static unsigned char zero[SEC_SIZE];
+	unsigned int fs_sectors, part_start;
+	unsigned int type, spc, root_entries;
+	unsigned int reserved, num_fats = 2, sec_per_fat, root_dir_sectors;
+	unsigned int clusters, fat_start, root_start, data_start;
+	unsigned int media;
+	int is_floppy = (d->kind == BLK_FLOPPY);
+	unsigned int i;
+
+	if (!d)
+		return -1;
+
+	if (is_floppy) {
+		fs_sectors = 2880;
+		part_start = 0;
+		media = 0xF0;
+	} else {
+		if (d->total_sectors < (2048 + 64))
+			return -1;   /* too small to partition */
+		part_start = 2048;
+		fs_sectors = d->total_sectors - part_start;
+		media = 0xF8;
+	}
+
+	choose_layout(fs_sectors, &type, &spc, &root_entries);
+	reserved = (type == 32) ? 32 : 1;
+
+	/* Converge on FAT size + cluster count. */
+	clusters = fs_sectors / spc;
+	for (i = 0; i < 3; i++) {
+		unsigned int data;
+		sec_per_fat = fat_sec_per_fat(type, clusters);
+		data = fs_sectors - reserved - num_fats * sec_per_fat
+			- ((root_entries * 32 + 511) / 512);
+		clusters = data / spc;
+	}
+	sec_per_fat = fat_sec_per_fat(type, clusters);
+	root_dir_sectors = (root_entries * 32 + 511) / 512;
+	fat_start = reserved;
+	root_start = reserved + num_fats * sec_per_fat;
+	data_start = root_start + root_dir_sectors;
+
+	zero_sector(zero);
+
+	/* 1. MBR (IDE only). */
+	if (!is_floppy) {
+		unsigned char *e;
+		zero_sector(sec);
+		e = sec + 0x1BE;
+		e[0] = 0x80;                            /* bootable */
+		e[1] = 0x00; e[2] = 0x02; e[3] = 0x00;   /* start CHS (C0 H0 S2) */
+		e[4] = (type == 32) ? 0x0C : (type == 16 ? 0x0E : 0x01);
+		e[5] = 0xFE; e[6] = 0xFF; e[7] = 0xFF;   /* end CHS (max, LBA) */
+		put32(e + 8, part_start);
+		put32(e + 12, fs_sectors);
+		sec[510] = 0x55;
+		sec[511] = 0xAA;
+		if (blk_write(d, 0, sec, 1) != 0)
+			return -1;
+	}
+
+	/* 2. Reserved area + boot sector (+ FSInfo/backup for FAT32). */
+	build_boot_sector(sec, type, spc, reserved, num_fats, root_entries,
+			  sec_per_fat, fs_sectors, part_start, media);
+	for (i = 0; i < reserved; i++) {
+		if (blk_write(d, part_start + i, zero, 1) != 0)
+			return -1;
+	}
+	if (blk_write(d, part_start, sec, 1) != 0)
+		return -1;
+	if (type == 32) {
+		if (blk_write(d, part_start + 6, sec, 1) != 0)   /* backup boot */
+			return -1;
+		build_fsinfo_sector(sec);
+		if (blk_write(d, part_start + 1, sec, 1) != 0)   /* FSInfo */
+			return -1;
+	}
+
+	/* 3. FATs (two copies). */
+	build_fat_first_sector(fat_sec, type, media);
+	for (i = 0; i < num_fats; i++) {
+		unsigned int j;
+		for (j = 0; j < sec_per_fat; j++) {
+			const unsigned char *s = (j == 0) ? fat_sec : zero;
+			if (blk_write(d, part_start + fat_start + i * sec_per_fat + j,
+				      s, 1) != 0)
+				return -1;
+		}
+	}
+
+	/* 4. Root directory (FAT12/16) or root cluster (FAT32). */
+	if (type == 32) {
+		/* Root dir is cluster 2 at the start of the data region. */
+		for (i = 0; i < spc; i++)
+			if (blk_write(d, part_start + data_start + i, zero, 1) != 0)
+				return -1;
+	} else {
+		for (i = 0; i < root_dir_sectors; i++)
+			if (blk_write(d, part_start + root_start + i, zero, 1) != 0)
+				return -1;
+	}
+
+	return 0;
+}

+ 11 - 0
fatformat.h

@@ -0,0 +1,11 @@
+/* Create a fresh FAT filesystem on a block device (floppy = FAT12 superfloppy,
+ * IDE = MBR + single FAT16/32 partition). */
+#ifndef FATFORMAT_H
+#define FATFORMAT_H
+
+#include "blkdev.h"
+
+/* Format device d. Returns 0 on success, -1 on error. */
+int fat_format(blk_dev_t *d);
+
+#endif

+ 92 - 0
format.c

@@ -0,0 +1,92 @@
+/* format command: create a fresh FAT filesystem on a device. Usage: format <device>. */
+
+#include "blkdev.h"
+#include "fatformat.h"
+#include "io.h"
+#include "vga.h"
+
+static void list_devices(void)
+{
+	unsigned int i;
+	io_putstr("devices:");
+	for (i = 0; i < blk_dev_count; i++) {
+		io_putchar(' ');
+		io_putstr(blk_devs[i].name);
+	}
+	io_putchar('\n');
+}
+
+void program_format_main(const char *arg)
+{
+	blk_dev_t *d;
+	char name[16];
+	unsigned int i = 0, j;
+	int k;
+
+	if (!arg) {
+		io_putstr("format: usage format <device>\n");
+		blk_scan();
+		list_devices();
+		return;
+	}
+
+	while (arg[i] == ' ')
+		i++;
+	j = 0;
+	while (arg[i] && arg[i] != ' ' && j < sizeof(name) - 1)
+		name[j++] = arg[i++];
+	name[j] = '\0';
+
+	if (name[0] == '\0') {
+		io_putstr("format: usage format <device>\n");
+		blk_scan();
+		list_devices();
+		return;
+	}
+
+	blk_scan();
+
+	d = blk_find(name);
+	if (!d) {
+		io_putstr("format: unknown device '");
+		io_putstr(name);
+		io_putstr("'\n");
+		list_devices();
+		return;
+	}
+
+	if (d->kind == BLK_IDE && !d->present) {
+		io_putstr("format: ");
+		io_putstr(d->name);
+		io_putstr(": not present\n");
+		return;
+	}
+
+	io_putstr("format ");
+	io_putstr(d->name);
+	io_putstr("? this destroys all data (y/n) ");
+	vga_fb_flush();
+
+	for (;;) {
+		k = io_poll_key_with_hw();
+		if (k == 'y' || k == 'Y')
+			break;
+		if (k == 'n' || k == 'N') {
+			io_putstr("aborted\n");
+			return;
+		}
+	}
+	io_putchar('\n');
+
+	io_putstr("formatting ");
+	io_putstr(d->name);
+	io_putstr("...\n");
+	vga_fb_flush();
+
+	if (fat_format(d) != 0) {
+		io_putstr("format: failed\n");
+		return;
+	}
+
+	io_putstr("done\n");
+}

+ 147 - 0
storage.c

@@ -0,0 +1,147 @@
+/* storage command: probe floppy + IDE devices and report FAT filesystems. */
+
+#include "blkdev.h"
+#include "fatdetect.h"
+#include "io.h"
+
+static void put_dec(unsigned int n)
+{
+	char buf[12];
+	unsigned int i = sizeof(buf) - 1;
+	buf[i] = '\0';
+	if (n == 0) {
+		io_putchar('0');
+		return;
+	}
+	while (n && i > 0) {
+		buf[--i] = (char)('0' + (n % 10));
+		n /= 10;
+	}
+	io_putstr(buf + i);
+}
+
+static void put_size(unsigned int bytes)
+{
+	if (bytes >= 1024u * 1024u * 1024u) {
+		unsigned int gb = bytes / (1024u * 1024u * 1024u);
+		unsigned int tenths = (bytes % (1024u * 1024u * 1024u)) * 10u / (1024u * 1024u * 1024u);
+		put_dec(gb);
+		if (tenths) {
+			io_putchar('.');
+			put_dec(tenths);
+		}
+		io_putstr(" GB");
+	} else if (bytes >= 1024u * 1024u) {
+		unsigned int mb = bytes / (1024u * 1024u);
+		unsigned int tenths = (bytes % (1024u * 1024u)) * 10u / (1024u * 1024u);
+		put_dec(mb);
+		if (tenths) {
+			io_putchar('.');
+			put_dec(tenths);
+		}
+		io_putstr(" MB");
+	} else {
+		put_dec(bytes / 1024u);
+		io_putstr(" KB");
+	}
+}
+
+static const char *fat_name(fat_type_t t)
+{
+	switch (t) {
+	case FAT12: return "FAT12";
+	case FAT16: return "FAT16";
+	case FAT32: return "FAT32";
+	default:    return "FAT";
+	}
+}
+
+static void report_fs(const char *name, const fat_info_t *info)
+{
+	io_putstr(name);
+	io_putstr(": ");
+	io_putstr(fat_name(info->type));
+	io_putchar(' ');
+	put_size(info->total_sectors * info->bytes_per_sector);
+	if (info->label[0]) {
+		io_putstr("  \"");
+		io_putstr(info->label);
+		io_putchar('"');
+	}
+	io_putchar('\n');
+}
+
+static void part_name(char *out, const char *base, unsigned int idx)
+{
+	unsigned int i = 0;
+	while (base[i] && i < 14) {
+		out[i] = base[i];
+		i++;
+	}
+	out[i++] = 'p';
+	out[i++] = (char)('0' + idx + 1);
+	out[i] = '\0';
+}
+
+void program_storage_main(void)
+{
+	static unsigned char buf[512];
+	static unsigned char pbuf[512];
+	unsigned int i;
+
+	blk_scan();
+
+	for (i = 0; i < blk_dev_count; i++) {
+		blk_dev_t *d = &blk_devs[i];
+		fat_info_t info;
+
+		if (d->kind == BLK_IDE && !d->present) {
+			io_putstr(d->name);
+			io_putstr(": not present\n");
+			continue;
+		}
+
+		if (blk_read(d, 0, buf, 1) != 0) {
+			io_putstr(d->name);
+			io_putstr(": not present / unreadable\n");
+			continue;
+		}
+
+		if (d->kind == BLK_FLOPPY) {
+			if (fat_detect(buf, &info) == 0)
+				report_fs(d->name, &info);
+			else {
+				io_putstr(d->name);
+				io_putstr(": no valid FAT filesystem\n");
+			}
+		} else {
+			mbr_part_t parts[4];
+			int n = mbr_parse(buf, parts);
+			int found = 0;
+			int j;
+
+			for (j = 0; j < n; j++) {
+				char pname[16];
+				if (!parts[j].is_fat || parts[j].start_lba == 0 ||
+				    parts[j].sectors == 0)
+					continue;
+				if (blk_read(d, parts[j].start_lba, pbuf, 1) != 0)
+					continue;
+				if (fat_detect(pbuf, &info) == 0) {
+					part_name(pname, d->name, parts[j].index);
+					report_fs(pname, &info);
+					found = 1;
+				}
+			}
+
+			if (!found) {
+				if (fat_detect(buf, &info) == 0)
+					report_fs(d->name, &info);
+				else {
+					io_putstr(d->name);
+					io_putstr(": no valid FAT filesystem\n");
+				}
+			}
+		}
+	}
+}

+ 53 - 0
terminal.c

@@ -33,6 +33,8 @@ extern void program_serial_loop_main(const char *arg);
 extern void program_serial_recv_main(const char *arg);
 extern void program_run_serial_main(const char *arg);
 extern void program_lsusb_main(void);
+extern void program_storage_main(void);
+extern void program_format_main(const char *arg);
 
 #define DATETIME_MS 1000
 #define LINE_MAX 64
@@ -328,6 +330,7 @@ static int is_cmd_run(const char *line, unsigned int line_len, char *filename_bu
 #define SAVE_ARGS_MAX 128
 #define RM_FNAME_MAX 64
 #define LS_PATH_MAX 64
+#define FORMAT_DEV_MAX 16
 
 static int is_cmd_save(const char *line, unsigned int line_len, char *arg_buf, unsigned int buf_size)
 {
@@ -413,6 +416,48 @@ static int is_cmd_rmdir(const char *line, unsigned int line_len, char *path_buf,
 	return (j > 0);
 }
 
+static int is_cmd_storage(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 7 > line_len)
+		return 0;
+	if (line[i] != 's' || line[i+1] != 't' || line[i+2] != 'o' ||
+	    line[i+3] != 'r' || line[i+4] != 'a' || line[i+5] != 'g' || line[i+6] != 'e')
+		return 0;
+	i += 7;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
+static int is_cmd_format(const char *line, unsigned int line_len, char *dev_buf, unsigned int buf_size)
+{
+	unsigned int i = 0, j;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 6 > line_len)
+		return 0;
+	if (line[i] != 'f' || line[i+1] != 'o' || line[i+2] != 'r' ||
+	    line[i+3] != 'm' || line[i+4] != 'a' || line[i+5] != 't')
+		return 0;
+	i += 6;
+	if (i < line_len && line[i] != ' ')
+		return 0;  /* "format" must be a whole word */
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i >= line_len)
+		return 0;
+	j = 0;
+	while (i < line_len && line[i] != ' ' && j < buf_size - 1)
+		dev_buf[j++] = line[i++];
+	dev_buf[j] = '\0';
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len && j > 0);
+}
+
 static int is_cmd_help(const char *line, unsigned int line_len)
 {
 	unsigned int i = 0;
@@ -699,6 +744,7 @@ void terminal_run(void)
 					static char save_args[SAVE_ARGS_MAX];
 					static char rm_fname[RM_FNAME_MAX];
 					static char ls_path[LS_PATH_MAX];
+					static char format_dev[FORMAT_DEV_MAX];
 					unsigned int kill_pid;
 					int skip_prompt = 0;
 					io_putchar('\n');
@@ -717,6 +763,9 @@ void terminal_run(void)
 					} else if (is_cmd_lsusb(line, line_len)) {
 						if (process_create("lsusb", program_lsusb_main) < 0)
 							io_putstr("error: too many processes\n");
+					} else if (is_cmd_storage(line, line_len)) {
+						if (process_create("storage", program_storage_main) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_clock(line, line_len)) {
 						if (process_create("clock", program_clock_main) < 0)
 							io_putstr("error: too many processes\n");
@@ -761,6 +810,8 @@ void terminal_run(void)
 					} else if (is_cmd_mouseinfo(line, line_len)) {
 						if (process_create("mouseinfo", program_mouseinfo_main) < 0)
 							io_putstr("error: too many processes\n");
+					} else if (is_cmd_format(line, line_len, format_dev, FORMAT_DEV_MAX)) {
+						program_format_main(format_dev);
 					} else if (is_cmd_ps(line, line_len)) {
 						process_ps();
 					} else if (is_cmd_kill(line, line_len, &kill_pid)) {
@@ -798,6 +849,8 @@ void terminal_run(void)
 						io_putstr("cpuinfo\n");
 						io_putstr("lsusb\n");
 						io_putstr("mouseinfo\n");
+						io_putstr("storage\n");
+						io_putstr("format <device>\n");
 						io_putstr("ps\n");
 						io_putstr("kill <pid>\n");
 						io_putstr("kexec\n");