# AO_Storage

The Active Object that owns the microSD card and the internal FAT: the only code that opens a file, with loaned reads, paged listings and room counts.

## What it is

A Kode Dot keeps files in two places: the microSD card and the internal FAT partition. **AO_Storage** owns both and is the only code in the SDK that opens a file. Everything else sends it a request and gets events back: a list of files, a chunk of a file, a write, a copy, a delete, the room left on a volume, a download of a URL into a file. A request names a file on a medium, or gives a full path that starts with `/`, `/sdcard/…` or `/storage/…`.

It reads a file in 32 KB chunks through two buffers in PSRAM. It lends one buffer to the reader, who gives it back when the bytes are used, so the next chunk is read while the first is in use. The system allows one reader and one writer at a time, and `cp` is the one case that needs both. AO_Storage also runs the card tests of the production line and the bench.

## How it is connected

```mermaid
flowchart LR
  subgraph own["AO_Storage and below"]
    sto["AO_Storage<br/>priority 5"] -- "job" --> w["storage_sd<br/>worker"]
    w -- "mount, sectors,<br/>format" --> sd["kdrv_sd"]
    sto -- "files" --> st["kdrv_storage"]
  end
  appmgr["AO_AppMgr"] -- "open, read, next" --> sto
  con["AO_Console"] -- "path, pair, text" --> sto
  gui["AO_Gui, AO_Audio,<br/>apps"] -- "list, read, write" --> sto
  sd --> card["microSD"]
  st --> fat["Internal FAT"]
  class sto,appmgr,con,gui ao
  class card,fat store
```

*Who asks AO_Storage, and what it calls*

### Priority and the defer queue

AO_Storage runs at priority 5 with a queue of 16 events and a 6144-byte stack. It claims `KBSP_RES_SDMMC` and `KBSP_RES_FATFS`. The priority is low on purpose: a slow card is the longest wait in the system, and down here it can delay only AO_Net, AO_Gui and AO_Radio. Its steps stay short. A write moves 32 KB per step and a timer gives lower priorities one slot between steps.

The AO has one state, `Storage_active`, with a filter in front of it. While a call to the card is out, any request that could touch the card waits in a defer queue of 8 (`KODE_STORAGE_DEFER_DEPTH`) and is taken again in order when the call returns. A request over that room is refused with an answer, never in silence. A request for the internal partition is served at once.

### The worker

`storage_sd` is a task of AO_Storage with an 8192-byte stack in PSRAM and a queue of one job (`sdk/kqp`). It runs one call of `kdrv_sd` at a time and decides nothing: mount, unmount, remount, read or write raw sectors, format. AO_Storage reads the status in `STORAGE_SDJOB_DONE_SIG`.

Every call has a deadline, the driver's bound plus `KODE_STORAGE_JOB_MARGIN_MS` (500 ms). When it fires, AO_Storage tells the waiter the call failed, and the late result answers nobody twice. An overrun in the middle of a card script ends the script, because the next phase would ask the card for a second call while the worker is still inside the first.

The stack is in PSRAM because nothing a job touches reaches the internal flash. The test file of the card row can land on the internal FAT, so its write stays in the AO.

### One question, `busy()`

Nine facts say whether a file handle is in use:

- A reader.
- A writer.
- A running card script.
- A copy.
- A `cat`.
- A `file_put`.
- An app data folder being written.
- The erase of an app's files.
- A card call that overran its deadline and has not returned.

Almost every path asks `busy()` first and refuses while it is true.

### Listing

`storage_list_request()` posts an unmount of the card, a mount and the first page of bootable images, in that order. The remount makes the listing honest: FATFS keeps what it read at mount, so a swapped card would stay unseen otherwise. The internal partition is not remounted.

`storage_list_page(skip, who)` walks the card first and the internal FAT second as one listing, and posts up to 24 `STORAGE_ENTRY_SIG` events and an end marker to the asker alone. `pos` counts across pages and media, and `more` on the end marker says another page follows. A name of 64 characters or more is skipped.

The end marker comes from two static events, so an empty pool cannot lose it. `sd_ls` and `fs_ls` publish one page of 24 and say `capped`.

`storage_list_ask(who, path, skip)` lists one folder in pages of up to 24 entries, posted to the asker alone, and ends each page with `FILE_LIST_END_SIG` (`count`, `more`). `kode_sys_file_list()` reads a folder through it, and so does the console's `ls`, page after page until the folder's end. A name of 96 characters or more, which FAT allows and no path holds, is left out with a warning.

### Reading, the loan

The reader sends `STORAGE_OPEN_REQ_SIG` and gets `STORAGE_OPEN_RSP_SIG` with the size. A bare name is searched on the card first and then on the internal FAT, and a name starting with `/` opens exactly that file.

`STORAGE_READ_REQ_SIG` makes AO_Storage fill a free buffer and post `STORAGE_DATA_SIG` (`idx`, `len`, `eof`). The bytes are valid until the reader returns the index with `STORAGE_NEXT_SIG`, which also asks for the next chunk. Only the index travels, never an address.

### The manifest peek and the app data folder

`STORAGE_DESC_REQ_SIG` reads the front of a `.bin` and answers its project name, display name, category and build id, inside one step and without marking the asker as the reader.

`APPDATA_REQ_SIG` resolves the folder `/storage/.kode/appsdata/<project>`, tries the internal FAT before the card and uses the first folder it finds whole. It posts one `APPDATA_FIELDS_SIG`, zero or three `APPDATA_ICON_SIG` and an `APPDATA_END_SIG`. The conversation always closes, so a launcher scan never stalls.

`APPDATA_RM_REQ_SIG` deletes the folder, one level of subfolder included, from the medium the reader finds it on: the internal FAT's when there is one, and the card's only when the card alone holds one. A card folder of the same name is then left where it is and logged.

`APPDATA_PUT_REQ_SIG` writes a whole folder: `app.json`, then the icon when the request carries one, under temporary names beside the old files, which they replace only when both are down. The folder arrives apart from its image, so it can be on the board before the app is. Where it goes:

- A folder that is there is written over on the medium that holds it, the internal FAT before the card. One on the internal FAT with no room there for its replacement goes to a card that took the write check and has room, and the old folder is removed once the new one reads back as written. A folder on the card never moves inside.
- A new folder goes to a card that took the write check and has room, and stays there. A card that then will not take the write is not chosen again while it is in, keeps none of the folder, and the folder goes inside. With no such card it goes inside and the log says why.
- On the internal FAT a new folder must leave 128 KB free (`KODE_APPDATA_FREE_MIN_BYTES`). When the inside has no room and a mounted card has, the folder goes to the card. One that fits on neither is refused with `KODE_NO_RESOURCES`.

Each file is charged what it weighs on the volume, rounded up to the volume's cluster. A failed put leaves the folder that was there as it was. `APPDATA_PUT_RSP_SIG` answers the asker.

`STORAGE_APP_WIPE_REQ_SIG` takes every file of one app off both media. It walks the root of each medium, removes the images whose descriptor names the project (never `kodeos.bin` or `c5_slave.bin`), one file a step, then the project's data folder on each medium. A delete on the card that fails is told to the card's driver; the card is mounted again before the next step and the same file or folder is tried once more, so a counterfeit card that refused it on four lines takes it on one. `STORAGE_APP_WIPE_RSP_SIG` says per medium whether it was walked, how many images went, how many stayed and what became of the folder.

The same request with `others` set (`storage_apps_clear_request(keep, who)`) is the factory reset's clear: every app's files but `keep`'s. It removes the image of every ESP32-P4 app at a medium's root whatever the file is called, and every other app's data folder. It keeps the user's own files, the images of the running kodeOS and of the C5 under any name, images built for another chip, and the face's pack. A root or a tree that holds more names than one walk keeps is walked again, up to three walks (`KODE_RESET_FILES_WALKS`), and the answer says `cut` for a part never looked at.

### The path requests

The console and the facade never open a file themselves. `STORAGE_PATH_REQ_SIG` carries `STAT`, `LIST`, `CAT`, `MKDIR`, `UNLINK`, `RMDIR` and `SPACE`. `STORAGE_PAIR_REQ_SIG` carries `MOVE`, `COPY` and `REPLACE`. A move across `/sdcard` and `/storage` is refused with `KODE_DENIED`, since FAT cannot rename across a mount.

`REPLACE` puts a file on a name that may be taken, on one volume, in one step with one answer. The file already there goes to `<dst>.bak` first, comes back if a step fails and is removed once the new one is in place, and a `<dst>.bak` left from before is removed. A reset between the steps leaves the old file as `<dst>.bak` and the new one where it was, never a cut file on the name. AO_AppMgr puts an app's copy on the card this way.

Before a change on the card at a path typed at the console (`mkdir`, `rm`, `rmdir`, `mv`, `cp`, `write`, `file_put`), AO_Storage logs a warning, `<verb> on the card: <path>`, even when the change is then refused, because one failed write on a counterfeit card poisons its later reads (see Gotchas). The changes kodeOS and the apps make there by their own choice are said only while the card has not proved it takes a write: an app's data folder written or removed, the `REPLACE` that puts an app's copy on its name, and every change asked through the two file doors (`kode_sys_file_*()` and `kode_file_*()`), the launcher's saved list among them. A `mkdir` of a name already taken is answered `KODE_EXISTS` (`exists` at the console) and is not logged as a failure.

`STORAGE_TEXT_REQ_SIG` writes text, or replaces one line by writing a `.tmp` file, renaming the original to `.bak` and the new file into place.

`CAT` sends 24 lines per step, 200 bytes at most per line. `SPACE` counts a volume in whole kilobytes with the count `sd_info` and `fs_info` print, and answers only for a volume's own root, `/sdcard` or `/storage`. `COPY` borrows one buffer, copies 32 KB per step and removes the destination whole if it fails.

### Writing

`storage_write_all_request()` takes a payload that is already whole in the caller's memory, which must stay valid until `STORAGE_WRITE_RSP_SIG`. A name that starts with `/` goes to the volume it names only, and is refused with `KODE_NO_RESOURCES`, nothing written, when that volume has less room than the payload. A bare name is placed by the card's write check (`sdk/kdrv/storage`), and the log says where at NOTICE:

- A name a medium already holds is written over where a read finds it, `'<name>' is written over on <medium>, where it is`. A name the card holds is the exception while the card has not taken the check: the write goes inside, and a read still finds the card's file first.
- A new name goes to the card when the card took the check and has room, `'<name>' goes to the card`, and inside otherwise, with the reason: no card is mounted, the card has not proved it takes a write, or it is full.

After a failed chunk the stub is removed and the write tries once on the other medium, `retrying on the <medium>`: the card only when it took the check. A card a write failed on is mounted again once nothing is in flight (`the card is mounted again after the write that failed on it`), because a failed write poisons the card's later reads. After a failure on four lines that mount is on one line, where the card is checked again and chosen again if it takes the check; after a failure on one line the card is not chosen again while it is in. A failed write never leaves a partial file. A card put in since the last listing is mounted before a bare name is placed.

`storage_write_yield_request()` writes the same way and gives way to a download into a file: it is refused with `KODE_DENIED` while one runs, and a download asked for while it is in flight cuts it between two chunks, removes the half-written file and answers `KODE_DENIED` with the bytes put down so far. It refuses a path on a card that has not taken the check with `KODE_ERROR`, and a full card with `KODE_NO_RESOURCES` (`the card is full: '<name>' is not written`). AO_AppMgr's copies to the card use it. `storage_write_abandon_request(who)` (`STORAGE_WRITE_ABANDON_REQ_SIG`) ends the asker's write between two chunks, removes the half-written file and answers it; a late one is ignored. A write's `tag` comes back in its answer, so a writer that abandons a write tells its late answer from the next one's.

### The card's mounts

AO_Storage publishes `STORAGE_CARD_SIG` (`StorageCardEvt`, `mounted` and `rested`) when a card is mounted, the same one again or another, and when the mounted card is mounted no more. An app's rest that puts the card away publishes it with `rested` set: the card is not mounted and still in as far as is known, and the next request that needs it brings it back. A rest with no card in the slot puts nothing away, and a wake that finds no card publishes again with `rested` clear. A change of either field is published. What a subscriber knew of the card's files is to be asked again, since a card can be changed while its supply is off. When a card mounts, AO_Storage walks its root for what a cut copy of an app left, `<project>.bin.tmp`, and removes it, 32 names a pass and at most 8 leftovers a pass, a pacer tick apart.

### Downloading into a file

`HTTP_FILE_REQ_SIG` (`storage_fetch_ask()`, the door behind `kode_sys_http_get_file()`) downloads a URL into a file of any size. AO_Storage leads: it asks AO_Net for the body from the length the file already has, 0 for a new file (`NET_STREAM_OPEN_FROM_SIG`, `sdk/kaos/net`), and appends each chunk in one step, opening and closing the file around it. So the same request after a cut takes the download up where it stopped; to start over, delete the file first. Each chunk in the file posts `HTTP_FILE_PROGRESS_SIG` to the asker and the end posts one `HTTP_FILE_RSP_SIG`, both `HttpFileEvt`:

| Field | What it says |
| --- | --- |
| `rc` | The end: `KODE_OK` when the body is all in the file, or a stop ended it. `KODE_DENIED` for a server that ignores ranges asked for the rest (`status` 200), no network, another download or transfer in the way. `KODE_TIMEOUT` for a body that stopped. Otherwise the file's or the network's refusal. Progress: `KODE_OK` |
| `stopped` | `kode_sys_http_file_stop()` ended it (`HTTP_FILE_STOP_SIG`); what was written is kept |
| `status` | The server's: 200 for a body from its start, 206 for the rest of one, 416 for a file that was whole already (with `KODE_OK`) or longer than the resource (with `KODE_DENIED`); 0 when none answered |
| `written` | Bytes this download appended |
| `size` | The file's length now |
| `total` | The length the file will have; 0 when the server did not say |

A redirect is not followed: it ends the download with `KODE_ERROR` and its status. A bare name goes where a bare write goes, and the card is not mounted for it first. A chunk the card fails ends the download and takes the card's word back, as a write's does. A chunk that finds the file handle held by another transfer is tried again 50 ms later (`KODE_HTTP_FILE_RETRY_MS`), and AO_Net silent for 30 s (`KODE_HTTP_FILE_STALL_MS`) ends the download with `KODE_TIMEOUT`.

There is one download at a time on the board, and one per asker. A second, and an install from a URL while one runs, are refused with `KODE_DENIED`; AO_AppMgr's record says `why=busy`. A download cuts a yielding write in flight and refuses new ones, which is how it pauses AO_AppMgr's copies to the card (`the write of '<name>' gives way to a download`). A file holds 4 GB at most. The code is in `storage_fetch.c`, linked only by an app that asks for a download.

### Files for an app

An app reaches the files through two doors that end in the same requests. An Active Object calls `kode_sys_file_*()` and gets the answer as an event posted to it alone. A task calls `kode_file_*()` in `kode.h`, which blocks while AO_Storage answers into a waiter instead of an event. Both name a volume and a path; neither opens a handle.

A read names a window: `kode_sys_file_read()` and `kode_file_read_at()` take an offset and a capacity, so a file of any size is read in pieces. A read at or past the end gives no bytes and is not an error. A write takes bytes and a length, so a `0` inside the data is written like any other byte, and `append` keeps what the file held. `kode_sys_file_space()` and `kode_file_space()` ask how big a volume is and how much of it is free, so an app learns a card is full before a write fails part-way.

### Receiving a file

`file_put` uses the five receive signals that AO_AppMgr uses (`sdk/kaos/appmgr`), but AO_Storage posts them and does not publish them, so the Opening card never appears. It arms raw mode on the console first, and opens the destination only after the port is raw. The idle timer starts as a 30 s long-stop and tightens to 5 s before `RECV_READY_SIG` goes out.

### The card tests

`test component=sd` judges the board's slot and leaves the card as it was. It has five phases and publishes one `STORAGE_TEST_SIG` for each: `identify`, `read4`, `read1`, `write`, `verify`.

Only `identify` and `read4` decide the verdict, since counterfeit cards read well and refuse writes.

`sd_verify` judges the card itself, destructively, with `probe` and `format`. Both end in a published `TEST_RESULT_SIG`.

### Resting with the board

With `CONFIG_KODE_LOWPOWER`, AO_Storage joins the rounds of AO_LowPower as `storage` (`sdk/kaos/lowpower`). A file is open only while a transfer runs, so the rest is a check. With nothing open, no call out to the card and no request held, the files are closed and the card is idle, and the round is answered ready. An open reader or writer answers `file write`. A download into a file answers `download`, since the radio would rest with the board and the body with it. Any other transfer, or a call to the card that is out, answers `storage busy`. A round that also rests an app's parts has the worker unmount the card and switch its supply off (`kdrv_storage_card_rest()`), and is answered when both are done. The card is then at rest for the app, and `STORAGE_CARD_SIG` says so with `rested` (`sdk/kaos/part-rest`).

The card's supply is not AO_Storage's: deep sleep holds it off. Nothing is restored when the board wakes, so AO_Storage listens to the rounds and not to `LOWPOWER_STATE_SIG`.

## Specifications

### Requests

| Signal | Event | What AO_Storage does |
| --- | --- | --- |
| `STORAGE_CMD_SIG` | `StorageCmdEvt` (`medium`, `op`, `images_only`, `last`, `who`) | `op` is `STORAGE_OP_MOUNT`, `_UNMOUNT`, `_INFO`, `_LIST`, `_SELFTEST` or `_VERIFY`. With `who` set it posts `STORAGE_CMD_RSP_SIG` when the command has run |
| `STORAGE_LIST_PAGE_SIG` | `StorageListPageEvt` (`skip`, `who`) | One page of bootable images, to `who` alone |
| `STORAGE_OPEN_REQ_SIG`, `STORAGE_READ_REQ_SIG`, `STORAGE_NEXT_SIG`, `STORAGE_CLOSE_REQ_SIG` | `StorageOpenEvt`, none, `StorageBufEvt`, none | The loan. Close ends a read only, and is ignored while a write, copy or `file_put` runs |
| `STORAGE_WRITE_REQ_SIG` | `StorageWriteEvt` (`name`, `data`, `len`, `who`, `tag`, `yields`) | Put a caller's data in a file. `yields` gives way to a download |
| `STORAGE_WRITE_ABANDON_REQ_SIG` | `StorageWriteAbandonEvt` (`who`) | End the asker's write in flight, between two chunks |
| `STORAGE_DESC_REQ_SIG` | `StorageDescReqEvt` | The manifest peek |
| `APPDATA_REQ_SIG`, `APPDATA_RM_REQ_SIG` | `AppDataReqEvt` (`project`, `who`) | Read or delete an app's data folder |
| `APPDATA_PUT_REQ_SIG` | `AppDataPutEvt` (`project`, `buf`, `json_len`, `icon_len`, `who`) | Write an app's data folder on the medium the rules above choose. AO_Storage owns `buf` from the post |
| `STORAGE_APP_WIPE_REQ_SIG` | `AppDataReqEvt` (`project`, `who`, `others`) | Take every file of an app off both media; with `others`, every app's files but that one's |
| `HTTP_FILE_REQ_SIG`, `HTTP_FILE_STOP_SIG` | `HttpFileReqEvt` (`job`, `who`, `rsp`), `HttpFileStopEvt` (`who`) | Download a URL into a file; end the asker's download |
| `NET_STREAM_FROM_RSP_SIG`, `NET_STREAM_DATA_SIG` | `NetStreamFromRspEvt` (`size`, `http`, `status`), stream events | AO_Net's answers to a download |
| `FILE_*` asks of `kode_sys_file_*()` | One request per kind, carried by the path, pair and text requests | Status, space, list, folder, delete, rename, read and write for an Active Object |
| `STORAGE_PATH_REQ_SIG`, `STORAGE_PAIR_REQ_SIG`, `STORAGE_TEXT_REQ_SIG` | `StoragePathEvt`, `StoragePairEvt`, `StorageTextEvt` | The file tree |
| `STORAGE_FIELD_REQ_SIG` | `StorageFieldReqEvt` (`op`, `field`, `value`, `who`) | Get, set or dump a field of the card's table. A set is followed by a get |
| `STORAGE_RECV_REQ_SIG` | `StorageRecvEvt` | Start a `file_put` |
| `CONSOLE_RAW_RSP_SIG` | `ConsoleRawRspEvt` | AO_Log's answer to the raw-mode request |
| `RECV_DATA_SIG` | `RecvDataEvt` | A chunk of a `file_put`, from the reader task or the NimBLE task |
| `LOWPOWER_ROUND_SIG` | `LowPowerRoundEvt` | With `CONFIG_KODE_LOWPOWER`: a round of the board's rest, answered ready or busy |

Private signals: `STORAGE_SDJOB_DONE_SIG` (a `KqpWorkerDoneEvt` from `storage_sd`), and the `QTimeEvt`s `STORAGE_SDJOB_TO_SIG`, `STORAGE_APP_WIPE_NEXT_SIG`, `APPDATA_PUT_NEXT_SIG`, `STORAGE_WRITE_NEXT_SIG`, `STORAGE_TEST_NEXT_SIG`, `STORAGE_CAT_NEXT_SIG`, `STORAGE_COPY_NEXT_SIG`, `STORAGE_SWEEP_NEXT_SIG`, `HTTP_FILE_RETRY_SIG`, `HTTP_FILE_STALL_SIG` and `STORAGE_RECV_IDLE_SIG`.

### Answers

| Signal | Event | Range | To |
| --- | --- | --- | --- |
| `STORAGE_ENTRY_SIG` | `StorageEntryEvt` (`name`, `size`, `from_sd`, `pos`, `is_dir`) | publish for `sd_ls`, `fs_ls`; post for a page | Subscribers; the asker of a page |
| `STORAGE_LIST_END_SIG` | `ListEndEvt` (`more`) | same | Same |
| `STORAGE_INFO_SIG` | `StorageInfoEvt` (`medium`, `mounted`, `usage_known`, `why`, `total_kb`, `free_kb`, `card_mb`) | publish | Closes `sd_info` and `fs_info`. `card_mb` is the size of the card, and the volume on it can be smaller. `why` is `kdrv_sd_why()`, what the card's last bring-up found (an empty slot, no FAT volume, a card that would not come up), and `KDRV_SD_WHY_NONE` while the card is mounted and for the internal partition (`sdk/kdrv/storage`) |
| `STORAGE_CARD_SIG` | `StorageCardEvt` (`mounted`, `rested`) | publish | A card was mounted, is mounted no more, or was put away by an app's rest (`rested`) |
| `HTTP_FILE_PROGRESS_SIG`, `HTTP_FILE_RSP_SIG` | `HttpFileEvt` (`rc`, `stopped`, `status`, `written`, `size`, `total`) | post | The asker of a download: one per chunk in the file, then its end |
| `NET_STREAM_OPEN_FROM_SIG` | `NetStreamFromEvt` (`offset`, `who`, `url`) | post | AO_Net: the body of a download from the file's length on |
| `STORAGE_TEST_SIG`, `TEST_RESULT_SIG` | `StorageTestEvt`, `TestResultEvt` | publish | One per phase of a card script, then the verdict |
| `STORAGE_OPEN_RSP_SIG`, `STORAGE_DATA_SIG`, `STORAGE_WRITE_RSP_SIG`, `STORAGE_DESC_RSP_SIG`, `STORAGE_FIELD_RSP_SIG` | Matching events | post | `who` |
| `STORAGE_PATH_RSP_SIG`, `STORAGE_LINE_SIG`, `STORAGE_CMD_RSP_SIG` | `StoragePathRspEvt`, `StorageLineEvt`, none | post | `who` |
| `APPDATA_FIELDS_SIG`, `APPDATA_ICON_SIG`, `APPDATA_END_SIG`, `APPDATA_RM_RSP_SIG` | App data events | post | `who` |
| `APPDATA_PUT_RSP_SIG`, `STORAGE_APP_WIPE_RSP_SIG` | `AppDataPutRspEvt` (`rc`), `StorageAppWipeRspEvt` (`status`, `fs`, `sd`) | post | `who` |
| `FILE_STATUS_RSP_SIG`, `FILE_SPACE_RSP_SIG`, `FILE_LIST_END_SIG`, `FILE_FOLDER_RSP_SIG`, `FILE_DELETE_RSP_SIG`, `FILE_RENAME_RSP_SIG`, `FILE_READ_RSP_SIG`, `FILE_WRITE_RSP_SIG` | `FileRspEvt` (`rc`, and `stat`, `space`, `got`, `count`, `more` where the kind has them) | post | The asking AO |
| `RECV_READY_SIG`, `RECV_ACK_SIG`, `RECV_DONE_SIG`, `RECV_FAIL_SIG`, `RECV_STALL_SIG` | none | post | The `who` of the `file_put` |
| `CONSOLE_RAW_REQ_SIG`, `CONSOLE_RAW_END_SIG` | `ConsoleRawReqEvt`, none | post | AO_Log |

### Limits and timers

| Name | Value | Meaning |
| --- | --- | --- |
| `STORAGE_BUFS`, `STORAGE_CHUNK` | 2, 32 KB | Streaming buffers in PSRAM, aligned to 64 bytes |
| `KODE_STORAGE_LIST_MAX` | 24 | Entries in a page; a page and its end marker are 25 events |
| `KODE_APP_FILE_MAX` | 64 | Longest name in the listing of the bootable images, NUL included |
| `KODE_STORAGE_NAME_MAX` | 96 | Longest name in any other listing, NUL included: as long as a path |
| `KODE_PATH_MAX` | 96 | Longest path |
| `KODE_FS_TEXT_MAX` | 120 | Longest `write text=` |
| `KODE_FS_CAT_MAX_DEFAULT`, `_CEIL` | 4096, 32768 bytes | A `cat` reads this much |
| `KODE_FS_CAT_LINE_MAX` | 200 | A longer line is cut to 199 and logged |
| `KODE_RECV_CHUNK` | 4096 | One chunk of `file_put`, acknowledged with `>\|ack` |
| Write, test, cat and copy pacers | 10 ms each | One step per tick |
| `STORAGE_RECV_LONGSTOP_TICKS`, `KODE_RECV_IDLE_MS` | 30 s, 5 s | `file_put` watchdog: long-stop, then between chunks |
| Card call deadline | Driver bound + 500 ms | Mount, sectors (`KDRV_SD_SECTORS_MAX_MS` 5 s), format (`KDRV_SD_FORMAT_MAX_MS` 120 s) |
| `KODE_HTTP_FILE_STALL_MS` | 30 s | A download with no word from AO_Net ends with `KODE_TIMEOUT` |
| `KODE_HTTP_FILE_RETRY_MS` | 50 ms | A chunk whose file handle another transfer holds is tried again |
| `KODE_SYS_HTTP_FILE_URL_MAX` | 256 | A download's URL, terminator included |

### The facade

An Active Object asks for files with the `kode_sys_file_*()` calls of `kode_sys.h`: `kode_sys_file_status()`, `_space()`, `_list()`, `_create_folder()`, `_delete()`, `_rename()`, `_read()` and `_write()`. Each posts one request and takes one answer, posted to the asker alone: `FILE_STATUS_RSP_SIG`, `FILE_SPACE_RSP_SIG`, `FILE_LIST_END_SIG` after the `STORAGE_ENTRY_SIG` events, `FILE_FOLDER_RSP_SIG`, `FILE_DELETE_RSP_SIG`, `FILE_RENAME_RSP_SIG`, `FILE_READ_RSP_SIG` and `FILE_WRITE_RSP_SIG`. An asker has one request of each kind out at a time.

A path is absolute and virtual, under `/sdcard` or `/storage`, shorter than `KODE_SYS_FILE_PATH_MAX` (96). A read or a write moves up to `KODE_SYS_FILE_READ_MAX` (32768 bytes) in one call; a bigger file is read in windows with an offset and written in parts, each with `append`. The buffer is lent: AO_Storage writes a read's buffer in place just before the answer and reads a write's buffer in place until the answer, so keep it valid and unchanged until then. A listing leaves `KODE_SYS_LIST_FREE_SLOTS` (8) slots free in the asker's queue and ends early, with `more` set, when an entry would take one.

`kode_sys_http_get_file(me, url, path)` downloads a URL into a file and `kode_sys_http_file_stop(me)` ends it, as described above. `path` is absolute and virtual, in a folder that exists, or a bare name. Without `CONFIG_KODEOS_NET` both answer `KODE_DENIED`.

A task calls the blocking `kode_file_*()` calls of `kode.h`: `kode_file_read()`, `_read_bytes()`, `_read_at()`, `_write()`, `_append()`, `_write_bytes()`, `_append_bytes()`, `_status()`, `_space()`, `_exists()`, `_list()`, `_delete()`, `_create_folder()`, `_rename()` and `_move()`. A path starts with `sd/` or `flash/`, and `kode_error()` says why a call failed. A whole-file read is limited to `KODE_FILE_READ_MAX` (4 MiB), and `kode_file_read_at()` reads a file of any size into the caller's buffer. A write takes any length the volume can hold and goes in parts, so a failure after the first part leaves the file cut. A file call waits for another task's file call to finish, and each storage request waits up to `KODE_FILE_BUSY_MS` (5 s) when storage is busy. Never call them from an Active Object.

### Console verbs and settings

`sd_mount`, `sd_unmount`, `sd_ls`, `sd_info`, `fs_mount`, `fs_unmount`, `fs_ls`, `fs_info`, `ls`, `cd`, `pwd`, `stat`, `cat`, `mkdir`, `rm`, `rmdir`, `mv`, `cp`, `write`, `file_put`, `file_get`, `file_desc`, `appdata_ls`, `appdata_info`, `appdata_rm`, `sd`, `sd_verify` and `test component=sd|fs`. AO_Storage owns no stored setting.

## Gotchas

> **WARNING**
>
> **A failed write on a counterfeit card poisons every later read.** Some cards shipped with units report exactly 30000 MB and refuse writes. After one failed write FATFS holds sectors it can never flush, and every later open on that volume returns length 0 until the card is mounted again. A bare name goes to the card only when the card took the write check at mount, and a card a write failed on is mounted again: on one line, where it is checked again, when the write failed on four, and not written to for the rest of the boot when it failed on one. The check proves the way a write goes, not that the card keeps it. Run `test component=sd` and `sd_verify` before you trust a card.

> **WARNING**
>
> **A file call returns `KODE_DENIED` while anything else holds a file.** An install, a `cp`, a `cat` or a read on loan keeps the handles, and a write, a delete or an unmount waits its turn or is refused. Retry after the other transfer ends.

> **WARNING**
>
> **Card scripts fail right after boot.** Bringing the C5 link up is SDIO traffic on the same controller, and heavy raw access to the card during that time makes the vendor driver fail an assertion in `sdio_rx_get_buffer`. Start `test component=sd` and `sd_verify` after the board has settled.

> **NOTE**
>
> **A listing that reads `truncated` was starved of pool blocks.** AO_Gui subscribes to the entries and sits near the bottom of the priority map, so a busy renderer can hold the pool blocks of a page. Pages go to the asker alone for this reason, and the next page is asked only after the end marker is read.

## Example code

Write a file to the internal FAT and read it back. With the app running, the log prints `read back: hello from the app`.

```c
/*
 * storage_roundtrip.c - from Kode with love
 *
 * Writes a short text file to the internal FAT through AO_Storage and reads
 * it back. kode_file_*() block until AO_Storage answers, so they run from
 * app_main() and never from an Active Object. The log prints the text.
 */
#include "kode.h"
#include "kode_log.h"

#define TAG  "fsdemo"
#define PATH "flash/hello.txt"

/* Write, read back, log. */
void app_main(void)
{
    kode_init();

    if (!kode_file_write(PATH, "hello from the app")) {
        KLOG_E(TAG, "write failed: %s", kode_error());
        return;
    }
    KLOG_I(TAG, "read back: %s", kode_file_read(PATH));
}
```

Compiled against the 0.1.1 SDK with ESP-IDF v6.1 on 2026-11-11. Not run on a Kode Dot.

## In the SDK

- [`components/kaos/storage`](https://github.com/kodediy/kode-sdk/tree/main/components/kaos/storage): `storage_ao.c`, the whole Active Object.
- [`components/kdrv/storage`](https://github.com/kodediy/kode-sdk/tree/main/components/kdrv/storage): the driver AO_Storage calls (`sdk/kdrv/storage`).
- [`kode.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kode/include/kode.h): the `kode_file_*()` calls for tasks. [`kode_sys.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kode_sys/include/kode_sys.h): the `kode_sys_file_*()` calls for Active Objects.
