Skip to content

afatfs: report the whole SD card's free space over MSP - #12156

Open
MrScothh wants to merge 16 commits into
iNavFlight:maintenance-10.xfrom
MrScothh:feature/afatfs-free-space
Open

MrScothh wants to merge 16 commits into
iNavFlight:maintenance-10.xfrom
MrScothh:feature/afatfs-free-space

Conversation

@MrScothh

@MrScothh MrScothh commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Builds on #12056 (freefile regrow at boot), so this branch contains it and the diff shows both until #12056 is merged. The changes of its own are the commits after it.

What it does:

  • The count starts at the first MSP_SDCARD_SUMMARY, which the Configurator sends from the Blackbox tab, and arming stops it; stopped, it resumes where it was at the next request while disarmed. So nothing reads the FAT at the boots before a flight, and nothing in flight.
  • It counts the free clusters outside the freefile, one FAT sector at a time, paused while files are open, so it never holds up a log's writes. Regular allocations and frees keep it up to date afterwards.
  • A 2 ms gap follows each FAT sector: terrain takes the card from the blackbox only while afatfs_isIdle(), and back-to-back reads would keep it waiting until the count ends. A FAT sector that can't be read within a second ends the count, and the value stays unknown.
  • The freefile's own chain is skipped: it holds no free cluster, so its FAT sectors are not read.
  • Then the card's directories are read, one sector at a time with the same gap, to tell what holds the space taken outside the freefile:
    • the logs (LOG*.TXT) take whole superclusters from the freefile, so the rest of each log's last one stays taken without data until the log is deleted;
    • the terrain files (*.TER);
    • what no file or directory holds, left by writes cut short.
      Any change to a directory entry makes the walk run again at the next request. A directory that can't be read, or nests deeper than 4, leaves these unknown.
  • MSP_SDCARD_SUMMARY gets cardFreeSpaceKB, logTailsKB, terrainKB and lostKB (uint32 each) appended, 0xFFFFFFFF until counted or while the card is not ready. The fields before them are unchanged, so older configurators read the reply as before.
  • None of it is built into the bootloaders: nothing asks them for it.
  • Configurator side: Onboard logging: show the whole SD card's free space inav-configurator#2840.

Size against #12056:

Target Flash RAM ITCM
MATEKF722SE +1344 B (98.99 %) +80 B +8 B
MATEKF405SE +1680 B +60 B
KAKUTEF7 / KAKUTEF7HDV +1832 / +1824 B +72 B +16 B
TBS_LUCID_H7_WING +1848 B +128 B +8 B

The count step and the walk are kept out of line, or LTO would pull them into scheduler()'s ITCM. Bootloaders: MATEKF722SE_bl +80 B (91.4 % of 32 KB), MATEKF405SE_bl +24 B (83.7 %).

Tested in the SITL with --sdcard, each value checked against the image read by an independent script:

  • Free space: FAT32, 8 GB, empty and with 60 files with every third deleted; FAT16, 1 GB, with deleted files; after boot, during and after a log, on the next boot. All matched to the KiB.
  • On request: on the 8 GB card nothing was counted after 40 s without a request, and the count ended 14 to 16 s after the first one. Asked once and then armed for 40 s, it made no progress while armed and ended 9 to 12 s after the disarm, with the same value.
  • What holds the taken space: a FAT32 card of 2 GB (16 KB clusters) with PC files, a terrain file, nested folders, a log and two lost chains left on purpose, and a FAT16 card of 1 GB with logs. The log ends, the terrain data and the lost space matched to the KiB the script, which follows every chain in the image. On the first try the 2 GB card also had a lost chain of 44 MB I hadn't made: the test had killed the SITL while afatfs: regrow the blackbox freefile at boot, so the card is not full after 4 GB of logs #12056 was building the freefile, and the walk reported it.

On the TBS Lucid H7 Wing (2026-10-20), a 16 GB card (FAT32, 32 KB clusters) with bench logs and the lost chains of earlier power-cut tests: the count and the directory walk ended 8.7 s after the first request, and the free space (11163168 KiB), the log ends (308608 KiB), terrain (0) and lost space (1098880 KiB) all equal what the script reads from the card, read back in mass storage mode.

On a TBS Lucid H7 (SDIO) with a 16 GB card, FAT32 with 32 KB clusters, about 3800 FAT sectors, measured before the freefile skip (which leaves out about a quarter of them on that card):

  • The count ends 8 s after the card is ready. Sampled during the count with a bench build that prints it from the CLI, afatfs_isIdle() was true 91-92 % of the time, and 100 % after it. Without the gap the count took 0.7 s, with afatfs busy the whole time.
  • A 1.3 MB log lowered the free space by exactly the 4 MiB supercluster it took. At the next boot the regrow moved that much from outside the freefile into it, and the total stayed the same.

A 1 ms gap would roughly halve the count time and still leave afatfs idle most of the time; I kept the 2 ms I measured.

#12060 refills the freefile while running; #12158 joins the two.

…boot

The freefile is created once, on the largest free block of the card and
at most 4 GB (the largest FAT32 file), and reused as it is at every later
boot. Its size is a whole number of superclusters plus one cluster, so
once the logs have taken the superclusters one cluster is left: the card
reads as full and the blackbox stops logging until the card is formatted,
although the rest of a card larger than 4 GB and any log deleted from a PC
are free.

When the freefile is below 2 GB at boot, search the FAT for the largest
free block as on the first boot, and if that is larger, free the old
freefile's clusters and move the freefile there. Larger freefiles are
reused without a search, as before.
…w it

Logs take their clusters from the start of the freefile, so it only ever
shrank until the next format, and one log could never grow past what was
left of it at boot. On a card larger than 4 GB the clusters that follow
the freefile are normally free, so at boot extend it over them, up to the
largest file size, leaving AFATFS_FREEFILE_LEAVE_CLUSTERS for regular
files as a new freefile does. Only a freefile that is still below 2 GB
afterwards is moved to the largest free block.

The new clusters are chained and flushed before the freefile's last
cluster points at them, and the new size is saved after that, so a power
cut leaves at worst unreferenced clusters, never a chain that runs into
free ones.
After the skip the search went on reading the FAT sector of the freefile's
first cluster while the cluster number had moved past it, so the entries
it examined belonged to other clusters. It could only matter when those
sectors were already cached, and the search at boot now runs with the
freefile in place.
afatfs_FATFillWithPattern() counted a final FAT sector it only writes part
of among the sectors to pre-erase. That sector has to be read first, and
on an SD card on SPI the read ends the multiple-block write started with
ACMD23 before it reaches that block; the SD specification leaves an
unwritten pre-erased block undefined, erased or old. Its other entries,
which can belong to the next file, could then be read back erased. A new
freefile ends that way (whole superclusters plus one cluster), and so
does every extension of it.
…rectory entry each step

A power cut while the freefile was regrown or moved at boot left whatever
chain was in flight as a lost FAT chain: up to 4 GB of new chain, and up to
2 GB of the old freefile when moving it. Three cuts on a TBS Lucid H7 Wing
left three lost chains of 650 MB on average.

The new chain now grows in 256 MB blocks, each one chained, linked, saved and
flushed before the next. A moved freefile gives its old clusters back the
same way from its end: the smaller size is saved, then the chain is cut there,
then the tail is freed. A cut strands at most one block either way.
The freefile holds only part of the card, at most 4 GiB, and with the regrow
at boot later logs also reach the free clusters outside it. After mount, while
no file is open, those clusters are counted one FAT sector at a time with a
gap after each, so that terrain can still take the card while afatfs is idle,
and the count is kept up to date by allocations and frees.

MSP_SDCARD_SUMMARY gets the freefile plus that count appended as
cardFreeSpaceKB, 0xFFFFFFFF until the count is done (or for good if a FAT
sector cannot be read). Older configurators read the fields before it as
they did.
@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

Regrow the SD freefile and report whole-card free space over MSP

✨ Enhancement 🐞 Bug fix 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Regrow or relocate the freefile at boot so reclaimed SD space becomes available for logging.
• Count free clusters in the background and report whole-card free space through an appended MSP
 field.
• Document SD logging behavior and the distinction between next-log and whole-card capacity.
Diagram

graph TD
    Boot["Mount filesystem"] --> Existing{"Freefile exists?"} -->|Yes| Extend["Extend freefile"] --> Small{"Below 2 GiB?"} -->|Yes| Relocate["Choose larger block"] --> Ready["Filesystem ready"] --> Count["Count FAT space"] --> MSP["MSP card summary"]
    Existing -->|No| Relocate
    Small -->|No| Ready
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use FAT32 FSInfo for free-space reporting
  • ➕ Could avoid a post-mount FAT scan on FAT32 cards.
  • ➖ Does not cover FAT16 and would require validating and maintaining FSInfo counts that afatfs currently does not use.
2. Count all clusters during mount
  • ➕ Makes the total available as soon as the filesystem becomes ready.
  • ➖ Delays filesystem readiness and logging while scanning large FATs.

Recommendation: Keep the incremental post-mount scan: it supports both FAT16 and FAT32 without trusting FSInfo or blocking mount. The boot-time regrow and relocation address the separate problem of making reclaimed space usable for logs; review their write ordering and interruption behavior closely.

Files changed (6) +397 / -23

Enhancement (3) +384 / -20
fc_msp.cAppend whole-card free space to MSP_SDCARD_SUMMARY +3/-0

Append whole-card free space to MSP_SDCARD_SUMMARY

• Serializes the new afatfs whole-card free-space value after the existing SD summary fields, preserving their order. Emits zero for the field when SD-card support is disabled.

src/main/fc/fc_msp.c

asyncfatfs.cRegrow the freefile and track whole-card free clusters +379/-20

Regrow the freefile and track whole-card free clusters

• Adds mount-time freefile extension and relocation in persisted steps, plus a paced post-mount FAT scan that pauses while files are open. Tracks subsequent regular cluster allocations and frees, exposes the completed count in KiB, and leaves it unknown if a FAT sector cannot be read.

src/main/io/asyncfatfs/asyncfatfs.c

asyncfatfs.hExpose the whole-card free-space query +2/-0

Expose the whole-card free-space query

• Declares afatfs_getFreeSpaceKB() and the sentinel returned before counting completes or when the count fails.

src/main/io/asyncfatfs/asyncfatfs.h

Documentation (3) +13 / -3
Blackbox.mdExplain SD-card log files and freefile regrowth +3/-0

Explain SD-card log files and freefile regrowth

• Documents the log and FREESPAC.E filenames and explains that space freed by deleting logs on a PC becomes available again after a power cycle.

docs/Blackbox.md

README.mdDocument whole-card free space in the SD summary +2/-1

Document whole-card free space in the SD summary

• Distinguishes the existing next-log freefile capacity from the new whole-card value. Documents the appended field and its unknown sentinel.

docs/development/msp/README.md

msp_messages.jsonAdd the SD free-space field to the MSP specification +8/-2

Add the SD free-space field to the MSP specification

• Bumps the specification patch version and appends cardFreeSpaceKB to MSP_SDCARD_SUMMARY without changing earlier fields. Clarifies the existing freeSpaceKB field's meaning.

docs/development/msp/msp_messages.json

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

qodo-free-for-open-source-projects Bot commented Oct 16, 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


Remediation recommended

1. Removed cards still show free space ✓ Resolved
Description
serializeSDCardSummaryReply() appends afatfs_getFreeSpaceKB() even when it has set the card
state to not present. After a completed count, removing the card leaves the filesystem state and
count intact, so the reply reports free space from the removed card alongside a not-present state.

2. Card free space shows up late, mostly on small cards ✓ Resolved
Description
afatfs_countFreeClustersContinue reads every FAT sector from cluster 2 to the end of the volume,
including the ones that hold only the freefile's chain. Those sectors can't contain a free cluster,
so each costs a card read plus the 2 ms gap for nothing. For a 4 GB freefile with 32 KB clusters
that is about 1024 wasted sectors: roughly a quarter of the count on a 16 GB card, half on an 8 GB
one, and nearly all of it on cards of 4 GB or less. The wait is longest on SPI cards, the case the
author asked about.

Grey Divider

Tip of the day
💡 Did you know, you can import rules and skills only from the repositories your team follows

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/main/fc/fc_msp.c Resolved
Comment thread src/main/io/asyncfatfs/asyncfatfs.c Resolved
…dy card

The freefile's chain holds no free cluster, so the count no longer reads its
FAT sectors: about a quarter of them on a 16 GB card, nearly all on cards of
4 GB or less. And a removed card's count stays in afatfs, so the summary sends
it only while the card is ready.
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

RAM / Flash usage vs. base commit ae6ace4 — commit b7167ce

Target Flash Δ RAM Δ
MATEKF405 +3148 B (+0.44%) CCM: -4 B (-0.01%)
RAM: +92 B (+0.09%)
MATEKF722 +2288 B (+0.49%) ITCM_RAM: ±0 B (±0.00%)
RAM: +80 B (+0.09%)
TCM: ±0 B (±0.00%)
MATEKF765 +4084 B (+0.54%) DTCM_RAM: -4 B (-0.01%)
SRAM1: +76 B (+0.06%)
MATEKH743 +3016 B (+0.38%) D2_RAM: ±0 B (±0.00%)
DTCM_RAM: ±0 B (±0.00%)
ITCM_RAM: ±0 B (±0.00%)
RAM: ±0 B (±0.00%)

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

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Test firmware build ready — commit b7167ce

Download firmware for PR #12156

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.

…ding to KiB

With 512-byte clusters an odd freefile and an odd outside count each lost half a KiB.
@error414

Copy link
Copy Markdown
Contributor

tested and it works, just I would like to add couple notes

  1. FC calculates free space after each boot, probably it should be on demand from configurator
  2. arm should stop calculating free space

The count read the whole FAT after every boot, from the realtime callbacks,
and went on while armed whenever no file was open (a card used only for
terrain, or before the log opens). It now starts at the first
MSP_SDCARD_SUMMARY, which the Configurator sends from the Blackbox tab, and
arming stops it; a stopped count resumes where it was at the next request.
After the free count the card's directories are read, one sector at a time
with the count's gap, and MSP_SDCARD_SUMMARY gets three fields appended:

- logTailsKB: each log takes whole superclusters from the freefile, and the
  rest of its last one stays taken without data until the log is deleted;
- terrainKB: the terrain files (*.TER);
- lostKB: what is taken outside the freefile but held by no file or
  directory, left by writes cut short.

Any change to a directory entry makes the walk run again at the next request.
A directory that can't be read, or nests deeper than 4, leaves the three
unknown until the card changes.
@MrScothh

Copy link
Copy Markdown
Contributor Author

@error414 thanks for testing it, and both points are right. The count started after every boot and only paused while a file was open: with the blackbox on the card the log opens at arm and stopped it, but with the card used only for terrain, or between arming and the log opening, it went on. Now it starts only when the Configurator asks for the card's summary (the Blackbox tab), and arming stops it, so nothing is read at the boots before a flight. The tab also shows what holds the taken space now: terrain data, the unused end of logs (each log takes whole blocks of a few MB) and space no file holds, left by writes cut short.

…rst cluster

The directory walk skipped the freefile's entry by its first cluster. Once the
freefile is used up, that cluster is the first of whatever file follows its
region, so the walk skipped that file instead and reported its size as lost:
on a full card in the SITL, 512 KiB for the log after it, and the same after
every lap of iNavFlight#12150's wraparound, whose relocated freefile is used up by the
log created in it. The entry is now told by its sector and index.
@MrScothh

MrScothh commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased nothing, one commit on top (83ac671): the directory walk told the freefile's entry apart by its first cluster, and once the freefile is used up that cluster is the first of the file after its region, which the walk then skipped and reported as lost. I found it testing this PR over #12150 in the SITL: after each lap of the wraparound the log after the relocated freefile showed as 512 KiB lost. The entry is now told by its sector and index. Flash +48 B on KAKUTEF7, KAKUTEF7HDV and MATEKF405SE, +32 B on MATEKF722SE and TBS_LUCID_H7_WING; RAM and ITCM unchanged; unit tests 620/620.

The test itself, on this branch merged with next-10.1 (345233c): a 1 GB card full but for a 6 MB and a 1.5 MB hole, 13 short logs, so the freefile runs out at the 10th and #12150 evicts logs 1 to 3 for logs 11 to 13. The free space reported over MSP matched the image's FAT at every step (8192 KiB at boot, 3064 KiB after the three laps); the only lost space is the last cluster of the used-up freefile, 4 KiB, which #12150 leaves behind when it relocates it. Nothing of #12158 is needed over #12150: its reclaim touches the directory, not the FAT, so the count neither waits behind it nor has to start over.

@sensei-hacker sensei-hacker added this to the 10.1 milestone Nov 28, 2026
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.

3 participants