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

usb: xHCI hub TT, composite HID and seriallog

Bring up the Yoga second (Alpine Ridge) xHCI and the devices behind its USB2 hub: route strings and the parent hub TT slot/port in tt_info, a slot-only Configure Endpoint for the hub, and the Last Valid Endpoint fix for slots that gain a second or third interrupt endpoint.  The old LVE calculation lowered the slot context endpoint count when EP2/EP3 were added after EP1, so the xHC rejected them with Parameter Error (0x11).

Add the Logitech DJ receiver and report-protocol HID handling, the always-on COM1 ring with seriallog show|save, and the Synaptics LPSS I2C diagnostics (PMECTRL, reset, clock and controller register dump).  Update the architecture docs and extend the QEMU USB tests.
Johannes Zellner 4 часов назад
Родитель
Сommit
d71d10869c
22 измененных файлов с 1018 добавлено и 251 удалено
  1. 87 24
      AGENTS.md
  2. 4 1
      Makefile
  3. 1 1
      docs/boot.html
  4. 2 2
      docs/development.html
  5. 24 6
      docs/drivers.html
  6. 43 0
      kernel/bootcon.c
  7. 10 0
      kernel/bootcon.h
  8. 7 2
      kernel/ehci.c
  9. 51 1
      kernel/i2c.c
  10. 7 0
      kernel/i2c.h
  11. 11 4
      kernel/ohci.c
  12. 1 0
      kernel/serial.c
  13. 86 1
      kernel/terminal.c
  14. 86 12
      kernel/touchpad.c
  15. 4 2
      kernel/uhci.c
  16. 42 16
      kernel/usb.c
  17. 2 1
      kernel/usb.h
  18. 18 2
      kernel/usb_hcd.h
  19. 83 16
      kernel/usbhid.c
  20. 11 9
      kernel/usbhid.h
  21. 424 150
      kernel/xhci.c
  22. 14 1
      tools/qmp_cursor_test.py

+ 87 - 24
AGENTS.md

@@ -239,8 +239,8 @@ and `make net-dev`/`kernel-net-dev` reload over the network.  `bootlog save
    used); fixed disks use EDD LBA.
    used); fixed disks use EDD LBA.
 3. `kernel.c` — `kernel_main` zeroes BSS then inits serial → memory/paging →
 3. `kernel.c` — `kernel_main` zeroes BSS then inits serial → memory/paging →
    ACPI/MADT → I/O → power → idle → processes → timer (PIT; 1 kHz busy,
    ACPI/MADT → I/O → power → idle → processes → timer (PIT; 1 kHz busy,
-   100 Hz idle + IDT) → SMP AP bring-up → PS/2 mouse (the I2C touchpad
-   probe only on Airmont) → VGA shadow buffer → ramfs inflate →
+   100 Hz idle + IDT) → SMP AP bring-up → PS/2 mouse and I2C touchpad
+   (Elan on Airmont, Synaptics on Sunrise Point-LP) → VGA shadow buffer → ramfs inflate →
    `wm_server_init()` → start `/ramfs/bin/init` as PID 1 → init spawns the
    `wm_server_init()` → start `/ramfs/bin/init` as PID 1 → init spawns the
    WM → publish `vfs_scan_busy` → `wm_server_boot_ready()` → wait (idle `hlt`,
    WM → publish `vfs_scan_busy` → `wm_server_boot_ready()` → wait (idle `hlt`,
    1 s cap) until the first terminal has presented → USB bring-up and scan
    1 s cap) until the first terminal has presented → USB bring-up and scan
@@ -1522,9 +1522,17 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   max-X/Y (`0x0106`/`0x0107`).  On Skylake/Kaby Lake it finds the PCI
   max-X/Y (`0x0106`/`0x0107`).  On Skylake/Kaby Lake it finds the PCI
   00:15.0/1/2 LPSS functions, enables their memory decode and puts them in
   00:15.0/1/2 LPSS functions, enables their memory decode and puts them in
   D0 first (the firmware leaves the command register at 0: Linux logs
   D0 first (the firmware leaves the command register at 0: Linux logs
-  `intel-lpss 0000:00:15.0: enabling device (0000 -> 0002)`), maps the BAR
-  and probes the Synaptics at `0x2c`; the HID descriptor vendor/product
-  `0x06CB/0x7F8F` filters out the Wacom touchscreen on I2C1.  The
+  `intel-lpss 0000:00:15.0: enabling device (0000 -> 0002)`), clears the
+  LPSS `PMECTRLSTATUS` at PCI config `0x84` (the DSDT `LPD0(SB10)` target;
+  the PMC `PWRMBASE + 0x84` address is a different register and leaves the
+  I2C FSM power-gated), enables the LPSS functional clock at private
+  `0x200` (gate + M=6/N=5 for the 120 MHz I2C clock; the BIOS leaves
+  unused LPSS blocks gated, and the register file still answers while the
+  I2C FSM does not drive the bus), maps the BAR and probes the Synaptics
+  at `0x2c`; the HID descriptor vendor/product
+  `0x06CB/0x7F8F` filters out the Wacom touchscreen on I2C1.  The BIOS
+  already leaves GPP_C16/C17 in native function 1 (Linux's `pins` shows
+  `mode 1 0x84000702 0x58`), so the kernel does not rewrite the pads.  The
   Synaptics probe follows Linux i2c-hid: address ACK, read the HID
   Synaptics probe follows Linux i2c-hid: address ACK, read the HID
   descriptor, then power-on (`0x0800`), reset (`0x0100`) and the
   descriptor, then power-on (`0x0800`), reset (`0x0100`) and the
   zero-length reset-complete input report.  The report line is
   zero-length reset-complete input report.  The report line is
@@ -1552,8 +1560,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `rightclick off|tap|corner|both`, `tapclick on|off`,
   `rightclick off|tap|corner|both`, `tapclick on|off`,
   `scroll on|off|natural|traditional` and `invert on|off`; `touchpad probe`
   `scroll on|off|natural|traditional` and `invert on|off`; `touchpad probe`
   reruns a failed boot probe and prints the LPSS PCI id/BAR/command, the
   reruns a failed boot probe and prints the LPSS PCI id/BAR/command, the
-  DesignWare component type and the 0x200/0x204 private registers on
-  failure.  `mouseinfo` lists the Elan/Synaptics VID/PID.
+  DesignWare component type, the 0x200 clock and 0x204 reset registers, and
+  the PMECTRLSTATUS before/after clear on failure.
+  `mouseinfo` lists the Elan/Synaptics VID/PID.
 - **USB**: `usb.c/h` — controller-agnostic core: device enumeration,
 - **USB**: `usb.c/h` — controller-agnostic core: device enumeration,
   descriptor parsing, hub recursion, bus scans, per-controller addresses, the
   descriptor parsing, hub recursion, bus scans, per-controller addresses, the
   hotplug watcher and the interrupt-IN consumers (mouse + keyboard).  It keeps
   hotplug watcher and the interrupt-IN consumers (mouse + keyboard).  It keeps
@@ -2633,7 +2642,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `acpidump` (writes the mapped
 `mkdir <path>`, `rmdir <path>`, `hello`, `acpidump` (writes the mapped
 DSDT to `/share/DSDT.BIN`), `reboot`, `poweroff`,
 DSDT to `/share/DSDT.BIN`), `reboot`, `poweroff`,
-`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [probe] [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional] [invert on|off]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `bootscan` (the live boot storage-scan window), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
+`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [probe] [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional] [invert on|off]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `bootscan` (the live boot storage-scan window), `seriallog save <path>|show` (write the always-on COM1 capture to a file, or print only its xhci/usb/touchpad lines on screen), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
 `ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `service [list|status <name>|start|stop|restart|kill <name>|logs <name>|logtail <name>|--gui]` (init's client; `websrv` is the first service and holds the raw NIC receiver while running), `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher; waits for the app so a terminal launch is foreground), and `chat [config-path]` (Cloudron Chat client).
 `ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `service [list|status <name>|start|stop|restart|kill <name>|logs <name>|logtail <name>|--gui]` (init's client; `websrv` is the first service and holds the raw NIC receiver while running), `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher; waits for the app so a terminal launch is foreground), and `chat [config-path]` (Cloudron Chat client).
 
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
@@ -2934,11 +2943,29 @@ briefly reporting disconnected.
   running. The PCI scan checks **all functions** (real PIIX3/PIIX4/VIA
   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
   layouts put the USB function at 0:07.2 / 0:01.2) and ignores controllers
   whose BARs the firmware left unassigned. One instance only.
   whose BARs the firmware left unassigned. One instance only.
-- **xHCI**: MMIO BAR0 (PCI class `0c03:30`), one controller, polled.  The
-  Supported Protocol extended capabilities include both USB2 and USB3
+- **xHCI**: MMIO BAR0 (PCI class `0c03:30`), up to two controllers
+  (`XHCI_MAX_HCD`), polled.  The Yoga 720 has the Sunrise Point-LP PCH
+  controller and, behind its Thunderbolt bridges, the Alpine Ridge
+  USB-C/Thunderbolt xHCI (PCI `3e:00.0`); the driver used to stop at the
+  first one, so the Lenovo hub and the Logitech receiver were invisible.
+  Each instance has its own state struct (page-allocated to keep the
+  kernel BSS below the `0x90000` wall) and the vtable's local index selects
+  it; the interrupt-slot table records which instance owns each slot
+  because `int_in_poll()` gets only the slot.
+  The Supported Protocol extended capabilities include both USB2 and USB3
   protocol entries; direct SuperSpeed root-port devices are enumerated with
   protocol entries; direct SuperSpeed root-port devices are enumerated with
-  a 512-byte EP0 and the port speed in the slot context.  USB3 hub
-  port-status decoding is not implemented.  `xhci_init()` waits for `CNR=0`,
+  a 512-byte EP0 and the port speed in the slot context.  The slot context
+  also carries the 20-bit route string for devices behind a USB2 hub (the
+  root port is in its own field) and the parent hub's slot id/port as the
+  TT fields for a low/full-speed device behind a high-speed hub, plus the
+  device's own speed (the root port runs at the hub's upstream speed), so
+  the Logitech receiver on the Yoga's Lenovo hub enumerates.  The TT fields
+  are the slot context's `tt_info` dword (`p[2]`), not `dev_info2`, and a
+  hub slot is moved to Configured with a slot-only Configure Endpoint after
+  Address Device: the xHC does not change the slot state from the USB
+  `SET_CONFIGURATION` request, and a high-speed hub must be Configured
+  before a downstream TT Address Device (otherwise the child gets
+  Parameter Error `cc=0x11`).  USB3 hub port-status decoding is not implemented.  `xhci_init()` waits for `CNR=0`,
   clears `RS` and waits for `USBSTS.HCH` **before** `HCRST` (the xHC may
   clears `RS` and waits for `USBSTS.HCH` **before** `HCRST` (the xHC may
   ignore the reset while running), waits 1-2 ms after the HCRST write before
   ignore the reset while running), waits 1-2 ms after the HCRST write before
   touching any other register (Intel CherryView/Braswell requires this, or
   touching any other register (Intel CherryView/Braswell requires this, or
@@ -3028,6 +3055,16 @@ briefly reporting disconnected.
   keyboard only reports changes, `io.c` adds software typematic repeat
   keyboard only reports changes, `io.c` adds software typematic repeat
   (500 ms delay, 33 ms rate) for the last make code; real PS/2 hardware
   (500 ms delay, 33 ms rate) for the last make code; real PS/2 hardware
   repeat keeps resetting the same timer.
   repeat keeps resetting the same timer.
+  A Logitech Unifying receiver (`046d:c52b`) is handled specially on its
+  DJ interface (2): the probe claims it and decodes the paired device's DJ
+  mouse reports (`report_type 2`, 12-bit X/Y, wheel) as a normal mouse.
+  Unlike Linux's `hid-logitech-dj`, it does not send the HID++ switch
+  command: a receiver left in boot mode uses the boot mouse interface (1),
+  while a receiver already in DJ mode (the usual warm-reboot case after
+  Linux has used it) sends DJ reports directly.  The interrupt slots take a
+  report length separate from the endpoint's max packet size (`USB_INT_MAX`
+  32), because the receiver's endpoint is 32 bytes; boot HID devices keep
+  8-byte reports.
   `usbhid_poll()` (from `mouse_poll_update()`) also runs the hotplug
   `usbhid_poll()` (from `mouse_poll_update()`) also runs the hotplug
   watcher: root-port connect changes are enumerated (throttled to 250 ms).
   watcher: root-port connect changes are enumerated (throttled to 250 ms).
   A port read must report disconnected three times in a row before the
   A port read must report disconnected three times in a row before the
@@ -3049,16 +3086,18 @@ briefly reporting disconnected.
   `tools/qmp_cursor_test.py` (injects mouse motion with QMP
   `tools/qmp_cursor_test.py` (injects mouse motion with QMP
   `input-send-event`, verifies the cursor with `screendump`) and
   `input-send-event`, verifies the cursor with `screendump`) and
   `tools/qmp_keyboard_test.py` (types with QMP `send-key`, verifies the
   `tools/qmp_keyboard_test.py` (types with QMP `send-key`, verifies the
-  screen output); the cursor test takes `--uhci`, `--uhci72` and `--multi`,
-  and both take `--hotplug`, `--xhci` and `--ehci`.
+  screen output); the cursor test takes `--uhci`, `--uhci72`, `--multi` and
+  `--hub` (a USB2 hub with the mouse on its downstream port) and both take
+  `--hotplug`, `--xhci` and `--ehci`.
 - **Limits**: EHCI drives high-speed root-port devices only (no TT/split
 - **Limits**: EHCI drives high-speed root-port devices only (no TT/split
   transactions for low/full-speed devices behind a high-speed hub), hotplug
   transactions for low/full-speed devices behind a high-speed hub), hotplug
   watches root ports only (a device behind a hub is only enumerated when a
   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).
+  scan runs), generic HID report IDs are not handled (a device that
+  prepends report IDs decodes as garbage; the Logitech Unifying DJ receiver
+  is decoded explicitly), absolute pointers/tablets are ignored, boot mice
+  have no wheel (the DJ path maps it), 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`)
 
 
@@ -3131,6 +3170,30 @@ QEMU gotchas that bit once:
   written while no client is attached, so a late-connecting reader misses the
   written while no client is attached, so a late-connecting reader misses the
   boot log (kexec tests that wait for it then mis-report a failed reload).
   boot log (kexec tests that wait for it then mis-report a failed reload).
 
 
+### Serial-less boards: save the COM1 capture to a file
+
+`serial_putc()` feeds an always-on 64 KB COM1 ring (`bootcon_serlog_char()`,
+allocated from the frame allocator by `bootcon_log_init()`), independent of
+the `bootscan` thread.  `seriallog save <path>` writes it to a file; on a
+laptop with no legacy COM1 (the Yoga 720), write it to the USB ESP and read
+it from Linux after a reboot:
+
+```
+touchpad probe
+seriallog show
+```
+
+`seriallog show` prints only the xhci/usb/touchpad lines, so the filtered
+trace is readable on screen even when no USB volume is mounted; `seriallog
+save /usb0p3/USBLOG.TXT` writes the complete capture to the boot stick's FAT
+ESP instead.  The file contains the xHCI init lines for every controller,
+every `usbhid:` attach/detach/first-report line, USB port-reset/Address
+Device errors (with the completion code), and the touchpad probe's serial
+copy (`tp_serial_status()` includes the LPSS id/BAR, component type,
+private/reset registers, PMECTRL before/after and pad configs).  `/data` is
+the installed data volume and `/share` is RAM-only.  `bootlog save` remains
+the early boot-console log; `seriallog` is the COM1 driver log.
+
 ## Fatal exception screen (`panic`)
 ## Fatal exception screen (`panic`)
 
 
 The on-screen debug overlay (`kdbg`: live counters, heartbeat, boot info rows)
 The on-screen debug overlay (`kdbg`: live counters, heartbeat, boot info rows)
@@ -3528,11 +3591,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     fits at 8.29 MB) and the framebuffer below 4 GB; otherwise the kernel
     fits at 8.29 MB) and the framebuffer below 4 GB; otherwise the kernel
     starts headless (serial only).  The same 2 M-pixel cap keeps a
     starts headless (serial only).  The same 2 M-pixel cap keeps a
     full-screen RGB565 canvas inside the 4 MB window slot.
     full-screen RGB565 canvas inside the 4 MB window slot.
-    xHCI drives USB2 and USB3 root ports (USB3 hubs are not decoded), and
-    EHCI only high-speed root ports (no transaction translator for
-    low/full-speed devices behind a high-speed hub), so a full-speed device
-    behind a USB2 hub can still leave the UI without input (PS/2 may still
-    work).
+    xHCI drives up to two controllers (the PCH and the Yoga's Alpine Ridge
+    USB-C/Thunderbolt function); USB2 hubs behind either work through the
+    route string, but USB3 hub downstream ports are not decoded.  EHCI
+    only drives high-speed root ports (no transaction translator for
+    low/full-speed devices behind a high-speed hub).
     OVMF delivers the ISA IRQs through the 8259 path; the kernel nevertheless
     OVMF delivers the ISA IRQs through the 8259 path; the kernel nevertheless
     masks the IOAPIC's normal redirection entries after ACPI init, so
     masks the IOAPIC's normal redirection entries after ACPI init, so
     firmware-left vectors cannot collide with the PIC or LAPIC timer.
     firmware-left vectors cannot collide with the PIC or LAPIC timer.

+ 4 - 1
Makefile

@@ -130,7 +130,7 @@ KERNEL_OBJS = $(foreach n,$(KERNEL_LINK_ORDER),$(call kobj,$(n)))
 KERNEL_OS = terminal disk fat nvidia nv50 uhci ohci ehci xhci asix rndis \
 KERNEL_OS = terminal disk fat nvidia nv50 uhci ohci ehci xhci asix rndis \
 	iwl_trans iwl_mvm iwl_dvm wifi_fw rtl8821au wifi ccmp usb lsusb lspci \
 	iwl_trans iwl_mvm iwl_dvm wifi_fw rtl8821au wifi ccmp usb lsusb lspci \
 	peek ne2000 r8168 blkdev fatdetect fatformat format install usbmsc dbg vfs \
 	peek ne2000 r8168 blkdev fatdetect fatformat format install usbmsc dbg vfs \
-	wm sys_wm ideapad i2c touchpad
+	wm sys_wm ideapad i2c touchpad usbhid
 $(addprefix $(B)/kernel/,$(addsuffix .o,$(KERNEL_OS))): OPT = -Os
 $(addprefix $(B)/kernel/,$(addsuffix .o,$(KERNEL_OS))): OPT = -Os
 $(B)/kernel/e1000e.o: OPT = -Oz
 $(B)/kernel/e1000e.o: OPT = -Oz
 # The ACPI table/S5 parser and the poweroff path are cold boot/shutdown code
 # The ACPI table/S5 parser and the poweroff path are cold boot/shutdown code
@@ -1201,6 +1201,9 @@ test-usb: floppy.img root.img
 	python3 tools/qmp_cursor_test.py --uhci72
 	python3 tools/qmp_cursor_test.py --uhci72
 	python3 tools/qmp_cursor_test.py --hotplug
 	python3 tools/qmp_cursor_test.py --hotplug
 	python3 tools/qmp_cursor_test.py --xhci
 	python3 tools/qmp_cursor_test.py --xhci
+	python3 tools/qmp_cursor_test.py --xhci2
+	python3 tools/qmp_cursor_test.py --xhci2hub
+	python3 tools/qmp_cursor_test.py --hub
 	python3 tools/qmp_cursor_test.py --ehci
 	python3 tools/qmp_cursor_test.py --ehci
 	python3 tools/qmp_keyboard_test.py
 	python3 tools/qmp_keyboard_test.py
 	python3 tools/qmp_keyboard_test.py --hotplug
 	python3 tools/qmp_keyboard_test.py --hotplug

+ 1 - 1
docs/boot.html

@@ -410,7 +410,7 @@
 			<li>Parse ACPI/MADT; initialise I/O, power, idle, thermal and board sensors.</li>
 			<li>Parse ACPI/MADT; initialise I/O, power, idle, thermal and board sensors.</li>
 			<li>Create the process table, then start the PIT and verify it ticks.</li>
 			<li>Create the process table, then start the PIT and verify it ticks.</li>
 			<li>Start APs through INIT-SIPI-SIPI (they idle until scheduling is enabled).</li>
 			<li>Start APs through INIT-SIPI-SIPI (they idle until scheduling is enabled).</li>
-			<li>Initialise PS/2 (the I2C touchpad probe only on Airmont) and the VGA shadow buffer.</li>
+			<li>Initialise PS/2 and the I2C touchpad (the Elan on Airmont, the Synaptics on Sunrise Point-LP), then the VGA shadow buffer.</li>
 			<li>Inflate the command pack into <code>/ramfs</code> (table-driven whole-buffer inflate), initialize the kernel window server and start <code>/ramfs/bin/init</code> as PID 1. Init spawns <code>/ramfs/bin/wm</code>; the kernel never starts a WM and the boot console stays if init is absent.</li>
 			<li>Inflate the command pack into <code>/ramfs</code> (table-driven whole-buffer inflate), initialize the kernel window server and start <code>/ramfs/bin/init</code> as PID 1. Init spawns <code>/ramfs/bin/wm</code>; the kernel never starts a WM and the boot console stays if init is absent.</li>
 			<li>Publish <code>vfs_scan_busy</code> and call <code>wm_server_boot_ready()</code>; the WM spawns the <code>bootscan</code> log window first and the first terminal after it, then idle (1 s cap) until the terminal presents.</li>
 			<li>Publish <code>vfs_scan_busy</code> and call <code>wm_server_boot_ready()</code>; the WM spawns the <code>bootscan</code> log window first and the first terminal after it, then idle (1 s cap) until the terminal presents.</li>
 			<li>Bring up USB (controllers, HID, USB NICs/WiFi/disks) non-preemptibly, as before the WM existed; probe the NIC, restore retained network config, start the kworker.</li>
 			<li>Bring up USB (controllers, HID, USB NICs/WiFi/disks) non-preemptibly, as before the WM existed; probe the NIC, restore retained network config, start the kworker.</li>

+ 2 - 2
docs/development.html

@@ -344,7 +344,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 	<section id="tests">
 	<section id="tests">
 		<h2>Tests</h2>
 		<h2>Tests</h2>
 		<ul>
 		<ul>
-			<li><strong>USB regression.</strong> <code>make test-usb</code> runs QMP cursor and keyboard tests against UHCI, OHCI, EHCI and xHCI, including hotplug.</li>
+			<li><strong>USB regression.</strong> <code>make test-usb</code> runs QMP cursor and keyboard tests against UHCI, OHCI, EHCI and xHCI, including hotplug, a two-controller xHCI setup and a mouse behind a USB2 hub on the second controller.</li>
 			<li><strong>Installer.</strong> <code>make test-install</code> boots the dual image with its USB mass-storage source and a blank target, types <code>install ide1</code> through QMP, verifies the clone and boots the target in BIOS and (under OVMF) UEFI.</li>
 			<li><strong>Installer.</strong> <code>make test-install</code> boots the dual image with its USB mass-storage source and a blank target, types <code>install ide1</code> through QMP, verifies the clone and boots the target in BIOS and (under OVMF) UEFI.</li>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
@@ -365,7 +365,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 		<ul>
 		<ul>
 			<li><strong>Serial log.</strong> <code>make monitor</code> shows the boot trace and printf-style driver output. The <code>NebOS v… booted</code> line is written before the framebuffer is ready.</li>
 			<li><strong>Serial log.</strong> <code>make monitor</code> shows the boot trace and printf-style driver output. The <code>NebOS v… booted</code> line is written before the framebuffer is ready.</li>
 			<li><strong>Boot time.</strong> Timestamp COM1 on the host (QEMU <code>-serial stdio</code>): the kernel starts at <code>NebOS v… booted</code>, the desktop at <code>wm: first frame</code>, and the terminal is on screen at <code>wm: first window frame (term) at N ms</code> (kernel uptime; the <code>bootscan</code> window presents just before it and is not counted).  On QEMU the USB image reaches it about 0.5 s after the kernel starts; USB, the NIC and the disks are probed after that (<code>[boot] usb/net/storage</code> lines).</li>
 			<li><strong>Boot time.</strong> Timestamp COM1 on the host (QEMU <code>-serial stdio</code>): the kernel starts at <code>NebOS v… booted</code>, the desktop at <code>wm: first frame</code>, and the terminal is on screen at <code>wm: first window frame (term) at N ms</code> (kernel uptime; the <code>bootscan</code> window presents just before it and is not counted).  On QEMU the USB image reaches it about 0.5 s after the kernel starts; USB, the NIC and the disks are probed after that (<code>[boot] usb/net/storage</code> lines).</li>
-			<li><strong>No serial port.</strong> The boot console is the early log. After the desktop, <code>bootlog</code> prints the captured text and <code>bootlog save /usb0p3/BOOTLOG.TXT</code> writes it to the live stick's FAT ESP (mount that partition on the host to read it). Once DHCP works, <code>make netmon</code> mirrors serial and terminal output to UDP 19290, so it becomes the serial console.</li>
+			<li><strong>No serial port.</strong> The boot console is the early log. After the desktop, <code>bootlog</code> prints the captured text and <code>bootlog save /usb0p3/BOOTLOG.TXT</code> writes it to the live stick's FAT ESP (mount that partition on the host to read it).  <code>seriallog show</code> prints only the always-on COM1 capture's <code>xhci</code>/<code>usb</code>/<code>touchpad</code> lines on screen, which works even when no USB volume is mounted; <code>seriallog save /usb0p3/USBLOG.TXT</code> writes the full capture instead.  The capture includes the xHCI init/Address Device failure lines for both controllers and the touchpad probe's LPSS/PMECTRL/pad diagnostics; run <code>touchpad probe</code> first.  Once DHCP works, <code>make netmon</code> mirrors serial and terminal output to UDP 19290, so it becomes the serial console.</li>
 			<li><strong>Network console.</strong> <code>make netmon</code> listens to UDP 19290 for serial and terminal output; <code>netconsole host &lt;ip&gt;</code> narrows the target.</li>
 			<li><strong>Network console.</strong> <code>make netmon</code> listens to UDP 19290 for serial and terminal output; <code>netconsole host &lt;ip&gt;</code> narrows the target.</li>
 			<li><strong>dbg.</strong> The ring-0 serial monitor accepts <code>r addr len</code>, <code>w addr b0 …</code>, <code>i port</code>, <code>o port val</code>, <code>h</code> and <code>q</code>.</li>
 			<li><strong>dbg.</strong> The ring-0 serial monitor accepts <code>r addr len</code>, <code>w addr b0 …</code>, <code>i port</code>, <code>o port val</code>, <code>h</code> and <code>q</code>.</li>
 			<li><strong>Keys.</strong> <code>keytest</code> drains the raw scancode tap in <span class="file">io.c</span> and prints every byte with its E0-prefix state, make/break kind and decoded <code>IO_KEY_*</code>/ASCII value; Ctrl+C stops it.  It sees releases and keys the decoder ignores, so an unknown action-row key is easy to identify.</li>
 			<li><strong>Keys.</strong> <code>keytest</code> drains the raw scancode tap in <span class="file">io.c</span> and prints every byte with its E0-prefix state, make/break kind and decoded <code>IO_KEY_*</code>/ASCII value; Ctrl+C stops it.  It sees releases and keys the decoder ignores, so an unknown action-row key is easy to identify.</li>

+ 24 - 6
docs/drivers.html

@@ -291,7 +291,7 @@
 					<tr><td>UHCI</td><td>PCI I/O ports</td><td>1</td><td>Frame list at <code>0x3000</code>; control QH plus one QH per interrupt slot.</td></tr>
 					<tr><td>UHCI</td><td>PCI I/O ports</td><td>1</td><td>Frame list at <code>0x3000</code>; control QH plus one QH per interrupt slot.</td></tr>
 					<tr><td>OHCI</td><td>PCI MMIO</td><td>up to 4</td><td>HCCA from the page allocator, static ED/TD sets in the uncacheable <code>ohci_dma_page</code>, TDs start at <code>CC = NotAccessed</code>. Before reset it requests SMM ownership (<code>HcCommandStatus.OCR</code>, clear <code>HcControl.IR</code>) and disables the AMD southbridge USB SMI on <code>1002:4385</code>.</td></tr>
 					<tr><td>OHCI</td><td>PCI MMIO</td><td>up to 4</td><td>HCCA from the page allocator, static ED/TD sets in the uncacheable <code>ohci_dma_page</code>, TDs start at <code>CC = NotAccessed</code>. Before reset it requests SMM ownership (<code>HcCommandStatus.OCR</code>, clear <code>HcControl.IR</code>) and disables the AMD southbridge USB SMI on <code>1002:4385</code>.</td></tr>
 					<tr><td>EHCI</td><td>PCI MMIO</td><td>up to 4</td><td>Async QH/qTD schedule, page-allocated descriptors, polling only, no periodic list. The async-advance doorbell (<code>IAAD</code>) is rung after an idle gap and before cancelling a stuck transfer; the MCP79 can otherwise keep a halted QH's old qTD cached and never fetch a USB disk's first read after enumeration. A bulk-IN qTD is armed with exactly the starting call's length and is not pre-armed for a later chunk, so a device that ends a 512-byte sector transfer without a zero-length packet still completes.</td></tr>
 					<tr><td>EHCI</td><td>PCI MMIO</td><td>up to 4</td><td>Async QH/qTD schedule, page-allocated descriptors, polling only, no periodic list. The async-advance doorbell (<code>IAAD</code>) is rung after an idle gap and before cancelling a stuck transfer; the MCP79 can otherwise keep a halted QH's old qTD cached and never fetch a USB disk's first read after enumeration. A bulk-IN qTD is armed with exactly the starting call's length and is not pre-armed for a later chunk, so a device that ends a 512-byte sector transfer without a zero-length packet still completes.</td></tr>
-					<tr><td>xHCI</td><td>PCI MMIO</td><td>—</td><td>USB2 and USB3 root ports; direct SuperSpeed devices use a 512-byte EP0 and the port speed in the slot context (USB3 hubs are not decoded). Halts and waits for <code>HCH</code> around <code>HCRST</code>; EP0 max packet is the speed's fixed value (8/64/512), and a full-speed EP0 is corrected with Evaluate Context after the first descriptor read (the VIA VL805 on the 970A-DS3P babbled on a high-speed stick otherwise); a SuperSpeed port is not PED-disabled before its reset; failed control transfers are always logged with their completion code; EP0 stages are encoded as one TD per stage (EDK2 style) because chained control TDs stall on Braswell.</td></tr>
+					<tr><td>xHCI</td><td>PCI MMIO</td><td>up to 2</td><td>USB2 and USB3 root ports, and USB2 hubs via the xHCI route string; the slot context also carries the parent hub's TT slot/port for a low/full-speed device behind a high-speed hub (the <code>tt_info</code> dword) and the device's own speed (the root port runs at the hub's upstream speed). A hub slot is moved to Configured with a slot-only Configure Endpoint after Address Device; <code>SET_CONFIGURATION</code> alone leaves the xHC slot Addressed and a downstream TT Address Device fails with Parameter Error. The Yoga's Lenovo hub is on the Alpine Ridge USB-C/Thunderbolt controller (PCI <code>3e:00.0</code>), which is the second instance. Direct SuperSpeed devices use a 512-byte EP0 and the port speed in the slot context (USB3 hub port-status decoding is not implemented). Each instance has its own page-allocated state; halts and waits for <code>HCH</code> around <code>HCRST</code>; EP0 max packet is the speed's fixed value (8/64/512), and a full-speed EP0 is corrected with Evaluate Context after the first descriptor read (the VIA VL805 on the 970A-DS3P babbled on a high-speed stick otherwise); a SuperSpeed port is not PED-disabled before its reset; failed control transfers are always logged with their completion code; EP0 stages are encoded as one TD per stage (EDK2 style) because chained control TDs stall on Braswell.</td></tr>
 				</tbody>
 				</tbody>
 			</table>
 			</table>
 		</div>
 		</div>
@@ -553,6 +553,7 @@
 		</p>
 		</p>
 		<ul>
 		<ul>
 			<li><strong>Mouse.</strong> Three-byte boot reports: buttons in <code>b0 &amp; 7</code>, signed <code>dx/dy</code>. HID's +y is flipped to the PS/2 convention.</li>
 			<li><strong>Mouse.</strong> Three-byte boot reports: buttons in <code>b0 &amp; 7</code>, signed <code>dx/dy</code>. HID's +y is flipped to the PS/2 convention.</li>
+			<li><strong>Logitech Unifying receiver.</strong> The <code>046d:c52b</code> receiver's interface 2 is a vendor HID++/DJ channel. <span class="file">usbhid.c</span> claims it and decodes the paired device's DJ reports: report type 2 carries a 16-button, 12-bit X/Y, wheel and pan mouse report. Unlike Linux's <code>hid-logitech-dj</code> it does not send the HID++ switch command: a receiver in boot mode carries reports on the boot mouse interface (1), while one already in DJ mode (the warm-reboot case after Linux used it) sends DJ reports directly. The receiver's USB path is the second xHCI (the Lenovo USB-C hub), so both the controller and the DJ decode are needed for the M705.</li>
 			<li><strong>Keyboard.</strong> Eight-byte boot reports (modifier + six keycodes). Reports are diffed and decoded through a HID-usage → scancode-set-1 table, then injected with <code>io_inject_scancode()</code>.</li>
 			<li><strong>Keyboard.</strong> Eight-byte boot reports (modifier + six keycodes). Reports are diffed and decoded through a HID-usage → scancode-set-1 table, then injected with <code>io_inject_scancode()</code>.</li>
 			<li><strong>Repeat.</strong> A boot keyboard only reports changes, so <code>io.c</code> adds software typematic repeat (500 ms delay, 33 ms rate).</li>
 			<li><strong>Repeat.</strong> A boot keyboard only reports changes, so <code>io.c</code> adds software typematic repeat (500 ms delay, 33 ms rate).</li>
 			<li><strong>PS/2.</strong> The i8042 path shares the cursor and keyboard code; the BIOS legacy USB emulation is disabled because the kernel owns the devices.</li>
 			<li><strong>PS/2.</strong> The i8042 path shares the cursor and keyboard code; the BIOS legacy USB emulation is disabled because the kernel owns the devices.</li>
@@ -577,7 +578,18 @@
 			functions, enables their memory decode and puts them in D0
 			functions, enables their memory decode and puts them in D0
 			first (the firmware leaves the command register at 0, which
 			first (the firmware leaves the command register at 0, which
 			Linux logs as <em>enabling device (0000 -&gt; 0002)</em>),
 			Linux logs as <em>enabling device (0000 -&gt; 0002)</em>),
-			maps their BARs. <span class="file">i2c.c</span> drives either
+			clears the LPSS <code>PMECTRLSTATUS</code> at PCI config
+			<code>0x84</code> (the DSDT <code>LPD0(SB10)</code> target;
+			the PMC <code>PWRMBASE + 0x84</code> address is a different
+			register and leaves the I2C FSM power-gated), enables the
+			LPSS functional clock at private <code>0x200</code>
+			(gate + M=6/N=5 for the 120 MHz I2C clock; the BIOS leaves
+			unused LPSS blocks gated and the register file still answers
+			while the FSM does not drive the bus), maps their BARs.
+			The BIOS already leaves GPP_C16/C17 in native function 1
+			(Linux's <code>pins</code> output shows
+			<code>mode 1 0x84000702 0x58</code>), so the kernel does not
+			rewrite the pads. <span class="file">i2c.c</span> drives either
 			controller in fast mode, polled and without interrupts.
 			controller in fast mode, polled and without interrupts.
 		</p>
 		</p>
 		<ul>
 		<ul>
@@ -594,7 +606,9 @@
 			(<code>0x0106</code>/<code>0x0107</code>) give the corner zone a
 			(<code>0x0106</code>/<code>0x0107</code>) give the corner zone a
 			physical coordinate frame; the Synaptics frame is 1219 x 799.
 			physical coordinate frame; the Synaptics frame is 1219 x 799.
 			<code>touchpad probe</code> reruns the probe and prints the LPSS
 			<code>touchpad probe</code> reruns the probe and prints the LPSS
-			PCI id/BAR/command, component type and private registers when it
+			PCI id/BAR/command, component type, the <code>0x200</code>
+			clock and <code>0x204</code> reset registers, and
+			<code>PMECTRLSTATUS</code> before/after the clear when it
 			fails.</li>
 			fails.</li>
 			<li><strong>Reports.</strong> The Elan vendor report <code>0x5D</code>
 			<li><strong>Reports.</strong> The Elan vendor report <code>0x5D</code>
 			carries a finger bitmask and five packed bytes per active finger
 			carries a finger bitmask and five packed bytes per active finger
@@ -662,7 +676,11 @@
 			tick and froze the boot after <code>[process]</code>. The boot console
 			tick and froze the boot after <code>[process]</code>. The boot console
 			and netlog mirrors are still fed before the dead check.
 			and netlog mirrors are still fed before the dead check.
 			<code>serial_puthex</code> and <code>serial_putdec</code> are the
 			<code>serial_puthex</code> and <code>serial_putdec</code> are the
-			structured dump helpers used by drivers.
+			structured dump helpers used by drivers.  Every COM1 character is
+			also appended to an always-on 64 KB ring (even when the UART is
+			absent); <code>seriallog save &lt;path&gt;</code> writes it to a
+			file.  On the Yoga, save it on the USB ESP and read the xHCI/USB
+			trace from Linux.
 		</p>
 		</p>
 	</section>
 	</section>
 
 
@@ -748,8 +766,8 @@
 		<ul>
 		<ul>
 			<li><strong>Polling.</strong> USB, storage and network drivers consume CPU time while waiting; there is no IRQ-driven data path outside PS/2, serial and the PIT.</li>
 			<li><strong>Polling.</strong> USB, storage and network drivers consume CPU time while waiting; there is no IRQ-driven data path outside PS/2, serial and the PIT.</li>
 			<li><strong>EHCI.</strong> High-speed root ports only; no split transactions for low/full-speed devices behind a high-speed hub.</li>
 			<li><strong>EHCI.</strong> High-speed root ports only; no split transactions for low/full-speed devices behind a high-speed hub.</li>
-			<li><strong>xHCI.</strong> USB2 and USB3 root ports; direct SuperSpeed devices work, but USB3 hub port-status decoding is not implemented.</li>
-			<li><strong>HID.</strong> Report IDs are not handled, absolute pointers/tablets are ignored, and there is no wheel support.</li>
+			<li><strong>xHCI.</strong> USB2 and USB3 root ports; USB2 hubs behind xHCI work through the route string (a QEMU hub+mouse cursor test covers it), but USB3 hub port-status decoding is not implemented.</li>
+			<li><strong>HID.</strong> Generic report IDs are not handled (a device that prepends report IDs decodes as garbage; the Logitech Unifying DJ receiver is decoded explicitly), absolute pointers/tablets are ignored, and boot mice have no wheel (the DJ path maps it).</li>
 			<li><strong>AHCI.</strong> First controller only, no hotplug after boot, disks above 2 TB are clamped to 32-bit LBA.</li>
 			<li><strong>AHCI.</strong> First controller only, no hotplug after boot, disks above 2 TB are clamped to 32-bit LBA.</li>
 			<li><strong>eMMC.</strong> Polled 1-bit/25 MHz PIO; no DMA, IRQ, CMD6 bus-width/high-speed/DDR switch or hotplug. Only the eMMC function is driven; the SDIO/SD functions and SD card reader are not.</li>
 			<li><strong>eMMC.</strong> Polled 1-bit/25 MHz PIO; no DMA, IRQ, CMD6 bus-width/high-speed/DDR switch or hotplug. Only the eMMC function is driven; the SDIO/SD functions and SD card reader are not.</li>
 			<li><strong>Storage serialization.</strong> A FAT/floppy operation sets <code>sys_fs_busy</code> and stalls process switching for its duration; the PIT keeps ticking.</li>
 			<li><strong>Storage serialization.</strong> A FAT/floppy operation sets <code>sys_fs_busy</code> and stalls process switching for its duration; the PIT keeps ticking.</li>

+ 43 - 0
kernel/bootcon.c

@@ -42,6 +42,12 @@ static unsigned int log_cap;
 static unsigned int log_len;
 static unsigned int log_len;
 static int log_truncated;
 static int log_truncated;
 
 
+/* Always-on COM1 log (the `seriallog save` source). */
+static char *serlog_buf;
+static unsigned int serlog_cap;
+static unsigned int serlog_len;
+static int serlog_truncated;
+
 /* Serial output of the bootscan kernel thread (bootcon_scan_begin). */
 /* Serial output of the bootscan kernel thread (bootcon_scan_begin). */
 static char *scan_buf;
 static char *scan_buf;
 static unsigned int scan_cap;
 static unsigned int scan_cap;
@@ -210,6 +216,17 @@ void bootcon_log_init(void)
 {
 {
 	unsigned int mem;
 	unsigned int mem;
 
 
+	if (!serlog_buf) {
+		mem = mm_alloc_pages(BOOTCON_SERLOG_PAGES);
+		if (mem) {
+			serlog_buf = (char *)mem;
+			serlog_cap = BOOTCON_SERLOG_PAGES * PAGE_SIZE;
+			serlog_len = 0;
+			serlog_truncated = 0;
+			serlog_buf[0] = '\0';
+		}
+	}
+
 	if (log_buf)
 	if (log_buf)
 		return;
 		return;
 	mem = mm_alloc_pages(BOOTCON_LOG_PAGES);
 	mem = mm_alloc_pages(BOOTCON_LOG_PAGES);
@@ -267,6 +284,32 @@ int bootcon_log_truncated(void)
 	return log_truncated;
 	return log_truncated;
 }
 }
 
 
+/* Every COM1 character, independent of the bootscan thread and of whether
+ * the UART itself answered.  `seriallog save` writes this to a file on the
+ * USB ESP so a serial-less board can be debugged from Linux. */
+void bootcon_serlog_char(char c)
+{
+	if (!serlog_buf)
+		return;
+	if (serlog_len + 1 < serlog_cap) {
+		serlog_buf[serlog_len++] = c;
+		serlog_buf[serlog_len] = '\0';
+	} else {
+		serlog_truncated = 1;
+	}
+}
+
+const char *bootcon_serlog(unsigned int *len)
+{
+	*len = serlog_len;
+	return serlog_buf ? serlog_buf : "";
+}
+
+int bootcon_serlog_truncated(void)
+{
+	return serlog_truncated;
+}
+
 /* ---- bootscan thread serial capture ---------------------------------- */
 /* ---- bootscan thread serial capture ---------------------------------- */
 
 
 void bootcon_scan_begin(void)
 void bootcon_scan_begin(void)

+ 10 - 0
kernel/bootcon.h

@@ -16,6 +16,9 @@
 /* Ring for the storage scan thread's own serial output (see bootcon.c).  It
 /* Ring for the storage scan thread's own serial output (see bootcon.c).  It
  * is allocated on demand from the frame allocator, not BSS. */
  * is allocated on demand from the frame allocator, not BSS. */
 #define BOOTCON_SCAN_PAGES 4
 #define BOOTCON_SCAN_PAGES 4
+/* Always-on COM1 capture used by `seriallog save` on serial-less boards.
+ * The xHCI/USB/touchpad debug lines go here even though the UART is absent. */
+#define BOOTCON_SERLOG_PAGES 16
 
 
 void bootcon_init(void);
 void bootcon_init(void);
 int  bootcon_ok(void);
 int  bootcon_ok(void);
@@ -55,4 +58,11 @@ int bootcon_scan_running(void);
  * oldest byte still in the ring.  Returns the byte count. */
  * oldest byte still in the ring.  Returns the byte count. */
 unsigned int bootcon_scan_read(unsigned int off, char *dst, unsigned int max);
 unsigned int bootcon_scan_read(unsigned int off, char *dst, unsigned int max);
 
 
+/* Always-on COM1 log (independent of the bootscan thread).  It starts at
+ * bootcon_log_init() and keeps the first BOOTCON_SERLOG_PAGES pages of
+ * serial output; later output is dropped after the buffer fills. */
+void bootcon_serlog_char(char c);
+const char *bootcon_serlog(unsigned int *len);
+int bootcon_serlog_truncated(void);
+
 #endif
 #endif

+ 7 - 2
kernel/ehci.c

@@ -749,7 +749,7 @@ static void ehci_int_in_stop(unsigned int slot)
 
 
 static int ehci_int_in_start(unsigned int ctrl, unsigned int slot,
 static int ehci_int_in_start(unsigned int ctrl, unsigned int slot,
 			     unsigned int addr, unsigned int ep,
 			     unsigned int addr, unsigned int ep,
-			     unsigned int mps, int low_speed)
+			     unsigned int mps, unsigned int len, int low_speed)
 {
 {
 	struct ehci_ctrl *c;
 	struct ehci_ctrl *c;
 	struct ehci_int *in;
 	struct ehci_int *in;
@@ -766,7 +766,11 @@ static int ehci_int_in_start(unsigned int ctrl, unsigned int slot,
 	in->mps = mps ? mps : 8;
 	in->mps = mps ? mps : 8;
 	if (in->mps > 1024)
 	if (in->mps > 1024)
 		in->mps = 1024;
 		in->mps = 1024;
-	in->buf_len = in->mps > 64 ? 64 : in->mps;
+	if (!len)
+		len = in->mps;
+	if (len > USB_INT_MAX)
+		len = USB_INT_MAX;
+	in->buf_len = len;
 
 
 	qh_init(in->qh);
 	qh_init(in->qh);
 	in->qh->info1 = QH_DEVADDR(addr) | QH_ENDPT(ep) | QH_EPS_HIGH |
 	in->qh->info1 = QH_DEVADDR(addr) | QH_ENDPT(ep) | QH_EPS_HIGH |
@@ -1556,4 +1560,5 @@ const struct usb_hcd_ops usb_ehci_ops = {
 	ehci_bulk_in,
 	ehci_bulk_in,
 	ehci_bulk_reset,
 	ehci_bulk_reset,
 	ehci_print_ports,
 	ehci_print_ports,
+	0,
 };
 };

+ 51 - 1
kernel/i2c.c

@@ -12,6 +12,7 @@
  * explicit assert/release cycle, so i2c_dw_init() always does one. */
  * explicit assert/release cycle, so i2c_dw_init() always does one. */
 
 
 #include "i2c.h"
 #include "i2c.h"
+#include "serial.h"
 #include "timer.h"
 #include "timer.h"
 
 
 #define DW_IC_CON		0x00
 #define DW_IC_CON		0x00
@@ -33,6 +34,7 @@
 #define DW_IC_RXFLR		0x78
 #define DW_IC_RXFLR		0x78
 #define DW_IC_ENABLE_STATUS	0x9c
 #define DW_IC_ENABLE_STATUS	0x9c
 #define DW_IC_FS_SPKLEN		0xa0
 #define DW_IC_FS_SPKLEN		0xa0
+#define DW_IC_SDA_HOLD		0x7c
 #define DW_IC_COMP_VERSION	0xf8
 #define DW_IC_COMP_VERSION	0xf8
 #define DW_IC_COMP_TYPE		0xfc
 #define DW_IC_COMP_TYPE		0xfc
 #define DW_IC_COMP_TYPE_VALUE	0x44570140u
 #define DW_IC_COMP_TYPE_VALUE	0x44570140u
@@ -48,7 +50,7 @@
 #define IC_DATA_CMD_RESTART	0x00000400u
 #define IC_DATA_CMD_RESTART	0x00000400u
 
 
 #define IC_STATUS_TFNF		0x00000002u
 #define IC_STATUS_TFNF		0x00000002u
-#define IC_STATUS_RFNE		0x00000004u
+#define IC_STATUS_RFNE		0x00000008u
 #define IC_STATUS_TFE		0x00000004u
 #define IC_STATUS_TFE		0x00000004u
 #define IC_STATUS_MST_ACTIVITY	0x00000020u
 #define IC_STATUS_MST_ACTIVITY	0x00000020u
 
 
@@ -134,6 +136,49 @@ int i2c_dw_present(unsigned int base)
 	return i2c_dw_comp_type(base) == DW_IC_COMP_TYPE_VALUE;
 	return i2c_dw_comp_type(base) == DW_IC_COMP_TYPE_VALUE;
 }
 }
 
 
+void i2c_dw_dump(unsigned int base)
+{
+	serial_puts(SERIAL_COM1, "touchpad: i2c con=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_CON));
+	serial_puts(SERIAL_COM1, " tar=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_TAR));
+	serial_puts(SERIAL_COM1, " status=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_STATUS));
+	serial_puts(SERIAL_COM1, " en=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_ENABLE));
+	serial_puts(SERIAL_COM1, " enst=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_ENABLE_STATUS));
+	serial_puts(SERIAL_COM1, " abrt=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_TX_ABRT_SOURCE));
+	serial_puts(SERIAL_COM1, " sda=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_SDA_HOLD));
+	serial_puts(SERIAL_COM1, " spk=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_FS_SPKLEN));
+	serial_puts(SERIAL_COM1, " ss=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_SS_SCL_HCNT));
+	serial_putc(SERIAL_COM1, '/');
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_SS_SCL_LCNT));
+	serial_puts(SERIAL_COM1, " fs=");
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_FS_SCL_HCNT));
+	serial_putc(SERIAL_COM1, '/');
+	serial_puthex(SERIAL_COM1, dw_rd(base, DW_IC_FS_SCL_LCNT));
+	serial_putc(SERIAL_COM1, '\n');
+}
+
+void i2c_dw_clock_spt(unsigned int base)
+{
+	/* LPSS private 0x200: bit 0 gates the functional clock, bits 1..15
+	 * are the M divider, bits 16..30 the N divider, bit 31 updates the
+	 * divider.  With the gate off the DesignWare register file still
+	 * answers (the component type reads) but the I2C FSM never drives
+	 * the bus.  Linux's intel-lpss enables it before the device probe;
+	 * the BIOS leaves unused LPSS blocks gated.  SPT-LP runs the LPSS
+	 * clock at 120 MHz with the unity divider (the clk_summary shows
+	 * 120000000 for i2c_designware.0 pclk), so M=N=1. */
+	dw_wr(base, 0x200, 0x80010003u);
+	dw_delay_ms(1);
+}
+
 int i2c_dw_init(unsigned int base)
 int i2c_dw_init(unsigned int base)
 {
 {
 	unsigned int t0;
 	unsigned int t0;
@@ -158,6 +203,11 @@ int i2c_dw_init(unsigned int base)
 	dw_wr(base, DW_IC_FS_SCL_HCNT, 112);
 	dw_wr(base, DW_IC_FS_SCL_HCNT, 112);
 	dw_wr(base, DW_IC_FS_SCL_LCNT, 211);
 	dw_wr(base, DW_IC_FS_SCL_LCNT, 211);
 	dw_wr(base, DW_IC_FS_SPKLEN, 1);
 	dw_wr(base, DW_IC_FS_SPKLEN, 1);
+	/* Sunrise Point-LP declares an i2c-sda-hold-time-ns of 230; at
+	 * 120 MHz that is ~28 IC clocks.  The Synaptics touchpad NAKs its
+	 * address without a hold time, while the Braswell Elan tolerates
+	 * the reset value. */
+	dw_wr(base, DW_IC_SDA_HOLD, 30);
 	dw_wr(base, DW_IC_RX_TL, 0);
 	dw_wr(base, DW_IC_RX_TL, 0);
 	dw_wr(base, DW_IC_TX_TL, 0);
 	dw_wr(base, DW_IC_TX_TL, 0);
 	dw_clear_irq(base);
 	dw_clear_irq(base);

+ 7 - 0
kernel/i2c.h

@@ -16,6 +16,13 @@ extern unsigned int i2c_last_abort;
 /* Raw component-type / reset-release access for the LPSS scan. */
 /* Raw component-type / reset-release access for the LPSS scan. */
 unsigned int i2c_dw_comp_type(unsigned int base);
 unsigned int i2c_dw_comp_type(unsigned int base);
 void i2c_dw_reset_release(unsigned int base);
 void i2c_dw_reset_release(unsigned int base);
+/* Sunrise Point-LP only: enable the LPSS functional clock gate and set
+ * the fractional divider (0x200).  The BIOS leaves it off for unused
+ * LPSS blocks; the register file still answers, but the I2C FSM does not
+ * drive the bus. */
+void i2c_dw_clock_spt(unsigned int base);
+/* One-line controller register dump for the seriallog. */
+void i2c_dw_dump(unsigned int base);
 
 
 /* Combined write + repeated-start read, the form HID-over-I2C uses for
 /* Combined write + repeated-start read, the form HID-over-I2C uses for
  * register-addressed transfers.  Either buffer may be empty. */
  * register-addressed transfers.  Either buffer may be empty. */

+ 11 - 4
kernel/ohci.c

@@ -143,8 +143,9 @@ struct ohci_ctrl {
 	struct ohci_ed int_ed[USB_HCD_INT_SLOTS];
 	struct ohci_ed int_ed[USB_HCD_INT_SLOTS];
 	struct ohci_td int_td[USB_HCD_INT_SLOTS];
 	struct ohci_td int_td[USB_HCD_INT_SLOTS];
 	struct ohci_td int_dummy[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 char int_buf[USB_HCD_INT_SLOTS][USB_INT_MAX] __attribute__((aligned(16)));
 	unsigned int int_mps[USB_HCD_INT_SLOTS];
 	unsigned int int_mps[USB_HCD_INT_SLOTS];
+	unsigned int int_len[USB_HCD_INT_SLOTS];
 	unsigned int int_toggle[USB_HCD_INT_SLOTS];
 	unsigned int int_toggle[USB_HCD_INT_SLOTS];
 	int int_armed[USB_HCD_INT_SLOTS];
 	int int_armed[USB_HCD_INT_SLOTS];
 };
 };
@@ -752,7 +753,7 @@ static void ohci_int_arm(struct ohci_ctrl *c, unsigned int slot)
 	c->int_td[slot].cbp = (unsigned int)c->int_buf[slot];
 	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].next = (unsigned int)&c->int_dummy[slot];
 	c->int_td[slot].be = (unsigned int)c->int_buf[slot] +
 	c->int_td[slot].be = (unsigned int)c->int_buf[slot] +
-			     c->int_mps[slot] - 1;
+			     c->int_len[slot] - 1;
 
 
 	/* Publish the TD before the ED points at it, and the new head before
 	/* Publish the TD before the ED points at it, and the new head before
 	 * the controller's next pass. */
 	 * the controller's next pass. */
@@ -768,7 +769,7 @@ static void ohci_int_arm(struct ohci_ctrl *c, unsigned int slot)
 
 
 static int ohci_int_in_start(unsigned int ctrl, unsigned int slot,
 static int ohci_int_in_start(unsigned int ctrl, unsigned int slot,
 			     unsigned int addr, unsigned int ep,
 			     unsigned int addr, unsigned int ep,
-			     unsigned int mps, int low_speed)
+			     unsigned int mps, unsigned int len, int low_speed)
 {
 {
 	struct ohci_ctrl *c;
 	struct ohci_ctrl *c;
 
 
@@ -779,6 +780,11 @@ static int ohci_int_in_start(unsigned int ctrl, unsigned int slot,
 	ohci_int_in_stop(slot);
 	ohci_int_in_stop(slot);
 
 
 	c->int_mps[slot] = mps ? mps : 8;
 	c->int_mps[slot] = mps ? mps : 8;
+	if (!len)
+		len = c->int_mps[slot];
+	if (len > USB_INT_MAX)
+		len = USB_INT_MAX;
+	c->int_len[slot] = len;
 	c->int_ed[slot].flags = ED_FA(addr) | ED_EN(ep) |
 	c->int_ed[slot].flags = ED_FA(addr) | ED_EN(ep) |
 				ED_MPS(c->int_mps[slot]) |
 				ED_MPS(c->int_mps[slot]) |
 				(low_speed ? ED_S : 0);
 				(low_speed ? ED_S : 0);
@@ -834,7 +840,7 @@ static int ohci_int_in_poll(unsigned int slot, unsigned char *buf,
 
 
 	n = c->int_td[slot].cbp
 	n = c->int_td[slot].cbp
 		? (c->int_td[slot].cbp - (unsigned int)c->int_buf[slot])
 		? (c->int_td[slot].cbp - (unsigned int)c->int_buf[slot])
-		: c->int_mps[slot];
+		: c->int_len[slot];
 	if (n > len)
 	if (n > len)
 		n = len;
 		n = len;
 	for (i = 0; i < n; i++)
 	for (i = 0; i < n; i++)
@@ -881,4 +887,5 @@ const struct usb_hcd_ops usb_ohci_ops = {
 	0,
 	0,
 	0,
 	0,
 	0,
 	0,
+	0,
 };
 };

+ 1 - 0
kernel/serial.c

@@ -49,6 +49,7 @@ void serial_putc(unsigned int port, char c)
 	 * the ones that use netlog. */
 	 * the ones that use netlog. */
 	if (port == SERIAL_COM1) {
 	if (port == SERIAL_COM1) {
 		bootcon_scan_char(c);
 		bootcon_scan_char(c);
+		bootcon_serlog_char(c);
 		netlog_char(c);
 		netlog_char(c);
 	}
 	}
 
 

+ 86 - 1
kernel/terminal.c

@@ -61,6 +61,7 @@ struct kcmd {
 /* The terminal's spawn/path helpers are defined later in this file. */
 /* The terminal's spawn/path helpers are defined later in this file. */
 
 
 static int cmd_bootlog(struct term *t, const char *args);
 static int cmd_bootlog(struct term *t, const char *args);
+static int cmd_seriallog(struct term *t, const char *args);
 static int cmd_acpidump(struct term *t, const char *args);
 static int cmd_acpidump(struct term *t, const char *args);
 static int cmd_dbg(struct term *t, const char *args);
 static int cmd_dbg(struct term *t, const char *args);
 static int cmd_format(struct term *t, const char *args);
 static int cmd_format(struct term *t, const char *args);
@@ -84,6 +85,7 @@ static int cmd_serial(struct term *t, const char *args);
 static const struct kcmd cmds[] = {
 static const struct kcmd cmds[] = {
 	{ "help",       "help",                          CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_help },
 	{ "help",       "help",                          CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_help },
 	{ "bootlog",    "bootlog",                       CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_bootlog },
 	{ "bootlog",    "bootlog",                       CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_bootlog },
+	{ "seriallog",  "seriallog save <path>|show",    CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_seriallog },
 	{ "acpidump",   "acpidump",                      CK_CUSTOM, 0, 0, 0, 0, cmd_acpidump },
 	{ "acpidump",   "acpidump",                      CK_CUSTOM, 0, 0, 0, 0, cmd_acpidump },
 	{ "reboot",     "reboot",                        CK_CUSTOM, 0, 0, 0, 0, cmd_reboot },
 	{ "reboot",     "reboot",                        CK_CUSTOM, 0, 0, 0, 0, cmd_reboot },
 	{ "poweroff",   "poweroff",                      CK_SPAWN_ARG, 0, 0, program_poweroff_main, 0, 0 },
 	{ "poweroff",   "poweroff",                      CK_SPAWN_ARG, 0, 0, program_poweroff_main, 0, 0 },
@@ -214,6 +216,88 @@ static int cmd_bootlog(struct term *t, const char *args)
 	return 0;
 	return 0;
 }
 }
 
 
+/* Save the always-on COM1 capture (xHCI, usbhid, USB errors and explicit
+ * touchpad diagnostics) to a file.  On a serial-less board, write it to the
+ * USB ESP and read it from Linux after a reboot. */
+static int cmd_seriallog(struct term *t, const char *args)
+{
+	const char *p;
+	unsigned int len;
+
+	(void)t;
+	p = bootcon_serlog(&len);
+	while (*args == ' ')
+		args++;
+	if (args[0] == 's' && args[1] == 'h' && args[2] == 'o' &&
+	    args[3] == 'w' && (args[4] == ' ' || args[4] == '\0')) {
+		unsigned int i = 0;
+
+		while (i < len) {
+			unsigned int j = i, k;
+			int show = 0;
+
+			while (j < len && p[j] != '\n')
+				j++;
+			{
+				static const char *const pat[3] = {
+					"xhci", "usbhid", "touchpad"
+				};
+
+				for (k = 0; k < 3; k++) {
+					const char *q = pat[k];
+					unsigned int a, b;
+
+					for (a = i; a < j && !show; a++) {
+						for (b = 0; q[b] &&
+						     a + b < j &&
+						     p[a + b] == q[b]; b++)
+							;
+						if (!q[b])
+							show = 1;
+					}
+				}
+			}
+			if (show) {
+				for (k = i; k < j; k++)
+					if (p[k] != '\r')
+						io_putchar(p[k]);
+				io_putchar('\n');
+			}
+			i = j < len ? j + 1 : j;
+		}
+		if (bootcon_serlog_truncated())
+			io_putstr("seriallog: [truncated]\n");
+		return 0;
+	}
+	if (!(args[0] == 's' && args[1] == 'a' && args[2] == 'v' &&
+	      args[3] == 'e' && (args[4] == ' ' || args[4] == '\0'))) {
+		io_putstr("seriallog: usage seriallog save <path>|show\n");
+		return 0;
+	}
+	{
+		const char *path = args + 4;
+		int r;
+
+		while (*path == ' ')
+			path++;
+		if (!*path) {
+			io_putstr("seriallog: usage seriallog save <path>\n");
+			return 0;
+		}
+		r = sys_write_file(path, p, len);
+		if (r == 0)
+			io_putstr("seriallog saved\n");
+		else {
+			io_putstr("seriallog: save failed (");
+			io_puthex((unsigned int)r);
+			io_putstr(")\n");
+		}
+	}
+	if (bootcon_serlog_truncated())
+		io_putstr("seriallog: [truncated]\n");
+	return 0;
+}
+
 static int cmd_dbg(struct term *t, const char *args)
 static int cmd_dbg(struct term *t, const char *args)
 {
 {
 	(void)t;
 	(void)t;
@@ -753,7 +837,8 @@ int term_kcmd_spawn(const char *name, const char *args, unsigned int tty)
 	int pid;
 	int pid;
 
 
 	if (!c || ((c->flags & CMD_BUILTIN) && c->custom != cmd_help &&
 	if (!c || ((c->flags & CMD_BUILTIN) && c->custom != cmd_help &&
-		   c->custom != cmd_bootlog))
+		   c->custom != cmd_bootlog &&
+		   c->custom != cmd_seriallog))
 		return -1;
 		return -1;
 	ctx = (struct kcmd_ctx *)kmalloc(sizeof(*ctx));
 	ctx = (struct kcmd_ctx *)kmalloc(sizeof(*ctx));
 	if (!ctx)
 	if (!ctx)

+ 86 - 12
kernel/touchpad.c

@@ -30,6 +30,7 @@
 #include "io.h"
 #include "io.h"
 #include "paging.h"
 #include "paging.h"
 #include "pci.h"
 #include "pci.h"
+#include "serial.h"
 #include "timer.h"
 #include "timer.h"
 
 
 #define TP_ADDR			0x15
 #define TP_ADDR			0x15
@@ -53,6 +54,10 @@
 #define TP_SYN_MAX_X		1219
 #define TP_SYN_MAX_X		1219
 #define TP_SYN_MAX_Y		799
 #define TP_SYN_MAX_Y		799
 
 
+/* Sunrise Point-LP GPIO community 1 (GPP_C) and the I2C0 pads.  The
+ * DSDT builds the community windows as SBRG + 0xAE0000 (community 1),
+ * +0xAF0000 (0) and +0xAC0000 (2); P2SB's fixed 16 MB MMIO window on
+ * this PCH starts at 0xFD000000. */
 #define TP_MAX_X_REG		0x0106
 #define TP_MAX_X_REG		0x0106
 #define TP_MAX_Y_REG		0x0107
 #define TP_MAX_Y_REG		0x0107
 #define TP_ABS_MAX		4095
 #define TP_ABS_MAX		4095
@@ -84,6 +89,8 @@ static unsigned int tp_err_val;
 /* Probe diagnostics for `touchpad` when the controller/device is absent. */
 /* Probe diagnostics for `touchpad` when the controller/device is absent. */
 static unsigned int tp_dbg_id, tp_dbg_bar, tp_dbg_cmd, tp_dbg_comp;
 static unsigned int tp_dbg_id, tp_dbg_bar, tp_dbg_cmd, tp_dbg_comp;
 static unsigned int tp_dbg_priv0, tp_dbg_priv4;
 static unsigned int tp_dbg_priv0, tp_dbg_priv4;
+static unsigned int tp_dbg_pmec, tp_dbg_pmec_after;
+static int tp_dbg_seen;
 
 
 static struct tpg_state tp_gesture;
 static struct tpg_state tp_gesture;
 static int tp_last_buttons;
 static int tp_last_buttons;
@@ -373,10 +380,15 @@ static int probe_synaptics(unsigned int base)
 		tp_err = "i2c init failed";
 		tp_err = "i2c init failed";
 		return 0;
 		return 0;
 	}
 	}
+	/* The LPSS reset release at 0x204 clears the 0x200 clock gate, so
+	 * enable the functional clock after it. */
+	i2c_dw_clock_spt(base);
 	tp_base = base;
 	tp_base = base;
 	tp_addr = TP_SYN_ADDR;
 	tp_addr = TP_SYN_ADDR;
-	tp_dbg_priv0 = *(volatile unsigned int *)(base + 0x200);
-	tp_dbg_priv4 = *(volatile unsigned int *)(base + 0x204);
+	if (!tp_dbg_seen) {
+		tp_dbg_priv0 = *(volatile unsigned int *)(base + 0x200);
+		tp_dbg_priv4 = *(volatile unsigned int *)(base + 0x204);
+	}
 
 
 	/* Linux's i2c-hid first checks the address and reads the HID
 	/* Linux's i2c-hid first checks the address and reads the HID
 	 * descriptor; only the report-descriptor stage powers the device on
 	 * descriptor; only the report-descriptor stage powers the device on
@@ -385,6 +397,7 @@ static int probe_synaptics(unsigned int base)
 	if (i2c_dw_transfer(base, tp_addr, 0, 0, ack, 1) != 0) {
 	if (i2c_dw_transfer(base, tp_addr, 0, 0, ack, 1) != 0) {
 		tp_err = "no device at 0x2c";
 		tp_err = "no device at 0x2c";
 		tp_err_val = i2c_last_abort;
 		tp_err_val = i2c_last_abort;
+		i2c_dw_dump(base);
 		return 0;
 		return 0;
 	}
 	}
 	for (i = 0; i < 4; i++) {
 	for (i = 0; i < 4; i++) {
@@ -471,17 +484,27 @@ static int probe_synaptics(unsigned int base)
  * Both steps are no-ops when firmware already did them. */
  * Both steps are no-ops when firmware already did them. */
 static void lpss_pci_prepare(unsigned int dev, unsigned int func)
 static void lpss_pci_prepare(unsigned int dev, unsigned int func)
 {
 {
-	unsigned int cmd, cap, pm;
+	unsigned int cmd, pmcsr;
 
 
 	cmd = pci_cfg_read32(0, dev, func, 0x04) & 0xFFFFu;
 	cmd = pci_cfg_read32(0, dev, func, 0x04) & 0xFFFFu;
 	pci_cfg_write16(0, dev, func, 0x04,
 	pci_cfg_write16(0, dev, func, 0x04,
 			(unsigned short)(cmd | 0x0006u));
 			(unsigned short)(cmd | 0x0006u));
 
 
-	cap = pci_cfg_read32(0, dev, func, 0x34) & 0xFFu;
-	if (cap >= 0x40 && (cap & 3) == 0) {
-		pm = (pci_cfg_read32(0, dev, func, cap) >> 16) & 0xFFFFu;
-		pci_cfg_write16(0, dev, func, cap + 4,
-				(unsigned short)(pm & ~3u));
+	/* The DSDT's I2C0._PS0() is LPD0(SB10), which clears bits 15 and 1
+	 * of the LPSS PMECTRLSTATUS at config offset 0x84 through the P2SB
+	 * alias.  The same register is directly reachable as PCI config
+	 * 0x84.  Writing the PMC's PWRMBASE + 0x84 instead (0xFE000084)
+	 * left the LPSS island power-gated: the DesignWare register file
+	 * answered, but the I2C FSM never drove the bus, so the touchpad
+	 * NAKed its address. */
+	pmcsr = pci_cfg_read32(0, dev, func, 0x84);
+	if (!tp_dbg_seen)
+		tp_dbg_pmec = pmcsr;
+	if (pmcsr != 0xFFFFFFFFu) {
+		pci_cfg_write32(0, dev, func, 0x84, pmcsr & 0xFFFF7FFCu);
+		if (!tp_dbg_seen)
+			tp_dbg_pmec_after = pci_cfg_read32(0, dev, func,
+							   0x84);
 	}
 	}
 	msleep(10);
 	msleep(10);
 }
 }
@@ -542,17 +565,22 @@ int touchpad_init(void)
 		 * while the block is still in functional reset, and the
 		 * while the block is still in functional reset, and the
 		 * I2C FSM never clocks until 0x204 is released. */
 		 * I2C FSM never clocks until 0x204 is released. */
 		i2c_dw_reset_release(base);
 		i2c_dw_reset_release(base);
-		tp_dbg_id = id;
-		tp_dbg_bar = bar;
-		tp_dbg_cmd = pci_cfg_read32(0, 0x15, k, 0x04) & 0xFFFFu;
-		tp_dbg_comp = i2c_dw_comp_type(base);
+		if (!tp_dbg_seen) {
+			tp_dbg_id = id;
+			tp_dbg_bar = bar;
+			tp_dbg_cmd = pci_cfg_read32(0, 0x15, k, 0x04) &
+				     0xFFFFu;
+			tp_dbg_comp = i2c_dw_comp_type(base);
+		}
 		if (!i2c_dw_present(base)) {
 		if (!i2c_dw_present(base)) {
 			tp_err = "LPSS not a DesignWare I2C";
 			tp_err = "LPSS not a DesignWare I2C";
 			tp_err_val = tp_dbg_comp;
 			tp_err_val = tp_dbg_comp;
+			tp_dbg_seen = 1;
 			continue;
 			continue;
 		}
 		}
 		if (probe_synaptics(base))
 		if (probe_synaptics(base))
 			return 1;
 			return 1;
+		tp_dbg_seen = 1;
 	}
 	}
 
 
 	if (!tp_err)
 	if (!tp_err)
@@ -743,10 +771,54 @@ static void print_absent(void)
 		io_puthex(tp_dbg_priv0);
 		io_puthex(tp_dbg_priv0);
 		io_putchar('/');
 		io_putchar('/');
 		io_puthex(tp_dbg_priv4);
 		io_puthex(tp_dbg_priv4);
+		io_putstr(" pmec ");
+		io_puthex(tp_dbg_pmec);
+		io_putchar('/');
+		io_puthex(tp_dbg_pmec_after);
 		io_putchar('\n');
 		io_putchar('\n');
 	}
 	}
 }
 }
 
 
+static void tp_serial_status(void)
+{
+	serial_puts(SERIAL_COM1, "touchpad: ");
+	if (tp_present) {
+		serial_puts(SERIAL_COM1, tp_kind == TP_KIND_SYNAPTICS ?
+				   "present synaptics " : "present elan ");
+		serial_puthex(SERIAL_COM1, tp_vendor);
+		serial_putc(SERIAL_COM1, ':');
+		serial_puthex(SERIAL_COM1, tp_product);
+		serial_puts(SERIAL_COM1, " i2c 0x");
+		serial_puthex(SERIAL_COM1, tp_base);
+		serial_puts(SERIAL_COM1, " addr 0x");
+		serial_puthex(SERIAL_COM1, tp_addr);
+	} else {
+		serial_puts(SERIAL_COM1, "absent ");
+		serial_puts(SERIAL_COM1, tp_err ? tp_err : "unknown");
+		serial_puts(SERIAL_COM1, " val=");
+		serial_puthex(SERIAL_COM1, tp_err_val);
+		if (tp_dbg_id) {
+			serial_puts(SERIAL_COM1, " id=");
+			serial_puthex(SERIAL_COM1, tp_dbg_id);
+			serial_puts(SERIAL_COM1, " bar=");
+			serial_puthex(SERIAL_COM1, tp_dbg_bar);
+			serial_puts(SERIAL_COM1, " cmd=");
+			serial_puthex(SERIAL_COM1, tp_dbg_cmd);
+			serial_puts(SERIAL_COM1, " comp=");
+			serial_puthex(SERIAL_COM1, tp_dbg_comp);
+			serial_puts(SERIAL_COM1, " priv=");
+			serial_puthex(SERIAL_COM1, tp_dbg_priv0);
+			serial_putc(SERIAL_COM1, '/');
+			serial_puthex(SERIAL_COM1, tp_dbg_priv4);
+			serial_puts(SERIAL_COM1, " pmec=");
+			serial_puthex(SERIAL_COM1, tp_dbg_pmec);
+			serial_putc(SERIAL_COM1, '/');
+			serial_puthex(SERIAL_COM1, tp_dbg_pmec_after);
+		}
+	}
+	serial_putc(SERIAL_COM1, '\n');
+}
+
 void program_touchpad_main(const char *arg)
 void program_touchpad_main(const char *arg)
 {
 {
 	arg = arg ? skip_spaces(arg) : 0;
 	arg = arg ? skip_spaces(arg) : 0;
@@ -757,10 +829,12 @@ void program_touchpad_main(const char *arg)
 			print_status();
 			print_status();
 		else
 		else
 			print_absent();
 			print_absent();
+		tp_serial_status();
 		return;
 		return;
 	}
 	}
 	if (!tp_present) {
 	if (!tp_present) {
 		print_absent();
 		print_absent();
+		tp_serial_status();
 		return;
 		return;
 	}
 	}
 
 

+ 4 - 2
kernel/uhci.c

@@ -91,7 +91,7 @@ static unsigned char setup_buf[8];
 struct uhci_int_ep {
 struct uhci_int_ep {
 	struct uhci_td td;
 	struct uhci_td td;
 	struct uhci_qh qh;
 	struct uhci_qh qh;
-	unsigned char buf[8] __attribute__((aligned(16)));
+	unsigned char buf[USB_INT_MAX] __attribute__((aligned(16)));
 	unsigned int addr, ep, mps;
 	unsigned int addr, ep, mps;
 	unsigned int toggle;
 	unsigned int toggle;
 	int low;
 	int low;
@@ -460,11 +460,12 @@ static void int_rearm(struct uhci_int_ep *ep)
 
 
 static int uhci_int_in_start(unsigned int ctrl, unsigned int slot,
 static int uhci_int_in_start(unsigned int ctrl, unsigned int slot,
 			     unsigned int addr, unsigned int ep_num,
 			     unsigned int addr, unsigned int ep_num,
-			     unsigned int mps, int low_speed)
+			     unsigned int mps, unsigned int len, int low_speed)
 {
 {
 	struct uhci_int_ep *ep;
 	struct uhci_int_ep *ep;
 
 
 	(void)ctrl;
 	(void)ctrl;
+	(void)len;   /* UHCI transfers one packet per TD; boot HID reports only */
 	if (!found || slot >= USB_HCD_INT_SLOTS)
 	if (!found || slot >= USB_HCD_INT_SLOTS)
 		return -1;
 		return -1;
 	ep = &int_eps[slot];
 	ep = &int_eps[slot];
@@ -552,4 +553,5 @@ const struct usb_hcd_ops usb_uhci_ops = {
 	0,
 	0,
 	0,
 	0,
 	0,
 	0,
+	0,
 };
 };

+ 42 - 16
kernel/usb.c

@@ -53,6 +53,7 @@ struct usb_ctrl_ref {
 #define PSTAT_CONNECT   0x0001u
 #define PSTAT_CONNECT   0x0001u
 #define PSTAT_ENABLE    0x0002u
 #define PSTAT_ENABLE    0x0002u
 #define PSTAT_LOW_SPEED 0x0200u
 #define PSTAT_LOW_SPEED 0x0200u
+#define PSTAT_HIGH_SPEED 0x0400u
 
 
 /* How much of a configuration descriptor we read/parse. */
 /* How much of a configuration descriptor we read/parse. */
 #define USB_CONFIG_MAX 128
 #define USB_CONFIG_MAX 128
@@ -358,8 +359,8 @@ static void usb_fail(const char *what, unsigned int ctrl, unsigned int port,
    interrupt-IN endpoint to the active probe.  Returns 1 when the device
    interrupt-IN endpoint to the active probe.  Returns 1 when the device
    answered and its configuration was parsed. */
    answered and its configuration was parsed. */
 static int probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
 static int probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
-			int low, unsigned int port, unsigned int vendor,
-			unsigned int product)
+			int low, unsigned int port, unsigned int route,
+			unsigned int vendor, unsigned int product)
 {
 {
 	struct usb_iface_info info;
 	struct usb_iface_info info;
 	unsigned int total, i;
 	unsigned int total, i;
@@ -391,6 +392,7 @@ static int probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
 	info.mps = mps;
 	info.mps = mps;
 	info.low_speed = low;
 	info.low_speed = low;
 	info.port = port;
 	info.port = port;
+	info.route = route;
 	info.vendor = vendor;
 	info.vendor = vendor;
 	info.product = product;
 	info.product = product;
 	info.config_value = conf_buf[5];
 	info.config_value = conf_buf[5];
@@ -467,16 +469,19 @@ static int probe_config(unsigned int ctrl, unsigned int addr, unsigned int mps,
 }
 }
 
 
 static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
 static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
-			  int low, unsigned int port, unsigned int depth);
+			  int low, unsigned int port, unsigned int route,
+			  unsigned int depth);
 static int enumerate_device(unsigned int ctrl, unsigned int addr,
 static int enumerate_device(unsigned int ctrl, unsigned int addr,
 			    unsigned int mps, int low, unsigned int port,
 			    unsigned int mps, int low, unsigned int port,
-			    unsigned int depth);
-static int enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
+			    unsigned int route, unsigned int depth);
+static int enumerate_new_device(unsigned int ctrl, unsigned int port,
+				unsigned int route, unsigned int parent_addr,
+				unsigned int speed_hint, int low,
 				unsigned int depth);
 				unsigned int depth);
 
 
 static int enumerate_device(unsigned int ctrl, unsigned int addr,
 static int enumerate_device(unsigned int ctrl, unsigned int addr,
 			    unsigned int mps, int low, unsigned int port,
 			    unsigned int mps, int low, unsigned int port,
-			    unsigned int depth)
+			    unsigned int route, unsigned int depth)
 {
 {
 	unsigned int vendor, product, cls, subcls, proto;
 	unsigned int vendor, product, cls, subcls, proto;
 
 
@@ -529,21 +534,23 @@ static int enumerate_device(unsigned int ctrl, unsigned int addr,
 	}
 	}
 
 
 	if (cls == 0x09) {
 	if (cls == 0x09) {
-		enumerate_hub(ctrl, addr, mps, low, port, depth + 1);
+		enumerate_hub(ctrl, addr, mps, low, port, route, depth + 1);
 		return 1;
 		return 1;
 	}
 	}
 
 
 	if (current_probe || print_devices)
 	if (current_probe || print_devices)
-		return probe_config(ctrl, addr, mps, low, port, vendor, product);
+		return probe_config(ctrl, addr, mps, low, port, route, vendor,
+				    product);
 
 
 	return 1;
 	return 1;
 }
 }
 
 
 static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
 static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps,
-			  int low, unsigned int port, unsigned int depth)
+			  int low, unsigned int port, unsigned int route,
+			  unsigned int depth)
 {
 {
 	unsigned char cfg[9];
 	unsigned char cfg[9];
-	unsigned int nports, p, i, power_good;
+	unsigned int nports, p, i, power_good, spd2;
 
 
 	/* Put the hub in its configured state before issuing hub-class
 	/* Put the hub in its configured state before issuing hub-class
 	   requests.  The core does not configure non-HID devices itself, and
 	   requests.  The core does not configure non-HID devices itself, and
@@ -642,6 +649,9 @@ static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps
 		}
 		}
 		if (!(st & PSTAT_ENABLE))
 		if (!(st & PSTAT_ENABLE))
 			continue;
 			continue;
+		/* xHCI speed IDs: 1 full, 2 low, 3 high. */
+		spd2 = (st & PSTAT_LOW_SPEED) ? 2 :
+		       ((st & PSTAT_HIGH_SPEED) ? 3 : 1);
 
 
 		if (print_devices) {
 		if (print_devices) {
 			unsigned int chg = (unsigned int)port_st[2] |
 			unsigned int chg = (unsigned int)port_st[2] |
@@ -656,11 +666,25 @@ static void enumerate_hub(unsigned int ctrl, unsigned int addr, unsigned int mps
 			io_putchar('\n');
 			io_putchar('\n');
 		}
 		}
 
 
-		enumerate_new_device(ctrl, port, low2, depth);
+		enumerate_new_device(ctrl, port,
+				     route | (p << (4u * (depth - 2u))),
+				     addr, spd2, low2, depth);
 	}
 	}
 }
 }
 
 
-static int enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
+static void usb_hcd_set_route(unsigned int ctrl, unsigned int port,
+			      unsigned int route, unsigned int parent_addr,
+			      unsigned int speed_hint)
+{
+	if (ctrl < n_usb_ctrls && usb_ctrls[ctrl].ops->set_route)
+		usb_ctrls[ctrl].ops->set_route(usb_ctrls[ctrl].local, port,
+					       route, parent_addr,
+					       speed_hint);
+}
+
+static int enumerate_new_device(unsigned int ctrl, unsigned int port,
+				unsigned int route, unsigned int parent_addr,
+				unsigned int speed_hint, int low,
 				unsigned int depth)
 				unsigned int depth)
 {
 {
 	unsigned int mps;
 	unsigned int mps;
@@ -690,6 +714,7 @@ static int enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
 	 * high-speed device accepts the short transfer and reports its real
 	 * high-speed device accepts the short transfer and reports its real
 	 * bMaxPacketSize0 in the descriptor. */
 	 * bMaxPacketSize0 in the descriptor. */
 	mps = 8;
 	mps = 8;
+	usb_hcd_set_route(ctrl, port, route, parent_addr, speed_hint);
 	if (usb_control_out(ctrl, 0, mps, low, RT_HOST2DEV_STD,
 	if (usb_control_out(ctrl, 0, mps, low, RT_HOST2DEV_STD,
 			    REQ_SET_ADDRESS, (unsigned short)addr, 0) < 0) {
 			    REQ_SET_ADDRESS, (unsigned short)addr, 0) < 0) {
 		usb_fail("SET_ADDRESS failed", ctrl, port, 0);
 		usb_fail("SET_ADDRESS failed", ctrl, port, 0);
@@ -720,7 +745,7 @@ static int enumerate_new_device(unsigned int ctrl, unsigned int port, int low,
 		mps = 8;
 		mps = 8;
 
 
 	dbg_dec("usb:   enumerated device, addr ", addr);
 	dbg_dec("usb:   enumerated device, addr ", addr);
-	return enumerate_device(ctrl, addr, mps, low, port, depth);
+	return enumerate_device(ctrl, addr, mps, low, port, route, depth);
 }
 }
 
 
 /* A port reset hands the device to its companion controller, and the first
 /* A port reset hands the device to its companion controller, and the first
@@ -735,7 +760,7 @@ static int enum_port_retry(unsigned int ctrl, unsigned int port,
 	unsigned int try;
 	unsigned int try;
 
 
 	for (try = 0;; try++) {
 	for (try = 0;; try++) {
-		if (enumerate_new_device(ctrl, port,
+		if (enumerate_new_device(ctrl, port, 0, 0, 0,
 					 ops->port_low_speed(local, port), 1))
 					 ops->port_low_speed(local, port), 1))
 			return 1;
 			return 1;
 		if (try >= 2)
 		if (try >= 2)
@@ -813,7 +838,8 @@ int usb_port_connected(unsigned int ctrl, unsigned int port)
 }
 }
 
 
 int usb_int_in_start(unsigned int ctrl, unsigned int slot, unsigned int addr,
 int usb_int_in_start(unsigned int ctrl, unsigned int slot, unsigned int addr,
-		     unsigned int ep, unsigned int mps, int low_speed)
+		     unsigned int ep, unsigned int mps, unsigned int len,
+		     int low_speed)
 {
 {
 	const struct usb_hcd_ops *ops;
 	const struct usb_hcd_ops *ops;
 	int r;
 	int r;
@@ -827,7 +853,7 @@ int usb_int_in_start(unsigned int ctrl, unsigned int slot, unsigned int addr,
 		slot_ops[slot] = 0;
 		slot_ops[slot] = 0;
 	}
 	}
 	r = ops->int_in_start(usb_ctrls[ctrl].local, slot, addr, ep, mps,
 	r = ops->int_in_start(usb_ctrls[ctrl].local, slot, addr, ep, mps,
-			      low_speed);
+			      len, low_speed);
 	slot_ops[slot] = r == 0 ? ops : 0;
 	slot_ops[slot] = r == 0 ? ops : 0;
 	return r;
 	return r;
 }
 }

+ 2 - 1
kernel/usb.h

@@ -99,7 +99,8 @@ void usb_register_device_probe(usb_device_probe_fn fn);
 /* Interrupt-IN endpoints (slots 0..USB_HCD_INT_SLOTS-1; usbhid assigns
 /* Interrupt-IN endpoints (slots 0..USB_HCD_INT_SLOTS-1; usbhid assigns
    one per HID interface it claims). */
    one per HID interface it claims). */
 int usb_int_in_start(unsigned int ctrl, unsigned int slot, unsigned int addr,
 int usb_int_in_start(unsigned int ctrl, unsigned int slot, unsigned int addr,
-		     unsigned int ep, unsigned int mps, int low_speed);
+		     unsigned int ep, unsigned int mps, unsigned int len,
+		     int low_speed);
 int usb_int_in_poll(unsigned int slot, unsigned char *buf, unsigned int len);
 int usb_int_in_poll(unsigned int slot, unsigned char *buf, unsigned int len);
 void usb_int_in_stop(unsigned int slot);
 void usb_int_in_stop(unsigned int slot);
 
 

+ 18 - 2
kernel/usb_hcd.h

@@ -23,6 +23,7 @@ struct usb_iface_info {
 	unsigned int mps;         /* device EP0 max packet size */
 	unsigned int mps;         /* device EP0 max packet size */
 	int low_speed;
 	int low_speed;
 	unsigned int port;        /* root port the device hangs off (0xFF: behind a hub) */
 	unsigned int port;        /* root port the device hangs off (0xFF: behind a hub) */
+	unsigned int route;       /* xHCI route string (0 = directly on the root port) */
 	unsigned int vendor, product;
 	unsigned int vendor, product;
 	unsigned int cls, subcls, proto;   /* interface class/subclass/protocol */
 	unsigned int cls, subcls, proto;   /* interface class/subclass/protocol */
 	unsigned int iface_num;
 	unsigned int iface_num;
@@ -70,10 +71,13 @@ struct usb_hcd_ops {
 	 * USB_HCD_INT_SLOTS).  The transfer stays armed in the schedule;
 	 * USB_HCD_INT_SLOTS).  The transfer stays armed in the schedule;
 	 * the controller retries NAKs itself.  poll: > 0 report bytes
 	 * the controller retries NAKs itself.  poll: > 0 report bytes
 	 * (auto re-armed), 0 nothing yet, -1 error (still armed, toggle
 	 * (auto re-armed), 0 nothing yet, -1 error (still armed, toggle
-	 * preserved; the caller may count errors and re-init). */
+	 * preserved; the caller may count errors and re-init).  mps is the
+	 * endpoint's wMaxPacketSize; len is the report buffer size (up to
+	 * USB_INT_MAX, so multi-packet HID reports fit). */
+#define USB_INT_MAX 32
 	int (*int_in_start)(unsigned int ctrl, unsigned int slot,
 	int (*int_in_start)(unsigned int ctrl, unsigned int slot,
 			    unsigned int addr, unsigned int ep,
 			    unsigned int addr, unsigned int ep,
-			    unsigned int mps, int low_speed);
+			    unsigned int mps, unsigned int len, int low_speed);
 	int (*int_in_poll)(unsigned int slot, unsigned char *buf,
 	int (*int_in_poll)(unsigned int slot, unsigned char *buf,
 			   unsigned int len);
 			   unsigned int len);
 	void (*int_in_stop)(unsigned int slot);
 	void (*int_in_stop)(unsigned int slot);
@@ -103,6 +107,18 @@ struct usb_hcd_ops {
 	/* Optional: print raw root-port status during `lsusb` (print mode
 	/* Optional: print raw root-port status during `lsusb` (print mode
 	 * only).  Used by EHCI to show PORTSC while debugging routing. */
 	 * only).  Used by EHCI to show PORTSC while debugging routing. */
 	void (*print_ports)(unsigned int ctrl);
 	void (*print_ports)(unsigned int ctrl);
+
+	/* Optional: record the root port, route string, parent hub address
+	 * and device speed for the next address assignment.  xHCI needs the
+	 * route string to reach a device behind a hub, the parent hub's slot
+	 * id as the TT hub for a low/full-speed device, and the device's own
+	 * speed (the root port runs at the hub's upstream speed).  speed_hint
+	 * is 0 for a root-port device (use the port speed), 1 low, 2 full,
+	 * 3 high; USB2 HCDs ignore it.  parent_addr is 0 for a root-port
+	 * device. */
+	void (*set_route)(unsigned int ctrl, unsigned int port,
+			  unsigned int route, unsigned int parent_addr,
+			  unsigned int speed_hint);
 };
 };
 
 
 extern const struct usb_hcd_ops usb_uhci_ops;
 extern const struct usb_hcd_ops usb_uhci_ops;

+ 83 - 16
kernel/usbhid.c

@@ -1,11 +1,12 @@
-/* USB HID boot devices: mice + keyboards.
+/* USB HID devices: mice, keyboards and the Logitech Unifying receiver.
  *
  *
  * The probe claims every HID interface it understands: boot mouse/keyboard
  * 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.
+ * (class 3 / subclass 1 / protocol 2 or 1), report-protocol HID interfaces
+ * whose report descriptor says "mouse"/"pointer" or "keyboard" (class 3,
+ * other subclasses — many modern and composite devices), and the vendor
+ * DJ interface of a Logitech Unifying receiver.  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
  * 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
  * into PS/2 set-1 scancodes and injected into the regular input queue
@@ -35,13 +36,14 @@
 /* How much of a report descriptor to read for classification. */
 /* How much of a report descriptor to read for classification. */
 #define REPORT_MAX 64
 #define REPORT_MAX 64
 
 
-enum { KIND_FREE = 0, KIND_MOUSE, KIND_KBD };
+enum { KIND_FREE = 0, KIND_MOUSE, KIND_KBD, KIND_DJ };
 
 
 struct hid_dev {
 struct hid_dev {
 	unsigned int kind;        /* KIND_*, KIND_FREE = slot unused */
 	unsigned int kind;        /* KIND_*, KIND_FREE = slot unused */
 	int present;              /* endpoint armed */
 	int present;              /* endpoint armed */
 	int claimed;              /* claimed by the scan in progress */
 	int claimed;              /* claimed by the scan in progress */
 	unsigned int ctrl, addr, ep, mps, port;
 	unsigned int ctrl, addr, ep, mps, port;
+	unsigned int xfer;        /* report buffer size for int_in_start */
 	int low;
 	int low;
 	unsigned int err;         /* consecutive transfer errors */
 	unsigned int err;         /* consecutive transfer errors */
 	unsigned int disc;        /* consecutive "port disconnected" reads */
 	unsigned int disc;        /* consecutive "port disconnected" reads */
@@ -222,7 +224,13 @@ static int hid_probe(const struct usb_iface_info *in)
 	if (in->cls != 0x03u || !in->ep_addr || !(in->ep_addr & 0x80u))
 	if (in->cls != 0x03u || !in->ep_addr || !(in->ep_addr & 0x80u))
 		return 0;
 		return 0;
 
 
-	if (in->subcls == 0x01u && in->proto == 0x02u)
+	/* Logitech Unifying receiver: interface 2 is the HID++/DJ channel
+	 * that carries the paired device's reports.  Its vendor report
+	 * descriptor is not a mouse collection, so claim it explicitly. */
+	if (in->vendor == 0x046du && in->product == 0xc52bu &&
+	    in->iface_num == 2 && in->subcls == 0x00u && in->proto == 0x00u)
+		kind = KIND_DJ;
+	else if (in->subcls == 0x01u && in->proto == 0x02u)
 		kind = KIND_MOUSE;
 		kind = KIND_MOUSE;
 	else if (in->subcls == 0x01u && in->proto == 0x01u)
 	else if (in->subcls == 0x01u && in->proto == 0x01u)
 		kind = KIND_KBD;
 		kind = KIND_KBD;
@@ -255,6 +263,8 @@ static int hid_probe(const struct usb_iface_info *in)
 	d->addr = in->addr;
 	d->addr = in->addr;
 	d->ep = in->ep_addr & 0x0Fu;
 	d->ep = in->ep_addr & 0x0Fu;
 	d->mps = in->ep_mps ? in->ep_mps : 8;
 	d->mps = in->ep_mps ? in->ep_mps : 8;
+	d->xfer = kind == KIND_DJ ? USB_INT_MAX :
+		  (in->ep_mps ? in->ep_mps : 8);
 	d->port = in->port;
 	d->port = in->port;
 	d->low = in->low_speed;
 	d->low = in->low_speed;
 	d->claimed = 1;
 	d->claimed = 1;
@@ -265,7 +275,8 @@ static void dev_attach(struct hid_dev *d, unsigned int slot)
 {
 {
 	unsigned int i;
 	unsigned int i;
 
 
-	if (usb_int_in_start(d->ctrl, slot, d->addr, d->ep, d->mps, d->low) != 0)
+	if (usb_int_in_start(d->ctrl, slot, d->addr, d->ep, d->mps,
+			     d->xfer, d->low) != 0)
 		return;
 		return;
 	d->err = 0;
 	d->err = 0;
 	d->disc = 0;
 	d->disc = 0;
@@ -274,10 +285,15 @@ static void dev_attach(struct hid_dev *d, unsigned int slot)
 	for (i = 0; i < 6; i++)
 	for (i = 0; i < 6; i++)
 		d->prev[i] = 0;
 		d->prev[i] = 0;
 
 
-	serial_puts(SERIAL_COM1, d->kind == KIND_MOUSE
-				   ? "usbhid: mouse attached ("
-				   : "usbhid: keyboard attached (");
+	if (d->kind == KIND_DJ)
+		serial_puts(SERIAL_COM1, "usbhid: Logitech DJ receiver attached (");
+	else if (d->kind == KIND_MOUSE)
+		serial_puts(SERIAL_COM1, "usbhid: mouse attached (");
+	else
+		serial_puts(SERIAL_COM1, "usbhid: keyboard attached (");
 	serial_puts(SERIAL_COM1, usb_hcd_name_ctrl(d->ctrl));
 	serial_puts(SERIAL_COM1, usb_hcd_name_ctrl(d->ctrl));
+	serial_puts(SERIAL_COM1, " ctrl ");
+	serial_putdec(SERIAL_COM1, d->ctrl);
 	serial_puts(SERIAL_COM1, ", addr ");
 	serial_puts(SERIAL_COM1, ", addr ");
 	serial_putdec(SERIAL_COM1, d->addr);
 	serial_putdec(SERIAL_COM1, d->addr);
 	serial_puts(SERIAL_COM1, " ep ");
 	serial_puts(SERIAL_COM1, " ep ");
@@ -295,7 +311,9 @@ static void dev_detach(struct hid_dev *d, unsigned int slot)
 	 * everything, and is the only reliable recovery on this SB950. */
 	 * everything, and is the only reliable recovery on this SB950. */
 	need_rescan = 1;
 	need_rescan = 1;
 	last_watch = get_ticks_ms() - WATCH_MS;   /* watch again soon */
 	last_watch = get_ticks_ms() - WATCH_MS;   /* watch again soon */
-	serial_puts(SERIAL_COM1, d->kind == KIND_MOUSE
+	serial_puts(SERIAL_COM1, d->kind == KIND_DJ
+				   ? "usbhid: Logitech DJ receiver detached (addr "
+				   : d->kind == KIND_MOUSE
 				   ? "usbhid: mouse detached (addr "
 				   ? "usbhid: mouse detached (addr "
 				   : "usbhid: keyboard detached (addr ");
 				   : "usbhid: keyboard detached (addr ");
 	serial_putdec(SERIAL_COM1, d->addr);
 	serial_putdec(SERIAL_COM1, d->addr);
@@ -391,9 +409,47 @@ static int dev_poll(struct hid_dev *d, unsigned int slot, unsigned char *buf,
 	return n;
 	return n;
 }
 }
 
 
+static int dj_seen;
+static int mouse_seen;
+
+static void dj_decode(const unsigned char *r, unsigned int n,
+		      unsigned int *buttons, int *dx, int *dy,
+		      int *scroll, int *got)
+{
+	const unsigned char *p;
+	unsigned int btn;
+	int x, y;
+
+	if (n < 10 || (r[0] != 0x20u && r[0] != 0x21u))
+		return;
+	/* Device index 1..7, standard mouse report type.  The receiver's
+	 * connection/notification reports (0x40/0x41/0x42) and other device
+	 * types are ignored. */
+	if (r[1] < 1 || r[1] > 7 || r[2] != 0x02u)
+		return;
+	p = r + 3;
+	btn = p[0] | ((unsigned int)p[1] << 8);
+	x = p[2] | ((p[3] & 0x0Fu) << 8);
+	y = (p[3] >> 4) | (p[4] << 4);
+	if (x & 0x800)
+		x -= 0x1000;       /* 12-bit signed relative X */
+	if (y & 0x800)
+		y -= 0x1000;
+	*buttons |= btn & 0x07u;
+	*dx += x;
+	*dy -= y;                  /* HID +y down; mouse.c expects +y up */
+	if (scroll)
+		*scroll -= (int)(signed char)p[5] * 48;
+	*got = 1;
+	if (!dj_seen) {
+		dj_seen = 1;
+		serial_puts(SERIAL_COM1, "usbhid: first DJ mouse report\n");
+	}
+}
+
 int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll)
 int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll)
 {
 {
-	unsigned char buf[8];
+	unsigned char buf[USB_INT_MAX];
 	unsigned int now, i, all_busy = 1;
 	unsigned int now, i, all_busy = 1;
 	unsigned int b = 0;
 	unsigned int b = 0;
 	int n, x = 0, y = 0, got = 0;
 	int n, x = 0, y = 0, got = 0;
@@ -446,6 +502,14 @@ int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll)
 			/* HID: +y is down; mouse.c expects +y = up. */
 			/* HID: +y is down; mouse.c expects +y = up. */
 			y -= (int)(signed char)buf[2];
 			y -= (int)(signed char)buf[2];
 			got = 1;
 			got = 1;
+			if (!mouse_seen) {
+				mouse_seen = 1;
+				serial_puts(SERIAL_COM1,
+					    "usbhid: first boot mouse report\n");
+			}
+		} else if (d->kind == KIND_DJ && n >= 10) {
+			dj_decode(buf, (unsigned int)n, &b, &x, &y,
+				  scroll, &got);
 		} else if (n >= 8 && d->kind == KIND_KBD) {
 		} else if (n >= 8 && d->kind == KIND_KBD) {
 			kbd_decode(d, buf);
 			kbd_decode(d, buf);
 		}
 		}
@@ -464,7 +528,8 @@ int usbhid_mouse_attached(void)
 	unsigned int i;
 	unsigned int i;
 
 
 	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
 	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
-		if (devs[i].kind == KIND_MOUSE && devs[i].present)
+		if ((devs[i].kind == KIND_MOUSE || devs[i].kind == KIND_DJ) &&
+		    devs[i].present)
 			return 1;
 			return 1;
 	}
 	}
 	return 0;
 	return 0;
@@ -489,7 +554,9 @@ void usbhid_get_info(unsigned int *ctrl, unsigned int *addr,
 	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
 	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
 		struct hid_dev *d = &devs[i];
 		struct hid_dev *d = &devs[i];
 
 
-		if (d->kind == KIND_MOUSE && d->present) {
+		if (d->kind == KIND_MOUSE || d->kind == KIND_DJ) {
+			if (!d->present)
+				continue;
 			*ctrl = d->ctrl;
 			*ctrl = d->ctrl;
 			*addr = d->addr;
 			*addr = d->addr;
 			*ep = d->ep;
 			*ep = d->ep;

+ 11 - 9
kernel/usbhid.h

@@ -1,11 +1,12 @@
-/* USB HID boot devices: mouse + keyboard.
+/* USB HID devices: mouse + keyboard (boot protocol, report protocol and
+ * the Logitech Unifying receiver's DJ channel).
  *
  *
- * 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. */
+ * A single manager owns the scan/hotplug state for every interrupt-IN
+ * endpoint: find, configure, put boot devices into boot protocol, arm the
+ * endpoint and keep it 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
 #ifndef USBHID_H
 #define USBHID_H
 #define USBHID_H
 
 
@@ -14,10 +15,11 @@
    running then. */
    running then. */
 void usbhid_init(void);
 void usbhid_init(void);
 
 
-/* Service both endpoints (called once per WM loop iteration from
+/* Service all endpoints (called once per WM loop iteration from
    mouse_poll_update()).  Returns 1 when a mouse report is available and
    mouse_poll_update()).  Returns 1 when a mouse report is available and
    fills buttons/dx/dy (PS/2 sign convention: dy > 0 = up) plus scroll in
    fills buttons/dx/dy (PS/2 sign convention: dy > 0 = up) plus scroll in
-   pixels (currently always 0: boot-protocol mice have no wheel field). */
+   pixels (boot-protocol mice have no wheel field; the Logitech DJ path
+   maps one wheel notch to 48 px). */
 int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll);
 int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll);
 
 
 int usbhid_mouse_attached(void);
 int usbhid_mouse_attached(void);

+ 424 - 150
kernel/xhci.c

@@ -23,7 +23,7 @@
 #define XHCI_DEBUG 0
 #define XHCI_DEBUG 0
 
 
 /* ---- controller limits ------------------------------------------------- */
 /* ---- controller limits ------------------------------------------------- */
-#define XHCI_MAX_SLOTS		4
+#define XHCI_MAX_SLOTS		8
 #define XHCI_MAX_PORTS		32
 #define XHCI_MAX_PORTS		32
 #define XHCI_EVT_TRBS		256
 #define XHCI_EVT_TRBS		256
 #define XHCI_CMD_TRBS		32
 #define XHCI_CMD_TRBS		32
@@ -145,6 +145,9 @@ struct xhci_slot {
 	unsigned int addr;	/* logical address used by usb.c */
 	unsigned int addr;	/* logical address used by usb.c */
 	unsigned int dev_addr;	/* address assigned by the xHC */
 	unsigned int dev_addr;	/* address assigned by the xHC */
 	unsigned int port;
 	unsigned int port;
+	unsigned int route;	/* xHCI route string (0 for a root-port device) */
+	unsigned int tt_slot;	/* parent high-speed hub slot (TT) */
+	unsigned int tt_port;	/* downstream port on that hub */
 	unsigned int speed;
 	unsigned int speed;
 	unsigned int dc;	/* device context page */
 	unsigned int dc;	/* device context page */
 	unsigned int ep0;	/* EP0 transfer ring page */
 	unsigned int ep0;	/* EP0 transfer ring page */
@@ -166,7 +169,7 @@ struct xhci_int {
 	unsigned int pending_len;
 	unsigned int pending_len;
 	int pending;
 	int pending;
 	int error;
 	int error;
-	unsigned char buf[8] __attribute__((aligned(16)));
+	unsigned char buf[USB_INT_MAX] __attribute__((aligned(16)));
 };
 };
 
 
 struct xhci_bulk {
 struct xhci_bulk {
@@ -187,64 +190,162 @@ struct xhci_bulk {
 	int error;
 	int error;
 };
 };
 
 
-static unsigned int mmio_base;   /* kernel mapping of BAR0 */
-static unsigned int mmio_phys;   /* BAR0 itself (logged, reported) */
-static unsigned int cap_len;
-static unsigned int rt_off;
-static unsigned int db_off;
-static unsigned int max_slots;
-static unsigned int max_ports;
-static unsigned int ctx_size;
-static unsigned int port_mask;
-static unsigned int hcc_params;
-static unsigned int pci_bus, pci_dev, pci_func;
-static unsigned int pci_id;
-static unsigned int hci_version;
-static int found;
-static int last_port = -1;
-
-static unsigned int dcbaa;
-static unsigned int input_ctx;
-static unsigned int cmd_ring;
-static unsigned int evt_ring;
-static unsigned int erst;
-static unsigned int cmd_enq;
-static unsigned int cmd_cycle;
-static unsigned int evt_idx;
-static unsigned int evt_cycle;
-
-static unsigned int cmd_busy;
-static unsigned int cmd_done;
-static unsigned int cmd_status;
-static unsigned int cmd_slot;
-static unsigned int cmd_trb_addr;
-
-static unsigned int ctl_busy;
-static unsigned int ctl_done;
-static unsigned int ctl_slot;
-static unsigned int ctl_status;
-static unsigned int ctl_req_len;
-static unsigned int ctl_actual;
-static unsigned int ctl_data_seen;
-static unsigned int ctl_setup_trb;
-static unsigned int ctl_data_trb;
-static unsigned int ctl_status_trb;
-
-static struct xhci_bulk bulk_in;
-static struct xhci_bulk bulk_out;
-static unsigned int out_busy;
-static unsigned int out_done;
-static unsigned int out_status;
-static unsigned int out_slot;
-static unsigned int out_trb;
-
-static struct xhci_slot slots[XHCI_MAX_SLOTS + 1];
-static unsigned int addr_slot[128];
-static unsigned int port_slot[XHCI_MAX_PORTS];
-static struct xhci_int ints[USB_HCD_INT_SLOTS];
+#define XHCI_MAX_HCD 2
+
+/* One xHCI instance.  The Yoga 720 has two: the Sunrise Point-LP PCH
+ * controller (camera, Bluetooth, card reader) and the Alpine Ridge
+ * USB-C/Thunderbolt controller that carries the Lenovo hub and the
+ * Logitech receiver.  The driver used to stop at the first one. */
+struct xhci_hcd {
+	unsigned int mmio_base;   /* kernel mapping of BAR0 */
+	unsigned int mmio_phys;   /* BAR0 itself (logged, reported) */
+	unsigned int cap_len;
+	unsigned int rt_off;
+	unsigned int db_off;
+	unsigned int max_slots;
+	unsigned int max_ports;
+	unsigned int ctx_size;
+	unsigned int port_mask;
+	unsigned int hcc_params;
+	unsigned int bus_no, dev_no, func_no;
+	unsigned int pci_id;
+	unsigned int hci_version;
+	int present;
+	int last_port_num;
+
+	unsigned int dcbaa;
+	unsigned int input_ctx;
+	unsigned int cmd_ring;
+	unsigned int evt_ring;
+	unsigned int erst;
+	unsigned int cmd_enq;
+	unsigned int cmd_cycle;
+	unsigned int evt_idx;
+	unsigned int evt_cycle;
+
+	unsigned int cmd_busy;
+	unsigned int cmd_done;
+	unsigned int cmd_status;
+	unsigned int cmd_slot;
+	unsigned int cmd_trb_addr;
+
+	unsigned int ctl_busy;
+	unsigned int ctl_done;
+	unsigned int ctl_slot;
+	unsigned int ctl_status;
+	unsigned int ctl_req_len;
+	unsigned int ctl_actual;
+	unsigned int ctl_data_seen;
+	unsigned int ctl_setup_trb;
+	unsigned int ctl_data_trb;
+	unsigned int ctl_status_trb;
+
+	struct xhci_bulk bulk_in;
+	struct xhci_bulk bulk_out;
+	unsigned int out_busy;
+	unsigned int out_done;
+	unsigned int out_status;
+	unsigned int out_slot;
+	unsigned int out_trb;
+
+	struct xhci_slot slots[XHCI_MAX_SLOTS + 1];
+	unsigned int addr_slot[128];
+	unsigned int port_slot[XHCI_MAX_PORTS];
+	struct xhci_int ints[USB_HCD_INT_SLOTS];
+
+	unsigned int enum_port;
+	unsigned int enum_route;
+	unsigned int enum_parent_addr;
+	unsigned int enum_tt_slot;
+	unsigned int enum_speed_hint;
+};
+
+/* Page-allocated: two full instances would otherwise add ~2 KB to the
+ * kernel BSS, which is already close to the 0x90000 wall. */
+static struct xhci_hcd *xhci_hcds;
+static struct xhci_hcd *xh;      /* instance of the current call */
+static unsigned int xhci_nctrl;
+/* int_in_poll()/stop() get only the slot, not the controller index. */
+static unsigned int int_ctrl[USB_HCD_INT_SLOTS];
+
+#define mmio_base	(xh->mmio_base)
+#define mmio_phys	(xh->mmio_phys)
+#define cap_len		(xh->cap_len)
+#define rt_off		(xh->rt_off)
+#define db_off		(xh->db_off)
+#define max_slots	(xh->max_slots)
+#define max_ports	(xh->max_ports)
+#define ctx_size	(xh->ctx_size)
+#define port_mask	(xh->port_mask)
+#define hcc_params	(xh->hcc_params)
+#define pci_bus		(xh->bus_no)
+#define pci_dev		(xh->dev_no)
+#define pci_func	(xh->func_no)
+#define pci_id		(xh->pci_id)
+#define hci_version	(xh->hci_version)
+#define found		(xh->present)
+#define last_port	(xh->last_port_num)
+#define dcbaa		(xh->dcbaa)
+#define input_ctx	(xh->input_ctx)
+#define cmd_ring	(xh->cmd_ring)
+#define evt_ring	(xh->evt_ring)
+#define erst		(xh->erst)
+#define cmd_enq		(xh->cmd_enq)
+#define cmd_cycle	(xh->cmd_cycle)
+#define evt_idx		(xh->evt_idx)
+#define evt_cycle	(xh->evt_cycle)
+#define cmd_busy	(xh->cmd_busy)
+#define cmd_done	(xh->cmd_done)
+#define cmd_status	(xh->cmd_status)
+#define cmd_slot	(xh->cmd_slot)
+#define cmd_trb_addr	(xh->cmd_trb_addr)
+#define ctl_busy	(xh->ctl_busy)
+#define ctl_done	(xh->ctl_done)
+#define ctl_slot	(xh->ctl_slot)
+#define ctl_status	(xh->ctl_status)
+#define ctl_req_len	(xh->ctl_req_len)
+#define ctl_actual	(xh->ctl_actual)
+#define ctl_data_seen	(xh->ctl_data_seen)
+#define ctl_setup_trb	(xh->ctl_setup_trb)
+#define ctl_data_trb	(xh->ctl_data_trb)
+#define ctl_status_trb	(xh->ctl_status_trb)
+#define bulk_in		(xh->bulk_in)
+#define bulk_out	(xh->bulk_out)
+#define out_busy	(xh->out_busy)
+#define out_done	(xh->out_done)
+#define out_status	(xh->out_status)
+#define out_slot	(xh->out_slot)
+#define out_trb		(xh->out_trb)
+#define slots		(xh->slots)
+#define addr_slot	(xh->addr_slot)
+#define port_slot	(xh->port_slot)
+#define ints		(xh->ints)
+#define enum_port	(xh->enum_port)
+#define enum_route	(xh->enum_route)
+#define enum_parent_addr (xh->enum_parent_addr)
+#define enum_tt_slot	(xh->enum_tt_slot)
+#define enum_speed_hint	(xh->enum_speed_hint)
 
 
 static spinlock_t xhci_lock;
 static spinlock_t xhci_lock;
 
 
+/* Select the instance for a vtable call (ctrl is the local index that
+ * usb.c registered). */
+static int xhci_use(unsigned int ctrl)
+{
+	if (!xhci_hcds || ctrl >= XHCI_MAX_HCD ||
+	    !xhci_hcds[ctrl].present)
+		return 0;
+	xh = &xhci_hcds[ctrl];
+	return 1;
+}
+
+static int xhci_use_slot(unsigned int slot)
+{
+	if (slot >= USB_HCD_INT_SLOTS || int_ctrl[slot] >= XHCI_MAX_HCD)
+		return 0;
+	return xhci_use(int_ctrl[slot]);
+}
+
 /* ---- debug ------------------------------------------------------------- */
 /* ---- debug ------------------------------------------------------------- */
 #if XHCI_DEBUG
 #if XHCI_DEBUG
 static void dbg(const char *s)
 static void dbg(const char *s)
@@ -491,7 +592,7 @@ static void xhci_poll_locked(void)
 
 
 /* ---- commands ---------------------------------------------------------- */
 /* ---- commands ---------------------------------------------------------- */
 static int xhci_cmd(unsigned int p0, unsigned int p1, unsigned int control,
 static int xhci_cmd(unsigned int p0, unsigned int p1, unsigned int control,
-		    unsigned int *out_slot)
+		    unsigned int *slot_out)
 {
 {
 	unsigned int flags, t0, rc;
 	unsigned int flags, t0, rc;
 
 
@@ -533,8 +634,8 @@ static int xhci_cmd(unsigned int p0, unsigned int p1, unsigned int control,
 		dbg("xhci: command timeout\n");
 		dbg("xhci: command timeout\n");
 		return -1;
 		return -1;
 	}
 	}
-	if (out_slot)
-		*out_slot = cmd_slot;
+	if (slot_out)
+		*slot_out = cmd_slot;
 	rc = cmd_status;
 	rc = cmd_status;
 	spin_unlock_irqrestore(&xhci_lock, flags);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 	if (rc != CC_SUCCESS) {
 	if (rc != CC_SUCCESS) {
@@ -546,13 +647,15 @@ static int xhci_cmd(unsigned int p0, unsigned int p1, unsigned int control,
 
 
 /* ---- contexts ---------------------------------------------------------- */
 /* ---- contexts ---------------------------------------------------------- */
 static void fill_slot_ctx(unsigned int addr, unsigned int port,
 static void fill_slot_ctx(unsigned int addr, unsigned int port,
-			  unsigned int speed, unsigned int last_ctx)
+			  unsigned int route, unsigned int tt_slot,
+			  unsigned int tt_port, unsigned int speed,
+			  unsigned int last_ctx)
 {
 {
 	unsigned int *p = (unsigned int *)(input_ctx + ctx_size);
 	unsigned int *p = (unsigned int *)(input_ctx + ctx_size);
 
 
-	p[0] = (speed << 20) | (last_ctx << 27);
-	p[1] = (port + 1) << 16;
-	p[2] = 0;
+	p[0] = (route & 0xFFFFFu) | (speed << 20) | (last_ctx << 27);
+	p[1] = (port + 1) << 16;       /* root hub port, max exit latency 0 */
+	p[2] = (tt_slot & 0xFFu) | ((tt_port & 0xFFu) << 8);  /* tt_info */
 	p[3] = addr;
 	p[3] = addr;
 }
 }
 
 
@@ -665,26 +768,93 @@ static int xhci_config_ep(struct xhci_slot *s, unsigned int ep_index,
 	unsigned int i, flags;
 	unsigned int i, flags;
 	int rc;
 	int rc;
 
 
+	/* Last Valid Endpoint is the highest DCI in the slot, including the
+	 * one being added now.  Scanning only the existing mask and assigning
+	 * it unconditionally used to lower it again (EP1 IN = DCI 3 already
+	 * configured, then adding EP2 IN = DCI 5 sent LVE 3 and the xHC
+	 * rejected the command with Parameter Error). */
 	for (i = 1; i < 32; i++)
 	for (i = 1; i < 32; i++)
-		if (s->ep_mask & (1u << i))
+		if ((s->ep_mask & (1u << i)) && i > last)
 			last = i;
 			last = i;
 
 
 	spin_lock_irqsave(&xhci_lock, &flags);
 	spin_lock_irqsave(&xhci_lock, &flags);
 	zero_page(input_ctx, 4096);
 	zero_page(input_ctx, 4096);
 	*(unsigned int *)input_ctx = 0;
 	*(unsigned int *)input_ctx = 0;
 	*(unsigned int *)(input_ctx + 4) = SLOT_FLAG | ep_flag;
 	*(unsigned int *)(input_ctx + 4) = SLOT_FLAG | ep_flag;
-	fill_slot_ctx(s->dev_addr, s->port, s->speed, last);
+	fill_slot_ctx(s->dev_addr, s->port, s->route, s->tt_slot,
+		      s->tt_port, s->speed, last);
 	fill_ep_ctx(ep_index, type, mps, interval, ring);
 	fill_ep_ctx(ep_index, type, mps, interval, ring);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 
 
 	rc = xhci_cmd(input_ctx, 0,
 	rc = xhci_cmd(input_ctx, 0,
 		      TRB_TYPE(TRB_CONFIG_EP) | (s->slot_id << 24), 0);
 		      TRB_TYPE(TRB_CONFIG_EP) | (s->slot_id << 24), 0);
-	if (rc == 0)
+	if (rc == 0) {
 		s->ep_mask |= ep_flag;
 		s->ep_mask |= ep_flag;
+	} else {
+		xlog_hex("xhci: configure ep failed ep ", ep_index);
+		xlog_hex(" cc ", cmd_status);
+		xlog_hex(" slot ", s->slot_id);
+		xlog_hex(" spd ", s->speed);
+		xlog_hex(" route ", s->route);
+		xlog_hex(" tt ", s->tt_slot);
+		xlog_hex(" ttp ", s->tt_port);
+		serial_putc(SERIAL_COM1, '\n');
+	}
 	return rc;
 	return rc;
 }
 }
 
 
 /* ---- slots ------------------------------------------------------------- */
 /* ---- slots ------------------------------------------------------------- */
+static void set_route(unsigned int ctrl, unsigned int port,
+		      unsigned int route, unsigned int parent_addr,
+		      unsigned int speed_hint)
+{
+	struct xhci_slot *hs;
+
+	if (!xhci_use(ctrl))
+		return;
+	enum_port = port;
+	enum_route = route & 0xFFFFFu;
+	enum_parent_addr = parent_addr;
+	enum_speed_hint = speed_hint;
+	enum_tt_slot = 0;
+	if (parent_addr) {
+		hs = slot_by_addr(parent_addr);
+		if (hs && hs->speed == 3)
+			enum_tt_slot = hs->slot_id;
+	}
+}
+
+/* Move an Addressed slot to Configured.  The xHC does not do this from the
+ * USB SET_CONFIGURATION request; a Configure Endpoint command is required.
+ * A high-speed hub used as a TT must be Configured before a downstream
+ * Address Device, otherwise the xHC rejects the child with Parameter Error
+ * (cc 0x11).  Only the slot context is added; EP0 is already in the device
+ * context. */
+static int xhci_configure_slot(struct xhci_slot *s)
+{
+	unsigned int flags;
+	int rc;
+
+	spin_lock_irqsave(&xhci_lock, &flags);
+	zero_page(input_ctx, 4096);
+	*(unsigned int *)input_ctx = 0;
+	*(unsigned int *)(input_ctx + 4) = SLOT_FLAG;
+	fill_slot_ctx(s->dev_addr, s->port, s->route, s->tt_slot,
+		      s->tt_port, s->speed, 1);
+	spin_unlock_irqrestore(&xhci_lock, flags);
+
+	rc = xhci_cmd(input_ctx, 0,
+		      TRB_TYPE(TRB_CONFIG_EP) | (s->slot_id << 24), 0);
+	if (rc != 0) {
+		xlog_hex("xhci: configure slot failed cc ", cmd_status);
+		xlog_hex(" slot ", s->slot_id);
+		xlog_hex(" spd ", s->speed);
+		serial_putc(SERIAL_COM1, '\n');
+		return -1;
+	}
+	return 0;
+}
+
 /* Create a slot.  bsr=1: Address Device with Block Set Address Request,
 /* Create a slot.  bsr=1: Address Device with Block Set Address Request,
  * leaving the slot in the Default state at device address 0 (new
  * leaving the slot in the Default state at device address 0 (new
  * enumeration scheme).  bsr=0: the command carries target_addr and moves
  * enumeration scheme).  bsr=0: the command carries target_addr and moves
@@ -698,15 +868,18 @@ static struct xhci_slot *new_slot_common(unsigned int target_addr,
 	unsigned int slot_id, dc, ep0, flags;
 	unsigned int slot_id, dc, ep0, flags;
 	int rc;
 	int rc;
 
 
-	if (last_port < 0 || last_port >= (int)max_ports)
+	if (enum_port >= max_ports)
 		return 0;
 		return 0;
-	if (port_slot[last_port])
+	if (enum_route == 0 && port_slot[enum_port])
 		return 0;
 		return 0;
 
 
 	slot_id = 0;
 	slot_id = 0;
 	rc = xhci_cmd(0, 0, TRB_TYPE(TRB_ENABLE_SLOT), &slot_id);
 	rc = xhci_cmd(0, 0, TRB_TYPE(TRB_ENABLE_SLOT), &slot_id);
 	if (rc != 0 || slot_id == 0 || slot_id > max_slots) {
 	if (rc != 0 || slot_id == 0 || slot_id > max_slots) {
-		dbg("xhci: enable slot failed\n");
+		xlog_hex("xhci: enable slot failed rc ", rc);
+		xlog_hex(" cc ", cmd_status);
+		xlog_hex(" slot ", slot_id);
+		serial_putc(SERIAL_COM1, '\n');
 		return 0;
 		return 0;
 	}
 	}
 
 
@@ -726,8 +899,18 @@ static struct xhci_slot *new_slot_common(unsigned int target_addr,
 	s->used = 1;
 	s->used = 1;
 	s->slot_id = slot_id;
 	s->slot_id = slot_id;
 	s->addr = 0;
 	s->addr = 0;
-	s->port = (unsigned int)last_port;
-	s->speed = port_speed((unsigned int)last_port);
+	s->port = enum_port;
+	s->route = enum_route;
+	s->speed = enum_speed_hint ? enum_speed_hint :
+		   port_speed(enum_port);
+	if (enum_route && (s->speed == 1 || s->speed == 2)) {
+		s->tt_slot = enum_tt_slot;
+		s->tt_port = enum_route & 0xFu;
+	} else {
+		/* High/SuperSpeed devices do not go through a TT. */
+		s->tt_slot = 0;
+		s->tt_port = 0;
+	}
 	s->dc = dc;
 	s->dc = dc;
 	s->ep0 = ep0;
 	s->ep0 = ep0;
 	s->ep0_enq = 0;
 	s->ep0_enq = 0;
@@ -744,7 +927,8 @@ static struct xhci_slot *new_slot_common(unsigned int target_addr,
 	zero_page(input_ctx, 4096);
 	zero_page(input_ctx, 4096);
 	*(unsigned int *)input_ctx = 0;
 	*(unsigned int *)input_ctx = 0;
 	*(unsigned int *)(input_ctx + 4) = SLOT_FLAG | EP0_FLAG;
 	*(unsigned int *)(input_ctx + 4) = SLOT_FLAG | EP0_FLAG;
-	fill_slot_ctx(0, s->port, s->speed, 1);
+	fill_slot_ctx(0, s->port, s->route, s->tt_slot, s->tt_port,
+		      s->speed, 1);
 	fill_ep0_ctx(mps, ep0, s->ep0_enq, s->ep0_cycle);
 	fill_ep0_ctx(mps, ep0, s->ep0_enq, s->ep0_cycle);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 
 
@@ -755,6 +939,9 @@ static struct xhci_slot *new_slot_common(unsigned int target_addr,
 		xlog_hex(bsr ? "xhci: address default failed port " :
 		xlog_hex(bsr ? "xhci: address default failed port " :
 			 "xhci: address device failed port ", s->port);
 			 "xhci: address device failed port ", s->port);
 		xlog_hex(" spd ", s->speed);
 		xlog_hex(" spd ", s->speed);
+		xlog_hex(" route ", s->route);
+		xlog_hex(" tt ", s->tt_slot);
+		xlog_hex(" ttp ", s->tt_port);
 		xlog_hex(" cc ", cmd_status);
 		xlog_hex(" cc ", cmd_status);
 		xlog_hex(" portsc ",
 		xlog_hex(" portsc ",
 			 mmio_rd(op(XHCI_OP_PORTSC) + s->port * 0x10));
 			 mmio_rd(op(XHCI_OP_PORTSC) + s->port * 0x10));
@@ -773,7 +960,10 @@ static struct xhci_slot *new_slot_common(unsigned int target_addr,
 	s->dev_addr = ((unsigned int *)s->dc)[3] & 0xFF;
 	s->dev_addr = ((unsigned int *)s->dc)[3] & 0xFF;
 	s->addr = bsr ? 0 : target_addr;
 	s->addr = bsr ? 0 : target_addr;
 	addr_slot[s->addr] = slot_id;
 	addr_slot[s->addr] = slot_id;
-	port_slot[s->port] = slot_id;
+	if (s->route == 0)
+		port_slot[s->port] = slot_id;
+	if (!bsr)
+		(void)xhci_configure_slot(s);
 	return s;
 	return s;
 }
 }
 
 
@@ -820,7 +1010,7 @@ static void free_slot(struct xhci_slot *s)
 		bulk_reset(&bulk_in);
 		bulk_reset(&bulk_in);
 	if (bulk_out.active && bulk_out.slot == s->slot_id)
 	if (bulk_out.active && bulk_out.slot == s->slot_id)
 		bulk_reset(&bulk_out);
 		bulk_reset(&bulk_out);
-	if (s->port < XHCI_MAX_PORTS)
+	if (s->route == 0 && s->port < XHCI_MAX_PORTS)
 		port_slot[s->port] = 0;
 		port_slot[s->port] = 0;
 	s->used = 0;
 	s->used = 0;
 	s->addr = 0;
 	s->addr = 0;
@@ -843,7 +1033,8 @@ static int set_address(unsigned int new_addr, unsigned int mps)
 	zero_page(input_ctx, 4096);
 	zero_page(input_ctx, 4096);
 	*(unsigned int *)input_ctx = 0;
 	*(unsigned int *)input_ctx = 0;
 	*(unsigned int *)(input_ctx + 4) = SLOT_FLAG | EP0_FLAG;
 	*(unsigned int *)(input_ctx + 4) = SLOT_FLAG | EP0_FLAG;
-	fill_slot_ctx(0, s->port, s->speed, 1);
+	fill_slot_ctx(0, s->port, s->route, s->tt_slot, s->tt_port,
+		      s->speed, 1);
 	fill_ep0_ctx(mps, s->ep0, s->ep0_enq, s->ep0_cycle);
 	fill_ep0_ctx(mps, s->ep0, s->ep0_enq, s->ep0_cycle);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 
 
@@ -861,6 +1052,7 @@ static int set_address(unsigned int new_addr, unsigned int mps)
 	s->addr = new_addr;
 	s->addr = new_addr;
 	addr_slot[new_addr] = s->slot_id;
 	addr_slot[new_addr] = s->slot_id;
 	spin_unlock_irqrestore(&xhci_lock, flags);
 	spin_unlock_irqrestore(&xhci_lock, flags);
+	(void)xhci_configure_slot(s);
 	return 0;
 	return 0;
 }
 }
 
 
@@ -901,10 +1093,9 @@ static int control_transfer(unsigned int ctrl, unsigned int addr,
 	unsigned int setup_c, data_c, status_c;
 	unsigned int setup_c, data_c, status_c;
 	unsigned int last_bell;
 	unsigned int last_bell;
 
 
-	(void)ctrl;
 	(void)low_speed;
 	(void)low_speed;
 
 
-	if (!found)
+	if (!xhci_use(ctrl))
 		return -1;
 		return -1;
 
 
 	/* xHCI owns SET_ADDRESS: it is an Address Device command, not a
 	/* xHCI owns SET_ADDRESS: it is an Address Device command, not a
@@ -1044,22 +1235,29 @@ static int control_transfer(unsigned int ctrl, unsigned int addr,
 /* ---- HID interrupt endpoint -------------------------------------------- */
 /* ---- HID interrupt endpoint -------------------------------------------- */
 static int int_in_start(unsigned int ctrl, unsigned int slot,
 static int int_in_start(unsigned int ctrl, unsigned int slot,
 			unsigned int addr, unsigned int ep,
 			unsigned int addr, unsigned int ep,
-			unsigned int mps, int low_speed)
+			unsigned int mps, unsigned int len, int low_speed)
 {
 {
-	struct xhci_slot *s = slot_by_addr(addr);
+	struct xhci_slot *s;
 	struct xhci_int *in;
 	struct xhci_int *in;
 	unsigned int ep_index, ep_id, ring, flags;
 	unsigned int ep_index, ep_id, ring, flags;
 	int rc;
 	int rc;
 
 
-	(void)ctrl;
 	(void)low_speed;
 	(void)low_speed;
 
 
-	if (!found || !s || slot >= USB_HCD_INT_SLOTS || ep < 1 || ep > 15)
+	if (!xhci_use(ctrl))
+		return -1;
+	s = slot_by_addr(addr);
+	if (!s || slot >= USB_HCD_INT_SLOTS || ep < 1 || ep > 15)
 		return -1;
 		return -1;
+	int_ctrl[slot] = ctrl;
 	if (mps < 1)
 	if (mps < 1)
 		mps = 8;
 		mps = 8;
-	if (mps > 8)
-		mps = 8;
+	if (mps > 64)
+		mps = 64;
+	if (len < 1)
+		len = mps;
+	if (len > USB_INT_MAX)
+		len = USB_INT_MAX;
 
 
 	if (ints[slot].active)
 	if (ints[slot].active)
 		stop_int(slot);
 		stop_int(slot);
@@ -1078,7 +1276,7 @@ static int int_in_start(unsigned int ctrl, unsigned int slot,
 	in->ring = ring;
 	in->ring = ring;
 	in->enq = 0;
 	in->enq = 0;
 	in->cycle = 1;
 	in->cycle = 1;
-	in->trb_len = mps;
+	in->trb_len = len;
 	in->pending = 0;
 	in->pending = 0;
 	in->error = 0;
 	in->error = 0;
 	in->active = 0;
 	in->active = 0;
@@ -1109,7 +1307,7 @@ static int int_in_poll(unsigned int slot, unsigned char *buf, unsigned int len)
 	struct xhci_int *in;
 	struct xhci_int *in;
 	unsigned int flags, n, i;
 	unsigned int flags, n, i;
 
 
-	if (!found || slot >= USB_HCD_INT_SLOTS)
+	if (!xhci_use_slot(slot))
 		return 0;
 		return 0;
 
 
 	in = &ints[slot];
 	in = &ints[slot];
@@ -1163,6 +1361,13 @@ static void stop_int(unsigned int slot)
 	spin_unlock_irqrestore(&xhci_lock, flags);
 	spin_unlock_irqrestore(&xhci_lock, flags);
 }
 }
 
 
+static void int_in_stop(unsigned int slot)
+{
+	if (!xhci_use_slot(slot))
+		return;
+	stop_int(slot);
+}
+
 /* ---- bulk transfers ---------------------------------------------------- */
 /* ---- bulk transfers ---------------------------------------------------- */
 static void bulk_reset(struct xhci_bulk *b)
 static void bulk_reset(struct xhci_bulk *b)
 {
 {
@@ -1181,13 +1386,16 @@ static void bulk_reset(struct xhci_bulk *b)
 static int xhci_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 static int xhci_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 		   unsigned int mps, unsigned char *buf, unsigned int len)
 		   unsigned int mps, unsigned char *buf, unsigned int len)
 {
 {
-	struct xhci_slot *s = slot_by_addr(addr);
-	struct xhci_bulk *b = &bulk_in;
+	struct xhci_slot *s;
+	struct xhci_bulk *b;
 	unsigned int ep_index, ep_id, ring, flags, n, err;
 	unsigned int ep_index, ep_id, ring, flags, n, err;
 	int rc;
 	int rc;
 
 
-	(void)ctrl;
-	if (!found || !s || ep < 1 || ep > 15 || !buf || !len)
+	if (!xhci_use(ctrl))
+		return -1;
+	b = &bulk_in;
+	s = slot_by_addr(addr);
+	if (!s || ep < 1 || ep > 15 || !buf || !len)
 		return -1;
 		return -1;
 	if (mps < 1)
 	if (mps < 1)
 		mps = 512;
 		mps = 512;
@@ -1254,12 +1462,15 @@ static int xhci_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 static void xhci_bulk_reset(unsigned int ctrl, unsigned int addr,
 static void xhci_bulk_reset(unsigned int ctrl, unsigned int addr,
 			    unsigned int ep, int dir_in)
 			    unsigned int ep, int dir_in)
 {
 {
-	struct xhci_slot *s = slot_by_addr(addr);
-	struct xhci_bulk *b = dir_in ? &bulk_in : &bulk_out;
+	struct xhci_slot *s;
+	struct xhci_bulk *b;
 	unsigned int flags, slot, ep_id;
 	unsigned int flags, slot, ep_id;
 
 
-	(void)ctrl;
-	if (!found || !s)
+	if (!xhci_use(ctrl))
+		return;
+	s = slot_by_addr(addr);
+	b = dir_in ? &bulk_in : &bulk_out;
+	if (!s)
 		return;
 		return;
 
 
 	spin_lock_irqsave(&xhci_lock, &flags);
 	spin_lock_irqsave(&xhci_lock, &flags);
@@ -1284,13 +1495,16 @@ static int xhci_bulk_out(unsigned int ctrl, unsigned int addr, unsigned int ep,
 		    unsigned int mps, const unsigned char *buf,
 		    unsigned int mps, const unsigned char *buf,
 		    unsigned int len)
 		    unsigned int len)
 {
 {
-	struct xhci_slot *s = slot_by_addr(addr);
-	struct xhci_bulk *b = &bulk_out;
+	struct xhci_slot *s;
+	struct xhci_bulk *b;
 	unsigned int ep_index, ep_id, ring, flags, t0, done, status;
 	unsigned int ep_index, ep_id, ring, flags, t0, done, status;
 	int rc;
 	int rc;
 
 
-	(void)ctrl;
-	if (!found || !s || ep < 1 || ep > 15 || !buf || !len)
+	if (!xhci_use(ctrl))
+		return -1;
+	b = &bulk_out;
+	s = slot_by_addr(addr);
+	if (!s || ep < 1 || ep > 15 || !buf || !len)
 		return -1;
 		return -1;
 	if (mps < 1)
 	if (mps < 1)
 		mps = 512;
 		mps = 512;
@@ -1371,13 +1585,21 @@ static int port_reset(unsigned int ctrl, unsigned int port)
 {
 {
 	unsigned int ps, t0;
 	unsigned int ps, t0;
 
 
-	(void)ctrl;
-	if (!found || port >= max_ports ||
-	    !(port_mask & (1u << port)))
+	if (!xhci_use(ctrl))
+		return -1;
+	if (port >= max_ports || !(port_mask & (1u << port)))
 		return -1;
 		return -1;
 
 
 	if (port_slot[port])
 	if (port_slot[port])
 		free_slot(&slots[port_slot[port]]);
 		free_slot(&slots[port_slot[port]]);
+	{
+		unsigned int i;
+
+		for (i = 1; i <= max_slots && i <= XHCI_MAX_SLOTS; i++)
+			if (slots[i].used && slots[i].route == 0 &&
+			    slots[i].port == port)
+				free_slot(&slots[i]);
+	}
 
 
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	if (!(ps & PORTSC_CCS))
 	if (!(ps & PORTSC_CCS))
@@ -1455,9 +1677,9 @@ static int port_connected(unsigned int ctrl, unsigned int port)
 {
 {
 	unsigned int ps;
 	unsigned int ps;
 
 
-	(void)ctrl;
-	if (!found || port >= max_ports ||
-	    !(port_mask & (1u << port)))
+	if (!xhci_use(ctrl))
+		return 0;
+	if (port >= max_ports || !(port_mask & (1u << port)))
 		return 0;
 		return 0;
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	return (ps & PORTSC_CCS) ? 1 : 0;
 	return (ps & PORTSC_CCS) ? 1 : 0;
@@ -1467,8 +1689,9 @@ static int port_low_speed(unsigned int ctrl, unsigned int port)
 {
 {
 	unsigned int ps;
 	unsigned int ps;
 
 
-	(void)ctrl;
-	if (!found || port >= max_ports)
+	if (!xhci_use(ctrl))
+		return 0;
+	if (port >= max_ports)
 		return 0;
 		return 0;
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	return ((ps >> PORTSC_SPEED_SHIFT) & PORTSC_SPEED_MASK) == 2;
 	return ((ps >> PORTSC_SPEED_SHIFT) & PORTSC_SPEED_MASK) == 2;
@@ -1478,8 +1701,9 @@ static int port_take_change(unsigned int ctrl, unsigned int port)
 {
 {
 	unsigned int ps;
 	unsigned int ps;
 
 
-	(void)ctrl;
-	if (!found || port >= max_ports)
+	if (!xhci_use(ctrl))
+		return 0;
+	if (port >= max_ports)
 		return 0;
 		return 0;
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	ps = mmio_rd(op(XHCI_OP_PORTSC) + port * 0x10);
 	if (!(ps & PORTSC_CSC))
 	if (!(ps & PORTSC_CSC))
@@ -1575,52 +1799,23 @@ static void scan_protocols(void)
 			    ((1u << max_ports) - 1);
 			    ((1u << max_ports) - 1);
 }
 }
 
 
-static int xhci_init(void)
+static int xhci_init_one(unsigned int bus, unsigned int dev,
+			 unsigned int func, unsigned int bar)
 {
 {
-	unsigned int bus, dev, func, id, class_rev, bar, bar_hi, cmd;
+	unsigned int cmd;
 	unsigned int hcs1, hcs2, t0, i, n, scratch;
 	unsigned int hcs1, hcs2, t0, i, n, scratch;
 
 
-	if (found)
-		return 1;
-
-	for (bus = 0; bus < 256; bus++) {
-		for (dev = 0; dev < 32; dev++) {
-			for (func = 0; func < 8; func++) {
-				id = pci_cfg_read32(bus, dev, func, 0x00);
-				if (id == 0xFFFFFFFFu || id == 0)
-					continue;
-				class_rev = pci_cfg_read32(bus, dev, func, 0x08);
-				if ((class_rev >> 16) != 0x0C03)
-					continue;
-				if (((class_rev >> 8) & 0xFF) != 0x30)
-					continue;
-				bar = pci_cfg_read32(bus, dev, func, 0x10);
-				if (bar & 1)
-					continue;
-				bar_hi = 0;
-				if ((bar & 0x6) == 0x4)
-					bar_hi = pci_cfg_read32(bus, dev,
-								func, 0x14);
-				bar &= 0xFFFFFFF0u;
-				if (!bar || bar_hi)
-					continue;
-				pci_bus = bus;
-				pci_dev = dev;
-				pci_func = func;
-				goto found_xhci;
-			}
-		}
-	}
-	return 0;
-
-found_xhci:
+	pci_bus = bus;
+	pci_dev = dev;
+	pci_func = func;
+	last_port = -1;
 	cmd = pci_cfg_read32(pci_bus, pci_dev, pci_func, 0x04);
 	cmd = pci_cfg_read32(pci_bus, pci_dev, pci_func, 0x04);
 	pci_cfg_write32(pci_bus, pci_dev, pci_func, 0x04, cmd | 0x0006);
 	pci_cfg_write32(pci_bus, pci_dev, pci_func, 0x04, cmd | 0x0006);
 
 
 	mmio_phys = bar;
 	mmio_phys = bar;
 	mmio_base = (unsigned int)ioremap(bar, 0x10000, IOREMAP_MMIO);
 	mmio_base = (unsigned int)ioremap(bar, 0x10000, IOREMAP_MMIO);
 	if (!mmio_base)
 	if (!mmio_base)
-		return -1;
+		return 0;
 
 
 	pci_id = pci_cfg_read32(pci_bus, pci_dev, pci_func, 0x00);
 	pci_id = pci_cfg_read32(pci_bus, pci_dev, pci_func, 0x00);
 	cap_len = mmio_rd(0) & 0xFF;
 	cap_len = mmio_rd(0) & 0xFF;
@@ -1820,16 +2015,93 @@ found_xhci:
 	return 1;
 	return 1;
 }
 }
 
 
+static int xhci_seen(unsigned int bus, unsigned int dev, unsigned int func)
+{
+	unsigned int i;
+
+	for (i = 0; i < xhci_nctrl; i++)
+		if (xhci_hcds[i].bus_no == bus &&
+		    xhci_hcds[i].dev_no == dev &&
+		    xhci_hcds[i].func_no == func)
+			return 1;
+	return 0;
+}
+
+static int xhci_init(void)
+{
+	unsigned int bus, dev, func, id, class_rev, bar, bar_hi;
+
+	if (xhci_nctrl)
+		return (int)xhci_nctrl;
+
+	if (!xhci_hcds) {
+		unsigned int pages = (XHCI_MAX_HCD * sizeof(*xhci_hcds) +
+				      4095u) / 4096u;
+
+		xhci_hcds = (struct xhci_hcd *)mm_alloc_pages(pages);
+		if (!xhci_hcds)
+			return 0;
+		zero_page((unsigned int)xhci_hcds, pages * 4096);
+	}
+
+	for (bus = 0; bus < 256; bus++) {
+		for (dev = 0; dev < 32; dev++) {
+			for (func = 0; func < 8; func++) {
+				id = pci_cfg_read32(bus, dev, func, 0x00);
+				if (id == 0xFFFFFFFFu || id == 0)
+					continue;
+				class_rev = pci_cfg_read32(bus, dev, func, 0x08);
+				if ((class_rev >> 16) != 0x0C03)
+					continue;
+				if (((class_rev >> 8) & 0xFF) != 0x30)
+					continue;
+				if (xhci_seen(bus, dev, func))
+					continue;
+				bar = pci_cfg_read32(bus, dev, func, 0x10);
+				if (bar & 1)
+					continue;
+				bar_hi = 0;
+				if ((bar & 0x6) == 0x4)
+					bar_hi = pci_cfg_read32(bus, dev,
+								func, 0x14);
+				bar &= 0xFFFFFFF0u;
+				xlog_hex("xhci: pci ", id);
+				xlog_hex(" loc ",
+					 (bus << 16) | (dev << 11) |
+					 (func << 8));
+				xlog_hex(" bar ", bar);
+				xlog_hex(" hi ", bar_hi);
+				serial_putc(SERIAL_COM1, '\n');
+				if (!bar || bar_hi)
+					continue;
+				if (xhci_nctrl >= XHCI_MAX_HCD)
+					return (int)xhci_nctrl;
+				xh = &xhci_hcds[xhci_nctrl];
+				zero_page((unsigned int)xh, sizeof(*xh));
+				xh->last_port_num = -1;
+				if (xhci_init_one(bus, dev, func, bar))
+					xhci_nctrl++;
+			}
+		}
+	}
+	return (int)xhci_nctrl;
+}
+
 static unsigned int xhci_count(void)
 static unsigned int xhci_count(void)
 {
 {
-	return found ? 1u : 0u;
+	return xhci_nctrl;
 }
 }
 
 
 static void xhci_info(unsigned int ctrl, unsigned int *bus,
 static void xhci_info(unsigned int ctrl, unsigned int *bus,
 		      unsigned int *dev, unsigned int *func,
 		      unsigned int *dev, unsigned int *func,
 		      unsigned int *base, int *mmio)
 		      unsigned int *base, int *mmio)
 {
 {
-	(void)ctrl;
+	if (!xhci_use(ctrl)) {
+		*bus = *dev = *func = 0;
+		*base = 0;
+		*mmio = 1;
+		return;
+	}
 	*bus = pci_bus;
 	*bus = pci_bus;
 	*dev = pci_dev;
 	*dev = pci_dev;
 	*func = pci_func;
 	*func = pci_func;
@@ -1839,8 +2111,9 @@ static void xhci_info(unsigned int ctrl, unsigned int *bus,
 
 
 static unsigned int xhci_port_count(unsigned int ctrl)
 static unsigned int xhci_port_count(unsigned int ctrl)
 {
 {
-	(void)ctrl;
-	return found ? max_ports : 0;
+	if (!xhci_use(ctrl))
+		return 0;
+	return max_ports;
 }
 }
 
 
 const struct usb_hcd_ops usb_xhci_ops = {
 const struct usb_hcd_ops usb_xhci_ops = {
@@ -1856,9 +2129,10 @@ const struct usb_hcd_ops usb_xhci_ops = {
 	port_take_change,
 	port_take_change,
 	int_in_start,
 	int_in_start,
 	int_in_poll,
 	int_in_poll,
-	stop_int,
+	int_in_stop,
 	xhci_bulk_out,
 	xhci_bulk_out,
 	xhci_bulk_in,
 	xhci_bulk_in,
 	xhci_bulk_reset,
 	xhci_bulk_reset,
 	0,
 	0,
+	set_route,
 };
 };

+ 14 - 1
tools/qmp_cursor_test.py

@@ -120,7 +120,8 @@ def move(s, dx, dy):
 
 
 def main():
 def main():
     mode = "ohci"
     mode = "ohci"
-    for m in ("uhci", "uhci72", "multi", "hotplug", "xhci", "ehci"):
+    for m in ("uhci", "uhci72", "multi", "hotplug", "xhci", "xhci2",
+              "xhci2hub", "ehci", "hub"):
         if "--" + m in sys.argv:
         if "--" + m in sys.argv:
             mode = m
             mode = m
 
 
@@ -145,6 +146,18 @@ def main():
         qemu += ["-device", "pci-ohci"]
         qemu += ["-device", "pci-ohci"]
     elif mode == "xhci":
     elif mode == "xhci":
         qemu += ["-device", "qemu-xhci", "-device", "usb-mouse"]
         qemu += ["-device", "qemu-xhci", "-device", "usb-mouse"]
+    elif mode == "xhci2":
+        qemu += ["-device", "qemu-xhci,id=xhci0",
+                 "-device", "qemu-xhci,id=xhci1",
+                 "-device", "usb-mouse,bus=xhci1.0"]
+    elif mode == "xhci2hub":
+        qemu += ["-device", "qemu-xhci,id=xhci0",
+                 "-device", "qemu-xhci,id=xhci1",
+                 "-device", "usb-hub,bus=xhci1.0,port=1,id=hub1",
+                 "-device", "usb-mouse,bus=xhci1.0,port=1.2"]
+    elif mode == "hub":
+        qemu += ["-device", "qemu-xhci", "-device", "usb-hub,id=hub0",
+                 "-device", "usb-mouse,bus=usb-bus.0,port=1.2"]
     elif mode == "ehci":
     elif mode == "ehci":
         qemu += ["-device", "usb-ehci,id=ehci0",
         qemu += ["-device", "usb-ehci,id=ehci0",
                  "-device", "piix3-usb-uhci,id=uhci0",
                  "-device", "piix3-usb-uhci,id=uhci0",