Browse Source

Add code to read a floppy drive and access fat fs on it in readonly mode

Johannes Zellner 8 tháng trước cách đây
mục cha
commit
4ef5729bb0
12 tập tin đã thay đổi với 1098 bổ sung và 68 xóa
  1. 45 15
      Makefile
  2. 52 29
      boot.S
  3. 73 0
      cat.c
  4. 392 0
      disk.c
  5. 17 0
      disk.h
  6. 180 0
      fat.c
  7. 21 0
      fat.h
  8. 39 16
      io.c
  9. 55 7
      kernel.c
  10. 54 0
      ls.c
  11. 77 0
      terminal.c
  12. 93 1
      timer.S

+ 45 - 15
Makefile

@@ -1,19 +1,21 @@
-# Bootloader: 512-byte boot sector + kernel at sector 2. Builds image.bin for QEMU.
+# Bootloader: 512-byte boot sector + contiguous kernel at sector 1. Builds image.bin for QEMU.
 
 CC      = gcc
 AS      = as
 LD      = ld
 OBJCOPY = objcopy
 
-CFLAGS   = -ffreestanding -fno-pie -m32 -nostdlib -fno-stack-protector \
-           -fno-asynchronous-unwind-tables -Wall -Wextra -O2 -c
+# -march=i586: first-gen Pentium (P5); avoids CMOV etc. (P6+)
+CFLAGS   = -ffreestanding -fno-pie -m32 -march=i586 -nostdlib -fno-stack-protector \
+           -fno-asynchronous-unwind-tables -mno-sse -mno-sse2 -mno-mmx \
+           -Wall -Wextra -O2 -c
 ASFLAGS  = --32
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
 .PHONY: all clean run
 
-all: image.bin
+all: image.bin final.bin root.img
 
 boot.o: boot.S
 	$(AS) $(ASFLAGS) -o $@ $<
@@ -24,12 +26,24 @@ kernel.o: kernel.c io.h terminal.h timer.h
 io.o: io.c io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-terminal.o: terminal.c terminal.h io.h rtc.h timer.h
+terminal.o: terminal.c terminal.h io.h rtc.h timer.h disk.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 hello.o: hello.c io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+disk.o: disk.c disk.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+fat.o: fat.c fat.h disk.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ls.o: ls.c fat.h io.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+cat.o: cat.c fat.h io.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 rtc.o: rtc.c rtc.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -39,7 +53,7 @@ boot.elf: boot.o
 timer.o: timer.S
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: kernel.o timer.o io.o rtc.o terminal.o hello.o
+kernel.elf: kernel.o timer.o io.o rtc.o terminal.o hello.o disk.o fat.o ls.o cat.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 boot.bin: boot.elf
@@ -51,15 +65,31 @@ boot.bin: boot.elf
 kernel.bin: kernel.elf
 	$(OBJCOPY) -O binary $< $@
 
+KERNEL_SECTORS_OFFSET = 62
 image.bin: boot.bin kernel.bin
-	@KERNEL_SECTORS=$$(( ($$(wc -c < kernel.bin) + 511) / 512 )); \
-	TOTAL_SECTORS=$$(( 1 + KERNEL_SECTORS )); \
-	dd if=/dev/zero of=$@ bs=512 count=$$TOTAL_SECTORS 2>/dev/null; \
-	dd if=boot.bin of=$@ bs=512 conv=notrunc 2>/dev/null; \
-	dd if=kernel.bin of=$@ bs=512 seek=1 conv=notrunc 2>/dev/null
-
-run: image.bin
-	qemu-system-i386 -M pc -drive file=image.bin,format=raw 2>/dev/null || qemu-system-x86_64 -M pc -drive file=image.bin,format=raw
+	SECTORS=$$(( ($$(stat -c%s kernel.bin) + 511) / 512 )); \
+	cp boot.bin boot.bin.patched; \
+	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=boot.bin.patched bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
+	cat boot.bin.patched kernel.bin > $@; \
+	truncate -s 1474560 $@; \
+	rm -f boot.bin.patched
+
+final.bin: boot.bin kernel.bin
+	SECTORS=$$(( ($$(stat -c%s kernel.bin) + 511) / 512 )); \
+	cp boot.bin boot.bin.patched; \
+	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=boot.bin.patched bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
+	cat boot.bin.patched kernel.bin > $@; \
+	rm -f boot.bin.patched
+
+root.img:
+	dd if=/dev/zero of=$@ bs=512 count=2880 2>/dev/null
+	mkfs.fat -F 12 -n "ROOTDISK" $@
+	echo "Hello from the second floppy!" | mcopy -i $@ - ::HELLO.TXT
+	echo "This is a test file on drive 1." | mcopy -i $@ - ::TEST.TXT
+
+run: image.bin root.img
+	qemu-system-i386 -M pc -drive file=image.bin,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
+	qemu-system-x86_64 -M pc -drive file=image.bin,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
 
 clean:
-	rm -f boot.o kernel.o timer.o io.o rtc.o terminal.o hello.o boot.elf kernel.elf boot.bin kernel.bin boot.bin.tmp image.bin
+	rm -f boot.o kernel.o timer.o io.o rtc.o terminal.o hello.o fat.o ls.o cat.o disk.o boot.elf kernel.elf boot.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin final.bin root.img

+ 52 - 29
boot.S

@@ -1,38 +1,73 @@
-/* Minimal x86 boot sector: load kernel from sector 2 to 0x7E00,
- * switch to protected mode, jump to kernel (C code at 0x7E00). */
+/* Boot sector: load contiguous kernel sectors 1..N to 0x7E00, then PM. No FAT. */
 
 .code16
 .section .text
 
 .globl _start
 _start:
-	/* Segment and stack for real mode */
+	.byte 0xEB, 0x3E, 0x90
+	.space 0x3E - 3, 0
+
+	.org 0x3E
+kernel_sectors:
+	.word 1
+
+	.org 0x40
+loader_start:
 	xorw  %ax, %ax
 	movw  %ax, %ds
 	movw  %ax, %ss
 	movw  $0x7c00, %sp
-
-	/* Save boot drive (BIOS puts it in DL) */
 	movb  %dl, boot_drive
 
-	/* Set VGA mode 0x03 (80x25 color text) so 0xB8000 is the visible framebuffer */
 	movw  $0x0003, %ax
 	int   $0x10
 
-	/* Load kernel: 10 sectors from sector 2 into 0x7E00 (ES:BX = 0x07E0:0) */
+	/* Load kernel: sectors 1..kernel_sectors to 0x7E00. */
+	movw  kernel_sectors, %cx
+	movw  $1, %si
 	movw  $0x07e0, %ax
 	movw  %ax, %es
 	xorw  %bx, %bx
-	movb  $0x02, %ah          /* int 0x13 read */
-	movb  $10, %al            /* 10 sectors (kernel up to 5K) */
-	xorw  %cx, %cx
-	movb  $2, %cl             /* sector 2 (1-based) */
-	xorw  %dx, %dx             /* head 0, drive in DL */
+
+load_loop:
+	cmpw  $0, %cx
+	jz    load_done
+	pushw %cx
+	pushw %si
+	/* CHS from LBA in SI */
+	movw  %si, %ax
+	xorw  %dx, %dx
+	movw  $18, %di
+	divw  %di
+	movb  %dl, %cl
+	incb  %cl
+	xorw  %dx, %dx
+	movw  $2, %di
+	divw  %di
+	movb  %dl, %dh
+	movb  %al, %ch
 	movb  boot_drive, %dl
+	movb  $0x02, %ah
+	movb  $1, %al
 	int   $0x13
-	jc    halt                /* on error just halt */
+	popw  %si
+	popw  %cx
+	jc    halt
+	addw  $0x200, %bx
+	jnc   1f
+	movw  %es, %ax
+	addw  $0x1000, %ax
+	movw  %ax, %es
+1:	incw  %si
+	decw  %cx
+	jnz   load_loop
+
+load_done:
+	movw  $0x7DFC, %bx
+	movb  boot_drive, %al
+	movb  %al, (%bx)
 
-	/* Protected mode: load GDT, set CR0.PE, far jump to 32-bit code */
 	cli
 	lgdt  gdtr
 	movl  %cr0, %eax
@@ -46,28 +81,23 @@ _start:
 boot_drive:
 	.byte 0
 
-/* GDT (flat 4GB code and data) */
 	.align 8
 gdt:
-	.quad 0x0000000000000000
-	/* 0x08: 32-bit code, DPL=0, base=0, limit=0xfffff (4GB) */
+	.quad 0
 	.word 0xffff, 0x0000
 	.byte 0x00, 0x9a, 0xcf, 0x00
-	/* 0x10: 32-bit data */
 	.word 0xffff, 0x0000
 	.byte 0x00, 0x92, 0xcf, 0x00
 gdt_end:
-
 gdtr:
 	.word gdt_end - gdt - 1
-	.long gdt                 /* linear address (linker uses 0x7C00 base) */
+	.long gdt
 
 halt:
 	cli
 1:	hlt
 	jmp   1b
 
-/* --- 32-bit protected mode --- */
 .code32
 pm_start:
 	movw  $0x10, %ax
@@ -76,16 +106,9 @@ pm_start:
 	movw  %ax, %fs
 	movw  %ax, %gs
 	movw  %ax, %ss
-	movl  $0x10000, %esp      /* stack well above kernel (grows down from 64K) */
-
-	/* Jump to kernel at 0x7E00 (direct; *0x7e00 would be indirect = wrong) */
+	movl  $0x10000, %esp
 	movl  $0x7e00, %eax
 	jmp   *%eax
 
-1:	cli
-	hlt
-	jmp   1b
-
-/* Boot signature at offset 510 (linker places it) */
 .section .bootsig
 .byte 0x55, 0xaa

+ 73 - 0
cat.c

@@ -0,0 +1,73 @@
+/* cat command: print file contents to screen. */
+
+#include "fat.h"
+#include "io.h"
+
+#define DUMP_BUF_SIZE 4096
+#define NAME_BUF_SIZE 12
+
+static void to_8_3(const char *in, unsigned int in_len, char *out)
+{
+	unsigned int i, j, dot;
+	for (i = 0; i < in_len && in[i] == ' '; i++)
+		;
+	dot = i;
+	while (dot < in_len && in[dot] != '.' && in[dot] != ' ')
+		dot++;
+	j = 0;
+	while (i < dot && j < 8) {
+		out[j++] = (char)(in[i] >= 'a' && in[i] <= 'z' ? in[i] - 32 : in[i]);
+		i++;
+	}
+	while (j < 8)
+		out[j++] = ' ';
+	if (i < in_len && in[i] == '.')
+		i++;
+	while (i < in_len && in[i] != ' ' && j < 11) {
+		out[j++] = (char)(in[i] >= 'a' && in[i] <= 'z' ? in[i] - 32 : in[i]);
+		i++;
+	}
+	while (j < 11)
+		out[j++] = ' ';
+	out[11] = '\0';
+}
+
+void program_cat_main(const char *filename)
+{
+	static unsigned char buf[DUMP_BUF_SIZE];
+	char name_8_3[NAME_BUF_SIZE];
+	int n;
+	unsigned int i;
+
+	if (!filename || !filename[0]) {
+		io_putstr("cat: usage cat <filename>\n");
+		return;
+	}
+	to_8_3(filename, 64, name_8_3);
+	if (fat_init() != 0) {
+		io_putstr("cat: fat init failed\n");
+		return;
+	}
+	n = fat_read_file(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");
+}

+ 392 - 0
disk.c

@@ -0,0 +1,392 @@
+/* Disk layer: read sectors via direct FDC + ISA DMA in protected mode. */
+
+#include "disk.h"
+#include "timer.h"
+
+#define SECTOR_SIZE       512
+#define SECTORS_PER_TRACK 18
+#define HEADS             2
+#define DMA_BUF_ADDR      0x10000
+
+/* FDC I/O ports */
+#define FDC_DOR   0x3F2
+#define FDC_MSR   0x3F4
+#define FDC_FIFO  0x3F5
+#define FDC_CCR   0x3F7
+
+/* ISA DMA channel 2 ports */
+#define DMA_CH2_ADDR      0x04
+#define DMA_CH2_COUNT     0x05
+#define DMA_CH2_PAGE      0x81
+#define DMA_SINGLEMASK    0x0A
+#define DMA_MODE          0x0B
+#define DMA_FLIPFLOP      0x0C
+
+/* MSR bits */
+#define MSR_RQM  0x80
+#define MSR_DIO  0x40
+#define MSR_CB   0x10
+
+/* FDC commands */
+#define CMD_SPECIFY      0x03
+#define CMD_RECALIBRATE  0x07
+#define CMD_SENSE_INT    0x08
+#define CMD_READ_DATA    0xE6   /* READ | MFM | SK */
+#define CMD_SEEK         0x0F
+
+#define MOTOR_DELAY_MS   300
+#define IRQ_TIMEOUT_MS   2000
+#define MAX_RETRIES      3
+
+/* PIC master mask port */
+#define PIC1_DATA  0x21
+
+static inline unsigned char inb(unsigned short port)
+{
+	unsigned char v;
+	__asm__ volatile ("inb %1, %0" : "=a"(v) : "Nd"(port));
+	return v;
+}
+
+static inline void outb(unsigned short port, unsigned char v)
+{
+	__asm__ volatile ("outb %0, %1" : : "a"(v), "Nd"(port));
+}
+
+volatile int fdc_irq_fired;
+
+void fdc_irq(void)
+{
+	fdc_irq_fired = 1;
+	outb(0x20, 0x20);
+}
+
+static int fdc_initialized;
+static int motor_on;
+static unsigned int cur_cylinder;
+static unsigned int current_drive;
+
+/* ---- low-level FDC helpers ---- */
+
+static int fdc_wait_rqm(void)
+{
+	unsigned int t0 = get_ticks_ms();
+	while ((get_ticks_ms() - t0) < 500) {
+		if (inb(FDC_MSR) & MSR_RQM)
+			return 0;
+	}
+	return -1;
+}
+
+static int fdc_send(unsigned char b)
+{
+	if (fdc_wait_rqm() != 0)
+		return -1;
+	if (inb(FDC_MSR) & MSR_DIO)
+		return -1;
+	outb(FDC_FIFO, b);
+	return 0;
+}
+
+static int fdc_recv(unsigned char *b)
+{
+	if (fdc_wait_rqm() != 0)
+		return -1;
+	if (!(inb(FDC_MSR) & MSR_DIO))
+		return -1;
+	*b = inb(FDC_FIFO);
+	return 0;
+}
+
+static int fdc_wait_irq(void)
+{
+	unsigned int t0 = get_ticks_ms();
+	while (!fdc_irq_fired) {
+		if ((get_ticks_ms() - t0) >= IRQ_TIMEOUT_MS)
+			return -1;
+		__asm__ volatile ("hlt");
+	}
+	return 0;
+}
+
+static int fdc_sense_interrupt(unsigned char *st0, unsigned char *cyl)
+{
+	if (fdc_send(CMD_SENSE_INT) != 0)
+		return -1;
+	if (fdc_recv(st0) != 0)
+		return -1;
+	if (fdc_recv(cyl) != 0)
+		return -1;
+	return 0;
+}
+
+/* ---- motor control ---- */
+
+static void fdc_motor_on(void)
+{
+	if (motor_on)
+		return;
+	outb(FDC_DOR, (unsigned char)((1 << (4 + current_drive)) | 0x0C | current_drive));
+	{
+		unsigned int t0 = get_ticks_ms();
+		while ((get_ticks_ms() - t0) < MOTOR_DELAY_MS)
+			__asm__ volatile ("hlt");
+	}
+	motor_on = 1;
+}
+
+/* ---- reset ---- */
+
+static int fdc_reset(void)
+{
+	unsigned char st0, cyl;
+	int i;
+
+	/* Pull reset line: DOR = 0 turns off controller + motor */
+	outb(FDC_DOR, 0x00);
+	motor_on = 0;
+	{
+		unsigned int t0 = get_ticks_ms();
+		while ((get_ticks_ms() - t0) < 10)
+			;
+	}
+
+	/* Release reset: controller on, DMA/IRQ enabled, no motor.
+	 * The FDC fires IRQ 6 once the reset completes. */
+	fdc_irq_fired = 0;
+	outb(FDC_DOR, (unsigned char)(0x0C | current_drive));
+
+	if (fdc_wait_irq() != 0)
+		return -1;
+
+	for (i = 0; i < 4; i++)
+		fdc_sense_interrupt(&st0, &cyl);
+
+	outb(FDC_CCR, 0x00); /* 500 kbps for 1.44 MB */
+
+	/* SPECIFY: SRT=3ms, HUT=240ms, HLT=16ms, DMA mode */
+	if (fdc_send(CMD_SPECIFY) != 0)
+		return -1;
+	if (fdc_send(0xDF) != 0)
+		return -1;
+	if (fdc_send(0x02) != 0)
+		return -1;
+
+	return 0;
+}
+
+static int fdc_recalibrate(void)
+{
+	unsigned char st0, cyl;
+
+	fdc_irq_fired = 0;
+	if (fdc_send(CMD_RECALIBRATE) != 0)
+		return -1;
+	if (fdc_send((unsigned char)current_drive) != 0)
+		return -1;
+
+	if (fdc_wait_irq() != 0)
+		return -1;
+	if (fdc_sense_interrupt(&st0, &cyl) != 0)
+		return -1;
+	if (st0 & 0xC0)
+		return -1;
+
+	cur_cylinder = 0;
+	return 0;
+}
+
+static int fdc_seek(unsigned int cylinder, unsigned int head)
+{
+	unsigned char st0, cyl;
+
+	fdc_irq_fired = 0;
+	if (fdc_send(CMD_SEEK) != 0)
+		return -1;
+	if (fdc_send((unsigned char)((head << 2) | current_drive)) != 0)
+		return -1;
+	if (fdc_send((unsigned char)cylinder) != 0)
+		return -1;
+
+	if (fdc_wait_irq() != 0)
+		return -1;
+	if (fdc_sense_interrupt(&st0, &cyl) != 0)
+		return -1;
+	if ((st0 & 0xC0) || cyl != (unsigned char)cylinder)
+		return -1;
+
+	cur_cylinder = cylinder;
+	return 0;
+}
+
+/* ---- DMA channel 2 setup ---- */
+
+static void dma_setup_read(unsigned int phys, unsigned int len)
+{
+	unsigned int count = len - 1;
+
+	outb(DMA_SINGLEMASK, 0x06);        /* mask channel 2 */
+	outb(DMA_FLIPFLOP, 0xFF);         /* reset flip-flop */
+	outb(DMA_CH2_ADDR, (unsigned char)(phys & 0xFF));
+	outb(DMA_CH2_ADDR, (unsigned char)((phys >> 8) & 0xFF));
+	outb(DMA_CH2_PAGE, (unsigned char)((phys >> 16) & 0xFF));
+	outb(DMA_FLIPFLOP, 0xFF);         /* reset flip-flop */
+	outb(DMA_CH2_COUNT, (unsigned char)(count & 0xFF));
+	outb(DMA_CH2_COUNT, (unsigned char)((count >> 8) & 0xFF));
+	outb(DMA_MODE, 0x46);             /* single, increment, write, ch2 */
+	outb(DMA_SINGLEMASK, 0x02);        /* unmask channel 2 */
+}
+
+/* ---- read one sector ---- */
+
+static void lba_to_chs(unsigned int lba,
+			unsigned int *cyl, unsigned int *head, unsigned int *sec)
+{
+	unsigned int tmp = lba / SECTORS_PER_TRACK;
+	*sec  = (lba % SECTORS_PER_TRACK) + 1;
+	*head = tmp % HEADS;
+	*cyl  = tmp / HEADS;
+}
+
+static int fdc_do_read(unsigned int cyl, unsigned int head, unsigned int sec)
+{
+	unsigned char results[7];
+	int i;
+
+	dma_setup_read(DMA_BUF_ADDR, SECTOR_SIZE);
+
+	fdc_irq_fired = 0;
+
+	if (fdc_send(CMD_READ_DATA) != 0)   return -1;
+	if (fdc_send((unsigned char)((head << 2) | current_drive)) != 0) return -1;
+	if (fdc_send((unsigned char)cyl) != 0)  return -1;
+	if (fdc_send((unsigned char)head) != 0) return -1;
+	if (fdc_send((unsigned char)sec) != 0)  return -1;
+	if (fdc_send(0x02) != 0)            return -1; /* 512 bytes/sector */
+	if (fdc_send((unsigned char)SECTORS_PER_TRACK) != 0) return -1;
+	if (fdc_send(0x1B) != 0)            return -1; /* gap3 */
+	if (fdc_send(0xFF) != 0)            return -1; /* data length */
+
+	if (fdc_wait_irq() != 0)
+		return -1;
+
+	for (i = 0; i < 7; i++) {
+		if (fdc_recv(&results[i]) != 0)
+			return -1;
+	}
+
+	if (results[0] & 0xC0)
+		return -1;
+
+	return 0;
+}
+
+static int fdc_read_one(unsigned int lba)
+{
+	unsigned int cyl, head, sec;
+
+	lba_to_chs(lba, &cyl, &head, &sec);
+
+	if (cyl != cur_cylinder) {
+		if (fdc_seek(cyl, head) != 0)
+			return -1;
+	}
+
+	return fdc_do_read(cyl, head, sec);
+}
+
+/* ---- public API ---- */
+
+static int fdc_init_once(void)
+{
+	/* Reset the FDC first (clears any pending interrupt state left by BIOS).
+	 * IRQ 6 is still masked at this point so no spurious interrupts. */
+	outb(FDC_DOR, 0x00);
+	motor_on = 0;
+	{
+		unsigned int t0 = get_ticks_ms();
+		while ((get_ticks_ms() - t0) < 10)
+			;
+	}
+	outb(FDC_DOR, (unsigned char)(0x0C | current_drive));
+
+	/* Now that the FDC is in a clean state, unmask IRQ 6 at the PIC.
+	 * The reset completion interrupt is latched and fires immediately. */
+	fdc_irq_fired = 0;
+	outb(PIC1_DATA, inb(PIC1_DATA) & ~0x40);
+
+	if (fdc_wait_irq() != 0)
+		return -1;
+
+	{
+		unsigned char st0, cyl;
+		int i;
+		for (i = 0; i < 4; i++)
+			fdc_sense_interrupt(&st0, &cyl);
+
+		outb(FDC_CCR, 0x00);
+
+		if (fdc_send(CMD_SPECIFY) != 0)
+			return -1;
+		if (fdc_send(0xDF) != 0)
+			return -1;
+		if (fdc_send(0x02) != 0)
+			return -1;
+	}
+
+	fdc_motor_on();
+	if (fdc_recalibrate() != 0)
+		return -1;
+
+	fdc_initialized = 1;
+	return 0;
+}
+
+void disk_set_drive(unsigned int drive)
+{
+	if (drive > 1)
+		return;
+	if (drive == current_drive && fdc_initialized)
+		return;
+	current_drive = drive;
+	motor_on = 0;
+	fdc_initialized = 0;
+}
+
+unsigned int disk_get_drive(void)
+{
+	return current_drive;
+}
+
+int disk_read_sectors(unsigned int lba, void *buf, unsigned int count)
+{
+	unsigned int i;
+
+	if (!fdc_initialized) {
+		if (fdc_init_once() != 0)
+			return -1;
+	}
+
+	for (i = 0; i < count; i++) {
+		int attempt, ok = 0;
+		for (attempt = 0; attempt < MAX_RETRIES; attempt++) {
+			if (fdc_read_one(lba + i) == 0) {
+				ok = 1;
+				break;
+			}
+			fdc_reset();
+			fdc_motor_on();
+			fdc_recalibrate();
+		}
+		if (!ok)
+			return -1;
+		{
+			unsigned int j;
+			unsigned char *dst = (unsigned char *)buf + (i * SECTOR_SIZE);
+			const unsigned char *src = (const unsigned char *)DMA_BUF_ADDR;
+			for (j = 0; j < SECTOR_SIZE; j++)
+				dst[j] = src[j];
+		}
+	}
+	return 0;
+}

+ 17 - 0
disk.h

@@ -0,0 +1,17 @@
+/* Disk layer: read sectors via direct FDC + ISA DMA in protected mode. */
+
+#ifndef DISK_H
+#define DISK_H
+
+/* Select the floppy drive (0 or 1) used by subsequent disk_read_sectors calls.
+ * Resets FDC state so the next read re-initialises for the new drive. */
+void disk_set_drive(unsigned int drive);
+
+/* Return currently selected drive number. */
+unsigned int disk_get_drive(void);
+
+/* Read count sectors starting at lba into buf.
+ * Returns 0 on success, -1 on error. */
+int disk_read_sectors(unsigned int lba, void *buf, unsigned int count);
+
+#endif

+ 180 - 0
fat.c

@@ -0,0 +1,180 @@
+/* FAT12 read-only: BPB parse, root list, read file by following FAT chain. */
+
+#include "disk.h"
+#include "fat.h"
+
+#define SECTOR_SIZE 512
+#define ROOT_ENTRY_SIZE 32
+#define FAT12_EOC_MIN 0xFF8
+
+/* BPB offsets (same for FAT12 1.44MB floppy) */
+#define BPB_BYTES_PER_SEC   0x0B
+#define BPB_SEC_PER_CLUSTER 0x0D
+#define BPB_RESERVED        0x0E
+#define BPB_NUM_FATS        0x10
+#define BPB_ROOT_ENTRIES    0x11
+#define BPB_SEC_PER_FAT     0x16
+
+static unsigned int fat_reserved;
+static unsigned int fat_root_start;
+static unsigned int fat_root_sectors;
+static unsigned int fat_data_start;
+static unsigned int fat_sec_per_cluster;
+static int fat_ready;
+
+static unsigned char sector_buf[SECTOR_SIZE];
+
+static int fat_read_sector(unsigned int lba)
+{
+	if (disk_read_sectors(lba, sector_buf, 1) != 0)
+		return -1;
+	return 0;
+}
+
+/* Get 12-bit FAT entry at cluster index. FAT is in sector_buf (one sector). */
+static unsigned int fat_get_entry(unsigned int cluster_idx)
+{
+	unsigned int byte_off = (cluster_idx * 3) / 2;
+	unsigned int word_val;
+	if (byte_off + 2 > SECTOR_SIZE)
+		return 0xFFFF;
+	word_val = (unsigned int)sector_buf[byte_off] | ((unsigned int)sector_buf[byte_off + 1] << 8);
+	if (cluster_idx & 1)
+		return word_val >> 4;
+	return word_val & 0xFFF;
+}
+
+int fat_init(void)
+{
+	unsigned int num_fats, root_entries, sec_per_fat;
+
+	if (fat_read_sector(0) != 0)
+		return -1;
+	fat_reserved = (unsigned int)sector_buf[BPB_RESERVED] | ((unsigned int)sector_buf[BPB_RESERVED + 1] << 8);
+	num_fats = sector_buf[BPB_NUM_FATS];
+	root_entries = (unsigned int)sector_buf[BPB_ROOT_ENTRIES] | ((unsigned int)sector_buf[BPB_ROOT_ENTRIES + 1] << 8);
+	sec_per_fat = (unsigned int)sector_buf[BPB_SEC_PER_FAT] | ((unsigned int)sector_buf[BPB_SEC_PER_FAT + 1] << 8);
+	fat_sec_per_cluster = sector_buf[BPB_SEC_PER_CLUSTER];
+
+	fat_root_start = fat_reserved + num_fats * sec_per_fat;
+	fat_root_sectors = (root_entries * ROOT_ENTRY_SIZE + SECTOR_SIZE - 1) / SECTOR_SIZE;
+	fat_data_start = fat_root_start + fat_root_sectors;
+	fat_ready = 1;
+	return 0;
+}
+
+static void trim_name_8_3(const char *in, char *out)
+{
+	unsigned int i;
+	for (i = 0; i < 8 && in[i] && in[i] != ' '; i++)
+		out[i] = (char)(in[i] >= 'a' && in[i] <= 'z' ? in[i] - 32 : in[i]);
+	for (; i < 8; i++)
+		out[i] = ' ';
+	for (i = 0; i < 3 && in[8 + i] && in[8 + i] != ' '; i++)
+		out[8 + i] = (char)(in[8 + i] >= 'a' && in[8 + i] <= 'z' ? in[8 + i] - 32 : in[8 + i]);
+	for (; i < 3; i++)
+		out[8 + i] = ' ';
+	out[11] = '\0';
+}
+
+int fat_list_root(fat_root_callback_t callback)
+{
+	unsigned int sec, off;
+	char name_buf[12];
+
+	if (!fat_ready || !callback)
+		return -1;
+	for (sec = 0; sec < fat_root_sectors; sec++) {
+		if (fat_read_sector(fat_root_start + sec) != 0)
+			return -2;
+		for (off = 0; off < SECTOR_SIZE; off += ROOT_ENTRY_SIZE) {
+			unsigned char *e = sector_buf + off;
+			if (e[0] == 0x00)
+				return 0;
+			if (e[0] == 0xE5)
+				continue;
+			if ((e[11] & 0x18) == 0x08)
+				continue;
+			trim_name_8_3((const char *)e, name_buf);
+			{
+				unsigned int size = (unsigned int)e[28] | ((unsigned int)e[29] << 8) |
+					((unsigned int)e[30] << 16) | ((unsigned int)e[31] << 24);
+				(*callback)(name_buf, (e[11] & 0x10) ? 1 : 0, size);
+			}
+		}
+	}
+	return 0;
+}
+
+/* Find root entry by 8.3 name; return first cluster and size, or -1. */
+static int fat_find_root(const char *name_8_3, unsigned int *out_cluster, unsigned int *out_size)
+{
+	unsigned int sec, off;
+	char want[12];
+	unsigned int i;
+
+	for (i = 0; i < 11; i++)
+		want[i] = (char)(name_8_3[i] >= 'a' && name_8_3[i] <= 'z' ? name_8_3[i] - 32 : name_8_3[i]);
+	want[11] = '\0';
+
+	for (sec = 0; sec < fat_root_sectors; sec++) {
+		if (fat_read_sector(fat_root_start + sec) != 0)
+			return -2;
+		for (off = 0; off < SECTOR_SIZE; off += ROOT_ENTRY_SIZE) {
+			unsigned char *e = sector_buf + off;
+			if (e[0] == 0x00)
+				return -1;
+			if (e[0] == 0xE5 || (e[11] & 0x10))
+				continue;
+			for (i = 0; i < 11; i++)
+				if ((e[i] >= 'a' ? e[i] - 32 : e[i]) != (unsigned char)want[i])
+					break;
+			if (i < 11)
+				continue;
+			*out_cluster = (unsigned int)e[26] | ((unsigned int)e[27] << 8);
+			*out_size = (unsigned int)e[28] | ((unsigned int)e[29] << 8) |
+				((unsigned int)e[30] << 16) | ((unsigned int)e[31] << 24);
+			return 0;
+		}
+	}
+	return -1;
+}
+
+int fat_read_file(const char *name_8_3, void *buf, unsigned int max_len)
+{
+	unsigned int cluster, size;
+	unsigned int fat_start = fat_reserved;
+	unsigned int copied = 0;
+	unsigned char *dst = (unsigned char *)buf;
+
+	if (!fat_ready || !buf)
+		return -1;
+	{
+		int fr = fat_find_root(name_8_3, &cluster, &size);
+		if (fr == -2)
+			return -2;
+		if (fr != 0)
+			return -1;
+	}
+	if (size > max_len)
+		size = max_len;
+
+	while (cluster >= 2 && cluster < 0xFF8 && copied < size) {
+		unsigned int sector = fat_data_start + (cluster - 2) * fat_sec_per_cluster;
+		unsigned int chunk = fat_sec_per_cluster * SECTOR_SIZE;
+		unsigned int n_sec;
+		if (chunk > size - copied)
+			chunk = size - copied;
+		n_sec = (chunk + SECTOR_SIZE - 1) / SECTOR_SIZE;
+		if (disk_read_sectors(sector, dst + copied, n_sec) != 0)
+			return -2;
+		copied += chunk;
+		if (copied >= size)
+			break;
+		/* Next cluster from FAT */
+		if (fat_read_sector(fat_start + (cluster * 3) / (2 * SECTOR_SIZE)) != 0)
+			return -2;
+		cluster = fat_get_entry(cluster);
+	}
+	return (int)copied;
+}

+ 21 - 0
fat.h

@@ -0,0 +1,21 @@
+/* FAT12 read-only filesystem. Root directory only.
+ * Error conventions:  0 = success, -1 = not found / not ready, -2 = disk I/O error. */
+
+#ifndef FAT_H
+#define FAT_H
+
+typedef void (*fat_root_callback_t)(const char *name, int is_dir, unsigned int size);
+
+/* Parse BPB from sector 0. Call once before list/read.
+ * Returns 0 on success, -1 on error. */
+int fat_init(void);
+
+/* Iterate root directory, call callback for each file/dir.
+ * Returns 0 on success, -1 if not ready, -2 on disk I/O error. */
+int fat_list_root(fat_root_callback_t callback);
+
+/* Read file by 8.3 name into buf, max max_len bytes.
+ * Returns bytes read on success, -1 if not found, -2 on disk I/O error. */
+int fat_read_file(const char *name_8_3, void *buf, unsigned int max_len);
+
+#endif

+ 39 - 16
io.c

@@ -47,6 +47,30 @@ static unsigned short cursor_cell;
 static unsigned char last_scancode;
 static int scroll_occurred;
 
+#define KBD_BUF_SIZE 16
+static volatile unsigned char kbd_buf[KBD_BUF_SIZE];
+static volatile unsigned int kbd_head, kbd_tail;
+
+void kbd_irq(void)
+{
+	unsigned char sc = inb(KB_DATA);
+	unsigned int next = (kbd_head + 1) % KBD_BUF_SIZE;
+	if (next != kbd_tail) {
+		kbd_buf[kbd_head] = sc;
+		kbd_head = next;
+	}
+	outb(0x20, 0x20);
+}
+
+static int kbd_buf_get(unsigned char *sc)
+{
+	if (kbd_tail == kbd_head)
+		return 0;
+	*sc = kbd_buf[kbd_tail];
+	kbd_tail = (kbd_tail + 1) % KBD_BUF_SIZE;
+	return 1;
+}
+
 static char apply_shift(char c)
 {
 	if (!shift_pressed) return c;
@@ -155,28 +179,27 @@ void io_drain_keyboard(void)
 {
 	while (inb(KB_STATUS) & 1)
 		(void)inb(KB_DATA);
+	kbd_head = kbd_tail = 0;
 }
 
 char io_poll_key(void)
 {
-	if (!(inb(KB_STATUS) & 1))
+	unsigned char sc;
+	if (!kbd_buf_get(&sc))
+		return 0;
+	if (sc & 0x80) {
+		if (sc == 0xAA || sc == 0xB6) shift_pressed = 0;
+		return 0;
+	}
+	if (sc == 0x2A || sc == 0x36) {
+		shift_pressed = 1;
 		return 0;
+	}
 	{
-		unsigned char sc = inb(KB_DATA);
-		if (sc & 0x80) {
-			if (sc == 0xAA || sc == 0xB6) shift_pressed = 0;
-			return 0;
-		}
-		if (sc == 0x2A || sc == 0x36) {
-			shift_pressed = 1;
-			return 0;
-		}
-		{
-			char c = (char)scancode_to_ascii[sc];
-			if (c) {
-				last_scancode = sc;
-				return apply_shift(c);
-			}
+		char c = (char)scancode_to_ascii[sc];
+		if (c) {
+			last_scancode = sc;
+			return apply_shift(c);
 		}
 	}
 	return 0;

+ 55 - 7
kernel.c

@@ -28,6 +28,10 @@ static struct idt_entry idt[256];
 static struct idtr_desc idtr;
 
 extern void pit_irq_stub(void);
+extern void kbd_irq_stub(void);
+extern void fdc_irq_stub(void);
+extern void default_irq_stub(void);
+extern unsigned int exc_stub_table[];
 
 void pit_irq(void);
 
@@ -42,10 +46,46 @@ unsigned int get_ticks_ms(void)
 	return ticks;
 }
 
+void exc_handler(unsigned int vector);
+void exc_handler(unsigned int vector)
+{
+	static const char * const names[] = {
+		"#DE Divide Error", "#DB Debug", "NMI", "#BP Breakpoint",
+		"#OF Overflow", "#BR Bound Range", "#UD Invalid Opcode",
+		"#NM No FPU", "#DF Double Fault", "Coprocessor Overrun",
+		"#TS Invalid TSS", "#NP Seg Not Present", "#SS Stack Fault",
+		"#GP General Protection", "#PF Page Fault", "Reserved",
+		"#MF FPU Error", "#AC Alignment Check", "#MC Machine Check",
+		"#XM SIMD Error",
+	};
+	io_putstr("\n*** EXCEPTION: ");
+	if (vector < 20)
+		io_putstr(names[vector]);
+	else {
+		io_putstr("vector ");
+		if (vector >= 10)
+			io_putchar((char)('0' + vector / 10));
+		io_putchar((char)('0' + vector % 10));
+	}
+	io_putstr(" ***\nSystem halted.\n");
+	for (;;)
+		__asm__ volatile ("cli; hlt");
+}
+
+static void set_idt_gate(int vec, unsigned int handler)
+{
+	idt[vec].offset_lo = (unsigned short)(handler & 0xFFFF);
+	idt[vec].selector  = 0x08;
+	idt[vec].zero      = 0;
+	idt[vec].type      = 0x8E;
+	idt[vec].offset_hi = (unsigned short)((handler >> 16) & 0xFFFF);
+}
+
 static void timer_init(void)
 {
-	unsigned int stub = (unsigned int)pit_irq_stub;
+	int i;
 
+	/* Remap PICs: master at 0x20, slave at 0x28. */
 	outb(0x20, 0x11);
 	outb(0xA0, 0x11);
 	outb(0x21, 0x20);
@@ -54,14 +94,22 @@ static void timer_init(void)
 	outb(0xA1, 0x02);
 	outb(0x21, 0x01);
 	outb(0xA1, 0x01);
-	outb(0x21, 0xFE);
+	outb(0x21, 0xFC);
 	outb(0xA1, 0xFF);
 
-	idt[0x20].offset_lo = (unsigned short)(stub & 0xFFFF);
-	idt[0x20].selector  = 0x08;
-	idt[0x20].zero      = 0;
-	idt[0x20].type      = 0x8E;
-	idt[0x20].offset_hi = (unsigned short)((stub >> 16) & 0xFFFF);
+	/* Default handler for all 256 vectors: absorbs any unexpected
+	   interrupt (including spurious IRQ 7) with an EOI + iret. */
+	for (i = 0; i < 256; i++)
+		set_idt_gate(i, (unsigned int)default_irq_stub);
+
+	/* Exception handlers 0-31: print the fault name and halt. */
+	for (i = 0; i < 32; i++)
+		set_idt_gate(i, exc_stub_table[i]);
+
+	/* Hardware IRQ handlers. */
+	set_idt_gate(0x20, (unsigned int)pit_irq_stub);
+	set_idt_gate(0x21, (unsigned int)kbd_irq_stub);
+	set_idt_gate(0x26, (unsigned int)fdc_irq_stub);
 
 	idtr.limit = (unsigned short)(sizeof(idt) - 1);
 	idtr.base  = (unsigned int)idt;

+ 54 - 0
ls.c

@@ -0,0 +1,54 @@
+/* ls command: list root directory of FAT12 floppy. */
+
+#include "fat.h"
+#include "io.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;
+
+	(void)is_dir;
+	for (i = 0; i < 11 && name[i]; i++)
+		io_putchar(name[i] == ' ' ? ' ' : name[i]);
+	if (i < 11)
+		io_putchar(' ');
+	io_putstr(" ");
+	/* Simple decimal print for size */
+	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(void)
+{
+	int r;
+
+	if (fat_init() != 0) {
+		io_putstr("ls: fat init failed\n");
+		return;
+	}
+	r = fat_list_root(list_cb);
+	if (r == -2) {
+		io_putstr("ls: disk read error\n");
+		return;
+	}
+	if (r != 0) {
+		io_putstr("ls: list failed\n");
+		return;
+	}
+}

+ 77 - 0
terminal.c

@@ -6,6 +6,10 @@
 #include "timer.h"
 
 extern void program_hello_main(void);
+extern void program_ls_main(void);
+extern void program_cat_main(const char *filename);
+extern void disk_set_drive(unsigned int drive);
+extern unsigned int disk_get_drive(void);
 
 #define DATETIME_MS 1000
 #define LINE_MAX 64
@@ -79,6 +83,64 @@ static int is_cmd_hello(const char *line, unsigned int line_len)
 	return (i == line_len);
 }
 
+static int is_cmd_ls(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 2 > line_len)
+		return 0;
+	if (line[i] != 'l' || line[i+1] != 's')
+		return 0;
+	i += 2;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
+#define CAT_FNAME_MAX 64
+static int is_cmd_cat(const char *line, unsigned int line_len, char *filename_buf, unsigned int buf_size)
+{
+	unsigned int i = 0, j;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 3 > line_len)
+		return 0;
+	if (line[i] != 'c' || line[i+1] != 'a' || line[i+2] != 't')
+		return 0;
+	i += 3;
+	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)
+		filename_buf[j++] = line[i++];
+	filename_buf[j] = '\0';
+	return (j > 0);
+}
+
+static int is_cmd_drive(const char *line, unsigned int line_len, unsigned int *drive_num)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 5 > line_len)
+		return 0;
+	if (line[i] != 'd' || line[i+1] != 'r' || line[i+2] != 'i' || line[i+3] != 'v' || line[i+4] != 'e')
+		return 0;
+	i += 5;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i >= line_len || line[i] < '0' || line[i] > '1')
+		return 0;
+	*drive_num = (unsigned int)(line[i] - '0');
+	i++;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
 void terminal_run(void)
 {
 	static char line[LINE_MAX];
@@ -107,11 +169,26 @@ void terminal_run(void)
 						io_putchar(c);
 					}
 				} else if (c == '\n') {
+					static char cat_fname[CAT_FNAME_MAX];
+					unsigned int drive_sel;
 					io_putchar(c);
 					if (is_cmd_hello(line, line_len)) {
 						program_hello_main();
 						io_drain_keyboard();
 						draw_header_row();
+					} else if (is_cmd_ls(line, line_len)) {
+						program_ls_main();
+						io_drain_keyboard();
+						draw_header_row();
+					} else if (is_cmd_cat(line, line_len, cat_fname, CAT_FNAME_MAX)) {
+						program_cat_main(cat_fname);
+						io_drain_keyboard();
+						draw_header_row();
+					} else if (is_cmd_drive(line, line_len, &drive_sel)) {
+						disk_set_drive(drive_sel);
+						io_putstr("drive ");
+						io_putchar((char)('0' + disk_get_drive()));
+						io_putstr(" selected\n");
 					}
 					line_len = 0;
 					line[0]  = '\0';

+ 93 - 1
timer.S

@@ -1,4 +1,4 @@
-/* PIT IRQ0 stub: save state, call C handler, restore, iret. */
+/* IRQ stubs: save state, call C handler, restore, iret. */
 .code32
 .text
 
@@ -8,3 +8,95 @@ pit_irq_stub:
 	call  pit_irq
 	popa
 	iret
+
+.globl kbd_irq_stub
+kbd_irq_stub:
+	pusha
+	call  kbd_irq
+	popa
+	iret
+
+.globl fdc_irq_stub
+fdc_irq_stub:
+	pusha
+	call  fdc_irq
+	popa
+	iret
+
+/* Default IRQ handler: send EOI and return.  Catches spurious and
+   unexpected hardware interrupts that would otherwise triple-fault. */
+.globl default_irq_stub
+default_irq_stub:
+	pushl %eax
+	movb  $0x20, %al
+	outb  %al, $0x20
+	popl  %eax
+	iret
+
+/* CPU exception stubs (vectors 0-31).  The handler never returns,
+   so we don't need to preserve the full frame for iret. */
+
+.macro exc_no_err vec
+exc_stub_\vec:
+	pushl $\vec
+	jmp   exc_common
+.endm
+
+.macro exc_err vec
+exc_stub_\vec:
+	addl  $4, %esp
+	pushl $\vec
+	jmp   exc_common
+.endm
+
+exc_no_err 0
+exc_no_err 1
+exc_no_err 2
+exc_no_err 3
+exc_no_err 4
+exc_no_err 5
+exc_no_err 6
+exc_no_err 7
+exc_err    8
+exc_no_err 9
+exc_err    10
+exc_err    11
+exc_err    12
+exc_err    13
+exc_err    14
+exc_no_err 15
+exc_no_err 16
+exc_err    17
+exc_no_err 18
+exc_no_err 19
+exc_no_err 20
+exc_no_err 21
+exc_no_err 22
+exc_no_err 23
+exc_no_err 24
+exc_no_err 25
+exc_no_err 26
+exc_no_err 27
+exc_no_err 28
+exc_no_err 29
+exc_no_err 30
+exc_no_err 31
+
+exc_common:
+	call  exc_handler
+	cli
+1:	hlt
+	jmp   1b
+
+/* Lookup table so C can iterate over the 32 stubs. */
+.section .rodata
+.globl exc_stub_table
+exc_stub_table:
+	.long exc_stub_0,  exc_stub_1,  exc_stub_2,  exc_stub_3
+	.long exc_stub_4,  exc_stub_5,  exc_stub_6,  exc_stub_7
+	.long exc_stub_8,  exc_stub_9,  exc_stub_10, exc_stub_11
+	.long exc_stub_12, exc_stub_13, exc_stub_14, exc_stub_15
+	.long exc_stub_16, exc_stub_17, exc_stub_18, exc_stub_19
+	.long exc_stub_20, exc_stub_21, exc_stub_22, exc_stub_23
+	.long exc_stub_24, exc_stub_25, exc_stub_26, exc_stub_27
+	.long exc_stub_28, exc_stub_29, exc_stub_30, exc_stub_31