Skip to content

# SD card driver: do not hold interrupts off while the card is busy - #1066

Merged
chrisgleissner merged 5 commits into
GideonZ:masterfrom
JC-000:fix/sd-card-interrupts-off
Nov 12, 2026
Merged

chrisgleissner merged 5 commits into
GideonZ:masterfrom
JC-000:fix/sd-card-interrupts-off

Conversation

@JC-000

@JC-000 JC-000 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1055

Problem

Every SD card sector transfer runs with all interrupts masked, including the poll loops that wait for the card to finish programming. While the card is busy the system tick, networking and USB interrupts are all blacked out. Measured on the C64 Ultimate: an interrupts-off stretch of ~119 ms during SD writes. The poll waits are bounded by the SD spec worst case (up to ~100 ms for a data token, ~250 ms for card-busy), so the blackout can in principle be longer still.

Cause, on current master:

SdCard::read/write wrap each sector — command, R1, data, and the card-busy / data-token poll waits — in ENTER_SAFE_SECTION (software/io/sd_card/sd_card.cc:257-276 and :334-346). The poll waits live in sdio.cc. The section only needs to give one task exclusive use of the SPI port; the SPI master raises SS after each byte and needs no CPU timing, no ISR uses SDIO, and no DMA is involved.

What changed and why

Replace the interrupt mask with the driver's existing per-instance mutex, taken around each sector, around CID/CSD, and around init(). Mutual exclusion between tasks is preserved; interrupts stay on while the card programs. Non-OS builds (where ENTER_SAFE_SECTION was already empty) are unchanged.

Products. builds for the C64 Ultimate and the Ultimate-II cartridges (U2+, U2+L); the Ultimate 64 Elite (Nios) does not compile sd_card.cc. Tested on the C64 Ultimate only.

How I tested it

Host: macOS, with the device-free tests run in an Ubuntu 24.04 container (g++ 13.3). The hardware runs used the test harness from the same machine.

Host tests (device-free, run before and after the change):

  • SD driver against a modelled card: make -B -C target/pc/linux/sdcard test
    • with the change: 12 passed, 0 failed
    • without it: with sd_card.cc from master: 10 fail (init, CID/CSD and write run with interrupts off and without the mutex)

Hardware.

Device Firmware Ultimate FPGA C64 core
Ultimate 64 Elite ac0304316 126 1.50
C64 Ultimate b0f40a17b 126 1.50

RED = master, GREEN = fix, from the runtime interrupts-off profiler.

RED GREEN
top interrupts-off site SdCard::write, ~119 ms no SD site in the top list
data round-trip, transfer rate — unchanged within noise

Host suite target/pc/linux/sdcard (gcc; the Makefile hard-codes CXX=g++, and it also builds under clang with a CXX=clang++ override): 12/12 with the fix; 10 fail on master; 13 mutants killed.

Standard profile (./run-tests --profile standard), red = master, green = a build carrying this landing set of fixes (this change included), report from python3 tools/e2e_report.py:

  • U64 Elite: 71 of 72 suites pass on master and 71 of 72 with the fixes. The one failure is the same on both, iec-partition-config: it stops at a key-send step because the upstream test's REST backend has no F2 key alias (rest_backend.py:556), a test-side limitation, not an app difference.
  • C64 Ultimate: 71 of 72 on master and 71 of 72 with the fixes. The one failure is again iec-partition-config, here at a "menu screen unavailable" step that also fails on master, so it is not from these changes.

Soaks pass on both devices: mount-cache-leak, listener-soak, network-connection.

Hardware: C64 Ultimate with an SD card

SdCard::read and SdCard::write ran every sector, including the wait for the card to finish programming, inside a critical
section that keeps interrupts off. On a C64 Ultimate with an SD card, a counter build of master showed SdCard::write holding
interrupts off for up to 149 ms (and SdCard::read 9 ms) while a large file was written, with 18386 such sections of 2 ms or
more across the run. With this PR, the same build and the same transfers show no interrupts-off section of 2 ms or more at
any SdCard site. The driver takes its own mutex per sector instead, so the port is still used by one task at a time. Eight
megabyte writes with a second client reading the card at the same time kept matching checksums, and the rate did not drop
(271 vs 250 KB/s alone, 204 vs 176 KB/s with the second client).

The results table is in the comment below.

Untested

  • Ultimate-II cartridge (U2+ / U2+L): not tested. I do not have one. Not built either for the cartridges, because the build environment I use cannot build those targets; CI builds them.
  • The C64 Ultimate gateware is not in this tree; the change assumes its SPI master behaves like the in-tree one (per-byte transceive, no interrupt or DMA on SDIO).
  • The Makefile hard-codes CXX=g++; a CXX=clang++ override works but is not what the default run uses.

Written with Claude Opus 5.5 in Claude Code.

SdCard::read() and write() ran each sector's whole SPI exchange
(command, response, data and the wait for the card) inside
ENTER_SAFE_SECTION. After a write the card stays busy while it
programs the block, up to 250 ms by the spec. On a C64U, timing the
interrupts-off sections with a free-running counter showed 78 ms at
SdCard::write, and over a thousand sections of 2 ms or more since
boot. The tick and the RMII, UART and USB interrupts waited for the
card.

The section only kept other tasks off the SPI port. The SPI master in
this tree (fpga/io/spi, used by ultimate_logic_32) clocks each byte on
its own and raises SS between bytes, so the exchange needs no timing
from the CPU, and no interrupt handler uses the port. The C64U's
gateware is not in this tree; its SD port is assumed to work the same
way. That still has to be confirmed on a C64U.

The card's mutex was created in the constructor but never taken. It
now does the job with interrupts on: around each sector in read() and
write(), around the CID and CSD reads, and around init(), which the
card manager runs on its own task when a card is inserted. sdio.cc is
unchanged, and builds without OS are unchanged.

The waits for the card (busy after a write, the data token before a
read) still poll, now with interrupts on. They do not yield: with the
tick running, tasks of the same priority already share the CPU by time
slicing, and higher priorities preempt. A yield every few polls was
tried and dropped. Against a busy task of the same priority it handed
over the rest of every 5 ms tick, and a host model of the driver
(0.4 us per SPI byte) put reads and writes at 1 to 4 % of the old
rate. Without it they keep 97 to 99 % of the old rate on a fast card
and 74 to 91 % on slower ones.

Risk: this is the SD block driver. Anything that touches the SD port
without taking the mutex can now run in the middle of a transfer.
sdio_sense() (card detect, a register read with no SPI exchange) is
the only such caller left. A transfer can now be preempted part-way
through a sector, which costs some throughput when another task of
the same priority is busy (the figures above).

The new host test target/pc/linux/sdcard runs sd_card.cc and sdio.cc
against a simulated slow card, with the mutex simulated as a
non-recursive FreeRTOS mutex. It covers init(), CID/CSD, read and
write, a contended mutex and the error paths, and checks that the
waits never give up the CPU (taskYIELD, portYIELD, vTaskDelay or
vTaskDelayUntil). SD_MODEL=1 prints the throughput model. It is
part of make host_tests and builds with gcc and clang.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chrisgleissner chrisgleissner added bug Existing behavior is incorrect, broken, or regressed; includes supported documentation defects. storage Disk/tape emulation, images, mounting, copying, filenames, filesystems, and storage media. labels Nov 10, 2026
@chrisgleissner
chrisgleissner self-requested a review November 10, 2026 12:30
@chrisgleissner

Copy link
Copy Markdown
Collaborator

@JC-000 thanks, this is a clear improvement. The mutex covers the same regions that were interrupts-off, every exit path releases it, and init() is now protected too. With only sd_card.cc reverted to master, 10 of the 12 new host tests fail, so the tests do guard the change.

To get it over the line:

  1. Comment wording. The comment at sd_card.cc:35-38 describes what the code used to do. Please state the property instead, e.g. that a transfer holds the lock but leaves interrupts on.
  2. Hardware. The U64 Elite does not build this file, so the check belongs on a C64U: the interrupts-off stretch of about 119 ms during an SD write should be gone, and a large SD copy with network traffic in parallel should keep matching checksums. Could you confirm that run in the description?

Happy to merge after that.

@chrisgleissner chrisgleissner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @JC-000. Requesting changes for the points in my comment above; I will merge once they are addressed.

@chrisgleissner

chrisgleissner commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

@JC-000 thank you again for the SD card work; your measurements of the long interrupt blackout are what made this worth fixing. I had said I would finish this PR myself. I am handing it back to you, so please treat it as yours again. This is where it stands.

Done (pushed to your branch):

  • 69d3f05f0: the comment above SD_LOCK() now states what the mutex does.
  • 25682c787: a merge of master (the host_tests list in the top-level Makefile overlapped; both lines kept). The 12 SD host tests pass, and CI is green.

Outstanding before this can be merged:

  1. Hardware run on the C64 Ultimate with an SD card inserted. The bench unit used for review has no card, so the SD driver could not be exercised there. Please show, on master and on this branch, that the interrupts-off stretch in SdCard::write (about 119 ms) is gone, and that a large copy to the SD card with network traffic in parallel keeps matching checksums and a similar rate.
  2. U2+ and U2+L. sd_card.cc is compiled for them; CI only builds them. Please say whether they were run, or state that they were not.

Nothing else is asked of you on this PR.

@JC-000

JC-000 commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Hardware run: C64 Ultimate with an SD card, RAM loads (cold), one lock hold, 2026-11-10
Both images are the same tree plus the same bench-only counter commits (they report the longest interrupts-off sections,
with the code address of each). The first is master (f5aaf08, the master this PR was merged with), so it has no part of the fix.
The second is this PR's head (25682c7). Each run writes 3 x 8 MB to /SD over FTP, alone ("serial"), then 3 x 8 MB while a
second FTP client repeatedly reads a 2 MB file from the same card and lists its folder ("contended"). Every upload is read back
and its sha256 compared; every read by the second client is compared too.

row image hash interrupts-off sections of 2 ms or more at SdCard code, after the writes longest at SdCard::write sha256 (uploads, reads) serial KB/s (median of 3) contended KB/s (median of 3)
master + counters e1b087b4f SdCard::write 149 ms, SdCard::read 9 ms 149 ms all matched 250 176
PR head + counters dca378da1 none none all matched 271 204

Count of interrupts-off sections of 2 ms or more during the writes: 18386 on master, 3 with the PR. In the PR run the only
other long sites are not SD: U64Machine::clear_ram (66 ms, at boot), S_SidDetector (11 ms) and xTaskResumeAll (4 ms).
The 149 ms on master is larger than the 119 ms first measured; the figure is the longest since boot on a card under this load,
and the site is the same (SdCard::write). The rate with the PR is not lower than master's (271 vs 250 and 204 vs 176 KB/s).
Network traffic in parallel is the FTP transfers themselves (the upload plus the second client); no separate flood was run.

U2+ and U2+L: Not run. We have neither device; they were only compiled by CI.

Written with Claude Opus and Claude Sonnet in Claude Code.

Makefile host_tests: keep both the sdcard and the new socketdma test lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chrisgleissner chrisgleissner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. The hardware run on the C64 Ultimate covers what I asked for: SdCard::write no longer holds interrupts off (149 ms on master), sections of 2 ms or more drop from 18386 to 3, all checksums match and the rate is not lower. The comment wording is fixed and the U2+ and U2+L status is stated (compiled by CI only). Approving.

@chrisgleissner chrisgleissner self-assigned this Nov 11, 2026
@chrisgleissner

Copy link
Copy Markdown
Collaborator

I'm assigning this to myself. I'm investigating whether it is merge ready by running the standard E2E profile locally on an Ultimate 64 Elite and an Ultimate II+L, with this PR combined with the other approved bug fixes, and comparing against master. I'll report the result here.

@chrisgleissner

Copy link
Copy Markdown
Collaborator

Test result for the batch this PR is part of (#1043, #1064, #1065, #1066, #1068, #1070).

Firmware: upstream master b57d894a0 plus these six PRs (build 5c1492908), compared with plain master.
Devices: Ultimate 64 Elite (JTAG, from RAM) and Ultimate II+L in a C64 Ultimate (flashed). Standard E2E profile, overlay mode.

Run Ultimate 64 Elite Ultimate II+L in C64 Ultimate
Batch build, full standard profile 67 of 72 suites passed 39 of 48 suites passed
Failed suites rerun after installing the missing host Python modules (tests/requirements.txt) all 5 pass 6 of 8 fail
Master, same suites all 5 pass the same 6 of 8 fail

@chrisgleissner
chrisgleissner merged commit c164482 into GideonZ:master Nov 12, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Existing behavior is incorrect, broken, or regressed; includes supported documentation defects. storage Disk/tape emulation, images, mounting, copying, filenames, filesystems, and storage media.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SD card driver masks all interrupts for ~119 ms during card writes (C64 Ultimate)

2 participants