HeapCrash / Challenges / Nested mutexes under load

Nested mutexes under load

A storage task and a logger share an SPI flash and a log buffer, each behind a FreeRTOS mutex. A 1 ms control task logs faults. After hours of soak testing the storage task and the logger both stop, and the control task occasionally misses its deadline by seconds.

The code

Embedded C for Cortex-M. It compiles. There are 3 real bugs in it: the kind that pass a bench test and fail in the field.

SemaphoreHandle_t spi_mtx, log_mtx;
QueueHandle_t rec_q;

void log_write(const char *msg)
{
    xSemaphoreTake(log_mtx, portMAX_DELAY);
    log_append(msg);
    if (log_full()) {
        xSemaphoreTake(spi_mtx, portMAX_DELAY);
        flush_log_to_flash();
        xSemaphoreGive(spi_mtx);
    }
    xSemaphoreGive(log_mtx);
}

void storage_task(void *p)      /* priority 1 */
{
    for (;;) {
        rec_t r;
        xSemaphoreTake(spi_mtx, portMAX_DELAY);
        xQueueReceive(rec_q, &r, portMAX_DELAY);
        flash_write_record(&r);
        log_write("record stored");
        xSemaphoreGive(spi_mtx);
    }
}

void control_task(void *p)      /* priority 5, 1 ms period */
{
    for (;;) {
        run_control();
        if (fault()) log_write("fault");
        vTaskDelay(1);
    }
}

What an interviewer expects

The bugs, reference fixes and the follow-up question are in the practice app, after you've tried it.

Companies that test this

Matched on the skills each company's embedded roles emphasise.

Related challenges

Flag the lines, say what breaks, then fix it and build it with clang in your browser.

Find the bugs