nandlog v1.1

API Reference

Every function in nandlog.h, the one header an application includes, grouped by what it does.

The library keeps one log on one part. A caller needs five ideas to use it:

Each group below opens with a summary. Read Calling conventions first if more than one thread uses the log. The Writing and Reading groups cover what most applications call. Earlier epochs, retransmission, diagnostics, and recovery follow.

Calling conventions

Every function except three takes the port's lock for its whole duration, so with a real mutex in nandlog_port_lock() any thread may call any function. The exceptions need no lock: nandlog_data_bytes_per_page() reads constants, while nandlog_framed_next_record() and nandlog_crc32() work only on the caller's buffer. The library never takes the lock twice, so the mutex need not be recursive. However, the library calls nandlog_port_log() and nandlog_port_unwritable() with its lock held, so those must not call back into it.

The lock is a single lock. As a result, a nandlog_store_record() that only copies into RAM waits behind whatever holds it, and the longest holders are the calls that read across the epoch or the part. On the Alliance part, an end-bounded nandlog_begin_reading() over a 10,000-page epoch holds the lock for 3.0 s, nandlog_read_span() with a byte total over 1,000 pages holds it for 1.0 s, and the first nandlog_begin_epoch() on a part with no slot holds it for about 1.1 s. A logger that cannot wait that long should buffer its own records during a download (see Performance).

A call made outside a session wakes the part for that call and puts it back to sleep afterwards. Pointer arguments must be valid unless a function says it accepts NULL.

Builds without a part. With NANDLOG_HAS_HARDWARE set to 0, every function is a stand-in. nandlog_init(), nandlog_probe(), and nandlog_begin_epoch() return true, nandlog_store_record() and nandlog_flush() return NANDLOG_OK, and every read, count, and walk yields nothing (including nandlog_framed_next_record()). nandlog_crc32() still computes the CRC.

Lifecycle

Call nandlog_init() once at boot. The other functions here test for a part, release the port, or pause logging.

bool nandlog_probe(void);

Confirm that a part is present and answering, without bringing the log up or writing anything. It is meant for builds that only test for a part. nandlog_init() performs the same check itself.

bool nandlog_init(void);

Bring the log up: open the port, identify the part, and load its bad-block table, then recover the current epoch from the metadata ring and find the write head. The boot may write a metadata slot and erase the blocks ahead of the write head before it returns. A second call returns true at once.

Returns false if the port would not open, the part did not answer, the target is big-endian, or the part's page leaves too little room for NANDLOG_MAX_EPOCH_DETAILS_BYTES. Make no other call in that case. A log that comes up sealed or unable to write still returns true: the boot calls nandlog_port_unwritable(), and nandlog_store_record() reports why.

void nandlog_deinit(void);

Release the port. nandlog_init() can bring the log back up afterwards. Records still buffered in RAM are lost, exactly as a power cut would lose them, so flush first.

void nandlog_disable(bool disable);

Stop or resume accepting records. A disabled log refuses records with NANDLOG_ERR_DISABLED rather than buffer them. It still serves reads, and nandlog_flush() still commits what it accepted earlier, but does no erase-ahead. nandlog_init() brings the log up enabled. Resuming does not lift the log's own refusal: a log that stopped because no block would retain a page waits for a reboot or a new epoch, and a sealed epoch waits for a new epoch.

uint32_t nandlog_data_bytes_per_page(void);

Payload bytes a page holds on the fitted part: the page size less the 32-byte header the log writes into it (4,064 on a 4 KB page). It is answered from the chip driver, so it is correct before nandlog_init() has run.

Sessions

A session holds the part powered across a run of calls, instead of waking and sleeping it around each one. nandlog_begin_epoch(), nandlog_select_epoch(), and nandlog_begin_reading() require one. Every other function works with or without one.

void nandlog_begin_session(void);
void nandlog_end_session(void);

Open and close a session. Sessions do not nest: a second nandlog_begin_session() does nothing, and one nandlog_end_session() closes the session. Ending a session also closes any open read and returns the read view to the current epoch.

Epochs

An epoch is one generation of the log: a numbered run of pages with its own start block, its own sequence numbering from 0, and a details blob of your own. Writing always goes to the current epoch. Reads go to the current epoch unless you select an earlier one.

bool nandlog_begin_epoch(const void *blob, uint16_t length);

Begin a new epoch, described by an opaque blob of at most NANDLOG_MAX_EPOCH_DETAILS_BYTES. The log stores the blob but never reads or interprets it. Records still buffered for the old epoch are committed to it first. The new epoch is numbered above every epoch the ring has seen. On a part whose ring holds no slot, a fresh one or one whose whole ring was lost, the call first reads a header from each block of the log region, about 1.1 s on the Alliance part, and numbers the epoch above every page left there, starting from 1 on a fresh part.

The new epoch begins in the first good block at or after the old epoch's write head that holds none of its pages, so the log keeps sweeping forward. On a full region, it begins in the full epoch's own first block. Its metadata slot is the commit point: until the slot is on the part, the old epoch remains current and untouched. A new epoch is also the way out of a sealed epoch and of a log that stopped taking pages.

Requires a session with no read open. Returns false if the log is not initialized, there is no session, a read is open, the blob is too large, the buffered records could not be committed, no good block is left to begin in, or no slot in the metadata ring would take the new slot.

void nandlog_retrieve_epoch_details(void *blob, uint16_t length);

Copy the details of the selected epoch into blob, truncated to length. The buffer is zero-filled first, so a caller whose epoch has no details, or whose details no longer read whole, gets zeros rather than stale bytes.

Reading an earlier epoch

The metadata ring remembers earlier epochs, and their pages stay on the part until the write head reaches them. You can list them, select one, and read it with the ordinary read functions.

An earlier epoch is not preserved, only left alone. The write head sweeps forward from where the previous epoch stopped and erases each block just before it needs it, so the current epoch consumes an earlier one from its start. A block the log fails to erase is retired, and its pages are no longer read. A read of an earlier epoch returns whatever is left, and a page that has been swept over reads as a gap, exactly like one that rotted.

uint32_t nandlog_epoch_count(void);

How many epochs the metadata ring still describes, the current one included, up to NANDLOG_MAX_LISTED_EPOCHS (16). Returns 0 on a part where no epoch has been begun. It walks the ring back from the current epoch's slot, one slot read per slot pair, until it has 16 epochs or reaches the oldest slot. Nothing is cached between calls.

bool nandlog_epoch_info(uint32_t index, nandlog_epoch_info_t *info);

Describe the index-th epoch, newest first, so index 0 is always the current one. Returns false once the index runs past what the ring describes, or past 15. It costs the same walk as nandlog_epoch_count(), as far as that index.

typedef struct
{
   uint32_t epoch;               /* the epoch number                               */
   uint32_t created_timestamp;   /* always 0, since the log reads no clock         */
   uint32_t first_page;          /* the page it began at; sequence 0 is there, or  */
                                 /*   in the next good block if that one retired  */
   uint16_t details_length;      /* bytes of details in its slot                   */
   bool     is_current;          /* whether this is the epoch being written        */
   bool     is_sealed;           /* the current epoch takes no more pages          */
   bool     layout_unverified;   /* the bad-block table no longer lays the current */
                                 /*   epoch out as it was written                 */
} nandlog_epoch_info_t;

Put a creation time in the details blob if you need one. is_sealed means that the current epoch refuses records with NANDLOG_ERR_SEALED until a new one is begun. layout_unverified gives one cause of a seal: the bad-block table no longer lays the epoch's positions out as they were written. A read of such an epoch goes ahead, but may miss pages or serve a relocated page twice under one sequence number. The next epoch begun starts past every block that still holds a page of it. Both flags are false for an earlier epoch.

bool nandlog_select_epoch(uint32_t epoch);
void nandlog_select_current_epoch(void);

Point reads at another epoch, and back again. Writing is refused while an earlier epoch is selected, with NANDLOG_ERR_EARLIER_EPOCH, so a download cannot be mistaken for a place to put data. Retransmission and nandlog_retrieve_epoch_details() follow the selection too.

nandlog_select_epoch() requires a session and fails while a read is open. It returns false if the epoch is not among the 16 newest the ring describes, or if its slot cannot be read. Selecting the current epoch's number succeeds and selects the current epoch. nandlog_select_current_epoch() closes a read open over an earlier epoch, and ending the session also returns to the current epoch.

A read of an earlier epoch ends at the last page it wrote, which the log finds by reading page headers back from the end of the last block or two before its successor began. A page of another epoch is always a gap, never data. A read that yields nothing means the epoch has been overwritten, not that it never existed: nandlog_epoch_info() still describes it from the ring.

nandlog_begin_session();

for (uint32_t i = 0; i < nandlog_epoch_count(); ++i)
{
   nandlog_epoch_info_t info;
   if (nandlog_epoch_info(i, &info))
      printf("epoch %u%s\n", info.epoch, info.is_current ? " (current)" : "");
}

if (nandlog_select_epoch(previous))
{
   nandlog_retrieve_epoch_details(&details, sizeof(details));
   nandlog_begin_reading(0, 0);
   /* ... the usual read loop ... */
}

nandlog_end_session();                       /* back to the current epoch */

Writing

Records go into a page in RAM, and the log commits the page when the next record will not fit or when you flush. Committing a page programs it, reads it back, and moves it to another block if the part does not retain it.

nandlog_status_t nandlog_store_record(uint8_t record_type, uint32_t timestamp,
                                      const void *data, uint32_t data_length);

Append one record to the page being assembled in RAM. record_type and data are opaque to the log. The timestamp is only ever compared, never interpreted, so its epoch and units are yours. With NANDLOG_RECORD_FRAMING on, the record is prefixed with its 2-byte data length. Records are never split across pages.

A record may carry a timestamp earlier than the largest in its page by up to NANDLOG_TIMESTAMP_TOLERANCE_MS, in your timestamp units. That happens, for example, when a record stamped at the start of an event is stored after another writer's later record. The record keeps its timestamp and joins the page, whose time bounds widen to cover it, so a page need not be in time order. A larger step back means the time base moved, and commits the page first. A record stamped NANDLOG_NO_TIMESTAMP (0xFFFFFFFF) keeps that stamp, but its page's bounds count it as 0xFFFFFFFE.

The call that finds the page full commits it, so this call occasionally writes to flash. A call that commits nothing may instead erase the next block ahead of the write head. Records stored while a read is open are not served by that read.

Returns NANDLOG_OK if the record was stored, and otherwise why it was not:

StatusMeaning
NANDLOG_ERR_NOT_INITIALIZEDnandlog_init() has not succeeded.
NANDLOG_ERR_NO_EPOCHNo epoch has ever been begun on this part. Call nandlog_begin_epoch().
NANDLOG_ERR_DISABLEDnandlog_disable(true) is in force, or the log stopped writing because the part no longer retains pages.
NANDLOG_ERR_EARLIER_EPOCHAn earlier epoch is selected for reading.
NANDLOG_ERR_READINGA read is open, and storing this record meant committing a page.
NANDLOG_ERR_TOO_LARGEThe record can never fit in a page: its data exceeds nandlog_data_bytes_per_page() less 7 bytes (less 5 without framing).
NANDLOG_ERR_FULLEvery page of the log region belongs to the current epoch. Begin a new one.
NANDLOG_ERR_UNWRITABLEA commit this call needed failed, because no block would retain the page. The records already buffered for it are lost too. Later records get NANDLOG_ERR_DISABLED until a reboot or a new epoch.
NANDLOG_ERR_SEALEDThe epoch is sealed and takes no more pages until a new one is begun. Reads go on.

A record that is not stored is counted in records_refused, and buffered records that a failed commit loses are counted in records_lost. NANDLOG_ERR_FULL and NANDLOG_ERR_UNWRITABLE can also come from the erase-ahead of a call that commits nothing: if that erase fails and leaves the buffered records nowhere to go, they are counted lost and this record is refused.

A boot seals an epoch when its list of passed-over positions is nearly full, or when its metadata or layout can no longer be verified. The seal is recorded in the epoch's slot, so every later boot refuses records too and calls nandlog_port_unwritable(). Durability lists the causes.

nandlog_status_t nandlog_flush(bool write_partial_pages);

Commit what is buffered. A page is committed automatically as soon as the next record will not fit, so this is needed only to force out a partial page, on a timer or at shutdown. Pass false to commit only if a whole page has accumulated.

A call that commits nothing erases the next block ahead of the write head, if one is due, so an idle nandlog_flush(false) is a good place for that work. A disabled log skips the erase.

Returns the outcome of the commit, or NANDLOG_OK if there was nothing to commit. It refuses with NANDLOG_ERR_NOT_INITIALIZED, NANDLOG_ERR_SEALED, NANDLOG_ERR_DISABLED (only when the log stopped writing on its own), NANDLOG_ERR_EARLIER_EPOCH, or NANDLOG_ERR_READING, the last whenever a read is open. An erase-ahead that leaves the buffered records nowhere to go counts them lost and returns NANDLOG_ERR_FULL or NANDLOG_ERR_UNWRITABLE.

bool nandlog_has_buffered_data(void);

Whether any records are sitting in RAM, not yet committed.

Reading

A read is opened over the selected epoch with nandlog_begin_reading(), which fixes its span of pages, and then drained page by page. Two further functions fetch single pages without an open read: by sequence number, or counting back from the newest page.

The read functions describe each page in a nandlog_page_header_t. The fields a caller uses are seq, first_timestamp and last_timestamp (the smallest and largest record timestamps in the page), record_count, payload_length, and magic, which is NANDLOG_PAGE_MAGIC_FRAMED for framed records and NANDLOG_PAGE_MAGIC for opaque ones. On-Flash Format gives the byte layout. A payload buffer needs room for NANDLOG_MAX_DATA_BYTES_PER_PAGE bytes, and nothing past the payload is written to it.

void nandlog_begin_reading(uint32_t starting_timestamp, uint32_t ending_timestamp);

Open a read over the selected epoch, bounded by timestamp. Zero for either bound means "from the beginning" or "to the end". Both bounds are resolved here, so nothing downstream has to seek again.

Pages are selected by the time bounds their headers carry: from the first page whose largest timestamp reaches the start, to the last page whose smallest timestamp is within the end. Both bounds err outward, so every page holding a record within the window is selected. The read may also include pages whose records straddle the window, or pages between two that bracket it across a backward step of the time base. A window that ends before the first page found for its start selects nothing.

Records still buffered for the current epoch are committed first, as nandlog_flush(true) would, so a read serves only what is on the part. That is what makes a sequence number an identity: what a read serves under an epoch and sequence number is what that sequence number holds from then on, or a gap if the part later loses the page. It is never given to other records, across any number of reboots and power cuts.

A start bound reads page headers until the first page that reaches it, and an end bound reads every page header in the epoch, both with the lock held. An unbounded read needs no header reads.

Requires a session, and does nothing outside one. While a read is open, committing a page is refused, because an open read keeps its place by physical page and a failed commit could move the head's block. To keep logging through a long download, see below.

void nandlog_end_reading(void);

Close a read, whether or not it ran to completion. nandlog_end_session() implies it, and a read also closes itself after its last page.

void nandlog_read_span(uint32_t *num_pages, uint32_t *num_bytes);

Measure what the open read has still to yield: how many pages, including any that turn out to be unreadable, and how many payload bytes they hold. Either pointer may be NULL. Both are zero if no read is open. Pages are counted over the blocks the part holds good, so a retired block in the epoch adds nothing.

The byte total costs a read of every page in the span, which doubles the flash traffic of a download. Pass NULL for num_bytes unless you need the figure exactly; the page count is arithmetic.

The byte total runs the same checks that serve the pages, so a host can size a receive buffer from it. The one exception is a page that a power cut left with cells that read differently from one read to the next, which can pass its checks on one pass and fail them on the other.

uint32_t nandlog_retrieve_next_page(uint8_t *buffer, nandlog_page_header_t *header);

Take the next page of the open read, copying its payload into buffer and returning its length. Pass NULL for header to ignore it. The header's magic is the page's own record format, which differs from this build's only if NANDLOG_RECORD_FRAMING changed during the epoch.

Zero means a gap, not the end of the read. A gap is a page that could not be read, a position the log passed over, or a tombstone (the placeholder a relocation leaves for a page that was already unreadable). The header still carries the sequence number, so the host can ask for the page again. Zero also comes back once the read has closed, so loop over the count from nandlog_read_span().

uint32_t nandlog_retrieve_page_by_seq(uint32_t seq, uint8_t *buffer,
                                     nandlog_page_header_t *header);

Fetch one page of the selected epoch by sequence number, so that a host can re-request what it lost. No read need be open, so a host can ask after a read has run to its end. header must not be NULL. Returns zero for a gap, with a header that carries the sequence number but no time bounds or record count.

In the current epoch a sequence number is a position, so this costs one page read. In an earlier epoch, a block retired since may have shifted positions, so the log checks its first guess and falls back to a binary search over page headers. What comes back is what any read served under that sequence number, or a gap.

uint32_t nandlog_read_recent_page(uint32_t pages_back, uint8_t *buffer,
                                  nandlog_page_header_t *header, bool *end_of_epoch);

Walk backwards through the selected epoch, newest page first: pages_back 0 is its newest page, which for the current epoch is the page just below the write head. It works independently of any open read. Zero means that page could not be read, which is not the end of the log. *end_of_epoch is the signal to stop: it is set on the epoch's first page, whether or not that page could be read, and when pages_back runs past it. buffer, header, and end_of_epoch may each be NULL. The header is filled in only when the page's own header reads valid.

bool nandlog_framed_next_record(const uint8_t *payload, uint32_t length, uint32_t *offset,
                                const uint8_t **record, uint32_t *record_bytes);

Step through the records of a payload whose page header carries NANDLOG_PAGE_MAGIC_FRAMED. Set *offset to zero and call until it returns false, which it does at the end of the payload or at a record that would run past it. Each call points *record at [type:1][timestamp:4][data] and sets *record_bytes to 5 plus the data length. record and record_bytes may be NULL.

uint32_t nandlog_crc32(uint32_t crc, const void *data, uint32_t length);

The CRC-32 the log writes and checks, continued over length more bytes exactly as Python's zlib.crc32(data, crc) continues one. Pass 0 to begin. A served page's payload_crc is nandlog_crc32(0, buffer, length). With NANDLOG_PORT_CRC32 set it calls nandlog_port_crc32(), and otherwise it runs the library's software, which needs neither nandlog_init() nor the lock. nandlog_port.h also declares nandlog_crc32_software(), the same CRC always in software, for a port that checks its engine against it.

Logging through a long download

While a read is open, a record that would commit a page is refused with NANDLOG_ERR_READING. As a result, a download held open across a slow link stops logging once a page's worth of records is buffered. To keep logging, open the read only long enough to take its span (the first page's sequence number and the page count), close it, and fetch the rest by sequence number. That needs no open read, and it finds each page afresh, even after a relocation of the head's block.

uint8_t page[NANDLOG_MAX_DATA_BYTES_PER_PAGE];
nandlog_page_header_t header;
uint32_t first = 0, count = 0;

nandlog_begin_session();
nandlog_begin_reading(start_ms, end_ms);       /* commits what is buffered, and resolves the window */
nandlog_read_span(&count, NULL);
if (count)
{
   uint32_t length = nandlog_retrieve_next_page(page, &header);
   first = header.seq;                         /* a gap carries its sequence number too: send it */
}
nandlog_end_reading();

for (uint32_t seq = first + 1; seq < (first + count); ++seq)
{
   uint32_t length = nandlog_retrieve_page_by_seq(seq, page, &header);
   /* zero is a gap, and header.seq says which; records stored meanwhile commit as usual */
}
nandlog_end_session();

The window is resolved once, by the short read, so nothing is lost there. Three caveats remain. First, a gap fetched by sequence number comes back with a bare header, without the time bounds or record count an open read reports when a page's header survives but its payload does not. Second, an exact byte total has to be taken with nandlog_read_span() before the read is closed. Third, this works only for the current epoch, because writing stays refused while an earlier one is selected. Holding the session around the loop keeps the part awake between fetches, and logging does not mind it.

Retransmission

Sequence numbers are contiguous within an epoch, so a host knows exactly which pages it is missing. These functions collect the host's list and serve the pages back, from the epoch selected at the time. Like nandlog_retrieve_page_by_seq(), they need no open read.

void nandlog_retransmit_clear(void);
uint32_t nandlog_retransmit_add(const uint32_t *seqs, uint32_t count);
uint32_t nandlog_retransmit_count(void);

Collect the sequence numbers a host reports missing, across as many calls as it takes. nandlog_retransmit_add() returns the number now held, and anything beyond NANDLOG_MAX_RETRANSMIT_PAGES (256) is dropped. nandlog_init() also clears the list.

uint32_t nandlog_retransmit_total_bytes(void);

The exact payload bytes the requested pages will deliver, for a host sizing a receive buffer. It is exact in the same sense as nandlog_read_span()'s total, and costs a read of each requested page.

uint32_t nandlog_retrieve_retransmit_page(uint32_t index, uint8_t *buffer,
                                          nandlog_page_header_t *header);

Serve the index-th requested page, as nandlog_retrieve_page_by_seq() would. header must not be NULL. A page that is still unreadable comes back with zero length and its sequence number. An index past the end also yields a zero-length page rather than nothing, so the host can tell "still missing" from "never answered".

Diagnostics

Two functions report the part's health and the log's running totals. Both answer from RAM, so they cost nothing on the bus.

uint32_t nandlog_bad_block_count(void);

How many blocks across the metadata ring and the log region are retired, factory-marked and grown alike. Over a part's life, a count that climbs steadily means the part is nearing the end of its endurance, and a count that jumps is worth investigating.

void nandlog_get_stats(nandlog_stats_t *stats);

Copy out the running totals since nandlog_init(). Records are counted at the API, and pages and blocks on the part.

typedef struct
{
   uint32_t records_stored;      /* nandlog_store_record() calls that returned NANDLOG_OK  */
   uint32_t records_refused;     /* calls that returned anything else                     */
   uint32_t records_lost;        /* stored in RAM, but their page could not be committed  */
   uint32_t pages_committed;     /* written and verified by reading back                  */
   uint32_t pages_relocated;     /* moved out of a failing block, tombstones included     */
   uint32_t tombstones_written;  /* relocated pages that were already unreadable          */
   uint32_t positions_skipped;   /* sequence numbers the last boot passed over            */
   uint32_t blocks_retired;      /* blocks the log retired, persistently                  */
   uint32_t reads_at_ecc_limit;  /* reads the part corrected only at the limit of its ECC */
} nandlog_stats_t;

Records still in RAM at a reset or a nandlog_deinit() are not counted as lost. A page the part corrects only at the limit of its ECC is still delivered, but the next bit to fail will not be corrected, and nothing rewrites a log page in place. A part that keeps adding to reads_at_ecc_limit is wearing out. The count includes reads of metadata slots, and a boot that reads its newest slot at the limit writes that slot again (see Durability).

Recovery

One utility exists for a part whose bad-block table has gone wrong. Most applications never call it.

void nandlog_reset_bad_block_table(void);

Discard the persisted bad-block table, so that the next boot rebuilds it. Call it only after nandlog_init() has succeeded. What it can achieve depends on the part. The Alliance driver rebuilds from the factory markers and from the markers it writes into every block it retires, so a retirement survives the reset, and it keeps the table if any listed block's marker does not read back. The Winbond part remaps blocks in hardware and cannot forget them, so its driver keeps the table.

The table in RAM stands until the reboot, so logging can carry on meanwhile. If the rebuilt table lays the current epoch out differently from what its metadata slot recorded, the next boot seals the epoch, and you must begin a new one. The outcome is reported only through nandlog_port_log(). See Durability for how retirement works.

Version macros

nandlog.h versions the library and the on-flash format separately. This release is version 1.1 of the library and version 2 of the format.

#define NANDLOG_VERSION_MAJOR    1
#define NANDLOG_VERSION_MINOR    1
#define NANDLOG_VERSION_AT_LEAST(major, minor)   /* true if this build is that version or later */

#define NANDLOG_FORMAT_VERSION   2               /* recorded in every metadata slot */

The major number changes when something you built against has to change to keep working, so an application can refuse to build against the wrong one with #if (NANDLOG_VERSION_MAJOR != 1). The minor number changes for additions, such as new functions, options, chip drivers, or a new on-flash format, and NANDLOG_VERSION_AT_LEAST() tests for them. NANDLOG_FORMAT_VERSION versions what a build writes on the part, and moves independently of the library version. See On-Flash Format.