nandlog v1.1

Getting Started

This guide takes a firmware project from nothing to logging records on a SPI NAND part and reading them back. It also holds the reference for every configuration option.

nandlog adds three C files and a few headers to your build, with no build system of its own. You need a C99 compiler, a little-endian microcontroller, and one of the supported parts on a SPI bus. The work falls into eight steps:

  1. Install: add the library, one chip driver, and your port to the build.
  2. Configure: review the options in nandlog_conf.h.
  3. Port: implement thirteen small platform functions.
  4. Bring up: call nandlog_init() at boot.
  5. Begin an epoch: once on a fresh part, and again whenever you want a fresh log.
  6. Log: store records, and flush them on a timer.
  7. Read: open a read over a time window and take its pages one at a time.
  8. Check: verify a dump with the reference parser, and run the simulator.

Most of the steps take a few lines of code. The exceptions are the port, which the Porting page covers in full, and the configuration, whose defaults suit most devices. If you want to see the API in use, read Sections 4 through 7. If you are sizing a build or tuning the log for your device, read Section 2.

1. Install

Add the repository to your project, for example as a submodule:

git submodule add https://github.com/hedgetechllc/nandlog.git external/nandlog

Then add three source files to your build:

FileNotes
nandlog.cAlways.
chips/nandlog_chip_<PART>.cExactly one, for the part you have fitted: AS5F18G04SND (Alliance) or W25N01GWZEIG (Winbond). See Chip Drivers.
your nandlog_port.cCopy the template from the repository root into your own tree, and fill in its stubs (Section 3).

Put the repository root and chips/ on the include path. Both drivers have run on hardware (see Testing).

Build with -fno-strict-aliasing. This flag is required. The log reads page and metadata headers out of byte buffers by pointer cast, and without the flag an optimizer may reorder or drop those reads.

2. Configure

Every option lives in nandlog_conf.h, with the default shown below. The defaults suit a device that logs continuously and reboots now and then, so many projects change nothing here. The options that most often need a decision are NANDLOG_PASS_OVER_HEAD_AT_BOOT (Section 2.1), NANDLOG_BOOT_SALT, and NANDLOG_LOG_LEVEL.

OptionDefaultUnit and limitsMeaning
NANDLOG_HAS_HARDWARE10 or 1Whether a part is fitted. At 0, every function compiles to a stand-in that accepts everything and returns nothing, so the application needs no conditionals of its own.
NANDLOG_MAX_PAGE_SIZE_BYTES4096Bytes; at least the fitted part's page sizeThe largest page the build sets RAM aside for. nandlog.c keeps two buffers of this size, and a part with a larger page is a compile error in its driver.
NANDLOG_MAX_SPARE_SIZE_BYTES256Bytes; at least the fitted part's spare areaThe same budget for the spare area.
NANDLOG_BLOCK_ERRORS_BEFORE_REMOVAL3Erase attempts; at least 1Erase attempts on one block before the log retires it. A failed program is never repeated, so a single program failure retires its block.
NANDLOG_ERASE_AHEAD_BLOCKS2Blocks; 0 or moreBlocks kept erased ahead of the write head, so that a commit does not wait on an erase. Every boot erases them again. At 0, each block is erased only when the write head reaches it.
NANDLOG_PAGE_PLACEMENT_ATTEMPTS3Blocks; at least 1Blocks one page commit may try, its own included, before the log concludes that the part will not hold the page and stops writing. Each further block costs an erase and a block's worth of page copies.
NANDLOG_MAX_EPOCH_DETAILS_BYTES512Bytes; at most the page size less 320 (3,776 on a 4 KB page, 1,728 on a 2 KB page)The largest details blob nandlog_begin_epoch() accepts. Every byte it allows shortens the epoch's list of passed-over positions, as explained below.
NANDLOG_TIMESTAMP_TOLERANCE_MS250Your timestamp units; 0 or moreHow far a record's timestamp may fall below the largest in its page and still join that page. A larger step back commits the page first, because the log takes it as a change of time base.
NANDLOG_PASS_OVER_HEAD_AT_BOOT00 or 1Whether a boot that finds the write head part-way into a block skips the head's page rather than program it. See Section 2.1.
NANDLOG_BOOT_SALT0Any 32-bit value, evaluated at each bootA value that differs from boot to boot, such as a boot counter that survives a reset or a random number. The write-head search uses it to vary where its first four probes fall. Any value is safe.
NANDLOG_RECORD_FRAMING10 or 1Whether each record carries a 2-byte data length, so that a reader can walk a page without knowing your record types.
NANDLOG_BUSY_POLL_INTERVAL_US10µsThe delay between polls of the part's BUSY bit.
NANDLOG_BUSY_TIMEOUT_POLLS50000Polls; at least 1Polls before the driver declares the part dead and calls nandlog_port_fatal(). The wait lasts at least 0.5 s at the defaults, and longer in practice (see below).
NANDLOG_CHIP_PAGE_COPY10 or 1Whether a relocated page may move inside the chip instead of across the bus. Each driver decides for its own part, so set 0 only for a part that mishandles the internal copy.
NANDLOG_PORT_CRC3200 or 1Whether your port computes the log's CRC-32 in nandlog_port_crc32(), for example on a hardware engine, instead of the library's software. See Porting.
NANDLOG_CRC_TABLE_IN_RAM10 or 1Whether the software CRC's lookup table lives in RAM (1 KB, or 4 KB with slicing-by-4) rather than in flash. It is faster where flash reads have wait states.
NANDLOG_CRC_SLICE_BY_400 or 1Whether the software CRC takes four bytes per step through four tables. It is about twice as fast, for 3 KB more table.
NANDLOG_LOG_LEVEL30 to 3Which messages reach nandlog_port_log(): 0 none, 1 errors, 2 errors and warnings, 3 all of them, including the boot's INFO: lines. Messages above the level are compiled out, and the library behaves the same at every level.

Setting options. Edit nandlog_conf.h in place. nandlog.h includes it from its own directory, so a copy elsewhere on the include path is not picked up. Ten options can also be set from the compiler command line (for example, -DNANDLOG_LOG_LEVEL=1), because the header defines them only when they are not already defined: NANDLOG_HAS_HARDWARE, NANDLOG_ERASE_AHEAD_BLOCKS, NANDLOG_PASS_OVER_HEAD_AT_BOOT, NANDLOG_BOOT_SALT, NANDLOG_RECORD_FRAMING, NANDLOG_CHIP_PAGE_COPY, and the four CRC and diagnostics options. Removing one of the other eight is a named compile error.

RAM and CRC. Setting the two MAX_ budgets larger than your part needs costs only unused RAM. The Performance page lists what the library and each driver allocate and what each CRC option costs on hardware.

Epoch details and the seal threshold. An epoch's metadata slot keeps the details blob and the list of positions the epoch has passed over in one page, so the list gets whatever room the details leave. Each entry is a run of consecutive positions in 4 bytes. At the default of 512 bytes, the list has room for 880 runs on a 4 KB page and 368 on a 2 KB page. The log seals an epoch once fewer than four runs would remain free, which is after 876 runs on a 4 KB page (364 on a 2 KB page). A sealed epoch can still be read, but it refuses records with NANDLOG_ERR_SEALED until you begin a new epoch. The limit of the page size less 320 bytes keeps room for at least 64 runs: a larger value is a compile error, and nandlog_init() refuses a fitted part whose page leaves less room. Durability explains when positions are passed over.

Changing options under a written log. If a firmware update lowers NANDLOG_MAX_EPOCH_DETAILS_BYTES, the next boot seals an epoch whose slot carries longer details, or a longer list, than the new value leaves room for. Its pages stay readable, and logging resumes when you begin a new epoch. Begin a new epoch, too, whenever an update changes NANDLOG_RECORD_FRAMING, because an offload stream states a single record format for all of its pages (see On-Flash Format).

Busy timeout. The port offers no clock, so the timeout is a count of polls rather than a time. Each poll is one status read followed by a delay of NANDLOG_BUSY_POLL_INTERVAL_US, so the wait lasts at least polls × interval (0.5 s at the defaults) plus the time of the status reads themselves. On the Apollo4 Plus port, each poll takes about 47 µs in all, so the defaults wait about 2.4 s before the driver gives up (see Porting). Allow for that in your watchdog.

2.1 Choosing NANDLOG_PASS_OVER_HEAD_AT_BOOT

This option decides what a boot does with the page at the write head when the head is part-way into a block. A power cut during a commit can leave that page looking erased while it holds partial charge. With the option off, the log programs that page again. With it on, the boot skips the page, so no page of the log region is ever programmed twice. Durability describes the mechanism and the risk it removes.

The cost is paid at every boot that finds the head part-way into a block, clean or not, because nothing records a clean shutdown. Each such boot writes a metadata slot, spends one sequence number, and takes one run of the epoch's passed-over list unless nothing was committed since the boot before. The epoch is therefore sealed after about 876 such boots on a 4 KB page (364 on a 2 KB page), and logging stops until the application begins a new epoch. To choose, estimate how many boots an epoch sees with something committed between them.

Your deviceSetting
Rarely reboots (mains power, a weekly restart), or begins a new epoch for every mission, session, or download, and can lose power during a program.On. The boots stay well short of the limit, and no page is programmed twice.
Reboots often while it logs, such as a sensor that resets every minute. At one boot a minute, 876 boots take under 15 hours.Off. With it on, the epoch would soon be sealed.
Rarely loses power during a program, because a hold-up capacitor or brown-out detection stops logging first.Off. The exposure is a power cut during a commit, and there are almost none.
Reboots often, but begins new epochs often too.On, if the application begins a new epoch before the count reaches about half the limit, and handles NANDLOG_ERR_SEALED by beginning one.

3. Port

The port connects the library to your SPI peripheral, pins, mutex, delays, and diagnostics. Copy nandlog_port.c from the repository root into your own tree, delete its #error line, and implement its thirteen functions, or fourteen if you hand the log's CRC to a hardware engine. Each stub states what the library assumes of it. The Porting page covers the interface, the common mistakes, and a complete example for the Apollo4.

4. Bring the log up

Call nandlog_init() once at boot, before any other call:

#include "nandlog.h"

if (!nandlog_init())
{
   /* The port would not open, or the part did not answer. Make no other nandlog call. */
   return;
}

nandlog_init() opens the port, identifies the part, and loads its bad-block table. It then recovers the current epoch from the metadata ring and finds the write head, the position where the next page will go. On the Alliance part, a warm boot takes 82–89 ms with 35 blocks in its bad-block table, and each further block adds about 0.43 ms (see Performance). A second call returns at once. For a build that only needs to know whether a part is present, nandlog_probe() asks the part without bringing the log up.

5. Begin an epoch

An epoch is one generation of the log, numbered by the library, with its own sequence numbering of pages from 0. Reads cover one epoch at a time. A part on which no epoch has ever been begun accepts no records: nandlog_store_record() returns NANDLOG_ERR_NO_EPOCH rather than write somewhere a reboot would not find. Begin the first epoch when the part is fresh:

nandlog_begin_session();
if (nandlog_epoch_count() == 0)                 /* a fresh part: no epoch yet */
   nandlog_begin_epoch(&details, sizeof(details));
nandlog_end_session();

A part written by 1.0 or earlier also reports no epoch, and is safe to begin one on the same way. Its data is not readable by this release, so offload it first (see Format versions).

The details blob is yours, up to NANDLOG_MAX_EPOCH_DETAILS_BYTES. The log stores it, checksums it, and hands it back, but never looks inside, so it is a good place for a device ID, a start time, or a mission name. Begin a new epoch whenever you want a fresh log (for example, at the start of each mission), and whenever a record comes back NANDLOG_ERR_FULL or NANDLOG_ERR_SEALED. Records still buffered are committed to the old epoch first. The old epoch's pages stay on the part until the write head sweeps over them, and you can still read them by selecting that epoch (API Reference).

A session keeps the part powered across a run of calls instead of waking and sleeping it around each one. Beginning an epoch, selecting an epoch, and opening a read require one. Ordinary logging does not. Sessions do not nest.

6. Log records

const nandlog_status_t status = nandlog_store_record(RECORD_SAMPLE, now_ms, &sample, sizeof(sample));
if (status != NANDLOG_OK)
{
   /* Not stored. NANDLOG_ERR_FULL or NANDLOG_ERR_SEALED: begin a new epoch.
      NANDLOG_ERR_READING: a read is open and this record needed a page committed.
      NANDLOG_ERR_TOO_LARGE: the record can never fit in a page. */
}

The record type and the data are opaque to the log. You may ignore the status, since nandlog_get_stats() counts refused records either way. The API Reference lists every status.

Timestamps. Every record carries a 32-bit timestamp that you supply. The log reads no clock and never interprets the value, so its units and starting point are yours (for example, milliseconds since boot or Unix seconds). Each page header records the smallest and largest timestamps in its page, and a read uses them to select a time window (Section 7). Records need not arrive in time order. A step back of up to NANDLOG_TIMESTAMP_TOLERANCE_MS, in your units, stays in the same page as stamped, which suits records from several sources whose clocks disagree slightly. A larger step means the time base moved, as after a clock reset, so the log commits the current page first and never mixes two time bases in one page. A record with no meaningful time can carry NANDLOG_NO_TIMESTAMP.

Records collect in a page in RAM. Most calls only copy the record, but the call that finds the page full commits it to flash first. On the Alliance part, storing a 32-byte record takes about 17 µs, and the call that commits a page about 3 ms. Records are never split across pages. With framing on, each record costs 7 bytes of overhead, so the largest record holds nandlog_data_bytes_per_page() less 7 bytes of data: 4,057 bytes on a 4 KB page.

A partial page reaches flash only when you ask for it:

nandlog_flush(true);                       /* commit whatever is buffered  */
if (nandlog_has_buffered_data()) { ... }   /* anything unwritten in RAM?   */

Call nandlog_flush(true) on a timer and at shutdown. A record is durable once the call that commits its page returns, and not before. Until then, up to one page of recent records sits in RAM, and a reset loses it. Durability states the guarantee in full.

Call nandlog_flush(false) when idle. A call that commits no page is where the log erases the next block ahead of the write head. An idle flush gives that erase a place to run, so that no single call has to both program a page and erase a block.

If the part stops retaining pages, or a boot finds the epoch sealed, the library calls your nandlog_port_unwritable() and refuses further records. Reads still work.

7. Read it back

A read covers the selected epoch, by default the current one, within a time window. Open it, ask how many pages it holds, and take them one at a time:

uint8_t page[NANDLOG_MAX_DATA_BYTES_PER_PAGE];
uint32_t num_pages = 0;

nandlog_begin_session();
nandlog_begin_reading(start_ms, end_ms);     /* 0 for either bound means "no bound" */
nandlog_read_span(&num_pages, NULL);

for (uint32_t i = 0; i < num_pages; ++i)
{
   nandlog_page_header_t header;
   const uint32_t length = nandlog_retrieve_next_page(page, &header);
   if (length == 0)
   {
      /* A gap, not the end of the read: header.seq still says which page it was. */
   }
}

nandlog_end_session();                       /* also ends the read */

Loop over the page count, because nandlog_retrieve_next_page() also returns zero once the read is over. Both time bounds err outward, so the read may include a little data outside the window for you to filter, but never drops data inside it. Opening a read commits any buffered records first, so the read serves only what is on the part.

Writing a page is refused while a read is open, so a record that would commit one returns NANDLOG_ERR_READING. To keep logging through a long download, follow Logging through a long download.

Pass NULL for the byte total unless you need it exactly. The page count from nandlog_read_span() is arithmetic, but an exact byte total costs a read of every page in the span, which doubles the flash traffic of a download.

Walking the records in a page. With NANDLOG_RECORD_FRAMING on, you can walk a payload without knowing your record types. Inside the read loop above:

uint32_t offset = 0, record_bytes = 0;
const uint8_t *record = NULL;

while (nandlog_framed_next_record(page, length, &offset, &record, &record_bytes))
{
   const uint8_t type = record[0];
   uint32_t timestamp;
   memcpy(&timestamp, record + 1, sizeof(timestamp));
   const uint8_t *data = record + 5;
   const uint32_t data_length = record_bytes - 5;
}

8. Check your work

The reference parser in tools/ reads a raw dump of the part, or an offload stream from your device, and verifies every CRC independently of the device that wrote it:

python3 tools/nandlog_parse.py image dump.bin --page-size 4096 --spare-size 256
python3 tools/nandlog_parse.py stream offload.bin --json

The image defaults suit the Alliance part. Pass --page-size 2048 --spare-size 64 for the Winbond part, and --spare-size 0 for a dump of the main array only. On-Flash Format describes the parser's output.

The simulator in sim/ runs the real library and chip driver against an emulated part on your host. The first command runs the test suites. The second runs fixed sequences of calls, cuts power at every program and erase of each, and audits the log after every cut. The third lays down every combination of page states just below the write head on a small emulated part, and checks what each boot makes of it:

make -C sim
make -C sim campaign
make -C sim exhaustive

Testing explains what each target covers.

Next steps