Przeglądaj źródła

Add serial kexec hot-reload (floppy-free kernel dev loop)

- 115200 baud serial init; 'kexec' command + auto-detect reload
- bootstrap.c: one-time ring-0 loader for 9600-baud machines (no floppy)
- kexec_tramp.S: position-independent trampoline; rebuilds flat GDT at 0x900
- kexec_send.c: host sender (magic+entry+size+data+checksum)
- version.h: shared OS name/version; serial boot banner
- AGENTS.md: project map + hot-reload workflow
Johannes Zellner 1 miesiąc temu
rodzic
commit
5568b3f76c
15 zmienionych plików z 766 dodań i 12 usunięć
  1. 3 0
      .gitignore
  2. 143 0
      AGENTS.md
  3. 33 7
      Makefile
  4. 158 0
      bootstrap.c
  5. 2 0
      kernel.c
  6. 152 0
      kexec.c
  7. 14 0
      kexec.h
  8. 140 0
      kexec_send.c
  9. 59 0
      kexec_tramp.S
  10. 2 2
      serial.c
  11. 1 0
      serial.h
  12. 14 0
      serial_ring_buf.c
  13. 1 0
      serial_ring_buf.h
  14. 35 3
      terminal.c
  15. 9 0
      version.h

+ 3 - 0
.gitignore

@@ -1,3 +1,6 @@
 *.o
 *.bin
 *.elf
+*.img
+send_serial
+kexec_send

+ 143 - 0
AGENTS.md

@@ -0,0 +1,143 @@
+# AGENTS.md — Nebs OS (`nebos`)
+
+A from-scratch, freestanding **32-bit x86 hobby operating system** written in C and
+x86 assembly. Single-author project (~7,000 SLOC, no external runtime, no libc).
+Targets i586 (first-gen Pentium); runs under QEMU or on real hardware.
+
+## Build & run
+
+Toolchain: `gcc` (32-bit multilib), `as`/`ld`/`objcopy`, `mtools` (`mcopy`/`mkfs.fat`), `qemu`.
+
+```sh
+make all        # floppy.img usb.img final.bin root.img
+make run        # boot floppy.img + root.img in QEMU (fallback: qemu-system-x86_64)
+make run-usb    # boot usb.img as an IDE disk
+make clean
+```
+
+- Build flags (in `Makefile`): `-m32 -march=i586 -ffreestanding -fno-pie -nostdlib
+  -fno-stack-protector -mno-sse -mno-sse2 -mno-mmx -O2`.
+- `root.img` is a second FAT12 floppy holding user binaries (`PROG.BIN`, `SPACE.BIN`)
+  and test files; it requires `mtools` to build.
+- `make send PROGRAM=prog` transfers a binary to a real machine over serial.
+
+## Boot chain
+
+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`.
+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.
+
+## Hardcoded memory map (fragile — keep in sync when editing)
+
+| Address    | Purpose |
+|-----------|---------|
+| `0x600`   | Boot framebuffer info (`struct vga_boot_fb_info`, see `vga.h`) |
+| `0x7C00`  | Boot sector load address |
+| `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) |
+| `0x20000` | ISA DMA buffer (`disk.c`) + kernel upper bound (`kernel.ld` ASSERT) |
+| `0x20800` | Protected-mode stack top (`vesa_stage.S`) |
+| `0x20F00` | Program API struct (`PROGRAM_API_ADDR`, `run_api.h`) |
+| `0x21000` | User program load address (`run.c`, `user.ld`) |
+| `0x30000` | kexec staging buffer (received kernel image) |
+| `0x40000` | Process stack base (`PROC_STACK_BASE`, 4 KB × 8, `process.h`) |
+| `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.
+- **Graphics**: `vga.c/h`, `vga_copy.S`, `gpu.c`, `ati.c`, `nvidia.c`, `pci.h` —
+  VESA LFB + shadow buffer, 30 Hz dirty-row flush. ATI Mach64 CRTC fixup; NVIDIA no-op.
+- **Text console**: `fbtext.c`, `font_8x8.c/h`, `io.c/h` — framebuffer text,
+  8×8 font, rainbow separator, live datetime header, blinking cursor.
+- **Shell**: `terminal.c` — history, line editing, command dispatch (hand-rolled
+  `is_cmd_*` parsers).
+- **Filesystem**: `fat.c` (read-only FAT12), `disk.c` (FDC + ISA DMA ch2, retries).
+- **Serial**: `serial.c`, `serial_ring_buf.c/h`, `bin_recv.c/h`, `serial_recv.c`,
+  `serial_loop.c`, `send_serial.c` — 16550 UART, IRQ-driven ring buffer, XMODEM.
+- **Hot-reload (kexec)**: `kexec.c/h`, `kexec_tramp.S`, `bootstrap.c`, and the
+  host-side `kexec_send.c` — reload the kernel over serial without rebooting
+  (C-light: reuses the current framebuffer, re-runs `kernel_main`).
+- **Mouse**: `mouse.c` — PS/2 + IntelliMouse, hardware cursor.
+- **Power/idle**: `idle.c` — `mwait` C-states, `hlt` fallback.
+- **User programs**: `run.c`, `run_api.h`, `prog.c`, `space.c` — raw binaries at
+  `0x21000`, API function-pointer struct at `0x20F00`. `space` = Space Invaders.
+
+## Shell commands
+
+`hello`, `reboot`, `poweroff`, `ls`, `cat <file>`, `run <file>`, `space`, `clock`,
+`colors`, `display`, `cpuinfo`, `mouseinfo`, `power [info|set …]`, `drive <0|1>`,
+`ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`.
+
+## Serial hot-reload (kexec) workflow
+
+Develop without reflashing the floppy. The serial link (COM1 ↔ `/dev/ttyUSB0`)
+runs at **115200 baud**. Two paths exist:
+
+- **Auto-detect** (the normal loop) — the terminal's idle loop watches the serial
+  ring buffer for the `"KXEC"` magic and auto-spawns the reload, so `make dev`
+  alone boots a fresh kernel. The manual `kexec` command is kept as a fallback
+  that waits for the same image.
+- **`bootstrap`** (one-time, zero-reflash) — a ring-0 program loaded through the
+  existing `serial recv` + `run serial` path that switches the UART to 115200,
+  receives a new kernel, and jumps into it. Used only to install the first new
+  kernel onto a machine still running an old (9600 baud) build.
+
+Wire protocol (host → target, sent immediately; no handshake):
+`[magic "KXEC"][entry u32 LE][size u32 LE][data][checksum u8]`.
+
+**Every iteration:**
+```sh
+make dev            # builds kernel.bin, computes kernel_main via nm, sends
+```
+The reload is automatic. On boot the kernel prints `Nebs OS v<version> booted`
+to COM1, so a serial monitor can confirm the new build headlessly.
+
+**One-time install onto a 9600-baud machine (no floppy):**
+```sh
+make bootstrap                                   # builds bootstrap.bin
+# 1) start the host sender first (it waits for 'R'):
+./send_serial /dev/ttyUSB0 9600 bootstrap.bin
+# 2) on the PC: `serial recv` (sends 'R'), then `run serial`
+# 3) the bootstrap switches the link to 115200 and waits; send the kernel:
+make dev                                         # 115200
+```
+After the first kexec the machine is at 115200, and `make dev` is all you need
+from then on.
+
+Notes: the kexec path rebuilds a flat GDT at `0x900` before jumping (the old GDT
+lives inside the overwritten kernel region), so it's safe to edit any file,
+including `vesa_stage.S`/`boot.S` layout — but the video *mode* itself is only
+re-applied on a full floppy/USB boot (C-light reuses the current LFB).
+
+## Conventions & gotchas
+
+- **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.
+- **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.
+- **Keep the memory map in sync** — hardcoded addresses appear in `.S`, `.c`, and
+  linker scripts; changing one without the others breaks boot/loading.
+
+## Known issues (candidates for future tasks)
+
+1. `serial_puthex` (`serial.c`) uses `"01234589ABCDEF"` — digits **6 and 7 are
+   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.
+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.
+7. `terminal.c` command dispatch is ~30 near-identical `is_cmd_*` functions;
+   a table-driven parser would reduce this.

+ 33 - 7
Makefile

@@ -13,14 +13,14 @@ ASFLAGS  = --32
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
-.PHONY: all clean run run-floppy run-usb run-serial floppy usb space prog
+.PHONY: all clean run run-floppy run-usb run-serial floppy usb space prog bootstrap dev
 
 all: floppy.img usb.img final.bin root.img
 
 boot.o: boot.S
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.o: kernel.c idle.h io.h mouse.h process.h terminal.h timer.h serial.h vga.h
+kernel.o: kernel.c idle.h io.h mouse.h process.h terminal.h timer.h serial.h version.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 io.o: io.c io.h fbtext.h
@@ -32,7 +32,7 @@ font_8x8.o: font_8x8.c font_8x8.h
 fbtext.o: fbtext.c fbtext.h font_8x8.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-terminal.o: terminal.c terminal.h io.h fbtext.h idle.h mouse.h process.h rtc.h timer.h disk.h
+terminal.o: terminal.c terminal.h io.h fbtext.h idle.h kexec.h mouse.h process.h rtc.h timer.h disk.h version.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 hello.o: hello.c io.h
@@ -113,6 +113,12 @@ mouse.o: mouse.c mouse.h timer.h vga.h
 idle.o: idle.c idle.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+kexec.o: kexec.c kexec.h io.h serial.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+kexec_tramp.o: kexec_tramp.S
+	$(AS) $(ASFLAGS) -o $@ $<
+
 boot.elf: boot.o
 	$(LD) $(BOOT_LDFLAGS) -o $@ $<
 
@@ -128,7 +134,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 idle.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 idle.o kexec.o kexec_tramp.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -203,6 +209,15 @@ space.elf: space.o
 space.bin: space.elf
 	$(OBJCOPY) -O binary $< $@
 
+bootstrap.o: bootstrap.c
+	$(CC) $(CFLAGS) -o $@ $<
+
+bootstrap.elf: bootstrap.o
+	$(LD) -T user.ld -nostdlib -m elf_i386 -o $@ $<
+
+bootstrap.bin: bootstrap.elf
+	$(OBJCOPY) -O binary $< $@
+
 root.img: prog.bin space.bin
 	dd if=/dev/zero of=$@ bs=512 count=2880 2>/dev/null
 	mkfs.fat -F 12 -n "ROOTDISK" $@
@@ -234,8 +249,8 @@ scp-root: root.img
 	scp root.img root@192.168.0.136:
 	ssh root@192.168.0.136 dd if=root.img of=/dev/fd0 bs=512
 
-SERIAL_DEV ?= /dev/ttyUSB1
-SERIAL_BAUD ?= 9600
+SERIAL_DEV ?= /dev/ttyUSB0
+SERIAL_BAUD ?= 115200
 SZ ?= /usr/bin/lrzsz-sz
 
 run-serial:
@@ -251,5 +266,16 @@ send: $(PROGRAM).bin send_serial
 send_serial: send_serial.c
 	gcc -O2 -o $@ $<
 
+kexec_send: kexec_send.c
+	gcc -O2 -o $@ $<
+
+bootstrap: bootstrap.bin
+
+dev: kernel.bin kexec_send
+	@entry=$$(nm kernel.elf | awk '/ T kernel_main$$/{print $$1}'); \
+	if [ -z "$$entry" ]; then echo "error: kernel_main symbol not found"; exit 1; fi; \
+	echo "Sending kernel.bin (entry 0x$$entry) via $(SERIAL_DEV) @ $(SERIAL_BAUD)..."; \
+	./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 idle.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 send_serial
+	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 idle.o kexec.o kexec_tramp.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

+ 158 - 0
bootstrap.c

@@ -0,0 +1,158 @@
+/* One-time kexec bootstrap (loaded via the existing `serial recv` + `run serial`
+ * path at 9600 baud). Because nebos runs everything in ring-0, this program has
+ * full hardware access: it switches COM1 to 115200, receives a new kernel image,
+ * copies it over 0x7E00, and jumps to its kernel_main.
+ *
+ * Self-contained: no kernel symbols, no run_api dependency. We live at 0x21000
+ * (outside the 0x7E00..0x20000 kernel region), so we can overwrite the kernel
+ * directly from our own code without a relocated trampoline.
+ *
+ * Wire protocol (host -> us), after we emit 'R':
+ *   4 bytes: magic "KXEC" (LE)
+ *   4 bytes: entry address (LE)
+ *   4 bytes: size (LE)
+ *   N bytes: kernel.bin data
+ *   1 byte:  checksum (sum of data bytes mod 256)
+ */
+
+#define UART_BASE        0x3F8
+#define STAGE_ADDR       0x30000
+#define KERNEL_LOAD_ADDR 0x7E00
+#define BOOT_STACK       0x20800
+#define MAGIC            0x4345584B /* "KXEC" little-endian */
+#define MAX_SIZE         0x10000
+
+static inline void outb(unsigned short port, unsigned char v)
+{
+	__asm__ volatile ("outb %0, %1" : : "a"(v), "Nd"(port));
+}
+
+static inline unsigned char inb(unsigned short port)
+{
+	unsigned char v;
+	__asm__ volatile ("inb %1, %0" : "=a"(v) : "Nd"(port));
+	return v;
+}
+
+static void uart_115200(void)
+{
+	outb(UART_BASE + 1, 0x00); /* IER off */
+	outb(UART_BASE + 3, 0x80); /* DLAB */
+	outb(UART_BASE + 0, 0x01); /* divisor low = 1 (115200) */
+	outb(UART_BASE + 1, 0x00); /* divisor high = 0 */
+	outb(UART_BASE + 3, 0x03); /* 8N1 */
+	outb(UART_BASE + 2, 0xC7); /* FIFO on, clear */
+	outb(UART_BASE + 4, 0x03); /* DTR|RTS */
+}
+
+static unsigned char read_byte(void)
+{
+	while (!(inb(UART_BASE + 5) & 0x01))
+		;
+	return inb(UART_BASE + 0);
+}
+
+static unsigned int read32le(void)
+{
+	unsigned int v = 0;
+	unsigned int i;
+	for (i = 0; i < 4; i++)
+		v |= (unsigned int)read_byte() << (8 * i);
+	return v;
+}
+
+static void delay(void)
+{
+	volatile unsigned int i;
+	for (i = 0; i < 50000; i++)
+		;
+}
+
+static void halt(void)
+{
+	for (;;)
+		__asm__ volatile ("hlt");
+}
+
+/* Flat GDT (base 0 / 4 GB) + GDTR, written to 0x900 (below the kernel) so
+ * the new kernel's segment reloads don't read the old GDT we overwrite.
+ * Layout: 24-byte GDT at 0x900, 6-byte GDTR at 0x918 (limit 23, base 0x900). */
+static const unsigned char flat_gdt_blob[30] = {
+	0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, /* null */
+	0xFF,0xFF,0x00,0x00, 0x00,0x9A,0xCF,0x00, /* code */
+	0xFF,0xFF,0x00,0x00, 0x00,0x92,0xCF,0x00, /* data */
+	0x17,0x00,              /* gdtr limit = 23 */
+	0x00,0x09,0x00,0x00     /* gdtr base = 0x900 */
+};
+
+static void copy_to(unsigned int dst, const void *src, unsigned int n)
+{
+	__asm__ volatile (
+		"cld\n\t"
+		"rep movsb"
+		: "+S"(src), "+D"(dst), "+c"(n)
+		:
+		: "memory");
+}
+
+static void setup_flat_gdt(void)
+{
+	copy_to(0x900, flat_gdt_blob, sizeof(flat_gdt_blob));
+	__asm__ volatile ("lgdt (%0)" : : "r"(0x918));
+}
+
+void _start(void)
+{
+	unsigned char c, sum = 0, chk;
+	unsigned int magic, entry, size, i;
+
+	/* Stop the PIT (and all IRQs) so the kernel's serial_poll stops
+	 * competing with us for UART bytes. */
+	__asm__ volatile ("cli");
+	outb(0x21, 0xFF);
+	outb(0xA1, 0xFF);
+
+	uart_115200();
+
+	/* Drain stale bytes. */
+	while (inb(UART_BASE + 5) & 0x01)
+		(void)inb(UART_BASE + 0);
+
+	/* Emit 'R' until the host starts sending the header. */
+	for (;;) {
+		outb(UART_BASE + 0, 'R');
+		delay();
+		if (inb(UART_BASE + 5) & 0x01)
+			break;
+	}
+
+	magic = read32le();
+	entry = read32le();
+	size  = read32le();
+
+	if (magic != MAGIC || size == 0 || size > MAX_SIZE) {
+		outb(UART_BASE + 0, 'E');
+		halt();
+	}
+
+	for (i = 0; i < size; i++) {
+		c = read_byte();
+		((volatile unsigned char *)STAGE_ADDR)[i] = c;
+		sum += c;
+	}
+
+	chk = read_byte();
+	if (chk != sum) {
+		outb(UART_BASE + 0, 'E');
+		halt();
+	}
+
+	/* Copy staged kernel over 0x7E00, then jump to its kernel_main.
+	 * We live at 0x21000, outside the overwritten region, so this is safe. */
+	setup_flat_gdt();
+	for (i = 0; i < size; i++)
+		((volatile unsigned char *)KERNEL_LOAD_ADDR)[i] =
+			((volatile unsigned char *)STAGE_ADDR)[i];
+
+	__asm__ volatile ("movl %0, %%esp; jmp *%1" : : "i"(BOOT_STACK), "r"(entry));
+}

+ 2 - 0
kernel.c

@@ -7,6 +7,7 @@
 #include "terminal.h"
 #include "timer.h"
 #include "serial.h"
+#include "version.h"
 #include "vga.h"
 
 static inline void outb(unsigned short port, unsigned char v)
@@ -130,6 +131,7 @@ void kernel_main(void)
 
 	serial_init(SERIAL_COM1);
 	serial_ring_init();
+	serial_puts(SERIAL_COM1, "\r\n" OS_NAME " v" OS_VERSION " booted\r\n");
 	io_init();
 	idle_init();
 	timer_init();

+ 152 - 0
kexec.c

@@ -0,0 +1,152 @@
+/* kexec: receive a new kernel.bin over serial and jump into it.
+ *
+ * C-light reload: we do NOT return to real mode or re-run the VESA stage.
+ * Instead we reuse the current framebuffer (the boot FB info at 0x600 and the
+ * LFB are still valid) and jump straight to the new kernel's kernel_main,
+ * which re-inits IDT/PIC/PIT/mouse/process/VGA-shadow/terminal from scratch.
+ *
+ * Because this code lives at 0x7E00..0x20000 (inside the region we overwrite),
+ * the final "copy image to 0x7E00 and jump" is done by a small
+ * position-independent trampoline relocated to 0x800 (below the kernel).
+ *
+ * The terminal polls kexec_pending() on its idle loop, so `make dev` on the
+ * host alone triggers the reload (no typing required). The manual `kexec`
+ * command is kept as a fallback that waits for the same image.
+ *
+ * Wire protocol (host -> us):
+ *   4 bytes: magic "KXEC" (LE)
+ *   4 bytes: entry address (LE)   -- new kernel_main VMA
+ *   4 bytes: size (LE)            -- kernel.bin byte count
+ *   N bytes: kernel.bin data
+ *   1 byte:  checksum (sum of data bytes mod 256)
+ */
+
+#include "kexec.h"
+#include "io.h"
+#include "serial.h"
+
+#define KEXEC_MAGIC 0x4345584B /* "KXEC" little-endian */
+#define KEXEC_STAGE 0x30000    /* staging buffer for the received image */
+#define KEXEC_LOAD  0x7E00     /* where the kernel must be placed */
+#define KEXEC_TRAMP 0x800      /* relocated trampoline (below the kernel) */
+#define KEXEC_MAX   0x10000    /* 64 KB cap (fits the staging region) */
+
+volatile int kexec_busy;
+
+extern unsigned char kexec_trampoline[];
+extern unsigned char kexec_trampoline_end[];
+
+int kexec_pending(void)
+{
+	unsigned char b0 = 0, b1 = 0, b2 = 0, b3 = 0;
+
+	if (serial_ring_peek(0, &b0) && serial_ring_peek(1, &b1) &&
+	    serial_ring_peek(2, &b2) && serial_ring_peek(3, &b3))
+		return (b0 == 'K' && b1 == 'X' && b2 == 'E' && b3 == 'C');
+	return 0;
+}
+
+/* Drain whatever partial data remains in the ring buffer after a failure so a
+ * subsequent attempt starts clean. */
+static void kexec_drain(void)
+{
+	while (serial_has_data(SERIAL_COM1))
+		(void)serial_ring_getc();
+}
+
+static int kexec_fail(const char *msg)
+{
+	if (msg)
+		io_putstr(msg);
+	kexec_drain();
+	return -1;
+}
+
+static int kexec_recv(unsigned int *entry, unsigned int *size)
+{
+	volatile unsigned char *dst = (volatile unsigned char *)KEXEC_STAGE;
+	unsigned int i, magic = 0, n;
+	unsigned char c, sum = 0, chk;
+
+	for (i = 0; i < 4; i++) {
+		if (!serial_ring_wait(5000, &c))
+			return kexec_fail("kexec: timeout (magic)\n");
+		magic |= (unsigned int)c << (8 * i);
+	}
+	if (magic != KEXEC_MAGIC)
+		return kexec_fail("kexec: bad magic\n");
+
+	*entry = 0;
+	for (i = 0; i < 4; i++) {
+		if (!serial_ring_wait(5000, &c))
+			return kexec_fail("kexec: timeout (entry)\n");
+		*entry |= (unsigned int)c << (8 * i);
+	}
+
+	*size = 0;
+	for (i = 0; i < 4; i++) {
+		if (!serial_ring_wait(5000, &c))
+			return kexec_fail("kexec: timeout (size)\n");
+		*size |= (unsigned int)c << (8 * i);
+	}
+	if (*size == 0 || *size > KEXEC_MAX)
+		return kexec_fail("kexec: bad size\n");
+
+	for (n = 0; n < *size; n++) {
+		if (!serial_ring_wait(5000, &c))
+			return kexec_fail("kexec: timeout (data)\n");
+		dst[n] = c;
+		sum += c;
+		if ((n & 0xFFF) == 0xFFF)
+			io_putchar('.');
+	}
+	io_putchar('\n');
+
+	if (!serial_ring_wait(5000, &chk))
+		return kexec_fail("kexec: timeout (checksum)\n");
+	if (chk != sum)
+		return kexec_fail("kexec: checksum mismatch\n");
+
+	return 0;
+}
+
+void program_kexec_main(void)
+{
+	unsigned int entry = 0, size = 0;
+
+	io_putstr("kexec: waiting for kernel image over serial...\n");
+	if (kexec_recv(&entry, &size) != 0) {
+		io_putstr("kexec: aborted\n");
+		kexec_busy = 0;
+		return;
+	}
+
+	io_putstr("kexec: received ");
+	io_puthex(size);
+	io_putstr(" bytes, entry ");
+	io_puthex(entry);
+	io_putstr("\n");
+
+	/* Relocate the trampoline to 0x800 so it survives the kernel overwrite. */
+	{
+		const void *s = (const void *)kexec_trampoline;
+		void *d = (void *)KEXEC_TRAMP;
+		unsigned int n = (unsigned int)(kexec_trampoline_end - kexec_trampoline);
+		__asm__ volatile (
+			"cld\n\t"
+			"rep movsb"
+			: "+S"(s), "+D"(d), "+c"(n)
+			:
+			: "memory");
+	}
+
+	/* Serialize so the freshly-written trampoline is visible to fetch. */
+	__asm__ volatile ("cpuid" ::: "eax", "ebx", "ecx", "edx");
+
+	/* Jump to the trampoline with args in eax/ebx/ecx/edx. Never returns. */
+	__asm__ volatile (
+		"jmp *%4"
+		:
+		: "a"(KEXEC_STAGE), "b"(KEXEC_LOAD), "c"(size), "d"(entry), "r"(KEXEC_TRAMP)
+		: "memory");
+}

+ 14 - 0
kexec.h

@@ -0,0 +1,14 @@
+/* kexec: hot-reload the kernel over serial without a reboot (C-light variant). */
+#ifndef KEXEC_H
+#define KEXEC_H
+
+void program_kexec_main(void);
+
+/* Non-zero while a kexec receive is in progress (prevents double-trigger). */
+extern volatile int kexec_busy;
+
+/* Returns 1 if the serial ring buffer starts with the "KXEC" magic, i.e. the
+ * host has begun sending a new kernel image. */
+int kexec_pending(void);
+
+#endif

+ 140 - 0
kexec_send.c

@@ -0,0 +1,140 @@
+/* Host-side sender for nebos `kexec` / bootstrap.
+ *
+ * Protocol: send immediately (no handshake; the kernel auto-detects the magic):
+ *   4 bytes: magic "KXEC" (LE)
+ *   4 bytes: entry address (LE)
+ *   4 bytes: size (LE)
+ *   N bytes: kernel.bin data
+ *   1 byte:  checksum (sum of data bytes mod 256)
+ *
+ * Usage: kexec_send <device> <baud> <entry_hex> <file>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <termios.h>
+#include <stdint.h>
+
+static void put32le(unsigned char *p, uint32_t 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);
+}
+
+int main(int argc, char *argv[])
+{
+	int fd;
+	FILE *fp;
+	unsigned char *data;
+	long size;
+	unsigned int cksum = 0;
+	unsigned char hdr[12];
+	struct termios tty;
+	uint32_t entry;
+
+	if (argc != 5) {
+		fprintf(stderr, "Usage: %s <device> <baud> <entry_hex> <file>\n", argv[0]);
+		return 1;
+	}
+
+	entry = (uint32_t)strtoul(argv[3], NULL, 16);
+
+	fp = fopen(argv[4], "rb");
+	if (!fp) {
+		perror("fopen");
+		return 1;
+	}
+	fseek(fp, 0, SEEK_END);
+	size = ftell(fp);
+	fseek(fp, 0, SEEK_SET);
+
+	data = malloc((size_t)size);
+	if (!data) {
+		perror("malloc");
+		fclose(fp);
+		return 1;
+	}
+	if (fread(data, 1, (size_t)size, fp) != (size_t)size) {
+		perror("fread");
+		fclose(fp);
+		free(data);
+		return 1;
+	}
+	fclose(fp);
+
+	for (long i = 0; i < size; i++)
+		cksum += data[i];
+	cksum &= 0xFF;
+
+	fd = open(argv[1], O_RDWR | O_NOCTTY);
+	if (fd < 0) {
+		perror("open");
+		free(data);
+		return 1;
+	}
+
+	memset(&tty, 0, sizeof(tty));
+	if (tcgetattr(fd, &tty) != 0) {
+		perror("tcgetattr");
+		free(data);
+		close(fd);
+		return 1;
+	}
+	cfsetispeed(&tty, (speed_t)atoi(argv[2]));
+	cfsetospeed(&tty, (speed_t)atoi(argv[2]));
+	tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;
+	tty.c_cflag |= CLOCAL | CREAD;
+	tty.c_cflag &= ~(PARENB | PARODD | CRTSCTS | CSTOPB);
+	tty.c_iflag &= ~(IXON | IXOFF | IXANY | IGNBRK | BRKINT | ICRNL | INLCR);
+	tty.c_oflag &= ~OPOST;
+	tty.c_lflag = 0;
+	tty.c_cc[VMIN] = 1;
+	tty.c_cc[VTIME] = 0;
+	if (tcsetattr(fd, TCSANOW, &tty) != 0) {
+		perror("tcsetattr");
+		free(data);
+		close(fd);
+		return 1;
+	}
+
+	fprintf(stderr, "Sending %ld bytes (entry 0x%08x)...\n", size, entry);
+
+	memcpy(hdr, "KXEC", 4);
+	put32le(hdr + 4, entry);
+	put32le(hdr + 8, (uint32_t)size);
+
+	if (write(fd, hdr, 12) != 12) {
+		perror("write header");
+		free(data);
+		close(fd);
+		return 1;
+	}
+	tcdrain(fd);
+
+	if (write(fd, data, (size_t)size) != size) {
+		perror("write data");
+		free(data);
+		close(fd);
+		return 1;
+	}
+	tcdrain(fd);
+
+	hdr[0] = (unsigned char)cksum;
+	if (write(fd, hdr, 1) != 1) {
+		perror("write checksum");
+		free(data);
+		close(fd);
+		return 1;
+	}
+	tcdrain(fd);
+
+	fprintf(stderr, "Done.\n");
+	free(data);
+	close(fd);
+	return 0;
+}

+ 59 - 0
kexec_tramp.S

@@ -0,0 +1,59 @@
+/* Position-independent kexec trampoline. Copied to 0x800 at runtime (see
+ * kexec.c) because the final copy overwrites the kernel code we're executing.
+ *
+ * Args in registers (set by kexec.c):
+ *   eax = source (staging buffer)
+ *   ebx = dest   (0x7E00)
+ *   ecx = byte count
+ *   edx = entry  (new kernel_main)
+ *
+ * Also rebuilds a flat GDT at 0x900 and loads it, so the new kernel's segment
+ * reloads (iret on the first context switch) don't read the old GDT that lives
+ * inside the kernel region we overwrite. 0x900 is below 0x7E00 and is never
+ * overwritten, so the GDT survives. Clobbers esi/edi. Never returns.
+ */
+.code32
+.text
+
+.globl kexec_trampoline
+kexec_trampoline:
+	cli
+	pushl %eax
+	pushl %ebx
+	pushl %ecx
+	pushl %edx
+
+	/* Mask all IRQs. */
+	movb  $0xFF, %al
+	outb  %al, $0x21
+	outb  %al, $0xA1
+
+	/* Build flat GDT (base 0 / 4 GB) at 0x900 and load it. */
+	movl  $0x900, %edi
+	movl  $0, 0(%edi)          /* null */
+	movl  $0, 4(%edi)
+	movl  $0x0000FFFF, 8(%edi) /* code: limit 0xFFFF, base low 0 */
+	movl  $0x00CF9A00, 12(%edi)/* code: base mid 0, 0x9A, 0xCF, base hi 0 */
+	movl  $0x0000FFFF, 16(%edi)/* data: limit 0xFFFF, base low 0 */
+	movl  $0x00CF9200, 20(%edi)/* data: base mid 0, 0x92, 0xCF, base hi 0 */
+	movw  $0x17, 24(%edi)      /* gdtr limit = 23 */
+	movl  $0x900, 26(%edi)     /* gdtr base = 0x900 */
+	lgdt  24(%edi)
+
+	popl  %edx
+	popl  %ecx
+	popl  %ebx
+	popl  %eax
+
+	/* Copy new kernel: src=eax -> dst=ebx, count=ecx. */
+	movl  %eax, %esi
+	movl  %ebx, %edi
+	cld
+	rep   movsb
+
+	movl  $0x20800, %esp
+	jmp   *%edx
+
+.globl kexec_trampoline_end
+kexec_trampoline_end:
+	nop

+ 2 - 2
serial.c

@@ -7,8 +7,8 @@ void serial_init(unsigned int port)
 {
 	port_outb(port + 1, 0x00);
 	port_outb(port + 3, 0x80);
-	port_outb(port + 0, 0x0C);
-	port_outb(port + 1, 0x00);
+	port_outb(port + 0, 0x01); /* divisor low = 1  -> 115200 baud */
+	port_outb(port + 1, 0x00); /* divisor high = 0 */
 	port_outb(port + 3, 0x03);
 	port_outb(port + 2, 0xC7);
 	port_outb(port + 4, 0x03);

+ 1 - 0
serial.h

@@ -15,6 +15,7 @@ void serial_poll(void);
 void serial_ring_init(void);
 int  serial_ring_getc(void);
 int  serial_ring_wait(unsigned int timeout_ms, unsigned char *out);
+int  serial_ring_peek(unsigned int offset, unsigned char *byte);
 
 extern unsigned int serial_recv_size;
 

+ 14 - 0
serial_ring_buf.c

@@ -39,3 +39,17 @@ unsigned int serial_ring_count(void)
 		return h - t;
 	return SERIAL_RING_SIZE - t + h;
 }
+
+/* Peek at byte `offset` from the front of the queue without consuming it.
+ * Returns 1 and stores the byte, or 0 if `offset` is past the queued data. */
+int serial_ring_peek(unsigned int offset, unsigned char *byte)
+{
+	unsigned int h = ring_head;
+	unsigned int t = ring_tail;
+	unsigned int count = (h >= t) ? (h - t) : (SERIAL_RING_SIZE - t + h);
+
+	if (offset >= count)
+		return 0;
+	*byte = ring_buf[(t + offset) % SERIAL_RING_SIZE];
+	return 1;
+}

+ 1 - 0
serial_ring_buf.h

@@ -8,5 +8,6 @@ void serial_ring_init(void);
 void serial_ring_push(unsigned char byte);
 int  serial_ring_pop(unsigned char *byte);
 unsigned int serial_ring_count(void);
+int  serial_ring_peek(unsigned int offset, unsigned char *byte);
 
 #endif

+ 35 - 3
terminal.c

@@ -4,11 +4,13 @@
 #include "io.h"
 #include "fbtext.h"
 #include "idle.h"
+#include "kexec.h"
 #include "mouse.h"
 #include "process.h"
 #include "rtc.h"
 #include "terminal.h"
 #include "timer.h"
+#include "version.h"
 #include "vga.h"
 
 extern void program_hello_main(void);
@@ -74,8 +76,8 @@ static void update_cursor_blink(void)
 		io_cursor_hide_block();
 }
 
-static const char banner[] __attribute__((section(".text"))) = "Nebs OS |o|";
-#define BANNER_LEN 12
+static const char banner[] __attribute__((section(".text"))) = OS_NAME " v" OS_VERSION;
+#define BANNER_LEN 14
 static const char prompt[] __attribute__((section(".text"))) = "\n> ";
 static const char prompt_first[] __attribute__((section(".text"))) = "> ";
 
@@ -387,6 +389,21 @@ static int is_cmd_kill(const char *line, unsigned int line_len, unsigned int *pi
 	return 1;
 }
 
+static int is_cmd_kexec(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 5 > line_len)
+		return 0;
+	if (line[i] != 'k' || line[i+1] != 'e' || line[i+2] != 'x' || line[i+3] != 'e' || line[i+4] != 'c')
+		return 0;
+	i += 5;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
 static int is_cmd_serial(const char *line, unsigned int line_len, char *arg_buf, unsigned int buf_size)
 {
 	unsigned int i = 0, j = 0;
@@ -655,6 +672,16 @@ void terminal_run(void)
 							io_putstr("kill: no such process\n");
 						else
 							io_putstr("killed\n");
+					} else if (is_cmd_kexec(line, line_len)) {
+						if (kexec_busy) {
+							io_putstr("kexec: already receiving\n");
+						} else {
+							kexec_busy = 1;
+							if (process_create("kexec", program_kexec_main) < 0) {
+								kexec_busy = 0;
+								io_putstr("error: too many processes\n");
+							}
+						}
 					} else if (is_cmd_help(line, line_len)) {
 						io_putstr("hello     reboot    poweroff\n");
 						io_putstr("ls        cat <file>\n");
@@ -665,7 +692,7 @@ void terminal_run(void)
 						io_putstr("power [info|set <low|balanced|max>]\n");
 						io_putstr("drive <0|1>\n");
 					io_putstr("ps        kill <pid>\n");
-					io_putstr("serial test|recv  clear\n");
+					io_putstr("kexec     serial test|recv  clear\n");
 				} else if (is_cmd_clear(line, line_len)) {
 					io_clear_screen();
 					draw_header_row();
@@ -722,6 +749,11 @@ void terminal_run(void)
 					}
 				}
 			} else {
+				if (!kexec_busy && kexec_pending()) {
+					kexec_busy = 1;
+					if (process_create("kexec", program_kexec_main) < 0)
+						kexec_busy = 0;
+				}
 				cpu_idle();
 			}
 		}

+ 9 - 0
version.h

@@ -0,0 +1,9 @@
+/* OS name/version — single source of truth for the terminal banner and the
+ * serial boot line. */
+#ifndef VERSION_H
+#define VERSION_H
+
+#define OS_NAME    "Nebs OS"
+#define OS_VERSION "0.2.0"
+
+#endif