Skip to content

Commit 24f48d8

Browse files
committed
[spi_flash] handle reentrance gracefully
Report failure instead of deadlocking the device
1 parent 550eab2 commit 24f48d8

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

supervisor/shared/external_flash/spi_flash.c

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,12 @@ const external_flash_device* flash_device;
4242
uint32_t spi_flash_baudrate;
4343

4444
// Enable the flash over SPI.
45-
static void flash_enable(void) {
46-
while (!common_hal_busio_spi_try_lock(&supervisor_flash_spi_bus)) {}
47-
common_hal_digitalio_digitalinout_set_value(&cs_pin, false);
45+
static bool flash_enable(void) {
46+
if (common_hal_busio_spi_try_lock(&supervisor_flash_spi_bus)) {
47+
common_hal_digitalio_digitalinout_set_value(&cs_pin, false);
48+
return true;
49+
}
50+
return false;
4851
}
4952

5053
// Disable the flash over SPI.
@@ -54,7 +57,8 @@ static void flash_disable(void) {
5457
}
5558

5659
static bool transfer(uint8_t* command, uint32_t command_length, uint8_t* data_in, uint8_t* data_out, uint32_t data_length) {
57-
flash_enable();
60+
if (!flash_enable())
61+
return false;
5862
bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, command, command_length);
5963
if (status) {
6064
if (data_in != NULL && data_out != NULL) {
@@ -102,7 +106,8 @@ bool spi_flash_write_data(uint32_t address, uint8_t* data, uint32_t data_length)
102106
uint8_t request[4] = {CMD_PAGE_PROGRAM, 0x00, 0x00, 0x00};
103107
// Write the SPI flash write address into the bytes following the command byte.
104108
address_to_bytes(address, request + 1);
105-
flash_enable();
109+
if (!flash_enable())
110+
return false;
106111
common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8);
107112
bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, 4);
108113
if (status) {
@@ -119,9 +124,10 @@ bool spi_flash_read_data(uint32_t address, uint8_t* data, uint32_t data_length)
119124
request[0] = CMD_FAST_READ_DATA;
120125
command_length = 5;
121126
}
122-
// Write the SPI flash write address into the bytes following the command byte.
127+
// Write the SPI flash read address into the bytes following the command byte.
123128
address_to_bytes(address, request + 1);
124-
flash_enable();
129+
if (!flash_enable())
130+
return false;
125131
common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8);
126132
bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, command_length);
127133
if (status) {

0 commit comments

Comments
 (0)