Kleidos API Search

In development. It changes without notice.

LittleFS, NVS, the SD card's file system, the writer of updates, and what the security fuses say.

LittleFS holds the encrypted vault and survives an update. NVS holds preferences, the lockout's count, the event log and the hosts' names. The SD card is there only on the boards with a slot. Each has a handle that closes what it opened.

if ( fs.mount() ) {
auto f = kleidos::platform::littlefs::open( "/vault/groups.bin", "r" );
}

Mounting never formats; a partition is formatted only where every sector of it reads blank or a caller says so. This facade reads the security fuses and burns none.

See also
Vault Storage, SD Card, Update Policy

Files

file src/platform/storage/debug/storage_probe.cpp
The bench probe under the vault's storage: link-time wraps of the vault partition's flash calls and of the LittleFS API, and the flash primitives.
file src/platform/storage/debug/storage_probe.h
The bench probe under the vault's storage: what LittleFS and the flash cost one vault operation, and what one vault write programs and erases.
file src/platform/storage/little_fs.cpp
LittleFS mount, file, and directory operations.
file src/platform/storage/little_fs.h
LittleFS mount lifecycle and file I/O facade.
file src/platform/storage/little_fs_mmap_guard.h
When LittleFS may be handed a vault partition it reads through a memory map.
file src/platform/storage/little_fs_mount_logic.h
When a failed LittleFS mount may format: the blank test and the decision, with no ESP-IDF in it.
file src/platform/storage/nvs_store.cpp
ESP-IDF NVS namespace handle and typed accessors.
file src/platform/storage/nvs_store.h
ESP-IDF NVS (non-volatile storage) key/value facade.
file src/platform/storage/ota.cpp
OTA application-partition update implementation.
file src/platform/storage/ota.h
OTA application-partition update facade.
file src/platform/storage/sd_fs.cpp
SD-card (FATFS over SPI) mount, file, and directory operations.
file src/platform/storage/sd_fs.h
SD-card (FATFS over SPI) mount lifecycle and file I/O facade.
file src/platform/storage/security_fuses.cpp
Production eFuse hardening implementation.
file src/platform/storage/security_fuses.h
Production eFuse hardening helpers.
file src/platform/storage/vault_page_cache.h
A bounded set of mapped 64 KiB pages of the vault, least recently used out first.
file src/platform/storage/vault_read_path.h
The three ways an image reads the vault partition, and when each may serve.
file src/platform/storage/vfs_file.cpp
Shared POSIX-over-VFS file, directory, and path operations.
file src/platform/storage/vfs_file.h
Shared POSIX-over-VFS file handle and path operations.

Classes

class kleidos::platform::littlefs::LittleFsGuard
RAII guard that unmounts on destruction a mount it made itself. More about kleidos::platform::littlefs::LittleFsGuard
struct kleidos::platform::littlefs::BlankWalkRecord
What the last blank walk of the vault partition found. More about kleidos::platform::littlefs::BlankWalkRecord
struct kleidos::platform::littlefs::MapWindow
How the vault partition sits in the flash data window. More about kleidos::platform::littlefs::MapWindow
struct kleidos::platform::NvsStats
Aggregate NVS partition usage (entries and namespace count). More about kleidos::platform::NvsStats
class kleidos::platform::NvsStore
Owning handle to an NVS namespace with typed accessors. More about kleidos::platform::NvsStore
class kleidos::platform::ota::AppUpdateSession
RAII session that streams one OTA image to the next update partition. More about kleidos::platform::ota::AppUpdateSession
struct kleidos::platform::sdfatfs::Config
SD-card mount configuration. More about kleidos::platform::sdfatfs::Config
struct kleidos::platform::sdfatfs::VolumeInfo
FAT geometry and allocation state of the mounted volume. More about kleidos::platform::sdfatfs::VolumeInfo
struct kleidos::platform::littlefs::PageMapping
One page of the partition, as the mapper mapped it. More about kleidos::platform::littlefs::PageMapping
struct kleidos::platform::littlefs::PageCacheCounts
What the cache has done since the chip started; a debug build counts, others do not. More about kleidos::platform::littlefs::PageCacheCounts
class kleidos::platform::littlefs::PageCache< Mapper, Slots, Counted >
The least-recently-used set of mapped pages. More about kleidos::platform::littlefs::PageCache< Mapper, Slots, Counted >
struct kleidos::platform::vfs::Backend
Describes a VFS-mounted storage backend. More about kleidos::platform::vfs::Backend
class kleidos::platform::vfs::File
RAII handle to an open file or directory on a VFS-mounted backend. More about kleidos::platform::vfs::File

Typedefs

usingkleidos::platform::littlefs::File
usingkleidos::platform::sdfatfs::File
usingkleidos::platform::vfs::EntryVisitor
Visitor invoked once per directory entry.

Enumerations

enum class kleidos::platform::littlefs::MmapVerdict : uint8_t { kleidos::platform::littlefs::MmapVerdict::Admitted , kleidos::platform::littlefs::MmapVerdict::PlaintextUnderFlashEncryption , kleidos::platform::littlefs::MmapVerdict::MapFailed }
Whether LittleFS may be handed the vault partition on a build that maps it. More about kleidos::platform::littlefs::MmapVerdict
enum class kleidos::platform::littlefs::MountAttempt : uint8_t { kleidos::platform::littlefs::MountAttempt::Mounted , kleidos::platform::littlefs::MountAttempt::OutOfMemory , kleidos::platform::littlefs::MountAttempt::Refused }
How one mount attempt ended, with nothing formatted. More about kleidos::platform::littlefs::MountAttempt
enum class kleidos::platform::littlefs::DriverAnswer : uint8_t { kleidos::platform::littlefs::DriverAnswer::Mounted , kleidos::platform::littlefs::DriverAnswer::NoMemory , kleidos::platform::littlefs::DriverAnswer::NoWindow , kleidos::platform::littlefs::DriverAnswer::Failed }
What the driver's register call answered, before the heap is weighed. More about kleidos::platform::littlefs::DriverAnswer
enum class kleidos::platform::littlefs::BlankScan : uint8_t { kleidos::platform::littlefs::BlankScan::Blank , kleidos::platform::littlefs::BlankScan::HoldsData , kleidos::platform::littlefs::BlankScan::ReadFailed }
What a walk over the whole partition found. More about kleidos::platform::littlefs::BlankScan
enum class kleidos::platform::littlefs::MountOutcome : uint8_t { kleidos::platform::littlefs::MountOutcome::Mounted, kleidos::platform::littlefs::MountOutcome::FormattedBlank, kleidos::platform::littlefs::MountOutcome::OutOfMemory, kleidos::platform::littlefs::MountOutcome::Unreadable, kleidos::platform::littlefs::MountOutcome::FormatFailed, kleidos::platform::littlefs::MountOutcome::ReadPathRefused }
How a mount that may format a blank partition ended. More about kleidos::platform::littlefs::MountOutcome
enum class kleidos::platform::NvsErase : uint8_t { kleidos::platform::NvsErase::Erased , kleidos::platform::NvsErase::EraseFailed , kleidos::platform::NvsErase::NotBlank }
How nvsErasePartition ended. More about kleidos::platform::NvsErase
enum class kleidos::platform::ota::ImageState : uint8_t { kleidos::platform::ota::ImageState::New, kleidos::platform::ota::ImageState::PendingVerify, kleidos::platform::ota::ImageState::Valid, kleidos::platform::ota::ImageState::Invalid, kleidos::platform::ota::ImageState::Aborted, kleidos::platform::ota::ImageState::Undefined }
enum class kleidos::platform::ota::UpdateStage : uint8_t { kleidos::platform::ota::UpdateStage::None, kleidos::platform::ota::UpdateStage::SelectPartition, kleidos::platform::ota::UpdateStage::Begin, kleidos::platform::ota::UpdateStage::Write, kleidos::platform::ota::UpdateStage::End, kleidos::platform::ota::UpdateStage::SetBootPartition, kleidos::platform::ota::UpdateStage::Abort }
enum class kleidos::platform::sdfatfs::SpiHost : uint8_t { kleidos::platform::sdfatfs::SpiHost::Spi2 , kleidos::platform::sdfatfs::SpiHost::Spi3 }
SPI host the SD card is wired to. More about kleidos::platform::sdfatfs::SpiHost
enum class kleidos::platform::sdfatfs::MountOutcome : uint8_t { kleidos::platform::sdfatfs::MountOutcome::None , kleidos::platform::sdfatfs::MountOutcome::Mounted , kleidos::platform::sdfatfs::MountOutcome::NoFilesystem , kleidos::platform::sdfatfs::MountOutcome::NoCard }
enum class kleidos::platform::sdfatfs::CardInit : uint8_t { kleidos::platform::sdfatfs::CardInit::Initialized , kleidos::platform::sdfatfs::CardInit::NoCard , kleidos::platform::sdfatfs::CardInit::BusFailed , kleidos::platform::sdfatfs::CardInit::Mounted }
How a card-level initialization ended (initializeCard). More about kleidos::platform::sdfatfs::CardInit
enum class kleidos::platform::littlefs::VaultReadPath : uint8_t { kleidos::platform::littlefs::VaultReadPath::Plain , kleidos::platform::littlefs::VaultReadPath::LittleFsMmap , kleidos::platform::littlefs::VaultReadPath::PageCache }
How an image reads the vault partition. More about kleidos::platform::littlefs::VaultReadPath
enum class kleidos::platform::vfs::Presence : uint8_t { kleidos::platform::vfs::Presence::Present , kleidos::platform::vfs::Presence::Absent , kleidos::platform::vfs::Presence::Unknown }
Answer to "is this path there?", with the unanswerable case named. More about kleidos::platform::vfs::Presence

Functions

Filekleidos::platform::littlefs::open (const char *path, const char *mode="r")
Open a file or directory on LittleFS.
constexpr boolkleidos::platform::littlefs::mmapReadsMatchWrites (bool flashEncryptionOn, bool partitionEncrypted)
Whether a mapped read of the vault partition returns what was written.
constexpr MmapVerdictkleidos::platform::littlefs::mmapVerdict (bool flashEncryptionOn, bool partitionEncrypted, bool mapSucceeded)
The verdict on handing LittleFS the vault partition.
constexpr uint32_tkleidos::platform::littlefs::mapPagesFor (uint32_t offset, uint32_t size, uint32_t pageBytes)
MMU pages a map of size bytes at flash offset offset takes.
constexpr MountAttemptkleidos::platform::littlefs::classifyAttempt (DriverAnswer answer, bool allocationFailed)
Name one mount attempt from what the driver answered and what the heap saw.
constexpr boolkleidos::platform::littlefs::isMounted (MountOutcome outcome)
Whether the file system is mounted after outcome.
constexpr boolkleidos::platform::littlefs::needsOwner (MountOutcome outcome)
Whether outcome is one only the owner of the device can settle.
constexpr boolkleidos::platform::littlefs::judgedPartition (MountOutcome outcome)
Whether outcome is a verdict on what the partition holds.
constexpr const char *kleidos::platform::littlefs::outcomeName (MountOutcome outcome)
The token the debug console prints for outcome.
constexpr boolkleidos::platform::littlefs::allErased (const uint8_t *bytes, size_t count)
Whether bytes read as erased flash.
template<typename Reader>
BlankScankleidos::platform::littlefs::scanForBlank (Reader &reader, uint8_t *scratch, size_t scratchBytes)
Walk every sector of a partition and say whether it stores nothing.
template<typename Steps>
MountOutcomekleidos::platform::littlefs::resolveMount (Steps &steps)
Mount, and format only a partition a walk finds blank.
NvsStatskleidos::platform::nvsStats ()
Read aggregate usage statistics for the default NVS partition.
NvsErasekleidos::platform::nvsErasePartition ()
Erase the whole default NVS partition at the sector level, and prove it.
boolkleidos::platform::nvsInit ()
Initialize the default NVS partition now, and say whether it took.
uint32_tkleidos::platform::nvsForEachEntry (bool(*visit)(const char *ns, const char *key, void *context), void *context)
Visit the namespace and key name of every entry the default NVS holds.
ImageStatekleidos::platform::ota::runningPartitionState ()
Return the OTA state of the currently running partition.
size_tkleidos::platform::ota::nextUpdatePartitionSize ()
Size in bytes of the partition the next OTA image would be written to.
boolkleidos::platform::ota::markRunningAppValidCancelRollback ()
Confirm the running image as valid and cancel the rollback timer.
boolkleidos::platform::ota::markRunningAppInvalidRollbackAndReboot ()
Reject the running image and reboot into the previous one.
boolkleidos::platform::ota::runningPartitionLabel (char *output, size_t outputLength)
Copy the running partition label into output.
const char *kleidos::platform::ota::updateStageName (UpdateStage stage)
Return a human-readable name for an update stage.
Filekleidos::platform::sdfatfs::open (const char *path, const char *mode="r")
Open a file or directory on the SD card.
boolkleidos::platform::security::secureBootEnabled ()
Read-only: whether Secure Boot v2 is active on this SoC.
boolkleidos::platform::security::flashEncryptionEnabled ()
Read-only: whether Flash Encryption is active on this SoC.
boolkleidos::platform::security::hmacKeyReady (uint8_t keyIndex)
Read-only: whether key block KEY<keyIndex> holds a device-binding key.
constexpr boolkleidos::platform::littlefs::pageCacheAligned (uint32_t partitionAddress, uint32_t partitionBytes)
Whether a partition sits on whole MMU pages, the only kind the cache serves.
constexpr VaultReadPathkleidos::platform::littlefs::vaultReadPathOf (bool littlefsMmap, bool pageCache)
The read path a build's Kconfig choice names.
constexpr const char *kleidos::platform::littlefs::vaultReadPathName (VaultReadPath path)
The name the build command and the debug console give path.
constexpr boolkleidos::platform::littlefs::pageCacheServes (bool flashEncryptionOn, bool partitionEncrypted)
Whether the page cache may serve the vault's reads.
constexpr boolkleidos::platform::littlefs::pageCacheSlotsValid (uint32_t pages)
Whether a page-cache build may keep pages mapped.
Filekleidos::platform::vfs::open (const Backend &backend, const char *path, const char *mode)
Open a file or directory on the given backend.
boolkleidos::platform::vfs::exists (const Backend &backend, const char *path)
True when the path exists on the backend.
Presencekleidos::platform::vfs::presence (const Backend &backend, const char *path)
Presence of path, distinguishing "not there" from "cannot tell".
boolkleidos::platform::vfs::forEachEntry (const Backend &backend, const char *path, EntryVisitor visit, void *context)
Visit every entry of a directory by name, in ONE traversal.
boolkleidos::platform::vfs::mkdir (const Backend &backend, const char *path)
Create a directory.
boolkleidos::platform::vfs::rmdir (const Backend &backend, const char *path)
Remove an empty directory.
boolkleidos::platform::vfs::remove (const Backend &backend, const char *path)
Remove a file.
boolkleidos::platform::vfs::rename (const Backend &backend, const char *from, const char *to)
Rename or move a file or directory.

Variables

constexpr size_tkleidos::platform::littlefs::kBlankScanSectorBytes
constexpr size_tkleidos::platform::littlefs::kBlankScanSectorsPerPause
Sectors the walk reads before it lets other tasks run.
constexpr size_tkleidos::platform::ota::kPartitionLabelLength
Max partition label length incl. NUL.
constexpr uint32_tkleidos::platform::sdfatfs::kSpiSourceClockKHz
constexpr uint32_tkleidos::platform::sdfatfs::kFastestClockKHz
constexpr uint32_tkleidos::platform::littlefs::kVaultCachePageBytes
The unit the cache maps: one MMU page (CONFIG_MMU_PAGE_SIZE on both families).
constexpr uint32_tkleidos::platform::littlefs::kVaultCacheMinPages
The fewest pages a page-cache build may keep mapped.
constexpr uint32_tkleidos::platform::littlefs::kVaultCacheMaxPages

LittleFS: the partition below the file system

The factory reset's own bytes (vault/factory_reset_tag.h) and its proof that the partition holds nothing. Every call here reads or writes the flash as the SPI bus sees it, below LittleFS and below Flash Encryption, and each unmounts the file system first.

constexpr size_tkleidos::platform::littlefs::kPartitionSectorBytes
One erase unit of the vault partition: what eraseFirstSector erases.
BlankScankleidos::platform::littlefs::partitionReadsBlank ()
Walk every sector of the vault partition and say whether it holds nothing.
boolkleidos::platform::littlefs::readRaw (size_t offset, uint8_t *out, size_t bytes)
Read bytes of the vault partition raw (no decryption).
boolkleidos::platform::littlefs::writeRaw (size_t offset, const uint8_t *data, size_t bytes)
Program bytes of the vault partition raw (no encryption).
boolkleidos::platform::littlefs::eraseFirstSector ()
Erase the first sector (kPartitionSectorBytes) of the vault partition.

LittleFS: lifecycle

boolkleidos::platform::littlefs::begin ()
Mount LittleFS as it is found. Never writes to the flash.
MountOutcomekleidos::platform::littlefs::beginOrFormatBlank ()
Mount LittleFS, and format it only when the partition holds nothing.
BlankWalkRecordkleidos::platform::littlefs::lastBlankWalk ()
The last walk beginOrFormatBlank ran over the vault partition.
voidkleidos::platform::littlefs::end ()
Unmount LittleFS.
boolkleidos::platform::littlefs::mounted ()
True when LittleFS is currently mounted.
boolkleidos::platform::littlefs::mountAdmitted ()
Whether this image's read path would refuse the vault partition.
boolkleidos::platform::littlefs::format ()
Format the LittleFS partition, whatever it holds.
boolkleidos::platform::littlefs::eraseAll ()
Physically erase the ENTIRE LittleFS/vault partition.

LittleFS: properties

boolkleidos::platform::littlefs::partitionEncrypted ()
True when the vault partition is stored under Flash Encryption.
MapWindowkleidos::platform::littlefs::mapWindow ()
Read the data window and the vault's place in it, as they are now.

LittleFS: directory and path operations

boolkleidos::platform::littlefs::exists (const char *path)
True when the path exists on LittleFS.
vfs::Presencekleidos::platform::littlefs::presence (const char *path)
Presence of path on LittleFS, with "cannot tell" named.
boolkleidos::platform::littlefs::forEachEntry (const char *path, vfs::EntryVisitor visit, void *context)
Visit every entry of a LittleFS directory by name, in ONE traversal.
boolkleidos::platform::littlefs::mkdir (const char *path)
Create a directory.
boolkleidos::platform::littlefs::rmdir (const char *path)
Remove an empty directory.
boolkleidos::platform::littlefs::remove (const char *path)
Remove a file.
boolkleidos::platform::littlefs::rename (const char *from, const char *to)
Rename or move a file or directory.

LittleFS: capacity

size_tkleidos::platform::littlefs::usedBytes ()
Return bytes currently used on LittleFS.
size_tkleidos::platform::littlefs::totalBytes ()
Return total LittleFS partition capacity in bytes.
boolkleidos::platform::littlefs::info (size_t &total, size_t &used)
Read the capacity and the used-byte total in ONE traversal.

SD card: lifecycle

boolkleidos::platform::sdfatfs::begin (const Config &config)
Mount the SD card. Never formats it.
voidkleidos::platform::sdfatfs::end ()
Unmount the SD card.
CardInitkleidos::platform::sdfatfs::initializeCard (const Config &config)
Initialize the card in the slot and let it go, with no filesystem.
MountOutcomekleidos::platform::sdfatfs::lastMountOutcome ()
How the last begin that tried a mount ended.
const char *kleidos::platform::sdfatfs::mountOutcomeName (MountOutcome outcome)
Console token of a mount outcome.
boolkleidos::platform::sdfatfs::mounted ()
True when an SD card is currently mounted.
boolkleidos::platform::sdfatfs::format ()
Format the mounted SD card.

SD card: directory and path operations

boolkleidos::platform::sdfatfs::exists (const char *path)
True when the path exists on the SD card.
vfs::Presencekleidos::platform::sdfatfs::presence (const char *path)
Presence of path on the SD card, with "cannot tell" named.
boolkleidos::platform::sdfatfs::mkdir (const char *path)
Create a directory.
boolkleidos::platform::sdfatfs::rmdir (const char *path)
Remove an empty directory.
boolkleidos::platform::sdfatfs::remove (const char *path)
Remove a file.
boolkleidos::platform::sdfatfs::rename (const char *from, const char *to)
Rename or move a file or directory.

SD card: capacity and info

uint64_tkleidos::platform::sdfatfs::usedBytes ()
Return bytes currently used on the SD card.
uint64_tkleidos::platform::sdfatfs::totalBytes ()
Return the total SD card capacity in bytes.
boolkleidos::platform::sdfatfs::volumeInfo (VolumeInfo &out)
Read the mounted volume's FAT geometry and allocation state.
uint32_tkleidos::platform::sdfatfs::actualClockKHz ()
The SPI clock the host actually settled on for the card, in kHz.
uint32_tkleidos::platform::sdfatfs::cardMaxClockKHz ()
The fastest SPI clock the mounted card agreed to, in kHz.
const char *kleidos::platform::sdfatfs::cardType ()
Return a human-readable card type string.

Back to the top

Typedef Documentation

EntryVisitor #

using kleidos::platform::vfs::EntryVisitor

Visitor invoked once per directory entry.

Parameters
NameDirectionMeaning
nameinEntry basename; valid only for the duration of the call.
contextinOpaque pointer handed through from forEachEntry.
Return values
ValueMeaning
trueContinue the traversal.
falseStop the traversal here.

File [1/2] #

using kleidos::platform::littlefs::File

RAII handle to an open file or directory on LittleFS. LittleFS and SD-FATFS share the POSIX-over-VFS handle in vfs::File.

File [2/2] #

using kleidos::platform::sdfatfs::File

RAII handle to an open file or directory on the SD card. LittleFS and SD-FATFS share the POSIX-over-VFS handle in vfs::File.

Back to the top

Enumeration Type Documentation

BlankScan #

enum class kleidos::platform::littlefs::BlankScan : uint8_t

What a walk over the whole partition found.

Enumerator
Blank 

Every sector reads erased in one view or the other.

HoldsData 

A sector reads erased in neither view.

ReadFailed 

A read failed, or there was nothing to read with or from.

CardInit #

enum class kleidos::platform::sdfatfs::CardInit : uint8_t

How a card-level initialization ended (initializeCard).

Enumerator
Initialized 

A card identified and initialized, then let go: deselected, its supply on, nothing mounted.

NoCard 

No card completed its initialization: an empty slot, or a card that did not answer.

BusFailed 

The bus or the card's SPI device could not be set up, or a pin is missing: nothing was sent to the slot.

Mounted 

A card is mounted already, so it is initialized; nothing was sent.

DriverAnswer #

enum class kleidos::platform::littlefs::DriverAnswer : uint8_t

What the driver's register call answered, before the heap is weighed.

Enumerator
Mounted 

It mounted.

NoMemory 

No memory for its own context.

NoWindow 

It failed, and the flash data window cannot map the vault now: on a build whose driver maps the whole vault at mount, its map is what failed (the caller asks the window again once the attempt ended).

Failed 

Any other error, every error of lfs_mount among them.

ImageState #

enum class kleidos::platform::ota::ImageState : uint8_t

Validity state of an OTA image.

Value Meaning
New Freshly written, not yet booted.
PendingVerify Booted, awaiting rollback confirmation.
Valid Confirmed valid (rollback cancelled).
Invalid Marked invalid (will not boot again).
Aborted Update was aborted.
Undefined State could not be determined.
Enumerator
New 

Freshly written, not yet booted.

PendingVerify 

Booted, awaiting rollback confirmation.

Valid 

Confirmed valid.

Invalid 

Marked invalid (will not boot again).

Aborted 

Update was aborted.

Undefined 

State could not be determined.

MmapVerdict #

enum class kleidos::platform::littlefs::MmapVerdict : uint8_t

Whether LittleFS may be handed the vault partition on a build that maps it.

Enumerator
Admitted 

The map reads what was written, and it fits.

PlaintextUnderFlashEncryption 

Refused: Flash Encryption on, row not flagged.

MapFailed 

Refused: the data window could not map the vault.

MountAttempt #

enum class kleidos::platform::littlefs::MountAttempt : uint8_t

How one mount attempt ended, with nothing formatted.

Enumerator
Mounted 

The file system is mounted.

OutOfMemory 

No memory: the driver said so, an allocation failed meanwhile, or the data window had no room for the driver's map of the vault.

Refused 

An error, while no allocation failed (classifyAttempt).

MountOutcome [1/2] #

enum class kleidos::platform::littlefs::MountOutcome : uint8_t

How a mount that may format a blank partition ended.

Enumerator
Mounted 

Mounted as it was found. No flash was written.

FormattedBlank 

Every sector was blank, so it was formatted and mounted.

OutOfMemory 

No memory for the mount's buffers, or no room in the data window for its map of the vault. No flash was written.

Unreadable 

It would not mount with memory to spare, and it holds data or could not be read. No flash was written.

FormatFailed 

It was blank, and the format or the mount after it failed.

ReadPathRefused 

This image's read path refused the partition before anything read it (little_fs_mmap_guard.h). No flash was read or written.

MountOutcome [2/2] #

enum class kleidos::platform::sdfatfs::MountOutcome : uint8_t

How the last mount attempt ended.

A slot with no card and a seated card whose volume FatFs cannot mount (an exFAT card, which this build's FatFs does not read, or a card with no filesystem at all) both fail begin; only the second identified a card.

Enumerator
None 

No mount attempted since boot.

Mounted 

The card identified and its FAT volume mounted.

NoFilesystem 

The card identified and its volume did not mount.

NoCard 

No card identified: an empty slot, a card that did not answer, or a bus that could not be set up.

NvsErase #

enum class kleidos::platform::NvsErase : uint8_t

How nvsErasePartition ended.

Enumerator
Erased 

Every sector was erased and reads back 0xFF.

EraseFailed 

The erase was refused, or the partition is missing.

NotBlank 

The erase reported success, but a byte reads other than 0xFF, or the read-back failed.

Presence #

enum class kleidos::platform::vfs::Presence : uint8_t

Answer to "is this path there?", with the unanswerable case named.

Enumerator
Present 

stat succeeded: the path is on the backend.

Absent 

stat reported ENOENT: the path is genuinely not there.

Unknown 

The lookup failed (unmounted, path overflow, any other errno).

SpiHost #

enum class kleidos::platform::sdfatfs::SpiHost : uint8_t

SPI host the SD card is wired to.

Enumerator
Spi2 

SPI2 host.

Spi3 

SPI3 host.

UpdateStage #

enum class kleidos::platform::ota::UpdateStage : uint8_t

Stage reached by an update session (for diagnostics).

Value Meaning
None Not started (or last operation succeeded).
SelectPartition Selecting the next update partition.
Begin Beginning the write.
Write Streaming image data.
End Finalizing the image (esp_ota_end).
SetBootPartition Setting the boot partition.
Abort Aborting and discarding the partial image.
Enumerator
None 

Not started.

SelectPartition 

Selecting the target partition.

Begin 

Beginning the write.

Write 

Streaming image data.

End 

Finalizing the image.

SetBootPartition 

Setting the boot partition.

Abort 

Aborting.

VaultReadPath #

enum class kleidos::platform::littlefs::VaultReadPath : uint8_t

How an image reads the vault partition.

Enumerator
Plain 

One esp_partition_read per LittleFS read.

LittleFsMmap 

The component maps the whole vault at mount.

PageCache 

A bounded set of mapped pages, least recently used out first.

Back to the top

Function Documentation

actualClockKHz() #

uint32_t kleidos::platform::sdfatfs::actualClockKHz()

The SPI clock the host actually settled on for the card, in kHz.

A request is only a request: the peripheral divides a fixed source clock and takes the divisor nearest the clock the mount runs at (on the ESP32-S3, the 80 MHz APB clock over 2, 3, 4 and so on), and the mount runs at most at what the card agreed to (cardMaxClockKHz). Reading the negotiated value back is what separates "this board is as fast as it gets" from "the request was rounded away".

Returns
Working clock in kHz, or 0 when no card is mounted.

allErased() #

bool kleidos::platform::littlefs::allErased(const uint8_t * bytes, size_t count)
constexpr

Whether bytes read as erased flash.

Parameters
NameDirectionMeaning
bytesinBytes read.
countinHow many.
Returns
True when every byte is 0xFF.

begin() [1/2] #

bool kleidos::platform::littlefs::begin()

Mount LittleFS as it is found. Never writes to the flash.

Return values
ValueMeaning
trueFilesystem was successfully mounted.
falseMount failed (see KLEIDOS_LOG output for the esp_err code).

begin() [2/2] #

bool kleidos::platform::sdfatfs::begin(const Config & config)

Mount the SD card. Never formats it.

A card whose volume does not mount is reported (MountOutcome::NoFilesystem) and left as it is, whatever it holds. Only format writes a new volume, on the path a person asked for.

A chip-select a sleep latched (gpio::holdEnable) is released first: a latched pad ignores the driver, and the card would never be selected.

Parameters
NameMeaning
configSPI pins, host, clock, and mount options.
Return values
ValueMeaning
trueCard was successfully mounted.
falseMount failed (no card, bad filesystem, or driver error).

beginOrFormatBlank() #

MountOutcome kleidos::platform::littlefs::beginOrFormatBlank()

Mount LittleFS, and format it only when the partition holds nothing.

The one path a mount can format through. A mount error says nothing about what the flash holds, so whatever it was, the format runs only after every sector of the partition has read blank, on an unflagged and a flagged partition alike (little_fs_mount_logic.h). Every other outcome leaves the flash as it was.

It reads the whole partition when the partition is blank, which is seconds on the larger tables, so it belongs on a task that may wait (the vault worker). A partition with anything in it is told apart in a read or two.

Returns
How the mount ended.
See also
isMounted, needsOwner

cardMaxClockKHz() #

uint32_t kleidos::platform::sdfatfs::cardMaxClockKHz()

The fastest SPI clock the mounted card agreed to, in kHz.

A request at or below the default speed (20 MHz) is taken as it is. A faster one first asks the card to switch to high speed (CMD6), and a card that reports no support for the switch keeps its 20 MHz default while the mount still succeeds. So this below the request is the card refusing high speed, and actualClockKHz below this is the divider's rounding.

Returns
The card's ceiling in kHz, or 0 when no card is mounted.

cardType() #

const char * kleidos::platform::sdfatfs::cardType()

Return a human-readable card type string.

Returns
Static string such as "SDHC" or "Unknown".

classifyAttempt() #

MountAttempt kleidos::platform::littlefs::classifyAttempt(DriverAnswer answer, bool allocationFailed)
constexpr

Name one mount attempt from what the driver answered and what the heap saw.

lfs_mount reports a cache it could not allocate as it reports a damaged directory, and the driver passes both on as one error. An allocation that failed anywhere while the attempt ran is therefore taken as its cause. Running out of memory is never read as damage, at the price of deferring a refusal that met another task's failed allocation in the same window: out of memory leads to no walk, no format and no prompt, only to a later attempt. A data window with no room for the vault's map is a shortage of the same kind (DriverAnswer::NoWindow): the admission found room a moment before, so another map holds it now, and the partition was never judged.

Parameters
NameDirectionMeaning
answerinWhat the driver answered.
allocationFailedinWhether the heap reported a failed allocation while the attempt ran.
Returns
How the attempt ended.

eraseAll() #

bool kleidos::platform::littlefs::eraseAll()

Physically erase the ENTIRE LittleFS/vault partition.

Unlike format() — which only rewrites the LittleFS superblock pair and leaves every other (including freed) data block untouched — this performs a raw esp_partition_erase_range() across the whole partition, returning every byte to the flash-erased state. It is the authoritative physical destruction used by the panic / brute-force vault wipe.

Why it is required: LittleFS is copy-on-write. Unlinking or overwriting a file writes to NEW blocks and merely drops the old blocks from the allocator ("block deallocation is a noop"); the original bytes — including the KDF salt and the secret's verifier in meta.bin — survive in freed-but-not-erased blocks. On an open build, a release build included, a raw flash dump holds them and could resume an offline brute force of the secret from that salt. On a hardened build, whose table flags this partition for Flash Encryption, the dump holds them as ciphertext under the chip's key, and the device binding stands under that. Erasing the whole partition removes every block unconditionally, closing that gap on all builds.

Lifecycle: unmounts the partition first (via end()) and leaves it BLANK and unmounted. The caller MUST re-mount (beginOrFormatBlank formats a fresh empty FS over it) or reboot before using the filesystem again — do not operate on the partition while it is in this state.

Return values
ValueMeaning
trueThe partition was found and fully erased.
falseThe partition was not found or the erase failed (see the KLEIDOS_LOG output for the esp_err code).
Warning
Destroys ALL data on the vault partition irrecoverably. On the native host build there is no flash to erase, so this is a no-op seam (returns true); unit tests observe the invocation through the fake facade rather than by inspecting bytes.
See also
format, beginOrFormatBlank, end

eraseFirstSector() #

bool kleidos::platform::littlefs::eraseFirstSector()

Erase the first sector (kPartitionSectorBytes) of the vault partition.

Return values
ValueMeaning
trueThe erase completed.
falseThe partition is missing or the erase failed.

exists() [1/3] #

bool kleidos::platform::littlefs::exists(const char * path)

True when the path exists on LittleFS.

Two-valued: "not there" and "I could not tell" are both false. Any caller whose false branch destroys, overwrites or abandons data must ask presence instead.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
truepath refers to an existing file or directory.
falsepath does not exist, the partition is not mounted, or the lookup failed.
See also
presence

exists() [2/3] #

bool kleidos::platform::sdfatfs::exists(const char * path)

True when the path exists on the SD card.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
truepath refers to an existing file or directory.
falsepath does not exist on the card — OR the lookup itself failed. Use presence when the false branch destroys or replaces something.
See also
presence

exists() [3/3] #

bool kleidos::platform::vfs::exists(const Backend & backend, const char * path)

True when the path exists on the backend.

Two-valued, so it folds "I could not tell" into false. Use presence wherever the false branch destroys, overwrites or abandons data: a caller that unlinks a file's only surviving twin on a false answer must know whether that answer was stat reporting ENOENT or the lookup failing.

Parameters
NameMeaning
backendBackend descriptor.
pathNUL-terminated path string.
Return values
ValueMeaning
truepath refers to an existing file or directory.
falsepath does not exist, the backend is not mounted, or the lookup itself failed.
See also
presence

flashEncryptionEnabled() #

bool kleidos::platform::security::flashEncryptionEnabled()

Read-only: whether Flash Encryption is active on this SoC.

A pure eFuse query with no side effects. Reads 0 (false) on open builds.

Return values
ValueMeaning
trueFlash Encryption is enabled (eFuse burned).
falseFlash Encryption is disabled, or the native build.

forEachEntry() [1/2] #

bool kleidos::platform::littlefs::forEachEntry(const char * path, vfs::EntryVisitor visit, void * context)

Visit every entry of a LittleFS directory by name, in ONE traversal.

Use this instead of a loop of exists whenever the question is "which of these files are there": each exists resolves the directory again, and on LittleFS resolving a name walks the directory's metadata pairs, so N probes cost N walks where this costs one.

Parameters
NameDirectionMeaning
pathinNUL-terminated directory path.
visitinCallback invoked per entry; "." and ".." are skipped.
contextinOpaque pointer handed to visit.
Return values
ValueMeaning
trueThe directory was opened, traversed and closed; what visit saw is a COMPLETE listing.
falseThe listing is incomplete or never started; the caller must not conclude that an unseen file is absent.
See also
exists, kleidos::platform::vfs::forEachEntry

forEachEntry() [2/2] #

bool kleidos::platform::vfs::forEachEntry(const Backend & backend, const char * path, EntryVisitor visit, void * context)

Visit every entry of a directory by name, in ONE traversal.

The counterpart of exists for the question "which of these files are there": asking exists once per candidate resolves the directory once per candidate, and on a log-structured filesystem resolving a name walks the directory's metadata pairs. This walks them once and reports what it finds.

Names only — no stat, no open per entry — so the caller pays one traversal and nothing per candidate it was going to reject anyway. The directory is not to be mutated from inside visit.

Parameters
NameDirectionMeaning
backendinBackend descriptor.
pathinNUL-terminated directory path.
visitinCallback invoked per entry; "." and ".." are skipped.
contextinOpaque pointer handed to visit. A traversal that stops early because visit returned false is still a complete answer — the caller asked for the stop — and reports true.
Return values
ValueMeaning
trueThe directory was opened, traversed to its end (or to a stop visit asked for) and closed: what visit saw IS the listing.
falseThe backend is unmounted, path is not an openable directory, a read failed part-way through, or the close failed — the caller cannot treat what it saw as a complete listing. A caller whose false branch allocates, overwrites or destroys must not act on the entries it did see.
See also
exists

format() [1/2] #

bool kleidos::platform::littlefs::format()

Format the LittleFS partition, whatever it holds.

For a path a person asked for. A mount that failed does not reach this; it goes through beginOrFormatBlank.

Note
This rewrites only the LittleFS superblock pair (blocks 0-1); it does NOT erase the rest of the partition. Previously-written data blocks (including freed ones) survive a format untouched. For an authoritative physical wipe of every byte use eraseAll().
Return values
ValueMeaning
trueFormat completed successfully.
falseFormat operation failed.

format() [2/2] #

bool kleidos::platform::sdfatfs::format()

Format the mounted SD card.

Return values
ValueMeaning
trueFormat completed successfully.
falseFormat operation failed.

hmacKeyReady() #

bool kleidos::platform::security::hmacKeyReady(uint8_t keyIndex)

Read-only: whether key block KEY<keyIndex> holds a device-binding key.

True only when the block's purpose is HMAC_UP AND it is read-protected, which is what a host-side burn with espefuse burn-key ... HMAC_UP leaves. A key with the purpose but without the read protection works and is not ready: software could read it back, so a vault bound to it would be bound to a secret the chip does not keep.

Reports the eFuses as they are; it never burns one. A pure eFuse query with no side effects.

Parameters
NameDirectionMeaning
keyIndexinKey block index, 0 for BLOCK_KEY0.
Return values
ValueMeaning
trueKEY<keyIndex> is a read-protected HMAC_UP key.
falseAny other purpose or protection, an index past the last key block, a chip without key purposes or an HMAC peripheral (classic ESP32), or the native build.

info() #

bool kleidos::platform::littlefs::info(size_t & total, size_t & used)

Read the capacity and the used-byte total in ONE traversal.

usedBytes and totalBytes each ask the filesystem separately, and the used figure is counted by a full walk, so a caller that wants both pays that walk twice for one line of output. This pays it once.

Parameters
NameDirectionMeaning
totaloutPartition capacity in bytes.
usedoutBytes currently occupied.
Return values
ValueMeaning
trueBoth figures were read.
falseThe filesystem is not mounted or could not be queried; total and used are set to 0.

initializeCard() #

CardInit kleidos::platform::sdfatfs::initializeCard(const Config & config)

Initialize the card in the slot and let it go, with no filesystem.

Sends the card the commands a mount begins with and nothing after them: the reset (CMD0), the interface check (CMD8), the operating-condition handshake (ACMD41), the register reads (CID, CSD, SCR, SD status) and the clock switch, exactly as sdmmc_card_init sends them inside begin. No sector is read, no volume is mounted and nothing is written, so nothing on the card can change. The card's SPI device is then removed and its chip-select driven high: the card is left initialized and deselected, its supply on, as end leaves a card it unmounts.

Bus handling is begin's: a bus another device set up (the panel's) is joined and left in place, so the card's commands interleave with that device's through the SPI bus lock; a bus nobody set up is set up for the call and freed again. A chip-select a sleep latched is released first.

It blocks the calling task for the whole exchange, so call it from a task that may wait (the HAL runs it on Core 0). With a card that answers, that is the card's own initialization, mostly its ACMD41 handshake. With the slot empty, ESP-IDF's init gives up early (6.0.3, the same in 6.1.1). When MISO idles high it fails at the second CMD0, which finds no R1 byte in the eight it reads: the CMD52 the SDIO-enabled init sends first, the two CMD0s and the 20 ms SDMMC_GO_IDLE_DELAY_MS between them come to about 21 ms (the LILYGO T-Deck's empty slot measured about 25 ms, ESP_ERR_TIMEOUT). When MISO idles low the reply reads as a zero R1 and it fails at CMD8, whose echo is wrong: each of those four commands first polls MISO for up to the default 40 ms (wait_for_miso) with the bus held, which with the two 20 ms delays is at most about 200 ms. Each command takes the bus for its own exchange only: under a millisecond at the 400 kHz probing clock, up to about 41 ms with that MISO poll.

Not safe beside begin, end or another call on another task: the caller serializes them (the HAL's boot settle does).

Parameters
NameMeaning
configSPI pins, host and clock; the mount options are not read.
Returns
How it ended; CardInit::Mounted when a card is mounted already.

isMounted() #

bool kleidos::platform::littlefs::isMounted(MountOutcome outcome)
constexpr

Whether the file system is mounted after outcome.

Parameters
NameDirectionMeaning
outcomeinHow the mount ended.
Returns
True when it may be used.

judgedPartition() #

bool kleidos::platform::littlefs::judgedPartition(MountOutcome outcome)
constexpr

Whether outcome is a verdict on what the partition holds.

Running short of memory, for the mount's buffers or for the data window's pages, and a read path that refuses the partition both end before any walk, so neither says anything about the flash: a caller keeps what the last mount that judged the partition found.

Parameters
NameDirectionMeaning
outcomeinHow the mount ended.
Returns
False for OutOfMemory and ReadPathRefused, true for every other.

lastBlankWalk() #

BlankWalkRecord kleidos::platform::littlefs::lastBlankWalk()

The last walk beginOrFormatBlank ran over the vault partition.

A walk runs only after a refused mount, so a mount that works leaves this as it was. For diagnostics (the debug console): nothing decides on it. A board whose boot log is lost with the reset that printed it still reports what its boot's walk cost, and how far into a damaged partition it read before stopping.

Returns
A copy of the record.

lastMountOutcome() #

MountOutcome kleidos::platform::sdfatfs::lastMountOutcome()

How the last begin that tried a mount ended.

A begin on a card already mounted tries nothing and leaves it as it was. end leaves it too: it says how the card was last brought up.

Returns
The outcome, MountOutcome::None before the first attempt.

mapPagesFor() #

uint32_t kleidos::platform::littlefs::mapPagesFor(uint32_t offset, uint32_t size, uint32_t pageBytes)
nodiscardconstexpr

MMU pages a map of size bytes at flash offset offset takes.

esp_partition_mmap maps from the page that holds the first byte (esp_partition/partition_target.c), and the MMU maps whole pages (esp_mm/esp_mmu_map.c), so a span that starts inside a page takes one more than its size alone.

Parameters
NameMeaning
offsetFlash offset of the first byte.
sizeBytes to map.
pageBytesMMU page size (CONFIG_MMU_PAGE_SIZE, 64 KiB on both families).
Returns
Pages spanned; 0 for an empty span or a zero page size.

mapWindow() #

MapWindow kleidos::platform::littlefs::mapWindow()

Read the data window and the vault's place in it, as they are now.

Mounts nothing and maps nothing: mapped is true while the vault's first and last bytes are mapped (the whole vault, on a mounted littlefs_mmap build; the two end pages, when a page cache happens to hold both), and freePages counts the window with whatever is mapped at the moment. The cache fields describe a page_cache build and stay zero on the other paths; its counters are counted by a debug build only.

Returns
The reading; path is always the build's, and every other field zero and false on the native host build or when the partition is missing.

markRunningAppInvalidRollbackAndReboot() #

bool kleidos::platform::ota::markRunningAppInvalidRollbackAndReboot()

Reject the running image and reboot into the previous one.

For an image still pending verification that must not be confirmed: the bootloader marks it invalid and the restart boots the image it replaced.

Returns
Only on failure (no image pending verification, or no other valid image to return to): false. On success the chip restarts and the call never returns.

markRunningAppValidCancelRollback() #

bool kleidos::platform::ota::markRunningAppValidCancelRollback()

Confirm the running image as valid and cancel the rollback timer.

Return values
ValueMeaning
trueImage confirmed; bootloader will not roll back.
falseConfirmation failed (e.g. no pending-verify image).

mkdir() [1/3] #

bool kleidos::platform::littlefs::mkdir(const char * path)

Create a directory.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
trueDirectory created successfully.
falseCreation failed (already exists, missing parent, or driver error).

mkdir() [2/3] #

bool kleidos::platform::sdfatfs::mkdir(const char * path)

Create a directory.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
trueDirectory created successfully.
falseCreation failed (already exists, missing parent, or driver error).

mkdir() [3/3] #

bool kleidos::platform::vfs::mkdir(const Backend & backend, const char * path)

Create a directory.

Parameters
NameMeaning
backendBackend descriptor.
pathNUL-terminated path string.
Return values
ValueMeaning
trueDirectory created (or already present as a directory).
falseCreation failed (missing parent, name collision, or driver error).

mmapReadsMatchWrites() #

bool kleidos::platform::littlefs::mmapReadsMatchWrites(bool flashEncryptionOn, bool partitionEncrypted)
nodiscardconstexpr

Whether a mapped read of the vault partition returns what was written.

Parameters
NameMeaning
flashEncryptionOnThe chip's Flash Encryption is enabled (eFuse).
partitionEncryptedESP-IDF treats the vault partition as encrypted: its table row is flagged and Flash Encryption is on (esp_partition_t::encrypted).
Return values
ValueMeaning
trueReads through the map match writes: either nothing is encrypted, or both the writes and the map go through Flash Encryption.
falseFlash Encryption is on and the partition is not flagged: the writes are plaintext and the map decrypts them.

mmapVerdict() #

MmapVerdict kleidos::platform::littlefs::mmapVerdict(bool flashEncryptionOn, bool partitionEncrypted, bool mapSucceeded)
nodiscardconstexpr

The verdict on handing LittleFS the vault partition.

The encryption rule is decided first: a partition it refuses is never mapped, so mapSucceeded is not consulted for it.

Parameters
NameMeaning
flashEncryptionOnThe chip's Flash Encryption is enabled (eFuse).
partitionEncryptedesp_partition_t::encrypted of the vault partition.
mapSucceededThe facade's own map of the whole partition, made and released before the mount, succeeded.
Returns
MmapVerdict::Admitted only when both decisions allow it.

mountAdmitted() #

bool kleidos::platform::littlefs::mountAdmitted()

Whether this image's read path would refuse the vault partition.

Asks the read path's own question before a mount, without mounting. On a build that maps the whole vault at mount (CONFIG_LITTLEFS_MMAP_PARTITION) that is the Flash Encryption rule and a map of the partition made and released at once (little_fs_mmap_guard.h); on any other build nothing refuses the partition. The OTA confirmation asks it before it marks a fresh image valid, so an image whose read path refuses the vault is rolled back while the bootloader still can.

It catches that refusal and nothing else. Nothing is mounted, so a mount that would fail for another reason (a LittleFS geometry or on-disk version the image does not share with the partition) is admitted here.

Return values
ValueMeaning
trueThe read path would not refuse the vault, or it is mounted already. Always true on the plain and page-cache paths and on the native host build. Not a promise that a mount succeeds.
falseThe read path would refuse the vault partition.
See also
kleidos::ota::confirmPendingImage

mounted() [1/2] #

bool kleidos::platform::littlefs::mounted()

True when LittleFS is currently mounted.

Return values
ValueMeaning
trueMounted (a successful begin() or LittleFsGuard construction).
falseNot currently mounted.

mounted() [2/2] #

bool kleidos::platform::sdfatfs::mounted()

True when an SD card is currently mounted.

Return values
ValueMeaning
trueMounted (a successful begin() is in effect).
falseNot currently mounted.

mountOutcomeName() #

const char * kleidos::platform::sdfatfs::mountOutcomeName(MountOutcome outcome)

Console token of a mount outcome.

Parameters
NameMeaning
outcomeThe outcome.
Returns
none, ok, nofs or nocard; na for a value outside the enumeration.

needsOwner() #

bool kleidos::platform::littlefs::needsOwner(MountOutcome outcome)
constexpr

Whether outcome is one only the owner of the device can settle.

Running short of memory is not among them: the flash was never looked at, and a later mount can succeed. Nor is a read path that refuses the partition: the flash was never looked at either, a wipe would not bring the partition within this image's reach, and an image that reads it another way finds it as it was.

Parameters
NameDirectionMeaning
outcomeinHow the mount ended.
Returns
True for a refusal that will outlast a retry.

nextUpdatePartitionSize() #

size_t kleidos::platform::ota::nextUpdatePartitionSize()

Size in bytes of the partition the next OTA image would be written to.

Returns the size of the partition esp_ota_get_next_update_partition() selects, so a caller can reject an oversized image before opening a write session (which first erases the inactive slot).

Return values
ValueMeaning
>0Size in bytes of the next update partition.
0No OTA partition is available (e.g. host/native builds).

nvsErasePartition() #

NvsErase kleidos::platform::nvsErasePartition()

Erase the whole default NVS partition at the sector level, and prove it.

nvs_erase_key and nvs_erase_all only mark entries erased; their bytes stay on the flash until NVS recycles the page. This erases every sector of the partition (nvs_flash_erase_partition, which closes NVS first if it was open), then reads the whole partition back raw and requires every byte to be 0xFF. NVS is left uninitialized: the next NvsStore::open, or nvsInit, formats a fresh one. The NVS key partition of an encrypted NVS is not touched.

Meant for the one moment no other task holds NVS: the top of setup(), before any reader has opened it (reset/factory_reset_finish.h).

Returns
How the erase ended.

nvsForEachEntry() #

uint32_t kleidos::platform::nvsForEachEntry(bool(* visit )(const char *ns, const char *key, void *context), void * context)

Visit the namespace and key name of every entry the default NVS holds.

Names only, never values, for the debug console's listing of what survived a factory reset.

Parameters
NameDirectionMeaning
visitinCalled once per entry with its namespace and key; returning false stops the walk.
contextinHanded to visit.
Returns
How many entries were visited; 0 when NVS is not initialized, holds nothing, or on the native build.

nvsInit() #

bool kleidos::platform::nvsInit()

Initialize the default NVS partition now, and say whether it took.

Every NvsStore::open initializes NVS on first use; this is the same step, called on its own so a caller can tell a fresh NVS that will not come up from a key that is merely absent.

Return values
ValueMeaning
trueNVS is initialized.
falsenvs_flash_init failed (logged).

nvsStats() #

NvsStats kleidos::platform::nvsStats()

Read aggregate usage statistics for the default NVS partition.

A cheap read-only query over nvs_get_stats(NULL, ...). Requires NVS to be initialized; if it is not, NvsStats::ok reads false and the counts are 0.

Returns
A populated NvsStats on device; a zeroed value on native.

open() [1/3] #

File kleidos::platform::littlefs::open(const char * path, const char * mode = "r")

Open a file or directory on LittleFS.

Parameters
NameMeaning
pathNUL-terminated path string.
modefopen-style mode string ("r", "w", "a", etc.).
Returns
RAII File handle; check valid() before use.

open() [2/3] #

File kleidos::platform::sdfatfs::open(const char * path, const char * mode = "r")

Open a file or directory on the SD card.

Parameters
NameMeaning
pathNUL-terminated path string.
modefopen-style mode string ("r", "w", "a", etc.).
Returns
RAII File handle; check valid() before use.

open() [3/3] #

File kleidos::platform::vfs::open(const Backend & backend, const char * path, const char * mode)

Open a file or directory on the given backend.

Parameters
NameMeaning
backendBackend descriptor (base path + mount predicate).
pathNUL-terminated path string.
modefopen-style mode string ("r", "w", "a", etc.).
Returns
RAII File handle; check valid() before use.

outcomeName() #

const char * kleidos::platform::littlefs::outcomeName(MountOutcome outcome)
constexpr

The token the debug console prints for outcome.

Parameters
NameDirectionMeaning
outcomeinHow the mount ended.
Returns
A static string with no spaces.

pageCacheAligned() #

bool kleidos::platform::littlefs::pageCacheAligned(uint32_t partitionAddress, uint32_t partitionBytes)
nodiscardconstexpr

Whether a partition sits on whole MMU pages, the only kind the cache serves.

Parameters
NameMeaning
partitionAddressThe partition's flash address (esp_partition_t::address).
partitionBytesIts size (esp_partition_t::size).
Return values
ValueMeaning
trueBoth are multiples of kVaultCachePageBytes, and it is not empty: each cached page is one MMU page, mapped once.
falseOtherwise: every read of it takes the plain path.

pageCacheServes() #

bool kleidos::platform::littlefs::pageCacheServes(bool flashEncryptionOn, bool partitionEncrypted)
nodiscardconstexpr

Whether the page cache may serve the vault's reads.

A read through a mapping is decrypted whenever the chip's Flash Encryption is on, so the cache serves only where the writes went through it too, or nothing is encrypted (mmapReadsMatchWrites). Where it may not, every read falls through to the plain path, which reads an unflagged row as written: unlike the whole-vault map, the page cache never refuses a mount.

Parameters
NameMeaning
flashEncryptionOnThe chip's Flash Encryption is enabled (eFuse).
partitionEncryptedesp_partition_t::encrypted of the vault partition.
Return values
ValueMeaning
trueMapped pages read what was written.
falseFlash Encryption is on over an unflagged row: read the plain way.

pageCacheSlotsValid() #

bool kleidos::platform::littlefs::pageCacheSlotsValid(uint32_t pages)
nodiscardconstexpr

Whether a page-cache build may keep pages mapped.

Parameters
NameMeaning
pagesCONFIG_KLEIDOS_VAULT_PAGE_CACHE_PAGES.
Return values
ValueMeaning
truekVaultCacheMinPages to kVaultCacheMaxPages.
falseOutside that range.

partitionEncrypted() #

bool kleidos::platform::littlefs::partitionEncrypted()

True when the vault partition is stored under Flash Encryption.

Reads the encrypted field ESP-IDF resolved for the partition at boot. It is set only when the partition table flags the row encrypted (the secure tables do, held there by a check of the build) and the chip's Flash Encryption is on (esp_partition/partition.c, is_partition_encrypted). Every LittleFS read and write of the vault then goes through the chip's Flash Encryption, so what the flash holds is ciphertext under the chip's own key, beneath the records' own envelopes, and raw 0xFF wherever nothing has been programmed since the last erase.

Return values
ValueMeaning
trueThe vault partition is flash-encrypted.
falseIt is stored as written: an open build, a chip whose Flash Encryption is off, a table that leaves the row unflagged, a missing partition, or the native host build.
See also
kleidos::platform::security::flashEncryptionEnabled

partitionReadsBlank() #

BlankScan kleidos::platform::littlefs::partitionReadsBlank()

Walk every sector of the vault partition and say whether it holds nothing.

The walk beginOrFormatBlank runs before it may format (both views of a partition flagged encrypted, little_fs_mount_logic.h), without the format: a partition found blank is left blank. It reads the whole partition when it is blank, which is seconds on the larger tables.

Returns
What the walk found; BlankScan::ReadFailed when the partition is missing or a read failed.

presence() [1/3] #

vfs::Presence kleidos::platform::littlefs::presence(const char * path)

Presence of path on LittleFS, with "cannot tell" named.

Parameters
NameMeaning
pathNUL-terminated path string.
Returns
vfs::Presence::Present, vfs::Presence::Absent, or vfs::Presence::Unknown when the lookup itself failed.
See also
exists, kleidos::platform::vfs::presence

presence() [2/3] #

vfs::Presence kleidos::platform::sdfatfs::presence(const char * path)

Presence of path on the SD card, with "cannot tell" named.

exists answers false for an absent path, for an unmounted card and for every stat errno alike, which is the wrong shape for a caller whose false branch overwrites a file or picks a key-derivation input: on a card that is unseated or has a dirty contact, "no key file" and "this vault has no key file" are the same answer.

Parameters
NameMeaning
pathNUL-terminated path string.
Returns
vfs::Presence::Present, vfs::Presence::Absent, or vfs::Presence::Unknown when the lookup itself failed.
See also
exists

presence() [3/3] #

Presence kleidos::platform::vfs::presence(const Backend & backend, const char * path)

Presence of path, distinguishing "not there" from "cannot tell".

exists answers false for an absent path, for an unmounted backend, for a path that does not fit the physical buffer and for every stat errno alike — ENOMEM, EIO and an exhausted descriptor table included. A caller whose false branch destroys data needs those apart, because only Presence::Absent is evidence that there is nothing to lose.

Parameters
NameMeaning
backendBackend descriptor.
pathNUL-terminated path string.
Returns
Presence::Present, Presence::Absent, or Presence::Unknown when the question could not be answered.
See also
exists

readRaw() #

bool kleidos::platform::littlefs::readRaw(size_t offset, uint8_t * out, size_t bytes)

Read bytes of the vault partition raw (no decryption).

Parameters
NameDirectionMeaning
offsetinOffset into the partition.
outoutDestination, bytes long.
bytesinHow many bytes.
Return values
ValueMeaning
trueout holds what the flash stores there.
falseThe partition is missing, the range falls outside it, or the read failed.

remove() [1/3] #

bool kleidos::platform::littlefs::remove(const char * path)

Remove a file.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
trueFile removed successfully.
falseRemoval failed (missing file or driver error).

remove() [2/3] #

bool kleidos::platform::sdfatfs::remove(const char * path)

Remove a file.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
trueFile removed successfully.
falseRemoval failed (missing file or driver error).

remove() [3/3] #

bool kleidos::platform::vfs::remove(const Backend & backend, const char * path)

Remove a file.

Parameters
NameMeaning
backendBackend descriptor.
pathNUL-terminated path string.
Return values
ValueMeaning
trueFile removed successfully.
falseRemoval failed (missing file or driver error).

rename() [1/3] #

bool kleidos::platform::littlefs::rename(const char * from, const char * to)

Rename or move a file or directory.

Parameters
NameMeaning
fromSource path.
toDestination path.
Return values
ValueMeaning
trueRename completed successfully.
falseDriver reported a rename error.

rename() [2/3] #

bool kleidos::platform::sdfatfs::rename(const char * from, const char * to)

Rename or move a file or directory.

Parameters
NameMeaning
fromSource path.
toDestination path.
Return values
ValueMeaning
trueRename completed successfully.
falseDriver reported a rename error.

rename() [3/3] #

bool kleidos::platform::vfs::rename(const Backend & backend, const char * from, const char * to)

Rename or move a file or directory.

Parameters
NameMeaning
backendBackend descriptor.
fromSource path.
toDestination path.
Return values
ValueMeaning
trueRename completed successfully.
falseDriver reported a rename error.

resolveMount() #

template<typename Steps>
MountOutcome kleidos::platform::littlefs::resolveMount(Steps & steps)

Mount, and format only a partition a walk finds blank.

An attempt that failed an allocation is out of memory (classifyAttempt), and so is a refusal with no room left for the mount's buffers, which covers a heap whose failures nothing reports; the flash is not looked at. A refusal with room is tried again. One that outlasts the retry leaves the decision to the walk, whatever the mount reported, so a mount error alone can never format.

Template Parameters
NameMeaning
StepsProvides MountAttempt tryMount(), bool buffersAvailable(), BlankScan scan() and bool format().
Parameters
NameDirectionMeaning
stepsin, outWhat each step does on this platform.
Returns
How the mount ended.

rmdir() [1/3] #

bool kleidos::platform::littlefs::rmdir(const char * path)

Remove an empty directory.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
trueDirectory removed successfully.
falseRemoval failed or the directory is not empty.

rmdir() [2/3] #

bool kleidos::platform::sdfatfs::rmdir(const char * path)

Remove an empty directory.

Parameters
NameMeaning
pathNUL-terminated path string.
Return values
ValueMeaning
trueDirectory removed successfully.
falseRemoval failed or the directory is not empty.

rmdir() [3/3] #

bool kleidos::platform::vfs::rmdir(const Backend & backend, const char * path)

Remove an empty directory.

Parameters
NameMeaning
backendBackend descriptor.
pathNUL-terminated path string.
Return values
ValueMeaning
trueDirectory removed successfully.
falseRemoval failed or the directory is not empty.

runningPartitionLabel() #

bool kleidos::platform::ota::runningPartitionLabel(char * output, size_t outputLength)

Copy the running partition label into output.

Parameters
NameDirectionMeaning
outputoutDestination buffer.
outputLengthinBuffer size in bytes.
Return values
ValueMeaning
trueLabel was written to output.
falseoutput is too small to hold the label.

runningPartitionState() #

ImageState kleidos::platform::ota::runningPartitionState()

Return the OTA state of the currently running partition.

Return values
ValueMeaning
ImageState::NewFreshly written, not yet booted.
ImageState::PendingVerifyBooted, awaiting rollback confirmation.
ImageState::ValidConfirmed valid.
ImageState::InvalidMarked invalid (will not boot again).
ImageState::AbortedUpdate was aborted.
ImageState::UndefinedState could not be determined.

scanForBlank() #

template<typename Reader>
BlankScan kleidos::platform::littlefs::scanForBlank(Reader & reader, uint8_t * scratch, size_t scratchBytes)

Walk every sector of a partition and say whether it stores nothing.

Stops at the first sector that holds data, so a partition with a file system in it is told apart in a read or two, and only a blank one costs the whole walk.

Template Parameters
NameMeaning
ReaderProvides size_t sizeBytes(), bool encrypted(), bool readRaw(size_t offset, uint8_t* out, size_t bytes), bool readDecrypted(size_t offset, uint8_t* out, size_t bytes) and void pause().
Parameters
NameDirectionMeaning
readerin, outThe partition.
scratchoutBuffer for the reads.
scratchBytesinIts size; a sector is read in several chunks when it is shorter than one.
Returns
What the walk found. Nothing to read from or with is ReadFailed: a partition that could not be looked at is not verifiably blank.

secureBootEnabled() #

bool kleidos::platform::security::secureBootEnabled()

Read-only: whether Secure Boot v2 is active on this SoC.

A pure eFuse query with no side effects. Reads 0 (false) on every open build, which is deliberate: QA uses it to confirm a board under test is NOT accidentally running a hardened build.

Return values
ValueMeaning
trueSecure Boot is enabled (eFuse burned).
falseSecure Boot is disabled, or the native build.

totalBytes() [1/2] #

size_t kleidos::platform::littlefs::totalBytes()

Return total LittleFS partition capacity in bytes.

Free: the capacity is the block size times the block count, both known from the mount. Unlike usedBytes this walks nothing.

Returns
Total capacity in bytes.

totalBytes() [2/2] #

uint64_t kleidos::platform::sdfatfs::totalBytes()

Return the total SD card capacity in bytes.

Returns
Total capacity in bytes.

updateStageName() #

const char * kleidos::platform::ota::updateStageName(UpdateStage stage)

Return a human-readable name for an update stage.

Parameters
NameDirectionMeaning
stageinUpdateStage value to name.
Returns
Pointer to a static string.

usedBytes() [1/2] #

size_t kleidos::platform::littlefs::usedBytes()

Return bytes currently used on LittleFS.

Note
Costs a FULL filesystem traversal: LittleFS has no stored used-byte total, so the figure is counted by walking every metadata pair and every file's block chain. The price therefore grows with the file count, and the vault holds one file per credential slot. Treat it as a diagnostic, never as something to read per operation, and take it through info when the capacity is wanted alongside it.
Returns
Used byte count.

usedBytes() [2/2] #

uint64_t kleidos::platform::sdfatfs::usedBytes()

Return bytes currently used on the SD card.

Returns
Used byte count.

vaultReadPathName() #

const char * kleidos::platform::littlefs::vaultReadPathName(VaultReadPath path)
nodiscardconstexpr

The name the build command and the debug console give path.

Parameters
NameMeaning
pathA read path.
Returns
"plain", "littlefs_mmap" or "page_cache".

vaultReadPathOf() #

VaultReadPath kleidos::platform::littlefs::vaultReadPathOf(bool littlefsMmap, bool pageCache)
nodiscardconstexpr

The read path a build's Kconfig choice names.

Parameters
NameMeaning
littlefsMmapCONFIG_KLEIDOS_VAULT_READ_LITTLEFS_MMAP is set.
pageCacheCONFIG_KLEIDOS_VAULT_READ_PAGE_CACHE is set.
Returns
The path; VaultReadPath::Plain when neither is. The choice sets at most one, and little_fs.cpp refuses to build a component map set outside the choice.

volumeInfo() #

bool kleidos::platform::sdfatfs::volumeInfo(VolumeInfo & out)

Read the mounted volume's FAT geometry and allocation state.

The allocation hint decides how long the next write that needs a new cluster takes: FAT finds a free cluster by reading the table entry by entry from the hint on, so with no hint on a nearly full card it reads most of the table first.

Parameters
NameDirectionMeaning
outoutThe volume's state; untouched on failure.
Return values
ValueMeaning
trueout holds the volume's state.
falseNo card mounted.

writeRaw() #

bool kleidos::platform::littlefs::writeRaw(size_t offset, const uint8_t * data, size_t bytes)

Program bytes of the vault partition raw (no encryption).

The range must be erased: NOR flash only clears bits. The offset and the length are kept multiples of 32 bytes by the caller, the classic ESP32's Flash Encryption row, so the bytes are whole rows on every chip.

Parameters
NameDirectionMeaning
offsetinOffset into the partition.
datainBytes to program, bytes long.
bytesinHow many bytes.
Return values
ValueMeaning
trueThe write was accepted.
falseThe partition is missing, the range falls outside it, or the write failed.

Back to the top

Variable Documentation

kBlankScanSectorBytes #

size_t kleidos::platform::littlefs::kBlankScanSectorBytes
inlineconstexpr

Bytes the blank walk judges at a time: the flash's erase unit and LittleFS's block, so one erase takes a whole one back to the erased state.

kFastestClockKHz #

uint32_t kleidos::platform::sdfatfs::kFastestClockKHz
inlineconstexpr

The fastest SPI clock this chip's SPI master reads a card at, kHz: the source clock over 3 (26,666 kHz) on the classic ESP32. The SDSPI host reads the card in full duplex, where no dummy cycle can absorb a late input, and the classic ESP32's driver refuses a full-duplex clock whose read needs one. A MISO routed through the GPIO matrix (every slot board's: the Core2 v1.3's is GPIO38, not an IOMUX pin) arrives 25 ns late, which puts the ceiling at the source over 3; a mount asked for more fails when it switches the clock. The most Config::maxFrequencyKHz may ask; whether the card then switches to high speed is its own answer (cardMaxClockKHz).

The fastest SPI clock this chip's SPI master reads a card at, kHz: the source clock over 2 (40,000 kHz) on the ESP32-S3, whose driver applies no read-delay limit, and the fastest divisor of the source a high-speed card (50 MHz at most) accepts. The most Config::maxFrequencyKHz may ask; whether the card then switches to high speed is its own answer (cardMaxClockKHz).

kSpiSourceClockKHz #

uint32_t kleidos::platform::sdfatfs::kSpiSourceClockKHz
inlineconstexpr

The clock the SPI master divides to make the card's clock, kHz: the 80 MHz APB clock, on both chip families.

kVaultCacheMaxPages #

uint32_t kleidos::platform::littlefs::kVaultCacheMaxPages
inlineconstexpr

The most: the classic ESP32's 64-page window less the image's 20-page budget and the 4 pages kept free beside the vault leave 40, of which 32 are allowed.

Back to the top