Skip to content

USB mass storage: Bulk-Only Reset Recovery after an invalid status, and do not fail a busy unit - #1129

Open
JC-000 wants to merge 17 commits into
GideonZ:masterfrom
JC-000:fix/1100-usb-bot-reset-recovery
Open

JC-000 wants to merge 17 commits into
GideonZ:masterfrom
JC-000:fix/1100-usb-bot-reset-recovery

Conversation

@JC-000

@JC-000 JC-000 commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Fixes #1100

It also removes the stalled-write trigger of the teardown race described in #1128; the race itself needs a separate fix.

Problem

A USB stick that answers the status phase (CSW) of a command with a short packet and then NAKs leaves the unit failed for good.
status_transport keeps waiting for the missing bytes of the 13-byte CSW: each attempt runs the 3 s timeout and bulk_in retries
five times, so the command blocks for about 18 s. Then "Invalid status (len = -1 ...)" is printed and the unit is set to
e_device_failed, which poll() stops testing. The Bulk-Only Transport spec (5.3.3, 6.5) requires Reset Recovery after an invalid
CSW: the class Mass Storage Reset, then CLEAR_FEATURE(ENDPOINT_HALT) on both bulk endpoints. mass_storage_reset was commented out.

A second problem sits next to it. While a stalled command holds the driver mutex, poll()'s test_unit_ready waits 25 s (5000 ticks),
gets -9 ("driver unavailable"), and marks the unit failed. poll() then tears the filesystem down under the command that is still
running. A retry after Reset Recovery could lengthen that hold, so the retry is capped (below) and the -9 change goes with it.

Change

  • UsbBase::bulk_in gets a stop_on_short argument. status_transport uses it, so a CSW that arrives as a short packet is
    invalid at once instead of being waited out. A NAK timeout still goes through the normal retries.
  • mass_storage_reset() is back (no-data class request 0xFF to the interface) and reset_recovery() adds the two CLEAR_FEATURE
    requests and resets both data toggles. The endpoint addresses carry the direction bit; t_pipe.DevEP keeps only the endpoint number.
    The log line only says that recovery was issued: the control transfers' return value does not prove the device answered.
  • exec_command: if the status phase of a command that does not send data to the device (READ, TEST UNIT READY and the like) fails
    fast, run Reset Recovery and issue the command once more. The unit is only marked failed
    when the second attempt fails too. A fast failure means the whole attempt (command, data and status phase) took under 1 s, as for the
    reporter's 1-byte status. An attempt that already spent a NAK timeout is not reset and not retried: the unit fails after the same wait
    as before. The second attempt uses a shorter CBW timeout and no NAK-timeout retries (bulk_out has a new retries argument, control_exchange and
    unstall_pipe a timeout argument; defaults unchanged for every other caller). The decision is
    bot_retry_after_status_fault() in usb_bot_policy.h, with a host test (make bot-policy in software/io/usb/tests). INQUIRY is never retried.
    A command that sends data to the device (WRITE) is never reset or retried: it fails exactly as on master, because the lost status of a
    write cannot be told from a completed one.
  • After any Reset Recovery the unit is read-only until it is re-enumerated (see "Why read-only after a recovery"). UsbScsi::status() reports
    STA_PROTECT, so FatFs refuses to open a file for writing (FR_WRITE_PROTECTED), and UsbScsi::write returns RES_WRPRT before it touches
    the device. Reads and TEST UNIT READY are unchanged. A replug creates a new unit, which is writable.
  • The two stall paths that clear the halt on the bulk-IN endpoint passed the endpoint number without the IN direction bit, so the request went to
    endpoint N OUT. They now use the same endpoint-address helper as the Reset Recovery. The bulk-OUT sites were already right.
  • test_unit_ready treats -9 as "busy, skip this poll" and no longer sets e_device_failed. usb_ms_cbi shares this function.

Why read-only after a recovery

On the bench a SanDisk Ultra Fit hung on the first write after a Bulk-Only reset, in four runs and with several variants of this change
(different timeouts, a retry of the write, a write after a read recovery): no status for the write, then no answer to anything, and a replug
was needed. Reads after a recovery were fine (37 recoveries, every file SHA-exact), and another stick took 15 write recoveries without
trouble. A recovery that lets a write follow would risk a half-written file on such a stick. Reset Recovery is what the specification asks for,
so it stays for reads and status polls, and the unit becomes read-only afterwards. That can never tear a write, and it is strictly better
than master, which fails the whole unit at the first fault. To write again the user replugs the stick.

What a program sees when it tries to write a read-only unit: FatFs refuses the open with FR_WRITE_PROTECTED, which is WRITE PROTECTED in the UCI
DOS status text and 26,WRITE PROTECT ON on the IEC error channel (set_error_fres maps FR_WRITE_PROTECTED to it, iec_drive.cc);
a write on a file that was already open gets RES_WRPRT from the block layer, which FatFs reports as a disk error.

How long a command can hold the driver

Everything that waits for the drive (an emulated drive feeding a C64 LOAD, a UCI DOS read, a REU load) waits for this. The change does not
make that longer than before, with one exception: a read or a status poll whose status the old code also failed at once (a stalled
status, or a 13-byte status with a bad signature) now gets a Reset Recovery and one more attempt, and if the device is dead afterwards this
adds at most about 13 s before the unit fails (recovery 6 s, retry 7 s), still below the 15 to 36 s the old code could hold the driver.
The recovery's control transfers keep the default 0.5 s waits (the second attempt uses a 1 s CBW timeout and no NAK-timeout retries; its data and
status phases keep the normal 3 s, because a device that is still executing the command NAKs the status). A healthy device answers the recovery
in milliseconds. Writes and INQUIRY are never reset or retried.

Timeouts of the old code: CBW 2.5 s with 5 retries (6 attempts, 15 s, then -6 and no data or status phase); data and status 3 s with 5
retries (18 s each); INQUIRY 1 s with 3 retries (4 s each).

Command Worst case before this PR (code bound) After a slow first attempt (a NAK timeout spent) Fast fault, then a dead device (code bound)
READ(10) 36 s (data 18 + status 18); 15 s if the CBW fails 36 s, no reset, no retry a stalled CSW or bad signature failed at once (a short CSW cost 18 s); now up to 13 s more
TEST UNIT READY 18 s (status); 15 s if the CBW fails 18 s up to 10 s more
WRITE(10) 36 s; 15 s if the CBW fails 36 s unchanged: no reset, no retry
INQUIRY 8 s (data 4 + status 4); 15 s if the CBW fails 8 s unchanged: not retried

Measured: about 10 ms for the recovery and the retry on a healthy stick (the reporter's case, a 1-byte status followed by NAKs), 1.5 s
once for the old-style recovery against a dead stick. Everything else in the table is from the code (usb_scsi.cc exec_command,
usb_base.cc bulk_in, bulk_out and control_exchange), not measured. The host test covers the retry decision and the added-time
arithmetic, not the call site.

No new error codes: a failed USB read or write still reaches the C64 through the existing reporting paths. Two existing reporting bugs
on master (UCI READ_DATA status, IEC streaming read) are filed separately.

Evidence (Ultimate 64 Elite, work-in-progress builds; two sticks)

Rows B and the stall rows ran on earlier versions of this change that also reset and retried writes; the final code does not (see Limits).
Sticks: a SanDisk Ultra Fit (0781:5583) for the first rows and a generic "USB Flash Disk" (21C4:8381) for rows B, the stall rows
and the no-hook row. The hook builds are test-only and NOT part of this PR. They contain: (a) after the real 13-byte CSW has been read, report
it as 1 byte, at most once every 4 s (the stick itself stays healthy and then NAKs the follow-up read); (b) hold the driver
mutex for 30 s during one WRITE(10) (stall rows only); (c) re-enumerate the stick's hub port 45 s after the unit is marked failed
(every hook image; the GREEN image also does it once 88 s after boot); (d) forward the log to a syslog collector.
The stall rows also ran hook (a) (4 and 9 recoveries).

Run Code Load Result
RED #1100 master + hooks 4 MiB FTP reads 6 x Bulk IN error $2C00 0/12 (18 s), Invalid status (len = -1), USB READ ERROR, reads fail; six read errors over 103 s until the unit is invalidated
GREEN first commit of this PR + hooks 19 good reads of 4 MiB (one miss during the test re-enumerate) 37 injected faults, 37 recoveries (under 10 ms each, syslog resolution), every read SHA-exact at 3.1-3.2 s
B this PR + hooks 8 x 512 KiB writes with read-back 15 faults, 15 recoveries, all data exact, no errors
RED race master + hooks (b)(c)(d) 2 MiB write unavailable (EX), ERROR Testing Unit.. -9, Invalidate event on USB1.. Checking 1 files while the write is in flight, then Hmm.. written = -1, Closing invalidated file; still failed when the log ends 17 s later
stall without the -9 change this PR minus the last commit + hooks (a)(b)(c)(d) 2 MiB write the same sequence
stall with the -9 change this PR + hooks (a)(b)(c)(d) 2 MiB write unavailable (EX) only; write completes in 35 s, data exact; no failure, no invalidation
final final commit + hooks (a)(c)(d), the fault on READ(10) only 8 reads of a 5.5 MB file; one write attempt after the recoveries 9 faults, 9 recoveries, every read SHA-exact at 3.92-4.04 s (3.91 s on the bench's work-in-progress image without this change, same stick); the write is refused at once (the upload fails within 0.1 s) and the stick keeps answering: the three reads after it are exact
no hook this PR 5 x 4 MiB reads, 2 MiB write reads 3.02-3.04 s, SHA-exact (3.00-3.01 s on a work-in-progress firmware image without this change, same stick); write with read-back exact in 5.1 s

The rows above ran on the first two commits of this PR; the retry cap came later and changes only the slow and dead-device cases, not the
fast fault the rows inject. The final row is the run on the final commit; the no-hook row ran on the second commit.

The log line of the recovery was reworded after the GREEN and B runs (the earlier text printed the control transfers' return values);
behaviour is unchanged.

Two whole-box deaths happened during 1.3 MB FTP uploads on hook images while the SanDisk stick had stopped answering or was being
stressed: once on an earlier version of this change that also cut the status wait on a NAK timeout, since fixed (the log shows the stall/invalidate sequence of the RED race row, then stops 21 s later), once on
the GREEN-row code with no log captured. Cause not established; the teardown of a failed unit under a running transfer (see Limits) is a possible one. The SanDisk was not used again afterwards.

Limits

  • A stick that NAKs the CBW (not the CSW) gets no recovery: that path returns -6 before the status phase. A stick that never answers
    fails after the same wait as before: no reset and no retry once a NAK timeout has been spent.
  • Some captures show 0/13: the whole CSW is NAKed. stop_on_short does not help that case (the 18 s retries still run before recovery) and
    it is not tested here.
  • A CSW with status 2 (Phase Error) still counts as success, and the CSW tag is not checked. Not changed.
  • read and write still mark the unit failed on -9 (usb_scsi.cc around :901 and :935).
  • A WRITE with an invalid status gets no recovery and no retry, so the unit fails as on master. Recovery of a faulted write was only tested on the
    generic stick, with an earlier version of this change.
  • A fault on the background status poll is enough to make the unit read-only, without any user I/O. A disk image already mounted from the stick then
    cannot be written: its writes get a disk error (how each drive emulation reports that is not verified).
  • After a recovery the unit stays read-only until the stick is replugged; there is no way to make it writable again from the menu.
  • Reset Recovery measured 1.5 s once against a dead stick.
  • A device that needs a physical reset to come back still has to be replugged; this PR does not re-enumerate the port. On master (and here, unchanged) a failed
    unit can return to READY: a test_unit_ready that poll queued on the driver mutex before the failure runs after it and sets READY over
    the failed state (usb_scsi.cc test_unit_ready, set_state(e_device_ready)), and readers already queued also run after the failure. This is
    what the six read errors over 103 s in the RED row look like; verified in the code, inferred from the log (the successful poll prints nothing).
    Not changed here.
  • The teardown of a failed unit while another task is inside FatFs is a separate, older problem (draft issue to follow). This PR only stops
    poll() from triggering it for a merely busy driver.

Written with Claude Sonnet 5.5 and Claude Opus 5.5 in Claude Code.

🤖 Generated with Claude Code

JC-000 and others added 13 commits November 21, 2026 09:32
A USB stick that answers the CSW with a short packet and then NAKs made
exec_command wait through all bulk-in retries (3 s each) and then the unit
was set to e_device_failed for good. The Bulk-Only Transport spec requires
Reset Recovery after an invalid CSW: the class Mass Storage Reset, then
CLEAR_FEATURE(ENDPOINT_HALT) on both bulk endpoints.

status_transport now stops at the first short packet (new stop_on_short
argument of UsbBase::bulk_in) and exec_command runs Reset Recovery and
issues the command once more. The unit is marked failed only if the
second attempt fails too.

Fixes GideonZ#1100

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
When another command holds the UsbScsiDriver mutex longer than the wait
(5000 ticks, 25 s: a stalled transfer, now also a Reset Recovery and one
retry), test_unit_ready got -9 from exec_command and set e_device_failed.
The poll then tore the filesystem down under the transfer that was still
running. A busy driver is not a failed unit: skip this poll.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Reset Recovery plus a second attempt doubled the time a hung command held
the driver, and the C64 side waits for that driver. The retry is now
limited to an attempt that failed fast (under 1 s in total, e.g. a 1-byte
CSW). An attempt that already spent a NAK timeout fails as before, with
no reset and no retry, so it takes the same time as without this change.
The second attempt gets no NAK-timeout retries, so a fast fault followed
by a dead device costs at most about 11 s, below the 15 to 36 s that the
original code could hold the driver.

The decision is a small inline function with a host test. bulk_out gets a
retries argument (default 5, unchanged for other callers).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
INQUIRY runs with 1 s timeouts (4 s worst case); a Reset Recovery plus a
second attempt could exceed that, so it keeps the old behaviour. The host
test covers it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Only the fast-fault path changes: the recovery control transfers wait
125 ms per step and the second attempt uses 250 ms for the CBW and the
status phase and 1 s for the data phase, so recovery plus retry add at
most about 3 s, even when the device is dead. A stalled or bad-signature
CSW failed at once before; this bounds what it can add. control_exchange
and unstall_pipe get a timeout argument (default unchanged).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The stall paths passed DevEP & 0xFF, which has no direction bit, so
CLEAR_FEATURE(ENDPOINT_HALT) went to endpoint N OUT instead of N IN. The
two bulk-IN sites now use the same endpoint-address helper as the Reset
Recovery (bit 7 set for IN). The bulk-OUT sites were already right.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
On hardware a 250 ms status timeout on the retried WRITE aborted a command
the SanDisk stick was still committing, and the stick then NAKed every
CBW and needed a replug. The retry keeps no NAK-timeout retries and a 1 s
CBW timeout, but its data and status phases use the normal 3 s again. The
added worst case after a fast fault on a dead device is about 8.5 s, below
the 15 to 36 s the old code could hold the driver.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
On hardware (a SanDisk Ultra Fit) the 125 ms control-transfer timeout
introduced for the recovery aborted the Mass Storage Reset mid-way and the
stick wedged twice. The recovery uses the default 0.5 s waits again. The
added worst case after a fast fault on a dead device is about 13 s (6 s
recovery, 7 s retry), still below the 15 to 36 s the old code could hold
the driver; a healthy device answers in milliseconds.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A WRITE whose status phase fails fails as it always did: no Reset
Recovery and no second attempt. On the bench a SanDisk Ultra Fit wedged
when a reset and a retry followed a faulted write (37 read recoveries on
it and 15 write recoveries on another stick were clean), and the lost
status of a write cannot be told from a completed one. Reads, TEST UNIT
READY and the other commands without outgoing data keep the recovery.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
On the bench a SanDisk Ultra Fit hung on the first write after a Reset
Recovery. The recovery now waits 500 ms (vTaskDelay, fault path only)
before the command is issued again. Added worst case after a fast fault on
a dead device: about 13.5 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
With writes locked after a recovery the pause is unproven and not needed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
On the bench a SanDisk Ultra Fit hung on the first write after a Bulk-Only
reset (reads were fine, another stick wrote fine). After any Reset
Recovery the unit now reports STA_PROTECT, so FatFs refuses to open a file
for writing (FR_WRITE_PROTECTED: "WRITE PROTECTED" for UCI, 26,WRITE PROTECT
ON for IEC), and UsbScsi::write returns RES_WRPRT before it touches the
device. Reads and TEST UNIT READY keep working. A replug creates a new
unit and makes it writable again. A recovery can no longer tear a write.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
UsbScsi::write checked the read-only state before it queued on the driver
mutex, so a write that waited while another command recovered still ran its
WRITE(10) right after the reset. The state now lives in the driver and is
checked in exec_command with the mutex held (-8, which write() maps to
RES_WRPRT), and status() and write() read it from there. The Reset Recovery
no longer walks the LUN table, and the constructor clears it (it was never
initialised, so a recovery during install could read stale pointers).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
JC-000 and others added 4 commits November 23, 2026 09:53
A device can end a READ data phase early and send the CSW in place of the
missing data. Add the decision logic (retry the READ once, use the CSW as
the status, or read the status as usual) and the stop-on-short rule that
ignores a discarded duplicate packet, with host tests.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A packet the controller discarded because the data toggle did not match
returns zero bytes with the toggle unchanged. stop_on_short took it as the
end of the transfer, so the status phase failed as an invalid CSW and
started a Reset Recovery. Keep polling instead, and print a line when a
discard happens.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Read the data phase with stop_on_short. When the short tail is a CSW with
our tag (bot_short_data_tail), print it and use it as the status instead of
reading a status that was already sent. Status 0 with no residue and bytes
missing retries the READ once without Reset Recovery; any other CSW takes
the usual error handling, and a repeat of the lie takes the fast-fault
path.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…e toggle parity

One nano command moves many packets and flips the data toggle once per
accepted packet, so toggle_before != toggle_after only holds for an odd
count. bot_in_stop_on_short now takes the max packet size and derives from
transferred / mps whether the last packet was accepted (a short packet or a
zero length packet) or discarded as a duplicate. The "IN toggle discard"
print uses the same decision.

The CSW tag in a short data tail is compared as raw bytes, so the host byte
order does not matter. inquiry() treats a reply shorter than 36 bytes as a
failure. A CSW with status 2 found in a data tail takes the fault path.

Host tests: k = 0..3 full packets followed by a short packet, a zero length
packet or a discarded duplicate, at max packet 512 and 64, and a check that
the data IN call site still passes stop_on_short and looks for a CSW tail.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

C64U: USB Mass Storage read failures with General UDisk (ID abcd:1234)

1 participant