Explorar el Código

Add on-screen debug overlay and harden keyboard input

Johannes Zellner hace 1 mes
padre
commit
5a6048436c
Se han modificado 12 ficheros con 508 adiciones y 30 borrados
  1. 67 0
      AGENTS.md
  2. 4 1
      Makefile
  3. 18 11
      colors.c
  4. 18 4
      idle.c
  5. 75 12
      io.c
  6. 244 0
      kdbg.c
  7. 37 0
      kdbg.h
  8. 9 1
      kernel.c
  9. 9 1
      mouse.c
  10. 5 0
      switch.S
  11. 4 0
      terminal.c
  12. 18 0
      wm.c

+ 67 - 0
AGENTS.md

@@ -80,6 +80,9 @@ make clean
 - **Text console**: `fbtext.c`, `font_8x8.c/h`, `io.c/h`, `screen.c/h` — 8×8 font,
   framebuffer glyph blitting (`fbtext_draw_cells`) and per-terminal cell buffers
   (`struct text_screen`).
+- **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.
 - **Shell**: `terminal.c` — history, line editing, command dispatch (hand-rolled
   `is_cmd_*` parsers). Runs in a window (`term_run(struct term *)`); reads keys
   from its per-terminal queue (filled by the WM).
@@ -218,6 +221,70 @@ QEMU gotchas that bit once:
   the string) and kills your script; use `pkill qemu` (process-name match) or
   kill by PID.
 
+## 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 10
+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`). 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.
+
+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 10 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_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; the kernel must stay under the `0x30000`
+  boundary (`kernel.ld` ASSERT).
+
 ## Conventions & gotchas
 
 - **Freestanding C** — no libc, no `malloc`, no `printf`. Use `io_putstr` /

+ 4 - 1
Makefile

@@ -131,6 +131,9 @@ usb.o: usb.c usb.h io.h timer.h uhci.h
 lsusb.o: lsusb.c io.h usb.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+kdbg.o: kdbg.c kdbg.h font_8x8.h timer.h vga.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 lspci.o: lspci.c io.h pci.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -230,7 +233,7 @@ syscall_stub.o: syscall_stub.S
 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 elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.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 radeon.o mtrr.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 hello_embed.o
+kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.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 radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o usb.o lsusb.o kdbg.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 hello_embed.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386

+ 18 - 11
colors.c

@@ -13,15 +13,22 @@
 #define FPS_RECT_W    (7 * 8)
 #define FPS_RECT_H    8
 
-/* Precomputed hue-to-RGB lookup table. Packed as 0x00BBGGRR for fast 32-bit load. */
-static unsigned int hue_lut[RAINBOW_FULL];
+/* Precomputed hue-to-RGB lookup table. Packed as 0x00BBGGRR for fast 32-bit load.
+ * The hue cycle is RAINBOW_FULL entries, but the table is decimated by
+ * LUT_STEP: a 4-hue step is ~1.5% of a color segment and invisible, and the
+ * smaller table keeps the kernel image under the 0x30000 memory-bound. */
+#define LUT_STEP      4
+#define LUT_SIZE      (RAINBOW_FULL / LUT_STEP)
+
+static unsigned int hue_lut[LUT_SIZE];
 
 static void build_hue_lut(void)
 {
 	unsigned int i;
-	for (i = 0; i < RAINBOW_FULL; i++) {
-		unsigned int seg = i / RAINBOW_SEG;
-		unsigned int f   = i % RAINBOW_SEG;
+	for (i = 0; i < LUT_SIZE; i++) {
+		unsigned int hue = i * LUT_STEP;
+		unsigned int seg = hue / RAINBOW_SEG;
+		unsigned int f   = hue % RAINBOW_SEG;
 		unsigned int r1, g1, b1, r2, g2, b2;
 		if (seg >= 6)
 			seg = 0;
@@ -58,7 +65,7 @@ static void draw_frame(unsigned char *fb, unsigned int w, unsigned int h,
 				unsigned int *p = (unsigned int *)row;
 				for (x = 0; x < w; x++) {
 					if (x >= FPS_RECT_W) {
-						unsigned int packed = hue_lut[row_hue];
+						unsigned int packed = hue_lut[row_hue / LUT_STEP];
 						*p = packed;
 					}
 					p++;
@@ -69,7 +76,7 @@ static void draw_frame(unsigned char *fb, unsigned int w, unsigned int h,
 			} else if (bpp == 24) {
 				for (x = 0; x < w; x++) {
 					if (x >= FPS_RECT_W) {
-						unsigned int packed = hue_lut[row_hue];
+						unsigned int packed = hue_lut[row_hue / LUT_STEP];
 						row[x * 3]     = (unsigned char)(packed & 0xFF);
 						row[x * 3 + 1] = (unsigned char)((packed >> 8) & 0xFF);
 						row[x * 3 + 2] = (unsigned char)((packed >> 16) & 0xFF);
@@ -81,7 +88,7 @@ static void draw_frame(unsigned char *fb, unsigned int w, unsigned int h,
 			} else if (bpp == 16) {
 				for (x = 0; x < w; x++) {
 					if (x >= FPS_RECT_W) {
-						unsigned int packed = hue_lut[row_hue];
+						unsigned int packed = hue_lut[row_hue / LUT_STEP];
 						unsigned int r = (packed >> 16) & 0xFF;
 						unsigned int g = (packed >> 8) & 0xFF;
 						unsigned int b = packed & 0xFF;
@@ -100,14 +107,14 @@ static void draw_frame(unsigned char *fb, unsigned int w, unsigned int h,
 			if (bpp == 32) {
 				unsigned int *p = (unsigned int *)row;
 				for (x = 0; x < w; x++) {
-					*p++ = hue_lut[row_hue];
+					*p++ = hue_lut[row_hue / LUT_STEP];
 					row_hue += scale_x;
 					if (row_hue >= RAINBOW_FULL)
 						row_hue -= RAINBOW_FULL;
 				}
 			} else if (bpp == 24) {
 				for (x = 0; x < w; x++) {
-					unsigned int packed = hue_lut[row_hue];
+					unsigned int packed = hue_lut[row_hue / LUT_STEP];
 					row[x * 3]     = (unsigned char)(packed & 0xFF);
 					row[x * 3 + 1] = (unsigned char)((packed >> 8) & 0xFF);
 					row[x * 3 + 2] = (unsigned char)((packed >> 16) & 0xFF);
@@ -117,7 +124,7 @@ static void draw_frame(unsigned char *fb, unsigned int w, unsigned int h,
 				}
 			} else if (bpp == 16) {
 				for (x = 0; x < w; x++) {
-					unsigned int packed = hue_lut[row_hue];
+					unsigned int packed = hue_lut[row_hue / LUT_STEP];
 					unsigned int r = (packed >> 16) & 0xFF;
 					unsigned int g = (packed >> 8) & 0xFF;
 					unsigned int b = packed & 0xFF;

+ 18 - 4
idle.c

@@ -1,7 +1,16 @@
-/* CPU idle: use mwait for deep C-states when available, hlt fallback. */
-
+/* CPU idle: HLT (C1) by default; optional MONITOR/MWAIT (C2).
+ *
+ * NOTE: MWAIT is intentionally disabled.  On the ASUS AT3IONT-I (Atom 330 +
+ * NVIDIA MCP79) a USB-legacy SMM event (the first key press) hangs the
+ * machine when the CPU idles via MWAIT C2.  HLT is the path QEMU always used
+ * (its default CPU has no MONITOR/MWAIT) and what every BIOS's legacy-USB
+ * emulation expects, since DOS idles with HLT.
+ */
 #include "idle.h"
 
+#define IDLE_USE_MWAIT 0
+
+#if IDLE_USE_MWAIT
 static int has_mwait = 0;
 static int has_mwait_ext = 0;
 static unsigned int mwait_cstate_hint = 0x00;
@@ -13,9 +22,11 @@ static void cpuid_idle(unsigned int leaf, unsigned int *eax, unsigned int *ebx,
 		: "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
 		: "a"(leaf), "c"(0));
 }
+#endif
 
 void idle_init(void)
 {
+#if IDLE_USE_MWAIT
 	unsigned int eax, ebx, ecx, edx;
 	unsigned int max_leaf;
 
@@ -32,10 +43,12 @@ void idle_init(void)
 	}
 
 	mwait_cstate_hint = 0x10;
+#endif
 }
 
 void cpu_idle(void)
 {
+#if IDLE_USE_MWAIT
 	if (has_mwait && has_mwait_ext) {
 		volatile unsigned int dummy = 0;
 		__asm__ volatile (
@@ -48,7 +61,8 @@ void cpu_idle(void)
 			:
 			: "a"(mwait_cstate_hint), "c"(1)
 		);
-	} else {
-		__asm__ volatile ("hlt");
+		return;
 	}
+#endif
+	__asm__ volatile ("hlt");
 }

+ 75 - 12
io.c

@@ -4,8 +4,10 @@
 
 #include "io.h"
 #include "fbtext.h"
+#include "kdbg.h"
 #include "process.h"
 #include "screen.h"
+#include "timer.h"
 
 #define VGA_ATTR 0x0A
 
@@ -61,13 +63,57 @@ static struct text_screen *io_current_screen(void)
 	return s ? s : &io_fallback;
 }
 
+/* IRQ1: read the controller status first and only read data when the output
+ * buffer is full.  Some USB-legacy SMM implementations keep raising IRQ1:
+ * reading 0x60 with no byte present does not acknowledge anything, and a
+ * level-triggered line then storms.  The loop is bounded, and if the rate
+ * 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;
+
 void kbd_irq(void)
 {
-	unsigned char sc = inb(KB_DATA);
-	unsigned int next = (kbd_head + 1) % KBD_BUF_SIZE;
-	if (next != kbd_tail) {
-		kbd_buf[kbd_head] = sc;
-		kbd_head = next;
+	unsigned int guard = 0;
+	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) {
+		/* IRQ1 storm; mask it (master PIC) and poll instead. */
+		outb(0x21, (unsigned char)(inb(0x21) | 0x02));
+		kdbg_irq_masked = 1;
+	}
+
+	while (guard++ < 32) {
+		st = inb(KB_STATUS);
+		if (!(st & 0x01))
+			break;
+		{
+			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) {
+					kbd_buf[kbd_head] = sc;
+					kbd_head = next;
+				}
+			}
+		}
 	}
 	outb(0x20, 0x20);
 }
@@ -234,18 +280,35 @@ int io_poll_key(void)
 }
 
 /* Like io_poll_key but also reads from port 0x60 when buffer is empty.
-   For use by full-screen programs (e.g. space.bin) where IRQ may be missed on real HW. */
+   For use by full-screen programs (e.g. space.bin) where IRQ may be missed on
+   real HW.  Only reads when a keyboard byte is actually pending (OBF set, AUX
+   clear); the status+data pair is read atomically wrt IRQ1. */
 int io_poll_key_with_hw(void)
 {
-	unsigned char sc;
-	if (kbd_tail == kbd_head) {
-		if (!(inb(KB_STATUS) & 1))
-			return 0;
-		sc = inb(KB_DATA);
-	} else {
+	unsigned char sc = 0;
+	unsigned int flags;
+	int got = 0;
+
+	if (kbd_tail != kbd_head) {
 		if (!kbd_buf_get(&sc))
 			return 0;
+		return kbd_process_byte(sc);
+	}
+
+	__asm__ volatile ("pushfl; popl %0; cli" : "=r"(flags));
+	{
+		unsigned char st = inb(KB_STATUS);
+		if ((st & 0x01) && !(st & 0x20)) {
+			sc = inb(KB_DATA);
+			got = 1;
+		}
 	}
+	__asm__ volatile ("pushl %0; popfl" : : "r"(flags));
+
+	if (!got)
+		return 0;
+	kdbg_irq_bytes++;
+	kdbg_last_sc = sc;
 	return kbd_process_byte(sc);
 }
 

+ 244 - 0
kdbg.c

@@ -0,0 +1,244 @@
+/* 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 10
+static char kdbg_info_buf[KDBG_INFO_MAX][40];
+static unsigned char kdbg_info_used[KDBG_INFO_MAX];
+
+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);
+}
+
+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();
+}

+ 37 - 0
kdbg.h

@@ -0,0 +1,37 @@
+/* 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);
+
+/* 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

+ 9 - 1
kernel.c

@@ -2,6 +2,7 @@
 
 #include "idle.h"
 #include "io.h"
+#include "kdbg.h"
 #include "kmalloc.h"
 #include "mm.h"
 #include "mouse.h"
@@ -64,7 +65,12 @@ void exc_handler(unsigned int eip, unsigned int vector)
 		"#XM SIMD Error",
 	};
 	__asm__ volatile ("mov %%cr2, %0" : "=r"(cr2));
-	/* Print the fault to serial FIRST, using only minimal/no-stack code, so it
+	/* 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);
@@ -185,6 +191,8 @@ void kernel_main(void)
 	mouse_init();
 	vga_shadow_init();
 	vga_fb_flush();
+	kdbg_init();
+	kdbg_status();
 	vfs_mount_all();
 	wm_run();
 }

+ 9 - 1
mouse.c

@@ -262,16 +262,24 @@ void mouse_init(void)
 
 void mouse_poll_update(void)
 {
+	unsigned int guard = 0;
+
 	if (mouse_present_flag && !mouse_cursor_flag)
 		mouse_cursor_setup();
 	if (!mouse_streaming_flag)
 		return;
 
 	for (;;) {
-		unsigned char st = inb(PS2_STATUS);
+		unsigned char st;
 		unsigned char b0;
 		int dx, dy;
 
+		/* Bound the drain: a stuck/emulated controller must not
+		 * wedge the WM loop; leftovers are read next iteration. */
+		if (guard++ >= 64)
+			return;
+
+		st = inb(PS2_STATUS);
 		if ((st & (STATUS_OUT_FULL | STATUS_AUX_DATA)) !=
 		    (STATUS_OUT_FULL | STATUS_AUX_DATA))
 			return;

+ 5 - 0
switch.S

@@ -21,6 +21,7 @@
 .extern schedule
 .extern vga_shadow_flush_pending
 .extern serial_poll
+.extern kdbg_pit_tick
 .extern tss
 
 /* struct process offsets (must match process.h / process.c) */
@@ -54,6 +55,10 @@ 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
+
 	/* Shadow buffer flush at 30Hz: set pending flag, main loop does the copy. */
 	decl  flush_counter
 	jnz   .no_flush

+ 4 - 0
terminal.c

@@ -3,6 +3,7 @@
 
 #include "io.h"
 #include "dbg.h"
+#include "kdbg.h"
 #include "kexec.h"
 #include "process.h"
 #include "terminal.h"
@@ -907,6 +908,9 @@ 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");

+ 18 - 0
wm.c

@@ -6,6 +6,7 @@
 #include "fbtext.h"
 #include "idle.h"
 #include "io.h"
+#include "kdbg.h"
 #include "kexec.h"
 #include "mouse.h"
 #include "process.h"
@@ -379,15 +380,32 @@ static void wm_handle_mouse(void)
 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 (!fw || !fw->term)
 		return;
+
 	for (n = 0; n < 8; n++) {
 		int k = io_poll_key();
+		if (!k && (now - last_hw_poll) >= (kdbg_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). */
+			k = io_poll_key_with_hw();
+			last_hw_poll = now;
+		}
 		if (!k)
 			break;
+		kdbg_wm_count++;
+		kdbg_wm_last = (unsigned int)k;
+		handled = 1;
 		term_key_push(fw->term, k);
 	}
+	if (handled)
+		kdbg_status();
 }
 
 static void wm_draw_bar(void)