Sfoglia il codice sorgente

Remove the debug overlay and expand the fatal exception screen

Delete kdbg.c/h: the bottom-left status/info rows, the bottom-right heartbeat
and the IRQ/key counters are gone, along with the PIT hook in switch.S and the
row writers in mtrr.c/r8168.c (their serial logs stay).  The IRQ1 storm guard
remains in io.c and the WM polls through io_keyboard_irq_masked().

The fatal exception screen moves to panic.c/h and now captures much more:

- timer.S keeps the CPU error code (a zero is injected for vectors that push
  none), saves the GPRs with pusha and passes a struct exc_state pointer, so
  the handler sees vector/err/eip/cs/eflags/esp/ss plus EAX..EDI.
- panic_report() draws straight into the LFB (no WM/shadow dependency) and
  mirrors the same lines to COM1: vector and error code (#PF decodes
  P/W/U/RSVD/ID), EIP/CS/EFLAGS, GPRs, CR0/CR2/CR3/CR4, pid/name, uptime and
  kernel-stack bounds, the bytes at EIP, and stack dwords plus return-address
  candidates found by scanning the faulting stack page.
- COM1 additionally gets 32 stack dwords and every candidate with its offset.
- Ring-3 faults still kill the offending command without halting.

Addresses are raw kernel addresses, for nm kernel.elf / addr2line.
Johannes Zellner 2 settimane fa
parent
commit
d78138aaa1
15 ha cambiato i file con 511 aggiunte e 575 eliminazioni
  1. 39 72
      AGENTS.md
  2. 6 6
      Makefile
  3. 8 20
      io.c
  4. 3 1
      io.h
  5. 0 252
      kdbg.c
  6. 0 41
      kdbg.h
  7. 11 36
      kernel.c
  8. 5 35
      mtrr.c
  9. 391 0
      panic.c
  10. 32 0
      panic.h
  11. 5 86
      r8168.c
  12. 0 5
      switch.S
  13. 0 4
      terminal.c
  14. 10 9
      timer.S
  15. 1 8
      wm.c

+ 39 - 72
AGENTS.md

@@ -151,9 +151,10 @@ below the run area), so adding code no longer moves any address.
   `screen_damage_cell()`/`screen_damage_cursor()`, reset by
   `screen_clear_damage()`), so the WM repaints a keystroke's cell instead of the
   whole window content and the blink only marks the cursor's own cell.
-- **On-screen debug**: `kdbg.c/h` — framebuffer debug overlay (live status rows,
-  heartbeat, boot info rows, exception banner) for machines without serial; see
-  the kdbg section below.
+- **Fatal exception screen**: `panic.c/h`, `timer.S` — on a ring-0 fault,
+  dumps vector/error code, GPRs, CRs, EIP instruction bytes and stack
+  return-address candidates straight into the LFB (and COM1) before halting;
+  see the panic section below.
 - **Shell**: `terminal.c` — history, line editing, and a table-driven command
   registry (`cmds[]`: name, usage, spawn kind/handler) that holds only the
   builtins (`cd`, `path`, `help`, `clear`) and the kernel commands.  Everything
@@ -586,75 +587,41 @@ QEMU gotchas that bit once:
   written while no client is attached, so a late-connecting reader misses the
   boot log (kexec tests that wait for it then mis-report a failed reload).
 
-## On-screen debug overlay (`kdbg`)
-
-For machines **without a serial console** (e.g. the ASUS AT3IONT-I), `kdbg.c/h`
-draws a debug overlay straight into the VESA LFB, bypassing the shadow buffer
-and the WM. It stays on screen even when the WM or the scheduler is wedged, so
-a freeze can be diagnosed by reading/photographing the screen. This is how the
-"freeze on first key press" was tracked down: the counters showed that no key
-event ever reached the OS (all zeros) and the heartbeat stopped, i.e. the CPU
-was wedged in firmware/SMM before IRQ1 was delivered.
-
-Layout (bottom-left, and a heartbeat square bottom-right):
-
-```
-MTRRdef 00000E06 vcnt 8            <- boot info rows (yellow), up to 14
-M0 b=00000000 m=FF000800 WB
-...
-WC=e7 b=FD000000 s=00800000
-IRQ 12  SC 9C  BY 12  OT 0  MK 0   <- live status row 1 (green)
-WM 6  K 000A  TRM 6  K 000A        <- live status row 2 (blue)
-```
-
-**Live status rows** (bottom two, refreshed on key events and 1×/s):
-
-- `IRQ` — IRQ1 entries; `SC` — last scancode read from port 0x60; `BY` —
-  scancode bytes read (IRQ + polling); `OT` — dropped other/AUX bytes; `MK` —
-  1 if the IRQ1 storm guard tripped (IRQ1 masked; WM falls back to polling).
-- `WM n K xxxx` — keys handed by the WM to the focused terminal; `TRM n K xxxx`
-  — keys consumed by `term_run`; `K` = last key value.
-- **Heartbeat square** (bottom-right) toggles every 500 ticks (~1 Hz) from the
-  PIT IRQ. If it stops, the *CPU* is wedged, not just the UI.
-
-**Info rows** (yellow, above the status rows) are boot-time diagnostics, e.g.
-the MTRR dump from `mtrr.c`: `MTRRdef` = default-type MSR + number of variable
-slots; `M0..M7` = the BIOS's own MTRR entries as found at boot (`-` = free
-slot; `b`/`m` = base/address mask; type `UC`/`WB`/`WC`/`WT`/`WP`); `WC=eN ...`
-= the write-combining entry the kernel added in free slot N for the
-framebuffer (or `WC skipped: no free MTRR entry`). An entry that already
-covers the LFB base (left by a previous kexec boot -- variable MTRRs survive
-a kernel reload) is reused instead of consuming another slot. Never overwrite
-BIOS-populated MTRR entries — chipset/MMIO uncacheability (and the USB-legacy
-SMM) breaks otherwise.
-
-**Exception banner**: `exc_handler()` (`kernel.c`) calls `kdbg_panic()`, which
-draws a red banner with vector name, EIP and CR2 at the top of the screen
-(visible without serial) before the CPU halts.  Faults from ring 3 do not halt:
-the process is killed (with a short message in its terminal and on serial) and
-the kernel keeps running.
-
-API / wiring:
-
-- `kdbg_init()` — cache LFB geometry; call after `vga_shadow_init()`.
-- `kdbg_status()` — redraw the live rows; called from key paths and the PIT.
-- `kdbg_info(row, s)` — set one of 14 info rows (row 0 = lowest, at
-  `fb_h-31`). Text is **copied**, so stack buffers are fine, and it is safe to
-  call before `kdbg_init()` (stored, drawn once the framebuffer is up).
-- `kdbg_info_alloc()` — claim the next free info row (`-1` when full); boot
-  subsystems (MTRR dump, NIC) take rows in init order without colliding.
-- `kdbg_pit_tick()` — called from the PIT stub (`switch.S`); blinks the
-  heartbeat and refreshes the overlay every second.
-- Counters live in `kdbg.c`, bumped from `io.c` (`kbd_irq`,
-  `io_poll_key_with_hw`), `wm.c` (`wm_handle_keyboard`) and `terminal.c`
-  (`term_run`).
-
-Caveats:
-
-- Pixels are written directly to the LFB; WM full redraws overwrite them but
-  the 1 Hz refresh brings them back.
-- Info rows cost ~0.5 KB BSS; keep the kernel under the `0x7F000` boundary
-  (`kernel.ld` ASSERT).
+## Fatal exception screen (`panic`)
+
+The on-screen debug overlay (`kdbg`: live counters, heartbeat, boot info rows)
+has been removed.  The one diagnostic screen left is the fatal exception
+banner: on a ring-0 fault, `exc_handler()` (`kernel.c`) calls
+`panic_report()` (`panic.c/h`), which draws straight into the VESA LFB
+(bypassing the shadow buffer and the WM) and mirrors the same data to COM1,
+then halts.  Faults from ring 3 do not halt: the process is killed (with a
+short message in its terminal and on serial) and the kernel keeps running.
+
+What the banner and the COM1 dump contain:
+
+- vector name/number and the CPU error code (`#PF` also decodes P/W/U/RSVD/ID),
+- EIP, CS (ring), EFLAGS, and the faulting ESP (ring 0) or user ESP/SS,
+- EAX..EDI and EBP,
+- CR0, CR2, CR3, CR4,
+- current pid/name and uptime ticks,
+- up to 16 bytes at EIP (read only from mapped RAM and clipped at the page
+  boundary, so the dump cannot fault again),
+- a few stack dwords plus return-address candidates found by scanning the
+  faulting stack page for values in the kernel image (`0x7E00..__bss_end`).
+  `-O2` omits frame pointers, so there is no EBP-chain backtrace; the
+  candidates are hints, not a true trace.
+
+COM1 additionally gets 32 stack dwords and every candidate, each with its
+offset from the faulting ESP.  Addresses are raw kernel addresses: resolve
+them with `nm kernel.elf` / `addr2line -e kernel.elf <addr>`.
+
+Wiring: `timer.S` builds a `struct exc_state` (GPRs via `pusha` and the CPU's
+exception frame, including the error code that the old stubs discarded) and
+passes it to `exc_handler()`; `panic.h` documents the layout.  The banner
+caches the LFB geometry lazily, so no boot hook is needed.  The MTRR dump and
+the NIC bring-up trail that used to fill the info rows now go to COM1 only
+(`mtrr.c`, `r8168.c`).  The IRQ1 storm guard still masks a storming keyboard
+and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 ## Conventions & gotchas
 

+ 6 - 6
Makefile

@@ -20,7 +20,7 @@ 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 usbhid.h version.h vga.h
+kernel.o: kernel.c idle.h io.h mouse.h panic.h process.h terminal.h timer.h serial.h usbhid.h version.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 screen.o: screen.c screen.h
@@ -110,7 +110,7 @@ nv50.o: nv50.c nv50.h nvidia.h serial.h
 radeon.o: radeon.c radeon.h pci.h paging.h serial.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-mtrr.o: mtrr.c mtrr.h kdbg.h serial.h
+mtrr.o: mtrr.c mtrr.h serial.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 gfx.o: gfx.c gfx.h mm.h vga.h
@@ -137,7 +137,7 @@ usbhid.o: usbhid.c usbhid.h io.h usb.h usb_hcd.h serial.h timer.h
 lsusb.o: lsusb.c io.h usb.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
-kdbg.o: kdbg.c kdbg.h font_8x8.h timer.h vga.h
+panic.o: panic.c panic.h font_8x8.h process.h serial.h timer.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 lspci.o: lspci.c io.h pci.h
@@ -149,7 +149,7 @@ peek.o: peek.c io.h
 ne2000.o: ne2000.c ne2000.h pci.h timer.h io.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
-r8168.o: r8168.c r8168.h netdev.h io.h kdbg.h mm.h paging.h pci.h process.h serial.h timer.h
+r8168.o: r8168.c r8168.h netdev.h io.h mm.h paging.h pci.h process.h serial.h timer.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
 netkexec.o: netkexec.c netkexec.h io.h kexec.h net.h netdev.h timer.h
@@ -257,7 +257,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o prog_embed.o space_embed.o cmds_pack.o ramfs.o payload.o
+kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o prog_embed.o space_embed.o cmds_pack.o ramfs.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -600,4 +600,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 8 - 20
io.c

@@ -4,7 +4,6 @@
 
 #include "io.h"
 #include "fbtext.h"
-#include "kdbg.h"
 #include "process.h"
 #include "screen.h"
 #include "timer.h"
@@ -47,7 +46,6 @@ static const unsigned char scancode_to_ascii[256] __attribute__((section(".rodat
 
 static int shift_pressed;
 static int ctrl_pressed;
-static unsigned char last_scancode;
 static int kbd_extended;  /* 1 after 0xE0, next byte is extended scancode */
 
 #define KBD_BUF_SIZE 16
@@ -70,6 +68,12 @@ static struct text_screen *io_current_screen(void)
  * gets absurd we mask IRQ1 and let the WM fall back to polling. */
 static unsigned int kbd_win_start;
 static unsigned int kbd_win_count;
+static volatile int kbd_irq_masked;
+
+int io_keyboard_irq_masked(void)
+{
+	return kbd_irq_masked;
+}
 
 void kbd_irq(void)
 {
@@ -77,18 +81,15 @@ void kbd_irq(void)
 	unsigned int now = get_ticks_ms();
 	unsigned char st;
 
-	kdbg_irq_count++;
-	if (kdbg_irq_count <= 8)
-		kdbg_status();
 	if (now - kbd_win_start >= 1000) {
 		kbd_win_start = now;
 		kbd_win_count = 0;
 	}
 	kbd_win_count++;
-	if (!kdbg_irq_masked && kbd_win_count > 200) {
+	if (!kbd_irq_masked && kbd_win_count > 200) {
 		/* IRQ1 storm; mask it (master PIC) and poll instead. */
 		outb(0x21, (unsigned char)(inb(0x21) | 0x02));
-		kdbg_irq_masked = 1;
+		kbd_irq_masked = 1;
 	}
 
 	while (guard++ < 32) {
@@ -99,13 +100,8 @@ void kbd_irq(void)
 			unsigned char sc = inb(KB_DATA);
 			if (st & 0x20) {
 				/* AUX (mouse) byte: not ours, drop it. */
-				kdbg_irq_other++;
 				continue;
 			}
-			kdbg_irq_bytes++;
-			kdbg_last_sc = sc;
-			if (kdbg_irq_count <= 8)
-				kdbg_status();
 			{
 				unsigned int next = (kbd_head + 1) % KBD_BUF_SIZE;
 				if (next != kbd_tail) {
@@ -257,7 +253,6 @@ static int kbd_process_byte(unsigned char sc)
 	{
 		char c = (char)scancode_to_ascii[sc];
 		if (c) {
-			last_scancode = sc;
 			c = apply_shift(c);
 			if (ctrl_pressed) {
 				/* Ctrl+letter -> control character (e.g. Ctrl+C -> 0x03). */
@@ -307,16 +302,9 @@ int io_poll_key_with_hw(void)
 
 	if (!got)
 		return 0;
-	kdbg_irq_bytes++;
-	kdbg_last_sc = sc;
 	return kbd_process_byte(sc);
 }
 
-unsigned char io_last_scancode(void)
-{
-	return last_scancode;
-}
-
 /* Queue a scancode from a non-IRQ source (the USB keyboard backend); the
    normal io_poll_key/io_poll_key_with_hw path then decodes it.  Interrupts
    are masked while touching the ring so an IRQ1 producer cannot corrupt it. */

+ 3 - 1
io.h

@@ -37,7 +37,9 @@ void io_drain_keyboard(void);
 int io_poll_key(void);
 /* Same as io_poll_key but also reads port 0x60 when buffer empty (for full-screen programs). */
 int io_poll_key_with_hw(void);
-unsigned char io_last_scancode(void);
+/* 1 when the IRQ1 storm guard masked the keyboard; the WM then polls the
+   controller directly (every few ms) instead of relying on interrupts. */
+int io_keyboard_irq_masked(void);
 /* Queue a PS/2 set-1 scancode from a non-IRQ source (USB keyboard backend);
    it is then decoded by the normal io_poll_key path. */
 void io_inject_scancode(unsigned char sc);

+ 0 - 252
kdbg.c

@@ -1,252 +0,0 @@
-/* On-screen kernel debug output: see kdbg.h. */
-
-#include "kdbg.h"
-#include "font_8x8.h"
-#include "timer.h"
-#include "vga.h"
-
-volatile unsigned int kdbg_irq_count;
-volatile unsigned int kdbg_irq_bytes;
-volatile unsigned int kdbg_irq_other;
-volatile unsigned int kdbg_last_sc;
-volatile unsigned int kdbg_irq_masked;
-volatile unsigned int kdbg_wm_count;
-volatile unsigned int kdbg_wm_last;
-volatile unsigned int kdbg_term_count;
-volatile unsigned int kdbg_term_last;
-
-static unsigned int fb_w, fb_h, fb_pitch, fb_bpp;
-static volatile unsigned char *fb_lfb;
-static int fb_ok;
-
-#define KDBG_INFO_MAX 14
-static char kdbg_info_buf[KDBG_INFO_MAX][40];
-static unsigned char kdbg_info_used[KDBG_INFO_MAX];
-static unsigned int kdbg_info_next;
-
-void kdbg_init(void)
-{
-	fb_w = vga_fb_width();
-	fb_h = vga_fb_height();
-	fb_pitch = vga_fb_pitch();
-	fb_bpp = vga_fb_bpp();
-	fb_lfb = (volatile unsigned char *)(unsigned long)vga_fb_lfb_addr();
-	fb_ok = (fb_w > 0 && fb_h > 60 && fb_pitch > 0 && fb_lfb &&
-		 (fb_bpp == 16 || fb_bpp == 24 || fb_bpp == 32));
-}
-
-static void px(unsigned int x, unsigned int y,
-	       unsigned int r, unsigned int g, unsigned int b)
-{
-	volatile unsigned char *p;
-
-	if (!fb_ok || x >= fb_w || y >= fb_h)
-		return;
-	p = fb_lfb + (unsigned long)y * fb_pitch + (unsigned long)x * (fb_bpp / 8);
-	if (fb_bpp == 16) {
-		unsigned int v = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
-		p[0] = (unsigned char)(v & 0xFF);
-		p[1] = (unsigned char)(v >> 8);
-	} else if (fb_bpp == 24) {
-		p[0] = (unsigned char)b;
-		p[1] = (unsigned char)g;
-		p[2] = (unsigned char)r;
-	} else {
-		p[0] = (unsigned char)b;
-		p[1] = (unsigned char)g;
-		p[2] = (unsigned char)r;
-		p[3] = 0;
-	}
-}
-
-static void rect(unsigned int x, unsigned int y, unsigned int w, unsigned int h,
-		 unsigned int r, unsigned int g, unsigned int b)
-{
-	unsigned int i, j;
-	for (j = 0; j < h; j++)
-		for (i = 0; i < w; i++)
-			px(x + i, y + j, r, g, b);
-}
-
-static void draw_ch(unsigned int x, unsigned int y, char c, unsigned int sc,
-		    unsigned int r, unsigned int g, unsigned int b)
-{
-	const unsigned char *gl = &font_8x8[(unsigned char)c * 8];
-	unsigned int row, col, i, j;
-
-	for (row = 0; row < 8; row++) {
-		unsigned char bits = gl[row];
-		for (col = 0; col < 8; col++) {
-			if (bits & (0x80 >> col)) {
-				for (i = 0; i < sc; i++)
-					for (j = 0; j < sc; j++)
-						px(x + col * sc + i,
-						   y + row * sc + j, r, g, b);
-			}
-		}
-	}
-}
-
-static void draw_str(unsigned int x, unsigned int y, unsigned int sc,
-		     const char *s, unsigned int r, unsigned int g, unsigned int b)
-{
-	while (*s) {
-		draw_ch(x, y, *s, sc, r, g, b);
-		x += 8 * sc;
-		s++;
-	}
-}
-
-static unsigned int app_str(char *buf, unsigned int i, const char *s)
-{
-	while (*s)
-		buf[i++] = *s++;
-	return i;
-}
-
-static unsigned int app_dec(char *buf, unsigned int i, unsigned int v)
-{
-	char tmp[11];
-	unsigned int n = 0, j;
-
-	if (v == 0) {
-		buf[i++] = '0';
-		return i;
-	}
-	while (v) {
-		tmp[n++] = (char)('0' + v % 10);
-		v /= 10;
-	}
-	for (j = n; j > 0; j--)
-		buf[i++] = tmp[j - 1];
-	return i;
-}
-
-static unsigned int app_hex(char *buf, unsigned int i, unsigned int v,
-			    unsigned int digits)
-{
-	static const char hx[] = "0123456789ABCDEF";
-	unsigned int d;
-
-	for (d = 0; d < digits; d++)
-		buf[i++] = hx[(v >> (4 * (digits - 1 - d))) & 0xF];
-	return i;
-}
-
-static void kdbg_draw_info_row(unsigned int row)
-{
-	unsigned int y;
-
-	if (!fb_ok || row >= KDBG_INFO_MAX || !kdbg_info_used[row])
-		return;
-	y = fb_h - 31 - row * 10;
-	rect(0, y, 400, 9, 0, 0, 0);
-	draw_str(1, y, 1, kdbg_info_buf[row], 255, 220, 80);
-}
-
-void kdbg_info(unsigned int row, const char *s)
-{
-	unsigned int i = 0;
-
-	if (row >= KDBG_INFO_MAX)
-		return;
-	while (s[i] && i < sizeof(kdbg_info_buf[0]) - 1) {
-		kdbg_info_buf[row][i] = s[i];
-		i++;
-	}
-	kdbg_info_buf[row][i] = '\0';
-	kdbg_info_used[row] = 1;
-	kdbg_draw_info_row(row);
-}
-
-static void kdbg_redraw_info(void)
-{
-	unsigned int r;
-
-	for (r = 0; r < KDBG_INFO_MAX; r++)
-		kdbg_draw_info_row(r);
-}
-
-int kdbg_info_alloc(void)
-{
-	if (kdbg_info_next >= KDBG_INFO_MAX)
-		return -1;
-	return (int)kdbg_info_next++;
-}
-
-void kdbg_status(void)
-{
-	char buf[96];
-	unsigned int i;
-
-	if (!fb_ok)
-		return;
-
-	i = 0;
-	i = app_str(buf, i, "IRQ ");
-	i = app_dec(buf, i, kdbg_irq_count);
-	i = app_str(buf, i, " SC ");
-	i = app_hex(buf, i, kdbg_last_sc, 2);
-	i = app_str(buf, i, " BY ");
-	i = app_dec(buf, i, kdbg_irq_bytes);
-	i = app_str(buf, i, " OT ");
-	i = app_dec(buf, i, kdbg_irq_other);
-	i = app_str(buf, i, " MK ");
-	i = app_dec(buf, i, kdbg_irq_masked);
-	buf[i] = '\0';
-	rect(0, fb_h - 21, 400, 9, 0, 0, 0);
-	draw_str(1, fb_h - 21, 1, buf, 120, 255, 120);
-
-	i = 0;
-	i = app_str(buf, i, "WM ");
-	i = app_dec(buf, i, kdbg_wm_count);
-	i = app_str(buf, i, " K ");
-	i = app_hex(buf, i, kdbg_wm_last, 4);
-	i = app_str(buf, i, " TRM ");
-	i = app_dec(buf, i, kdbg_term_count);
-	i = app_str(buf, i, " K ");
-	i = app_hex(buf, i, kdbg_term_last, 4);
-	buf[i] = '\0';
-	rect(0, fb_h - 11, 400, 9, 0, 0, 0);
-	draw_str(1, fb_h - 11, 1, buf, 120, 180, 255);
-
-	kdbg_redraw_info();
-}
-
-/* Called from the PIT IRQ (~1 kHz). */
-void kdbg_pit_tick(void)
-{
-	static unsigned int n;
-
-	n++;
-	if (!fb_ok)
-		return;
-	if ((n % 500) == 0) {
-		int on = (int)((n / 500) & 1);
-		/* 1 Hz heartbeat square, bottom-right corner. */
-		rect(fb_w - 12, fb_h - 12, 10, 10,
-		     on ? 0 : 60, on ? 255 : 60, on ? 0 : 60);
-	}
-	if ((n % 1000) == 0)
-		kdbg_status();
-}
-
-void kdbg_panic(const char *name, unsigned int eip, unsigned int cr2)
-{
-	char buf[64];
-	unsigned int i = 0;
-
-	if (!fb_ok)
-		return;
-
-	rect(0, 0, fb_w, 52, 140, 0, 0);
-	draw_str(4, 4, 2, "*** EXCEPTION ***", 255, 255, 255);
-	draw_str(4, 26, 1, name, 255, 255, 0);
-	i = app_str(buf, i, "EIP ");
-	i = app_hex(buf, i, eip, 8);
-	i = app_str(buf, i, "  CR2 ");
-	i = app_hex(buf, i, cr2, 8);
-	buf[i] = '\0';
-	draw_str(4, 38, 1, buf, 255, 200, 200);
-	kdbg_status();
-}

+ 0 - 41
kdbg.h

@@ -1,41 +0,0 @@
-/* On-screen kernel debug output (no serial console needed).
- *
- * Draws straight into the linear framebuffer, bypassing the shadow buffer
- * and the window manager, so it still works when the WM is wedged.  Used on
- * real hardware to debug e.g. keyboard/IRQ problems:
- *
- *   - kdbg_status():  two counter lines in the bottom-left corner
- *   - kdbg_pit_tick(): 0.5s heartbeat square (bottom-right) + periodic
- *                     status refresh, called from the PIT IRQ
- *   - kdbg_panic():   red banner with exception info
- */
-#ifndef KDBG_H
-#define KDBG_H
-
-void kdbg_init(void);
-void kdbg_status(void);
-void kdbg_pit_tick(void);
-void kdbg_panic(const char *name, unsigned int eip, unsigned int cr2);
-
-/* Extra debug lines drawn above the status block (row 0 = lowest, at
-   fb_h-31).  Text is copied, so callers may pass stack buffers.  Safe to
-   call before kdbg_init(): the text is stored and drawn once the
-   framebuffer is up. */
-void kdbg_info(unsigned int row, const char *s);
-
-/* Allocate the next free info row (boot subsystems claim rows in init
-   order).  Returns -1 when every row is already taken. */
-int kdbg_info_alloc(void);
-
-/* Counters shared by the keyboard IRQ, the WM and the terminal. */
-extern volatile unsigned int kdbg_irq_count;   /* IRQ1 entries */
-extern volatile unsigned int kdbg_irq_bytes;   /* scancode bytes read */
-extern volatile unsigned int kdbg_irq_other;   /* AUX/empty reads */
-extern volatile unsigned int kdbg_last_sc;     /* last scancode read */
-extern volatile unsigned int kdbg_irq_masked;  /* storm guard tripped */
-extern volatile unsigned int kdbg_wm_count;    /* keys handled by the WM */
-extern volatile unsigned int kdbg_wm_last;
-extern volatile unsigned int kdbg_term_count;  /* keys handled by terminal */
-extern volatile unsigned int kdbg_term_last;
-
-#endif

+ 11 - 36
kernel.c

@@ -2,7 +2,7 @@
 
 #include "idle.h"
 #include "io.h"
-#include "kdbg.h"
+#include "panic.h"
 #include "kmalloc.h"
 #include "mm.h"
 #include "mouse.h"
@@ -56,9 +56,10 @@ unsigned int get_ticks_ms(void)
 	return ticks;
 }
 
-void exc_handler(unsigned int eip, unsigned int vector, unsigned int cs);
-void exc_handler(unsigned int eip, unsigned int vector, unsigned int cs)
+void exc_handler(struct exc_state *st);
+void exc_handler(struct exc_state *st)
 {
+	unsigned int vector = st->vector;
 	unsigned int cr2 = 0;
 	static const char * const names[] = {
 		"#DE Divide Error", "#DB Debug", "NMI", "#BP Breakpoint",
@@ -73,46 +74,22 @@ void exc_handler(unsigned int eip, unsigned int vector, unsigned int cs)
 
 	/* A fault from ring 3 is a bug in a user command (or its ELF): kill that
 	 * process and keep the kernel running.  Kernel faults still halt. */
-	if ((cs & 3) == 3) {
+	if ((st->cs & 3) == 3) {
 		serial_puts(SERIAL_COM1, "\n*** user fault vec ");
 		serial_puthex(SERIAL_COM1, vector);
 		serial_puts(SERIAL_COM1, " eip=");
-		serial_puthex(SERIAL_COM1, eip);
+		serial_puthex(SERIAL_COM1, st->eip);
+		serial_puts(SERIAL_COM1, " cr2=");
+		serial_puthex(SERIAL_COM1, cr2);
 		serial_puts(SERIAL_COM1, " -- process killed\n");
 		io_putstr("\n*** fault: ");
 		io_putstr(vector < 20 ? names[vector] : "unknown vector");
 		io_putstr(" -- command killed\n");
 		process_exit();     /* marks us dead and waits to be switched out */
 	}
-	/* Draw the fault info directly into the framebuffer FIRST: with no
-	 * serial console attached, a fault was previously invisible (the text
-	 * went to the current process's screen buffer, which the WM never got
-	 * to render because the CPU halts here). */
-	kdbg_panic(vector < 20 ? names[vector] : "unknown vector", eip, cr2);
-	/* Print the fault to serial, using only minimal/no-stack code, so it
-	 * survives even if the screen buffer or kernel stack is the problem. */
-	serial_puts(SERIAL_COM1, "\n*** EXC vec ");
-	serial_puthex(SERIAL_COM1, vector);
-	serial_puts(SERIAL_COM1, " eip=");
-	serial_puthex(SERIAL_COM1, eip);
-	serial_puts(SERIAL_COM1, " cr2=");
-	serial_puthex(SERIAL_COM1, cr2);
-	serial_puts(SERIAL_COM1, " ");
-	if (vector < 20)
-		serial_puts(SERIAL_COM1, names[vector]);
-	serial_puts(SERIAL_COM1, " ***\n");
-
-	/* Then attempt the screen output (may fault if the screen is broken). */
-	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");
+	/* Fatal kernel fault: the banner goes straight into the LFB (no serial
+	 * console needed) and the full state is mirrored to COM1. */
+	panic_report(st, vector < 20 ? names[vector] : "unknown vector");
 	for (;;)
 		__asm__ volatile ("cli; hlt");
 }
@@ -218,8 +195,6 @@ void kernel_main(void)
 	usbhid_init();
 	vga_shadow_init();
 	vga_fb_flush();
-	kdbg_init();
-	kdbg_status();
 	vfs_mount_all();
 	/* The command pack: read-only, mounted at /ramfs (see ramfs.c). */
 	{

+ 5 - 35
mtrr.c

@@ -22,13 +22,11 @@
  *     version had them inverted, so e.g. a 16 MB request marked the first
  *     4 KB of every 16 MB block as WC instead of the framebuffer range.)
  *
- * The MTRR layout found at boot and the result are dumped to the on-screen
- * debug lines (kdbg) and to serial, so this can be inspected on machines
- * without a serial console.
+ * The MTRR layout found at boot and the result are dumped to serial, so this
+ * can be inspected on machines without a VGA console.
  */
 
 #include "mtrr.h"
-#include "kdbg.h"
 #include "serial.h"
 
 #define MSR_MTRRCAP        0x0FE
@@ -112,14 +110,12 @@ static const char *type_name(unsigned int t)
 	}
 }
 
-/* Dump MTRRdefType and the variable entries to kdbg and serial.  Rows come
- * from the kdbg info pool, so other subsystems keep their own. */
+/* Dump MTRRdefType and the variable entries to serial. */
 static void dump_mtrrs(unsigned int vcnt)
 {
 	char buf[56];
 	char *p;
 	unsigned int i, lo, hi, mlo, mhi;
-	int row;
 
 	rdmsr(MSR_MTRR_DEF_TYPE, &lo, &hi);
 	p = buf;
@@ -128,9 +124,6 @@ static void dump_mtrrs(unsigned int vcnt)
 	p = app(p, " vcnt ");
 	*p++ = (char)('0' + (vcnt > 9 ? 9 : vcnt));
 	*p = '\0';
-	row = kdbg_info_alloc();
-	if (row >= 0)
-		kdbg_info((unsigned int)row, buf);
 	serial_puts(SERIAL_COM1, buf);
 	serial_puts(SERIAL_COM1, "\n");
 
@@ -152,9 +145,6 @@ static void dump_mtrrs(unsigned int vcnt)
 			p = app(p, type_name(lo));
 		}
 		*p = '\0';
-		row = kdbg_info_alloc();
-		if (row >= 0)
-			kdbg_info((unsigned int)row, buf);
 		serial_puts(SERIAL_COM1, buf);
 		serial_puts(SERIAL_COM1, "\n");
 	}
@@ -168,9 +158,6 @@ int mtrr_set_wc(unsigned int base, unsigned int size,
 	unsigned int vcnt;
 	unsigned int i, use = ~0u;
 	unsigned int region_size, align, physmask;
-	int row;
-	char buf[56];
-	char *p;
 
 	if (!cpu_has_mtrr() || size == 0)
 		return 0;
@@ -182,8 +169,8 @@ int mtrr_set_wc(unsigned int base, unsigned int size,
 	if (vcnt == 0)
 		return 0;
 
-	/* Dump the first 8 at most (kdbg info rows are a shared pool); the
-	 * search below still covers every variable range. */
+	/* Dump the first 8 at most; the search below still covers every
+	 * variable range. */
 	dump_mtrrs(vcnt > 8 ? 8 : vcnt);
 
 	/* Round size up to the next power of two (min 4 KB). */
@@ -238,13 +225,7 @@ int mtrr_set_wc(unsigned int base, unsigned int size,
 		}
 	}
 
-	p = buf;
 	if (use == ~0u) {
-		p = app(p, "WC skipped: no free MTRR entry");
-		*p = '\0';
-		row = kdbg_info_alloc();
-		if (row >= 0)
-			kdbg_info((unsigned int)row, buf);
 		serial_puts(SERIAL_COM1, "mtrr: no free variable entry; skipping WC\n");
 		return 0;
 	}
@@ -265,17 +246,6 @@ int mtrr_set_wc(unsigned int base, unsigned int size,
 
 	wrmsr(MSR_MTRR_DEF_TYPE, def_type, 0);
 
-	p = app(p, "WC=e");
-	*p++ = (char)('0' + (use > 9 ? 9 : use));
-	p = app(p, " b=");
-	p = hex8(p, base);
-	p = app(p, " s=");
-	p = hex8(p, region_size);
-	*p = '\0';
-	row = kdbg_info_alloc();
-	if (row >= 0)
-		kdbg_info((unsigned int)row, buf);
-
 	serial_puts(SERIAL_COM1, "mtrr: LFB WC [");
 	serial_puthex(SERIAL_COM1, base);
 	serial_puts(SERIAL_COM1, " +");

+ 391 - 0
panic.c

@@ -0,0 +1,391 @@
+/* Fatal exception screen: see panic.h. */
+
+#include "panic.h"
+#include "font_8x8.h"
+#include "process.h"
+#include "serial.h"
+#include "timer.h"
+#include "vga.h"
+
+#define LINE_H      10
+#define PANIC_LINES 12
+#define RAM_LIMIT   0x08000000u   /* MM_MAX_PHYS: identity-mapped RAM */
+#define KERNEL_BASE 0x7E00u       /* kernel load address (kernel.ld) */
+
+static unsigned int fb_w, fb_h, fb_pitch, fb_bpp;
+static volatile unsigned char *fb_lfb;
+static int fb_ok;
+static unsigned int panic_line;
+
+static const char hx[] = "0123456789ABCDEF";
+
+extern unsigned char __bss_end[];
+
+/* 8 GPRs from pusha + vector/err/eip/cs/eflags/esp/ss. */
+_Static_assert(sizeof(struct exc_state) == 15 * sizeof(unsigned int),
+	       "struct exc_state must match the timer.S stub");
+
+/* --- direct LFB drawing (works with no WM/shadow) ----------------------- */
+
+static void cache_fb(void)
+{
+	fb_w = vga_fb_width();
+	fb_h = vga_fb_height();
+	fb_pitch = vga_fb_pitch();
+	fb_bpp = vga_fb_bpp();
+	fb_lfb = (volatile unsigned char *)(unsigned long)vga_fb_lfb_addr();
+	fb_ok = (fb_w > 0 && fb_h > 0 && fb_pitch > 0 && fb_lfb &&
+		 (fb_bpp == 16 || fb_bpp == 24 || fb_bpp == 32));
+}
+
+static void px(unsigned int x, unsigned int y,
+	       unsigned int r, unsigned int g, unsigned int b)
+{
+	volatile unsigned char *p;
+
+	if (!fb_ok || x >= fb_w || y >= fb_h)
+		return;
+	p = fb_lfb + (unsigned long)y * fb_pitch + (unsigned long)x * (fb_bpp / 8);
+	if (fb_bpp == 16) {
+		unsigned int v = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
+		p[0] = (unsigned char)(v & 0xFF);
+		p[1] = (unsigned char)(v >> 8);
+	} else {
+		p[0] = (unsigned char)b;
+		p[1] = (unsigned char)g;
+		p[2] = (unsigned char)r;
+		if (fb_bpp == 32)
+			p[3] = 0;
+	}
+}
+
+static void rect(unsigned int x, unsigned int y, unsigned int w, unsigned int h,
+		 unsigned int r, unsigned int g, unsigned int b)
+{
+	unsigned int i, j;
+	for (j = 0; j < h; j++)
+		for (i = 0; i < w; i++)
+			px(x + i, y + j, r, g, b);
+}
+
+static void draw_ch(unsigned int x, unsigned int y, char c, unsigned int sc,
+		    unsigned int r, unsigned int g, unsigned int b)
+{
+	const unsigned char *gl = &font_8x8[(unsigned char)c * 8];
+	unsigned int row, col, i, j;
+
+	for (row = 0; row < 8; row++) {
+		unsigned char bits = gl[row];
+		for (col = 0; col < 8; col++) {
+			if (bits & (0x80 >> col)) {
+				for (i = 0; i < sc; i++)
+					for (j = 0; j < sc; j++)
+						px(x + col * sc + i,
+						   y + row * sc + j, r, g, b);
+			}
+		}
+	}
+}
+
+static void draw_str(unsigned int x, unsigned int y, unsigned int sc,
+		     const char *s, unsigned int r, unsigned int g, unsigned int b)
+{
+	while (*s) {
+		draw_ch(x, y, *s, sc, r, g, b);
+		x += 8 * sc;
+		s++;
+	}
+}
+
+/* --- small freestanding formatters ------------------------------------- */
+
+static unsigned int app_str(char *buf, unsigned int i, const char *s)
+{
+	while (*s)
+		buf[i++] = *s++;
+	return i;
+}
+
+static unsigned int app_dec(char *buf, unsigned int i, unsigned int v)
+{
+	char tmp[11];
+	unsigned int n = 0, j;
+
+	if (v == 0) {
+		buf[i++] = '0';
+		return i;
+	}
+	while (v) {
+		tmp[n++] = (char)('0' + v % 10);
+		v /= 10;
+	}
+	for (j = n; j > 0; j--)
+		buf[i++] = tmp[j - 1];
+	return i;
+}
+
+static unsigned int app_hex(char *buf, unsigned int i, unsigned int v,
+			    unsigned int digits)
+{
+	unsigned int d;
+
+	for (d = 0; d < digits; d++)
+		buf[i++] = hx[(v >> (4 * (digits - 1 - d))) & 0xF];
+	return i;
+}
+
+static unsigned int app_ptr(char *buf, unsigned int i, unsigned int v)
+{
+	i = app_str(buf, i, "0x");
+	return app_hex(buf, i, v, 8);
+}
+
+/* One report line: the screen (until the block is full) and COM1. */
+static void emit(const char *s)
+{
+	if (fb_ok && panic_line < PANIC_LINES) {
+		unsigned int y = 26 + panic_line * LINE_H;
+
+		draw_str(4, y, 1, s, 255, 235, 190);
+	}
+	panic_line++;
+	serial_puts(SERIAL_COM1, s);
+	serial_putc(SERIAL_COM1, '\n');
+}
+
+/* --- the report --------------------------------------------------------- */
+
+void panic_report(const struct exc_state *st, const char *name)
+{
+	char buf[128];
+	unsigned int i, n, k;
+	unsigned int cr0, cr2, cr3, cr4;
+	unsigned int esp, page_top;
+	unsigned int code_n = 0;
+	unsigned char code[16];
+	unsigned int cand_val[12], cand_off[12];
+	unsigned int cand_n = 0;
+	int stack_ok, user = (st->cs & 3) == 3;
+
+	__asm__ volatile ("mov %%cr0, %0" : "=r"(cr0));
+	__asm__ volatile ("mov %%cr2, %0" : "=r"(cr2));
+	__asm__ volatile ("mov %%cr3, %0" : "=r"(cr3));
+	__asm__ volatile ("mov %%cr4, %0" : "=r"(cr4));
+
+	/* Fault-time stack pointer: the CPU also pushes SS:ESP on a privilege
+	 * change; for a ring-0 fault it is just above the EFLAGS slot. */
+	esp = user ? st->esp : (unsigned int)&st->eflags + 4;
+	stack_ok = (esp >= 0x1000u && esp < RAM_LIMIT);
+	page_top = stack_ok ? (esp | 0xFFFu) + 1 : esp;
+
+	/* The faulting instruction bytes (only from mapped RAM, and never
+	 * across a page boundary, so a bad EIP cannot fault the handler). */
+	if (st->eip < RAM_LIMIT) {
+		unsigned int eip_top = (st->eip | 0xFFFu) + 1;
+
+		while (code_n < sizeof(code) && st->eip + code_n < eip_top) {
+			code[code_n] = *(volatile unsigned char *)(st->eip + code_n);
+			code_n++;
+		}
+	}
+
+	/* Return-address candidates: scan the faulting stack page for dwords
+	 * that point into the kernel image.  There is no EBP chain to walk
+	 * (-O2 omits frame pointers), so these are best-effort hints. */
+	if (stack_ok) {
+		for (n = esp; n + 4 <= page_top && cand_n < 12; n += 4) {
+			unsigned int v = *(volatile unsigned int *)n;
+
+			if (v >= KERNEL_BASE && v < (unsigned int)__bss_end) {
+				cand_val[cand_n] = v;
+				cand_off[cand_n] = n - esp;
+				cand_n++;
+			}
+		}
+	}
+
+	cache_fb();
+	if (fb_ok) {
+		rect(0, 0, fb_w, 22, 160, 0, 0);
+		draw_str(4, 4, 2, "*** KERNEL EXCEPTION ***", 255, 255, 255);
+		rect(0, 22, fb_w, 6 + PANIC_LINES * LINE_H, 24, 0, 0);
+	}
+	panic_line = 0;
+	serial_puts(SERIAL_COM1, "\n*** KERNEL EXCEPTION ***\n");
+
+	/* Vector, error code, and the #PF error-code bits. */
+	i = 0;
+	i = app_str(buf, i, name);
+	i = app_str(buf, i, "  vec ");
+	i = app_dec(buf, i, st->vector);
+	i = app_str(buf, i, "  err 0x");
+	i = app_hex(buf, i, st->err, 8);
+	if (st->vector == 14) {
+		i = app_str(buf, i, "  P=");
+		buf[i++] = (char)((st->err & 0x01) ? '1' : '0');
+		i = app_str(buf, i, " W=");
+		buf[i++] = (char)((st->err & 0x02) ? '1' : '0');
+		i = app_str(buf, i, " U=");
+		buf[i++] = (char)((st->err & 0x04) ? '1' : '0');
+		i = app_str(buf, i, " RSVD=");
+		buf[i++] = (char)((st->err & 0x08) ? '1' : '0');
+		i = app_str(buf, i, " ID=");
+		buf[i++] = (char)((st->err & 0x10) ? '1' : '0');
+	}
+	buf[i] = '\0';
+	emit(buf);
+
+	/* Faulting instruction pointer and flags. */
+	i = 0;
+	i = app_str(buf, i, "EIP ");
+	i = app_ptr(buf, i, st->eip);
+	i = app_str(buf, i, "  CS ");
+	i = app_str(buf, i, "0x");
+	i = app_hex(buf, i, st->cs, 4);
+	i = app_str(buf, i, user ? " ring 3" : " ring 0");
+	i = app_str(buf, i, "  EFLAGS 0x");
+	i = app_hex(buf, i, st->eflags, 8);
+	if (st->eflags & 0x200u)
+		i = app_str(buf, i, " IF");
+	if (st->eflags & 0x20000u)
+		i = app_str(buf, i, " VM");
+	buf[i] = '\0';
+	emit(buf);
+
+	/* General registers (two lines of four). */
+	i = 0;
+	i = app_str(buf, i, "EAX "); i = app_ptr(buf, i, st->eax);
+	i = app_str(buf, i, "  EBX "); i = app_ptr(buf, i, st->ebx);
+	i = app_str(buf, i, "  ECX "); i = app_ptr(buf, i, st->ecx);
+	i = app_str(buf, i, "  EDX "); i = app_ptr(buf, i, st->edx);
+	buf[i] = '\0';
+	emit(buf);
+
+	i = 0;
+	i = app_str(buf, i, "ESI "); i = app_ptr(buf, i, st->esi);
+	i = app_str(buf, i, "  EDI "); i = app_ptr(buf, i, st->edi);
+	i = app_str(buf, i, "  EBP "); i = app_ptr(buf, i, st->ebp);
+	i = app_str(buf, i, "  ESP "); i = app_ptr(buf, i, esp);
+	buf[i] = '\0';
+	emit(buf);
+
+	/* Control registers. */
+	i = 0;
+	i = app_str(buf, i, "CR0 "); i = app_ptr(buf, i, cr0);
+	i = app_str(buf, i, "  CR2 "); i = app_ptr(buf, i, cr2);
+	i = app_str(buf, i, "  CR3 "); i = app_ptr(buf, i, cr3);
+	i = app_str(buf, i, "  CR4 "); i = app_ptr(buf, i, cr4);
+	buf[i] = '\0';
+	emit(buf);
+
+	/* Current process and uptime. */
+	i = 0;
+	i = app_str(buf, i, "pid ");
+	i = app_dec(buf, i, current_pid);
+	if (procs) {
+		i = app_str(buf, i, " (");
+		for (n = 0; n < PROC_NAME_LEN && procs[current_pid].name[n]; n++)
+			buf[i++] = procs[current_pid].name[n];
+		buf[i++] = ')';
+	}
+	i = app_str(buf, i, "  ticks ");
+	i = app_dec(buf, i, get_ticks_ms());
+	buf[i] = '\0';
+	emit(buf);
+
+	/* Kernel stack bounds: an ESP below the base means stack overflow. */
+	if (procs) {
+		i = 0;
+		i = app_str(buf, i, "kstack base ");
+		i = app_ptr(buf, i, procs[current_pid].stack_base);
+		i = app_str(buf, i, "  top ");
+		i = app_ptr(buf, i, procs[current_pid].kstack_top);
+		buf[i] = '\0';
+		emit(buf);
+	}
+
+	/* Bytes at EIP: the faulting instruction (raw, for a disassembler). */
+	i = 0;
+	i = app_str(buf, i, "code");
+	for (n = 0; n < code_n; n++) {
+		buf[i++] = ' ';
+		buf[i++] = hx[code[n] >> 4];
+		buf[i++] = hx[code[n] & 0xF];
+	}
+	if (code_n == 0)
+		i = app_str(buf, i, " (unmapped)");
+	buf[i] = '\0';
+	emit(buf);
+
+	/* A few dwords at the faulting stack pointer. */
+	if (stack_ok) {
+		for (k = 0; k < 2; k++) {
+			unsigned int p = esp + k * 16;
+
+			i = 0;
+			i = app_str(buf, i, "stk ");
+			i = app_ptr(buf, i, p);
+			i = app_str(buf, i, ":");
+			for (n = 0; n < 4; n++) {
+				unsigned int a = p + n * 4;
+
+				if (a + 4 > page_top)
+					break;
+				i = app_str(buf, i, " ");
+				i = app_hex(buf, i, *(volatile unsigned int *)a, 8);
+			}
+			buf[i] = '\0';
+			emit(buf);
+		}
+	} else {
+		i = 0;
+		i = app_str(buf, i, "stk ");
+		i = app_ptr(buf, i, esp);
+		i = app_str(buf, i, " (not mapped)");
+		buf[i] = '\0';
+		emit(buf);
+	}
+
+	/* Return-address candidates found on the stack. */
+	i = 0;
+	i = app_str(buf, i, "ret");
+	for (n = 0; n < cand_n && n < 5; n++) {
+		buf[i++] = ' ';
+		i = app_ptr(buf, i, cand_val[n]);
+	}
+	if (cand_n == 0)
+		i = app_str(buf, i, " none");
+	buf[i] = '\0';
+	emit(buf);
+
+	/* Serial gets the full stack and every candidate, each with its offset
+	 * from the faulting ESP, so a crash log can be read without the screen. */
+	if (stack_ok) {
+		for (n = 0; n < 32; n++) {
+			unsigned int p = esp + n * 4;
+
+			if (p + 4 > page_top)
+				break;
+			i = 0;
+			i = app_str(buf, i, "stk +");
+			i = app_hex(buf, i, n * 4, 3);
+			i = app_str(buf, i, " @");
+			i = app_hex(buf, i, p, 8);
+			i = app_str(buf, i, " = ");
+			i = app_hex(buf, i, *(volatile unsigned int *)p, 8);
+			buf[i] = '\0';
+			serial_puts(SERIAL_COM1, buf);
+			serial_putc(SERIAL_COM1, '\n');
+		}
+	}
+	for (n = 0; n < cand_n; n++) {
+		i = 0;
+		i = app_str(buf, i, "ret +");
+		i = app_hex(buf, i, cand_off[n], 3);
+		i = app_str(buf, i, " ");
+		i = app_ptr(buf, i, cand_val[n]);
+		buf[i] = '\0';
+		serial_puts(SERIAL_COM1, buf);
+		serial_putc(SERIAL_COM1, '\n');
+	}
+}

+ 32 - 0
panic.h

@@ -0,0 +1,32 @@
+/* Fatal exception screen.
+ *
+ * Only ring-0 faults reach this path: a fault from ring 3 kills the offending
+ * process and the kernel keeps running (see exc_handler() in kernel.c).  The
+ * handler runs with interrupts off and never returns, so this code must not
+ * depend on the scheduler, the heap or the current screen buffer: it draws
+ * straight into the VESA LFB (bypassing the WM and the shadow buffer) and
+ * mirrors everything to COM1.
+ *
+ * Addresses printed here are raw kernel addresses; resolve them with
+ * `nm kernel.elf` / `addr2line -e kernel.elf`. */
+#ifndef PANIC_H
+#define PANIC_H
+
+/* CPU state captured by the exception stubs (timer.S).  The layout must
+ * match the stub exactly, low to high:
+ *
+ *   pusha block: EDI, ESI, EBP, ESP(as saved by pusha), EBX, EDX, ECX, EAX
+ *   exception frame: vector, error code, EIP, CS, EFLAGS, [user ESP, user SS]
+ *
+ * The ESP/SS fields are only meaningful for a fault from ring 3 (the CPU
+ * pushes them on a privilege change). */
+struct exc_state {
+	unsigned int edi, esi, ebp, esp_pusha;
+	unsigned int ebx, edx, ecx, eax;
+	unsigned int vector, err, eip, cs, eflags, esp, ss;
+};
+
+/* Draw the banner and dump the state to COM1.  `name` is the vector name. */
+void panic_report(const struct exc_state *st, const char *name);
+
+#endif

+ 5 - 86
r8168.c

@@ -5,14 +5,11 @@
  * TX/RX use 16-byte descriptors the NIC DMAs to/from memory; register and
  * descriptor values mirror the r8169 sequence from Linux.
  *
- * Every wait is time-bounded and each bring-up step writes a kdbg info row
- * (and serial), because the target machine has no serial console: a wedged
- * driver must still be diagnosable from the screen (progress row + PIT
- * heartbeat).
+ * Every wait is time-bounded and each bring-up step goes to serial, because
+ * a wedged driver must still be diagnosable from the log.
  */
 
 #include "io.h"
-#include "kdbg.h"
 #include "mm.h"
 #include "netdev.h"
 #include "paging.h"
@@ -140,15 +137,13 @@ static unsigned char *rx_bufs;
 static unsigned int tx_cur;
 static unsigned int rx_cur;
 
-/* Counters (mirrored into the kdbg status row). */
+/* Counters (also reported by `netregs`). */
 static unsigned int tx_ok, tx_err, rx_ok, rx_err, rx_drop;
 static unsigned int last_tx_status;     /* raw descriptor status after TX */
 static unsigned int isr_last;           /* last IntrStatus value we acked */
 static unsigned int isr_rovw, isr_fov, isr_tdu;
 static unsigned int rx_restarts;
 
-static int kdbg_stat_row = -1;          /* link + counters */
-
 static int timed_out(unsigned int start_ms, unsigned int ms)
 {
 	return get_ticks_ms() - start_ms > ms;
@@ -269,33 +264,10 @@ static void put_dec(unsigned int v)
 		io_putchar(b[--i]);
 }
 
-/* ---- debug trail (kdbg rows + serial) ---- */
-
-/* Each step advances to a fresh info row (up to R8168_TRAIL_ROWS) so a photo
- * of the screen shows the bring-up sequence (PCI -> reset -> ... -> link);
- * after that the last row is reused, which keeps the most recent step
- * visible.  The row count is capped because the pool is shared with the MTRR
- * dump (11 rows on the AT3IONT-I). */
-#define R8168_TRAIL_ROWS 2
-
-static int trail_row = -1;
-static int trail_used;
+/* ---- debug trail (serial) ---- */
 
 static void dbg(const char *s)
 {
-	if (trail_row < 0) {
-		trail_row = kdbg_info_alloc();
-		trail_used = 1;
-	} else if (trail_used < R8168_TRAIL_ROWS) {
-		int next = kdbg_info_alloc();
-
-		if (next >= 0) {
-			trail_row = next;
-			trail_used++;
-		}
-	}
-	if (trail_row >= 0)
-		kdbg_info((unsigned int)trail_row, s);
 	serial_puts(SERIAL_COM1, "r8168: ");
 	serial_puts(SERIAL_COM1, s);
 	serial_puts(SERIAL_COM1, "\n");
@@ -348,7 +320,7 @@ static int mdio_read(unsigned int reg)
 	return (int)(r32(REG_PHYAR) & 0xffff);
 }
 
-/* ---- status row ---- */
+/* ---- status ---- */
 
 /* "1000M"/"100M"/"10M"/"?" + duplex letter, into out[6]. */
 static void speed_string(unsigned int st, char *out)
@@ -365,47 +337,6 @@ static void speed_string(unsigned int st, char *out)
 	out[5] = '\0';
 }
 
-/* "NIC U 1000MF TX 3/0 RX 5/0" into the kdbg status row. */
-static void status_line(void)
-{
-	char buf[40];
-	unsigned int st = r8(REG_PHYstatus);
-	unsigned int i = 0;
-
-	if (kdbg_stat_row < 0)
-		kdbg_stat_row = kdbg_info_alloc();   /* reserve the row up front */
-
-	if (kdbg_stat_row < 0)
-		return;
-
-	i = app(buf, i, "NIC ");
-	buf[i++] = (st & PHYST_LINK) ? 'U' : 'D';
-	buf[i++] = ' ';
-	{
-		char sp[6];
-		unsigned int j;
-
-		speed_string(st, sp);
-		for (j = 0; sp[j]; j++)
-			buf[i++] = sp[j];
-	}
-	buf[i++] = (st & PHYST_FULLDUP) ? 'F' : 'H';
-	i = app(buf, i, " TX ");
-	i = appd(buf, i, tx_ok);
-	buf[i++] = '/';
-	i = appd(buf, i, tx_err);
-	i = app(buf, i, " RX ");
-	i = appd(buf, i, rx_ok);
-	buf[i++] = '/';
-	i = appd(buf, i, rx_err);
-	buf[i] = '\0';
-
-	if (kdbg_stat_row < 0)
-		kdbg_stat_row = kdbg_info_alloc();
-	if (kdbg_stat_row >= 0)
-		kdbg_info((unsigned int)kdbg_stat_row, buf);
-}
-
 /* Re-arm every RX descriptor and restart the RX engine.  The chip can halt
  * its RX DMA after a FIFO overflow or when it ran out of descriptors (which
  * happens when nothing polls for a while, e.g. while a command is printing);
@@ -689,10 +620,6 @@ int r8168_init(void)
 		return present ? 0 : -1;
 	inited = 1;
 
-	/* Reserve the status row before the trail grabs rows. */
-	if (kdbg_stat_row < 0)
-		kdbg_stat_row = kdbg_info_alloc();
-
 	if (probe_pci() != 0) {
 		dbg("no 10ec:8168 found");
 		return -1;
@@ -765,7 +692,6 @@ int r8168_init(void)
 	dbg(buf);
 
 	present = 1;
-	status_line();
 	return 0;
 }
 
@@ -783,7 +709,6 @@ void r8168_reset(void)
 	}
 	read_mac();
 	hw_start();
-	status_line();
 	dbg("netreset done");
 }
 
@@ -827,7 +752,6 @@ int r8168_tx(const unsigned char *buf, unsigned int len)
 	while (d->opts1 & DescOwn) {
 		if (timed_out(t0, 100)) {
 			tx_err++;
-			status_line();
 			return -1;
 		}
 	}
@@ -855,7 +779,6 @@ int r8168_tx(const unsigned char *buf, unsigned int len)
 	while (d->opts1 & DescOwn) {
 		if (timed_out(t0, 100)) {
 			tx_err++;
-			status_line();
 			return -1;
 		}
 	}
@@ -863,8 +786,6 @@ int r8168_tx(const unsigned char *buf, unsigned int len)
 	tx_cur = (entry + 1) % R8168_NTX;
 	last_tx_status = d->opts1;
 	tx_ok++;
-	if ((tx_ok & 63) == 0)
-		status_line();
 	return 0;
 }
 
@@ -916,8 +837,6 @@ int r8168_rx(unsigned char *buf, unsigned int maxlen)
 				for (i = 0; i < len; i++)
 					buf[i] = src[i];
 				rx_ok++;
-				if ((rx_ok & 63) == 0)
-					status_line();
 				rx_arm(entry);
 				rx_cur = (rx_cur + 1) % R8168_NRX;
 				return (int)len;

+ 0 - 5
switch.S

@@ -20,7 +20,6 @@
 .extern procs
 .extern schedule
 .extern serial_poll
-.extern kdbg_pit_tick
 .extern tss
 
 .include "irqret.inc"
@@ -62,10 +61,6 @@ pit_irq_stub:
 	/* Poll UART for received serial data (prevents FIFO overflow). */
 	call  serial_poll
 
-	/* On-screen debug heartbeat / status refresh (no serial console on
-	 * some targets; this keeps a live indicator on the framebuffer). */
-	call  kdbg_pit_tick
-
 	/* Decrement timeslice counter; switch only when it reaches 0. */
 	decl  slice_counter
 	jnz   .no_switch

+ 0 - 4
terminal.c

@@ -3,7 +3,6 @@
 
 #include "io.h"
 #include "dbg.h"
-#include "kdbg.h"
 #include "kexec.h"
 #include "process.h"
 #include "terminal.h"
@@ -1192,9 +1191,6 @@ void term_run(struct term *t)
 		{
 			int k = term_key_pop(t);
 			if (k) {
-				kdbg_term_count++;
-				kdbg_term_last = (unsigned int)k;
-				kdbg_status();
 				if (k == IO_KEY_CTRL_C) {
 					/* Ctrl+C at the prompt: discard the line. */
 					io_putstr("^C\n");

+ 10 - 9
timer.S

@@ -43,19 +43,20 @@ default_irq_stub:
 	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. */
+/* CPU exception stubs (vectors 0-31).  The handler never returns; it gets a
+ * pointer to a struct exc_state (panic.h): the saved GPRs plus the CPU's
+ * exception frame (vector, error code, EIP, CS, EFLAGS, [user ESP, SS]). */
 
 .macro exc_no_err vec
 exc_stub_\vec:
+	pushl $0               /* the CPU pushes no error code: supply a zero */
 	pushl $\vec
 	jmp   exc_common
 .endm
 
 .macro exc_err vec
 exc_stub_\vec:
-	addl  $4, %esp
-	pushl $\vec
+	pushl $\vec            /* the CPU's error code is already on the stack */
 	jmp   exc_common
 .endm
 
@@ -104,11 +105,11 @@ exc_common:
 	movw  %ax, %gs
 	popl  %eax
 
-	pushl 8(%esp)      /* CS  -> 3rd arg */
-	pushl 4(%esp)      /* vector -> 2nd arg */
-	pushl 12(%esp)     /* faulting EIP -> 1st arg */
-	call  exc_handler  /* exc_handler(eip, vector, cs) */
-	addl  $12, %esp
+	/* Layout at %esp must match struct exc_state (panic.h). */
+	pusha                  /* GPRs exactly as they were at the fault */
+	movl  %esp, %eax
+	pushl %eax             /* exc_handler(struct exc_state *st) */
+	call  exc_handler
 	cli
 1:	hlt
 	jmp   1b

+ 1 - 8
wm.c

@@ -6,7 +6,6 @@
 #include "fbtext.h"
 #include "idle.h"
 #include "io.h"
-#include "kdbg.h"
 #include "kexec.h"
 #include "mouse.h"
 #include "netkexec.h"
@@ -363,7 +362,6 @@ static void wm_handle_keyboard(void)
 	struct window *fw = wm_focused_window();
 	static unsigned int last_hw_poll;
 	unsigned int now = get_ticks_ms();
-	int handled = 0;
 	int n;
 
 	if (io_keyboard_raw())
@@ -374,7 +372,7 @@ static void wm_handle_keyboard(void)
 
 	for (n = 0; n < 8; n++) {
 		int k = io_poll_key();
-		if (!k && (now - last_hw_poll) >= (kdbg_irq_masked ? 5 : 50)) {
+		if (!k && (now - last_hw_poll) >= (io_keyboard_irq_masked() ? 5 : 50)) {
 			/* Fallback paths: IRQ1 was storm-masked, or no IRQ is
 			 * delivering; sample the controller directly (faster
 			 * when masked, so fast typing isn't dropped). */
@@ -383,9 +381,6 @@ static void wm_handle_keyboard(void)
 		}
 		if (!k)
 			break;
-		kdbg_wm_count++;
-		kdbg_wm_last = (unsigned int)k;
-		handled = 1;
 		/* A graphics command owns its window's keys (ESC etc.);
 		 * Ctrl+C always reaches the terminal so its foreground kill
 		 * keeps working. */
@@ -393,8 +388,6 @@ static void wm_handle_keyboard(void)
 		    !sys_gfx_push_key(&fw->term->screen, k))
 			term_key_push(fw->term, k);
 	}
-	if (handled)
-		kdbg_status();
 }
 
 static void wm_draw_bar(void)