Add Core1 refresh recovery and shared SPI arbitration

This commit is contained in:
Adolfo Reyna
2026-02-18 15:43:35 -05:00
parent ebc58d7e4d
commit 3e54466752
5 changed files with 188 additions and 32 deletions

65
lib/shared_spi_bus.c Normal file
View File

@@ -0,0 +1,65 @@
#include "shared_spi_bus.h"
#include "pico/mutex.h"
#include "pico/multicore.h"
#include <stdbool.h>
static mutex_t g_spi_bus_mutex;
static bool g_spi_bus_initialized = false;
static uint32_t g_core_depth[2] = {0, 0};
void shared_spi_bus_init(void) {
if (g_spi_bus_initialized) {
return;
}
mutex_init(&g_spi_bus_mutex);
g_spi_bus_initialized = true;
}
void shared_spi_bus_lock(void) {
if (!g_spi_bus_initialized) {
shared_spi_bus_init();
}
int core = get_core_num();
if (core < 0 || core > 1) {
core = 0;
}
// Re-entrant lock on same core (needed for nested SD helpers).
if (g_core_depth[core] > 0) {
g_core_depth[core]++;
return;
}
mutex_enter_blocking(&g_spi_bus_mutex);
g_core_depth[core] = 1;
}
void shared_spi_bus_unlock(void) {
if (!g_spi_bus_initialized) {
return;
}
int core = get_core_num();
if (core < 0 || core > 1) {
core = 0;
}
if (g_core_depth[core] == 0) {
return;
}
g_core_depth[core]--;
if (g_core_depth[core] == 0) {
mutex_exit(&g_spi_bus_mutex);
}
}
void shared_spi_bus_force_recover(void) {
// Used after Core1 reset to avoid stale mutex/depth state.
mutex_init(&g_spi_bus_mutex);
g_core_depth[0] = 0;
g_core_depth[1] = 0;
g_spi_bus_initialized = true;
}