nandlog v1.1

Porting

How to connect nandlog to your microcontroller, bus, and RTOS. A port is the one file of platform code you write, and this page is for whoever writes it.

Copy nandlog_port.c from the repository root into your own tree, delete its #error line, and fill in its thirteen functions. Everything else in the library is platform-independent, and the chip driver reaches the part only through this file's two transfer functions.

The thirteen functions bring the peripheral up and down, move bytes over the bus, serialize the library against itself, drive the write-protect pin and the peripheral's power, and report: a diagnostic log, a fatal fault that must not return, and a softer notice that the log has stopped taking records. A build that sets NANDLOG_PORT_CRC32 adds nandlog_port_crc32(), which computes the log's CRC-32 on a hardware engine.

The worked example is the port that has run the 1.0 library on an Ambiq Apollo4 Plus under FreeRTOS, with the Alliance AS5F18G04SND on a 48 MHz SPI bus.

If you are writing a port, read The interface and Things to get right, and use the Apollo4 example as a model. Read The CRC hook only if your MCU has a CRC engine you want to use. Checking your port is a bring-up checklist.

The interface

nandlog_port.h declares the functions below, and the template in nandlog_port.c states each one's contract in a comment. nandlog_probe() and nandlog_init() take the lock and then call nandlog_port_init() before anything touches the part.

FunctionContract
nandlog_port_initConfigure the SPI peripheral (mode 0, MSB first) and its pins, and drive write-protect and HOLD inactive. False stops the log coming up.
nandlog_port_deinitRelease the peripheral, leaving a state nandlog_port_init() can start from again.
nandlog_port_transfer_readSend a command byte and address bytes, then clock data in, with chip-select asserted throughout.
nandlog_port_transfer_writeThe same exchange, clocking data out.
nandlog_port_lock, nandlog_port_unlockSerialize the library against itself. Empty in a single-threaded system.
nandlog_port_write_enableDrive the write-protect pin. True permits programming and erasing.
nandlog_port_powerWake the host's peripheral, or return it to its lowest-power state.
nandlog_port_logA printf-style sink for diagnostics. Must not call back into nandlog.
nandlog_port_delay_usA busy-wait that paces the BUSY poll. Must be cheap and must not yield.
nandlog_port_delay_msA coarse delay while the part comes up at probe time. May yield.
nandlog_port_fatalThe part has stopped answering. Must not return.
nandlog_port_unwritableThe part answers, but the log has stopped taking records. Not urgent.
nandlog_port_crc32Only with NANDLOG_PORT_CRC32 set to 1: the log's CRC-32, exactly as zlib.crc32() computes it. See below.
nandlog_port_crc32_hardwareOptional, and never called by the library: whether nandlog_port_crc32() runs on hardware.

The log wakes the peripheral with nandlog_port_power(true) around each operation and puts it back to sleep afterward, except inside a session, where it stays awake. Putting the part itself to sleep is the chip driver's job (nandlog_chip_low_power()). NANDLOG_LOG_LEVEL sets which messages reach nandlog_port_log(), and the rest are compiled out with their text. The header also gives the port nandlog_crc32_software(), the library's own CRC-32 under the same contract as the hook.

Things to get right

Most of the contract is plain, but five points cause failures that the log cannot diagnose, because the bus traffic looks normal.

The transfer shape is command, address, data

Both transfer functions take (command, address, address_length, buffer, length). The command byte and the address bytes go out first, then the data, with chip-select asserted across the whole exchange.

Nothing above this file names a bus. The same shape serves SPI in one, two, four, or eight lanes, or a parallel ONFI bus whose port drives the command and address latches.

The lock protects the part's cache register

A single-threaded system can leave both lock functions empty. Anything else must supply a real mutex, because reading a page is a sequence of commands against the one cache register inside the part: latch the page, then clock it out. Two callers that interleave those sequences read each other's pages, and nothing about the bus traffic looks wrong.

Every public function takes the lock for its whole duration and does its work in a _locked internal, so a caller never holds it and the calls never nest. Release the lock under the same condition you took it. If the lock cannot be taken in every context the library is called from, such as before the scheduler starts or in an interrupt, detect that case and skip the lock rather than block or fail.

One lock covers everything, so a call that only buffers a record can wait behind a long one. A bounded nandlog_begin_reading() reads page headers across the epoch, at about 300 µs each on the Apollo4 Plus, so over a full epoch of the Alliance part (about 260,000 pages) it holds the lock for over a minute. A byte-exact nandlog_read_span() reads whole pages and takes several minutes. A task that logs on a deadline should not share the log with such a read, or should buffer its own records while one runs (see Long downloads).

Write-protect polarity is a board property

Most WP# pins are active low, but a board may invert one, so the level that permits programming depends on the board, not the part. Get it backwards and every program fails silently.

The two failure callbacks are not the same

nandlog_port_fatal() means the part has stopped answering. The supplied drivers call it when BUSY does not clear within NANDLOG_BUSY_TIMEOUT_POLLS polls NANDLOG_BUSY_POLL_INTERVAL_US apart (at least 0.5 s by default, plus the time of the reads), and a port calls it when a transfer fails past retrying. What happens next is yours: record the reason somewhere that survives, then reset or halt. It must not return, because the header declares it with NANDLOG_NORETURN (the GCC and Clang attribute, or C11's _Noreturn), and the compiler may drop the code after the call. To keep the system running without storage, reset into a configuration that does not initialize the log.

nandlog_port_unwritable() is the softer failure. The part still answers, but the log has stopped taking records, for one of these reasons:

Nothing here is urgent, and nothing here should reset the system. Leave a breadcrumb the next boot can find, or tell whoever can begin a new epoch. Durability lists every failure and what the log does about it.

Delays and logging run inside the library's work

nandlog_port_delay_us() runs between status polls, dozens of times in each program or erase, so make it a cheap busy-wait that never yields. nandlog_port_log() can be reached from inside a page commit, so it must not call back into nandlog.

The CRC hook

Every page the log writes carries two CRC-32s, one over its header and one over its payload, and every page it reads is checked against both. In software, the library's table-driven loop takes 467 µs for a 4,064-byte payload on the Apollo4 Plus at 96 MHz (see Performance). A host with a CRC engine can take this over: set NANDLOG_PORT_CRC32 to 1 and implement nandlog_port_crc32(), and every CRC the log writes or checks comes from there. The contract, from nandlog_port.h:

A wrong CRC goes to the part as it is. The commit's read-back compares the page with what was meant to be written, CRC included, so nothing in the log can tell. The page then fails its check at every read and is served as a gap. Before its first use, an engine has to agree with nandlog_crc32_software() on known vectors, including a continuation split at an odd offset, and it should be dropped for good if it ever misbehaves.

The template in nandlog_port.c carries a commented sketch of a hook, and the Apollo4 port below is a complete one. If your MCU has no engine, NANDLOG_CRC_SLICE_BY_4 makes the software about twice as fast for 3 KB more table (see Configuration).

Worked example: Ambiq Apollo4 Plus under FreeRTOS

This is the port the SociTrack firmware uses, built on the Ambiq HAL's IOM peripheral. It runs SPI mode 0 at 48 MHz, and it is the port the 1.0 library's hardware measurements ran on. The pin names, the print() sink, and the system_* calls belong to the surrounding firmware, not to nandlog. The excerpts follow the real file, except where a comment says they are abbreviated.

Bring-up

static void *spi_handle;
static SemaphoreHandle_t log_mutex;
static StaticSemaphore_t log_mutex_buffer;

bool nandlog_port_init(void)
{
   const am_hal_iom_config_t spi_config =
   {
      .eInterfaceMode = AM_HAL_IOM_SPI_MODE,
      .ui32ClockFreq = AM_HAL_IOM_48MHZ,
      .eSpiMode = AM_HAL_IOM_SPI_MODE_0,
      .pNBTxnBuf = NULL,
      .ui32NBTxnBufLength = 0
   };

   // Configure and assert the Write-Protect and Hold pins to disable them
   configASSERT0(am_hal_gpio_pinconfig(PIN_STORAGE_WRITE_PROTECT, am_hal_gpio_pincfg_output));
   am_hal_gpio_output_set(PIN_STORAGE_WRITE_PROTECT);
   configASSERT0(am_hal_gpio_pinconfig(PIN_STORAGE_HOLD, am_hal_gpio_pincfg_output));
   am_hal_gpio_output_set(PIN_STORAGE_HOLD);

   // Initialize the SPI module and enable all relevant SPI pins
   ...   /* abbreviated: SCK, MISO, MOSI, and CS configured from the BSP's IOM0 pin settings */
   configASSERT0(am_hal_iom_power_ctrl(spi_handle, AM_HAL_SYSCTRL_WAKE, false));
   configASSERT0(am_hal_iom_configure(spi_handle, &spi_config));
   configASSERT0(am_hal_iom_enable(spi_handle));

   ...   /* the CRC engine's check, below */
   return true;
}

void nandlog_port_deinit(void)
{
   am_hal_iom_disable(spi_handle);
   am_hal_iom_uninitialize(spi_handle);
   spi_handle = NULL;
}

Transfers

The command and address go out as one transaction with bContinue set, so chip-select stays asserted, and the data follows, split across as many transactions as the peripheral's maximum requires. The port packs the command and up to three address bytes into one word, which covers both supplied drivers. The transaction count is fixed before the loop rather than tested against the remaining length, so a zero-length read still issues the one empty transaction a part may rely on. Each transaction gets three attempts, 10 µs apart.

void nandlog_port_transfer_read(uint8_t command, const void *address, uint32_t address_length, void *read_buffer, uint32_t read_length)
{
   // Create the SPI transaction structure
   uint32_t instruction = command, retries_remaining = 4;
   uint32_t num_reads = 1 + (read_length / (1 + AM_HAL_IOM_MAX_TXNSIZE_SPI));
   memcpy(((uint8_t*)&instruction) + 1, address, address_length);
   am_hal_iom_transfer_t spi_transaction = {
      .eDirection                   = AM_HAL_IOM_TX,
      .ui32NumBytes                 = 1 + address_length,
      .pui32TxBuffer                = &instruction,
      .bContinue                    = true,
      .ui8Priority                  = 1,
      ...   /* abbreviated: every other field is zero or NULL */
   };

   // Repeat the transfer until it succeeds or requires a device reset
   while (--retries_remaining && (am_hal_iom_blocking_transfer(spi_handle, &spi_transaction) != AM_HAL_STATUS_SUCCESS))
      am_hal_delay_us(10);
   if (!retries_remaining)
      system_reset(true);

   // Split the read across as many transactions as the peripheral's maximum requires
   uint32_t read_offset = 0;
   while (num_reads--)
   {
      uint32_t read_bytes = (read_length > AM_HAL_IOM_MAX_TXNSIZE_SPI) ? AM_HAL_IOM_MAX_TXNSIZE_SPI : read_length;
      read_length -= read_bytes;

      retries_remaining = 4;
      spi_transaction.eDirection = AM_HAL_IOM_RX;
      spi_transaction.ui32NumBytes = read_bytes;
      spi_transaction.pui32TxBuffer = NULL;
      spi_transaction.pui32RxBuffer = (uint32_t*)((uint8_t*)read_buffer + read_offset);
      spi_transaction.bContinue = read_length > 0;
      read_offset += read_bytes;

      while (--retries_remaining && (am_hal_iom_blocking_transfer(spi_handle, &spi_transaction) != AM_HAL_STATUS_SUCCESS))
         am_hal_delay_us(10);
      if (!retries_remaining)
         system_reset(true);
   }
}

/* nandlog_port_transfer_write() is the same function in the other direction, split the same way */

After three failed attempts, this port resets the MCU directly with the firmware's system_reset(). The contract asks for nandlog_port_fatal() at that point, which here would also record the reason before the reset.

Locking

Before the scheduler runs there is only one context, so there is nothing to serialize against, and taking a FreeRTOS mutex there or from an interrupt is an error rather than a wait. The mutex is therefore created on first use, which comes after the scheduler has started. The double check under a critical section makes the creation itself safe against two tasks arriving together.

static inline bool locking_applies(void)
{
   return (xTaskGetSchedulerState() == taskSCHEDULER_RUNNING) && !xPortIsInsideInterrupt();
}

void nandlog_port_lock(void)
{
   if (locking_applies())
   {
      if (!log_mutex)
      {
         taskENTER_CRITICAL();
         if (!log_mutex)
            log_mutex = xSemaphoreCreateMutexStatic(&log_mutex_buffer);
         taskEXIT_CRITICAL();
      }
      if (log_mutex)
         xSemaphoreTake(log_mutex, portMAX_DELAY);
   }
}

void nandlog_port_unlock(void)
{
   if (log_mutex && locking_applies())
      xSemaphoreGive(log_mutex);
}

The rest

On this board, driving the write-protect pin high permits programming. A sleep-and-wake cycle of the peripheral through nandlog_port_power() takes 17 µs.

void nandlog_port_write_enable(bool enable)
{
   if (enable)
      am_hal_gpio_output_set(PIN_STORAGE_WRITE_PROTECT);
   else
      am_hal_gpio_output_clear(PIN_STORAGE_WRITE_PROTECT);
}

void nandlog_port_power(bool awake)
{
   am_hal_iom_power_ctrl(spi_handle, awake ? AM_HAL_SYSCTRL_WAKE : AM_HAL_SYSCTRL_DEEPSLEEP, true);
}

void nandlog_port_log(const char *format, ...)
{
   char message[160];
   va_list args;
   va_start(args, format);
   vsnprintf(message, sizeof(message), format, args);
   va_end(args);
   print("%s", message);
}

void nandlog_port_delay_us(uint32_t microseconds) { am_hal_delay_us(microseconds); }
void nandlog_port_delay_ms(uint32_t milliseconds) { am_util_delay_ms(milliseconds); }

void nandlog_port_fatal(const char *reason)
{
   print("ERROR: Storage hardware fault: %s; resetting\n", reason);
   system_record_diagnostic(RESET_DIAGNOSTIC_STORAGE_FATAL);
   system_reset(true);
   while (true);   // nandlog requires this never to return
}

void nandlog_port_unwritable(void)
{
   // Not a reason to reset: the device can still range and still serve BLE.
   // Leave a breadcrumb so that the next boot's log says the flash has already given up
   system_record_diagnostic(RESET_DIAGNOSTIC_STORAGE_UNWRITABLE);
}

The busy timeout on this port. With the default 50,000 polls, each poll here costs about 47 µs: a 32 µs status read, the 10 µs delay (which takes 11 µs), and about 4 µs between calls, as the 1.0 bench measured them. The part therefore has about 2.4 s to clear BUSY before the driver calls nandlog_port_fatal(). On the bench, a page program took 16 polls and a full block's erase 74.

The CRC engine

The Apollo4's security block computes CRC-32 in hardware (the HAL's am_hal_crc32()). It reads LEN bytes, a multiple of four, from SRCADDR, and continues from the seed in RESULT. RESULT reads as the finished CRC, zlib's value, but the engine takes a seed written there bit-reversed, so a run that continues the zlib value z is seeded with __RBIT(~z). (The HAL only ever seeds 0xFFFFFFFF, which bit reversal leaves alone.) Ambiq documents neither behavior, and both were measured on an Apollo4 Plus. The engine also serves the BLE controller's driver, so a run suspends the scheduler, leaves alone an engine another user has running, and puts back the registers it borrowed. The SociTrack Makefiles set NANDLOG_PORT_CRC32.

#define HW_CRC_MIN_BYTES                            64          // shorter runs cost the software less than the engine's setup
#define HW_CRC_POLL_LIMIT                           1000000     // ENABLE polls before a run is given up as hung

static engine_run_t engine_run(uint32_t *crc, const uint8_t *words, uint32_t length)
{
   // One run of the engine over 'length' bytes at 'words', both multiples of four, going on from the zlib-style value
   // '*crc', which it replaces only if the run completed
   const bool scheduling = (xTaskGetSchedulerState() == taskSCHEDULER_RUNNING);
   if (scheduling)
      vTaskSuspendAll();
   engine_run_t run = ENGINE_BUSY;
   if (!SECURITY->CTRL_b.ENABLE)
   {
      const uint32_t result_was = SECURITY->RESULT, address_was = SECURITY->SRCADDR, length_was = SECURITY->LEN;
      const uint32_t function_was = SECURITY->CTRL_b.FUNCTION;
      SECURITY->RESULT = __RBIT(~*crc);        // the seed, which the engine takes bit-reversed
      SECURITY->SRCADDR = (uint32_t)words;
      SECURITY->LEN = length;
      SECURITY->CTRL_b.FUNCTION = SECURITY_CTRL_FUNCTION_CRC32;
      if (((uint32_t)words + length) >= (SRAM_BASEADDR + TCM_MAX_SIZE))
         am_hal_sysctrl_bus_write_flush();      // as the HAL does: writes outside the TCM must land before the engine reads
      SECURITY->CTRL_b.ENABLE = 1;
      uint32_t polls = 0;
      while (SECURITY->CTRL_b.ENABLE && (++polls < HW_CRC_POLL_LIMIT));
      if (SECURITY->CTRL_b.ENABLE)
         run = ENGINE_FAILED;                   // still running: its registers stay as they are
      else
      {
         run = SECURITY->CTRL_b.CRCERROR ? ENGINE_FAILED : ENGINE_DONE;
         if (run == ENGINE_DONE)
            *crc = SECURITY->RESULT;            // the finished CRC
         SECURITY->RESULT = __RBIT(~result_was); // RESULT reads as it did before
         SECURITY->SRCADDR = address_was;
         SECURITY->LEN = length_was;
         SECURITY->CTRL_b.FUNCTION = function_was;
      }
   }
   if (scheduling)
      xTaskResumeAll();
   return run;
}

static uint32_t crc_by_engine(uint32_t crc, const uint8_t *bytes, uint32_t length)
{
   // The software to the first word boundary, the engine for the whole words after it, and the software for the rest.
   // A run the engine does not do goes to the software too; one it starts and does not finish refuses it for good
   uint32_t head = (uint32_t)(-(uintptr_t)bytes & 3);
   if (head > length)
      head = length;
   crc = nandlog_crc32_software(crc, bytes, head);
   bytes += head;
   length -= head;
   const uint32_t words = length & ~3u;
   if (words)
   {
      const engine_run_t run = engine_run(&crc, bytes, words);
      if (run != ENGINE_DONE)
      {
         ++engine_misses;
         if ((run == ENGINE_FAILED) && (hw_crc_state == HW_CRC_IN_USE))
            refuse_engine("did not complete a run");
         crc = nandlog_crc32_software(crc, bytes, words);
      }
   }
   return nandlog_crc32_software(crc, bytes + words, length - words);
}

uint32_t nandlog_port_crc32(uint32_t crc, const void *data, uint32_t length)
{
   if ((hw_crc_state != HW_CRC_IN_USE) || (length < HW_CRC_MIN_BYTES) || xPortIsInsideInterrupt())
      return nandlog_crc32_software(crc, data, length);
   return crc_by_engine(crc, (const uint8_t*)data, length);
}

The engine does nothing for the log until nandlog_port_init() has checked it, once a boot and before the log computes its first CRC. Until then, and from an interrupt, every CRC goes to the software. The check, in engine_disagreement(), requires the engine's CRC of "12345678" from the HAL's seed to be zlib's (0x9AE0DAAF). It then requires the whole path (software to the first word boundary, the engine for the whole words, and software for the tail) to agree with nandlog_crc32_software() on "123456789" at every alignment, on 4,064 bytes of the program image both whole and continued from a split at byte 1,001, and on runs in RAM at every alignment, whole and split. Every one of those runs must have been the engine's. nandlog_port_crc32_hardware() returns whether the engine passed and is still in use.

#if NANDLOG_PORT_CRC32
   // Once a boot, before the log computes its first CRC: the engine is used only if it agrees on every vector
   if (hw_crc_state == HW_CRC_UNTESTED)
   {
      const char *disagreement = engine_disagreement();
      if (disagreement)
         refuse_engine(disagreement);
      else
      {
         hw_crc_state = HW_CRC_IN_USE;
         nandlog_port_log("INFO: The CRC-32 engine agrees with the software; nandlog's CRCs of %u bytes or more use it\n",
                          (uint32_t)HW_CRC_MIN_BYTES);
      }
   }
#endif

A disagreement refuses the engine, and from then on every CRC is computed in software, after one warning in the log. Later, a run the engine starts and does not finish (still running after 1,000,000 polls, or reporting a CRC error) also refuses it for good. A run that finds the engine busy with another user goes to the software alone. On the Apollo4 Plus the hook takes 50 µs for a 4,064-byte payload, against 467 µs in software. A 28-byte header goes to the software either way: 4.1 µs directly, or 5.3 µs through the hook.

Checking your port

Bring a new port up in this order, since each step depends on the one before. Getting Started walks through the same steps from the application's side.

  1. nandlog_probe() returns true. If it does not, the part is not answering its identity command, so check the wiring, the SPI mode, and chip-select.
  2. nandlog_init() returns true. A first boot reads every block's factory bad-block mark, which takes about 1.4 s on the Alliance part.
  3. Begin an epoch inside a session. Until one is begun, nandlog_store_record() returns NANDLOG_ERR_NO_EPOCH.
  4. Store a few records, call nandlog_flush(true), and read them back. If writes seem to succeed but nothing reads back, check the write-protect polarity.
  5. Run the on-device tests. They check the parts of the chip interface the simulator cannot, such as column addressing and the internal copy (see Testing).
  6. With NANDLOG_PORT_CRC32, check the hook. nandlog_crc32(0, "123456789", 9) must return 0xCBF43926, and your hook's verdict on its engine must be the one you expect. The on-device benchmark prints both (BENCH_INFO crc_hook, crc_hw_selftest, and crc_vectors_ok) and times the hook against the software.