Repository navigation
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
Open
USB mass storage: Bulk-Only Reset Recovery after an invalid status, and do not fail a busy unit#1129JC-000 wants to merge 17 commits into
JC-000 wants to merge 17 commits into
Conversation
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>
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_transportkeeps waiting for the missing bytes of the 13-byte CSW: each attempt runs the 3 s timeout andbulk_inretriesfive 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, whichpoll()stops testing. The Bulk-Only Transport spec (5.3.3, 6.5) requires Reset Recovery after an invalidCSW: the class Mass Storage Reset, then CLEAR_FEATURE(ENDPOINT_HALT) on both bulk endpoints.
mass_storage_resetwas commented out.A second problem sits next to it. While a stalled command holds the driver mutex,
poll()'stest_unit_readywaits 25 s (5000 ticks),gets -9 ("driver unavailable"), and marks the unit failed.
poll()then tears the filesystem down under the command that is stillrunning. A retry after Reset Recovery could lengthen that hold, so the retry is capped (below) and the
-9change goes with it.Change
UsbBase::bulk_ingets astop_on_shortargument.status_transportuses it, so a CSW that arrives as a short packet isinvalid 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) andreset_recovery()adds the two CLEAR_FEATURErequests and resets both data toggles. The endpoint addresses carry the direction bit;
t_pipe.DevEPkeeps 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) failsfast, 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_outhas a newretriesargument,control_exchangeandunstall_pipea timeout argument; defaults unchanged for every other caller). The decision isbot_retry_after_status_fault()inusb_bot_policy.h, with a host test (make bot-policyinsoftware/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.
UsbScsi::status()reportsSTA_PROTECT, so FatFs refuses to open a file for writing (FR_WRITE_PROTECTED), andUsbScsi::writereturnsRES_WRPRTbefore it touchesthe device. Reads and TEST UNIT READY are unchanged. A replug creates a new unit, which is writable.
endpoint N OUT. They now use the same endpoint-address helper as the Reset Recovery. The bulk-OUT sites were already right.
test_unit_readytreats -9 as "busy, skip this poll" and no longer setse_device_failed.usb_ms_cbishares 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 isWRITE PROTECTEDin the UCIDOS status text and
26,WRITE PROTECT ONon the IEC error channel (set_error_fresmapsFR_WRITE_PROTECTEDto it,iec_drive.cc);a write on a file that was already open gets
RES_WRPRTfrom 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).
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.ccexec_command,usb_base.ccbulk_in,bulk_outandcontrol_exchange), not measured. The host test covers the retry decision and the added-timearithmetic, 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_DATAstatus, 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).
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 invalidatedunavailable (EX),ERROR Testing Unit.. -9,Invalidate event on USB1.. Checking 1 fileswhile the write is in flight, thenHmm.. written = -1,Closing invalidated file; still failed when the log ends 17 s later-9change-9changeunavailable (EX)only; write completes in 35 s, data exact; no failure, no invalidationThe 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
fails after the same wait as before: no reset and no retry once a NAK timeout has been spent.
0/13: the whole CSW is NAKed.stop_on_shortdoes not help that case (the 18 s retries still run before recovery) andit is not tested here.
readandwritestill mark the unit failed on -9 (usb_scsi.ccaround :901 and :935).generic stick, with an earlier version of this change.
cannot be written: its writes get a disk error (how each drive emulation reports that is not verified).
unit can return to READY: a
test_unit_readythat poll queued on the driver mutex before the failure runs after it and sets READY overthe failed state (usb_scsi.cc
test_unit_ready,set_state(e_device_ready)), and readers already queued also run after the failure. This iswhat 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.
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