Skip to content

blackbox: hand the device a block of bytes, not one byte per call - #12059

Merged
sensei-hacker merged 9 commits into
iNavFlight:next-10.1from
MrScothh:feature/blackbox-block-writes
Nov 29, 2026
Merged

sensei-hacker merged 9 commits into
iNavFlight:next-10.1from
MrScothh:feature/blackbox-block-writes

Conversation

@MrScothh

@MrScothh MrScothh commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #12058 (the byte count per iteration it adds stays in blackboxWrite()), which is stacked on #12057; their commits show here until they are merged.

The frame encoders write one byte at a time, and every byte went to the device on its own: one afatfs_fputc() or flashfsWriteByte() call per byte, each with its own checks and cache lookup.

The change

blackboxWrite() collects the bytes in a 128 byte block, and the block goes to the device with one afatfs_fwrite() or, on SITL, fwrite() call. It goes out:

  • when it is full;
  • before anything else reaches the device: header prints, device flushes, the end of a log, the header budget;
  • at the end of every blackboxUpdate().

So nothing waits longer than one loop and the bytes keep their order. While the terrain code has the SD card, the block waits until the card is back. Serial ports and flash chips still get one byte at a time: serialWriteBuf() would wait for room, and an asynchronous flashfsWrite() drops a whole block the busy chip can't take.

Results

On a TBS Lucid H7 logging to SD the blackbox takes 2.3% of the CPU at 1 kHz and 4.4% at 2 kHz; with this, 10 to 13% less. Logs decode the same.

Not tested:

  • F4 on hardware.

Flash chips and F7 have run since: a W25Q128 on a Flywoo F722 Pro V2 and a W25N01G NAND on a Holybro Kakute H7 Mini, see below.

After review

Built on F4, F7, H7, AT32 and SITL; KAKUTEF7 and KAKUTEF7HDV fit their ITCM. On the TBS Lucid H7 Wing after review: a 60 s log at 1983 Hz, no iteration missing; with #12058's bench test of the switch (a card holding its write for 0.3 to 4 s, the switch moved around it), 13 logs with no corrupt frame. Not tested: flash chips (the Lucid has none).

Related PRs

Tested on flash chips (2026-10-06)

  • Flywoo F722 Pro V2, W25Q128 (NOR): logs at 1 kHz (71 KB/s) and 200 Hz, 8 to 11 MB, downloaded over MSP and decoded, no corrupt frame.
  • Holybro Kakute H7 Mini, W25N01G (NAND): 15 logs, 6 MB; a 173 s log at 200 Hz lost 8 iterations in two 12 ms stalls of the flash, nothing else.
    Both from images merged on the current maintenance-10.x, which the branch has had merged in since 0a27742 (flash: guard flashFlush() against a NULL flush callback #11943, the flash flush fix, included).

The encoders write one byte at a time, and every byte went to the device
on its own: one afatfs_fputc() or flashfsWriteByte() call per byte.
Collect them in a 128 byte block and hand it over with one
afatfs_fwrite() or flashfsWrite() call. The block goes out when it is
full, before anything else reaches the device (header prints, flushes,
the end of a log, the header budget) and at the end of every
blackboxUpdate(), so nothing waits longer than one loop and the bytes
keep their order; while the terrain code holds the SD card it waits
until the card is back. Serial ports still get one byte at a time,
since serialWriteBuf() would wait for room.

On a TBS Lucid H7 logging to SD the blackbox takes 2.3% of the CPU at
1 kHz and 4.4% at 2 kHz; this cuts that time by 10 to 13%.
@qodo-code-review

Copy link
Copy Markdown
Contributor

ⓘ Qodo reviews are paused because the subscription is no longer active. Ask your workspace admin to reactivate the subscription to resume reviews. Manage billing

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Batch blackbox writes and pause safely when the SD cache fills

✨ Enhancement 🐞 Bug fix 🕐 40+ Minutes

Grey Divider

AI Description

• Batch encoded bytes into device writes to reduce blackbox CPU overhead while preserving output
 order.
• Pause SD logging before cache exhaustion and resume on an I-frame to avoid partial frames.
• Correct and expand SD cache capacity; expose pause statistics through sd_info.
Diagram

graph TD
    Loop["Loop update"] --> Guard{"SD space available?"} -->|yes| Encoder["Frame encoder"] --> Block["128-byte block"] --> Devices["Device writes"] -->|SD| Cache["FAT sector cache"]
    Cache -.-> Guard -->|no| Paused["Paused logging"] -->|recovered I-frame| Encoder
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Enlarge the SD cache without pausing
  • ➕ Keeps the existing logging state machine unchanged.
  • ➖ A sufficiently long card stall can still exhaust the cache and truncate a frame.
  • ➖ Does not reduce per-byte device-call overhead.
2. Encode complete frames into a dedicated staging buffer
  • ➕ Could reserve or reject a whole frame before writing any of its bytes.
  • ➖ Requires broader encoder changes and additional memory.
  • ➖ Complicates headers and events that share the output path.

Recommendation: Keep the shared write block and cache-aware pause approach: it reduces device-call overhead while handling stalls that a larger cache alone cannot guarantee against. Review hardware-specific cache placement and untested flash, F4, and F7 paths before relying on those configurations.

Files changed (6) +188 / -16

Enhancement (5) +167 / -8
blackbox.cPause logging on low SD space and flush each update +46/-3

Pause logging on low SD space and flush each update

• Checks device capacity before logging a frame and resumes a device-induced pause on an I-frame with a logging-resume event. Tracks pause counts and skipped iterations, and flushes pending bytes after each update unless terrain holds SD access.

src/main/blackbox/blackbox.c

blackbox.hExpose blackbox device-pause counters +1/-0

Expose blackbox device-pause counters

• Declares the accessor used to report device-induced pause and skipped-iteration counts.

src/main/blackbox/blackbox.h

blackbox_io.cBatch device writes and estimate SD headroom +106/-5

Batch device writes and estimate SD headroom

• Collects encoded bytes into 128-byte blocks for SD, flash, and SITL writes while retaining byte-wise serial output. Flushes before other device operations and adds iteration-size tracking and SD pause/recovery thresholds.

src/main/blackbox/blackbox_io.c

blackbox_io.hDeclare buffering and capacity-check interfaces +6/-0

Declare buffering and capacity-check interfaces

• Exposes block flushing, iteration-size tracking, and device-buffer threshold checks to the blackbox state machine.

src/main/blackbox/blackbox_io.h

cli.cReport blackbox SD pauses in sd_info +8/-0

Report blackbox SD pauses in sd_info

• Adds pause count, skipped-loop count, and largest logged iteration size to SD diagnostics when blackbox support is enabled.

src/main/fc/cli.c

Bug fix (1) +21 / -8
asyncfatfs.cSize the FAT cache by MCU and exclude retained sectors +21/-8

Size the FAT cache by MCU and exclude retained sectors

• Expands cache capacity on H7, F7, and F4 SPI targets and places the F4 SPI cache in fast RAM. Makes free-space reporting exclude retained sectors that cannot be evicted, giving the pause check a usable capacity estimate.

src/main/io/asyncfatfs/asyncfatfs.c

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Flash logs lose bytes when writes stall ✓ Resolved
Description
blackboxWriteFlush() submits a full 128-byte block with flashfsWrite(..., false) and clears the
block before knowing whether FlashFS buffered it. When flash is busy, FlashFS can silently discard
an asynchronous remainder larger than its 127-byte usable buffer, so a full block is lost.

2. SD logs lose bytes during busy writes ✓ Resolved
Description
blackboxWriteFlush() clears blackboxWriteBlockCount before calling afatfs_fwrite() and ignores
the returned byte count, leaving no record of an unaccepted suffix. When AsyncFatFS is busy or
cannot lock or allocate the next sector, a zero or partial write drops buffered frame data before
subsequent bytes or end-of-log closure.


Remediation recommended

3. Logging resumes with the switch off ✓ Resolved
Description
The BLACKBOX_STATE_PAUSED resume condition checks only blackboxDeviceBufferRecovered() when
blackboxPausedForDevice is set, omitting the Blackbox RC-mode check. If the pilot switches logging
off during a device-buffer pause, recovery emits a resume event and logs an I-frame before the
running-state check pauses logging again.

4. Terrain waits for a paused SD card ✓ Resolved
Description
The new low-buffer branch moves Blackbox into BLACKBOX_STATE_PAUSED, but the terrain handoff
grants pending SD-card requests only while Blackbox is running or stopped. If terrain requests
access during a device-buffer pause, the request cannot be granted while that pause persists;
terrain's access check waits for the grant.

Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/main/blackbox/blackbox_io.c Resolved
Comment thread src/main/blackbox/blackbox.c Resolved
Comment thread src/main/blackbox/blackbox.c Resolved
Comment thread src/main/blackbox/blackbox_io.c Resolved
@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Test firmware build ready — commit a1a1be3

Download firmware for PR #12059

251 targets built. Find your board's .hex file by name on that page (e.g. MATEKF405SE.hex). Files are individually downloadable — no GitHub login required.

Development build for testing only. Use Full Chip Erase when flashing.

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RAM / Flash usage vs. base commit 01a7aa3 — commit a1a1be3

Using the nearest available size baseline: this build contains base commit 6cbfc64, which has no stored baseline yet, so the deltas also include what was merged to the base since 01a7aa3.

Target Flash Δ RAM Δ
MATEKF405 ⚠️ +5948 B (+0.82%) CCM: +12448 B (+38.23%)
RAM: -2140 B (-2.05%)
MATEKF722 ⚠️ +1712 B (+0.36%) ITCM_RAM: -928 B (-7.40%)
RAM: +8540 B (+9.84%)
TCM: +128 B (+0.51%)
MATEKF765 ⚠️ +3640 B (+0.48%) DTCM_RAM: +128 B (+0.45%)
SRAM1: +8544 B (+6.82%)
MATEKH743 ⚠️ +9732 B (+1.22%) D2_RAM: +256 B (+7.84%)
DTCM_RAM: +128 B (+0.99%)
ITCM_RAM: -896 B (-5.46%)
RAM: +14612 B (+10.26%)

See RAM/flash optimization guide for techniques to reduce usage.

@MrScothh
MrScothh force-pushed the feature/blackbox-block-writes branch from c6090ca to 99ed011 Compare September 28, 2026 18:10
@MrScothh
MrScothh force-pushed the feature/blackbox-block-writes branch from 99ed011 to 887e88e Compare September 28, 2026 19:20
…ume iteration is not counted

On the bench, sd_info counted one iteration too many for every pause the card
ended: the iteration that resumes is logged. When the switch takes over a pause
for the card and comes back on while the card is still behind, the resume wrote
its I frame into what is left below the threshold, 80 to 255 bytes: enough in
8 runs, not after a large iteration. Now it waits, and those iterations count
as lost to the card.
@MrScothh

MrScothh commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

@sensei-hacker tested on two flash chips today, both from images merged on the current maintenance-10.x: a W25Q128 NOR on a Flywoo F722 Pro V2 (logs at 1 kHz and 200 Hz, 8 to 11 MB, decoded with no corrupt frame) and a W25N01G NAND on a Holybro Kakute H7 Mini (a 173 s log lost 8 iterations in two 12 ms stalls of the flash, nothing else); details in the description. F4 and other SD cards remain untested. Is there anything else you would like tested?

@MrScothh

Copy link
Copy Markdown
Contributor Author

Flight data with this PR at its current head (0a27742): on the four flights listed on #12058 (1 kHz on SD, about
104 KB/s) the two flights in which the card never went busy lost 0.02 % of the iterations, 14 ms at most at a time.

@sensei-hacker
sensei-hacker changed the base branch from maintenance-10.x to next-10.1 November 6, 2026 05:08
@sensei-hacker
sensei-hacker changed the base branch from next-10.1 to maintenance-10.x November 28, 2026 21:18
@sensei-hacker
sensei-hacker changed the base branch from maintenance-10.x to next-10.1 November 28, 2026 21:18
@sensei-hacker
sensei-hacker merged commit a04be99 into iNavFlight:next-10.1 Nov 29, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants