Kaynağa Gözat

Add much stuff

Johannes Zellner 1 ay önce
ebeveyn
işleme
5231ed510f
16 değiştirilmiş dosya ile 837 ekleme ve 583 silme
  1. 48 2
      AGENTS.md
  2. 12 3
      Makefile
  3. 2 2
      bootstrap.c
  4. 0 444
      cpuinfo.c
  5. 0 16
      disk.c
  6. 0 7
      disk.h
  7. 0 31
      idle.c
  8. 0 3
      idle.h
  9. 2 2
      kexec.c
  10. 9 0
      lsusb.c
  11. 39 0
      pci.h
  12. 47 73
      terminal.c
  13. 346 0
      uhci.c
  14. 24 0
      uhci.h
  15. 301 0
      usb.c
  16. 7 0
      usb.h

+ 48 - 2
AGENTS.md

@@ -41,12 +41,14 @@ make clean
 | `0x7E00`  | Kernel load / VESA-stage entry (`kernel.ld`) |
 | `0x800`   | kexec trampoline (relocated at runtime; below the kernel) |
 | `0x900`   | kexec flat GDT + GDTR (built at runtime; below the kernel) |
+| `0x3000`  | UHCI frame list (1024 × 4 B, 4 KB-aligned; `uhci.c`) |
 | `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) |
+| `0x30000` | (free) |
 | `0x40000` | Process stack base (`PROC_STACK_BASE`, 4 KB × 8, `process.h`) |
+| `0x50000` | kexec staging buffer (received kernel image, up to 0x18200 B) |
 | `0x100000`| VGA shadow buffer (`VGA_SHADOW_BASE`, `vga.h`) |
 
 ## Key files
@@ -66,6 +68,9 @@ make clean
   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.
+- **USB**: `uhci.c/h`, `usb.c/h`, `lsusb.c` — UHCI host controller (PCI scan,
+  polling transfers, no IRQ), USB core enumeration with hub recursion, and the
+  `lsusb` command.
 - **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.
@@ -74,7 +79,7 @@ make clean
 
 `hello`, `reboot`, `poweroff`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `run <file>`, `space`, `clock`,
-`colors`, `display`, `cpuinfo`, `mouseinfo`, `power [info|set …]`, `drive <0|1>`,
+`colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`,
 `ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
 
 ## Serial hot-reload (kexec) workflow
@@ -143,6 +148,47 @@ and doesn't conflict with the kexec auto-detect. Reading arbitrary physical
 memory is safe (no paging); writing can corrupt the kernel, so the usual loop is
 inspect → `q` → `make dev` a fresh build.
 
+## Headless debugging via serial (no display, no keyboard)
+
+The terminal is framebuffer-only, so a headless QEMU gives you no easy way to
+*type* commands or *see* output. The reliable workflow (used for `lsusb`) is to
+temporarily mirror `io_putchar` to COM1, and to invoke the code under test
+directly at boot — no keystroke injection needed:
+
+1. **Echo the framebuffer to serial** — in `io.c` add `#include "serial.h"` and a
+   `serial_putc(SERIAL_COM1, c);` at the top of `io_putchar`. Every `io_putstr`/
+   `io_putchar` call (terminal prompt, echo, command output) now also lands on
+   COM1. `serial_puthex`/`serial_putdec` (`serial.h`) are available for structured
+   dumps inside drivers.
+2. **Call the code at boot** — temporarily call the function under test from
+   `kernel_main` (e.g. `usb_enumerate_and_print();` before `terminal_run()`), or
+   `process_create(...)` from `terminal_run()` to exercise the process context.
+   QMP `send-key`/`input-send-event` and HMP `sendkey` do **not** reliably reach
+   the PS/2 keyboard in headless/VNC-without-a-client mode, so don't script
+   keystrokes — script the call site instead.
+3. **Run QEMU headless and read the log**:
+   ```sh
+   qemu-system-i386 -M pc \
+     -drive file=floppy.img,format=raw,if=floppy \
+     -drive file=root.img,format=raw,if=floppy \
+     -serial file:/tmp/opencode/serial.log \
+     -display none -vga std
+   # ...then: cat -A /tmp/opencode/serial.log
+   ```
+   The `Nebs OS v<version> booted` line is already written to COM1 at boot, so
+   serial is live before the framebuffer is up — a crash in early init still shows.
+4. **Revert before committing** — remove the `io.c` echo and any boot-time call;
+   `git status` should show `io.c` and `kernel.c` unchanged.
+
+QEMU gotchas that bit once:
+
+- The default `-M pc` (QEMU ≥ 11) has **no USB controller**. Add
+  `-device piix3-usb-uhci` (plus `-device usb-mouse`/`usb-hub`/…) explicitly.
+  Cross-check the guest's view of the tree with the monitor `info usb`.
+- `pkill -f qemu-system-i386` matches *your own shell command line* (it contains
+  the string) and kills your script; use `pkill qemu` (process-name match) or
+  kill by PID.
+
 ## Conventions & gotchas
 
 - **Freestanding C** — no libc, no `malloc`, no `printf`. Use `io_putstr` /

+ 12 - 3
Makefile

@@ -101,12 +101,21 @@ colors.o: colors.c fbtext.h io.h timer.h vga.h
 display.o: display.c io.h vga.h gpu.h ati.h fbtext.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-cpuinfo.o: cpuinfo.c io.h timer.h idle.h
+cpuinfo.o: cpuinfo.c io.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 mousecmd.o: mousecmd.c io.h mouse.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+uhci.o: uhci.c uhci.h pci.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+usb.o: usb.c usb.h io.h timer.h uhci.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+lsusb.o: lsusb.c io.h usb.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 mouse.o: mouse.c mouse.h timer.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -149,7 +158,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 kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.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 uhci.o usb.o lsusb.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -298,4 +307,4 @@ dev: kernel.bin kexec_send
 	./kexec_send $(SERIAL_DEV) $(SERIAL_BAUD) $$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o 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 dbg.o save.o rm.o mkdir.o rmdir.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send
+	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o 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 uhci.o usb.o lsusb.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.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

+ 2 - 2
bootstrap.c

@@ -16,11 +16,11 @@
  */
 
 #define UART_BASE        0x3F8
-#define STAGE_ADDR       0x30000
+#define STAGE_ADDR       0x50000
 #define KERNEL_LOAD_ADDR 0x7E00
 #define BOOT_STACK       0x20800
 #define MAGIC            0x4345584B /* "KXEC" little-endian */
-#define MAX_SIZE         0x10000
+#define MAX_SIZE         0x18200
 
 static inline void outb(unsigned short port, unsigned char v)
 {

+ 0 - 444
cpuinfo.c

@@ -1,19 +1,8 @@
 /* cpuinfo command: print CPU vendor/model and estimated current clock speed. */
 
-#include "idle.h"
 #include "io.h"
 #include "timer.h"
 
-#define MSR_IA32_PERF_STATUS     0x198u
-#define MSR_IA32_PERF_CTL        0x199u
-#define MSR_IA32_PLATFORM_INFO   0xCEu
-#define MSR_IA32_PM_ENABLE       0x770u
-#define MSR_IA32_HWP_CAPABILITIES 0x771u
-#define MSR_IA32_HWP_REQUEST     0x774u
-#define MSR_IA32_ENERGY_PERF_BIAS 0x1B0u
-#define MSR_AMD_PSTATE_CTL       0xC0010062u
-#define MSR_AMD_PSTATE_STATUS    0xC0010063u
-
 static void put_uint(unsigned int n)
 {
 	char buf[12];
@@ -31,43 +20,6 @@ static void put_uint(unsigned int n)
 		io_putchar(*p++);
 }
 
-static int streq(const char *a, const char *b)
-{
-	unsigned int i = 0;
-	while (a[i] && b[i]) {
-		if (a[i] != b[i])
-			return 0;
-		i++;
-	}
-	return a[i] == '\0' && b[i] == '\0';
-}
-
-static int str_starts_with(const char *s, const char *prefix)
-{
-	unsigned int i = 0;
-	while (prefix[i]) {
-		if (s[i] != prefix[i])
-			return 0;
-		i++;
-	}
-	return 1;
-}
-
-static void put_hex8(unsigned int x)
-{
-	static const char hex[] = "0123456789ABCDEF";
-	io_putchar(hex[(x >> 4) & 0xF]);
-	io_putchar(hex[x & 0xF]);
-}
-
-static void put_hex32(unsigned int x)
-{
-	put_hex8((x >> 24) & 0xFF);
-	put_hex8((x >> 16) & 0xFF);
-	put_hex8((x >> 8) & 0xFF);
-	put_hex8(x & 0xFF);
-}
-
 static void cpuid(unsigned int leaf, unsigned int subleaf,
 	unsigned int *eax, unsigned int *ebx,
 	unsigned int *ecx, unsigned int *edx)
@@ -85,16 +37,6 @@ static unsigned int read_tsc_low(void)
 	return lo;
 }
 
-static void rdmsr_u32(unsigned int msr, unsigned int *lo, unsigned int *hi)
-{
-	__asm__ volatile ("rdmsr" : "=a"(*lo), "=d"(*hi) : "c"(msr));
-}
-
-static void wrmsr_u32(unsigned int msr, unsigned int lo, unsigned int hi)
-{
-	__asm__ volatile ("wrmsr" :: "c"(msr), "a"(lo), "d"(hi));
-}
-
 static void trim_right_spaces(char *s)
 {
 	unsigned int len = 0;
@@ -378,389 +320,3 @@ void program_cpuinfo_main(void)
 	print_features_leaf7(max_leaf);
 	print_features_ext(max_ext_leaf);
 }
-
-static void print_power_usage(void)
-{
-	io_putstr("usage:\n");
-	io_putstr("  power info\n");
-	io_putstr("  power set low      (deep C-state, lowest power)\n");
-	io_putstr("  power set balanced (moderate C-state)\n");
-	io_putstr("  power set max      (C1 only, max performance)\n");
-}
-
-static void detect_cpu(char vendor[13], unsigned int *max_leaf,
-		       unsigned int *eax1, unsigned int *ecx1, unsigned int *edx1,
-		       unsigned int *family, unsigned int *model, unsigned int *stepping)
-{
-	unsigned int ebx, ecx, edx;
-	cpuid(0, 0, max_leaf, &ebx, &ecx, &edx);
-	((unsigned int *)vendor)[0] = ebx;
-	((unsigned int *)vendor)[1] = edx;
-	((unsigned int *)vendor)[2] = ecx;
-	vendor[12] = '\0';
-	cpuid(1, 0, eax1, &ebx, ecx1, edx1);
-	parse_family_model(*eax1, family, model, stepping);
-}
-
-static int intel_has_platform_info(unsigned int family, unsigned int model)
-{
-	if (family != 6)
-		return 0;
-	if (model >= 0x1A)
-		return 1;
-	return 0;
-}
-
-static int intel_has_epb(unsigned int eax6)
-{
-	return (eax6 & (1u << 3)) ? 1 : 0;
-}
-
-static void power_info_intel(unsigned int family, unsigned int model, unsigned int ecx1, unsigned int edx1)
-{
-	unsigned int lo = 0, hi = 0;
-	unsigned int target_ratio = 0, current_ratio = 0;
-	unsigned int min_ratio = 0, max_ratio = 0;
-	unsigned int eax6, ebx6, ecx6, edx6;
-	int has_hwp = 0;
-	int hwp_enabled = 0;
-	int has_platinfo = 0;
-	int has_epb = 0;
-
-	if ((edx1 & (1u << 5)) == 0) {
-		io_putstr("intel: no MSR feature bit\n");
-		return;
-	}
-	if ((ecx1 & (1u << 7)) == 0)
-		io_putstr("intel: EIST not advertised\n");
-	if (family != 6 && family != 15) {
-		io_putstr("intel: family not supported for perf ctl\n");
-		return;
-	}
-
-	cpuid(6, 0, &eax6, &ebx6, &ecx6, &edx6);
-	(void)ebx6;
-	(void)ecx6;
-	(void)edx6;
-	has_hwp = (eax6 & (1u << 7)) ? 1 : 0;
-	has_epb = intel_has_epb(eax6);
-	has_platinfo = intel_has_platform_info(family, model);
-
-	if (has_platinfo) {
-		rdmsr_u32(MSR_IA32_PLATFORM_INFO, &lo, &hi);
-		min_ratio = (hi >> 8) & 0xFFu;
-		max_ratio = (lo >> 8) & 0xFFu;
-	}
-
-	rdmsr_u32(MSR_IA32_PERF_STATUS, &lo, &hi);
-	current_ratio = (lo >> 8) & 0xFF;
-	rdmsr_u32(MSR_IA32_PERF_CTL, &lo, &hi);
-	target_ratio = (lo >> 8) & 0xFF;
-
-	if (has_hwp) {
-		rdmsr_u32(MSR_IA32_PM_ENABLE, &lo, &hi);
-		hwp_enabled = (lo & 1u) ? 1 : 0;
-	}
-
-	io_putstr("intel ratio current ");
-	put_uint(current_ratio);
-	io_putstr(" target ");
-	put_uint(target_ratio);
-	io_putchar('\n');
-	if (has_platinfo) {
-		io_putstr("intel ratio range ");
-		put_uint(min_ratio);
-		io_putstr("..");
-		put_uint(max_ratio);
-		io_putchar('\n');
-	}
-	if (has_hwp) {
-		io_putstr("intel hwp ");
-		io_putstr(hwp_enabled ? "enabled\n" : "disabled\n");
-		if (hwp_enabled) {
-			rdmsr_u32(MSR_IA32_HWP_REQUEST, &lo, &hi);
-			io_putstr("intel hwp req min ");
-			put_uint(lo & 0xFFu);
-			io_putstr(" max ");
-			put_uint((lo >> 8) & 0xFFu);
-			io_putstr(" des ");
-			put_uint((lo >> 16) & 0xFFu);
-			io_putstr(" epp ");
-			put_uint((lo >> 24) & 0xFFu);
-			io_putchar('\n');
-			rdmsr_u32(MSR_IA32_HWP_CAPABILITIES, &lo, &hi);
-			io_putstr("intel hwp cap low ");
-			put_uint(lo & 0xFFu);
-			io_putstr(" high ");
-			put_uint((lo >> 8) & 0xFFu);
-			io_putstr(" guar ");
-			put_uint((lo >> 16) & 0xFFu);
-			io_putstr(" eff ");
-			put_uint((lo >> 24) & 0xFFu);
-			io_putchar('\n');
-		}
-	}
-	if (has_epb) {
-		rdmsr_u32(MSR_IA32_ENERGY_PERF_BIAS, &lo, &hi);
-		io_putstr("intel epb ");
-		put_uint(lo & 0xFu);
-		io_putchar('\n');
-	}
-	io_putstr("intel family ");
-	put_uint(family);
-	io_putstr(" model ");
-	put_uint(model);
-	io_putchar('\n');
-}
-
-static int power_set_intel(const char *profile, unsigned int family, unsigned int model, unsigned int ecx1, unsigned int edx1)
-{
-	unsigned int lo = 0, hi = 0;
-	unsigned int current_ratio, target_ratio;
-	unsigned int min_ratio = 8, max_ratio = 63;
-	unsigned int eax6, ebx6, ecx6, edx6;
-	int has_hwp = 0;
-	int hwp_enabled = 0;
-	int has_platinfo = 0;
-
-	if ((edx1 & (1u << 5)) == 0 || (ecx1 & (1u << 7)) == 0) {
-		io_putstr("intel: missing MSR/EIST support\n");
-		return -1;
-	}
-	if (family != 6 && family != 15) {
-		io_putstr("intel: unsupported family for write path\n");
-		return -1;
-	}
-
-	cpuid(6, 0, &eax6, &ebx6, &ecx6, &edx6);
-	(void)ebx6;
-	(void)ecx6;
-	(void)edx6;
-	has_hwp = (eax6 & (1u << 7)) ? 1 : 0;
-	has_platinfo = intel_has_platform_info(family, model);
-
-	if (has_platinfo) {
-		rdmsr_u32(MSR_IA32_PLATFORM_INFO, &lo, &hi);
-		min_ratio = (hi >> 8) & 0xFFu;
-		max_ratio = (lo >> 8) & 0xFFu;
-		if (min_ratio == 0 || max_ratio == 0 || min_ratio > max_ratio) {
-			min_ratio = 8;
-			max_ratio = 63;
-		}
-	}
-
-	if (has_hwp) {
-		rdmsr_u32(MSR_IA32_PM_ENABLE, &lo, &hi);
-		hwp_enabled = (lo & 1u) ? 1 : 0;
-	}
-
-	rdmsr_u32(MSR_IA32_PERF_STATUS, &lo, &hi);
-	current_ratio = (lo >> 8) & 0xFF;
-	target_ratio = current_ratio < min_ratio ? min_ratio : current_ratio;
-	if (target_ratio > max_ratio)
-		target_ratio = max_ratio;
-
-	if (streq(profile, "low")) {
-		target_ratio = min_ratio;
-	} else if (streq(profile, "balanced")) {
-		target_ratio = (min_ratio + max_ratio) / 2;
-	} else if (streq(profile, "max")) {
-		target_ratio = max_ratio;
-	} else {
-		io_putstr("power: invalid profile\n");
-		return -1;
-	}
-
-	if (has_hwp && hwp_enabled) {
-		unsigned int minp = min_ratio;
-		unsigned int maxp = max_ratio;
-		unsigned int des = target_ratio;
-		unsigned int epp = 0x80u;
-		if (streq(profile, "low"))
-			epp = 0xC0u;
-		else if (streq(profile, "balanced"))
-			epp = 0x80u;
-		else if (streq(profile, "max"))
-			epp = 0x00u;
-		lo = (minp & 0xFFu) |
-		     ((maxp & 0xFFu) << 8) |
-		     ((des & 0xFFu) << 16) |
-		     ((epp & 0xFFu) << 24);
-		wrmsr_u32(MSR_IA32_HWP_REQUEST, lo, 0);
-		io_putstr("intel hwp profile ");
-		io_putstr(profile);
-		io_putstr(" set (min ");
-		put_uint(minp);
-		io_putstr(" max ");
-		put_uint(maxp);
-		io_putstr(" des ");
-		put_uint(des);
-		io_putstr(" epp ");
-		put_uint(epp);
-		io_putstr(")\n");
-		return 0;
-	}
-
-	rdmsr_u32(MSR_IA32_PERF_CTL, &lo, &hi);
-	lo &= ~0xFF00u;
-	lo |= (target_ratio & 0xFFu) << 8;
-	wrmsr_u32(MSR_IA32_PERF_CTL, lo, hi);
-	io_putstr("intel target ratio set ");
-	put_uint(target_ratio);
-	io_putchar('\n');
-	return 0;
-}
-
-static void power_info_amd(unsigned int family, unsigned int model, unsigned int edx1)
-{
-	unsigned int lo = 0, hi = 0;
-	if ((edx1 & (1u << 5)) == 0) {
-		io_putstr("amd: no MSR feature bit\n");
-		return;
-	}
-	if (family < 0x10) {
-		io_putstr("amd: family too old for p-state ctl\n");
-		return;
-	}
-	rdmsr_u32(MSR_AMD_PSTATE_STATUS, &lo, &hi);
-	io_putstr("amd pstate current ");
-	put_uint(lo & 0x7u);
-	io_putstr(" raw 0x");
-	put_hex32(lo);
-	io_putchar('\n');
-	io_putstr("amd family ");
-	put_uint(family);
-	io_putstr(" model ");
-	put_uint(model);
-	io_putchar('\n');
-}
-
-static int power_set_amd(const char *profile, unsigned int family, unsigned int edx1)
-{
-	unsigned int lo = 0, hi = 0;
-	unsigned int pstate = 0;
-	if ((edx1 & (1u << 5)) == 0) {
-		io_putstr("amd: no MSR support\n");
-		return -1;
-	}
-	if (family < 0x10) {
-		io_putstr("amd: unsupported family for write path\n");
-		return -1;
-	}
-	if (streq(profile, "max")) {
-		pstate = 0;
-	} else if (streq(profile, "balanced")) {
-		pstate = 1;
-	} else if (streq(profile, "low")) {
-		pstate = 2;
-	} else {
-		io_putstr("power: invalid profile\n");
-		return -1;
-	}
-	rdmsr_u32(MSR_AMD_PSTATE_CTL, &lo, &hi);
-	lo &= ~0x7u;
-	lo |= pstate;
-	wrmsr_u32(MSR_AMD_PSTATE_CTL, lo, hi);
-	io_putstr("amd target pstate set ");
-	put_uint(pstate);
-	io_putchar('\n');
-	return 0;
-}
-
-void program_power_main(const char *args)
-{
-	char vendor[13];
-	char local[40];
-	char command[8];
-	char profile[16];
-	unsigned int max_leaf, eax1, ecx1, edx1, family, model, stepping;
-	unsigned int i = 0, j = 0;
-	int is_set = 0;
-	unsigned int cstate_level;
-
-	detect_cpu(vendor, &max_leaf, &eax1, &ecx1, &edx1, &family, &model, &stepping);
-	(void)eax1;
-	(void)max_leaf;
-
-	while (args && args[i] && i + 1 < sizeof(local)) {
-		local[i] = args[i];
-		i++;
-	}
-	local[i] = '\0';
-	i = 0;
-	while (local[i] == ' ')
-		i++;
-	j = 0;
-	while (local[i] && local[i] != ' ' && j + 1 < sizeof(command))
-		command[j++] = local[i++];
-	command[j] = '\0';
-	while (local[i] == ' ')
-		i++;
-	j = 0;
-	while (local[i] && local[i] != ' ' && j + 1 < sizeof(profile))
-		profile[j++] = local[i++];
-	profile[j] = '\0';
-
-	if (command[0] == '\0' || streq(command, "info")) {
-		io_putstr("power vendor ");
-		io_putstr(vendor);
-		io_putstr(" family ");
-		put_uint(family);
-		io_putstr(" model ");
-		put_uint(model);
-		io_putstr(" stepping ");
-		put_uint(stepping);
-		io_putchar('\n');
-
-		io_putstr("idle mode ");
-		if (idle_has_mwait())
-			io_putstr("mwait");
-		else
-			io_putstr("hlt");
-		io_putstr(" cstate C");
-		put_uint(idle_get_cstate());
-		io_putchar('\n');
-
-		if (streq(vendor, "GenuineIntel"))
-			power_info_intel(family, model, ecx1, edx1);
-		else if (streq(vendor, "AuthenticAMD"))
-			power_info_amd(family, model, edx1);
-		else
-			io_putstr("power: vendor backend unavailable\n");
-		print_power_usage();
-		return;
-	}
-
-	if (streq(command, "set"))
-		is_set = 1;
-	if (!is_set || profile[0] == '\0') {
-		print_power_usage();
-		return;
-	}
-	if (str_starts_with(profile, "low") == 0 &&
-	    str_starts_with(profile, "balanced") == 0 &&
-	    str_starts_with(profile, "max") == 0) {
-		io_putstr("power: expected low|balanced|max\n");
-		return;
-	}
-
-	if (streq(profile, "low")) {
-		cstate_level = 3;
-	} else if (streq(profile, "balanced")) {
-		cstate_level = 2;
-	} else {
-		cstate_level = 0;
-	}
-	idle_set_cstate(cstate_level);
-	io_putstr("idle cstate set C");
-	put_uint(cstate_level);
-	io_putchar('\n');
-
-	if (streq(vendor, "GenuineIntel")) {
-		if (power_set_intel(profile, family, model, ecx1, edx1) < 0)
-			io_putstr("power: intel p-state control unavailable\n");
-	} else if (streq(vendor, "AuthenticAMD")) {
-		if (power_set_amd(profile, family, edx1) < 0)
-			io_putstr("power: amd p-state control unavailable\n");
-	}
-}

+ 0 - 16
disk.c

@@ -477,22 +477,6 @@ static int fdc_init_once(void)
 	return 0;
 }
 
-void disk_set_drive(unsigned int drive)
-{
-	if (drive > 1)
-		return;
-	if (drive == current_drive && fdc_initialized)
-		return;
-	current_drive = drive;
-	motor_on = 0;
-	fdc_initialized = 0;
-}
-
-unsigned int disk_get_drive(void)
-{
-	return current_drive;
-}
-
 int disk_read_sectors(unsigned int lba, void *buf, unsigned int count)
 {
 	unsigned int i;

+ 0 - 7
disk.h

@@ -3,13 +3,6 @@
 #ifndef DISK_H
 #define DISK_H
 
-/* Select the floppy drive (0 or 1) used by subsequent disk_read_sectors calls.
- * Resets FDC state so the next read re-initialises for the new drive. */
-void disk_set_drive(unsigned int drive);
-
-/* Return currently selected drive number. */
-unsigned int disk_get_drive(void);
-
 /* Read count sectors starting at lba into buf.
  * Returns 0 on success, -1 on error. */
 int disk_read_sectors(unsigned int lba, void *buf, unsigned int count);

+ 0 - 31
idle.c

@@ -34,37 +34,6 @@ void idle_init(void)
 	mwait_cstate_hint = 0x10;
 }
 
-void idle_set_cstate(unsigned int level)
-{
-	switch (level) {
-	case 0:
-		mwait_cstate_hint = 0x00;
-		break;
-	case 1:
-		mwait_cstate_hint = 0x10;
-		break;
-	case 2:
-		mwait_cstate_hint = 0x20;
-		break;
-	case 3:
-		mwait_cstate_hint = 0x30;
-		break;
-	default:
-		mwait_cstate_hint = 0x10;
-		break;
-	}
-}
-
-unsigned int idle_get_cstate(void)
-{
-	return (mwait_cstate_hint >> 4) & 0xF;
-}
-
-int idle_has_mwait(void)
-{
-	return has_mwait;
-}
-
 void cpu_idle(void)
 {
 	if (has_mwait && has_mwait_ext) {

+ 0 - 3
idle.h

@@ -3,9 +3,6 @@
 #define IDLE_H
 
 void idle_init(void);
-void idle_set_cstate(unsigned int level);
-unsigned int idle_get_cstate(void);
-int idle_has_mwait(void);
 void cpu_idle(void);
 
 #endif

+ 2 - 2
kexec.c

@@ -26,10 +26,10 @@
 #include "serial.h"
 
 #define KEXEC_MAGIC 0x4345584B /* "KXEC" little-endian */
-#define KEXEC_STAGE 0x30000    /* staging buffer for the received image */
+#define KEXEC_STAGE 0x50000    /* 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) */
+#define KEXEC_MAX   0x18200    /* max = kernel region 0x7E00..0x20000 */
 
 volatile int kexec_busy;
 

+ 9 - 0
lsusb.c

@@ -0,0 +1,9 @@
+/* lsusb command: enumerate and print the USB device tree. */
+
+#include "io.h"
+#include "usb.h"
+
+void program_lsusb_main(void)
+{
+	usb_enumerate_and_print();
+}

+ 39 - 0
pci.h

@@ -26,6 +26,18 @@ static inline unsigned int port_inl(unsigned short port)
 	return v;
 }
 
+static inline void port_outw(unsigned short port, unsigned short v)
+{
+	__asm__ volatile ("outw %0, %1" : : "a"(v), "Nd"(port));
+}
+
+static inline unsigned short port_inw(unsigned short port)
+{
+	unsigned short v;
+	__asm__ volatile ("inw %1, %0" : "=a"(v) : "Nd"(port));
+	return v;
+}
+
 static inline unsigned int pci_cfg_read32(unsigned int bus, unsigned int dev,
 					  unsigned int func, unsigned int reg)
 {
@@ -34,4 +46,31 @@ static inline unsigned int pci_cfg_read32(unsigned int bus, unsigned int dev,
 	return port_inl(0xCFC);
 }
 
+static inline void pci_cfg_write32(unsigned int bus, unsigned int dev,
+				   unsigned int func, unsigned int reg,
+				   unsigned int val)
+{
+	port_outl(0xCF8, 0x80000000 | (bus << 16) | (dev << 11) |
+		  (func << 8) | (reg & 0xFC));
+	port_outl(0xCFC, val);
+}
+
+static inline void pci_cfg_write16(unsigned int bus, unsigned int dev,
+				   unsigned int func, unsigned int reg,
+				   unsigned short val)
+{
+	port_outl(0xCF8, 0x80000000 | (bus << 16) | (dev << 11) |
+		  (func << 8) | (reg & 0xFC));
+	port_outw((unsigned short)(0xCFC + (reg & 2)), val);
+}
+
+static inline void pci_cfg_write8(unsigned int bus, unsigned int dev,
+				  unsigned int func, unsigned int reg,
+				  unsigned char val)
+{
+	port_outl(0xCF8, 0x80000000 | (bus << 16) | (dev << 11) |
+		  (func << 8) | (reg & 0xFC));
+	port_outb((unsigned short)(0xCFC + (reg & 3)), val);
+}
+
 #endif

+ 47 - 73
terminal.c

@@ -29,12 +29,10 @@ extern void program_colors_main(void);
 extern void program_display_main(void);
 extern void program_cpuinfo_main(void);
 extern void program_mouseinfo_main(void);
-extern void program_power_main(const char *args);
 extern void program_serial_loop_main(const char *arg);
 extern void program_serial_recv_main(const char *arg);
 extern void program_run_serial_main(const char *arg);
-extern void disk_set_drive(unsigned int drive);
-extern unsigned int disk_get_drive(void);
+extern void program_lsusb_main(void);
 
 #define DATETIME_MS 1000
 #define LINE_MAX 64
@@ -154,6 +152,8 @@ static int is_cmd_ls(const char *line, unsigned int line_len, char *path_buf, un
 	if (line[i] != 'l' || line[i+1] != 's')
 		return 0;
 	i += 2;
+	if (i < line_len && line[i] != ' ')
+		return 0;  /* "ls" must be a whole word, so reject "lsusb" etc. */
 	while (i < line_len && line[i] == ' ')
 		i++;
 	if (i >= line_len) {
@@ -250,6 +250,22 @@ static int is_cmd_mouseinfo(const char *line, unsigned int line_len)
 	return (i == line_len);
 }
 
+static int is_cmd_lsusb(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] != 'l' || line[i+1] != 's' || line[i+2] != 'u' ||
+	    line[i+3] != 's' || line[i+4] != 'b')
+		return 0;
+	i += 5;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
 static int is_cmd_space(const char *line, unsigned int line_len)
 {
 	unsigned int i = 0;
@@ -397,27 +413,6 @@ static int is_cmd_rmdir(const char *line, unsigned int line_len, char *path_buf,
 	return (j > 0);
 }
 
-static int is_cmd_drive(const char *line, unsigned int line_len, unsigned int *drive_num)
-{
-	unsigned int i = 0;
-	while (i < line_len && line[i] == ' ')
-		i++;
-	if (i + 5 > line_len)
-		return 0;
-	if (line[i] != 'd' || line[i+1] != 'r' || line[i+2] != 'i' || line[i+3] != 'v' || line[i+4] != 'e')
-		return 0;
-	i += 5;
-	while (i < line_len && line[i] == ' ')
-		i++;
-	if (i >= line_len || line[i] < '0' || line[i] > '1')
-		return 0;
-	*drive_num = (unsigned int)(line[i] - '0');
-	i++;
-	while (i < line_len && line[i] == ' ')
-		i++;
-	return (i == line_len);
-}
-
 static int is_cmd_help(const char *line, unsigned int line_len)
 {
 	unsigned int i = 0;
@@ -550,34 +545,6 @@ static int is_cmd_serial(const char *line, unsigned int line_len, char *arg_buf,
 	return (i == line_len);
 }
 
-#define POWER_ARGS_MAX 32
-static int is_cmd_power(const char *line, unsigned int line_len, char *args_buf, unsigned int buf_size)
-{
-	unsigned int i = 0, j = 0;
-	while (i < line_len && line[i] == ' ')
-		i++;
-	if (i + 5 > line_len)
-		return 0;
-	if (line[i] != 'p' || line[i+1] != 'o' || line[i+2] != 'w' || line[i+3] != 'e' || line[i+4] != 'r')
-		return 0;
-	i += 5;
-	while (i < line_len && line[i] == ' ')
-		i++;
-	if (i == line_len) {
-		if (buf_size > 0)
-			args_buf[0] = '\0';
-		return 1;
-	}
-	while (i < line_len && j + 1 < buf_size)
-		args_buf[j++] = line[i++];
-	while (j > 0 && args_buf[j - 1] == ' ')
-		j--;
-	args_buf[j] = '\0';
-	while (i < line_len && line[i] == ' ')
-		i++;
-	return (i == line_len);
-}
-
 /* Redraw line from index `from` to end, clear one cell after, set cursor to line_pos. */
 static void redraw_line_from(const char *line, unsigned int line_len,
 	unsigned int line_pos, unsigned int line_start, unsigned int from)
@@ -672,7 +639,9 @@ void terminal_run(void)
 	history_browse     = 0;
 
 	io_drain_keyboard();
+	io_clear_screen();
 	draw_header_row();
+	io_set_cursor(IO_CONTENT_OFFSET);
 	io_putstr(prompt_first);
 	line_start = io_get_cursor();
 
@@ -727,11 +696,10 @@ void terminal_run(void)
 					}
 				} else if (k == '\n') {
 					static char cat_fname[CAT_FNAME_MAX];
-					static char power_args[POWER_ARGS_MAX];
 					static char save_args[SAVE_ARGS_MAX];
 					static char rm_fname[RM_FNAME_MAX];
 					static char ls_path[LS_PATH_MAX];
-					unsigned int drive_sel, kill_pid;
+					unsigned int kill_pid;
 					int skip_prompt = 0;
 					io_putchar('\n');
 					history_push(line, line_len);
@@ -746,6 +714,9 @@ void terminal_run(void)
 					} else if (is_cmd_ls(line, line_len, ls_path, LS_PATH_MAX)) {
 						if (process_create_arg("ls", program_ls_main, ls_path) < 0)
 							io_putstr("error: too many processes\n");
+					} else if (is_cmd_lsusb(line, line_len)) {
+						if (process_create("lsusb", program_lsusb_main) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_clock(line, line_len)) {
 						if (process_create("clock", program_clock_main) < 0)
 							io_putstr("error: too many processes\n");
@@ -790,14 +761,6 @@ void terminal_run(void)
 					} else if (is_cmd_mouseinfo(line, line_len)) {
 						if (process_create("mouseinfo", program_mouseinfo_main) < 0)
 							io_putstr("error: too many processes\n");
-					} else if (is_cmd_power(line, line_len, power_args, POWER_ARGS_MAX)) {
-						if (process_create_arg("power", program_power_main, power_args) < 0)
-							io_putstr("error: too many processes\n");
-					} else if (is_cmd_drive(line, line_len, &drive_sel)) {
-						disk_set_drive(drive_sel);
-						io_putstr("drive ");
-						io_putchar((char)('0' + disk_get_drive()));
-						io_putstr(" selected\n");
 					} else if (is_cmd_ps(line, line_len)) {
 						process_ps();
 					} else if (is_cmd_kill(line, line_len, &kill_pid)) {
@@ -818,18 +781,29 @@ void terminal_run(void)
 					} else if (is_cmd_dbg(line, line_len)) {
 						program_dbg_main();
 					} else if (is_cmd_help(line, line_len)) {
-						io_putstr("hello     reboot    poweroff\n");
-						io_putstr("ls [dir]  cat <file>\n");
-						io_putstr("save <f> <text>  rm <file>\n");
-						io_putstr("mkdir <dir>  rmdir <dir>\n");
-						io_putstr("run <file>  space\n");
-						io_putstr("clock     colors\n");
-						io_putstr("display   cpuinfo\n");
+						io_putstr("hello\n");
+						io_putstr("reboot\n");
+						io_putstr("poweroff\n");
+						io_putstr("ls [dir]\n");
+						io_putstr("cat <file>\n");
+						io_putstr("save <f> <text>\n");
+						io_putstr("rm <file>\n");
+						io_putstr("mkdir <dir>\n");
+						io_putstr("rmdir <dir>\n");
+						io_putstr("run <file>\n");
+						io_putstr("space\n");
+						io_putstr("clock\n");
+						io_putstr("colors\n");
+						io_putstr("display\n");
+						io_putstr("cpuinfo\n");
+						io_putstr("lsusb\n");
 						io_putstr("mouseinfo\n");
-						io_putstr("power [info|set <low|balanced|max>]\n");
-						io_putstr("drive <0|1>\n");
-					io_putstr("ps        kill <pid>\n");
-					io_putstr("kexec     dbg       serial test|recv  clear\n");
+						io_putstr("ps\n");
+						io_putstr("kill <pid>\n");
+						io_putstr("kexec\n");
+						io_putstr("dbg\n");
+						io_putstr("serial test|recv\n");
+						io_putstr("clear\n");
 				} else if (is_cmd_clear(line, line_len)) {
 					io_clear_screen();
 					draw_header_row();

+ 346 - 0
uhci.c

@@ -0,0 +1,346 @@
+/* UHCI (USB 1.1) host controller driver.
+   PCI discovery, register access, frame-list / queue-head / transfer-
+   descriptor schedule, and root-hub port control. Polling based (no IRQ);
+   the PIC slave (and thus the UHCI IRQ) is masked, so we poll TD status. */
+
+#include "pci.h"
+#include "timer.h"
+#include "uhci.h"
+
+/* Register offsets from the I/O base. */
+#define USBCMD       0x00
+#define USBSTS       0x02
+#define USBINTR      0x04
+#define USBFLBASEADD 0x08
+#define USBPORTSC1   0x10
+#define USBPORTSC2   0x12
+
+/* USBCMD bits. */
+#define USBCMD_RS      0x0001
+#define USBCMD_HCRESET 0x0002
+#define USBCMD_GRESET  0x0004
+#define USBCMD_CF      0x0040
+#define USBCMD_MAXP    0x0080
+
+/* USBSTS bits. */
+#define USBSTS_HCH 0x0020
+
+/* PORTSC bits. */
+#define USBPORTSC_CCS  0x0001
+#define USBPORTSC_CSC  0x0002
+#define USBPORTSC_PE   0x0004
+#define USBPORTSC_PEC  0x0008
+#define USBPORTSC_LSDA 0x0100
+#define USBPORTSC_PR   0x0200
+
+/* TD status bits. */
+#define TD_ACTIVE   0x00800000u
+#define TD_LS       0x04000000u
+#define TD_CERR_3   0x18000000u
+#define TD_ERR_MASK 0x007E0000u
+#define TD_ACTLEN   0x000007FFu
+
+/* TD token PIDs (UHCI-encoded). */
+#define TD_PID_SETUP 0x2Du
+#define TD_PID_IN    0x69u
+#define TD_PID_OUT   0xE1u
+
+/* PCI: base class 0x0C (serial), subclass 0x03 (USB). */
+#define PCI_USB_CLASS 0x0C03u
+
+struct uhci_td {
+	unsigned int link;
+	volatile unsigned int status;
+	unsigned int token;
+	unsigned int buffer;
+} __attribute__((aligned(16)));
+
+struct uhci_qh {
+	unsigned int link;
+	unsigned int element;
+} __attribute__((aligned(16)));
+
+#define UHCI_NUM_TD 16
+
+/* Frame list lives in low memory (below the kernel at 0x7E00) to avoid
+   bloating the kernel's BSS past the 0x20000 linker budget. It must be
+   4 KB aligned; 0x3000 is free after boot (see AGENTS.md memory map). */
+#define UHCI_FRAME_LIST_ADDR 0x3000u
+
+static struct uhci_td tds[UHCI_NUM_TD];
+static struct uhci_qh qh;
+
+static unsigned char setup_buf[8];
+
+static unsigned int io_base;
+static unsigned int pci_bus, pci_dev, pci_func;
+static int found;
+
+static unsigned short reg_readw(unsigned int reg)
+{
+	return port_inw((unsigned short)(io_base + reg));
+}
+
+static void reg_writew(unsigned int reg, unsigned short val)
+{
+	port_outw((unsigned short)(io_base + reg), val);
+}
+
+static void reg_writel(unsigned int reg, unsigned int val)
+{
+	port_outl((unsigned short)(io_base + reg), val);
+}
+
+static void delay_ms(unsigned int ms)
+{
+	unsigned int t0 = get_ticks_ms();
+	while (get_ticks_ms() - t0 < ms)
+		;
+}
+
+static void td_set(struct uhci_td *td, unsigned int link, unsigned int status,
+		   unsigned int token, unsigned int buffer)
+{
+	td->link = link;
+	td->status = status;
+	td->token = token;
+	td->buffer = buffer;
+}
+
+/* Stop the controller (clear RS) and wait for it to actually halt. */
+static void uhci_halt(void)
+{
+	unsigned int t0;
+	reg_writew(USBCMD, USBCMD_CF | USBCMD_MAXP);
+	t0 = get_ticks_ms();
+	while (!(reg_readw(USBSTS) & USBSTS_HCH)) {
+		if (get_ticks_ms() - t0 > 100)
+			break;
+	}
+}
+
+static unsigned int td_token(unsigned int pid, unsigned int addr,
+			     unsigned int ep, unsigned int toggle,
+			     unsigned int maxlen)
+{
+	unsigned int explen = (maxlen == 0) ? 0x7FFu
+					    : ((maxlen - 1) & 0x7FFu);
+	return (pid & 0xFFu) |
+	       ((addr & 0x7Fu) << 8) |
+	       ((ep & 0xFu) << 15) |
+	       ((toggle & 1u) << 19) |
+	       (explen << 21);
+}
+
+static void reset_controller(void)
+{
+	unsigned int *fl = (unsigned int *)UHCI_FRAME_LIST_ADDR;
+	unsigned int i;
+
+	reg_writew(USBCMD, USBCMD_GRESET);
+	delay_ms(50);
+	reg_writew(USBCMD, 0);
+	delay_ms(1);
+
+	reg_writew(USBCMD, USBCMD_HCRESET);
+	delay_ms(50);
+	reg_writew(USBCMD, 0);
+	delay_ms(1);
+
+	for (i = 0; i < 1024; i++)
+		fl[i] = (unsigned int)&qh | 0x2u;
+
+	qh.link = 0x1u;
+	qh.element = 0x1u;
+
+	reg_writel(USBFLBASEADD, UHCI_FRAME_LIST_ADDR);
+	reg_writew(USBINTR, 0);
+	reg_writew(USBSTS, 0x3Fu);
+	reg_writew(USBCMD, USBCMD_CF | USBCMD_MAXP);
+}
+
+int uhci_init(void)
+{
+	unsigned int bus, dev;
+
+	found = 0;
+	io_base = 0;
+
+	for (bus = 0; bus < 256 && !found; bus++) {
+		for (dev = 0; dev < 32; dev++) {
+			unsigned int id = pci_cfg_read32(bus, dev, 0, 0x00);
+			unsigned int class_rev, cmd, bar;
+			if (id == 0xFFFFFFFFu || id == 0)
+				continue;
+			class_rev = pci_cfg_read32(bus, dev, 0, 0x08);
+			if ((class_rev >> 16) != PCI_USB_CLASS)
+				continue;
+			if (((class_rev >> 8) & 0xFFu) != 0x00u)
+				continue;
+
+			/* Enable I/O space + bus master. */
+			cmd = pci_cfg_read32(bus, dev, 0, 0x04);
+			pci_cfg_write32(bus, dev, 0, 0x04, cmd | 0x0005u);
+
+			/* Disable legacy SMI emulation. */
+			pci_cfg_write16(bus, dev, 0, 0xC0, 0);
+
+			bar = pci_cfg_read32(bus, dev, 0, 0x20);
+			if (!(bar & 0x1u))
+				continue;
+			io_base = bar & 0xFFFFFFFCu;
+			pci_bus = bus;
+			pci_dev = dev;
+			pci_func = 0;
+			found = 1;
+			break;
+		}
+	}
+
+	if (!found)
+		return -1;
+
+	reset_controller();
+	return 0;
+}
+
+void uhci_pci_info(unsigned int *bus, unsigned int *dev, unsigned int *func,
+		   unsigned int *base)
+{
+	*bus = pci_bus;
+	*dev = pci_dev;
+	*func = pci_func;
+	*base = io_base;
+}
+
+unsigned int uhci_root_port_count(void)
+{
+	return 2;
+}
+
+int uhci_root_port_connected(unsigned int port)
+{
+	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
+	return (reg_readw(reg) & USBPORTSC_CCS) ? 1 : 0;
+}
+
+int uhci_root_port_low_speed(unsigned int port)
+{
+	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
+	return (reg_readw(reg) & USBPORTSC_LSDA) ? 1 : 0;
+}
+
+int uhci_root_port_reset(unsigned int port)
+{
+	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
+	unsigned int st;
+
+	/* Assert reset (this also resets the attached device). */
+	st = reg_readw(reg);
+	reg_writew(reg, (unsigned short)((st & ~USBPORTSC_PE) | USBPORTSC_PR));
+	delay_ms(50);
+
+	/* Deassert reset and clear the connect/enable change bits. */
+	st = reg_readw(reg);
+	reg_writew(reg, (unsigned short)((st & ~USBPORTSC_PR) |
+					 USBPORTSC_CSC | USBPORTSC_PEC));
+	delay_ms(20);
+
+	/* Enable the port: QEMU (and some hardware) require software to
+	   set PE explicitly after a reset. */
+	st = reg_readw(reg);
+	reg_writew(reg, (unsigned short)(st | USBPORTSC_PE));
+	delay_ms(10);
+
+	st = reg_readw(reg);
+	if (!(st & USBPORTSC_PE))
+		return -1;
+	return 0;
+}
+
+int uhci_control_transfer(unsigned int dev_addr, unsigned int mps, int low_speed,
+			  const unsigned char *setup, unsigned char *data,
+			  unsigned int len, int dir_in)
+{
+	unsigned int i, ntd = 0, n_data = 0;
+	unsigned int base = TD_ACTIVE | TD_CERR_3 | (low_speed ? TD_LS : 0);
+	unsigned int t0;
+
+	if (!found)
+		return -1;
+	if (mps == 0 || mps > 64)
+		mps = 64;
+
+	for (i = 0; i < 8; i++)
+		setup_buf[i] = setup[i];
+
+	/* SETUP stage (8 bytes, DATA0). */
+	td_set(&tds[ntd++], 0, base, td_token(TD_PID_SETUP, dev_addr, 0, 0, 8),
+	       (unsigned int)setup_buf);
+
+	/* DATA stage (split into max-packet-sized TDs, DATA1/DATA0/...). */
+	if (len > 0) {
+		unsigned int n = (len + mps - 1) / mps;
+		unsigned int offset = 0;
+		unsigned int toggle = 1;
+		for (i = 0; i < n; i++) {
+			unsigned int chunk = len - offset;
+			if (chunk > mps)
+				chunk = mps;
+			td_set(&tds[ntd++], 0, base,
+			       td_token(dir_in ? TD_PID_IN : TD_PID_OUT,
+					dev_addr, 0, toggle, chunk),
+			       (unsigned int)(data + offset));
+			offset += chunk;
+			toggle ^= 1u;
+		}
+		n_data = n;
+	}
+
+	/* STATUS stage (0 bytes, DATA1). */
+	td_set(&tds[ntd++], 0, base,
+	       td_token(dir_in ? TD_PID_OUT : TD_PID_IN, dev_addr, 0, 1, 0), 0);
+
+	/* Chain the TDs. */
+	for (i = 0; i + 1 < ntd; i++)
+		tds[i].link = (unsigned int)&tds[i + 1];
+	tds[ntd - 1].link = 0x1u;
+
+	qh.element = (unsigned int)&tds[0];
+
+	/* Run and poll until all TDs complete. */
+	reg_writew(USBCMD, USBCMD_RS | USBCMD_CF | USBCMD_MAXP);
+
+	t0 = get_ticks_ms();
+	for (;;) {
+		int done = 1;
+		for (i = 0; i < ntd; i++) {
+			unsigned int st = tds[i].status;
+			if (st & TD_ACTIVE) {
+				done = 0;
+				continue;
+			}
+			if (st & TD_ERR_MASK) {
+				uhci_halt();
+				return -1;
+			}
+		}
+		if (done)
+			break;
+		if (get_ticks_ms() - t0 > 2000) {
+			uhci_halt();
+			return -1;
+		}
+	}
+
+	uhci_halt();
+
+	{
+		unsigned int total = 0;
+		for (i = 0; i < n_data; i++) {
+			unsigned int st = tds[1 + i].status;
+			total += ((st & TD_ACTLEN) + 1) & TD_ACTLEN;
+		}
+		return (int)total;
+	}
+}

+ 24 - 0
uhci.h

@@ -0,0 +1,24 @@
+/* UHCI (USB 1.1) host controller driver.
+   PCI discovery, register access, frame-list / queue-head / transfer-
+   descriptor schedule, and root-hub port control. Polling based (no IRQ). */
+#ifndef UHCI_H
+#define UHCI_H
+
+int uhci_init(void);   /* find + reset/configure the controller; 0 on success */
+
+void uhci_pci_info(unsigned int *bus, unsigned int *dev, unsigned int *func,
+		   unsigned int *io_base);
+
+unsigned int uhci_root_port_count(void);
+int uhci_root_port_connected(unsigned int port);
+int uhci_root_port_low_speed(unsigned int port);
+int uhci_root_port_reset(unsigned int port);
+
+/* Control transfer on endpoint 0. Returns bytes transferred (>= 0) or -1.
+   mps = device max packet size for endpoint 0 (used to split the data stage).
+   dir_in: 1 = data stage IN (device->host), 0 = OUT or no data stage. */
+int uhci_control_transfer(unsigned int dev_addr, unsigned int mps, int low_speed,
+			  const unsigned char *setup, unsigned char *data,
+			  unsigned int len, int dir_in);
+
+#endif

+ 301 - 0
usb.c

@@ -0,0 +1,301 @@
+/* USB core: device enumeration, descriptor parsing, and hub recursion.
+   Drives the UHCI controller to build the device tree for `lsusb`. */
+
+#include "io.h"
+#include "timer.h"
+#include "uhci.h"
+#include "usb.h"
+
+/* Standard request types. */
+#define RT_DEV2HOST_STD 0x80u
+#define RT_HOST2DEV_STD 0x00u
+#define RT_DEV2HOST_CLS 0xA0u
+#define RT_DEV2HOST_OTH 0xA3u
+#define RT_HOST2DEV_OTH 0x23u
+
+/* Standard requests. */
+#define REQ_GET_STATUS     0x00u
+#define REQ_CLEAR_FEATURE  0x01u
+#define REQ_SET_FEATURE    0x03u
+#define REQ_SET_ADDRESS    0x05u
+#define REQ_GET_DESCRIPTOR 0x06u
+
+/* Descriptor types. */
+#define DESC_DEVICE 0x01u
+#define DESC_HUB    0x29u
+
+/* Hub feature selectors. */
+#define FEAT_PORT_RESET        4u
+#define FEAT_PORT_POWER        8u
+#define FEAT_C_PORT_CONNECTION 16u
+
+/* Hub port status bits. */
+#define PSTAT_CONNECT   0x0001u
+#define PSTAT_LOW_SPEED 0x0200u
+
+static unsigned int devnum;
+
+static unsigned char dev_desc[18];
+static unsigned char desc8[8];
+static unsigned char hub_desc[16];
+static unsigned char port_st[4];
+
+static void put_uint(unsigned int n)
+{
+	char buf[12];
+	char *p = buf + sizeof(buf) - 1;
+	*p = '\0';
+	if (n == 0) {
+		io_putchar('0');
+		return;
+	}
+	while (n) {
+		*--p = (char)('0' + (n % 10));
+		n /= 10;
+	}
+	while (*p)
+		io_putchar(*p++);
+}
+
+static void put_hex(unsigned int n, unsigned int digits)
+{
+	static const char hex[] = "0123456789ABCDEF";
+	unsigned int i;
+	for (i = 0; i < digits; i++)
+		io_putchar(hex[(n >> ((digits - 1 - i) * 4)) & 0xF]);
+}
+
+static void msleep(unsigned int ms)
+{
+	unsigned int t0 = get_ticks_ms();
+	while (get_ticks_ms() - t0 < ms)
+		;
+}
+
+static int ctrl_in(unsigned int addr, unsigned int mps, int low,
+		   unsigned char rt, unsigned char req, unsigned short value,
+		   unsigned short index, unsigned char *buf, unsigned int len)
+{
+	unsigned char setup[8];
+	setup[0] = rt;
+	setup[1] = req;
+	setup[2] = (unsigned char)(value & 0xFF);
+	setup[3] = (unsigned char)((value >> 8) & 0xFF);
+	setup[4] = (unsigned char)(index & 0xFF);
+	setup[5] = (unsigned char)((index >> 8) & 0xFF);
+	setup[6] = (unsigned char)(len & 0xFF);
+	setup[7] = (unsigned char)((len >> 8) & 0xFF);
+	return uhci_control_transfer(addr, mps, low, setup, buf, len, 1);
+}
+
+static int ctrl_out(unsigned int addr, unsigned int mps, int low,
+		    unsigned char rt, unsigned char req, unsigned short value,
+		    unsigned short index)
+{
+	unsigned char setup[8];
+	setup[0] = rt;
+	setup[1] = req;
+	setup[2] = (unsigned char)(value & 0xFF);
+	setup[3] = (unsigned char)((value >> 8) & 0xFF);
+	setup[4] = (unsigned char)(index & 0xFF);
+	setup[5] = (unsigned char)((index >> 8) & 0xFF);
+	setup[6] = 0;
+	setup[7] = 0;
+	return uhci_control_transfer(addr, mps, low, setup, 0, 0, 0);
+}
+
+static const char *class_name(unsigned int cls)
+{
+	switch (cls) {
+	case 0x00: return "Per-interface";
+	case 0x01: return "Audio";
+	case 0x02: return "Communications";
+	case 0x03: return "Human Interface";
+	case 0x05: return "Physical";
+	case 0x06: return "Image";
+	case 0x07: return "Printer";
+	case 0x08: return "Mass Storage";
+	case 0x09: return "Hub";
+	case 0x0A: return "CDC Data";
+	case 0x0B: return "Smart Card";
+	case 0x0D: return "Content Security";
+	case 0x0E: return "Video";
+	case 0x0F: return "Personal Healthcare";
+	case 0xE0: return "Wireless";
+	case 0xEF: return "Miscellaneous";
+	case 0xFE: return "Application";
+	case 0xFF: return "Vendor-specific";
+	default: return "Unknown";
+	}
+}
+
+static void indent(unsigned int depth)
+{
+	unsigned int i;
+	for (i = 0; i < depth; i++)
+		io_putstr("  ");
+}
+
+/* wPortStatus (little-endian) from the GET_PORT_STATUS buffer. */
+static unsigned int port_status_word(void)
+{
+	return (unsigned int)port_st[0] | ((unsigned int)port_st[1] << 8);
+}
+
+static void enumerate_hub(unsigned int addr, unsigned int mps, int low,
+			  unsigned int depth);
+static void enumerate_device(unsigned int addr, unsigned int mps, int low,
+			     unsigned int depth);
+static void enumerate_new_device(int low, unsigned int depth);
+
+static void enumerate_device(unsigned int addr, unsigned int mps, int low,
+			     unsigned int depth)
+{
+	unsigned int vendor, product, cls, subcls, proto;
+
+	if (ctrl_in(addr, mps, low, RT_DEV2HOST_STD, REQ_GET_DESCRIPTOR,
+		    (unsigned short)(DESC_DEVICE << 8), 0, dev_desc, 18) < 0) {
+		indent(depth);
+		io_putstr("(device descriptor read failed)\n");
+		return;
+	}
+
+	vendor  = dev_desc[8]  | ((unsigned int)dev_desc[9]  << 8);
+	product = dev_desc[10] | ((unsigned int)dev_desc[11] << 8);
+	cls     = dev_desc[4];
+	subcls  = dev_desc[5];
+	proto   = dev_desc[6];
+
+	indent(depth);
+	io_putstr("Bus 001 Device ");
+	put_uint(addr);
+	io_putstr(": ID ");
+	put_hex(vendor, 4);
+	io_putchar(':');
+	put_hex(product, 4);
+	io_putchar(' ');
+	io_putstr(class_name(cls));
+	io_putstr(" [");
+	put_hex(cls, 2);
+	io_putchar('/');
+	put_hex(subcls, 2);
+	io_putchar('/');
+	put_hex(proto, 2);
+	io_putstr("]\n");
+
+	if (cls == 0x09)
+		enumerate_hub(addr, mps, low, depth + 1);
+}
+
+static void enumerate_hub(unsigned int addr, unsigned int mps, int low,
+			  unsigned int depth)
+{
+	unsigned int nports, p;
+
+	if (ctrl_in(addr, mps, low, RT_DEV2HOST_CLS, REQ_GET_DESCRIPTOR,
+		    (unsigned short)(DESC_HUB << 8), 0, hub_desc,
+		    sizeof(hub_desc)) < 0)
+		return;
+
+	nports = hub_desc[2];
+	if (nports > 8)
+		nports = 8;
+
+	for (p = 1; p <= nports; p++) {
+		int low2;
+
+		if (ctrl_in(addr, mps, low, RT_DEV2HOST_OTH, REQ_GET_STATUS,
+			    0, (unsigned short)p, port_st, 4) < 0)
+			continue;
+		if (!(port_status_word() & PSTAT_CONNECT))
+			continue;
+
+		/* Power and reset the downstream port. */
+		ctrl_out(addr, mps, low, RT_HOST2DEV_OTH, REQ_SET_FEATURE,
+			 FEAT_PORT_POWER, (unsigned short)p);
+		if (ctrl_out(addr, mps, low, RT_HOST2DEV_OTH, REQ_SET_FEATURE,
+			     FEAT_PORT_RESET, (unsigned short)p) < 0)
+			continue;
+		msleep(30);
+
+		ctrl_out(addr, mps, low, RT_HOST2DEV_OTH, REQ_CLEAR_FEATURE,
+			 FEAT_C_PORT_CONNECTION, (unsigned short)p);
+
+		/* Re-read status to learn the child's speed. */
+		low2 = 0;
+		if (ctrl_in(addr, mps, low, RT_DEV2HOST_OTH, REQ_GET_STATUS,
+			    0, (unsigned short)p, port_st, 4) >= 0) {
+			if (port_status_word() & PSTAT_LOW_SPEED)
+				low2 = 1;
+		}
+
+		enumerate_new_device(low2, depth);
+	}
+}
+
+static void enumerate_new_device(int low, unsigned int depth)
+{
+	unsigned int mps;
+
+	devnum++;
+	if (devnum > 127) {
+		indent(depth);
+		io_putstr("(too many devices)\n");
+		return;
+	}
+
+	/* First 8 bytes at address 0 (learn max packet size). */
+	if (ctrl_in(0, 8, low, RT_DEV2HOST_STD, REQ_GET_DESCRIPTOR,
+		    (unsigned short)(DESC_DEVICE << 8), 0, desc8, 8) < 0) {
+		indent(depth);
+		io_putstr("(no response at address 0)\n");
+		return;
+	}
+
+	mps = desc8[7];
+	if (mps == 0)
+		mps = 8;
+
+	/* Assign an address. */
+	if (ctrl_out(0, 8, low, RT_HOST2DEV_STD, REQ_SET_ADDRESS,
+		     (unsigned short)devnum, 0) < 0) {
+		indent(depth);
+		io_putstr("(SET_ADDRESS failed)\n");
+		return;
+	}
+	msleep(5);
+
+	enumerate_device(devnum, mps, low, depth);
+}
+
+void usb_enumerate_and_print(void)
+{
+	unsigned int bus, dev, func, base;
+	unsigned int p;
+
+	devnum = 0;
+
+	if (uhci_init() != 0) {
+		io_putstr("lsusb: no UHCI host controller found\n");
+		return;
+	}
+
+	uhci_pci_info(&bus, &dev, &func, &base);
+	io_putstr("UHCI Host Controller (PCI ");
+	put_hex(bus, 2);
+	io_putchar(':');
+	put_hex(dev, 2);
+	io_putchar('.');
+	put_hex(func, 1);
+	io_putstr(", I/O 0x");
+	put_hex(base, 4);
+	io_putstr(")\n");
+
+	for (p = 0; p < uhci_root_port_count(); p++) {
+		if (!uhci_root_port_connected(p))
+			continue;
+		if (uhci_root_port_reset(p) != 0)
+			continue;
+		enumerate_new_device(uhci_root_port_low_speed(p), 1);
+	}
+}

+ 7 - 0
usb.h

@@ -0,0 +1,7 @@
+/* USB core: device enumeration, descriptor parsing, and hub recursion. */
+#ifndef USB_H
+#define USB_H
+
+void usb_enumerate_and_print(void);
+
+#endif