Преглед изворни кода

usb: fix boot-time mass-storage stalls

The ION's SanDisk NAKs its first READ(10) data stage after enumeration,
and a timed-out EHCI bulk-IN qTD stayed armed, so the boot scan sat in
the reset/retry chain for 9-21 s.

- EHCI: ring the async-advance doorbell after an idle gap and before
  cancelling a stuck bulk transfer; cancel a timed-out IN qTD and reset
  its data toggle; xHCI stops the endpoint before dropping its ring.
- usbmsc: clear both host-side toggles after the BOT reset's
  CLEAR_FEATURE requests, re-apply SET_CONFIGURATION once, request sense
  only after a CSW status error, and give the first media read a longer
  deadline (5 s best-effort boot probe, 15 s full scan).
- VFS: defer USB mounts until the bootscan window has closed; recognize
  the NebOS MBR layout without reading P1; do not probe a valid non-FAT
  MBR as a superfloppy; skip a partition whose boot sector is unreadable.
- The boot background USB pass can no longer delay the desktop, /ramfs,
  /share, the bootscan window or the WiFi autoconnect.
Johannes Zellner пре 2 дана
родитељ
комит
17fcbc512e
19 измењених фајлова са 486 додато и 48 уклоњено
  1. 50 10
      AGENTS.md
  2. 1 1
      docs/boot.html
  3. 15 3
      docs/drivers.html
  4. 1 0
      docs/filesystems.html
  5. 3 3
      docs/network.html
  6. 1 1
      docs/userland.html
  7. 122 5
      kernel/ehci.c
  8. 8 3
      kernel/kernel.c
  9. 1 0
      kernel/ohci.c
  10. 1 1
      kernel/sys_fs.c
  11. 1 0
      kernel/uhci.c
  12. 10 0
      kernel/usb.c
  13. 4 0
      kernel/usb.h
  14. 6 0
      kernel/usb_hcd.h
  15. 105 8
      kernel/usbmsc.c
  16. 10 0
      kernel/usbmsc.h
  17. 105 11
      kernel/vfs.c
  18. 8 2
      kernel/vfs.h
  19. 34 0
      kernel/xhci.c

+ 50 - 10
AGENTS.md

@@ -239,8 +239,9 @@ and `make net-dev`/`kernel-net-dev` reload over the network.  `bootlog save
    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
    (non-preemptible, as before the WM existed: reset/SOF timing) → NIC probe
-   → kworker → the `bootscan` kernel thread (storage scan + FAT mounts, then
-   the `/data` WiFi autoconnect once the boot DHCP finished) → DHCP.  So
+   → kworker → the `bootscan` kernel thread (non-USB storage scan + FAT
+   mounts, then the deferred USB mounts, then the `/data` WiFi autoconnect
+   once the boot DHCP finished) → DHCP.  So
    the terminal is on screen before USB, NIC and disks are probed; USB
    input, USB NICs and USB disks attach right after.  The WM's
    `SYS_NET_INFO` does not trigger the NIC probe (it reports "no NIC" until
@@ -816,7 +817,23 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   are no-ops.  A USB disk read by the rescan claims the USB bus
   (`usb_bus_claim()` in `usbmsc_read/write/flush`), so its HCD waits yield
   as well (see the USB bullet).  So `storage` no longer freezes the WM.  `disk_probe()` skips
-  a floppy whose CMOS drive type (register `0x10`) is 0.
+  a floppy whose CMOS drive type (register `0x10`) is 0.  `mount_device()`
+  recognises the NebOS MBR layout (`mbr_is_nebos_layout()`: active type-0x06
+  P1 at LBA 63 of 1024 sectors and P2 at LBA 1088) and skips P1 without
+  reading it, so scanning the boot stick costs only its MBR read; a valid MBR
+  whose partitions are all non-FAT is not probed as a superfloppy, and an
+  unreadable partition boot sector is skipped rather than mounted.
+  The boot call passes `skip_usb`: USB block devices are logged as `deferred`
+  and mounted later by `vfs_mount_usb()` after the boot-scan window has
+  closed, so a card reader or stick that NAKs its first media read for
+  seconds cannot delay the desktop, `/ramfs`, `/share` or the network.  The
+  background pass appends to the existing mount table and skips devices that
+  are already mounted; the `storage` command's rescan still uses the full
+  scan (`vfs_mount_all(0)`).  The background pass sets
+  `usbmsc_set_probe_only(1)`: a device's first media read gets one 5 s
+  attempt without the reset/retry chain, so a stuck USB disk cannot hold
+  `vfs_scan_busy` behind the boot.  A later `storage` rescan uses the normal
+  15 s first-read deadline and retries (`MSC_FIRST_READ_MS`).
 - **Installer**: `install.c/h` — the privileged `install <target> [source|self]`
   command clones the live NebOS image or writes the running image.  A clone
   detects a source by the MBR plus the LBA-63 boot-sector signature (`NEBOS`
@@ -856,7 +873,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   before the backend (`sys_fs_begin_w`).  The app saves the table as
   `MOUNTS.CFG` (`"NBMNT1\n\0"` + records) on the `NEBOSDATA` volume; the
   `bootscan` thread calls `sys_mount_load_config()` after `vfs_mount_all()`
-  and applies `/data/MOUNTS.CFG`.  The data volume itself is not editable
+  and again after `vfs_mount_usb()`, applying a `/data/MOUNTS.CFG` that only
+  appeared with the deferred USB volume.  The data volume itself is not editable
   from the app (it stores the file).  Format and install run the kernel
   commands with `-y` (which skips their raw-keyboard y/n prompt; the app
   confirms in its own dialog) through `SYS_SPAWN_KCMD` on a private tty and
@@ -1053,8 +1071,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   known SSID replaces its record and moves it to the front, and a full list
   drops the least recently used network.  Each record leaves the BSSID zero
   so a mesh/repeater AP with the same SSID still works.  After the storage
-  scan and the boot DHCP attempt the `bootscan` thread spawns
-  `/ramfs/bin/wifi autoconnect` when that file exists.  Autoconnect leaves a
+  scan, the deferred USB mount pass and the boot DHCP attempt the `bootscan`
+  thread spawns `/ramfs/bin/wifi autoconnect` when that file exists.  Autoconnect leaves a
   wired link that is physically up alone, and an already-linked WiFi card
   too.  Otherwise it scans once and joins the strongest network present whose
   SSID is in the saved list, moves on to the other saved networks found if
@@ -1532,7 +1550,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `serial_putc()` passes every COM1 character through `bootcon_scan_char()`,
   which keeps only the owning thread's output (CRs dropped) in a 16 KB
   frame-allocated ring.  The ring survives the thread, so a later manual
-  `bootscan` launch still shows the completed scan.  `SYS_BOOTLOG` (122, STAT
+  `bootscan` launch still shows the completed scan.  The deferred USB mount
+  pass runs after `bootcon_scan_end()`, so its lines go to COM1/netmon but
+  not into the window; the window's scan completes before the slow USB
+  probe.  `SYS_BOOTLOG` (122, STAT
   fills `struct sys_bootlog` with total/start/capacity/active, READ copies
   one 1 KB chunk from an absolute offset) is the ring-3 view.  The WM spawns
   the window before the terminal, waits (2 s bound) for it to appear and
@@ -2477,7 +2498,14 @@ briefly reporting disconnected.
   Disabling clears ASE and acknowledges `STS_IAA`; leaving the IAA doorbell
   status set stalls the next enable.  Bulk `in`/`out` use one qTD per call
   (up to five 4 KB buffer pages), which is enough for the ASIX AX88772 RX/TX
-  path.
+  path.  The HCD vtable's optional `bulk_reset` disarms the endpoint's qTD,
+  clears its data toggle and drops the bulk state, so a timed-out bulk-IN
+  transfer cannot leave the endpoint permanently armed; xHCI stops the
+  endpoint before dropping its ring.  After an async-transfer gap of 100 ms
+  (and before cancelling a stuck bulk transfer) the EHCI driver rings the
+  async-advance doorbell (`IAAD`) and waits for `STS_IAA`: the MCP79 can
+  keep a halted QH's old qTD cached, and without the handshake the first
+  USB-disk read after enumeration/`kexec` stays ACTIVE and times out.
   There is no transaction translator: low/full-speed devices behind a
   high-speed hub stay invisible to EHCI (use the companion controller for
   them).
@@ -2577,8 +2605,20 @@ briefly reporting disconnected.
   with SCSI INQUIRY + READ CAPACITY.  Commands use BOT CBW/CSW with LUN 0,
   512-byte blocks and at most 62 sectors per data stage; READ(10), WRITE(10),
   SYNCHRONIZE CACHE, a BOT reset and endpoint-halt clear are implemented.
-  Short bulk-IN chunks are accumulated within a BOT data stage; a failed
-  READ(10) gets REQUEST SENSE, three retries and a 1-sector fallback.
+  Short bulk-IN chunks are accumulated within a BOT data stage; a READ(10)
+  that completed with a non-zero CSW status gets REQUEST SENSE (a transport
+  timeout goes straight to the reset), then three retries and a 1-sector
+  fallback.  A timed-out bulk-IN transfer is cancelled through the HCD's
+  `bulk_reset` and the BOT reset clears both host-side data toggles after
+  the CLEAR_FEATURE requests, matching the device's DATA0 state (QEMU
+  tolerates the mismatch, real EHCI hardware does not; without this a single
+  timeout/unit-attention wedged every later transfer).  After the first
+  failed attempt the driver also re-applies SET_CONFIGURATION once, which
+  resets the device's endpoints/toggles without a port reset while keeping
+  its address and endpoint numbers.  The boot background pass sets
+  `usbmsc_set_probe_only(1)` so a stuck first media read is abandoned after
+  5 s instead of running the reset/retry chain; a `storage` rescan uses the
+  full path.
   `blk_scan()` registers present devices as `usb0..` (`BLK_USB`), so
   `storage`, the VFS mount path, `format` and `install` can use them.  Bulk
   transfers exist only on EHCI and xHCI; a storage device on a UHCI/OHCI

+ 1 - 1
docs/boot.html

@@ -413,7 +413,7 @@
 			<li>Inflate the command pack into <code>/ramfs</code> (table-driven whole-buffer inflate); start the WM and the first frame.</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>Start the <code>bootscan</code> kernel thread (storage probe + FAT mounts, then the <code>/data</code> WiFi autoconnect once the boot DHCP is done); its COM1 output is captured into the <code>SYS_BOOTLOG</code> ring, which the <code>bootscan</code> window tails live. Run DHCP if needed.</li>
+			<li>Start the <code>bootscan</code> kernel thread (non-USB storage probe + FAT mounts, then the deferred USB mounts after the scan window closes, then the <code>/data</code> WiFi autoconnect once the boot DHCP is done); its COM1 output is captured into the <code>SYS_BOOTLOG</code> ring, which the <code>bootscan</code> window tails live. The deferred USB pass can wait seconds for a slow card reader without holding up the desktop, the scan window or the other volumes. Run DHCP if needed.</li>
 			<li>Enable scheduling on the APs and enter the kernel idle loop.</li>
 		</ol>
 		<p>

+ 15 - 3
docs/drivers.html

@@ -290,7 +290,7 @@
 				<tbody>
 					<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>EHCI</td><td>PCI MMIO</td><td>up to 4</td><td>Async QH/qTD schedule, page-allocated descriptors, polling only, no periodic list.</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.</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>
 				</tbody>
 			</table>
@@ -360,8 +360,20 @@
 			Bulk-Only Transport with LUN 0 and 512-byte blocks: READ(10),
 			WRITE(10), SYNCHRONIZE CACHE and a BOT reset/endpoint-halt recovery.
 			Short bulk-IN chunks are accumulated within a BOT data stage; a
-			failed READ(10) gets REQUEST SENSE, retries and a 1-sector
-			fallback. Present devices are registered as <code>usb0..</code>
+			READ(10) that completed with a non-zero CSW status gets REQUEST
+			SENSE, retries and a 1-sector fallback, while a transport timeout
+			goes straight to the reset.  A timed-out bulk-IN transfer is
+			cancelled through the HCD's <code>bulk_reset</code> (EHCI disarms
+			the qTD and clears the data toggle; xHCI stops the endpoint before
+			dropping its ring), and the BOT reset clears both host-side toggles
+			after the CLEAR_FEATURE requests to match the device's DATA0 state
+			— QEMU tolerates the mismatch, real EHCI hardware does not.  After
+			the first failed attempt the driver re-applies SET_CONFIGURATION
+			once, resetting the device's endpoints and toggles without a port
+			reset. The boot background scan sets <code>usbmsc_set_probe_only</code>:
+			one 5 s first read without the reset/retry chain, so a stuck device
+			cannot hold the boot's disk scan; a <code>storage</code> rescan uses
+			the full path. Present devices are registered as <code>usb0..</code>
 			(<code>BLK_USB</code>) by <code>blk_scan()</code>, so
 			<code>storage</code>, the VFS, <code>format</code> and
 			<code>install</code> can use them.

+ 1 - 0
docs/filesystems.html

@@ -167,6 +167,7 @@
 			<li><strong>8.3 names.</strong> The on-disk name is the canonical one. The shell and <code>files</code> display the space-padded form; a long name cannot be created.</li>
 			<li><strong>Directory cache.</strong> The last FAT directory's first 64 entries are cached in <code>vfs.c</code>, so WebDAV's index sequence is one walk instead of N. Any write invalidates the cache.</li>
 			<li><strong>Serialization.</strong> A file operation runs in a non-preemptible section because the FAT driver has static state and the floppy needs IRQ 6; <code>vfs_scan_busy</code>/<code>format_busy</code> make it sleep first while a mount scan or a format owns the disks. A format releases the BKL for its raw-sector loop, and only disk-backed mounts wait for it, so <code>/ramfs</code> and <code>/share</code> stay usable.  A rescan (the <code>bootscan</code> thread or the <code>storage</code> command) re-adds <code>/ramfs</code>/<code>/share</code> first and is skipped by their operations too (<code>vfs_mount_is_ram</code>); it runs preemptible, and the floppy/ATA/AHCI/SDHCI wait loops (including the SDHCI command and CMD1 power-up polls) call <code>vfs_scan_poll</code>/<code>vfs_scan_relax</code>, which sleep (dropping the BKL) once a wait passes 2 ms and only for the scan's owning process.  A USB disk read by the rescan claims the USB bus (<code>usb_bus_claim()</code>), so its host-controller waits yield too; <code>storage</code> no longer freezes the WM.  The floppy probe is skipped for a drive whose CMOS type (register <code>0x10</code>) is 0.</li>
+			<li><strong>Mount scan.</strong> <code>mount_device()</code> recognises the NebOS MBR layout (<code>mbr_is_nebos_layout()</code>: active type-0x06 P1 at LBA 63 of 1024 sectors, P2 at LBA 1088) and skips P1 without reading it, so the boot stick costs only its MBR read. A valid MBR whose partitions are all non-FAT is not probed as a superfloppy, and an unreadable partition boot sector is skipped rather than mounted as FAT. The boot scan calls <code>vfs_mount_all(1)</code>, which logs USB devices as <code>deferred</code>; <code>vfs_mount_usb()</code> appends them after the bootscan window has closed, so a card reader that NAKs its first read for seconds cannot delay the other mounts or the desktop. The background pass is best-effort: one 5 s first read without the reset/retry chain (<code>usbmsc_set_probe_only</code>). The <code>storage</code> command's rescan still does the full scan (<code>vfs_mount_all(0)</code>) with the normal 15 s first-read deadline and retries.</li>
 		</ul>
 		<p>
 			<span class="file">fatdetect.c</span> and <span class="file">fatformat.c</span>

+ 3 - 3
docs/network.html

@@ -208,9 +208,9 @@
 			network (or all of them without an SSID).
 		</p>
 		<p>
-			After the boot DHCP attempt and the storage scan, the
-			<code>bootscan</code> thread spawns <code>wifi autoconnect</code>
-			when that file exists. It samples the active NIC's
+			After the boot DHCP attempt, the storage scan and the deferred
+			USB mount pass, the <code>bootscan</code> thread spawns
+			<code>wifi autoconnect</code> when that file exists. It samples the active NIC's
 			<code>link_up()</code> state: a wired cable that is physically up
 			keeps the Ethernet path, while no wired link lets WiFi scan and
 			join the strongest network present whose SSID is in the saved list,

+ 1 - 1
docs/userland.html

@@ -350,7 +350,7 @@
 		<h2>GUI applications</h2>
 		<ul>
 			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
-			<li><strong>bootscan</strong> — live tail of the boot storage-scan kernel thread's output (the WM opens it before the terminal, flush right under the top bar). The kernel captures the thread's COM1 trail (mounts, probes, boot traces) into a ring exposed by <code>SYS_BOOTLOG</code>; the window follows the tail while the scan runs, keeps the scrollback afterwards, pauses the follow when scrolled up, and closes with Esc. Also startable from the shell.</li>
+			<li><strong>bootscan</strong> — live tail of the boot storage-scan kernel thread's output (the WM opens it before the terminal, flush right under the top bar). The kernel captures the thread's COM1 trail (mounts, probes, boot traces) into a ring exposed by <code>SYS_BOOTLOG</code>; the window follows the tail while the scan runs, keeps the scrollback afterwards, pauses the follow when scrolled up, and closes with Esc. The deferred USB mount pass runs after the window's ring closes, so its lines appear on COM1/netmon but not in the bootscan scrollback. Also startable from the shell.</li>
 			<li><strong>process</strong> — graphical task manager (start menu <em>Tasks</em> entry or <code>process</code>), the ngui counterpart of <code>top</code>. It samples once per second into 60 s histories of CPU busy (<code>SYS_SCHEDINFO</code> idle ticks summed over all CPUs), physical memory in use (<code>SYS_MEMINFO</code>) and NIC throughput (<code>SYS_NET_INFO.rx_bytes</code>/<code>tx_bytes</code> from the netdev frame counters), then draws the three graphs with ngui rectangles and lines. The table lists PID, state, CPU%, memory, total CPU time and name; clicking a header sorts by PID, state, CPU, memory, time or name, and PgUp/PgDn or the wheel scrolls. Selecting a row shows its details; <em>End task</em> asks for a second click and then calls <code>SYS_KILL</code>, while kernel threads (<code>kernel_thread</code> in the process snapshot) and the monitor itself are protected. Esc closes it.</li>
 			<li><strong>disks</strong> — storage manager (start menu <em>Disks</em> entry, or the <em>Disks</em> button in <code>files</code>): devices, MBR partitions and mounts; per-volume mount name, read-only and automount saved to <code>/data/MOUNTS.CFG</code>; Format and Install NebOS dialogs that run <code>format -y</code>/<code>install -y</code> on a private tty and show the log. See <a href="filesystems.html#disks">Filesystems → Storage manager</a>.</li>
 			<li><strong>gallery</strong> — live widget and primitive showcase; the real app ships in the pack.</li>

+ 122 - 5
kernel/ehci.c

@@ -148,6 +148,7 @@ struct ehci_bulk {
 	unsigned int mps;
 	unsigned int buf_len;
 	unsigned int toggle;
+	unsigned int arm_ms;
 	int armed;
 	int sched;
 	struct ehci_ctrl *owner;
@@ -204,6 +205,7 @@ struct ehci_ctrl {
 	int recovering;
 	int sched_on;
 	int sched_refs;
+	unsigned int last_async_ms;	/* last async transfer, for idle IAA */
 	unsigned char addr_port[128];
 };
 
@@ -247,8 +249,13 @@ static void ehci_sched_set(struct ehci_ctrl *c, int on)
 {
 	unsigned int v, t0;
 
-	if (on == c->sched_on)
-		return;
+	if (on == c->sched_on) {
+		/* The software flag can be stale if the controller lost ASE
+		 * (an error or an unexpected reset); re-check the hardware
+		 * before assuming the async schedule is running. */
+		if (!on || (rd32(op_reg(c, EHCI_OP_USBCMD)) & CMD_ASE))
+			return;
+	}
 	v = rd32(op_reg(c, EHCI_OP_USBCMD));
 	if (on) {
 		wr32(op_reg(c, EHCI_OP_USBCMD), v | CMD_ASE);
@@ -464,16 +471,53 @@ static void bulk_configure(struct ehci_bulk *b, unsigned int addr,
 	b->armed = 0;
 }
 
+/* Ask the controller to release the async-schedule state it has cached.
+ * NVIDIA/MCP79 can keep a halted QH's old qTD cached and never fetch the
+ * re-armed one, so the first transfer after an idle gap (a USB disk's first
+ * read after enumeration) stays ACTIVE and times out forever.  Linux and
+ * U-Boot work around this with the IAAD doorbell. */
+static void ehci_iaa_wait(struct ehci_ctrl *c)
+{
+	unsigned int v, t0;
+
+	if (rd32(op_reg(c, EHCI_OP_USBSTS)) & STS_HALT) {
+		serial_puts(SERIAL_COM1, "ehci: controller halted\n");
+		return;
+	}
+	/* Drop a stale acknowledgement before ringing the doorbell. */
+	wr32(op_reg(c, EHCI_OP_USBSTS), STS_IAA);
+	v = rd32(op_reg(c, EHCI_OP_USBCMD));
+	wr32(op_reg(c, EHCI_OP_USBCMD), v | CMD_IAAD);
+	t0 = get_ticks_ms();
+	while (!(rd32(op_reg(c, EHCI_OP_USBSTS)) & STS_IAA)) {
+		if (get_ticks_ms() - t0 > 10) {
+			serial_puts(SERIAL_COM1, "ehci: IAA timeout\n");
+			break;
+		}
+		usb_poll_relax(t0);
+	}
+	wr32(op_reg(c, EHCI_OP_USBSTS), STS_IAA);
+}
+
 static void bulk_arm(struct ehci_bulk *b)
 {
+	unsigned int now;
+
 	if (!b->sched && b->owner) {
 		ehci_sched_get(b->owner);
 		b->sched = 1;
 	}
+	now = get_ticks_ms();
+	if (b->owner && b->owner->last_async_ms &&
+	    now - b->owner->last_async_ms >= 100)
+		ehci_iaa_wait(b->owner);
+	if (b->owner)
+		b->owner->last_async_ms = now;
 	b->qh->token = (b->qh->token & QTD_PING) |
 		       (b->toggle ? QTD_TOGGLE : 0);
 	qh_arm(b->qh, b->qtd);
 	b->armed = 1;
+	b->arm_ms = now;
 }
 
 static int ehci_bulk_out(unsigned int ctrl, unsigned int addr,
@@ -516,7 +560,7 @@ static int ehci_bulk_out(unsigned int ctrl, unsigned int addr,
 	bulk_arm(b);
 
 	if (qtd_wait(last, qtd, 2000) < 0) {
-		bulk_stop(b);
+		bulk_reset(b);
 		return -1;
 	}
 
@@ -525,8 +569,12 @@ static int ehci_bulk_out(unsigned int ctrl, unsigned int addr,
 		ztoken = last->token;
 	bulk_stop(b);
 	if ((token & QTD_ACTIVE) || qtd_error(token) ||
-	    (zlp && ((ztoken & QTD_ACTIVE) || qtd_error(ztoken))))
+	    (zlp && ((ztoken & QTD_ACTIVE) || qtd_error(ztoken)))) {
+		/* Clear the data toggle too: a failed transfer may have
+		 * advanced it or left the endpoint out of sync. */
+		bulk_reset(b);
 		return -1;
+	}
 
 	{
 		unsigned int packets = (len + mps - 1) / mps;
@@ -575,7 +623,10 @@ static int ehci_bulk_in(unsigned int ctrl, unsigned int addr,
 
 	b->armed = 0;
 	if (qtd_error(token)) {
-		bulk_stop(b);
+		/* A qTD error also leaves the endpoint's data toggle
+		 * unreliable; drop the state so the next transfer starts at
+		 * DATA0 with a fresh QH/qTD. */
+		bulk_reset(b);
 		return -1;
 	}
 
@@ -598,6 +649,63 @@ static int ehci_bulk_in(unsigned int ctrl, unsigned int addr,
 	return (int)actual;
 }
 
+/* Cancel a bulk transfer and clear the endpoint state, including the data
+ * toggle.  A timed-out bulk-IN qTD otherwise stays armed forever and every
+ * later transfer sees it as busy; a BOT reset also leaves the device at
+ * DATA0 while the host would keep its old toggle. */
+static void ehci_bulk_reset(unsigned int ctrl, unsigned int addr,
+			    unsigned int ep, int dir_in)
+{
+	struct ehci_ctrl *c;
+	struct ehci_bulk *b;
+
+	if (ctrl >= n_ctrls)
+		return;
+	c = &ctrls[ctrl];
+	b = dir_in ? &c->bin : &c->bout;
+	if (b->addr == addr && b->ep == ep) {
+		unsigned int token = b->qtd->token;
+
+		if ((token & QTD_ACTIVE) &&
+		    get_ticks_ms() - b->arm_ms > 100) {
+			unsigned int port = b->addr < 128 ?
+				c->addr_port[b->addr] : 0xFF;
+			unsigned int ps = 0;
+
+			if (port < c->n_ports)
+				ps = rd32(port_reg(c, port));
+			serial_puts(SERIAL_COM1, "ehci: stuck bulk ");
+			serial_puts(SERIAL_COM1, dir_in ? "in" : "out");
+			serial_puts(SERIAL_COM1, " sts ");
+			serial_puthex(SERIAL_COM1,
+				      rd32(op_reg(c, EHCI_OP_USBSTS)));
+			serial_puts(SERIAL_COM1, " cmd ");
+			serial_puthex(SERIAL_COM1,
+				      rd32(op_reg(c, EHCI_OP_USBCMD)));
+			serial_puts(SERIAL_COM1, " qtd ");
+			serial_puthex(SERIAL_COM1, token);
+			serial_puts(SERIAL_COM1, " qh ");
+			serial_puthex(SERIAL_COM1, b->qh->token);
+			serial_puts(SERIAL_COM1, " cur ");
+			serial_puthex(SERIAL_COM1, b->qh->current);
+			serial_puts(SERIAL_COM1, " port ");
+			serial_putdec(SERIAL_COM1, port + 1);
+			serial_puts(SERIAL_COM1, " ps ");
+			serial_puthex(SERIAL_COM1, ps);
+			serial_puts(SERIAL_COM1, " addr ");
+			serial_putdec(SERIAL_COM1, b->addr);
+			serial_puts(SERIAL_COM1, " ep ");
+			serial_putdec(SERIAL_COM1, b->ep);
+			serial_puts(SERIAL_COM1, " tgl ");
+			serial_putdec(SERIAL_COM1, b->toggle);
+			serial_putc(SERIAL_COM1, '\n');
+		}
+		if (c->sched_on && (token & QTD_ACTIVE))
+			ehci_iaa_wait(c);
+		bulk_reset(b);
+	}
+}
+
 /* ---- interrupt-IN endpoints ------------------------------------------- */
 static void int_arm(struct ehci_int *in)
 {
@@ -728,6 +836,14 @@ static int ehci_control(struct ehci_ctrl *c, unsigned int addr,
 	ehci_sched_get(c);
 	c->ctl_busy = 1;
 
+	{
+		unsigned int now = get_ticks_ms();
+
+		if (c->last_async_ms && now - c->last_async_ms >= 100)
+			ehci_iaa_wait(c);
+		c->last_async_ms = now;
+	}
+
 	for (i = 0; i < 8; i++)
 		c->setup[i] = setup[i];
 
@@ -1428,5 +1544,6 @@ const struct usb_hcd_ops usb_ehci_ops = {
 	ehci_int_in_stop,
 	ehci_bulk_out,
 	ehci_bulk_in,
+	ehci_bulk_reset,
 	ehci_print_ports,
 };

+ 8 - 3
kernel/kernel.c

@@ -410,16 +410,21 @@ static volatile int boot_dhcp_done;
 static void boot_storage_main(void)
 {
 	bootcon_scan_begin();
-	vfs_mount_all();
+	vfs_mount_all(1);
 	sys_mount_load_config();
 	boot_trace("storage");
+	/* USB storage can NAK its first read for seconds while a card reader or
+	 * stick initialises.  Close the live scan first, then mount it behind
+	 * the usable desktop; the boot window no longer waits for it. */
+	bootcon_scan_end();
+	vfs_mount_usb();
+	sys_mount_load_config();
 	/* As before, WiFi only starts after the boot DHCP attempt on the
 	 * wired NIC, so two DHCP clients never overlap. */
 	while (!boot_dhcp_done)
 		process_sleep_ms(20);
 	boot_wifi_autoconnect();
 	boot_trace("wifi auto");
-	bootcon_scan_end();
 }
 
 void kernel_main(void);
@@ -662,7 +667,7 @@ void kernel_main(void)
 	boot_trace("storage begin");
 	storage_inline = 0;
 	if (process_create("bootscan", boot_storage_main) <= 0) {
-		vfs_mount_all();
+		vfs_mount_all(0);
 		boot_trace("storage");
 		storage_inline = 1;
 	}

+ 1 - 0
kernel/ohci.c

@@ -880,4 +880,5 @@ const struct usb_hcd_ops usb_ohci_ops = {
 	0,
 	0,
 	0,
+	0,
 };

+ 1 - 1
kernel/sys_fs.c

@@ -97,7 +97,7 @@ void sys_fs_scan(void)
 	fs_format_wait();
 	fs_scan_wait();
 	__asm__ volatile ("sti");
-	vfs_mount_all();
+	vfs_mount_all(0);
 	__asm__ volatile ("cli");
 }
 

+ 1 - 0
kernel/uhci.c

@@ -551,4 +551,5 @@ const struct usb_hcd_ops usb_uhci_ops = {
 	0,
 	0,
 	0,
+	0,
 };

+ 10 - 0
kernel/usb.c

@@ -881,6 +881,16 @@ int usb_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 					    mps, buf, len);
 }
 
+void usb_bulk_reset(unsigned int ctrl, unsigned int addr, unsigned int ep,
+		    int dir_in)
+{
+	if (ctrl >= n_usb_ctrls || !usb_ctrls[ctrl].ops->bulk_reset ||
+	    usb_scan_foreign())
+		return;
+	usb_ctrls[ctrl].ops->bulk_reset(usb_ctrls[ctrl].local, addr, ep,
+					dir_in);
+}
+
 int usb_bulk_supported(unsigned int ctrl)
 {
 	if (ctrl >= n_usb_ctrls)

+ 4 - 0
kernel/usb.h

@@ -76,6 +76,10 @@ int usb_bulk_out(unsigned int ctrl, unsigned int addr, unsigned int ep,
 		 unsigned int len);
 int usb_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 		unsigned int mps, unsigned char *buf, unsigned int len);
+/* Cancel a bulk transfer and reset the endpoint's host-side state (toggle,
+ * armed qTD/ring) after a timeout or a BOT reset. */
+void usb_bulk_reset(unsigned int ctrl, unsigned int addr, unsigned int ep,
+		    int dir_in);
 
 /* 1 when the controller behind `ctrl` implements both bulk directions.
  * UHCI/OHCI do not, so device drivers that need bulk must check this. */

+ 6 - 0
kernel/usb_hcd.h

@@ -90,6 +90,12 @@ struct usb_hcd_ops {
 		       unsigned int ep, unsigned int mps,
 		       unsigned char *buf, unsigned int len);
 
+	/* Abort a bulk transfer and reset the host-side endpoint state
+	 * (data toggle, armed qTD/ring), so the next bulk_in/out starts
+	 * clean after a timeout or a BOT reset.  May be NULL. */
+	void (*bulk_reset)(unsigned int ctrl, unsigned int addr,
+			   unsigned int ep, int dir_in);
+
 	/* Optional: print raw root-port status during `lsusb` (print mode
 	 * only).  Used by EHCI to show PORTSC while debugging routing. */
 	void (*print_ports)(unsigned int ctrl);

+ 105 - 8
kernel/usbmsc.c

@@ -23,6 +23,13 @@
 #define MSC_CHUNK_SECTORS	62u
 #define MSC_BULK_CHUNK		2048u	/* EHCI's fixed bulk-IN buffer */
 #define MSC_TIMEOUT_MS		3000u
+/* The first media access after enumeration can take seconds while the card
+ * or stick finishes its internal initialisation.  It is better to wait on
+ * the outstanding READ(10) than to reset the pipe and restart that work. */
+#define MSC_FIRST_READ_MS	15000u
+/* Best-effort boot probe: one bounded attempt, then leave the device for a
+ * later `storage` rescan. */
+#define MSC_PROBE_MS		5000u
 #define MSC_CBW_SIG		0x43425355u	/* "USBC" LE */
 #define MSC_CSW_SIG		0x53425355u	/* "USBS" LE */
 
@@ -33,6 +40,9 @@ struct usb_msc {
 	unsigned int ep_in, ep_in_mps;	/* endpoint numbers (1..15) */
 	unsigned int ep_out, ep_out_mps;
 	unsigned int iface;
+	unsigned int config;		/* configuration value, for recovery */
+	unsigned int timeout_ms;	/* bulk-IN deadline */
+	unsigned int first_read;	/* media not read since the probe */
 	unsigned int sectors;
 	unsigned int tag;
 	unsigned int last_status, last_residue;
@@ -43,6 +53,21 @@ struct usb_msc {
 static struct usb_msc msc[USB_MSC_MAX];
 static char msc_names[USB_MSC_MAX][6];
 static unsigned int msc_generation;
+static int msc_probe_only;
+
+void usbmsc_set_probe_only(int on)
+{
+	msc_probe_only = on;
+}
+
+void usbmsc_begin_full_scan(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < USB_MSC_MAX; i++)
+		if (msc[i].present)
+			msc[i].first_read = 1;
+}
 
 static unsigned int rd32le(const unsigned char *p)
 {
@@ -108,7 +133,11 @@ static int msc_bulk_in(struct usb_msc *m, unsigned char *buf, unsigned int len)
 			 * byte count is reached. */
 			got += (unsigned int)n;
 			t0 = get_ticks_ms();
-		} else if (get_ticks_ms() - t0 > MSC_TIMEOUT_MS) {
+		} else if (get_ticks_ms() - t0 > m->timeout_ms) {
+			/* A timed-out bulk-IN qTD stays armed in the HCD
+			 * schedule; cancel it or every later transfer sees
+			 * the endpoint as permanently busy. */
+			usb_bulk_reset(m->ctrl, m->addr, m->ep_in, 1);
 			return -1;
 		} else {
 			usb_poll_relax(t0);
@@ -120,8 +149,12 @@ static int msc_bulk_in(struct usb_msc *m, unsigned char *buf, unsigned int len)
 static int msc_bulk_out(struct usb_msc *m, const unsigned char *buf,
 			unsigned int len)
 {
-	return usb_bulk_out(m->ctrl, m->addr, m->ep_out, m->ep_out_mps,
-			    buf, len);
+	if (usb_bulk_out(m->ctrl, m->addr, m->ep_out, m->ep_out_mps,
+			 buf, len) != 0) {
+		usb_bulk_reset(m->ctrl, m->addr, m->ep_out, 0);
+		return -1;
+	}
+	return 0;
 }
 
 /* BOT reset + clear both bulk endpoint halts. */
@@ -133,9 +166,28 @@ static void msc_reset(struct usb_msc *m)
 			0x02, 0x01, 0, (unsigned short)(0x80u | m->ep_in));
 	usb_control_out(m->ctrl, m->addr, m->mps, m->low,
 			0x02, 0x01, 0, (unsigned short)m->ep_out);
+	/* CLEAR_FEATURE resets the device's endpoint toggle to DATA0; the
+	 * host side must do the same or the next CBW/data stage is sent with
+	 * the wrong toggle (real EHCI hardware rejects it, QEMU does not). */
+	usb_bulk_reset(m->ctrl, m->addr, m->ep_in, 1);
+	usb_bulk_reset(m->ctrl, m->addr, m->ep_out, 0);
 	m->tag++;
 }
 
+/* Last-resort recovery for a device whose BOT reset did not restore the
+ * pipes: re-apply the configuration.  That resets the device's endpoints
+ * (and their data toggles) to DATA0 without a port reset, so the address
+ * and the driver's endpoint numbers stay valid. */
+static void msc_reconfigure(struct usb_msc *m)
+{
+	if (!m->config)
+		return;
+	usb_control_out(m->ctrl, m->addr, m->mps, m->low,
+			0x00, 0x09, (unsigned short)m->config, 0);
+	usb_bulk_reset(m->ctrl, m->addr, m->ep_in, 1);
+	usb_bulk_reset(m->ctrl, m->addr, m->ep_out, 0);
+}
+
 static int bot_cmd(struct usb_msc *m, const unsigned char *cb,
 		   unsigned int cb_len, void *data, unsigned int data_len,
 		   int dir_in)
@@ -174,8 +226,13 @@ static int bot_cmd(struct usb_msc *m, const unsigned char *cb,
 	}
 	m->last_status = csw[12];
 	m->last_residue = rd32le(csw + 8);
-	if (csw[12] != 0)
-		return -1;
+	if (csw[12] != 0) {
+		/* A command that completed with CHECK CONDITION (or another
+		 * SCSI status) has valid sense data; a transport failure does
+		 * not.  -2 tells the recovery path to ask for the sense
+		 * before resetting the pipe. */
+		return -2;
+	}
 	if (m->last_residue != 0)
 		return -1;
 	return 0;
@@ -239,13 +296,47 @@ static int msc_read10(struct usb_msc *m, unsigned int lba, unsigned int count,
 static int msc_read10_retry(struct usb_msc *m, unsigned int lba,
 			    unsigned int count, void *buf)
 {
-	unsigned int i;
+	unsigned int i, t0 = get_ticks_ms();
+	int probe_only = msc_probe_only && m->first_read;
 
 	for (i = 0; i < 3; i++) {
-		if (msc_read10(m, lba, count, buf) == 0)
+		int r;
+
+		if (i == 0 && m->first_read)
+			m->timeout_ms = probe_only ? MSC_PROBE_MS :
+						    MSC_FIRST_READ_MS;
+		r = msc_read10(m, lba, count, buf);
+		if (i == 0 && m->first_read) {
+			unsigned int elapsed = get_ticks_ms() - t0;
+
+			m->first_read = 0;
+			m->timeout_ms = MSC_TIMEOUT_MS;
+			if (r == 0 && elapsed > 1000) {
+				serial_puts(SERIAL_COM1,
+					    "usbmsc: first read ");
+				serial_putdec(SERIAL_COM1, elapsed);
+				serial_puts(SERIAL_COM1, " ms\n");
+			}
+		}
+		if (r == 0)
 			return 0;
-		msc_sense(m);
+		if (probe_only) {
+			/* Boot background scan: do not spend the reset and
+			 * retry chain on a device that did not answer its
+			 * first read.  `storage` will try the full path. */
+			return -1;
+		}
+		/* Only a completed command with a non-zero CSW status has
+		 * sense data.  After a timeout the endpoint is in an
+		 * unknown state, and a REQUEST SENSE would just add another
+		 * multi-second timeout before the reset. */
+		if (r == -2)
+			msc_sense(m);
 		msc_reset(m);
+		/* If the BOT reset alone did not restore the pipes, reset the
+		 * device configuration once before the next retry. */
+		if (i == 0)
+			msc_reconfigure(m);
 		msc_delay(10);
 	}
 	return -1;
@@ -333,6 +424,7 @@ static int msc_config(struct usb_msc *m)
 		return -1;
 
 	m->iface = iface;
+	m->config = config;
 	m->ep_in = ep_in;
 	m->ep_in_mps = ep_in_mps ? ep_in_mps : 64;
 	m->ep_out = ep_out;
@@ -402,6 +494,9 @@ static int device_probe(unsigned int ctrl, unsigned int addr,
 	m->port = port;
 	m->tag = 0;
 	m->iface = 0;
+	m->config = 0;
+	m->timeout_ms = MSC_TIMEOUT_MS;
+	m->first_read = 0;
 
 	if (msc_config(m) != 0)
 		return 0;
@@ -434,6 +529,8 @@ static int device_probe(unsigned int ctrl, unsigned int addr,
 
 	msc_set_model(m, inquiry);
 	m->sectors = sectors;
+	m->timeout_ms = MSC_TIMEOUT_MS;
+	m->first_read = 1;
 	m->present = 1;
 
 	serial_puts(SERIAL_COM1, "usbmsc: ");

+ 10 - 0
kernel/usbmsc.h

@@ -15,6 +15,16 @@ void usbmsc_register(void);
  * the end of blk_scan(); the USB bus scan itself runs earlier at boot. */
 void usbmsc_blk_scan(void);
 
+/* Best-effort boot mounting: the first media read gets one bounded attempt
+ * instead of the normal retry chain, so a stuck device cannot hold
+ * vfs_scan_busy behind the boot scan.  A later `storage` rescan uses the
+ * full recovery path again. */
+void usbmsc_set_probe_only(int on);
+
+/* A full storage rescan gives every present device its long first-media-read
+ * deadline again (the boot background probe consumes it once). */
+void usbmsc_begin_full_scan(void);
+
 /* Block I/O for BLK_USB devices (unit = usbmsc slot index). */
 int usbmsc_read(unsigned int unit, unsigned int lba, void *buf,
 		unsigned int count);

+ 105 - 11
kernel/vfs.c

@@ -14,6 +14,7 @@
 #include "share.h"
 #include "syscall.h"
 #include "timer.h"
+#include "usbmsc.h"
 
 vfs_mount_t vfs_mounts[VFS_MAX_MOUNTS];
 unsigned int vfs_mount_count;
@@ -607,17 +608,46 @@ static int name_eq(const char *a, const char *b)
 	return a[i] == '\0' && b[i] == '\0';
 }
 
+static unsigned int mbr_dword(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8) |
+	       ((unsigned int)p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+/* The NebOS MBR (boot/mbr.S) has a fixed layout: an active, FAT16-looking
+ * P1 at LBA 63 with 1024 sectors (boot sector + kernel) and P2 at LBA 1088
+ * (the rootfs partition, or the dummy entry that keeps the AT3IONT-I BIOS
+ * from classifying the stick as USB-ZIP).  Recognising that layout lets the
+ * boot stick skip the P1 content read, which is one USB round trip on every
+ * boot.  Anything that does not match exactly still goes through the
+ * content check below. */
+static int mbr_is_nebos_layout(const unsigned char *mbr)
+{
+	const unsigned char *p1 = mbr + 0x1BE;
+	const unsigned char *p2 = p1 + 16;
+
+	if (mbr[0] != 0xEB || mbr[1] != 0x42 || mbr[2] != 0x90)
+		return 0;
+	if (p1[0] != 0x80 || p1[4] != 0x06)
+		return 0;
+	if (mbr_dword(p1 + 8) != 63 || mbr_dword(p1 + 12) != 1024)
+		return 0;
+	return mbr_dword(p2 + 8) == 1088;
+}
+
 /* The P1 boot sector keeps only the NebOS header fields; a real FAT volume
  * never carries these values.  Older installed media still has the original
  * FAT-looking BPB (before boot.S was changed), so skip it explicitly instead
- * of mounting the raw kernel partition as a fake filesystem. */
+ * of mounting the raw kernel partition as a fake filesystem.
+ * Returns 1 = NebOS boot partition, 0 = not, -1 = the sector could not be
+ * read (skip it either way; a failed probe must not turn into a mount). */
 static int is_nebos_boot_partition(blk_dev_t *d, unsigned int start_lba)
 {
 	unsigned char s[512];
 	unsigned int i;
 
 	if (blk_read(d, start_lba, s, 1) != 0)
-		return 0;
+		return -1;
 	if (s[510] != 0x55 || s[511] != 0xAA)
 		return 0;
 	if (s[3] != 'N' || s[4] != 'E' || s[5] != 'B' || s[6] != 'O' ||
@@ -627,7 +657,7 @@ static int is_nebos_boot_partition(blk_dev_t *d, unsigned int start_lba)
 		return 0;
 	i = s[0x42] | (s[0x43] << 8) | (s[0x44] << 16) |
 	    ((unsigned int)s[0x45] << 24);
-	return i == ROOTFS_LBA;
+	return i == ROOTFS_LBA ? 1 : 0;
 }
 
 /* ---- mount policies ---- */
@@ -823,7 +853,8 @@ static void part_name(char *out, const char *base, unsigned int idx)
 static void mount_device(blk_dev_t *d, unsigned char *buf)
 {
 	mbr_part_t parts[4];
-	int n, j;
+	fat_info_t fi;
+	int n, j, neb_mbr;
 	int any_fat = 0;
 
 	if (!d->present)
@@ -833,24 +864,35 @@ static void mount_device(blk_dev_t *d, unsigned char *buf)
 		return;
 	}
 
-	/* IDE/SATA: MBR -> FAT partitions, else superfloppy. */
+	/* IDE/SATA/USB: MBR -> FAT partitions, else superfloppy. */
 	if (blk_read(d, 0, buf, 1) != 0)
 		return;
 	n = mbr_parse(buf, parts);
+	neb_mbr = mbr_is_nebos_layout(buf);
 	for (j = 0; j < n; j++) {
 		char pname[16];
+		int neb;
+
 		if (!parts[j].is_fat || parts[j].start_lba == 0 ||
 		    parts[j].sectors == 0)
 			continue;
-		/* The active NebOS partition holds the raw boot sector and
-		 * kernel, not a filesystem (old images still look like FAT). */
-		if (is_nebos_boot_partition(d, parts[j].start_lba))
+		/* The NebOS boot stick's P1 is the raw boot sector + kernel,
+		 * not a filesystem; the layout check above avoids a USB read
+		 * of it on every boot, the content check is the fallback. */
+		if (neb_mbr && parts[j].index == 0)
+			continue;
+		neb = is_nebos_boot_partition(d, parts[j].start_lba);
+		if (neb != 0)		/* NebOS or unreadable: not FAT */
 			continue;
 		any_fat = 1;
 		part_name(pname, d->name, parts[j].index);
 		mount_one(d, parts[j].start_lba, pname);
 	}
-	if (!any_fat)
+	/* A valid MBR whose partitions are all non-FAT (the NebOS boot stick)
+	 * is not a superfloppy; only probe one when the sector has no MBR
+	 * entries, or still looks like a FAT boot sector with stray partition
+	 * bytes (a formatted superfloppy). */
+	if (!any_fat && (n == 0 || fat_detect(buf, &fi) == 0))
 		mount_one(d, 0, d->name);
 }
 
@@ -876,7 +918,7 @@ static void unmount_device(const char *dev)
 	}
 }
 
-void vfs_mount_all(void)
+void vfs_mount_all(int skip_usb)
 {
 	static unsigned char buf[512];
 	unsigned int i;
@@ -896,9 +938,23 @@ void vfs_mount_all(void)
 
 	blk_scan();
 
+	if (!skip_usb) {
+		/* A user-initiated `storage` rescan gets the full USB recovery
+		 * path, including the long first-read deadline. */
+		usbmsc_set_probe_only(0);
+		usbmsc_begin_full_scan();
+	}
+
 	for (i = 0; i < blk_dev_count; i++) {
-		unsigned int t0 = get_ticks_ms();
+		unsigned int t0;
 
+		if (skip_usb && blk_devs[i].kind == BLK_USB) {
+			serial_puts(SERIAL_COM1, "vfs: ");
+			serial_puts(SERIAL_COM1, blk_devs[i].name);
+			serial_puts(SERIAL_COM1, " deferred\n");
+			continue;
+		}
+		t0 = get_ticks_ms();
 		mount_device(&blk_devs[i], buf);
 		serial_puts(SERIAL_COM1, "vfs: ");
 		serial_puts(SERIAL_COM1, blk_devs[i].name);
@@ -924,6 +980,44 @@ static int device_is_mounted(const char *dev)
 	return 0;
 }
 
+/* Mount the USB disks the boot scan deferred.  A card reader or a stick
+ * can NAK its first media read for several seconds while it initialises, so
+ * this runs after the bootscan window has closed: the desktop, /ramfs,
+ * /share and the network are already usable while it waits. */
+void vfs_mount_usb(void)
+{
+	static unsigned char buf[512];
+	unsigned int i;
+	int any = 0;
+
+	vfs_scan_owner_pid = current_proc() ? current_proc()->pid : 0;
+	vfs_scan_busy = 1;
+	usbmsc_set_probe_only(1);
+
+	for (i = 0; i < blk_dev_count; i++) {
+		blk_dev_t *d = &blk_devs[i];
+		unsigned int t0;
+
+		if (d->kind != BLK_USB || !d->present ||
+		    device_is_mounted(d->name))
+			continue;
+		t0 = get_ticks_ms();
+		mount_device(d, buf);
+		serial_puts(SERIAL_COM1, "vfs: ");
+		serial_puts(SERIAL_COM1, d->name);
+		serial_puts(SERIAL_COM1, " mount ");
+		serial_putdec(SERIAL_COM1, get_ticks_ms() - t0);
+		serial_puts(SERIAL_COM1, " ms\n");
+		any = 1;
+	}
+
+	usbmsc_set_probe_only(0);
+	if (any)
+		serial_puts(SERIAL_COM1, "vfs: usb storage scanned\n");
+
+	vfs_scan_busy = 0;
+}
+
 static void remount(blk_dev_t *d)
 {
 	unsigned char buf[512];

+ 8 - 2
kernel/vfs.h

@@ -78,8 +78,14 @@ extern unsigned int vfs_mount_count;
 
 /* Scan devices and mount all detected FAT filesystems.  The ramfs/share
  * mounts are kept available throughout the scan; file syscalls that run on
- * another CPU wait until it completes (see vfs_scan_busy). */
-void vfs_mount_all(void);
+ * another CPU wait until it completes (see vfs_scan_busy).  skip_usb defers
+ * BLK_USB devices to vfs_mount_usb(), so a slow card reader cannot hold up
+ * the boot scan or the other volumes. */
+void vfs_mount_all(int skip_usb);
+/* Mount the USB block devices registered by the boot scan, appending to the
+ * existing table.  Runs after the boot scan window has closed; safe to call
+ * more than once (already-mounted devices are skipped). */
+void vfs_mount_usb(void);
 /* Re-mount only one block device after it was formatted. */
 void vfs_remount_device(blk_dev_t *d);
 

+ 34 - 0
kernel/xhci.c

@@ -105,6 +105,7 @@ static unsigned int portsc_neutral(unsigned int ps)
 #define TRB_ADDR_DEV		11
 #define TRB_CONFIG_EP		12
 #define TRB_EVAL_CTX		13
+#define TRB_STOP_EP		15
 #define TRB_TRANSFER		32
 #define TRB_COMPLETION		33
 
@@ -1247,6 +1248,38 @@ static int xhci_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 	return 0;
 }
 
+/* Drop a bulk transfer after a timeout or a BOT reset.  Stop the endpoint
+ * first so the xHC no longer references the old ring page, then clear the
+ * software state; the next bulk call configures a fresh ring. */
+static void xhci_bulk_reset(unsigned int ctrl, unsigned int addr,
+			    unsigned int ep, int dir_in)
+{
+	struct xhci_slot *s = slot_by_addr(addr);
+	struct xhci_bulk *b = dir_in ? &bulk_in : &bulk_out;
+	unsigned int flags, slot, ep_id;
+
+	(void)ctrl;
+	if (!found || !s)
+		return;
+
+	spin_lock_irqsave(&xhci_lock, &flags);
+	if (!b->active || b->slot != s->slot_id || b->ep != ep) {
+		spin_unlock_irqrestore(&xhci_lock, flags);
+		return;
+	}
+	slot = b->slot;
+	ep_id = b->ep_id;
+	spin_unlock_irqrestore(&xhci_lock, flags);
+
+	xhci_cmd(0, 0, TRB_TYPE(TRB_STOP_EP) | (slot << 24) | (ep_id << 16),
+		 0);
+
+	spin_lock_irqsave(&xhci_lock, &flags);
+	if (b->active && b->slot == slot && b->ep == ep)
+		bulk_reset(b);
+	spin_unlock_irqrestore(&xhci_lock, flags);
+}
+
 static int xhci_bulk_out(unsigned int ctrl, unsigned int addr, unsigned int ep,
 		    unsigned int mps, const unsigned char *buf,
 		    unsigned int len)
@@ -1826,5 +1859,6 @@ const struct usb_hcd_ops usb_xhci_ops = {
 	stop_int,
 	xhci_bulk_out,
 	xhci_bulk_in,
+	xhci_bulk_reset,
 	0,
 };