Просмотр исходного кода

Add OHCI support and native USB HID mouse/keyboard

The ASUS ION's USB 1.1 ports hang off OHCI companions (NVIDIA MCP79),
where the UHCI-only driver found no controller, and its USB keyboard and
mouse were only usable through the BIOS PS/2 legacy emulation - which
also can't coexist with an OS owning the controllers.

USB core:
- usb.c/h is now controller-agnostic: probe-based enumeration, config
  descriptor walking, hub recursion, per-controller device addresses,
  bus scans, a root-port hotplug watcher and a scan generation counter
  (so `lsusb` can't leave a device dead).
- usb_hcd.h is the host-controller ops vtable (control transfers, root
  ports, interrupt-IN slots).

Host controllers:
- ohci.c/h: memory-mapped OHCI driver, up to 4 instances.  HCCA from the
  page allocator, 16-byte-aligned ED/TD lists, dummy TD as queue tail
  anchor, per-port power through PPCM + PPS, control transfers and
  interrupt endpoints polled via each TD's condition code (NAKs stay
  queued).  TDs must be initialized with CC = NotAccessed; data toggles
  are explicit (DATA0 0x02000000, DATA1 0x03000000) - QEMU ignores
  toggles, real hardware doesn't.
- uhci.c: adapted to the ops table; the PCI scan now checks all
  functions (PIIX3/PIIX4/VIA put the USB function at 0:07.2/0:01.2) and
  skips controllers with unassigned BARs.  The controller keeps running;
  the control QH and the per-slot interrupt QHs are all serviced every
  frame.

HID devices (usbhid.c/h):
- up to six interrupt slots; boot mouse/keyboard are used as-is, other
  HID interfaces are classified by reading their report descriptor (so
  subclass-0 mice and composite receivers work).  Mouse reports are
  merged into the cursor path; keyboard reports are diffed and decoded
  to PS/2 set-1 scancodes, injected via io_inject_scancode() so the
  terminal/WM are unchanged.  Root ports are watched for plug/unplug,
  and the BIOS PS/2 legacy emulation is disabled (config 0xC0) since the
  kernel owns the devices.

Integration and tests:
- mouse.c shares one cursor path between PS/2 and USB; mouseinfo shows
  the active backend and keyboard presence.
- run-floppy/run-usb boot with -device pci-ohci -device usb-mouse, the
  new run-uhci target exercises the UHCI backend, and `make test-usb`
  runs headless QEMU regressions (tools/qmp_cursor_test.py verifies
  injected mouse motion by locating the cursor triangle in a
  screendump; tools/qmp_keyboard_test.py types with QMP send-key).
Johannes Zellner 1 месяц назад
Родитель
Сommit
19a84e623f
19 измененных файлов с 2652 добавлено и 262 удалено
  1. 93 7
      AGENTS.md
  2. 35 12
      Makefile
  3. 18 0
      io.c
  4. 3 0
      io.h
  5. 5 0
      kernel.c
  6. 54 24
      mouse.c
  7. 3 0
      mouse.h
  8. 45 17
      mousecmd.c
  9. 684 0
      ohci.c
  10. 10 0
      ohci.h
  11. 206 0
      tools/qmp_cursor_test.py
  12. 138 0
      tools/qmp_keyboard_test.py
  13. 260 61
      uhci.c
  14. 4 18
      uhci.h
  15. 453 122
      usb.c
  16. 44 1
      usb.h
  17. 83 0
      usb_hcd.h
  18. 484 0
      usbhid.c
  19. 30 0
      usbhid.h

+ 93 - 7
AGENTS.md

@@ -12,6 +12,8 @@ Toolchain: `gcc` (32-bit multilib), `as`/`ld`/`objcopy`, `mtools` (`mcopy`/`mkfs
 make all        # floppy.img usb.img final.bin root.img
 make all        # floppy.img usb.img final.bin root.img
 make run        # boot floppy.img + root.img in QEMU (fallback: qemu-system-x86_64)
 make run        # boot floppy.img + root.img in QEMU (fallback: qemu-system-x86_64)
 make run-usb    # boot usb.img as an IDE disk
 make run-usb    # boot usb.img as an IDE disk
+make run-uhci   # like `make run` but with a UHCI controller + USB mouse
+make test-usb   # headless USB mouse/keyboard regression tests (QEMU + python3)
 make clean
 make clean
 ```
 ```
 
 
@@ -109,10 +111,22 @@ make clean
   acks every datagram with the next expected offset, verifies the checksum and
   acks every datagram with the next expected offset, verifies the checksum and
   jumps. While idle the same loop answers ARP/ICMP for our IP, so the board is
   jumps. While idle the same loop answers ARP/ICMP for our IP, so the board is
   reachable (and MAC-resolvable) without running any command.
   reachable (and MAC-resolvable) without running any command.
-- **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.
+- **Mouse**: `mouse.c/h` — cursor move/draw shared by the PS/2 path
+  (IntelliMouse, Cirrus/Radeon hardware cursor) and the USB backend;
+  `usbhid.c/h` — USB HID boot devices: find + configure a mouse and/or
+  keyboard, arm their interrupt endpoints, decode mouse reports and inject
+  keyboard scancodes, watch for plug/unplug.
+- **USB**: `usb.c/h` — controller-agnostic core: device enumeration,
+  descriptor parsing, hub recursion, bus scans, per-controller addresses, the
+  hotplug watcher and the interrupt-IN consumers (mouse + keyboard).
+  `usb_hcd.h` is the
+  host-controller ops vtable; `uhci.c` (I/O-port UHCI, frame list at
+  `0x3000`, one instance) and `ohci.c` (MMIO OHCI, up to 4 instances, HCCA +
+  ED/TD lists, polling) implement it.  `lsusb.c` — the `lsusb` command (lists
+  every controller and its tree).  The devices work on both controller types
+  and can be plugged in at any time (root-port connect-change watcher);
+  `lsusb` re-enumerates the bus, after which `usbhid` re-inits itself via a
+  scan generation counter.
 - **Power/idle**: `idle.c` — `mwait` C-states, `hlt` fallback.
 - **Power/idle**: `idle.c` — `mwait` C-states, `hlt` fallback.
 - **User programs**: `run.c`, `run_api.h`, `prog.c`, `space.c` — raw binaries at
 - **User programs**: `run.c`, `run_api.h`, `prog.c`, `space.c` — raw binaries at
   `0x41000`, API function-pointer struct at `0x40F00`.  `prog`/`space` are
   `0x41000`, API function-pointer struct at `0x40F00`.  `prog`/`space` are
@@ -246,6 +260,71 @@ sends an ad-hoc line.  Nothing is sent before the NIC is up, the producer
 never blocks (a full buffer drops characters and reports it), and the flush
 never blocks (a full buffer drops characters and reports it), and the flush
 pauses while a net command owns the receiver.
 pauses while a net command owns the receiver.
 
 
+## USB HID (mouse + keyboard) / host controllers
+
+`usb.c` is controller-agnostic; the drivers implement the `usb_hcd_ops`
+vtable (`usb_hcd.h`): control transfers, root-port queries/reset, and two
+interrupt-IN slots (0 = mouse, 1 = keyboard). `usb_hcd_init()` picks UHCI
+when present, otherwise OHCI (`ohci.c` drives up to 4 instances — MCP79 has
+four).
+
+- **OHCI**: BAR0 MMIO (`paging_map_mmio()`), HCCA from the page allocator,
+  static 16-byte-aligned ED/TD sets. Control transfers run on the control
+  list (`HcControlHeadED` + CLF) and are polled via each TD's condition code
+  — a NAKed TD stays queued and is retried by the controller. Both HID EDs
+  (F = 0) are chained and referenced from all 32 HCCA interrupt-table slots,
+  so their TDs are serviced every frame. No IRQs and no DoneHead handling:
+  software just harvests retired TDs. **TDs must be initialized with
+  CC = NotAccessed (0xF)** — OHCI has no active bit, and a zero CC makes
+  software think a fresh TD already completed. TD data toggles are explicit:
+  DATA0 = `0x02000000`, DATA1 = `0x03000000` (`0` means "use the ED carry
+  bit"); a wrong value makes the first control transfer fail with a toggle
+  mismatch on real hardware while QEMU (which ignores toggles) is happy.
+  Control queues use a dummy TD as the tail anchor; the data stage is one
+  TD (the controller splits it into MPS-sized packets itself).
+- **UHCI**: I/O ports, frame list at `0x3000`, control QH + two more QHs
+  (one per interrupt slot) serviced every frame while the controller keeps
+  running. The PCI scan checks **all functions** (real PIIX3/PIIX4/VIA
+  layouts put the USB function at 0:07.2 / 0:01.2) and ignores controllers
+  whose BARs the firmware left unassigned. One instance only.
+- **Devices** (`usbhid.c`): every HID (class 3) interface with an
+  interrupt-IN endpoint gets its own interrupt slot (USB_HCD_INT_SLOTS = 6).
+  Boot interfaces (subclass 1, protocol 2/1) are used as-is in boot
+  protocol; other class-3 interfaces are classified by reading their HID
+  report descriptor (a mouse/pointer collection or relative X/Y input is a
+  mouse, a keyboard collection is a keyboard; absolute pointers/tablets are
+  ignored).  Composite devices (keyboard + mouse behind one receiver) and
+  several devices can therefore coexist; mouse reports from all slots are
+  merged.  Mouse reports are 3 bytes (`b0&7` buttons, signed dx/dy; HID's
+  +y is flipped to the PS/2 convention).  Keyboard reports are 8 bytes
+  (modifier byte + 6 keycodes); they are diffed against the previous report
+  and decoded through a HID-usage → scancode-set-1 table (including 0xE0
+  extended keys), then injected with `io_inject_scancode()` so the
+  terminal/WM see exactly what a PS/2 keyboard would produce.
+  `usbhid_poll()` (from `mouse_poll_update()`) also runs the hotplug
+  watcher: root-port connect changes are enumerated (throttled to 250 ms),
+  `CCS` low or a few TD errors detach a device.  A full scan (`lsusb`) bumps
+  `usb_generation()`, which makes `usbhid` detach and rescan, so `lsusb`
+  can't leave the devices dead.  The BIOS PS/2 legacy emulation is
+  deliberately disabled (PCI config `0xC0`) because the kernel now owns
+  these devices.
+- **Debug**: `ohci:` / `uhci:` / `usbhid:` lines go to COM1 (and through the
+  netlog mirror on serial-less boards); `mouseinfo` shows the active mouse
+  backend and whether a USB keyboard is attached; `usb.c`'s `USB_DEBUG` and
+  `usbhid.c`'s `USBHID_DEBUG` (both default 0) add scan/report tracing.
+  Headless tests: `make test-usb` runs `tools/qmp_cursor_test.py` (injects
+  mouse motion with QMP `input-send-event`, verifies the cursor with
+  `screendump`) and `tools/qmp_keyboard_test.py` (types with QMP `send-key`,
+  verifies the screen output); both take mode flags (`--uhci`, `--uhci72`,
+  `--multi`, `--hotplug`).
+- **Limits**: no EHCI (high-speed devices stay invisible), hotplug watches
+  root ports only (a device behind a hub is only enumerated when a scan
+  runs), HID report IDs are not handled (a device that prepends report IDs
+  decodes as garbage), absolute pointers/tablets are ignored, no wheel
+  events, and no USB keyboard means no keyboard at all if the BIOS legacy
+  emulation was the only other source (`make net-dev` still reloads the
+  kernel).
+
 ## Serial debug monitor (`dbg`)
 ## Serial debug monitor (`dbg`)
 
 
 A ring-0 debugger driven over the serial link. On the PC type `dbg`, then drive
 A ring-0 debugger driven over the serial link. On the PC type `dbg`, then drive
@@ -299,9 +378,16 @@ directly at boot — no keystroke injection needed:
 
 
 QEMU gotchas that bit once:
 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`.
+- The default `-M pc` (QEMU ≥ 11) has **no USB controller**. The `run-floppy`
+  and `run-usb` targets therefore add `-device pci-ohci -device usb-mouse`
+  (the OHCI path, same controller type as the ASUS ION); `make run-uhci` runs
+  the same images with `-device piix3-usb-uhci -device usb-mouse` to exercise
+  the UHCI backend. To keep the controller but leave a device out (hotplug
+  test), drop it and use QMP `device_add`/`device_del`. A USB keyboard can be
+  added the same way (`-device usb-kbd`); QMP `send-key` then types on it
+  while the QEMU window's own keys still go to the PS/2 keyboard, so the dev
+  loop stays usable. 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
 - `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
   the string) and kills your script; use `pkill qemu` (process-name match) or
   kill by PID.
   kill by PID.

+ 35 - 12
Makefile

@@ -13,14 +13,14 @@ ASFLAGS  = --32
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
 
-.PHONY: all clean run run-floppy run-usb run-serial floppy usb flash space prog bootstrap dev net-dev netmon monitor
+.PHONY: all clean run run-floppy run-usb run-uhci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev netmon monitor
 
 
 all: floppy.img usb.img final.bin root.img
 all: floppy.img usb.img final.bin root.img
 
 
 boot.o: boot.S
 boot.o: boot.S
 	$(AS) $(ASFLAGS) -o $@ $<
 	$(AS) $(ASFLAGS) -o $@ $<
 
 
-kernel.o: kernel.c idle.h io.h mouse.h process.h terminal.h timer.h serial.h version.h vga.h
+kernel.o: kernel.c idle.h io.h mouse.h process.h terminal.h timer.h serial.h usbhid.h version.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
 screen.o: screen.c screen.h
 screen.o: screen.c screen.h
@@ -119,13 +119,19 @@ display.o: display.c io.h vga.h gpu.h ati.h radeon.h fbtext.h
 cpuinfo.o: cpuinfo.c io.h timer.h
 cpuinfo.o: cpuinfo.c io.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
-mousecmd.o: mousecmd.c io.h mouse.h
+mousecmd.o: mousecmd.c io.h mouse.h usb.h usbhid.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
-uhci.o: uhci.c uhci.h pci.h timer.h
+uhci.o: uhci.c uhci.h usb_hcd.h pci.h serial.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
-usb.o: usb.c usb.h io.h timer.h uhci.h
+ohci.o: ohci.c ohci.h usb_hcd.h pci.h paging.h mm.h serial.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+usb.o: usb.c usb.h usb_hcd.h io.h serial.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+usbhid.o: usbhid.c usbhid.h io.h usb.h usb_hcd.h serial.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
 lsusb.o: lsusb.c io.h usb.h
 lsusb.o: lsusb.c io.h usb.h
@@ -182,7 +188,7 @@ fatformat.o: fatformat.c fatformat.h blkdev.h
 format.o: format.c blkdev.h disk.h fatformat.h io.h vga.h
 format.o: format.c blkdev.h disk.h fatformat.h io.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
-mouse.o: mouse.c mouse.h cirrus.h radeon.h timer.h vga.h
+mouse.o: mouse.c mouse.h cirrus.h radeon.h timer.h usbhid.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
 idle.o: idle.c idle.h
 idle.o: idle.c idle.h
@@ -251,7 +257,7 @@ syscall_stub.o: syscall_stub.S
 mem.o: mem.c mm.h io.h
 mem.o: mem.c mm.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(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 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 peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o hello_embed.o prog_embed.o space_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 ohci.o usb.o usbhid.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 peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o hello_embed.o prog_embed.o space_embed.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -386,12 +392,29 @@ flash: usb.img
 	@./flash.sh "$(USB)" "$(FORCE)"
 	@./flash.sh "$(USB)" "$(FORCE)"
 
 
 run-floppy: floppy.img root.img
 run-floppy: floppy.img root.img
-	qemu-system-i386 -M pc -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
-	qemu-system-x86_64 -M pc -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
+	qemu-system-i386 -M pc -device pci-ohci -device usb-mouse -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
+	qemu-system-x86_64 -M pc -device pci-ohci -device usb-mouse -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
 
 
 run-usb: usb.img root.img
 run-usb: usb.img root.img
-	qemu-system-i386 -M pc -boot c -drive file=usb.img,format=raw,if=ide -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
-	qemu-system-x86_64 -M pc -boot c -drive file=usb.img,format=raw,if=ide -drive file=root.img,format=raw,if=floppy
+	qemu-system-i386 -M pc -boot c -device pci-ohci -device usb-mouse -drive file=usb.img,format=raw,if=ide -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
+	qemu-system-x86_64 -M pc -boot c -device pci-ohci -device usb-mouse -drive file=usb.img,format=raw,if=ide -drive file=root.img,format=raw,if=floppy
+
+# UHCI variant (machines with an Intel/VIA-style controller, and the
+# regression test for the UHCI backend of the USB core).
+run-uhci: floppy.img root.img
+	qemu-system-i386 -M pc -device piix3-usb-uhci -device usb-mouse -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
+	qemu-system-x86_64 -M pc -device piix3-usb-uhci -device usb-mouse -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
+
+# Headless USB HID regression tests (QEMU + python3): cursor movement via
+# injected USB mouse reports and keyboard input via injected key events,
+# including hotplug.  See tools/*.py.
+test-usb: floppy.img root.img
+	python3 tools/qmp_cursor_test.py
+	python3 tools/qmp_cursor_test.py --uhci
+	python3 tools/qmp_cursor_test.py --uhci72
+	python3 tools/qmp_cursor_test.py --hotplug
+	python3 tools/qmp_keyboard_test.py
+	python3 tools/qmp_keyboard_test.py --hotplug
 
 
 scp-final: final.bin
 scp-final: final.bin
 	scp final.bin root@192.168.0.136:
 	scp final.bin root@192.168.0.136:
@@ -459,4 +482,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 
 clean:
 clean:
-	rm -f boot.o 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 hello.o reboot.o poweroff.o fat.o ls.o cat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o 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 peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.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 bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o 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 hello.o reboot.o poweroff.o fat.o ls.o cat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.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 peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.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 bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 18 - 0
io.c

@@ -316,3 +316,21 @@ unsigned char io_last_scancode(void)
 {
 {
 	return last_scancode;
 	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. */
+void io_inject_scancode(unsigned char sc)
+{
+	unsigned int flags;
+
+	__asm__ volatile ("pushfl; popl %0; cli" : "=r"(flags));
+	{
+		unsigned int next = (kbd_head + 1) % KBD_BUF_SIZE;
+		if (next != kbd_tail) {
+			kbd_buf[kbd_head] = sc;
+			kbd_head = next;
+		}
+	}
+	__asm__ volatile ("pushl %0; popfl" : : "r"(flags));
+}

+ 3 - 0
io.h

@@ -38,5 +38,8 @@ int io_poll_key(void);
 /* Same as io_poll_key but also reads port 0x60 when buffer empty (for full-screen programs). */
 /* Same as io_poll_key but also reads port 0x60 when buffer empty (for full-screen programs). */
 int io_poll_key_with_hw(void);
 int io_poll_key_with_hw(void);
 unsigned char io_last_scancode(void);
 unsigned char io_last_scancode(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);
 
 
 #endif
 #endif

+ 5 - 0
kernel.c

@@ -13,6 +13,7 @@
 #include "process.h"
 #include "process.h"
 #include "timer.h"
 #include "timer.h"
 #include "tss.h"
 #include "tss.h"
+#include "usbhid.h"
 #include "wm.h"
 #include "wm.h"
 #include "serial.h"
 #include "serial.h"
 #include "version.h"
 #include "version.h"
@@ -195,6 +196,10 @@ void kernel_main(void)
 	gdt_tss_init();
 	gdt_tss_init();
 	timer_init();
 	timer_init();
 	mouse_init();
 	mouse_init();
+	/* USB HID backend (mouse + keyboard): controller bring-up + first
+	 * scan; devices plugged in later are picked up by the hotplug
+	 * watcher in the WM loop. */
+	usbhid_init();
 	vga_shadow_init();
 	vga_shadow_init();
 	vga_fb_flush();
 	vga_fb_flush();
 	kdbg_init();
 	kdbg_init();

+ 54 - 24
mouse.c

@@ -2,6 +2,7 @@
 #include "cirrus.h"
 #include "cirrus.h"
 #include "radeon.h"
 #include "radeon.h"
 #include "timer.h"
 #include "timer.h"
+#include "usbhid.h"
 #include "vga.h"
 #include "vga.h"
 
 
 #define PS2_DATA   0x60
 #define PS2_DATA   0x60
@@ -260,12 +261,58 @@ void mouse_init(void)
 	mouse_streaming_flag = 1;
 	mouse_streaming_flag = 1;
 }
 }
 
 
+/* Move the cursor by a relative delta (PS/2 sign convention: +dx right,
+   +dy up), redrawing it with the current backend (hardware cursor or
+   shadow-buffer save/restore). */
+static void mouse_move(int dx, int dy)
+{
+	long nx, ny;
+
+	if (!mouse_cursor_flag)
+		return;
+
+	nx = (long)cur_x + dx;
+	ny = (long)cur_y - dy;
+	mouse_clamp_ptr(&nx, &ny);
+	if ((unsigned int)nx == cur_x && (unsigned int)ny == cur_y)
+		return;
+
+	if (mouse_hw_cursor) {
+		cur_x = (unsigned int)nx;
+		cur_y = (unsigned int)ny;
+		if (mouse_hw_cursor == 2)
+			radeon_cursor_move(cur_x, cur_y);
+		else
+			cirrus_cursor_move(cur_x, cur_y);
+	} else {
+		vga_fb_write_rect(cur_x, cur_y, MOUSE_CUR_W, MOUSE_CUR_H,
+			cur_saved);
+		cur_x = (unsigned int)nx;
+		cur_y = (unsigned int)ny;
+		vga_fb_read_rect(cur_x, cur_y, MOUSE_CUR_W, MOUSE_CUR_H,
+			cur_saved);
+		mouse_draw_cursor(cur_x, cur_y);
+	}
+}
+
 void mouse_poll_update(void)
 void mouse_poll_update(void)
 {
 {
 	unsigned int guard = 0;
 	unsigned int guard = 0;
+	unsigned int usb_buttons = 0;
+	int usb_dx = 0, usb_dy = 0;
 
 
-	if (mouse_present_flag && !mouse_cursor_flag)
+	/* The cursor is set up for whichever backend shows up first (PS/2
+	   is probed at boot, USB may attach later). */
+	if ((mouse_present_flag || usbhid_mouse_attached()) && !mouse_cursor_flag)
 		mouse_cursor_setup();
 		mouse_cursor_setup();
+
+	/* USB HID mouse: reports arrive through the armed interrupt
+	   endpoint; the backend also handles hotplug/detach. */
+	if (usbhid_poll(&usb_buttons, &usb_dx, &usb_dy)) {
+		mouse_buttons = usb_buttons;
+		mouse_move(usb_dx, usb_dy);
+	}
+
 	if (!mouse_streaming_flag)
 	if (!mouse_streaming_flag)
 		return;
 		return;
 
 
@@ -300,33 +347,16 @@ void mouse_poll_update(void)
 		if ((b0 & 0xC0) != 0)
 		if ((b0 & 0xC0) != 0)
 			continue;
 			continue;
 
 
-		if (mouse_cursor_flag) {
-			long nx = (long)cur_x + dx;
-			long ny = (long)cur_y - dy;
-			mouse_clamp_ptr(&nx, &ny);
-			if ((unsigned int)nx != cur_x || (unsigned int)ny != cur_y) {
-				if (mouse_hw_cursor) {
-					cur_x = (unsigned int)nx;
-					cur_y = (unsigned int)ny;
-					if (mouse_hw_cursor == 2)
-						radeon_cursor_move(cur_x, cur_y);
-					else
-						cirrus_cursor_move(cur_x, cur_y);
-				} else {
-					vga_fb_write_rect(cur_x, cur_y, MOUSE_CUR_W, MOUSE_CUR_H,
-						cur_saved);
-					cur_x = (unsigned int)nx;
-					cur_y = (unsigned int)ny;
-					vga_fb_read_rect(cur_x, cur_y, MOUSE_CUR_W, MOUSE_CUR_H,
-						cur_saved);
-					mouse_draw_cursor(cur_x, cur_y);
-				}
-			}
-		}
+		mouse_move(dx, dy);
 	}
 	}
 }
 }
 
 
 int mouse_is_present(void)
 int mouse_is_present(void)
+{
+	return mouse_present_flag || usbhid_mouse_attached();
+}
+
+int mouse_ps2_present(void)
 {
 {
 	return mouse_present_flag;
 	return mouse_present_flag;
 }
 }

+ 3 - 0
mouse.h

@@ -5,6 +5,9 @@ void mouse_init(void);
 void mouse_poll_update(void);
 void mouse_poll_update(void);
 
 
 int mouse_is_present(void);
 int mouse_is_present(void);
+/* 1 when a PS/2 mouse was detected; the protocol accessors below are
+   PS/2-specific (the USB backend lives in usbhid.h). */
+int mouse_ps2_present(void);
 int mouse_streaming_enabled(void);
 int mouse_streaming_enabled(void);
 unsigned int mouse_device_id(void);
 unsigned int mouse_device_id(void);
 int mouse_cursor_visible(void);
 int mouse_cursor_visible(void);

+ 45 - 17
mousecmd.c

@@ -2,6 +2,8 @@
 
 
 #include "io.h"
 #include "io.h"
 #include "mouse.h"
 #include "mouse.h"
+#include "usb.h"
+#include "usbhid.h"
 
 
 static void put_uint(unsigned int n)
 static void put_uint(unsigned int n)
 {
 {
@@ -28,28 +30,54 @@ static void put_hex8(unsigned int x)
 
 
 void program_mouseinfo_main(void)
 void program_mouseinfo_main(void)
 {
 {
-	unsigned int id = mouse_device_id();
-
 	io_putstr("mouse present ");
 	io_putstr("mouse present ");
 	io_putstr(mouse_is_present() ? "yes\n" : "no\n");
 	io_putstr(mouse_is_present() ? "yes\n" : "no\n");
 	if (!mouse_is_present())
 	if (!mouse_is_present())
 		return;
 		return;
 
 
-	io_putstr("mouse id 0x");
-	put_hex8(id & 0xFFu);
-	io_putchar('\n');
-	io_putstr("mouse protocol ");
-	if (id == 0x03)
-		io_putstr("intellimouse (wheel)\n");
-	else if (id == 0x04)
-		io_putstr("intellimouse explorer (5-button)\n");
-	else
-		io_putstr("standard ps/2\n");
-	io_putstr("mouse packet bytes ");
-	put_uint(mouse_packet_size());
-	io_putchar('\n');
-	io_putstr("mouse streaming ");
-	io_putstr(mouse_streaming_enabled() ? "on\n" : "off\n");
+	if (mouse_ps2_present()) {
+		unsigned int id = mouse_device_id();
+
+		io_putstr("mouse ps/2 id 0x");
+		put_hex8(id & 0xFFu);
+		io_putchar('\n');
+		io_putstr("mouse protocol ");
+		if (id == 0x03)
+			io_putstr("intellimouse (wheel)\n");
+		else if (id == 0x04)
+			io_putstr("intellimouse explorer (5-button)\n");
+		else
+			io_putstr("standard ps/2\n");
+		io_putstr("mouse packet bytes ");
+		put_uint(mouse_packet_size());
+		io_putchar('\n');
+		io_putstr("mouse streaming ");
+		io_putstr(mouse_streaming_enabled() ? "on\n" : "off\n");
+	}
+
+	if (usbhid_mouse_attached()) {
+		unsigned int ctrl, addr, ep, mps;
+		int low;
+
+		usbhid_get_info(&ctrl, &addr, &ep, &mps, &low);
+		io_putstr("mouse usb ");
+		io_putstr(usb_hcd_name());
+		io_putstr(" hid boot\n");
+		io_putstr("mouse usb ctrl ");
+		put_uint(ctrl);
+		io_putstr(" addr ");
+		put_uint(addr);
+		io_putstr(" ep 0x");
+		put_hex8(0x80u | ep);
+		io_putchar('\n');
+		io_putstr("mouse usb mps ");
+		put_uint(mps);
+		io_putstr(low ? " (low speed)\n" : " (full speed)\n");
+	}
+
+	io_putstr("mouse usb keyboard ");
+	io_putstr(usbhid_keyboard_attached() ? "yes\n" : "no\n");
+
 	io_putstr("mouse cursor ");
 	io_putstr("mouse cursor ");
 	io_putstr(mouse_cursor_visible() ? "visible\n" : "hidden\n");
 	io_putstr(mouse_cursor_visible() ? "visible\n" : "hidden\n");
 }
 }

+ 684 - 0
ohci.c

@@ -0,0 +1,684 @@
+/* OHCI (USB 1.1) host controller driver.
+
+   Memory-mapped (BAR0) controller with ED/TD lists in the identity-mapped
+   kernel address space.  Polling based (no IRQ): control transfers run on
+   the control list and are monitored by polling each TD's condition code;
+   the mouse's interrupt-IN endpoint is a single always-armed TD linked into
+   every HCCA interrupt-table slot (F = 0 means "every frame"), so the
+   controller retries NAKs on its own and software only harvests reports.
+
+   Up to four controller instances (MCP79 exposes four of them); each PCI
+   function is one root hub with its own device address space. */
+
+#include "ohci.h"
+#include "usb_hcd.h"
+#include "pci.h"
+#include "paging.h"
+#include "mm.h"
+#include "serial.h"
+#include "timer.h"
+
+/* Register offsets. */
+#define R_REVISION       0x00
+#define R_CONTROL        0x04
+#define R_COMMAND        0x08
+#define R_INT_STATUS     0x0C
+#define R_INT_ENABLE     0x10
+#define R_INT_DISABLE    0x14
+#define R_HCCA           0x18
+#define R_PERIOD_CUR_ED  0x1C
+#define R_CTRL_HEAD_ED   0x20
+#define R_CTRL_CUR_ED    0x24
+#define R_BULK_HEAD_ED   0x28
+#define R_BULK_CUR_ED    0x2C
+#define R_DONE_HEAD      0x30
+#define R_FM_INTERVAL    0x34
+#define R_FM_REMAINING   0x38
+#define R_FM_NUMBER      0x3C
+#define R_PERIODIC_START 0x40
+#define R_LS_THRESHOLD   0x44
+#define R_RH_DESC_A      0x48
+#define R_RH_DESC_B      0x4C
+#define R_RH_STATUS      0x50
+#define R_RH_PORT_FIRST  0x54
+
+/* R_CONTROL bits. */
+#define CTL_PLE      0x00000004u
+#define CTL_CLE      0x00000010u
+#define CTL_BLE      0x00000020u
+#define CTL_HCFS     0x000000C0u
+#define HCFS_RESUME  0x00000040u
+#define HCFS_OPER    0x00000080u
+
+/* R_COMMAND bits. */
+#define CMD_HCR 0x00000001u
+#define CMD_CLF 0x00000002u
+
+/* R_INT_STATUS bits. */
+#define INTR_WDH 0x00000002u
+
+/* R_RH_DESC_A bits. */
+#define RHA_PSM    0x00000100u
+#define RHA_NPS    0x00000200u
+#define RHA_POTPGT 0xFF000000u
+#define RHA_NDP    0x000000FFu
+
+/* R_RH_STATUS bits. */
+#define RHS_LPSC 0x00010000u
+
+/* R_RH_DESC_B: PortPowerControlMask (which ports are individually
+   switched when PSM is set). */
+#define RHB_PPCM 0xFFFF0000u
+
+/* Root hub port status bits. */
+#define PS_CCS  0x00000001u
+#define PS_PES  0x00000002u
+#define PS_PRS  0x00000010u
+#define PS_PPS  0x00000100u   /* port power (write 1 to switch power on) */
+#define PS_LSDA 0x00000200u
+#define PS_CSC  0x00010000u
+#define PS_PESC 0x00020000u
+#define PS_PRSC 0x00100000u
+#define PS_WTC  (PS_CSC | PS_PESC | PS_PRSC)
+
+/* Endpoint descriptor (ED) fields. */
+#define ED_FA(a)  ((a) & 0x7Fu)
+#define ED_EN(e)  (((e) & 0xFu) << 7)
+#define ED_S      (1u << 13)
+#define ED_MPS(m) (((m) & 0x7FFu) << 16)
+#define ED_PTR_MASK 0xFFFFFFF0u
+#define ED_H      0x00000001u   /* head pointer: halted */
+#define ED_C      0x00000002u   /* head pointer: data-toggle carry */
+
+/* Transfer descriptor (TD) fields. */
+#define TD_R        (1u << 18)
+#define TD_DP(d)    (((d) & 3u) << 19)
+#define TD_DP_SETUP 0u
+#define TD_DP_OUT   1u
+#define TD_DP_IN    2u
+/* Data toggle field (bits 24-25): 10b = DATA0, 11b = DATA1. */
+#define TD_T_DATA0  0x02000000u
+#define TD_T_DATA1  0x03000000u
+#define TD_CC_SHIFT 28
+#define TD_CC_MASK  0xF0000000u
+#define TD_NOTACCESSED 0xFu
+
+/* PCI: class 0x0C (serial), subclass 0x03 (USB), prog.if 0x10 (OHCI). */
+#define PCI_USB_CLASS 0x0C03u
+
+#define OHCI_MAX_TD 16
+
+struct ohci_ed {
+	unsigned int flags;
+	unsigned int tail;
+	unsigned int head;
+	unsigned int next;
+} __attribute__((aligned(16)));
+
+struct ohci_td {
+	unsigned int flags;
+	unsigned int cbp;
+	unsigned int next;
+	unsigned int be;
+} __attribute__((aligned(16)));
+
+struct ohci_ctrl {
+	volatile unsigned int *regs;
+	unsigned int bus, dev, func, bar;
+	unsigned int hcca;
+	unsigned int ports;
+	unsigned int potpgt;
+	int nps;
+
+	/* Interrupt-IN endpoints: slot 0 = mouse, slot 1 = keyboard.  All
+	   slots stay linked into the periodic list; empty EDs are skipped
+	   by the controller. */
+	struct ohci_ed int_ed[USB_HCD_INT_SLOTS];
+	struct ohci_td int_td[USB_HCD_INT_SLOTS];
+	struct ohci_td int_dummy[USB_HCD_INT_SLOTS];
+	unsigned char int_buf[USB_HCD_INT_SLOTS][8] __attribute__((aligned(16)));
+	unsigned int int_mps[USB_HCD_INT_SLOTS];
+	unsigned int int_toggle[USB_HCD_INT_SLOTS];
+	int int_armed[USB_HCD_INT_SLOTS];
+};
+
+static struct ohci_ctrl ctrls[USB_HCD_MAX_CTRL];
+static unsigned int n_ctrls;
+
+/* Control-transfer scratch: transfers are serialized, so one ED/TD set for
+   all instances is enough.  A dummy TD anchors the tail of each queue (the
+   controller stops when HeadP == TailP; the dummy is never processed). */
+static struct ohci_ed ctrl_ed;
+static struct ohci_td ctrl_tds[OHCI_MAX_TD];
+static struct ohci_td ctrl_dummy;
+static unsigned char setup_buf[8] __attribute__((aligned(16)));
+static int ctl_busy;
+
+static void ohci_int_in_stop(unsigned int slot);
+
+static unsigned int rd(struct ohci_ctrl *c, unsigned int ofs)
+{
+	return c->regs[ofs >> 2];
+}
+
+static void wr(struct ohci_ctrl *c, unsigned int ofs, unsigned int val)
+{
+	c->regs[ofs >> 2] = val;
+}
+
+static void delay_ms(unsigned int ms)
+{
+	unsigned int t0 = get_ticks_ms();
+	while (get_ticks_ms() - t0 < ms)
+		;
+}
+
+static unsigned int port_reg(unsigned int port)
+{
+	return R_RH_PORT_FIRST + 4u * port;
+}
+
+static int ohci_setup_one(unsigned int bus, unsigned int dev, unsigned int func)
+{
+	struct ohci_ctrl *c;
+	unsigned int bar, cmd, rha, t0, i;
+
+	if (n_ctrls >= USB_HCD_MAX_CTRL)
+		return -1;
+
+	bar = pci_cfg_read32(bus, dev, func, 0x10);
+	if (bar & 0x1u) {
+		serial_puts(SERIAL_COM1, "ohci: BAR0 is not MMIO\n");
+		return -1;                      /* register block must be MMIO */
+	}
+	bar &= 0xFFFFFFF0u;
+	if (!bar) {
+		serial_puts(SERIAL_COM1, "ohci: BAR0 is unassigned\n");
+		return -1;
+	}
+
+	cmd = pci_cfg_read32(bus, dev, func, 0x04);
+	pci_cfg_write32(bus, dev, func, 0x04, cmd | 0x0006u);  /* mem + bus master */
+
+	/* Disable legacy SMI emulation (same idea as the UHCI driver). */
+	pci_cfg_write16(bus, dev, func, 0xC0, 0);
+
+	c = &ctrls[n_ctrls];
+	c->regs = (volatile unsigned int *)bar;
+	c->bus = bus;
+	c->dev = dev;
+	c->func = func;
+	c->bar = bar;
+
+	paging_map_mmio(bar, 0x1000);
+
+	if (rd(c, R_REVISION) == 0xFFFFFFFFu || rd(c, R_REVISION) == 0) {
+		serial_puts(SERIAL_COM1, "ohci: no register response (rev ");
+		serial_puthex(SERIAL_COM1, rd(c, R_REVISION));
+		serial_puts(SERIAL_COM1, ")\n");
+		return -1;
+	}
+
+	c->hcca = mm_alloc_page();
+	if (!c->hcca) {
+		serial_puts(SERIAL_COM1, "ohci: no memory for HCCA\n");
+		return -1;
+	}
+	for (i = 0; i < 1024; i++)
+		((unsigned int *)c->hcca)[i] = 0;
+
+	/* Periodic list: the interrupt EDs are chained and referenced from
+	   every HCCA table slot (F = 0 means "every frame").  Idle queues
+	   are empty (HeadP == TailP == dummy) but carry valid ED fields. */
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		c->int_ed[i].flags = ED_FA(0) | ED_EN(0) | ED_MPS(8);
+		c->int_ed[i].tail = (unsigned int)&c->int_dummy[i];
+		c->int_ed[i].head = (unsigned int)&c->int_dummy[i];
+		c->int_ed[i].next = (i + 1 < USB_HCD_INT_SLOTS)
+			? (unsigned int)&c->int_ed[i + 1] : 0;
+		c->int_dummy[i].flags = TD_NOTACCESSED << TD_CC_SHIFT;
+		c->int_dummy[i].cbp = 0;
+		c->int_dummy[i].next = 0;
+		c->int_dummy[i].be = 0;
+		c->int_armed[i] = 0;
+	}
+	for (i = 0; i < 32; i++)
+		((unsigned int *)c->hcca)[i] = (unsigned int)&c->int_ed[0];
+
+	/* Host controller reset. */
+	wr(c, R_COMMAND, CMD_HCR);
+	t0 = get_ticks_ms();
+	while (rd(c, R_COMMAND) & CMD_HCR) {
+		if (get_ticks_ms() - t0 > 100)
+			break;
+	}
+	delay_ms(2);
+
+	/* Standard frame timing (12 MHz / 1 kHz - 1) and list setup. */
+	wr(c, R_FM_INTERVAL, (0x2778u << 16) | 0x2EDFu);
+	wr(c, R_PERIODIC_START, 0x2A2Fu);
+	wr(c, R_LS_THRESHOLD, 0x628u);
+	wr(c, R_HCCA, c->hcca);
+	wr(c, R_INT_DISABLE, 0xFFFFFFFFu);
+	wr(c, R_INT_STATUS, 0xFFFFFFFFu);   /* clear pending */
+	wr(c, R_DONE_HEAD, 0);
+
+	/* Root hub: port count and power. */
+	rha = rd(c, R_RH_DESC_A);
+	c->ports = rha & RHA_NDP;
+	if (c->ports > 15)
+		c->ports = 15;
+	if (c->ports == 0) {
+		serial_puts(SERIAL_COM1, "ohci: no downstream ports\n");
+		return -1;
+	}
+	c->nps = (rha & RHA_NPS) ? 1 : 0;
+	c->potpgt = (rha & RHA_POTPGT) >> 24;
+
+	if (!c->nps) {
+		/* Power switching is implemented: mark every port as
+		   individually switchable, raise global power and switch on
+		   each port, then let the supply settle (POTPGT in 2 ms
+		   units). */
+		wr(c, R_RH_DESC_B, RHB_PPCM);
+		wr(c, R_RH_STATUS, RHS_LPSC);
+		for (i = 0; i < c->ports; i++)
+			wr(c, port_reg(i), PS_PPS);
+		delay_ms(c->potpgt * 2 + 20);
+	} else {
+		delay_ms(20);
+	}
+
+	/* Leave reset (spec: via USBRESUME) and enter operational with the
+	   periodic + control lists enabled. */
+	wr(c, R_CONTROL, HCFS_RESUME);
+	delay_ms(20);
+	wr(c, R_CONTROL, HCFS_OPER | CTL_PLE | CTL_CLE);
+
+	n_ctrls++;
+
+	{
+		unsigned int conn = 0, pwr = 0, st;
+
+		for (i = 0; i < c->ports; i++) {
+			st = rd(c, port_reg(i));
+			if (st & PS_CCS)
+				conn++;
+			if (st & PS_PPS)
+				pwr++;
+		}
+
+		serial_puts(SERIAL_COM1, "ohci: controller at ");
+		serial_putdec(SERIAL_COM1, bus);
+		serial_puts(SERIAL_COM1, ":");
+		serial_putdec(SERIAL_COM1, dev);
+		serial_puts(SERIAL_COM1, ".");
+		serial_putdec(SERIAL_COM1, func);
+		serial_puts(SERIAL_COM1, " ports ");
+		serial_putdec(SERIAL_COM1, c->ports);
+		serial_puts(SERIAL_COM1, " psm ");
+		serial_putdec(SERIAL_COM1, (rha & RHA_PSM) ? 1u : 0u);
+		serial_puts(SERIAL_COM1, " nps ");
+		serial_putdec(SERIAL_COM1, (unsigned int)c->nps);
+		serial_puts(SERIAL_COM1, " potpgt ");
+		serial_putdec(SERIAL_COM1, c->potpgt);
+		serial_puts(SERIAL_COM1, " conn ");
+		serial_putdec(SERIAL_COM1, conn);
+		serial_puts(SERIAL_COM1, " pwr ");
+		serial_putdec(SERIAL_COM1, pwr);
+		serial_puts(SERIAL_COM1, "\n");
+	}
+	return 0;
+}
+
+static int ohci_init(void)
+{
+	unsigned int bus, dev, func;
+
+	if (n_ctrls)
+		return (int)n_ctrls;
+
+	for (bus = 0; bus < 256 && n_ctrls < USB_HCD_MAX_CTRL; bus++) {
+		for (dev = 0; dev < 32; dev++) {
+			for (func = 0; func < 8; func++) {
+				unsigned int id = pci_cfg_read32(bus, dev, func, 0x00);
+				unsigned int class_rev;
+
+				if (id == 0xFFFFFFFFu || id == 0)
+					continue;
+				class_rev = pci_cfg_read32(bus, dev, func, 0x08);
+				if ((class_rev >> 16) != PCI_USB_CLASS)
+					continue;
+				if (((class_rev >> 8) & 0xFFu) != 0x10u)
+					continue;   /* not OHCI */
+
+				ohci_setup_one(bus, dev, func);
+			}
+		}
+	}
+	return (int)n_ctrls;
+}
+
+static unsigned int ohci_count(void)
+{
+	return n_ctrls;
+}
+
+static void ohci_info(unsigned int ctrl, unsigned int *bus, unsigned int *dev,
+		      unsigned int *func, unsigned int *base, int *mmio)
+{
+	struct ohci_ctrl *c = &ctrls[ctrl];
+	*bus = c->bus;
+	*dev = c->dev;
+	*func = c->func;
+	*base = c->bar;
+	*mmio = 1;
+}
+
+static unsigned int ohci_port_count(unsigned int ctrl)
+{
+	return ctrls[ctrl].ports;
+}
+
+static int ohci_port_connected(unsigned int ctrl, unsigned int port)
+{
+	return (rd(&ctrls[ctrl], port_reg(port)) & PS_CCS) ? 1 : 0;
+}
+
+static int ohci_port_low_speed(unsigned int ctrl, unsigned int port)
+{
+	return (rd(&ctrls[ctrl], port_reg(port)) & PS_LSDA) ? 1 : 0;
+}
+
+static int ohci_port_take_change(unsigned int ctrl, unsigned int port)
+{
+	struct ohci_ctrl *c = &ctrls[ctrl];
+	unsigned int ofs = port_reg(port);
+
+	if (!(rd(c, ofs) & PS_CSC))
+		return 0;
+	wr(c, ofs, PS_CSC);   /* write-1-to-clear */
+	return 1;
+}
+
+static int ohci_port_reset(unsigned int ctrl, unsigned int port)
+{
+	struct ohci_ctrl *c = &ctrls[ctrl];
+	unsigned int ofs = port_reg(port);
+	unsigned int t0, st;
+
+	if (!(rd(c, ofs) & PS_CCS))
+		return -1;
+
+	/* Clear stale change bits. */
+	wr(c, ofs, PS_WTC);
+
+	/* Assert reset; the controller clears PRS when the reset finishes
+	   (at least 10 ms for the device to see it). */
+	wr(c, ofs, PS_PRS);
+	t0 = get_ticks_ms();
+	for (;;) {
+		if (!(rd(c, ofs) & PS_PRS))
+			break;
+		if (get_ticks_ms() - t0 > 200)
+			return -1;
+	}
+	delay_ms(10);
+
+	/* Acknowledge reset-complete and make sure the port is enabled. */
+	wr(c, ofs, PS_PRSC | PS_CSC | PS_PESC);
+	wr(c, ofs, PS_PES);
+
+	st = rd(c, ofs);
+	if (!(st & PS_CCS) || !(st & PS_PES))
+		return -1;
+	return 0;
+}
+
+static void td_set(struct ohci_td *td, unsigned int flags, unsigned int cbp,
+		   unsigned int be)
+{
+	td->flags = flags | (TD_NOTACCESSED << TD_CC_SHIFT);
+	td->cbp = cbp;
+	td->next = 0;
+	td->be = be;
+}
+
+static int ohci_transfer(struct ohci_ctrl *c, unsigned int addr,
+			 unsigned int mps, int low,
+			 const unsigned char *setup, unsigned char *data,
+			 unsigned int len, int dir_in)
+{
+	unsigned int i, n = 0, n_data = 0, t0;
+
+	if (mps == 0 || mps > 64)
+		mps = 64;
+
+	for (i = 0; i < 8; i++)
+		setup_buf[i] = setup[i];
+
+	/* SETUP stage (DATA0). */
+	td_set(&ctrl_tds[n++], TD_DP(TD_DP_SETUP) | TD_T_DATA0,
+	       (unsigned int)setup_buf, (unsigned int)setup_buf + 7);
+
+	/* DATA stage: one TD for the whole buffer, DATA1 (like Linux; the
+	   controller splits it into MPS-sized packets itself). */
+	if (len > 0) {
+		td_set(&ctrl_tds[n++],
+		       TD_R | TD_DP(dir_in ? TD_DP_IN : TD_DP_OUT) |
+		       TD_T_DATA1,
+		       (unsigned int)data, (unsigned int)(data + len - 1));
+		n_data = 1;
+	}
+
+	/* STATUS stage (DATA1, opposite direction, no data). */
+	td_set(&ctrl_tds[n++],
+	       TD_DP(dir_in ? TD_DP_OUT : TD_DP_IN) | TD_T_DATA1, 0, 0);
+
+	/* Chain the TDs and anchor the tail on the dummy TD. */
+	for (i = 0; i + 1 < n; i++)
+		ctrl_tds[i].next = (unsigned int)&ctrl_tds[i + 1];
+	ctrl_tds[n - 1].next = (unsigned int)&ctrl_dummy;
+	ctrl_dummy.flags = TD_NOTACCESSED << TD_CC_SHIFT;
+	ctrl_dummy.cbp = 0;
+	ctrl_dummy.next = 0;
+	ctrl_dummy.be = 0;
+
+	ctrl_ed.flags = ED_FA(addr) | ED_EN(0) | ED_MPS(mps) | (low ? ED_S : 0);
+	ctrl_ed.tail = (unsigned int)&ctrl_dummy;
+	ctrl_ed.head = (unsigned int)&ctrl_tds[0];
+	ctrl_ed.next = 0;
+
+	wr(c, R_CTRL_HEAD_ED, (unsigned int)&ctrl_ed);
+	wr(c, R_COMMAND, CMD_CLF);
+
+	/* Poll until every TD has left "not accessed".  A NAKed TD stays
+	   untouched and is retried by the controller next frame. */
+	t0 = get_ticks_ms();
+	for (;;) {
+		int done = 1, err = 0;
+
+		for (i = 0; i < n; i++) {
+			unsigned int cc = (ctrl_tds[i].flags & TD_CC_MASK)
+					  >> TD_CC_SHIFT;
+			if (cc == TD_NOTACCESSED) {
+				done = 0;
+				continue;
+			}
+			if (cc != 0) {
+				err = 1;
+				serial_puts(SERIAL_COM1, "ohci: xfer err td ");
+				serial_putdec(SERIAL_COM1, i);
+				serial_puts(SERIAL_COM1, " cc ");
+				serial_putdec(SERIAL_COM1, cc);
+				serial_putc(SERIAL_COM1, '\n');
+			}
+		}
+		if (err) {
+			ctrl_ed.head = (unsigned int)&ctrl_dummy;
+			wr(c, R_CTRL_HEAD_ED, 0);
+			return -1;
+		}
+		if (done)
+			break;
+		if (get_ticks_ms() - t0 > 2000) {
+			serial_puts(SERIAL_COM1, "ohci: xfer timeout\n");
+			ctrl_ed.head = (unsigned int)&ctrl_dummy;
+			wr(c, R_CTRL_HEAD_ED, 0);
+			return -1;
+		}
+	}
+	ctrl_ed.head = (unsigned int)&ctrl_dummy;
+	wr(c, R_CTRL_HEAD_ED, 0);
+
+	/* Bytes actually received: the TD's CBP advances with the data
+	   (the controller clears it to 0 when the whole buffer arrived). */
+	if (len > 0 && dir_in && n_data == 1) {
+		unsigned int cbp = ctrl_tds[1].cbp;
+
+		if (cbp == 0)
+			return (int)len;
+		return (int)(cbp - (unsigned int)data);
+	}
+	return (int)len;
+}
+
+static int ohci_control_transfer(unsigned int ctrl, unsigned int addr,
+				 unsigned int mps, int low_speed,
+				 const unsigned char *setup,
+				 unsigned char *data, unsigned int len,
+				 int dir_in)
+{
+	int r;
+
+	if (ctrl >= n_ctrls || ctl_busy)
+		return -1;
+	ctl_busy = 1;
+	r = ohci_transfer(&ctrls[ctrl], addr, mps, low_speed, setup, data, len,
+			  dir_in);
+	ctl_busy = 0;
+	return r;
+}
+
+/* Arm one interrupt TD of one slot: (re)write it active.  Only call with
+   the TD retired.  The ED stays linked in the periodic chain. */
+static void ohci_int_arm(struct ohci_ctrl *c, unsigned int slot)
+{
+	c->int_td[slot].flags = (TD_NOTACCESSED << TD_CC_SHIFT) | TD_R |
+				TD_DP(TD_DP_IN) |
+				(c->int_toggle[slot] ? TD_T_DATA1
+						     : TD_T_DATA0);
+	c->int_td[slot].cbp = (unsigned int)c->int_buf[slot];
+	c->int_td[slot].next = (unsigned int)&c->int_dummy[slot];
+	c->int_td[slot].be = (unsigned int)c->int_buf[slot] +
+			     c->int_mps[slot] - 1;
+
+	c->int_ed[slot].head = (unsigned int)&c->int_td[slot] |
+			       (c->int_toggle[slot] ? ED_C : 0);
+	c->int_ed[slot].tail = (unsigned int)&c->int_dummy[slot];
+	/* int_ed[slot].next keeps the chain to the other slots. */
+
+	c->int_armed[slot] = 1;
+}
+
+static int ohci_int_in_start(unsigned int ctrl, unsigned int slot,
+			     unsigned int addr, unsigned int ep,
+			     unsigned int mps, int low_speed)
+{
+	struct ohci_ctrl *c;
+
+	if (ctrl >= n_ctrls || slot >= USB_HCD_INT_SLOTS)
+		return -1;
+	c = &ctrls[ctrl];
+
+	ohci_int_in_stop(slot);
+
+	c->int_mps[slot] = mps ? mps : 8;
+	c->int_ed[slot].flags = ED_FA(addr) | ED_EN(ep) |
+				ED_MPS(c->int_mps[slot]) |
+				(low_speed ? ED_S : 0);
+	c->int_ed[slot].tail = (unsigned int)&c->int_dummy[slot];
+	c->int_ed[slot].head = (unsigned int)&c->int_dummy[slot];
+	c->int_toggle[slot] = 0;   /* first report is DATA0 */
+	ohci_int_arm(c, slot);
+	return 0;
+}
+
+static int ohci_int_in_poll(unsigned int slot, unsigned char *buf,
+			    unsigned int len)
+{
+	struct ohci_ctrl *c = 0;
+	unsigned int i, cc, n;
+
+	if (slot >= USB_HCD_INT_SLOTS)
+		return 0;
+	for (i = 0; i < n_ctrls; i++) {
+		if (ctrls[i].int_armed[slot]) {
+			c = &ctrls[i];
+			break;
+		}
+	}
+	if (!c)
+		return 0;
+
+	cc = (c->int_td[slot].flags & TD_CC_MASK) >> TD_CC_SHIFT;
+	if (cc == TD_NOTACCESSED) {
+		if (c->int_ed[slot].head & ED_H) {
+			/* Halted by the controller without a CC update:
+			   clear it and stay armed. */
+			ohci_int_arm(c, slot);
+			return -1;
+		}
+		return 0;   /* still queued; the controller retries NAKs */
+	}
+	if (cc != 0) {
+		/* Report the error but stay armed (toggle preserved). */
+		ohci_int_arm(c, slot);
+		return -1;
+	}
+
+	n = c->int_td[slot].cbp
+		? (c->int_td[slot].cbp - (unsigned int)c->int_buf[slot])
+		: c->int_mps[slot];
+	if (n > len)
+		n = len;
+	for (i = 0; i < n; i++)
+		buf[i] = c->int_buf[slot][i];
+
+	c->int_toggle[slot] ^= 1u;
+	ohci_int_arm(c, slot);
+	return (int)n;
+}
+
+static void ohci_int_in_stop(unsigned int slot)
+{
+	unsigned int i;
+
+	if (slot >= USB_HCD_INT_SLOTS)
+		return;
+	for (i = 0; i < n_ctrls; i++) {
+		struct ohci_ctrl *c = &ctrls[i];
+
+		if (!c->int_armed[slot])
+			continue;
+		c->int_armed[slot] = 0;
+		c->int_ed[slot].head = (unsigned int)&c->int_dummy[slot];
+		c->int_ed[slot].tail = (unsigned int)&c->int_dummy[slot];
+	}
+}
+
+const struct usb_hcd_ops usb_ohci_ops = {
+	"OHCI",
+	ohci_init,
+	ohci_count,
+	ohci_info,
+	ohci_control_transfer,
+	ohci_port_count,
+	ohci_port_connected,
+	ohci_port_low_speed,
+	ohci_port_reset,
+	ohci_port_take_change,
+	ohci_int_in_start,
+	ohci_int_in_poll,
+	ohci_int_in_stop,
+};

+ 10 - 0
ohci.h

@@ -0,0 +1,10 @@
+/* OHCI (USB 1.1) host controller driver: implements the usb_hcd_ops vtable
+   declared in usb_hcd.h. */
+#ifndef OHCI_H
+#define OHCI_H
+
+#include "usb_hcd.h"
+
+extern const struct usb_hcd_ops usb_ohci_ops;
+
+#endif

+ 206 - 0
tools/qmp_cursor_test.py

@@ -0,0 +1,206 @@
+#!/usr/bin/env python3
+"""Headless USB HID cursor regression test (QEMU + QMP + screendump).
+
+Boots the OS with a USB mouse, injects motion through QMP and verifies the
+on-screen cursor triangle lands where the injected deltas say it should.
+
+Modes:
+  (default)   OHCI controller, mouse on it
+  --uhci      UHCI (piix3) controller
+  --uhci72    UHCI at PCI 00:01.2 (multifunction south-bridge layout)
+  --multi     three OHCI controllers, mouse on the third
+  --hotplug   boot without the mouse, plug it in, move, unplug, replug
+
+Requires: floppy.img/root.img built (make all), python3, QEMU.
+Exit code 0 = pass.
+"""
+import json
+import os
+import shutil
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+# 16x16 cursor bitmap rows (same table as mouse.c); bit 15 = column 0.
+CUR = [0x8000, 0xC000, 0xE000, 0xF000, 0xF800, 0xFC00, 0xFE00, 0xFF00,
+       0xFC00, 0xE000, 0x8000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000]
+
+
+def qmp_connect(sock):
+    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+    s.connect(sock)
+    qmp_recv(s)                  # greeting
+    qmp_cmd(s, "qmp_capabilities")
+    return s
+
+
+def qmp_recv(s):
+    buf = b""
+    while True:
+        chunk = s.recv(4096)
+        if not chunk:
+            raise RuntimeError("QMP connection closed")
+        buf += chunk
+        while b"\n" in buf:
+            line, buf = buf.split(b"\n", 1)
+            line = line.strip()
+            if line:
+                return json.loads(line)
+
+
+def qmp_cmd(s, execute, arguments=None):
+    req = {"execute": execute}
+    if arguments is not None:
+        req["arguments"] = arguments
+    s.sendall((json.dumps(req) + "\n").encode())
+    while True:
+        msg = qmp_recv(s)
+        if "return" in msg or "error" in msg:
+            if "error" in msg:
+                print("QMP error:", msg)
+            return msg
+
+
+def read_ppm(path):
+    data = open(path, "rb").read()
+    parts = data.split(b"\n", 3)
+    w, h = [int(x) for x in parts[1].split()]
+    return w, h, parts[3]
+
+
+def pixel(w, pix, x, y):
+    o = (y * w + x) * 3
+    return pix[o], pix[o + 1], pix[o + 2]
+
+
+def cursor_matches(w, pix, x0, y0):
+    for r in range(8):
+        for c in range(16):
+            want = (CUR[r] & (0x8000 >> c)) != 0
+            got = pixel(w, pix, x0 + c, y0 + r) == (255, 255, 255)
+            if want != got:
+                return False
+    return True
+
+
+def find_cursor(w, h, pix):
+    for y in range(h - 16):
+        for x in range(w - 16):
+            if cursor_matches(w, pix, x, y):
+                return (x, y)
+    return None
+
+
+def screendump(s, ppm):
+    if os.path.exists(ppm):
+        os.unlink(ppm)
+    qmp_cmd(s, "screendump", {"filename": ppm})
+    time.sleep(0.5)
+    return read_ppm(ppm)
+
+
+def move(s, dx, dy):
+    """Inject relative motion, split so no 8-bit HID field wraps."""
+    while dx or dy:
+        ex = max(-100, min(100, dx))
+        ey = max(-100, min(100, dy))
+        qmp_cmd(s, "input-send-event", {"events": [
+            {"type": "rel", "data": {"axis": "x", "value": ex}},
+            {"type": "rel", "data": {"axis": "y", "value": ey}}]})
+        dx -= ex
+        dy -= ey
+        time.sleep(0.3)
+
+
+def main():
+    mode = "ohci"
+    for m in ("uhci", "uhci72", "multi", "hotplug"):
+        if "--" + m in sys.argv:
+            mode = m
+
+    if not (os.path.exists(os.path.join(ROOT, "floppy.img")) and
+            os.path.exists(os.path.join(ROOT, "root.img"))):
+        print("floppy.img/root.img missing - run `make all` first")
+        return 1
+
+    workdir = tempfile.mkdtemp(prefix="nebos-cursor-")
+    sock = os.path.join(workdir, "qmp.sock")
+    ppm = os.path.join(workdir, "screen.ppm")
+
+    qemu = ["qemu-system-i386", "-M", "pc"]
+    if mode == "uhci":
+        qemu += ["-device", "piix3-usb-uhci", "-device", "usb-mouse"]
+    elif mode == "uhci72":
+        qemu += ["-device", "piix3-usb-uhci,addr=1.2", "-device", "usb-mouse"]
+    elif mode == "multi":
+        qemu += ["-device", "pci-ohci,id=o0", "-device", "pci-ohci,id=o1",
+                 "-device", "pci-ohci,id=o2", "-device", "usb-mouse,bus=o2.0"]
+    elif mode == "hotplug":
+        qemu += ["-device", "pci-ohci"]
+    else:
+        qemu += ["-device", "pci-ohci", "-device", "usb-mouse"]
+    qemu += ["-drive", "file=floppy.img,format=raw,if=floppy",
+             "-drive", "file=root.img,format=raw,if=floppy",
+             "-display", "none",
+             "-qmp", "unix:%s,server,nowait" % sock]
+
+    proc = subprocess.Popen(qemu, cwd=ROOT, stdout=subprocess.DEVNULL,
+                            stderr=subprocess.DEVNULL)
+    ok = False
+    try:
+        for _ in range(100):
+            if os.path.exists(sock):
+                break
+            time.sleep(0.1)
+        s = qmp_connect(sock)
+        time.sleep(4)                       # boot
+
+        if mode == "hotplug":
+            qmp_cmd(s, "device_add", {"driver": "usb-mouse", "id": "mouse"})
+            time.sleep(2)
+
+        w, h, pix = screendump(s, ppm)
+        start = find_cursor(w, h, pix)
+        move(s, 250, 150)
+        time.sleep(0.5)
+        w, h, pix = screendump(s, ppm)
+        end = find_cursor(w, h, pix)
+
+        if mode == "hotplug":
+            qmp_cmd(s, "device_del", {"id": "mouse"})
+            time.sleep(1)
+            qmp_cmd(s, "device_add", {"driver": "usb-mouse", "id": "mouse"})
+            time.sleep(2)
+            move(s, -100, -60)
+            time.sleep(0.5)
+            w, h, pix = screendump(s, ppm)
+            end2 = find_cursor(w, h, pix)
+            ok = (start == (100, 100) and end == (350, 250) and
+                  end2 == (250, 190))
+            print("mode=%s fb=%dx%d boot=%s plug=%s replug=%s -> %s"
+                  % (mode, w, h, start, end, end2,
+                     "ok" if ok else "MISMATCH"))
+        else:
+            ok = start == (100, 100) and end == (350, 250)
+            print("mode=%s fb=%dx%d cursor %s -> %s : %s"
+                  % (mode, w, h, start, end, "ok" if ok else "MISMATCH"))
+
+        qmp_cmd(s, "quit")
+        try:
+            proc.wait(timeout=10)
+        except subprocess.TimeoutExpired:
+            pass
+    finally:
+        if proc.poll() is None:
+            proc.kill()
+            proc.wait()
+        shutil.rmtree(workdir, ignore_errors=True)
+    return 0 if ok else 1
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 138 - 0
tools/qmp_keyboard_test.py

@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""Headless USB keyboard regression test (QEMU + QMP + screendump).
+
+Boots the OS, types a shell command on a USB keyboard through QMP and
+verifies the screen content changed (the command output).
+
+Modes:
+  (default)   OHCI + usb-mouse + usb-kbd; types "help"
+  --hotplug   boots without the keyboard, plugs it in via QMP, then types
+  --keys a,b,ret   type a custom key list (QEMU qcodes)
+
+Requires: floppy.img/root.img built (make all), python3, QEMU.
+Exit code 0 = pass.
+"""
+import json
+import os
+import shutil
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def qmp_recv(s):
+    buf = b""
+    while True:
+        chunk = s.recv(4096)
+        if not chunk:
+            raise RuntimeError("QMP connection closed")
+        buf += chunk
+        while b"\n" in buf:
+            line, buf = buf.split(b"\n", 1)
+            line = line.strip()
+            if line:
+                return json.loads(line)
+
+
+def qmp_cmd(s, execute, arguments=None):
+    req = {"execute": execute}
+    if arguments is not None:
+        req["arguments"] = arguments
+    s.sendall((json.dumps(req) + "\n").encode())
+    while True:
+        msg = qmp_recv(s)
+        if "return" in msg or "error" in msg:
+            if "error" in msg:
+                print("QMP error:", msg)
+            return msg
+
+
+def read_ppm(path):
+    data = open(path, "rb").read()
+    parts = data.split(b"\n", 3)
+    w, h = [int(x) for x in parts[1].split()]
+    return w, h, parts[3]
+
+
+def main():
+    hotplug = "--hotplug" in sys.argv
+    keys = ["h", "e", "l", "p", "ret"]
+    if "--keys" in sys.argv:
+        keys = sys.argv[sys.argv.index("--keys") + 1].split(",")
+
+    if not (os.path.exists(os.path.join(ROOT, "floppy.img")) and
+            os.path.exists(os.path.join(ROOT, "root.img"))):
+        print("floppy.img/root.img missing - run `make all` first")
+        return 1
+
+    workdir = tempfile.mkdtemp(prefix="nebos-kbd-")
+    sock = os.path.join(workdir, "qmp.sock")
+    ppm = os.path.join(workdir, "screen.ppm")
+
+    kbddev = [] if hotplug else ["-device", "usb-kbd"]
+    qemu = ["qemu-system-i386", "-M", "pc",
+            "-device", "pci-ohci", "-device", "usb-mouse"] + kbddev + [
+        "-drive", "file=floppy.img,format=raw,if=floppy",
+        "-drive", "file=root.img,format=raw,if=floppy",
+        "-display", "none",
+        "-qmp", "unix:%s,server,nowait" % sock]
+
+    proc = subprocess.Popen(qemu, cwd=ROOT, stdout=subprocess.DEVNULL,
+                            stderr=subprocess.DEVNULL)
+    ok = False
+    try:
+        for _ in range(100):
+            if os.path.exists(sock):
+                break
+            time.sleep(0.1)
+        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+        s.connect(sock)
+        qmp_recv(s)                  # greeting
+        qmp_cmd(s, "qmp_capabilities")
+        time.sleep(4)                # boot
+
+        if hotplug:
+            qmp_cmd(s, "device_add", {"driver": "usb-kbd", "id": "kbd"})
+            time.sleep(2)
+
+        if os.path.exists(ppm):
+            os.unlink(ppm)
+        qmp_cmd(s, "screendump", {"filename": ppm})
+        time.sleep(0.5)
+        w, h, before = read_ppm(ppm)
+
+        for k in keys:
+            qmp_cmd(s, "send-key", {"keys": [{"type": "qcode", "data": k}]})
+            time.sleep(0.25)
+        time.sleep(1.0)
+
+        if os.path.exists(ppm):
+            os.unlink(ppm)
+        qmp_cmd(s, "screendump", {"filename": ppm})
+        time.sleep(0.5)
+        w2, h2, after = read_ppm(ppm)
+
+        changed = sum(1 for a, b in zip(before, after) if a != b)
+        ok = changed > 3000          # the command output repaints the screen
+        print("keys=%s screen %dx%d changed bytes: %d -> %s"
+              % (",".join(keys), w, h, changed, "ok" if ok else "NO CHANGE"))
+
+        qmp_cmd(s, "quit")
+        try:
+            proc.wait(timeout=10)
+        except subprocess.TimeoutExpired:
+            pass
+    finally:
+        if proc.poll() is None:
+            proc.kill()
+            proc.wait()
+        shutil.rmtree(workdir, ignore_errors=True)
+    return 0 if ok else 1
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 260 - 61
uhci.c

@@ -1,11 +1,18 @@
 /* UHCI (USB 1.1) host controller driver.
 /* UHCI (USB 1.1) host controller driver.
    PCI discovery, register access, frame-list / queue-head / transfer-
    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. */
+   descriptor schedule, root-hub port control, polling control transfers and
+   one interrupt-IN endpoint (the mouse).  Polling based (no IRQ); the PIC
+   slave (and thus the UHCI IRQ) is masked, so we poll TD status.
+
+   Only the first controller instance is driven (the frame list lives at a
+   fixed low-memory address); among several PCI functions we pick the one
+   whose root port has a device attached. */
 
 
 #include "pci.h"
 #include "pci.h"
+#include "serial.h"
 #include "timer.h"
 #include "timer.h"
 #include "uhci.h"
 #include "uhci.h"
+#include "usb_hcd.h"
 
 
 /* Register offsets from the I/O base. */
 /* Register offsets from the I/O base. */
 #define USBCMD       0x00
 #define USBCMD       0x00
@@ -37,7 +44,9 @@
 #define TD_ACTIVE   0x00800000u
 #define TD_ACTIVE   0x00800000u
 #define TD_LS       0x04000000u
 #define TD_LS       0x04000000u
 #define TD_CERR_3   0x18000000u
 #define TD_CERR_3   0x18000000u
+#define TD_NAK      0x00080000u
 #define TD_ERR_MASK 0x007E0000u
 #define TD_ERR_MASK 0x007E0000u
+#define TD_ERR_NO_NAK (TD_ERR_MASK & ~TD_NAK)
 #define TD_ACTLEN   0x000007FFu
 #define TD_ACTLEN   0x000007FFu
 
 
 /* TD token PIDs (UHCI-encoded). */
 /* TD token PIDs (UHCI-encoded). */
@@ -45,7 +54,7 @@
 #define TD_PID_IN    0x69u
 #define TD_PID_IN    0x69u
 #define TD_PID_OUT   0xE1u
 #define TD_PID_OUT   0xE1u
 
 
-/* PCI: base class 0x0C (serial), subclass 0x03 (USB). */
+/* PCI: base class 0x0C (serial), subclass 0x03 (USB), prog.if 0x00 (UHCI). */
 #define PCI_USB_CLASS 0x0C03u
 #define PCI_USB_CLASS 0x0C03u
 
 
 struct uhci_td {
 struct uhci_td {
@@ -72,9 +81,23 @@ static struct uhci_qh qh;
 
 
 static unsigned char setup_buf[8];
 static unsigned char setup_buf[8];
 
 
+/* Interrupt-IN endpoints (slot 0 = mouse, slot 1 = keyboard): one TD and
+   one scheduled QH each, both serviced every frame. */
+struct uhci_int_ep {
+	struct uhci_td td;
+	struct uhci_qh qh;
+	unsigned char buf[8] __attribute__((aligned(16)));
+	unsigned int addr, ep, mps;
+	unsigned int toggle;
+	int low;
+	int armed;
+};
+static struct uhci_int_ep int_eps[USB_HCD_INT_SLOTS];
+
 static unsigned int io_base;
 static unsigned int io_base;
 static unsigned int pci_bus, pci_dev, pci_func;
 static unsigned int pci_bus, pci_dev, pci_func;
 static int found;
 static int found;
+static int ctl_busy;
 
 
 static unsigned short reg_readw(unsigned int reg)
 static unsigned short reg_readw(unsigned int reg)
 {
 {
@@ -107,18 +130,6 @@ static void td_set(struct uhci_td *td, unsigned int link, unsigned int status,
 	td->buffer = buffer;
 	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,
 static unsigned int td_token(unsigned int pid, unsigned int addr,
 			     unsigned int ep, unsigned int toggle,
 			     unsigned int ep, unsigned int toggle,
 			     unsigned int maxlen)
 			     unsigned int maxlen)
@@ -132,6 +143,8 @@ static unsigned int td_token(unsigned int pid, unsigned int addr,
 	       (explen << 21);
 	       (explen << 21);
 }
 }
 
 
+/* Bring the controller up: global + host reset, empty schedule (control QH
+   followed by the interrupt QH), run state. */
 static void reset_controller(void)
 static void reset_controller(void)
 {
 {
 	unsigned int *fl = (unsigned int *)UHCI_FRAME_LIST_ADDR;
 	unsigned int *fl = (unsigned int *)UHCI_FRAME_LIST_ADDR;
@@ -150,90 +163,157 @@ static void reset_controller(void)
 	for (i = 0; i < 1024; i++)
 	for (i = 0; i < 1024; i++)
 		fl[i] = (unsigned int)&qh | 0x2u;
 		fl[i] = (unsigned int)&qh | 0x2u;
 
 
-	qh.link = 0x1u;
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		int_eps[i].qh.element = 0x1u;
+		int_eps[i].qh.link = (i + 1 < USB_HCD_INT_SLOTS)
+			? ((unsigned int)&int_eps[i + 1].qh | 0x2u) : 0x1u;
+		int_eps[i].td.status = 0;
+		int_eps[i].armed = 0;
+	}
+	qh.link = (unsigned int)&int_eps[0].qh | 0x2u;
 	qh.element = 0x1u;
 	qh.element = 0x1u;
 
 
 	reg_writel(USBFLBASEADD, UHCI_FRAME_LIST_ADDR);
 	reg_writel(USBFLBASEADD, UHCI_FRAME_LIST_ADDR);
 	reg_writew(USBINTR, 0);
 	reg_writew(USBINTR, 0);
 	reg_writew(USBSTS, 0x3Fu);
 	reg_writew(USBSTS, 0x3Fu);
-	reg_writew(USBCMD, USBCMD_CF | USBCMD_MAXP);
+	reg_writew(USBCMD, USBCMD_RS | USBCMD_CF | USBCMD_MAXP);
 }
 }
 
 
-int uhci_init(void)
+static int uhci_init(void)
 {
 {
-	unsigned int bus, dev;
+	unsigned int bus, dev, func;
+	unsigned int first_io = 0, first_bus = 0, first_dev = 0, first_func = 0;
+	int have_first = 0;
 
 
-	found = 0;
-	io_base = 0;
+	if (found)
+		return 1;
 
 
 	for (bus = 0; bus < 256 && !found; bus++) {
 	for (bus = 0; bus < 256 && !found; bus++) {
 		for (dev = 0; dev < 32; dev++) {
 		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;
+			for (func = 0; func < 8; func++) {
+				unsigned int id = pci_cfg_read32(bus, dev, func, 0x00);
+				unsigned int class_rev, cmd, bar, io, st;
+
+				if (id == 0xFFFFFFFFu || id == 0)
+					continue;
+				class_rev = pci_cfg_read32(bus, dev, func, 0x08);
+				if ((class_rev >> 16) != PCI_USB_CLASS)
+					continue;
+				if (((class_rev >> 8) & 0xFFu) != 0x00u)
+					continue;   /* not UHCI */
+
+				/* Enable I/O space + bus master. */
+				cmd = pci_cfg_read32(bus, dev, func, 0x04);
+				pci_cfg_write32(bus, dev, func, 0x04, cmd | 0x0005u);
+
+				/* Disable legacy SMI emulation. */
+				pci_cfg_write16(bus, dev, func, 0xC0, 0);
+
+				/* The I/O BAR is BAR4 on UHCI controllers. */
+				bar = pci_cfg_read32(bus, dev, func, 0x20);
+				if (!(bar & 0x1u))
+					continue;
+				io = bar & 0xFFFFFFFCu;
+				if (!io)
+					continue;   /* BAR not assigned */
+
+				/* Prefer a controller with something plugged in. */
+				st = (unsigned int)port_inw((unsigned short)(io + USBPORTSC1)) |
+				     (unsigned int)port_inw((unsigned short)(io + USBPORTSC2));
+				if (st & USBPORTSC_CCS) {
+					io_base = io;
+					pci_bus = bus;
+					pci_dev = dev;
+					pci_func = func;
+					found = 1;
+					break;
+				}
+				if (!have_first) {
+					have_first = 1;
+					first_io = io;
+					first_bus = bus;
+					first_dev = dev;
+					first_func = func;
+				}
+			}
+			if (found)
+				break;
 		}
 		}
 	}
 	}
 
 
+	if (!found && have_first) {
+		io_base = first_io;
+		pci_bus = first_bus;
+		pci_dev = first_dev;
+		pci_func = first_func;
+		found = 1;
+	}
 	if (!found)
 	if (!found)
-		return -1;
+		return 0;
 
 
 	reset_controller();
 	reset_controller();
-	return 0;
+
+	serial_puts(SERIAL_COM1, "uhci: controller at ");
+	serial_putdec(SERIAL_COM1, pci_bus);
+	serial_puts(SERIAL_COM1, ":");
+	serial_putdec(SERIAL_COM1, pci_dev);
+	serial_puts(SERIAL_COM1, ".");
+	serial_putdec(SERIAL_COM1, pci_func);
+	serial_puts(SERIAL_COM1, ", 2 ports\n");
+	return 1;
 }
 }
 
 
-void uhci_pci_info(unsigned int *bus, unsigned int *dev, unsigned int *func,
-		   unsigned int *base)
+static unsigned int uhci_count(void)
 {
 {
+	return found ? 1u : 0u;
+}
+
+static void uhci_info(unsigned int ctrl, unsigned int *bus, unsigned int *dev,
+		      unsigned int *func, unsigned int *base, int *mmio)
+{
+	(void)ctrl;
 	*bus = pci_bus;
 	*bus = pci_bus;
 	*dev = pci_dev;
 	*dev = pci_dev;
 	*func = pci_func;
 	*func = pci_func;
 	*base = io_base;
 	*base = io_base;
+	*mmio = 0;
 }
 }
 
 
-unsigned int uhci_root_port_count(void)
+static unsigned int uhci_port_count(unsigned int ctrl)
 {
 {
+	(void)ctrl;
 	return 2;
 	return 2;
 }
 }
 
 
-int uhci_root_port_connected(unsigned int port)
+static int uhci_port_connected(unsigned int ctrl, unsigned int port)
 {
 {
 	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
 	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
+	(void)ctrl;
 	return (reg_readw(reg) & USBPORTSC_CCS) ? 1 : 0;
 	return (reg_readw(reg) & USBPORTSC_CCS) ? 1 : 0;
 }
 }
 
 
-int uhci_root_port_low_speed(unsigned int port)
+static int uhci_port_low_speed(unsigned int ctrl, unsigned int port)
 {
 {
 	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
 	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
+	(void)ctrl;
 	return (reg_readw(reg) & USBPORTSC_LSDA) ? 1 : 0;
 	return (reg_readw(reg) & USBPORTSC_LSDA) ? 1 : 0;
 }
 }
 
 
-int uhci_root_port_reset(unsigned int port)
+static int uhci_port_take_change(unsigned int ctrl, unsigned int port)
+{
+	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
+	(void)ctrl;
+	if (!(reg_readw(reg) & USBPORTSC_CSC))
+		return 0;
+	reg_writew(reg, USBPORTSC_CSC);   /* write-1-to-clear */
+	return 1;
+}
+
+static int uhci_port_reset(unsigned int ctrl, unsigned int port)
 {
 {
 	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
 	unsigned int reg = (port == 0) ? USBPORTSC1 : USBPORTSC2;
 	unsigned int st;
 	unsigned int st;
+	(void)ctrl;
 
 
 	/* Assert reset (this also resets the attached device). */
 	/* Assert reset (this also resets the attached device). */
 	st = reg_readw(reg);
 	st = reg_readw(reg);
@@ -258,9 +338,9 @@ int uhci_root_port_reset(unsigned int port)
 	return 0;
 	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)
+static int 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 i, ntd = 0, n_data = 0;
 	unsigned int base = TD_ACTIVE | TD_CERR_3 | (low_speed ? TD_LS : 0);
 	unsigned int base = TD_ACTIVE | TD_CERR_3 | (low_speed ? TD_LS : 0);
@@ -321,19 +401,19 @@ int uhci_control_transfer(unsigned int dev_addr, unsigned int mps, int low_speed
 				continue;
 				continue;
 			}
 			}
 			if (st & TD_ERR_MASK) {
 			if (st & TD_ERR_MASK) {
-				uhci_halt();
+				qh.element = 0x1u;
 				return -1;
 				return -1;
 			}
 			}
 		}
 		}
 		if (done)
 		if (done)
 			break;
 			break;
 		if (get_ticks_ms() - t0 > 2000) {
 		if (get_ticks_ms() - t0 > 2000) {
-			uhci_halt();
+			qh.element = 0x1u;
 			return -1;
 			return -1;
 		}
 		}
 	}
 	}
 
 
-	uhci_halt();
+	qh.element = 0x1u;
 
 
 	{
 	{
 		unsigned int total = 0;
 		unsigned int total = 0;
@@ -344,3 +424,122 @@ int uhci_control_transfer(unsigned int dev_addr, unsigned int mps, int low_speed
 		return (int)total;
 		return (int)total;
 	}
 	}
 }
 }
+
+static int uhci_control_transfer(unsigned int ctrl, unsigned int addr,
+				 unsigned int mps, int low_speed,
+				 const unsigned char *setup,
+				 unsigned char *data, unsigned int len,
+				 int dir_in)
+{
+	int r;
+
+	(void)ctrl;
+	if (ctl_busy)
+		return -1;
+	ctl_busy = 1;
+	r = control_transfer(addr, mps, low_speed, setup, data, len, dir_in);
+	ctl_busy = 0;
+	return r;
+}
+
+/* Queue the armed interrupt TD of one slot.  Only call when it is retired. */
+static void int_rearm(struct uhci_int_ep *ep)
+{
+	ep->td.link = 0x1u;
+	ep->td.buffer = (unsigned int)ep->buf;
+	ep->td.token = td_token(TD_PID_IN, ep->addr, ep->ep, ep->toggle, ep->mps);
+	ep->td.status = TD_ACTIVE | TD_CERR_3 | (ep->low ? TD_LS : 0);
+	ep->qh.element = (unsigned int)&ep->td;
+}
+
+static int uhci_int_in_start(unsigned int ctrl, unsigned int slot,
+			     unsigned int addr, unsigned int ep_num,
+			     unsigned int mps, int low_speed)
+{
+	struct uhci_int_ep *ep;
+
+	(void)ctrl;
+	if (!found || slot >= USB_HCD_INT_SLOTS)
+		return -1;
+	ep = &int_eps[slot];
+
+	/* Drop any old TD from the schedule, then write the new one. */
+	ep->armed = 0;
+	ep->qh.element = 0x1u;
+	delay_ms(2);
+
+	ep->addr = addr;
+	ep->ep = ep_num;
+	ep->mps = mps ? mps : 8;
+	ep->low = low_speed;
+	ep->toggle = 0;   /* first report is DATA0 */
+	int_rearm(ep);
+	ep->armed = 1;
+	return 0;
+}
+
+static int uhci_int_in_poll(unsigned int slot, unsigned char *buf,
+			    unsigned int len)
+{
+	struct uhci_int_ep *ep;
+	unsigned int st, n, i;
+
+	if (!found || slot >= USB_HCD_INT_SLOTS)
+		return 0;
+	ep = &int_eps[slot];
+	if (!ep->armed)
+		return 0;
+
+	st = ep->td.status;
+	if (st & TD_ACTIVE)
+		return 0;
+
+	if (st & TD_ERR_NO_NAK) {
+		/* Report the error but stay armed (toggle preserved). */
+		int_rearm(ep);
+		return -1;
+	}
+	if (st & TD_NAK) {
+		/* Some controllers retire a NAKed TD; just retry. */
+		int_rearm(ep);
+		return 0;
+	}
+
+	n = ((st & TD_ACTLEN) + 1) & TD_ACTLEN;
+	if (n > len)
+		n = len;
+	for (i = 0; i < n; i++)
+		buf[i] = ep->buf[i];
+
+	ep->toggle ^= 1u;
+	int_rearm(ep);
+	return (int)n;
+}
+
+static void uhci_int_in_stop(unsigned int slot)
+{
+	struct uhci_int_ep *ep;
+
+	if (slot >= USB_HCD_INT_SLOTS)
+		return;
+	ep = &int_eps[slot];
+	ep->armed = 0;
+	if (found)
+		ep->qh.element = 0x1u;
+}
+
+const struct usb_hcd_ops usb_uhci_ops = {
+	"UHCI",
+	uhci_init,
+	uhci_count,
+	uhci_info,
+	uhci_control_transfer,
+	uhci_port_count,
+	uhci_port_connected,
+	uhci_port_low_speed,
+	uhci_port_reset,
+	uhci_port_take_change,
+	uhci_int_in_start,
+	uhci_int_in_poll,
+	uhci_int_in_stop,
+};

+ 4 - 18
uhci.h

@@ -1,24 +1,10 @@
-/* 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). */
+/* UHCI (USB 1.1) host controller driver: implements the usb_hcd_ops vtable
+   declared in usb_hcd.h. */
 #ifndef UHCI_H
 #ifndef UHCI_H
 #define UHCI_H
 #define UHCI_H
 
 
-int uhci_init(void);   /* find + reset/configure the controller; 0 on success */
+#include "usb_hcd.h"
 
 
-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);
+extern const struct usb_hcd_ops usb_uhci_ops;
 
 
 #endif
 #endif

+ 453 - 122
usb.c

@@ -1,10 +1,11 @@
-/* USB core: device enumeration, descriptor parsing, and hub recursion.
-   Drives the UHCI controller to build the device tree for `lsusb`. */
+/* USB core: device enumeration, descriptor parsing, hub recursion, bus scans
+   and the hotplug watcher.  Controller-specific work goes through the
+   usb_hcd_ops vtable (uhci.c / ohci.c). */
 
 
 #include "io.h"
 #include "io.h"
 #include "timer.h"
 #include "timer.h"
-#include "uhci.h"
 #include "usb.h"
 #include "usb.h"
+#include "usb_hcd.h"
 
 
 /* Standard request types. */
 /* Standard request types. */
 #define RT_DEV2HOST_STD 0x80u
 #define RT_DEV2HOST_STD 0x80u
@@ -21,8 +22,11 @@
 #define REQ_GET_DESCRIPTOR 0x06u
 #define REQ_GET_DESCRIPTOR 0x06u
 
 
 /* Descriptor types. */
 /* Descriptor types. */
-#define DESC_DEVICE 0x01u
-#define DESC_HUB    0x29u
+#define DESC_DEVICE    0x01u
+#define DESC_CONFIG    0x02u
+#define DESC_INTERFACE 0x04u
+#define DESC_ENDPOINT  0x05u
+#define DESC_HUB       0x29u
 
 
 /* Hub feature selectors. */
 /* Hub feature selectors. */
 #define FEAT_PORT_RESET        4u
 #define FEAT_PORT_RESET        4u
@@ -33,12 +37,67 @@
 #define PSTAT_CONNECT   0x0001u
 #define PSTAT_CONNECT   0x0001u
 #define PSTAT_LOW_SPEED 0x0200u
 #define PSTAT_LOW_SPEED 0x0200u
 
 
-static unsigned int devnum;
+/* How much of a configuration descriptor we read/parse. */
+#define USB_CONFIG_MAX 128
+
+/* Hotplug watcher period. */
+#define HOTPLUG_MS 250
+
+/* Bring-up diagnostics to COM1 (also mirrored by the network console on
+   boards without serial).  Set to 0 to silence. */
+#define USB_DEBUG 0
+
+#if USB_DEBUG
+#include "serial.h"
+static void dbg(const char *s)
+{
+	serial_puts(SERIAL_COM1, s);
+}
+static void dbg_dec(const char *s, unsigned int n)
+{
+	serial_puts(SERIAL_COM1, s);
+	serial_putdec(SERIAL_COM1, n);
+	serial_putc(SERIAL_COM1, '\n');
+}
+static void dbg_port(unsigned int ctrl, unsigned int port, unsigned int conn,
+		     unsigned int low)
+{
+	serial_puts(SERIAL_COM1, "usb: ctrl ");
+	serial_putdec(SERIAL_COM1, ctrl);
+	serial_puts(SERIAL_COM1, " port ");
+	serial_putdec(SERIAL_COM1, port);
+	serial_puts(SERIAL_COM1, " connected ");
+	serial_putdec(SERIAL_COM1, conn);
+	serial_puts(SERIAL_COM1, " ls ");
+	serial_putdec(SERIAL_COM1, low);
+	serial_putc(SERIAL_COM1, '\n');
+}
+#else
+static void dbg(const char *s) { (void)s; }
+static void dbg_dec(const char *s, unsigned int n) { (void)s; (void)n; }
+static void dbg_port(unsigned int ctrl, unsigned int port, unsigned int conn,
+		     unsigned int low)
+{
+	(void)ctrl;
+	(void)port;
+	(void)conn;
+	(void)low;
+}
+#endif
+
+static const struct usb_hcd_ops *hcd;
+static unsigned int generation;
+static unsigned int next_addr[USB_HCD_MAX_CTRL];
+static usb_probe_fn current_probe;
+static int print_devices;
+static int scan_busy;
 
 
 static unsigned char dev_desc[18];
 static unsigned char dev_desc[18];
 static unsigned char desc8[8];
 static unsigned char desc8[8];
 static unsigned char hub_desc[16];
 static unsigned char hub_desc[16];
 static unsigned char port_st[4];
 static unsigned char port_st[4];
+static unsigned char conf_hdr[9];
+static unsigned char conf_buf[USB_CONFIG_MAX];
 
 
 static void put_uint(unsigned int n)
 static void put_uint(unsigned int n)
 {
 {
@@ -72,36 +131,11 @@ static void msleep(unsigned int 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)
+static void indent(unsigned int depth)
 {
 {
-	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);
+	unsigned int i;
+	for (i = 0; i < depth; i++)
+		io_putstr("  ");
 }
 }
 
 
 static const char *class_name(unsigned int cls)
 static const char *class_name(unsigned int cls)
@@ -129,34 +163,184 @@ static const char *class_name(unsigned int cls)
 	}
 	}
 }
 }
 
 
-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. */
 /* wPortStatus (little-endian) from the GET_PORT_STATUS buffer. */
 static unsigned int port_status_word(void)
 static unsigned int port_status_word(void)
 {
 {
 	return (unsigned int)port_st[0] | ((unsigned int)port_st[1] << 8);
 	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,
+int usb_control_in(unsigned int ctrl, unsigned int addr, unsigned int mps,
+		   int low_speed, unsigned char rt, unsigned char req,
+		   unsigned short value, unsigned short index,
+		   unsigned char *buf, unsigned int len)
+{
+	unsigned char setup[8];
+
+	if (!hcd)
+		return -1;
+	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 hcd->control_transfer(ctrl, addr, mps, low_speed, setup, buf, len, 1);
+}
+
+int usb_control_out(unsigned int ctrl, unsigned int addr, unsigned int mps,
+		    int low_speed, unsigned char rt, unsigned char req,
+		    unsigned short value, unsigned short index)
+{
+	unsigned char setup[8];
+
+	if (!hcd)
+		return -1;
+	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 hcd->control_transfer(ctrl, addr, mps, low_speed, setup, 0, 0, 0);
+}
+
+/* Read the configuration descriptor and hand every interface with an
+   interrupt-IN endpoint to the active probe. */
+static void probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
+			 int low, unsigned int port, unsigned int vendor,
+			 unsigned int product)
+{
+	struct usb_iface_info info;
+	unsigned int total, i;
+	int have_iface = 0;
+
+	if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_STD,
+			   REQ_GET_DESCRIPTOR,
+			   (unsigned short)(DESC_CONFIG << 8), 0,
+			   conf_hdr, 9) < 0) {
+		dbg("usb:   config descriptor header failed\n");
+		return;
+	}
+	total = (unsigned int)conf_hdr[2] | ((unsigned int)conf_hdr[3] << 8);
+	if (total < 9)
+		return;
+	if (total > USB_CONFIG_MAX)
+		total = USB_CONFIG_MAX;
+	if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_STD,
+			   REQ_GET_DESCRIPTOR,
+			   (unsigned short)(DESC_CONFIG << 8), 0,
+			   conf_buf, total) < 0) {
+		dbg("usb:   config descriptor read failed\n");
+		return;
+	}
+	dbg_dec("usb:   config descriptor len ", total);
+
+	info.ctrl = ctrl;
+	info.addr = addr;
+	info.mps = mps;
+	info.low_speed = low;
+	info.port = port;
+	info.vendor = vendor;
+	info.product = product;
+	info.config_value = conf_buf[5];
+	info.cls = 0;
+	info.subcls = 0;
+	info.proto = 0;
+	info.iface_num = 0;
+	info.ep_addr = 0;
+	info.ep_mps = 0;
+	info.ep_interval = 0;
+
+	i = 0;
+	while (i + 2 <= total) {
+		unsigned int blen = conf_buf[i];
+		unsigned int btype = conf_buf[i + 1];
+
+		if (blen < 2 || i + blen > total)
+			break;
+
+		if (btype == DESC_INTERFACE && blen >= 9) {
+			if (have_iface && info.ep_addr) {
+				dbg("usb:   interface has interrupt-IN ep\n");
+				if (current_probe)
+					current_probe(&info);
+			}
+			info.cls = conf_buf[i + 5];
+			info.subcls = conf_buf[i + 6];
+			info.proto = conf_buf[i + 7];
+			info.iface_num = conf_buf[i + 2];
+			if (print_devices) {
+				io_putstr("    Interface ");
+				put_uint(info.iface_num);
+				io_putstr(": ");
+				put_hex(info.cls, 2);
+				io_putchar('/');
+				put_hex(info.subcls, 2);
+				io_putchar('/');
+				put_hex(info.proto, 2);
+				io_putchar('\n');
+			} else {
+				dbg_dec("usb:   iface class ", info.cls);
+				dbg_dec("usb:   iface subclass ", info.subcls);
+				dbg_dec("usb:   iface protocol ", info.proto);
+			}
+			info.ep_addr = 0;
+			info.ep_mps = 0;
+			info.ep_interval = 0;
+			have_iface = 1;
+		} else if (btype == DESC_ENDPOINT && blen >= 7 && have_iface) {
+			unsigned int epa = conf_buf[i + 2];
+			unsigned int attr = conf_buf[i + 3] & 3u;
+			unsigned int mps = ((unsigned int)conf_buf[i + 4] |
+					    ((unsigned int)conf_buf[i + 5] << 8)) & 0x7FFu;
+			if (print_devices) {
+				io_putstr("      Endpoint 0x");
+				put_hex(epa, 2);
+				io_putstr(attr == 3u ? " interrupt" : " other");
+				io_putstr(", mps ");
+				put_uint(mps);
+				io_putchar('\n');
+			}
+			if (!info.ep_addr && (epa & 0x80u) && attr == 3u) {
+				info.ep_addr = epa;
+				info.ep_mps = mps;
+				info.ep_interval = conf_buf[i + 6];
+				dbg_dec("usb:   interrupt-IN endpoint ", epa & 0x0Fu);
+			}
+		}
+		i += blen;
+	}
+	if (have_iface && info.ep_addr && current_probe)
+		current_probe(&info);
+}
+
+static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
+			  int low, unsigned int port, unsigned int depth);
+static void enumerate_device(unsigned int ctrl, unsigned int addr,
+			     unsigned int mps, int low, unsigned int port,
 			     unsigned int depth);
 			     unsigned int depth);
-static void enumerate_new_device(int low, unsigned int depth);
+static void enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
+				 unsigned int depth);
 
 
-static void enumerate_device(unsigned int addr, unsigned int mps, int low,
+static void enumerate_device(unsigned int ctrl, unsigned int addr,
+			     unsigned int mps, int low, unsigned int port,
 			     unsigned int depth)
 			     unsigned int depth)
 {
 {
 	unsigned int vendor, product, cls, subcls, proto;
 	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");
+	if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_STD,
+			   REQ_GET_DESCRIPTOR,
+			   (unsigned short)(DESC_DEVICE << 8), 0,
+			   dev_desc, 18) < 0) {
+		dbg("usb:   device descriptor read failed\n");
+		if (print_devices) {
+			indent(depth);
+			io_putstr("(device descriptor read failed)\n");
+		}
 		return;
 		return;
 	}
 	}
 
 
@@ -166,35 +350,43 @@ static void enumerate_device(unsigned int addr, unsigned int mps, int low,
 	subcls  = dev_desc[5];
 	subcls  = dev_desc[5];
 	proto   = dev_desc[6];
 	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 (print_devices) {
+		indent(depth);
+		io_putstr("Bus ");
+		put_uint(ctrl + 1);
+		io_putstr(" 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 ((current_probe || print_devices) && cls != 0x09)
+		probe_config(ctrl, addr, mps, low, port, vendor, product);
 
 
 	if (cls == 0x09)
 	if (cls == 0x09)
-		enumerate_hub(addr, mps, low, depth + 1);
+		enumerate_hub(ctrl, addr, mps, low, port, depth + 1);
 }
 }
 
 
-static void enumerate_hub(unsigned int addr, unsigned int mps, int low,
-			  unsigned int depth)
+static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
+			  int low, unsigned int port, unsigned int depth)
 {
 {
 	unsigned int nports, p;
 	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)
+	if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_CLS,
+			   REQ_GET_DESCRIPTOR,
+			   (unsigned short)(DESC_HUB << 8), 0, hub_desc,
+			   sizeof(hub_desc)) < 0)
 		return;
 		return;
 
 
 	nports = hub_desc[2];
 	nports = hub_desc[2];
@@ -204,51 +396,64 @@ static void enumerate_hub(unsigned int addr, unsigned int mps, int low,
 	for (p = 1; p <= nports; p++) {
 	for (p = 1; p <= nports; p++) {
 		int low2;
 		int low2;
 
 
-		if (ctrl_in(addr, mps, low, RT_DEV2HOST_OTH, REQ_GET_STATUS,
-			    0, (unsigned short)p, port_st, 4) < 0)
+		if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_OTH,
+				   REQ_GET_STATUS, 0, (unsigned short)p,
+				   port_st, 4) < 0)
 			continue;
 			continue;
 		if (!(port_status_word() & PSTAT_CONNECT))
 		if (!(port_status_word() & PSTAT_CONNECT))
 			continue;
 			continue;
 
 
 		/* Power and reset the downstream port. */
 		/* 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)
+		usb_control_out(ctrl, addr, mps, low, RT_HOST2DEV_OTH,
+				REQ_SET_FEATURE, FEAT_PORT_POWER,
+				(unsigned short)p);
+		if (usb_control_out(ctrl, addr, mps, low, RT_HOST2DEV_OTH,
+				    REQ_SET_FEATURE, FEAT_PORT_RESET,
+				    (unsigned short)p) < 0)
 			continue;
 			continue;
 		msleep(30);
 		msleep(30);
 
 
-		ctrl_out(addr, mps, low, RT_HOST2DEV_OTH, REQ_CLEAR_FEATURE,
-			 FEAT_C_PORT_CONNECTION, (unsigned short)p);
+		usb_control_out(ctrl, 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. */
 		/* Re-read status to learn the child's speed. */
 		low2 = 0;
 		low2 = 0;
-		if (ctrl_in(addr, mps, low, RT_DEV2HOST_OTH, REQ_GET_STATUS,
-			    0, (unsigned short)p, port_st, 4) >= 0) {
+		if (usb_control_in(ctrl, addr, mps, low, RT_DEV2HOST_OTH,
+				   REQ_GET_STATUS, 0, (unsigned short)p,
+				   port_st, 4) >= 0) {
 			if (port_status_word() & PSTAT_LOW_SPEED)
 			if (port_status_word() & PSTAT_LOW_SPEED)
 				low2 = 1;
 				low2 = 1;
 		}
 		}
 
 
-		enumerate_new_device(low2, depth);
+		enumerate_new_device(ctrl, port, low2, depth);
 	}
 	}
 }
 }
 
 
-static void enumerate_new_device(int low, unsigned int depth)
+static void enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
+				 unsigned int depth)
 {
 {
 	unsigned int mps;
 	unsigned int mps;
+	unsigned int addr = next_addr[ctrl];
 
 
-	devnum++;
-	if (devnum > 127) {
-		indent(depth);
-		io_putstr("(too many devices)\n");
+	if (addr > 127) {
+		if (print_devices) {
+			indent(depth);
+			io_putstr("(too many devices)\n");
+		}
 		return;
 		return;
 	}
 	}
 
 
 	/* First 8 bytes at address 0 (learn max packet size). */
 	/* 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");
+	if (usb_control_in(ctrl, 0, 8, low, RT_DEV2HOST_STD,
+			   REQ_GET_DESCRIPTOR,
+			   (unsigned short)(DESC_DEVICE << 8), 0,
+			   desc8, 8) < 0) {
+		dbg("usb:   no response at address 0\n");
+		if (print_devices) {
+			indent(depth);
+			io_putstr("(no response at address 0)\n");
+		}
 		return;
 		return;
 	}
 	}
 
 
@@ -257,45 +462,171 @@ static void enumerate_new_device(int low, unsigned int depth)
 		mps = 8;
 		mps = 8;
 
 
 	/* Assign an address. */
 	/* 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");
+	if (usb_control_out(ctrl, 0, 8, low, RT_HOST2DEV_STD,
+			    REQ_SET_ADDRESS, (unsigned short)addr, 0) < 0) {
+		dbg("usb:   SET_ADDRESS failed\n");
+		if (print_devices) {
+			indent(depth);
+			io_putstr("(SET_ADDRESS failed)\n");
+		}
 		return;
 		return;
 	}
 	}
+	dbg_dec("usb:   enumerated device, addr ", addr);
 	msleep(5);
 	msleep(5);
 
 
-	enumerate_device(devnum, mps, low, depth);
+	next_addr[ctrl] = addr + 1;
+	enumerate_device(ctrl, addr, mps, low, port, depth);
 }
 }
 
 
-void usb_enumerate_and_print(void)
+int usb_hcd_init(void)
+{
+	if (hcd)
+		return 0;
+	if (usb_uhci_ops.init() > 0) {
+		hcd = &usb_uhci_ops;
+		return 0;
+	}
+	if (usb_ohci_ops.init() > 0) {
+		hcd = &usb_ohci_ops;
+		return 0;
+	}
+	return -1;
+}
+
+const char *usb_hcd_name(void)
+{
+	return hcd ? hcd->name : "none";
+}
+
+unsigned int usb_generation(void)
 {
 {
-	unsigned int bus, dev, func, base;
-	unsigned int p;
+	return generation;
+}
 
 
-	devnum = 0;
+int usb_port_connected(unsigned int ctrl, unsigned int port)
+{
+	if (!hcd)
+		return 0;
+	return hcd->port_connected(ctrl, port);
+}
 
 
-	if (uhci_init() != 0) {
-		io_putstr("lsusb: no UHCI host controller found\n");
-		return;
+int usb_int_in_start(unsigned int ctrl, unsigned int slot, unsigned int addr,
+		     unsigned int ep, unsigned int mps, int low_speed)
+{
+	if (!hcd || slot >= USB_HCD_INT_SLOTS)
+		return -1;
+	return hcd->int_in_start(ctrl, slot, addr, ep, mps, low_speed);
+}
+
+int usb_int_in_poll(unsigned int slot, unsigned char *buf, unsigned int len)
+{
+	if (!hcd || slot >= USB_HCD_INT_SLOTS)
+		return 0;
+	return hcd->int_in_poll(slot, buf, len);
+}
+
+void usb_int_in_stop(unsigned int slot)
+{
+	if (hcd && slot < USB_HCD_INT_SLOTS)
+		hcd->int_in_stop(slot);
+}
+
+int usb_scan(usb_probe_fn probe)
+{
+	unsigned int c, p;
+
+	if (scan_busy)
+		return -2;
+	if (usb_hcd_init() != 0)
+		return -1;
+
+	scan_busy = 1;
+	generation++;
+	current_probe = probe;
+	print_devices = (probe == 0);
+
+	for (c = 0; c < hcd->count() && c < USB_HCD_MAX_CTRL; c++) {
+		next_addr[c] = 1;
+
+		if (print_devices) {
+			unsigned int bus, dev, func, base;
+			int mmio;
+
+			hcd->info(c, &bus, &dev, &func, &base, &mmio);
+			io_putstr(hcd->name);
+			io_putstr(" Host Controller (PCI ");
+			put_hex(bus, 2);
+			io_putchar(':');
+			put_hex(dev, 2);
+			io_putchar('.');
+			put_hex(func, 1);
+			io_putstr(mmio ? ", MMIO 0x" : ", I/O 0x");
+			put_hex(base, mmio ? 8 : 4);
+			io_putstr(")\n");
+		}
+
+		for (p = 0; p < hcd->port_count(c); p++) {
+			unsigned int conn = (unsigned int)hcd->port_connected(c, p);
+
+			dbg_port(c, p, conn,
+				 (unsigned int)hcd->port_low_speed(c, p));
+			if (!conn)
+				continue;
+			hcd->port_take_change(c, p);   /* clear stale CSC */
+			if (hcd->port_reset(c, p) != 0) {
+				dbg("usb:   port reset failed\n");
+				continue;
+			}
+			dbg("usb:   port reset ok\n");
+			enumerate_new_device(c, p, hcd->port_low_speed(c, p), 1);
+		}
 	}
 	}
 
 
-	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);
+	current_probe = 0;
+	print_devices = 0;
+	scan_busy = 0;
+	return 0;
+}
+
+int usb_hotplug_poll(usb_probe_fn probe)
+{
+	static unsigned int last;
+	unsigned int now, c, p;
+	int n = 0;
+
+	if (!hcd || scan_busy)
+		return 0;
+
+	now = get_ticks_ms();
+	if (now - last < HOTPLUG_MS)
+		return 0;
+	last = now;
+
+	scan_busy = 1;
+	current_probe = probe;
+	for (c = 0; c < hcd->count() && c < USB_HCD_MAX_CTRL; c++) {
+		for (p = 0; p < hcd->port_count(c); p++) {
+			if (!hcd->port_take_change(c, p))
+				continue;
+			if (!hcd->port_connected(c, p))
+				continue;
+			if (hcd->port_reset(c, p) != 0)
+				continue;
+			enumerate_new_device(c, p, hcd->port_low_speed(c, p), 1);
+			n++;
+		}
 	}
 	}
+	current_probe = 0;
+	scan_busy = 0;
+	return n;
+}
+
+void usb_enumerate_and_print(void)
+{
+	int r = usb_scan(0);
+
+	if (r == -1)
+		io_putstr("lsusb: no USB host controller found\n");
+	else if (r == -2)
+		io_putstr("lsusb: a USB scan is already running\n");
 }
 }

+ 44 - 1
usb.h

@@ -1,7 +1,50 @@
-/* USB core: device enumeration, descriptor parsing, and hub recursion. */
+/* USB core: device enumeration, descriptor parsing, hub recursion, bus
+   scans and the hotplug watcher.  Controller-specific work (transfers, root
+   ports) goes through the usb_hcd_ops vtable (uhci.c / ohci.c). */
 #ifndef USB_H
 #ifndef USB_H
 #define USB_H
 #define USB_H
 
 
+#include "usb_hcd.h"
+
+/* `lsusb` command: full scan, print the tree. */
 void usb_enumerate_and_print(void);
 void usb_enumerate_and_print(void);
 
 
+/* Find + bring up a host controller; 0 when one is available. */
+int usb_hcd_init(void);
+const char *usb_hcd_name(void);
+
+/* Full bus scan: resets every connected root port, re-enumerates and calls
+   the probe for each interface (probe may be NULL to print instead).
+   Returns 0, -1 (no controller) or -2 (a scan is already running); every
+   completed scan bumps the generation counter. */
+int usb_scan(usb_probe_fn probe);
+
+/* Cheap periodic watcher: enumerates devices on root ports whose connect
+   state changed since the last call (internally throttled).  Returns the
+   number of ports with a new device. */
+int usb_hotplug_poll(usb_probe_fn probe);
+
+/* Incremented by every scan; consumers re-init when it changes. */
+unsigned int usb_generation(void);
+
+/* Root-port query (used to watch the port the mouse hangs off). */
+int usb_port_connected(unsigned int ctrl, unsigned int port);
+
+/* Control request helpers.  rt is the raw bmRequestType (standard 0x80/0x00,
+   class 0xA0/0x20, other 0xA3/0x23); the rest is the raw setup fields. */
+int usb_control_in(unsigned int ctrl, unsigned int addr, unsigned int mps,
+		   int low_speed, unsigned char rt, unsigned char req,
+		   unsigned short value, unsigned short index,
+		   unsigned char *buf, unsigned int len);
+int usb_control_out(unsigned int ctrl, unsigned int addr, unsigned int mps,
+		    int low_speed, unsigned char rt, unsigned char req,
+		    unsigned short value, unsigned short index);
+
+/* Interrupt-IN endpoints (slots 0..USB_HCD_INT_SLOTS-1; usbhid assigns
+   one per HID interface it claims). */
+int usb_int_in_start(unsigned int ctrl, unsigned int slot, unsigned int addr,
+		     unsigned int ep, unsigned int mps, int low_speed);
+int usb_int_in_poll(unsigned int slot, unsigned char *buf, unsigned int len);
+void usb_int_in_stop(unsigned int slot);
+
 #endif
 #endif

+ 83 - 0
usb_hcd.h

@@ -0,0 +1,83 @@
+/* USB host controller driver (HCD) interface.
+ *
+ * usb.c drives enumeration, bus scans and the interrupt-IN consumers (USB
+ * mouse + keyboard) through this vtable; uhci.c and ohci.c each implement it
+ * for their controller type.  One "controller instance" is one PCI function
+ * (MCP79 exposes four OHCI ones, for example). */
+#ifndef USB_HCD_H
+#define USB_HCD_H
+
+#define USB_HCD_MAX_CTRL 4
+
+/* Interrupt-IN endpoints serviced concurrently; usbhid manages which
+   slot carries which device (mice + keyboards, composite devices). */
+#define USB_HCD_INT_SLOTS 6
+
+/* One interface of one device, filled in during a scan and passed to the
+ * scan probe.  ep_addr is 0 when the interface has no interrupt-IN endpoint. */
+struct usb_iface_info {
+	unsigned int ctrl;        /* controller instance index */
+	unsigned int addr;        /* device address on that controller's bus */
+	unsigned int mps;         /* device EP0 max packet size */
+	int low_speed;
+	unsigned int port;        /* root port the device hangs off (0xFF: behind a hub) */
+	unsigned int vendor, product;
+	unsigned int cls, subcls, proto;   /* interface class/subclass/protocol */
+	unsigned int iface_num;
+	unsigned int config_value;
+	unsigned int ep_addr;     /* endpoint address byte (0x81 = EP1 IN) */
+	unsigned int ep_mps;
+	unsigned int ep_interval;
+};
+
+/* Called once per interface during a scan; return 1 when claimed. */
+typedef int (*usb_probe_fn)(const struct usb_iface_info *info);
+
+struct usb_hcd_ops {
+	const char *name;
+
+	/* Find + reset the controller(s).  Returns the number of instances
+	 * found (0 = none).  Idempotent: only brings hardware up on the
+	 * first successful call. */
+	int (*init)(void);
+	unsigned int (*count)(void);
+
+	/* PCI location and register base of one instance (for the `lsusb`
+	 * header).  *mmio is 1 for a memory-mapped register block. */
+	void (*info)(unsigned int ctrl, unsigned int *bus, unsigned int *dev,
+		     unsigned int *func, unsigned int *base, int *mmio);
+
+	/* Control transfer on endpoint 0.  Returns bytes transferred
+	 * (>= 0) or -1.  mps = EP0 max packet size (used to split the data
+	 * stage).  dir_in: 1 = IN data stage, 0 = OUT or no data stage. */
+	int (*control_transfer)(unsigned int ctrl, unsigned int addr,
+				unsigned int mps, int low_speed,
+				const unsigned char *setup, unsigned char *data,
+				unsigned int len, int dir_in);
+
+	/* Root hub ports of one instance.  Port numbers are 0-based. */
+	unsigned int (*port_count)(unsigned int ctrl);
+	int (*port_connected)(unsigned int ctrl, unsigned int port);
+	int (*port_low_speed)(unsigned int ctrl, unsigned int port);
+	int (*port_reset)(unsigned int ctrl, unsigned int port);
+	/* Returns 1 (and clears the hardware latch) when a connection change
+	 * was detected since the last call. */
+	int (*port_take_change)(unsigned int ctrl, unsigned int port);
+
+	/* Interrupt-IN endpoints (one slot per HID device; see
+	 * USB_HCD_INT_SLOTS).  The transfer stays armed in the schedule;
+	 * the controller retries NAKs itself.  poll: > 0 report bytes
+	 * (auto re-armed), 0 nothing yet, -1 error (still armed, toggle
+	 * preserved; the caller may count errors and re-init). */
+	int (*int_in_start)(unsigned int ctrl, unsigned int slot,
+			    unsigned int addr, unsigned int ep,
+			    unsigned int mps, int low_speed);
+	int (*int_in_poll)(unsigned int slot, unsigned char *buf,
+			   unsigned int len);
+	void (*int_in_stop)(unsigned int slot);
+};
+
+extern const struct usb_hcd_ops usb_uhci_ops;
+extern const struct usb_hcd_ops usb_ohci_ops;
+
+#endif

+ 484 - 0
usbhid.c

@@ -0,0 +1,484 @@
+/* USB HID boot devices: mice + keyboards.
+ *
+ * The probe claims every HID interface it understands: boot mouse/keyboard
+ * (class 3 / subclass 1 / protocol 2 or 1) or report-protocol HID
+ * interfaces whose report descriptor says "mouse"/"pointer" or "keyboard"
+ * (class 3, other subclasses — many modern and composite devices).  Each
+ * claimed interface gets its own interrupt slot, so a composite device
+ * (keyboard + mouse in one) and several devices can coexist.
+ *
+ * Mouse reports are handed back to mouse.c; keyboard reports are decoded
+ * into PS/2 set-1 scancodes and injected into the regular input queue
+ * (io_inject_scancode), so the terminal/WM see them exactly like a PS/2
+ * keyboard.  Root ports are watched so devices can be plugged in later. */
+
+#include "usbhid.h"
+#include "io.h"
+#include "usb.h"
+#include "serial.h"
+#include "timer.h"
+
+/* Request types/requests used here. */
+#define RT_HOST2DEV_STD 0x00u
+#define RT_HOST2DEV_CLS 0x21u
+#define RT_DEV2HOST_CLS_IF 0x81u   /* class request to an interface, IN */
+#define REQ_GET_DESCRIPTOR 0x06u
+#define REQ_SET_CONFIGURATION 0x09u
+#define REQ_SET_PROTOCOL      0x0Bu
+
+/* Hotplug watcher period (must match usb.c's internal throttle). */
+#define WATCH_MS 250
+
+/* Extended (0xE0-prefixed) PS/2 make codes in the mapping table. */
+#define K_EXT 0xE000u
+
+/* How much of a report descriptor to read for classification. */
+#define REPORT_MAX 64
+
+enum { KIND_FREE = 0, KIND_MOUSE, KIND_KBD };
+
+struct hid_dev {
+	unsigned int kind;        /* KIND_*, KIND_FREE = slot unused */
+	int present;              /* endpoint armed */
+	int claimed;              /* claimed by the scan in progress */
+	unsigned int ctrl, addr, ep, mps, port;
+	int low;
+	unsigned int err;         /* consecutive transfer errors */
+	/* keyboard report-diff state */
+	unsigned char prev[6];
+	unsigned char prev_mod;
+};
+
+static struct hid_dev devs[USB_HCD_INT_SLOTS];
+static int hcd_ok;
+static int need_rescan;
+static unsigned int gen;
+static unsigned int last_watch;
+
+/* --- keyboard report decoding ------------------------------------------ */
+
+/* HID keyboard usage -> PS/2 set-1 make code (0 = unmapped). */
+static const unsigned short hid_to_sc[256] = {
+	[0x04] = 0x1E, [0x05] = 0x30, [0x06] = 0x2E, [0x07] = 0x20,
+	[0x08] = 0x12, [0x09] = 0x21, [0x0A] = 0x22, [0x0B] = 0x23,
+	[0x0C] = 0x17, [0x0D] = 0x24, [0x0E] = 0x25, [0x0F] = 0x26,
+	[0x10] = 0x32, [0x11] = 0x31, [0x12] = 0x18, [0x13] = 0x19,
+	[0x14] = 0x10, [0x15] = 0x13, [0x16] = 0x1F, [0x17] = 0x14,
+	[0x18] = 0x16, [0x19] = 0x2F, [0x1A] = 0x11, [0x1B] = 0x2D,
+	[0x1C] = 0x15, [0x1D] = 0x2C,
+	[0x1E] = 0x02, [0x1F] = 0x03, [0x20] = 0x04, [0x21] = 0x05,
+	[0x22] = 0x06, [0x23] = 0x07, [0x24] = 0x08, [0x25] = 0x09,
+	[0x26] = 0x0A, [0x27] = 0x0B,
+	[0x28] = 0x1C, [0x29] = 0x01, [0x2A] = 0x0E, [0x2B] = 0x0F,
+	[0x2C] = 0x39, [0x2D] = 0x0C, [0x2E] = 0x0D, [0x2F] = 0x1A,
+	[0x30] = 0x1B, [0x31] = 0x2B, [0x33] = 0x27, [0x34] = 0x28,
+	[0x35] = 0x29, [0x36] = 0x33, [0x37] = 0x34, [0x38] = 0x35,
+	[0x39] = 0x3A,
+	[0x3A] = 0x3B, [0x3B] = 0x3C, [0x3C] = 0x3D, [0x3D] = 0x3E,
+	[0x3E] = 0x3F, [0x3F] = 0x40, [0x40] = 0x41, [0x41] = 0x42,
+	[0x42] = 0x43, [0x43] = 0x44, [0x44] = 0x57, [0x45] = 0x58,
+	[0x49] = K_EXT | 0x52, [0x4A] = K_EXT | 0x47, [0x4B] = K_EXT | 0x49,
+	[0x4C] = K_EXT | 0x53, [0x4D] = K_EXT | 0x4F, [0x4E] = K_EXT | 0x51,
+	[0x4F] = K_EXT | 0x4D, [0x50] = K_EXT | 0x4B, [0x51] = K_EXT | 0x50,
+	[0x52] = K_EXT | 0x48,
+};
+
+/* Modifier bit -> PS/2 make code: L/R ctrl, shift, alt, GUI. */
+static const unsigned short hid_mod_sc[8] = {
+	0x1D, K_EXT | 0x1D,   /* L Ctrl, R Ctrl */
+	0x2A, 0x36,           /* L Shift, R Shift */
+	0x38, K_EXT | 0x38,   /* L Alt, R Alt */
+	K_EXT | 0x5B, K_EXT | 0x5C,   /* L GUI, R GUI */
+};
+static const unsigned char hid_mod_bit[8] = {
+	0x01, 0x10, 0x02, 0x20, 0x04, 0x40, 0x08, 0x80,
+};
+
+static void kbd_inject(unsigned int code, int down)
+{
+	if (!code)
+		return;
+	if (code & K_EXT) {
+		io_inject_scancode(0xE0);
+		io_inject_scancode((unsigned char)((code & 0xFFu) |
+						   (down ? 0 : 0x80)));
+	} else {
+		io_inject_scancode((unsigned char)(code | (down ? 0 : 0x80)));
+	}
+}
+
+/* Boot keyboard report: [modifiers][reserved][key0..key5].  Diff against
+   the previous report to derive make/break scancodes. */
+static void kbd_decode(struct hid_dev *d, const unsigned char *r)
+{
+	unsigned int i, j;
+
+	for (i = 0; i < 8; i++) {
+		int was = (d->prev_mod & hid_mod_bit[i]) != 0;
+		int now = (r[0] & hid_mod_bit[i]) != 0;
+		if (was != now)
+			kbd_inject(hid_mod_sc[i], now);
+	}
+	d->prev_mod = r[0];
+
+	/* Releases: in the previous report, gone from this one. */
+	for (i = 0; i < 6; i++) {
+		if (!d->prev[i])
+			continue;
+		for (j = 0; j < 6; j++) {
+			if (r[2 + j] == d->prev[i])
+				break;
+		}
+		if (j == 6)
+			kbd_inject(hid_to_sc[d->prev[i]], 0);
+	}
+	/* Presses: new in this report. */
+	for (i = 0; i < 6; i++) {
+		if (!r[2 + i])
+			continue;
+		for (j = 0; j < 6; j++) {
+			if (d->prev[j] == r[2 + i])
+				break;
+		}
+		if (j == 6)
+			kbd_inject(hid_to_sc[r[2 + i]], 1);
+	}
+	for (i = 0; i < 6; i++)
+		d->prev[i] = r[2 + i];
+}
+
+/* --- report-descriptor classification ----------------------------------- */
+
+/* Minimal HID item walk: find a Generic Desktop (usage page 1) mouse or
+   keyboard collection.  Mouse detection accepts a Mouse/Pointer collection
+   or a relative X/Y input item (so absolute tablets are not claimed). */
+static unsigned int hid_classify(const struct usb_iface_info *in)
+{
+	static unsigned char rep[REPORT_MAX];
+	int n, mouse = 0, kbd = 0;
+	unsigned int i = 0, page = 0;
+	int loc_mouse = 0, loc_kbd = 0, loc_xy = 0;
+
+	n = usb_control_in(in->ctrl, in->addr, in->mps, in->low_speed,
+			   RT_DEV2HOST_CLS_IF, REQ_GET_DESCRIPTOR,
+			   (unsigned short)(0x22u << 8),
+			   (unsigned short)in->iface_num, rep, sizeof(rep));
+	if (n <= 0)
+		return KIND_FREE;
+
+	while (i < (unsigned int)n) {
+		unsigned int item = rep[i++];
+		unsigned int size = item & 3u;
+		unsigned int type = (item >> 2) & 3u;
+		unsigned int tag = (item >> 4) & 0xFu;
+		unsigned int data = 0, k;
+
+		if (size == 3u)
+			size = 4u;
+		for (k = 0; k < size; k++) {
+			if (i + k < (unsigned int)n)
+				data |= (unsigned int)rep[i + k] << (8u * k);
+		}
+		i += size;
+
+		if (type == 1u && tag == 0u) {          /* Global Usage Page */
+			page = data;
+		} else if (type == 2u && tag == 0u && page == 0x01u) {
+			if (data == 0x01u || data == 0x02u)     /* Pointer/Mouse */
+				loc_mouse = 1;
+			else if (data == 0x06u)                 /* Keyboard */
+				loc_kbd = 1;
+			else if (data == 0x30u || data == 0x31u) /* X/Y */
+				loc_xy = 1;
+		} else if (type == 0u) {                /* Main item */
+			if (tag == 0xAu) {              /* Collection */
+				if (loc_mouse)
+					mouse = 1;
+				if (loc_kbd)
+					kbd = 1;
+			} else if (tag == 0x8u && loc_xy &&
+				   (data & 0x04u)) {    /* Input, relative */
+				mouse = 1;
+			}
+			loc_mouse = loc_kbd = loc_xy = 0;
+		}
+	}
+
+	if (mouse)
+		return KIND_MOUSE;
+	if (kbd)
+		return KIND_KBD;
+	return KIND_FREE;
+}
+
+/* --- manager ------------------------------------------------------------ */
+
+static int hid_probe(const struct usb_iface_info *in)
+{
+	struct hid_dev *d = 0;
+	unsigned int kind, i;
+
+	if (in->cls != 0x03u || !in->ep_addr || !(in->ep_addr & 0x80u))
+		return 0;
+
+	if (in->subcls == 0x01u && in->proto == 0x02u)
+		kind = KIND_MOUSE;
+	else if (in->subcls == 0x01u && in->proto == 0x01u)
+		kind = KIND_KBD;
+	else
+		kind = hid_classify(in);
+	if (kind == KIND_FREE)
+		return 0;
+
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		if (!devs[i].present && !devs[i].claimed) {
+			d = &devs[i];
+			break;
+		}
+	}
+	if (!d)
+		return 0;   /* every slot is busy */
+
+	/* The endpoint is unusable until the device is configured. */
+	usb_control_out(in->ctrl, in->addr, in->mps, in->low_speed,
+			RT_HOST2DEV_STD, REQ_SET_CONFIGURATION,
+			(unsigned short)(in->config_value & 0xFFu), 0);
+	/* Boot protocol for boot-class devices; a stall is tolerated. */
+	if (in->subcls == 0x01u)
+		usb_control_out(in->ctrl, in->addr, in->mps, in->low_speed,
+				RT_HOST2DEV_CLS, REQ_SET_PROTOCOL, 0,
+				in->iface_num);
+
+	d->kind = kind;
+	d->ctrl = in->ctrl;
+	d->addr = in->addr;
+	d->ep = in->ep_addr & 0x0Fu;
+	d->mps = in->ep_mps ? in->ep_mps : 8;
+	d->port = in->port;
+	d->low = in->low_speed;
+	d->claimed = 1;
+	return 1;
+}
+
+static void dev_attach(struct hid_dev *d, unsigned int slot)
+{
+	unsigned int i;
+
+	if (usb_int_in_start(d->ctrl, slot, d->addr, d->ep, d->mps, d->low) != 0)
+		return;
+	d->err = 0;
+	d->present = 1;
+	d->prev_mod = 0;
+	for (i = 0; i < 6; i++)
+		d->prev[i] = 0;
+
+	serial_puts(SERIAL_COM1, d->kind == KIND_MOUSE
+				   ? "usbhid: mouse attached ("
+				   : "usbhid: keyboard attached (");
+	serial_puts(SERIAL_COM1, usb_hcd_name());
+	serial_puts(SERIAL_COM1, ", addr ");
+	serial_putdec(SERIAL_COM1, d->addr);
+	serial_puts(SERIAL_COM1, " ep ");
+	serial_putdec(SERIAL_COM1, 0x80u | d->ep);
+	serial_puts(SERIAL_COM1, ")\n");
+}
+
+static void dev_detach(struct hid_dev *d, unsigned int slot)
+{
+	usb_int_in_stop(slot);
+	d->present = 0;
+	d->claimed = 0;
+	last_watch = get_ticks_ms() - WATCH_MS;   /* watch again soon */
+	serial_puts(SERIAL_COM1, d->kind == KIND_MOUSE
+				   ? "usbhid: mouse detached (addr "
+				   : "usbhid: keyboard detached (addr ");
+	serial_putdec(SERIAL_COM1, d->addr);
+	serial_puts(SERIAL_COM1, ")\n");
+	d->kind = KIND_FREE;
+}
+
+static void arm_claimed(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		if (devs[i].claimed) {
+			dev_attach(&devs[i], i);
+			devs[i].claimed = 0;
+		}
+	}
+}
+
+static void hid_scan(void)
+{
+	unsigned int i;
+
+	/* A full scan resets every root port: existing handles are stale. */
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		if (devs[i].kind != KIND_FREE) {
+			usb_int_in_stop(i);
+			devs[i].kind = KIND_FREE;
+			devs[i].present = 0;
+			devs[i].claimed = 0;
+		}
+	}
+
+	if (usb_scan(hid_probe) != 0)
+		return;   /* busy: retried from the watcher */
+	need_rescan = 0;
+	gen = usb_generation();
+	arm_claimed();
+}
+
+void usbhid_init(void)
+{
+	if (usb_hcd_init() != 0) {
+		serial_puts(SERIAL_COM1, "usbhid: no USB host controller\n");
+		hcd_ok = 0;
+		return;
+	}
+	hcd_ok = 1;
+
+	if (usb_scan(hid_probe) != 0) {
+		/* A scan is already running (unlikely at boot): finish from
+		   the watcher. */
+		need_rescan = 1;
+		gen = usb_generation();
+		return;
+	}
+	gen = usb_generation();
+	arm_claimed();
+	if (!usbhid_mouse_attached() && !usbhid_keyboard_attached())
+		serial_puts(SERIAL_COM1,
+			    "usbhid: no HID boot mouse/keyboard found\n");
+}
+
+/* Service one slot: detach on disconnect/errors, return report length. */
+static int dev_poll(struct hid_dev *d, unsigned int slot, unsigned char *buf,
+		    unsigned int len)
+{
+	int n;
+
+	if (!d->present)
+		return 0;
+	if (d->port != 0xFFu && !usb_port_connected(d->ctrl, d->port)) {
+		dev_detach(d, slot);
+		return 0;
+	}
+	n = usb_int_in_poll(slot, buf, len);
+	if (n < 0) {
+		if (++d->err >= 5)
+			dev_detach(d, slot);
+		return 0;
+	}
+	d->err = 0;
+	return n;
+}
+
+int usbhid_poll(unsigned int *buttons, int *dx, int *dy)
+{
+	unsigned char buf[8];
+	unsigned int now, i, all_busy = 1;
+	unsigned int b = 0;
+	int n, x = 0, y = 0, got = 0;
+
+	if (!hcd_ok)
+		return 0;
+
+	/* A full bus re-scan (`lsusb`) invalidates every handle. */
+	if (usb_generation() != gen) {
+		for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+			if (devs[i].present)
+				dev_detach(&devs[i], i);
+		}
+		need_rescan = 1;
+	}
+
+	/* Throttled: finish a pending rescan, or watch for hotplug. */
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		if (devs[i].kind == KIND_FREE)
+			all_busy = 0;
+	}
+	now = get_ticks_ms();
+	if (now - last_watch >= WATCH_MS) {
+		last_watch = now;
+		if (need_rescan) {
+			hid_scan();
+		} else if (!all_busy) {
+			for (i = 0; i < USB_HCD_INT_SLOTS; i++)
+				devs[i].claimed = 0;
+			if (usb_hotplug_poll(hid_probe) > 0)
+				arm_claimed();
+		}
+	}
+
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		struct hid_dev *d = &devs[i];
+
+		if (d->kind == KIND_FREE)
+			continue;
+		n = dev_poll(d, i, buf, sizeof(buf));
+		if (n >= 3 && d->kind == KIND_MOUSE) {
+			b |= buf[0] & 0x07u;
+			x += (int)(signed char)buf[1];
+			/* HID: +y is down; mouse.c expects +y = up. */
+			y -= (int)(signed char)buf[2];
+			got = 1;
+		} else if (n >= 8 && d->kind == KIND_KBD) {
+			kbd_decode(d, buf);
+		}
+	}
+
+	if (got) {
+		*buttons = b;
+		*dx = x;
+		*dy = y;
+	}
+	return got;
+}
+
+int usbhid_mouse_attached(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		if (devs[i].kind == KIND_MOUSE && devs[i].present)
+			return 1;
+	}
+	return 0;
+}
+
+int usbhid_keyboard_attached(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		if (devs[i].kind == KIND_KBD && devs[i].present)
+			return 1;
+	}
+	return 0;
+}
+
+void usbhid_get_info(unsigned int *ctrl, unsigned int *addr,
+		     unsigned int *ep, unsigned int *mps, int *low)
+{
+	unsigned int i;
+
+	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
+		struct hid_dev *d = &devs[i];
+
+		if (d->kind == KIND_MOUSE && d->present) {
+			*ctrl = d->ctrl;
+			*addr = d->addr;
+			*ep = d->ep;
+			*mps = d->mps;
+			*low = d->low;
+			return;
+		}
+	}
+	*ctrl = 0;
+	*addr = 0;
+	*ep = 0;
+	*mps = 0;
+	*low = 0;
+}

+ 30 - 0
usbhid.h

@@ -0,0 +1,30 @@
+/* USB HID boot devices: mouse + keyboard.
+ *
+ * A single manager owns the scan/hotplug state for both interrupt-IN
+ * endpoints (slot 0 = mouse, slot 1 = keyboard): find, configure, put into
+ * boot protocol and keep each endpoint armed.  The mouse reports are handed
+ * back to mouse.c; keyboard reports are decoded into PS/2 set-1 scancodes
+ * and injected into the regular input queue (io_inject_scancode), so the
+ * terminal/WM see them exactly like a PS/2 keyboard. */
+#ifndef USBHID_H
+#define USBHID_H
+
+/* Bring up the USB subsystem and look for a boot mouse/keyboard.  Safe to
+   call when no controller or device exists; the hotplug watcher keeps
+   running then. */
+void usbhid_init(void);
+
+/* Service both endpoints (called once per WM loop iteration from
+   mouse_poll_update()).  Returns 1 when a mouse report is available and
+   fills buttons/dx/dy (PS/2 sign convention: dy > 0 = up). */
+int usbhid_poll(unsigned int *buttons, int *dx, int *dy);
+
+int usbhid_mouse_attached(void);
+int usbhid_keyboard_attached(void);
+
+/* For `mouseinfo`: controller instance, device address, endpoint number,
+   endpoint max packet size and the low-speed flag. */
+void usbhid_get_info(unsigned int *ctrl, unsigned int *addr,
+		     unsigned int *ep, unsigned int *mps, int *low);
+
+#endif