Explorar el Código

Add kmalloc and memory pagination

Johannes Zellner hace 1 mes
padre
commit
b382dc771c
Se han modificado 16 ficheros con 866 adiciones y 66 borrados
  1. 26 11
      AGENTS.md
  2. 15 3
      Makefile
  3. 7 0
      kernel.c
  4. 10 0
      kexec_tramp.S
  5. 115 0
      kmalloc.c
  6. 18 0
      kmalloc.h
  7. 56 0
      mem.c
  8. 243 0
      mm.c
  9. 68 0
      mm.h
  10. 67 0
      paging.c
  11. 7 0
      paging.h
  12. 164 42
      process.c
  13. 10 4
      process.h
  14. 6 6
      switch.S
  15. 19 0
      terminal.c
  16. 35 0
      vesa_stage.S

+ 26 - 11
AGENTS.md

@@ -25,9 +25,9 @@ make clean
 
 1. `boot.S` — 512-byte boot sector (FAT16 BPB). Loads contiguous kernel sectors
    to `0x7E00` (CHS for floppy, INT 13h AH=42h LBA for hard disk), jumps there.
-2. `vesa_stage.S` — real-mode VESA stage. Picks best VBE mode (≥16 bpp, LFB, fits
-   VRAM, ≤1280px), writes mode info to `0x600`, enables A20, enters protected mode,
-   jumps to `kernel_main`.
+2. `vesa_stage.S` — real-mode VESA stage. Probes INT 15h E820 into `0x1000`,
+   picks best VBE mode (≥16 bpp, LFB, fits VRAM, ≤1280px), writes mode info to
+   `0x600`, enables A20, enters protected mode, jumps to `kernel_main`.
 3. `kernel.c` — `kernel_main` zeroes BSS then inits serial → I/O → idle → timer
    (PIT 1 kHz + IDT) → mouse → processes → VGA shadow buffer → terminal.
 4. `mbr.S` — MBR (USB/HDD boot); loads partition boot sector at LBA 1.
@@ -41,22 +41,36 @@ make clean
 | `0x7E00`  | Kernel load / VESA-stage entry (`kernel.ld`) |
 | `0x800`   | kexec trampoline (relocated at runtime; below the kernel) |
 | `0x900`   | kexec flat GDT + GDTR (built at runtime; below the kernel) |
+| `0x1000`  | E820 memory map (`struct e820_map`, written by `vesa_stage.S`, parsed by `mm.c`) |
 | `0x3000`  | UHCI frame list (1024 × 4 B, 4 KB-aligned; `uhci.c`) |
 | `0x20000` | (free — kernel upper bound used to be here, now `0x30000`) |
 | `0x30000` | ISA DMA buffer (`disk.c`) + kernel upper bound (`kernel.ld` ASSERT) |
 | `0x30800` | Protected-mode stack top (`vesa_stage.S`) |
 | `0x30F00` | Program API struct (`PROGRAM_API_ADDR`, `run_api.h`) |
 | `0x31000` | User program load address (`run.c`, `user.ld`) |
-| `0x42000` | Process stack base (`PROC_STACK_BASE`, 4 KB × 8, `process.h`) |
+| `0x42000` | Fallback process stack pool (8 × 4 KB; primary stacks come from the frame allocator, ≥ `0x900000`, see `process.c`/`mm.c`) |
 | `0x50000` | kexec staging buffer (received kernel image, up to 0x28200 B) |
 | `0x100000`| VGA shadow buffer (`VGA_SHADOW_BASE`, `vga.h`) |
 
 ## Key files
 
 - **Multitasking**: `process.c/h`, `switch.S` — ring-0 preemptive round-robin,
-  8 slots, 20 ms timeslice, `ps`/`kill`. Context switch happens in the PIT stub.
-  Each process carries a `struct text_screen *screen` output target (child
-  processes inherit it, so command output lands in the owning terminal).
+  dynamically-sized process table (kmalloc'd, grows on demand), 20 ms timeslice,
+  `ps`/`kill`. Context switch happens in the PIT stub. Each process carries a
+  `struct text_screen *screen` output target (child processes inherit it, so
+  command output lands in the owning terminal). Exited processes are reaped and
+  their stacks freed by the scheduler.
+- **Memory**: `mm.c/h` — INT 15h E820 detection (real-mode in `vesa_stage.S`,
+  map at `0x1000`) + a bitmap page-frame allocator (4 KB pages). Reserves low
+  1 MB and an 8 MB VGA-shadow region. `kmalloc.c/h` — a power-of-two heap
+  allocator on top of the frame allocator (used for the process table). Process
+  stacks (≥ `0x900000`) come from the frame allocator, with an 8-stack fallback
+  pool at `0x42000`.
+- **Paging**: `paging.c/h` — identity-maps RAM (4 MB pages via CR4.PSE) + the
+  LFB (uncacheable) and enables CR0.PG/WP. A single shared page directory for
+  now (no per-process address spaces yet). The kexec trampoline
+  (`kexec_tramp.S`) clears CR0.PG before the copy so it can overwrite the old
+  kernel's page tables safely.
 - **Window manager**: `wm.c/h` — slot 0 runs `wm_run()`; fixed-size draggable
   terminal windows (64×20) with a system bar (banner + purple "+ New" button +
   clock + rainbow). Click-to-focus, drag-by-title-bar, close (×). The "+ New"
@@ -89,7 +103,7 @@ make clean
 
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <file>`, `space`,
-`clock`, `colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `storage`, `format <device>`,
+`clock`, `colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `storage`, `mem`, `format <device>`,
 `ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
 
 Each terminal has a current working directory (shown in the prompt as `[dir] > `),
@@ -208,8 +222,9 @@ QEMU gotchas that bit once:
 
 - **Freestanding C** — no libc, no `malloc`, no `printf`. Use `io_putstr` /
   `io_putchar` / `io_puthex` (`io.h`). Printing is VGA-framebuffer based.
-- **No paging / no MMU / no process isolation.** Everything runs ring-0; user
-  programs share the kernel's address space and privileges.
+- **Paging is on but flat** — identity-mapped 4 MB pages (`paging.c`), so
+  physical == virtual everywhere. Still no per-process address spaces or process
+  isolation: everything runs ring-0 and shares the address space.
 - **All drawing goes into the shadow buffer** (`vga_put_pixel_rgb` etc.); a 30 Hz
   flush copies dirty rows to VRAM. Full-screen programs call `vga_clear_rgb`.
 - **FAT is read-only** — parse/read only; no write/create/delete.
@@ -222,7 +237,7 @@ QEMU gotchas that bit once:
    missing** (bug).
 2. `vga.c` `draw_flush_debug_square()` — leftover debug artifact, still draws a
    color-cycling 32×32 square in the corner on every flush.
-3. No paging/virtual memory or process isolation.
+3. No per-process address spaces or process isolation (paging is identity-mapped).
 4. Read-only FAT filesystem.
 5. Implicit, hardcoded memory map (see table above).
 6. `disk.c` `fdc_reset()` and `fdc_init_once()` overlap/duplicate logic.

+ 15 - 3
Makefile

@@ -197,10 +197,22 @@ timer.o: timer.S
 switch.o: switch.S
 	$(AS) $(ASFLAGS) -o $@ $<
 
-process.o: process.c process.h io.h
+process.o: process.c process.h io.h kmalloc.h mm.h serial.h idle.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o screen.o io.o rtc.o terminal.o wm.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 cirrus.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 vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o ne2000.o netcmd.o net.o
+mm.o: mm.c mm.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+kmalloc.o: kmalloc.c kmalloc.h mm.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+paging.o: paging.c paging.h mm.h vga.h serial.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+mem.o: mem.c mm.h io.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o mem.o screen.o io.o rtc.o terminal.o wm.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 cirrus.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 vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o ne2000.o netcmd.o net.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -349,4 +361,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 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 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 vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o ne2000.o netcmd.o net.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 mm.o kmalloc.o paging.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 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 vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o ne2000.o netcmd.o net.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

+ 7 - 0
kernel.c

@@ -2,7 +2,10 @@
 
 #include "idle.h"
 #include "io.h"
+#include "kmalloc.h"
+#include "mm.h"
 #include "mouse.h"
+#include "paging.h"
 #include "process.h"
 #include "timer.h"
 #include "wm.h"
@@ -133,6 +136,10 @@ void kernel_main(void)
 	serial_init(SERIAL_COM1);
 	serial_ring_init();
 	serial_puts(SERIAL_COM1, "\n" OS_NAME " v" OS_VERSION " booted\n");
+	mm_init();
+	mm_dump();
+	kmalloc_init();
+	paging_init();
 	io_init();
 	idle_init();
 	timer_init();

+ 10 - 0
kexec_tramp.S

@@ -23,6 +23,16 @@ kexec_trampoline:
 	pushl %ecx
 	pushl %edx
 
+	/* Disable paging so the copy below can overwrite the old kernel's page
+	 * tables (which live inside the kernel region we overwrite) without
+	 * faulting.  We are identity-mapped, so the fetch after clearing PG is
+	 * safe; the jump flushes the prefetch queue. */
+	movl  %cr0, %eax
+	andl  $0x7FFFFFFF, %eax   /* clear CR0.PG */
+	movl  %eax, %cr0
+	jmp   1f
+1:
+
 	/* Mask all IRQs. */
 	movb  $0xFF, %al
 	outb  %al, $0x21

+ 115 - 0
kmalloc.c

@@ -0,0 +1,115 @@
+/* Kernel heap allocator: power-of-two segregated free lists over mm.c. */
+
+#include "kmalloc.h"
+#include "mm.h"
+
+#define KMALLOC_MIN     16      /* smallest block (bytes) */
+#define KMALLOC_CLASSES 9       /* 16, 32, ..., 4096 (log2(4096)-log2(16)+1) */
+
+/* Block header: when allocated, first word = size; when free, first word =
+ * the free-list link.  The returned pointer is block + sizeof(header). */
+union km_block {
+	struct { unsigned int size; } h;
+	union km_block *next;
+};
+
+static union km_block *free_lists[KMALLOC_CLASSES];
+
+static inline unsigned int round_up_pow2(unsigned int n)
+{
+	n--;
+	n |= n >> 1;
+	n |= n >> 2;
+	n |= n >> 4;
+	n |= n >> 8;
+	n |= n >> 16;
+	return n + 1;
+}
+
+/* size is a power of two in [KMALLOC_MIN, PAGE_SIZE]. */
+static inline unsigned int size_class_of(unsigned int size)
+{
+	unsigned int c = 0;
+	while (size > KMALLOC_MIN) {
+		size >>= 1;
+		c++;
+	}
+	return c;
+}
+
+void kmalloc_init(void)
+{
+	unsigned int i;
+	for (i = 0; i < KMALLOC_CLASSES; i++)
+		free_lists[i] = 0;
+}
+
+void *kmalloc(unsigned int size)
+{
+	unsigned int total, cls, off;
+	union km_block *b;
+	void *page;
+
+	if (size == 0)
+		size = 1;
+
+	/* Round up (header + payload) to a power of two. */
+	total = round_up_pow2(size + sizeof(unsigned int));
+	if (total < KMALLOC_MIN)
+		total = KMALLOC_MIN;
+
+	/* Large allocation: whole contiguous pages. */
+	if (total > PAGE_SIZE) {
+		unsigned int pages = (total + PAGE_SIZE - 1) / PAGE_SIZE;
+		page = (void *)mm_alloc_pages(pages);
+		if (!page)
+			return 0;
+		((union km_block *)page)->h.size = total;
+		return (void *)((unsigned int)page + sizeof(unsigned int));
+	}
+
+	cls = size_class_of(total);
+	b = free_lists[cls];
+	if (!b) {
+		/* Refill this size class from a fresh page. */
+		page = (void *)mm_alloc_page();
+		if (!page)
+			return 0;
+		for (off = 0; off + total <= PAGE_SIZE; off += total) {
+			union km_block *blk =
+				(union km_block *)((unsigned int)page + off);
+			blk->next = free_lists[cls];
+			free_lists[cls] = blk;
+		}
+		b = free_lists[cls];
+	}
+
+	free_lists[cls] = b->next;
+	b->h.size = total;
+	return (void *)((unsigned int)b + sizeof(unsigned int));
+}
+
+void kfree(void *ptr)
+{
+	union km_block *b;
+	unsigned int size, cls;
+
+	if (!ptr)
+		return;
+
+	b = (union km_block *)((unsigned int)ptr - sizeof(unsigned int));
+	size = b->h.size;
+
+	if (size > PAGE_SIZE) {
+		unsigned int pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
+		unsigned int addr = (unsigned int)b;
+		unsigned int i;
+		for (i = 0; i < pages; i++)
+			mm_free_page(addr + i * PAGE_SIZE);
+		return;
+	}
+
+	cls = size_class_of(size);
+	b->next = free_lists[cls];
+	free_lists[cls] = b;
+}

+ 18 - 0
kmalloc.h

@@ -0,0 +1,18 @@
+/* Kernel heap allocator (kmalloc/kfree) on top of the page-frame allocator.
+ *
+ * Power-of-two segregated free lists:
+ *   - small allocations (<= one page) come from size-class free lists, which
+ *     are refilled by carving whole pages from the frame allocator.
+ *   - large allocations (> one page) allocate contiguous pages directly.
+ *
+ * Each block carries a 4-byte header immediately before the returned pointer;
+ * it stores the block size (so kfree knows which free list / how many pages).
+ */
+#ifndef KMALLOC_H
+#define KMALLOC_H
+
+void *kmalloc(unsigned int size);
+void kfree(void *ptr);
+void kmalloc_init(void);
+
+#endif

+ 56 - 0
mem.c

@@ -0,0 +1,56 @@
+/* mem command: report total/free physical memory and the E820 map. */
+
+#include "io.h"
+#include "mm.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);
+}
+
+void program_mem_main(void)
+{
+	unsigned int total_kb = mm_total_ram_kb();
+	unsigned int free_pages = mm_free_pages();
+	unsigned int free_kb = free_pages * (PAGE_SIZE / 1024);
+	unsigned int n = mm_e820_count();
+	unsigned int i;
+
+	io_putstr("memory: ");
+	put_dec(total_kb);
+	io_putstr(" KB total, ");
+	put_dec(free_kb);
+	io_putstr(" KB free (");
+	put_dec(free_pages);
+	io_putstr(" pages)\n");
+
+	if (n == 0) {
+		io_putstr("E820 map unavailable\n");
+		return;
+	}
+
+	io_putstr("E820 map (");
+	put_dec(n);
+	io_putstr(" entries):\n");
+	for (i = 0; i < n; i++) {
+		const struct e820_entry *e = mm_e820_entry(i);
+		io_putstr("  [0x");
+		io_puthex((unsigned int)e->base);
+		io_putstr(" +0x");
+		io_puthex((unsigned int)e->length);
+		io_putstr("] type ");
+		put_dec(e->type);
+		io_putchar('\n');
+	}
+}

+ 243 - 0
mm.c

@@ -0,0 +1,243 @@
+/* Physical memory manager: parse the E820 map and hand out 4 KB pages. */
+
+#include "mm.h"
+#include "serial.h"
+
+/* One bit per 4 KB page; bit set = in use. */
+#define MM_BITMAP_BITS  (MM_MAX_PHYS / PAGE_SIZE)
+#define MM_BITMAP_WORDS (MM_BITMAP_BITS / 32)
+
+static unsigned int bitmap[MM_BITMAP_WORDS];
+static unsigned int free_pages;
+static unsigned int total_ram_kb;
+
+/* ---- bitmap helpers ---- */
+
+static inline void bit_set(unsigned int idx)
+{
+	bitmap[idx / 32] |= (1u << (idx % 32));
+}
+
+static inline void bit_clear(unsigned int idx)
+{
+	bitmap[idx / 32] &= ~(1u << (idx % 32));
+}
+
+static inline int bit_test(unsigned int idx)
+{
+	return (bitmap[idx / 32] >> (idx % 32)) & 1;
+}
+
+/* ---- interrupt flag save/restore (allocator is not IRQ-safe) ---- */
+
+static inline unsigned int irq_disable_save(void)
+{
+	unsigned int flags;
+	__asm__ volatile ("pushfl; popl %0; cli" : "=r"(flags));
+	return flags;
+}
+
+static inline void irq_restore(unsigned int flags)
+{
+	__asm__ volatile ("pushl %0; popfl" : : "r"(flags));
+}
+
+/* Mark a physical byte range [base, base+len) as used in the bitmap. */
+static void mark_used(unsigned long long base, unsigned long long len)
+{
+	unsigned long long end = base + len;
+	unsigned int p0, p1, p;
+
+	if (base >= MM_MAX_PHYS)
+		return;
+	if (end > MM_MAX_PHYS)
+		end = MM_MAX_PHYS;
+
+	p0 = (unsigned int)(base >> 12);
+	p1 = (unsigned int)((end + PAGE_SIZE - 1) >> 12);
+	for (p = p0; p < p1; p++)
+		bit_set(p);
+}
+
+/* Mark a physical byte range [base, base+len) as free (usable RAM). */
+static void mark_free(unsigned long long base, unsigned long long len)
+{
+	unsigned long long end = base + len;
+	unsigned int p0, p1, p;
+
+	if (base >= MM_MAX_PHYS)
+		return;
+	if (end > MM_MAX_PHYS)
+		end = MM_MAX_PHYS;
+
+	p0 = (unsigned int)(base >> 12);
+	p1 = (unsigned int)(end >> 12);
+	for (p = p0; p < p1; p++)
+		bit_clear(p);
+}
+
+/* Mark the whole bitmap as used, then walk the E820 map and free RAM. */
+void mm_init(void)
+{
+	const struct e820_map *map = (const struct e820_map *)E820_MAP_ADDR;
+	unsigned int i, n;
+
+	/* Everything starts in-use. */
+	for (i = 0; i < MM_BITMAP_WORDS; i++)
+		bitmap[i] = 0xFFFFFFFFu;
+
+	total_ram_kb = 0;
+
+	if (map->magic == E820_MAGIC && map->count <= E820_MAX_ENTRIES) {
+		n = map->count;
+		for (i = 0; i < n; i++) {
+			const struct e820_entry *e = &map->entry[i];
+			if (e->type == E820_RAM && e->length != 0) {
+				mark_free(e->base, e->length);
+				total_ram_kb += (unsigned int)(e->length >> 10);
+			}
+		}
+	} else {
+		/* No E820 map (very old BIOS, or first kexec onto an old build):
+		 * assume 16 MB of RAM from 1 MB up.  The process-stack fallback
+		 * pool keeps the system bootable if this guess is wrong. */
+		mark_free(0x100000ULL, 0x1000000ULL - 0x100000ULL);
+		total_ram_kb = (0x1000000ULL - 0x100000ULL) >> 10; /* 15 MB */
+	}
+
+	/* Re-reserve what the kernel already owns. */
+	mark_used(0, MM_RESERVE_LOW);
+	mark_used(MM_SHADOW_BASE, MM_SHADOW_RESERVE);
+
+	/* Count free pages. */
+	free_pages = 0;
+	for (i = 0; i < MM_BITMAP_BITS; i++) {
+		if (!bit_test(i))
+			free_pages++;
+	}
+}
+
+unsigned int mm_alloc_page(void)
+{
+	unsigned int i, w;
+	unsigned int flags = irq_disable_save();
+
+	for (w = 0; w < MM_BITMAP_WORDS; w++) {
+		if (bitmap[w] != 0xFFFFFFFFu) {
+			unsigned int word = bitmap[w];
+			for (i = 0; i < 32; i++) {
+				if (!(word & (1u << i))) {
+					unsigned int idx = w * 32 + i;
+					bitmap[w] |= (1u << i);
+					free_pages--;
+					irq_restore(flags);
+					return idx * PAGE_SIZE;
+				}
+			}
+		}
+	}
+
+	irq_restore(flags);
+	return 0;
+}
+
+unsigned int mm_alloc_pages(unsigned int n)
+{
+	unsigned int start = 0, run = 0;
+	unsigned int p;
+	unsigned int flags;
+
+	if (n == 0)
+		return 0;
+
+	flags = irq_disable_save();
+	for (p = 0; p < MM_BITMAP_BITS; p++) {
+		if (!bit_test(p)) {
+			if (run == 0)
+				start = p;
+			run++;
+			if (run == n) {
+				unsigned int i;
+				for (i = start; i < start + n; i++)
+					bit_set(i);
+				free_pages -= n;
+				irq_restore(flags);
+				return start * PAGE_SIZE;
+			}
+		} else {
+			run = 0;
+		}
+	}
+	irq_restore(flags);
+	return 0;
+}
+
+void mm_free_page(unsigned int addr)
+{
+	unsigned int idx = addr / PAGE_SIZE;
+	unsigned int flags;
+
+	if (addr == 0 || idx >= MM_BITMAP_BITS)
+		return;
+
+	flags = irq_disable_save();
+	if (bit_test(idx)) {
+		bit_clear(idx);
+		free_pages++;
+	}
+	irq_restore(flags);
+}
+
+unsigned int mm_free_pages(void)
+{
+	return free_pages;
+}
+
+unsigned int mm_total_ram_kb(void)
+{
+	return total_ram_kb;
+}
+
+unsigned int mm_e820_count(void)
+{
+	const struct e820_map *map = (const struct e820_map *)E820_MAP_ADDR;
+	if (map->magic == E820_MAGIC && map->count <= E820_MAX_ENTRIES)
+		return map->count;
+	return 0;
+}
+
+const struct e820_entry *mm_e820_entry(unsigned int i)
+{
+	const struct e820_map *map = (const struct e820_map *)E820_MAP_ADDR;
+	if (map->magic == E820_MAGIC && map->count <= E820_MAX_ENTRIES &&
+	    i < map->count)
+		return &map->entry[i];
+	return 0;
+}
+
+void mm_dump(void)
+{
+	const struct e820_map *map = (const struct e820_map *)E820_MAP_ADDR;
+	unsigned int i;
+
+	serial_puts(SERIAL_COM1, "mm: E820 ");
+	if (map->magic == E820_MAGIC && map->count <= E820_MAX_ENTRIES) {
+		serial_putdec(SERIAL_COM1, map->count);
+		serial_puts(SERIAL_COM1, " entries, ");
+		for (i = 0; i < map->count; i++) {
+			serial_puts(SERIAL_COM1, "\n  [");
+			serial_puthex(SERIAL_COM1, (unsigned int)map->entry[i].base);
+			serial_puts(SERIAL_COM1, " +");
+			serial_puthex(SERIAL_COM1, (unsigned int)map->entry[i].length);
+			serial_puts(SERIAL_COM1, "] type ");
+			serial_putdec(SERIAL_COM1, map->entry[i].type);
+		}
+	} else {
+		serial_puts(SERIAL_COM1, "unavailable (fallback 16 MB)");
+	}
+	serial_puts(SERIAL_COM1, "\nmm: total ");
+	serial_putdec(SERIAL_COM1, total_ram_kb);
+	serial_puts(SERIAL_COM1, " KB, free ");
+	serial_putdec(SERIAL_COM1, free_pages * (PAGE_SIZE / 1024));
+	serial_puts(SERIAL_COM1, " KB\n");
+}

+ 68 - 0
mm.h

@@ -0,0 +1,68 @@
+/* Physical memory manager: E820 detection + page-frame allocator.
+ *
+ * The real-mode VESA stage (vesa_stage.S) probes INT 15h E820 and stores the
+ * result at E820_MAP_ADDR (0x1000, below the kernel, so it survives kexec).
+ * mm_init() parses that map and builds a bitmap over physical RAM, reserving
+ * the low 1 MB (kernel, DMA, UHCI, UMA, boot structures) plus the VGA shadow
+ * buffer region.  Everything above that is handed out 4 KB pages at a time.
+ */
+#ifndef MM_H
+#define MM_H
+
+#define PAGE_SIZE        0x1000
+
+/* E820 map storage (written by vesa_stage.S in real mode). */
+#define E820_MAP_ADDR    0x1000
+#define E820_MAGIC       0xE820E820
+#define E820_MAX_ENTRIES 32
+
+/* Frame allocator covers physical RAM [0, MM_MAX_PHYS).  Bitmap: 1 bit/page.
+ * 256 MB covers every first-gen Pentium chipset (430FX = 128 MB, 430VX = 256 MB)
+ * and QEMU's default 128 MB; raise this only if larger machines are targeted. */
+#define MM_MAX_PHYS      (256u * 1024 * 1024)  /* 256 MB ceiling */
+
+/* Regions the kernel already owns (marked used at init): */
+#define MM_RESERVE_LOW     0x100000   /* 0 .. 1 MB: kernel/DMA/UHCI/UMA/boot */
+#define MM_SHADOW_BASE     0x100000   /* VGA shadow buffer base */
+#define MM_SHADOW_RESERVE  0x800000   /* conservative 8 MB for the shadow */
+
+/* E820 entry type codes. */
+#define E820_RAM       1
+#define E820_RESERVED  2
+
+/* One E820 entry (ACPI 3.0, 24 bytes). */
+struct e820_entry {
+	unsigned long long base;
+	unsigned long long length;
+	unsigned int type;
+	unsigned int attrs;
+} __attribute__((packed));
+
+struct e820_map {
+	unsigned int magic;
+	unsigned int count;
+	struct e820_entry entry[E820_MAX_ENTRIES];
+};
+
+void mm_init(void);
+
+/* Return the base address of a free 4 KB page, or 0 if none. */
+unsigned int mm_alloc_page(void);
+void mm_free_page(unsigned int addr);
+
+/* Return n contiguous pages (base address), or 0 if unavailable. */
+unsigned int mm_alloc_pages(unsigned int n);
+
+unsigned int mm_free_pages(void);
+
+/* Total usable RAM reported by E820, in KB. */
+unsigned int mm_total_ram_kb(void);
+
+/* E820 map accessors (count = 0 when the map is unavailable). */
+unsigned int mm_e820_count(void);
+const struct e820_entry *mm_e820_entry(unsigned int i);
+
+/* Dump the memory map + allocator stats to COM1. */
+void mm_dump(void);
+
+#endif

+ 67 - 0
paging.c

@@ -0,0 +1,67 @@
+/* Paging: identity-map RAM + the VESA LFB, enable CR0.PG (4 MB pages).
+ *
+ * This is the "paging on but flat" stage: every physical address is mapped
+ * 1:1, so all existing code (kernel, stacks, DMA, UHCI, VGA shadow) keeps
+ * working unchanged.  Per-process page directories come later (Phase 3b/4).
+ *
+ * Uses 4 MB pages via CR4.PSE (supported since the original Pentium), so the
+ * whole map is a single 4 KB page directory.
+ */
+
+#include "paging.h"
+#include "mm.h"
+#include "serial.h"
+#include "vga.h"
+
+/* Page-directory entry flags (4 MB page). */
+#define PDE_PRESENT  0x001
+#define PDE_WRITABLE 0x002
+#define PDE_PWT      0x008
+#define PDE_PCD      0x010
+#define PDE_PS       0x080   /* 4 MB page */
+
+/* How much of the LFB to map.  16 MB covers any mode up to 1280x1024x32
+ * (~5 MB) with margin, and is independent of the BIOS's VRAM report. */
+#define LFB_MAP_SIZE 0x1000000
+
+static unsigned int page_dir[1024] __attribute__((aligned(4096)));
+
+void paging_init(void)
+{
+	unsigned int i;
+	const volatile struct vga_boot_fb_info *fb = VGA_BOOT_FB;
+	/* Opaque asm hides the fixed 0x600 pointer from -Warray-bounds. */
+	__asm__ volatile ("" : "+r"(fb));
+
+	/* Identity-map RAM [0, MM_MAX_PHYS) with 4 MB pages (write-back). */
+	for (i = 0; i < MM_MAX_PHYS / 0x400000; i++)
+		page_dir[i] = (i << 22) | PDE_PS | PDE_WRITABLE | PDE_PRESENT;
+
+	/* Identity-map the framebuffer (MMIO, uncacheable) so the screen works. */
+	if (fb->valid && fb->lfb_base) {
+		unsigned int base = fb->lfb_base;
+		unsigned int p0 = base >> 22;
+		unsigned int p1 = (base + LFB_MAP_SIZE) >> 22;
+		for (i = p0; i < p1 && i < 1024; i++)
+			page_dir[i] = (i << 22) | PDE_PS | PDE_PCD |
+				      PDE_WRITABLE | PDE_PRESENT;
+	}
+
+	/* Load CR3, enable PSE, then PG + WP.  The jump flushes the prefetch
+	 * queue after the paging flip. */
+	__asm__ volatile (
+		"movl %0, %%cr3\n\t"
+		"movl %%cr4, %%eax\n\t"
+		"orl  $0x10, %%eax\n\t"       /* CR4.PSE */
+		"movl %%eax, %%cr4\n\t"
+		"movl %%cr0, %%eax\n\t"
+		"orl  $0x80010000, %%eax\n\t" /* CR0.PG | CR0.WP */
+		"movl %%eax, %%cr0\n\t"
+		"jmp  1f\n\t"
+		"1:\n\t"
+		:
+		: "r"((unsigned int)&page_dir[0])
+		: "eax", "memory");
+
+	serial_puts(SERIAL_COM1, "paging: enabled (identity map)\n");
+}

+ 7 - 0
paging.h

@@ -0,0 +1,7 @@
+/* Paging: identity-map RAM + the VESA LFB and enable CR0.PG (4 MB pages). */
+#ifndef PAGING_H
+#define PAGING_H
+
+void paging_init(void);
+
+#endif

+ 164 - 42
process.c

@@ -3,16 +3,51 @@
 #include "process.h"
 #include "idle.h"
 #include "io.h"
+#include "kmalloc.h"
+#include "mm.h"
+#include "serial.h"
 
-struct process procs[MAX_PROCS];
+struct process *procs;               /* dynamically-sized process table */
 volatile unsigned int current_pid;
 
+static unsigned int proc_cap;            /* current capacity of procs[] */
 static unsigned int next_pid_counter = 1; /* monotonic, wraps */
+static unsigned int fallback_stack_next;  /* 0..PROC_FALLBACK_STACK_MAX */
 
-/* Stack top for process slot (1..MAX_PROCS-1).  Slot 0 uses bootstrap stack. */
-static unsigned int stack_top_for(unsigned int slot)
+#define INITIAL_PROC_CAP 16
+
+/* ---- interrupt flag save/restore (for short critical sections) ---- */
+static inline unsigned int irq_save_disable(void)
+{
+	unsigned int flags;
+	__asm__ volatile ("pushfl; popl %0; cli" : "=r"(flags));
+	return flags;
+}
+
+static inline void irq_restore(unsigned int flags)
 {
-	return PROC_STACK_BASE + slot * PROC_STACK_SIZE;
+	__asm__ volatile ("pushl %0; popfl" : : "r"(flags));
+}
+
+/* Allocate a process stack and return its BASE address (page-aligned), or 0.
+ * *owned is set to 1 if it came from the frame allocator (must be freed on
+ * exit), 0 if it came from the fallback pool. */
+static unsigned int stack_alloc(int *owned)
+{
+	unsigned int base = mm_alloc_page();
+	if (base) {
+		*owned = 1;
+		return base;
+	}
+	if (fallback_stack_next < PROC_FALLBACK_STACK_MAX) {
+		unsigned int top = PROC_FALLBACK_STACK_BASE
+			+ fallback_stack_next * PROC_STACK_SIZE
+			+ PROC_STACK_SIZE;
+		fallback_stack_next++;
+		*owned = 0;
+		return top - PROC_STACK_SIZE;
+	}
+	return 0;
 }
 
 static void name_copy(char *dst, const char *src)
@@ -23,15 +58,62 @@ static void name_copy(char *dst, const char *src)
 	dst[i] = '\0';
 }
 
+/* Double the process table.  Called with interrupts disabled. */
+static int grow_proc_table(void)
+{
+	unsigned int new_cap = proc_cap * 2;
+	struct process *np =
+		(struct process *)kmalloc(new_cap * sizeof(struct process));
+	unsigned int i;
+
+	if (!np)
+		return 0;
+	for (i = 0; i < proc_cap; i++)
+		np[i] = procs[i];
+	for (i = proc_cap; i < new_cap; i++)
+		np[i].state = PROC_UNUSED;
+	kfree(procs);
+	procs = np;
+	proc_cap = new_cap;
+	return 1;
+}
+
+/* Find a free process slot (1..proc_cap-1), growing the table if needed.
+ * Slot 0 is the window manager and is never returned.  Called with interrupts
+ * disabled.  Returns the slot index, or -1 on failure. */
+static int alloc_slot(void)
+{
+	unsigned int slot;
+	for (slot = 1; slot < proc_cap; slot++)
+		if (procs[slot].state == PROC_UNUSED)
+			return (int)slot;
+	if (!grow_proc_table())
+		return -1;
+	for (slot = 1; slot < proc_cap; slot++)
+		if (procs[slot].state == PROC_UNUSED)
+			return (int)slot;
+	return -1;
+}
+
 void process_init(void)
 {
 	unsigned int i;
-	for (i = 0; i < MAX_PROCS; i++)
+
+	procs = (struct process *)kmalloc(INITIAL_PROC_CAP * sizeof(struct process));
+	if (!procs) {
+		serial_puts(SERIAL_COM1, "process_init: out of memory\n");
+		for (;;)
+			__asm__ volatile ("cli; hlt");
+	}
+	proc_cap = INITIAL_PROC_CAP;
+	for (i = 0; i < proc_cap; i++)
 		procs[i].state = PROC_UNUSED;
 
-	procs[0].state  = PROC_RUNNING;
-	procs[0].pid    = 0;
-	procs[0].screen = (void *)0;
+	procs[0].state      = PROC_RUNNING;
+	procs[0].pid        = 0;
+	procs[0].esp        = 0;
+	procs[0].screen     = (void *)0;
+	procs[0].stack_base = 0;  /* bootstrap stack, never freed */
 	name_copy(procs[0].name, "wm");
 	current_pid = 0;
 }
@@ -56,16 +138,24 @@ void process_init(void)
 static int setup_process(const char *name, unsigned int entry,
 			 int has_arg, const char *arg)
 {
-	unsigned int slot, top, *sp, arg_ptr = 0;
+	int slot, owned;
+	unsigned int base, top, *sp, arg_ptr = 0;
+	unsigned int flags;
 
-	for (slot = 1; slot < MAX_PROCS; slot++)
-		if (procs[slot].state == PROC_UNUSED)
-			break;
-	if (slot == MAX_PROCS)
-		return -1;
+	flags = irq_save_disable();
 
-	top = stack_top_for(slot);
+	slot = alloc_slot();
+	if (slot < 0) {
+		irq_restore(flags);
+		return -1;
+	}
 
+	base = stack_alloc(&owned);
+	if (!base) {
+		irq_restore(flags);
+		return -1;
+	}
+	top = base + PROC_STACK_SIZE;
 	sp = (unsigned int *)top;
 
 	if (has_arg && arg) {
@@ -99,14 +189,16 @@ static int setup_process(const char *name, unsigned int entry,
 	*--sp = 0;              /* ESI */
 	*--sp = 0;              /* EDI */
 
-	procs[slot].esp    = (unsigned int)sp;
-	procs[slot].state  = PROC_READY;
-	procs[slot].pid    = next_pid_counter++;
+	procs[slot].esp        = (unsigned int)sp;
+	procs[slot].state      = PROC_READY;
+	procs[slot].pid        = next_pid_counter++;
+	procs[slot].stack_base = owned ? base : 0;
 	name_copy(procs[slot].name, name);
 	/* Child inherits the parent's output screen (command output lands in the
 	   terminal that spawned it). */
 	procs[slot].screen = procs[current_pid].screen;
 
+	irq_restore(flags);
 	return (int)procs[slot].pid;
 }
 
@@ -124,15 +216,24 @@ int process_create_arg(const char *name, void (*entry)(const char *),
 /* Create a process whose entry takes a raw pointer argument (no string copy). */
 int process_create_ptr(const char *name, void (*entry)(void *), void *arg)
 {
-	unsigned int slot, top, *sp;
+	int slot, owned;
+	unsigned int base, top, *sp;
+	unsigned int flags;
 
-	for (slot = 1; slot < MAX_PROCS; slot++)
-		if (procs[slot].state == PROC_UNUSED)
-			break;
-	if (slot == MAX_PROCS)
+	flags = irq_save_disable();
+
+	slot = alloc_slot();
+	if (slot < 0) {
+		irq_restore(flags);
 		return -1;
+	}
 
-	top = stack_top_for(slot);
+	base = stack_alloc(&owned);
+	if (!base) {
+		irq_restore(flags);
+		return -1;
+	}
+	top = base + PROC_STACK_SIZE;
 	sp = (unsigned int *)top;
 
 	*--sp = (unsigned int)arg;        /* first C parameter */
@@ -143,12 +244,14 @@ int process_create_ptr(const char *name, void (*entry)(void *), void *arg)
 	*--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++;
+	procs[slot].esp        = (unsigned int)sp;
+	procs[slot].state      = PROC_READY;
+	procs[slot].pid        = next_pid_counter++;
+	procs[slot].stack_base = owned ? base : 0;
 	name_copy(procs[slot].name, name);
 	procs[slot].screen = procs[current_pid].screen;
 
+	irq_restore(flags);
 	return (int)procs[slot].pid;
 }
 
@@ -175,10 +278,17 @@ void schedule(void)
 {
 	unsigned int i, next;
 
-	/* Clean up dead processes. */
-	for (i = 0; i < MAX_PROCS; i++)
-		if (procs[i].state == PROC_DEAD)
+	/* Reap dead processes, freeing their stacks.  Skip the current slot: we
+	 * may be running on its stack right now (it just called process_exit),
+	 * so it is reaped on a later schedule() from another process's context. */
+	for (i = 0; i < proc_cap; i++) {
+		if (procs[i].state == PROC_DEAD && i != current_pid) {
+			if (procs[i].stack_base)
+				mm_free_page(procs[i].stack_base);
+			procs[i].stack_base = 0;
 			procs[i].state = PROC_UNUSED;
+		}
+	}
 
 	/* Mark current as READY (it was RUNNING). */
 	if (procs[current_pid].state == PROC_RUNNING)
@@ -186,8 +296,8 @@ void schedule(void)
 
 	/* Find next runnable slot. */
 	next = current_pid;
-	for (i = 0; i < MAX_PROCS; i++) {
-		next = (next + 1) % MAX_PROCS;
+	for (i = 0; i < proc_cap; i++) {
+		next = (next + 1) % proc_cap;
 		if (procs[next].state == PROC_READY) {
 			procs[next].state = PROC_RUNNING;
 			current_pid = next;
@@ -201,7 +311,7 @@ void schedule(void)
 		return;
 	}
 
-	/* Everything dead: fall back to slot 0 (terminal). */
+	/* Everything dead: fall back to slot 0 (window manager). */
 	procs[0].state = PROC_RUNNING;
 	current_pid = 0;
 }
@@ -217,19 +327,31 @@ static const char *state_str(unsigned int s)
 	}
 }
 
+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);
+}
+
 void process_ps(void)
 {
 	unsigned int i;
 	io_putstr("PID  STATE  NAME\n");
-	for (i = 0; i < MAX_PROCS; i++) {
+	for (i = 0; i < proc_cap; i++) {
 		if (procs[i].state == PROC_UNUSED || procs[i].state == PROC_DEAD)
 			continue;
 		io_putchar(' ');
-		if (procs[i].pid < 10)
-			io_putchar(' ');
-		if (procs[i].pid >= 10)
-			io_putchar((char)('0' + procs[i].pid / 10));
-		io_putchar((char)('0' + procs[i].pid % 10));
+		put_dec(procs[i].pid);
 		io_putstr("  ");
 		io_putstr(state_str(procs[i].state));
 		io_putstr("  ");
@@ -242,8 +364,8 @@ int process_kill(unsigned int pid)
 {
 	unsigned int i;
 	if (pid == 0)
-		return -1; /* cannot kill terminal */
-	for (i = 1; i < MAX_PROCS; i++) {
+		return -1; /* cannot kill window manager */
+	for (i = 1; i < proc_cap; i++) {
 		if (procs[i].state != PROC_UNUSED && procs[i].state != PROC_DEAD &&
 		    procs[i].pid == pid) {
 			procs[i].state = PROC_DEAD;
@@ -257,7 +379,7 @@ int process_kill(unsigned int pid)
 int process_is_alive(unsigned int pid)
 {
 	unsigned int i;
-	for (i = 0; i < MAX_PROCS; i++)
+	for (i = 0; i < proc_cap; i++)
 		if (procs[i].pid == pid &&
 		    (procs[i].state == PROC_READY ||
 		     procs[i].state == PROC_RUNNING))

+ 10 - 4
process.h

@@ -2,9 +2,13 @@
 #ifndef PROCESS_H
 #define PROCESS_H
 
-#define MAX_PROCS       8
-#define PROC_STACK_SIZE 0x1000  /* 4 KB per process */
-#define PROC_STACK_BASE 0x42000 /* process 1 stack bottom; process 0 uses bootstrap stack */
+#define PROC_STACK_SIZE 0x1000  /* 4 KB per process (= 1 page) */
+
+/* Process stacks are allocated from the frame allocator (mm.c), i.e. above the
+ * VGA shadow buffer.  If that is unavailable (no E820 map) we fall back to a
+ * small fixed pool below 1 MB so the system still boots with fewer processes. */
+#define PROC_FALLBACK_STACK_BASE 0x42000
+#define PROC_FALLBACK_STACK_MAX  8
 
 #define PROC_UNUSED  0
 #define PROC_READY   1
@@ -23,9 +27,11 @@ struct process {
 	unsigned int pid;
 	char         name[PROC_NAME_LEN];
 	struct text_screen *screen;  /* output target for io_putchar & co. */
+	unsigned int stack_base;     /* page to free on exit, or 0 (bootstrap/fallback) */
 };
 
-extern struct process procs[MAX_PROCS];
+/* Dynamically-sized process table (grown on demand; see process.c). */
+extern struct process *procs;
 extern volatile unsigned int current_pid;
 
 void process_init(void);

+ 6 - 6
switch.S

@@ -24,7 +24,7 @@
 
 /* struct process offsets (must match process.h / process.c) */
 .equ PCB_ESP,   0
-.equ PCB_SIZE,  28      /* sizeof(struct process): 4+4+4+12+4 = 28 */
+.equ PCB_SIZE,  32      /* sizeof(struct process): 4+4+4+12+4+4 = 32 */
 
 .equ TIMESLICE, 20
 .equ FLUSH_INTERVAL, 33 /* 1000Hz PIT / 30Hz flush ≈ 33 ticks */
@@ -55,11 +55,11 @@ pit_irq_stub:
 	/* Reset counter for next timeslice. */
 	movl  $TIMESLICE, slice_counter
 
-	/* Save current ESP into procs[current_pid].esp */
+	/* Save current ESP into procs[current_pid].esp (procs is a pointer). */
 	movl  current_pid, %eax
 	imull $PCB_SIZE, %eax
-	leal  procs(%eax), %ebx
-	movl  %esp, PCB_ESP(%ebx)
+	addl  procs, %eax
+	movl  %esp, PCB_ESP(%eax)
 
 	/* Let the C scheduler pick the next process. */
 	call  schedule
@@ -67,8 +67,8 @@ pit_irq_stub:
 	/* Load new ESP from procs[current_pid].esp */
 	movl  current_pid, %eax
 	imull $PCB_SIZE, %eax
-	leal  procs(%eax), %ebx
-	movl  PCB_ESP(%ebx), %esp
+	addl  procs, %eax
+	movl  PCB_ESP(%eax), %esp
 
 .no_switch:
 	popa

+ 19 - 0
terminal.c

@@ -29,6 +29,7 @@ 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_mem_main(void);
 extern void program_format_main(const char *arg);
 extern void program_lspci_main(void);
 extern void program_netinfo_main(void);
@@ -519,6 +520,21 @@ static int is_cmd_storage(const char *line, unsigned int line_len)
 	return (i == line_len);
 }
 
+static int is_cmd_mem(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 3 > line_len)
+		return 0;
+	if (line[i] != 'm' || line[i+1] != 'e' || line[i+2] != 'm')
+		return 0;
+	i += 3;
+	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;
@@ -981,6 +997,8 @@ void term_run(struct term *t)
 						term_spawn(t, "ping", program_ping_main);
 					} else if (is_cmd_storage(t->line, t->line_len)) {
 						term_spawn(t, "storage", program_storage_main);
+					} else if (is_cmd_mem(t->line, t->line_len)) {
+						term_spawn(t, "mem", program_mem_main);
 					} else if (is_cmd_clock(t->line, t->line_len)) {
 						io_putstr("clock: not available in windowed mode yet\n");
 					} else if (is_cmd_colors(t->line, t->line_len)) {
@@ -1071,6 +1089,7 @@ void term_run(struct term *t)
 						io_putstr("lsusb\n");
 						io_putstr("mouseinfo\n");
 						io_putstr("storage\n");
+						io_putstr("mem\n");
 						io_putstr("format <device>\n");
 						io_putstr("lspci\n");
 						io_putstr("netinfo\n");

+ 35 - 0
vesa_stage.S

@@ -13,11 +13,46 @@
 .code16
 .section .text.stage2, "ax", @progbits
 .globl _vesa_stage
+
+/* E820 map constants (must match mm.h). */
+.equ E820_MAGIC,    0xE820E820
+.equ E820_BUF_END,  0x1008 + 32*24   /* 32 entries * 24 bytes */
+
 _vesa_stage:
 	xorw  %ax, %ax
 	movw  %ax, %ds
 	movw  %ax, %es
 
+	/* ---- Probe INT 15h E820 memory map into 0:0x1000 ----
+	 * Layout (see mm.h): [magic u32][count u32][24-byte entries...].
+	 * Stored below the kernel (0x7E00) so it survives kexec reloads,
+	 * which re-run kernel_main but not this real-mode stage. */
+	movl  $E820_MAGIC, 0x1000     /* magic */
+	movl  $0, 0x1004              /* count = 0 */
+	xorl  %ebx, %ebx              /* continuation value */
+	movl  $0x1008, %edi           /* ES:DI -> first entry */
+e820_loop:
+	xorw  %ax, %ax
+	movw  %ax, %es                /* (re)set ES for the BIOS buffer */
+	movl  $0xE820, %eax
+	movl  $0x534D4150, %edx       /* "SMAP" */
+	movl  $24, %ecx
+	int   $0x15
+	jc    e820_done               /* CF set -> unsupported / done */
+	cmpl  $0x534D4150, %eax
+	jne   e820_done               /* not "SMAP" -> done */
+	cmpb  $20, %cl
+	jb    e820_done               /* too short -> stop */
+	movl  $0, 20(%edi)            /* zero ACPI attrs (BIOS may write 20 B) */
+	incl  0x1004                  /* count++ */
+	addl  $24, %edi
+	testl %ebx, %ebx
+	jz    e820_done               /* continuation == 0 -> done */
+	cmpl  $E820_BUF_END, %edi
+	jae   e820_done               /* buffer full -> stop */
+	jmp   e820_loop
+e820_done:
+
 	/* ---- VBE Controller Info into 0:0x2000 ---- */
 	movw  $0x2000, %di
 	movw  $0x4256, (%di)	/* "VB" */