Skip to content

Commit 3b613ff

Browse files
committed
[spi_flash] handle reentrance gracefully
Report failure instead of deadlocking the device
1 parent 98425c9 commit 3b613ff

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

supervisor/shared/external_flash/spi_flash.c

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +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)) {
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;
4749
}
48-
common_hal_digitalio_digitalinout_set_value(&cs_pin, false);
50+
return false;
4951
}
5052

5153
// Disable the flash over SPI.
@@ -54,8 +56,10 @@ static void flash_disable(void) {
5456
common_hal_busio_spi_unlock(&supervisor_flash_spi_bus);
5557
}
5658

57-
static bool transfer(uint8_t *command, uint32_t command_length, uint8_t *data_in, uint8_t *data_out, uint32_t data_length) {
58-
flash_enable();
59+
static bool transfer(uint8_t* command, uint32_t command_length, uint8_t* data_in, uint8_t* data_out, uint32_t data_length) {
60+
if (!flash_enable()) {
61+
return false;
62+
}
5963
bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, command, command_length);
6064
if (status) {
6165
if (data_in != NULL && data_out != NULL) {
@@ -103,7 +107,9 @@ bool spi_flash_write_data(uint32_t address, uint8_t *data, uint32_t data_length)
103107
uint8_t request[4] = {CMD_PAGE_PROGRAM, 0x00, 0x00, 0x00};
104108
// Write the SPI flash write address into the bytes following the command byte.
105109
address_to_bytes(address, request + 1);
106-
flash_enable();
110+
if (!flash_enable()) {
111+
return false;
112+
}
107113
common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8);
108114
bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, 4);
109115
if (status) {
@@ -120,9 +126,11 @@ bool spi_flash_read_data(uint32_t address, uint8_t *data, uint32_t data_length)
120126
request[0] = CMD_FAST_READ_DATA;
121127
command_length = 5;
122128
}
123-
// Write the SPI flash write address into the bytes following the command byte.
129+
// Write the SPI flash read address into the bytes following the command byte.
124130
address_to_bytes(address, request + 1);
125-
flash_enable();
131+
if (!flash_enable()) {
132+
return false;
133+
}
126134
common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8);
127135
bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, command_length);
128136
if (status) {

0 commit comments

Comments
 (0)