aboutsummaryrefslogtreecommitdiff
path: root/circuitpython/supervisor/shared/external_flash
diff options
context:
space:
mode:
authorRaghuram Subramani <raghus2247@gmail.com>2022-06-19 19:47:51 +0530
committerRaghuram Subramani <raghus2247@gmail.com>2022-06-19 19:47:51 +0530
commit4fd287655a72b9aea14cdac715ad5b90ed082ed2 (patch)
tree65d393bc0e699dd12d05b29ba568e04cea666207 /circuitpython/supervisor/shared/external_flash
parent0150f70ce9c39e9e6dd878766c0620c85e47bed0 (diff)
add circuitpython code
Diffstat (limited to 'circuitpython/supervisor/shared/external_flash')
-rw-r--r--circuitpython/supervisor/shared/external_flash/common_commands.h48
-rw-r--r--circuitpython/supervisor/shared/external_flash/device.h78
-rw-r--r--circuitpython/supervisor/shared/external_flash/devices.h.jinja50
-rw-r--r--circuitpython/supervisor/shared/external_flash/external_flash.c593
-rw-r--r--circuitpython/supervisor/shared/external_flash/external_flash.h55
-rw-r--r--circuitpython/supervisor/shared/external_flash/external_flash_root_pointers.h35
-rw-r--r--circuitpython/supervisor/shared/external_flash/qspi_flash.c57
-rw-r--r--circuitpython/supervisor/shared/external_flash/qspi_flash.h31
-rw-r--r--circuitpython/supervisor/shared/external_flash/spi_flash.c166
9 files changed, 1113 insertions, 0 deletions
diff --git a/circuitpython/supervisor/shared/external_flash/common_commands.h b/circuitpython/supervisor/shared/external_flash/common_commands.h
new file mode 100644
index 0000000..37efd8c
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/common_commands.h
@@ -0,0 +1,48 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef MICROPY_INCLUDED_ATMEL_SAMD_EXTERNAL_FLASH_COMMON_COMMANDS_H
+#define MICROPY_INCLUDED_ATMEL_SAMD_EXTERNAL_FLASH_COMMON_COMMANDS_H
+
+#define CMD_READ_JEDEC_ID 0x9f
+#define CMD_READ_DATA 0x03
+#define CMD_FAST_READ_DATA 0x0B
+#define CMD_SECTOR_ERASE 0x20
+// #define CMD_SECTOR_ERASE CMD_READ_JEDEC_ID
+#define CMD_DISABLE_WRITE 0x04
+#define CMD_ENABLE_WRITE 0x06
+#define CMD_PAGE_PROGRAM 0x02
+// #define CMD_PAGE_PROGRAM CMD_READ_JEDEC_ID
+#define CMD_READ_STATUS 0x05
+#define CMD_READ_STATUS2 0x35
+#define CMD_WRITE_STATUS_BYTE1 0x01
+#define CMD_WRITE_STATUS_BYTE2 0x31
+#define CMD_DUAL_READ 0x3b
+#define CMD_QUAD_READ 0x6b
+#define CMD_ENABLE_RESET 0x66
+#define CMD_RESET 0x99
+#define CMD_WAKE 0xab
+
+#endif // MICROPY_INCLUDED_ATMEL_SAMD_EXTERNAL_FLASH_COMMON_COMMANDS_H
diff --git a/circuitpython/supervisor/shared/external_flash/device.h b/circuitpython/supervisor/shared/external_flash/device.h
new file mode 100644
index 0000000..bbf6bfd
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/device.h
@@ -0,0 +1,78 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICE_H
+#define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICE_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+typedef struct {
+ uint32_t total_size;
+ uint16_t start_up_time_us;
+
+ // Three response bytes to 0x9f JEDEC ID command.
+ uint8_t manufacturer_id;
+ uint8_t memory_type;
+ uint8_t capacity;
+
+ // Max clock speed for all operations and the fastest read mode.
+ uint8_t max_clock_speed_mhz;
+
+ // Bitmask for Quad Enable bit if present. 0x00 otherwise. This is for the highest byte in the
+ // status register.
+ uint8_t quad_enable_bit_mask;
+
+ bool has_sector_protection : 1;
+
+ // Supports the 0x0b fast read command with 8 dummy cycles.
+ bool supports_fast_read : 1;
+
+ // Supports the fast read, quad output command 0x6b with 8 dummy cycles.
+ bool supports_qspi : 1;
+
+ // Supports the quad input page program command 0x32. This is known as 1-1-4 because it only
+ // uses all four lines for data.
+ bool supports_qspi_writes : 1;
+
+ // Requires a separate command 0x31 to write to the second byte of the status register.
+ // Otherwise two byte are written via 0x01.
+ bool write_status_register_split : 1;
+
+ // True when the status register is a single byte. This implies the Quad Enable bit is in the
+ // first byte and the Read Status Register 2 command (0x35) is unsupported.
+ bool single_status_byte : 1;
+
+ // Does not support using a ready bit within the status register
+ bool no_ready_bit : 1;
+
+ // Does not support the erase command (0x20)
+ bool no_erase_cmd : 1;
+
+ // Device does not have a reset command
+ bool no_reset_cmd : 1;
+} external_flash_device;
+
+#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICE_H
diff --git a/circuitpython/supervisor/shared/external_flash/devices.h.jinja b/circuitpython/supervisor/shared/external_flash/devices.h.jinja
new file mode 100644
index 0000000..7cad90d
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/devices.h.jinja
@@ -0,0 +1,50 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICES_H
+#define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICES_H
+
+{% for device in nvms %}
+#define {{ device.sku }} { \
+ .total_size = {{ device.total_size }}, \
+ .start_up_time_us = {{ device.start_up_time_us }}, \
+ .manufacturer_id = {{ device.manufacturer_id }}, \
+ .memory_type = {{ device.memory_type }}, \
+ .capacity = {{ device.capacity }}, \
+ .max_clock_speed_mhz = {{ device.max_clock_speed_mhz }}, \
+ .quad_enable_bit_mask = {{ device.quad_enable_bit_mask }}, \
+ .has_sector_protection = {{ device.has_sector_protection | lower() }}, \
+ .supports_fast_read = {{ device.supports_fast_read | lower() }}, \
+ .supports_qspi = {{ device["6b_quad_read"] | lower() }}, \
+ .supports_qspi_writes = {{ device["32_qspi_write"] | lower() }}, \
+ .write_status_register_split = {{ device.write_status_register_split | lower() }}, \
+ .single_status_byte = {{ (device.quad_enable_status_byte == 1) | lower() }}, \
+ .no_ready_bit = {{ (device.no_ready_bit == 1) | lower() }}, \
+ .no_erase_cmd = {{ (device.no_erase_cmd == 1) | lower() }}, \
+ .no_reset_cmd = {{ (device.no_reset_cmd == 1) | lower() }}, \
+}
+{% endfor %}
+
+#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICES_H
diff --git a/circuitpython/supervisor/shared/external_flash/external_flash.c b/circuitpython/supervisor/shared/external_flash/external_flash.c
new file mode 100644
index 0000000..7da45fd
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/external_flash.c
@@ -0,0 +1,593 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016, 2017 Scott Shawcroft for Adafruit Industries
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#include "supervisor/shared/external_flash/external_flash.h"
+
+#include <stdint.h>
+#include <string.h>
+#include "genhdr/devices.h"
+#include "supervisor/flash.h"
+#include "supervisor/spi_flash_api.h"
+#include "supervisor/shared/external_flash/common_commands.h"
+#include "extmod/vfs.h"
+#include "extmod/vfs_fat.h"
+#include "py/misc.h"
+#include "py/obj.h"
+#include "py/runtime.h"
+#include "lib/oofatfs/ff.h"
+#include "shared-bindings/microcontroller/__init__.h"
+#include "supervisor/memory.h"
+
+#define NO_SECTOR_LOADED 0xFFFFFFFF
+
+// The currently cached sector in the cache, ram or flash based.
+static uint32_t current_sector;
+
+STATIC const external_flash_device possible_devices[] = {EXTERNAL_FLASH_DEVICES};
+#define EXTERNAL_FLASH_DEVICE_COUNT MP_ARRAY_SIZE(possible_devices)
+
+static const external_flash_device *flash_device = NULL;
+
+// Track which blocks (up to 32) in the current sector currently live in the
+// cache.
+static uint32_t dirty_mask;
+
+static supervisor_allocation *supervisor_cache = NULL;
+
+// Wait until both the write enable and write in progress bits have cleared.
+static bool wait_for_flash_ready(void) {
+ bool ok = true;
+ // Both the write enable and write in progress bits should be low.
+ if (flash_device->no_ready_bit) {
+ // For NVM without a ready bit in status register
+ return ok;
+ }
+ uint8_t read_status_response[1] = {0x00};
+ do {
+ ok = spi_flash_read_command(CMD_READ_STATUS, read_status_response, 1);
+ } while (ok && (read_status_response[0] & 0x3) != 0);
+ return ok;
+}
+
+// Turn on the write enable bit so we can program and erase the flash.
+static bool write_enable(void) {
+ return spi_flash_command(CMD_ENABLE_WRITE);
+}
+
+// Read data_length's worth of bytes starting at address into data.
+static bool read_flash(uint32_t address, uint8_t *data, uint32_t data_length) {
+ if (flash_device == NULL) {
+ return false;
+ }
+ if (!wait_for_flash_ready()) {
+ return false;
+ }
+ return spi_flash_read_data(address, data, data_length);
+}
+
+// Writes data_length's worth of bytes starting at address from data. Assumes
+// that the sector that address resides in has already been erased. So make sure
+// to run erase_sector.
+static bool write_flash(uint32_t address, const uint8_t *data, uint32_t data_length) {
+ if (flash_device == NULL) {
+ return false;
+ }
+ // Don't bother writing if the data is all 1s. Thats equivalent to the flash
+ // state after an erase.
+ if (!flash_device->no_erase_cmd) {
+ // Only do this if the device has an erase command
+ bool all_ones = true;
+ for (uint16_t i = 0; i < data_length; i++) {
+ if (data[i] != 0xff) {
+ all_ones = false;
+ break;
+ }
+ }
+ if (all_ones) {
+ return true;
+ }
+ }
+
+ for (uint32_t bytes_written = 0;
+ bytes_written < data_length;
+ bytes_written += SPI_FLASH_PAGE_SIZE) {
+ if (!wait_for_flash_ready() || !write_enable()) {
+ return false;
+ }
+
+ if (!spi_flash_write_data(address + bytes_written, (uint8_t *)data + bytes_written,
+ SPI_FLASH_PAGE_SIZE)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool page_erased(uint32_t sector_address) {
+ // Check the first few bytes to catch the common case where there is data
+ // without using a bunch of memory.
+ if (flash_device->no_erase_cmd) {
+ // skip this if device doesn't have an erase command.
+ return true;
+ }
+ uint8_t short_buffer[4];
+ if (read_flash(sector_address, short_buffer, 4)) {
+ for (uint16_t i = 0; i < 4; i++) {
+ if (short_buffer[i] != 0xff) {
+ return false;
+ }
+ }
+ } else {
+ return false;
+ }
+
+ // Now check the full length.
+ uint8_t full_buffer[FILESYSTEM_BLOCK_SIZE];
+ if (read_flash(sector_address, full_buffer, FILESYSTEM_BLOCK_SIZE)) {
+ for (uint16_t i = 0; i < FILESYSTEM_BLOCK_SIZE; i++) {
+ if (short_buffer[i] != 0xff) {
+ return false;
+ }
+ }
+ } else {
+ return false;
+ }
+ return true;
+}
+
+// Erases the given sector. Make sure you copied all of the data out of it you
+// need! Also note, sector_address is really 24 bits.
+static bool erase_sector(uint32_t sector_address) {
+ // Before we erase the sector we need to wait for any writes to finish and
+ // and then enable the write again.
+ if (flash_device->no_erase_cmd) {
+ // skip this if device doesn't have an erase command.
+ return true;
+ }
+ if (!wait_for_flash_ready() || !write_enable()) {
+ return false;
+ }
+ if (flash_device->no_erase_cmd) {
+ return true;
+ }
+ spi_flash_sector_command(CMD_SECTOR_ERASE, sector_address);
+ return true;
+}
+
+// Sector is really 24 bits.
+static bool copy_block(uint32_t src_address, uint32_t dest_address) {
+ // Copy page by page to minimize RAM buffer.
+ uint16_t page_size = SPI_FLASH_PAGE_SIZE;
+ uint8_t buffer[page_size];
+ for (uint32_t i = 0; i < FILESYSTEM_BLOCK_SIZE / page_size; i++) {
+ if (!read_flash(src_address + i * page_size, buffer, page_size)) {
+ return false;
+ }
+ if (!write_flash(dest_address + i * page_size, buffer, page_size)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+void supervisor_flash_init(void) {
+ if (flash_device != NULL) {
+ return;
+ }
+
+ // Delay to give the SPI Flash time to get going.
+ // TODO(tannewt): Only do this when we know power was applied vs a reset.
+ uint16_t max_start_up_delay_us = 0;
+ for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) {
+ if (possible_devices[i].start_up_time_us > max_start_up_delay_us) {
+ max_start_up_delay_us = possible_devices[i].start_up_time_us;
+ }
+ }
+ common_hal_mcu_delay_us(max_start_up_delay_us);
+
+ spi_flash_init();
+
+ #ifdef EXTERNAL_FLASH_NO_JEDEC
+ // For NVM that don't have JEDEC response
+ spi_flash_command(CMD_WAKE);
+ for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) {
+ const external_flash_device *possible_device = &possible_devices[i];
+ flash_device = possible_device;
+ break;
+ }
+ #else
+ // The response will be 0xff if the flash needs more time to start up.
+ uint8_t jedec_id_response[3] = {0xff, 0xff, 0xff};
+ while (jedec_id_response[0] == 0xff) {
+ spi_flash_read_command(CMD_READ_JEDEC_ID, jedec_id_response, 3);
+ }
+ for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) {
+ const external_flash_device *possible_device = &possible_devices[i];
+ if (jedec_id_response[0] == possible_device->manufacturer_id &&
+ jedec_id_response[1] == possible_device->memory_type &&
+ jedec_id_response[2] == possible_device->capacity) {
+ flash_device = possible_device;
+ break;
+ }
+ }
+ #endif
+ if (flash_device == NULL) {
+ return;
+ }
+
+ // We don't know what state the flash is in so wait for any remaining writes and then reset.
+ uint8_t read_status_response[1] = {0x00};
+ // The write in progress bit should be low.
+ do {
+ spi_flash_read_command(CMD_READ_STATUS, read_status_response, 1);
+ } while ((read_status_response[0] & 0x1) != 0);
+ if (!flash_device->single_status_byte) {
+ // The suspended write/erase bit should be low.
+ do {
+ spi_flash_read_command(CMD_READ_STATUS2, read_status_response, 1);
+ } while ((read_status_response[0] & 0x80) != 0);
+ }
+
+ if (!(flash_device->no_reset_cmd)) {
+ spi_flash_command(CMD_ENABLE_RESET);
+ spi_flash_command(CMD_RESET);
+ }
+
+ // Wait 30us for the reset
+ common_hal_mcu_delay_us(30);
+
+ spi_flash_init_device(flash_device);
+
+ // Activity LED for flash writes.
+ #ifdef MICROPY_HW_LED_MSC
+ gpio_set_pin_function(SPI_FLASH_CS_PIN, GPIO_PIN_FUNCTION_OFF);
+ gpio_set_pin_direction(MICROPY_HW_LED_MSC, GPIO_DIRECTION_OUT);
+ // There's already a pull-up on the board.
+ gpio_set_pin_level(MICROPY_HW_LED_MSC, false);
+ #endif
+
+ if (flash_device->has_sector_protection) {
+ write_enable();
+
+ // Turn off sector protection
+ uint8_t data[1] = {0x00};
+ spi_flash_write_command(CMD_WRITE_STATUS_BYTE1, data, 1);
+ }
+
+ // Turn off writes in case this is a microcontroller only reset.
+ spi_flash_command(CMD_DISABLE_WRITE);
+
+ wait_for_flash_ready();
+
+ current_sector = NO_SECTOR_LOADED;
+ dirty_mask = 0;
+ MP_STATE_VM(flash_ram_cache) = NULL;
+}
+
+// The size of each individual block.
+uint32_t supervisor_flash_get_block_size(void) {
+ return FILESYSTEM_BLOCK_SIZE;
+}
+
+// The total number of available blocks.
+uint32_t supervisor_flash_get_block_count(void) {
+ // We subtract one erase sector size because we may use it as a staging area
+ // for writes.
+ return (flash_device->total_size - SPI_FLASH_ERASE_SIZE) / FILESYSTEM_BLOCK_SIZE;
+}
+
+// Flush the cache that was written to the scratch portion of flash. Only used
+// when ram is tight.
+static bool flush_scratch_flash(void) {
+ if (current_sector == NO_SECTOR_LOADED) {
+ return true;
+ }
+ // First, copy out any blocks that we haven't touched from the sector we've
+ // cached.
+ bool copy_to_scratch_ok = true;
+ uint32_t scratch_sector = flash_device->total_size - SPI_FLASH_ERASE_SIZE;
+ for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) {
+ if ((dirty_mask & (1 << i)) == 0) {
+ copy_to_scratch_ok = copy_to_scratch_ok &&
+ copy_block(current_sector + i * FILESYSTEM_BLOCK_SIZE,
+ scratch_sector + i * FILESYSTEM_BLOCK_SIZE);
+ }
+ }
+ if (!copy_to_scratch_ok) {
+ // TODO(tannewt): Do more here. We opted to not erase and copy bad data
+ // in. We still risk losing the data written to the scratch sector.
+ return false;
+ }
+ // Second, erase the current sector.
+ erase_sector(current_sector);
+ // Finally, copy the new version into it.
+ for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) {
+ copy_block(scratch_sector + i * FILESYSTEM_BLOCK_SIZE,
+ current_sector + i * FILESYSTEM_BLOCK_SIZE);
+ }
+ return true;
+}
+
+// Attempts to allocate a new set of page buffers for caching a full sector in
+// ram. Each page is allocated separately so that the GC doesn't need to provide
+// one huge block. We can free it as we write if we want to also.
+static bool allocate_ram_cache(void) {
+ uint8_t blocks_per_sector = SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE;
+ uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE;
+
+ uint32_t table_size = blocks_per_sector * pages_per_block * sizeof(uint32_t);
+ // Attempt to allocate outside the heap first.
+ supervisor_cache = allocate_memory(table_size + SPI_FLASH_ERASE_SIZE, false, false);
+ if (supervisor_cache != NULL) {
+ MP_STATE_VM(flash_ram_cache) = (uint8_t **)supervisor_cache->ptr;
+ uint8_t *page_start = (uint8_t *)supervisor_cache->ptr + table_size;
+
+ for (uint8_t i = 0; i < blocks_per_sector; i++) {
+ for (uint8_t j = 0; j < pages_per_block; j++) {
+ uint32_t offset = i * pages_per_block + j;
+ MP_STATE_VM(flash_ram_cache)[offset] = page_start + offset * SPI_FLASH_PAGE_SIZE;
+ }
+ }
+ return true;
+ }
+
+ if (MP_STATE_MEM(gc_pool_start) == 0) {
+ return false;
+ }
+
+ MP_STATE_VM(flash_ram_cache) = m_malloc_maybe(blocks_per_sector * pages_per_block * sizeof(uint32_t), false);
+ if (MP_STATE_VM(flash_ram_cache) == NULL) {
+ return false;
+ }
+ // Declare i and j outside the loops in case we fail to allocate everything
+ // we need. In that case we'll give it back.
+ uint8_t i = 0;
+ uint8_t j = 0;
+ bool success = true;
+ for (i = 0; i < blocks_per_sector; i++) {
+ for (j = 0; j < pages_per_block; j++) {
+ uint8_t *page_cache = m_malloc_maybe(SPI_FLASH_PAGE_SIZE, false);
+ if (page_cache == NULL) {
+ success = false;
+ break;
+ }
+ MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j] = page_cache;
+ }
+ if (!success) {
+ break;
+ }
+ }
+ // We couldn't allocate enough so give back what we got.
+ if (!success) {
+ // We add 1 so that we delete 0 when i is 1. Going to zero (i >= 0)
+ // would never stop because i is unsigned.
+ i++;
+ for (; i > 0; i--) {
+ for (; j > 0; j--) {
+ m_free(MP_STATE_VM(flash_ram_cache)[(i - 1) * pages_per_block + (j - 1)]);
+ }
+ j = pages_per_block;
+ }
+ m_free(MP_STATE_VM(flash_ram_cache));
+ MP_STATE_VM(flash_ram_cache) = NULL;
+ }
+ return success;
+}
+
+static void release_ram_cache(void) {
+ if (supervisor_cache != NULL) {
+ free_memory(supervisor_cache);
+ supervisor_cache = NULL;
+ } else if (MP_STATE_MEM(gc_pool_start)) {
+ m_free(MP_STATE_VM(flash_ram_cache));
+ }
+ MP_STATE_VM(flash_ram_cache) = NULL;
+}
+
+// Flush the cached sector from ram onto the flash. We'll free the cache unless
+// keep_cache is true.
+static bool flush_ram_cache(bool keep_cache) {
+ if (current_sector == NO_SECTOR_LOADED) {
+ if (!keep_cache) {
+ release_ram_cache();
+ }
+ return true;
+ }
+ // First, copy out any blocks that we haven't touched from the sector
+ // we've cached. If we don't do this we'll erase the data during the sector
+ // erase below.
+ bool copy_to_ram_ok = true;
+ uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE;
+ for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) {
+ if ((dirty_mask & (1 << i)) == 0) {
+ for (uint8_t j = 0; j < pages_per_block; j++) {
+ copy_to_ram_ok = read_flash(
+ current_sector + (i * pages_per_block + j) * SPI_FLASH_PAGE_SIZE,
+ MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j],
+ SPI_FLASH_PAGE_SIZE);
+ if (!copy_to_ram_ok) {
+ break;
+ }
+ }
+ }
+ if (!copy_to_ram_ok) {
+ break;
+ }
+ }
+
+ if (!copy_to_ram_ok) {
+ return false;
+ }
+ // Second, erase the current sector.
+ erase_sector(current_sector);
+ // Lastly, write all the data in ram that we've cached.
+ for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) {
+ for (uint8_t j = 0; j < pages_per_block; j++) {
+ write_flash(current_sector + (i * pages_per_block + j) * SPI_FLASH_PAGE_SIZE,
+ MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j],
+ SPI_FLASH_PAGE_SIZE);
+ if (!keep_cache && supervisor_cache == NULL && MP_STATE_MEM(gc_pool_start)) {
+ m_free(MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j]);
+ }
+ }
+ }
+ // We're done with the cache for now so give it back.
+ if (!keep_cache) {
+ release_ram_cache();
+ }
+ return true;
+}
+
+// Delegates to the correct flash flush method depending on the existing cache.
+// TODO Don't blink the status indicator if we don't actually do any writing (hard to tell right now).
+static void spi_flash_flush_keep_cache(bool keep_cache) {
+ #ifdef MICROPY_HW_LED_MSC
+ port_pin_set_output_level(MICROPY_HW_LED_MSC, true);
+ #endif
+ // If we've cached to the flash itself flush from there.
+ if (MP_STATE_VM(flash_ram_cache) == NULL) {
+ flush_scratch_flash();
+ } else {
+ flush_ram_cache(keep_cache);
+ }
+ current_sector = NO_SECTOR_LOADED;
+ #ifdef MICROPY_HW_LED_MSC
+ port_pin_set_output_level(MICROPY_HW_LED_MSC, false);
+ #endif
+}
+
+void supervisor_external_flash_flush(void) {
+ spi_flash_flush_keep_cache(true);
+}
+
+void supervisor_flash_release_cache(void) {
+ spi_flash_flush_keep_cache(false);
+}
+
+static int32_t convert_block_to_flash_addr(uint32_t block) {
+ if (0 <= block && block < supervisor_flash_get_block_count()) {
+ // a block in partition 1
+ return block * FILESYSTEM_BLOCK_SIZE;
+ }
+ // bad block
+ return -1;
+}
+
+static bool external_flash_read_block(uint8_t *dest, uint32_t block) {
+ int32_t address = convert_block_to_flash_addr(block);
+ if (address == -1) {
+ // bad block number
+ return false;
+ }
+
+ // Mask out the lower bits that designate the address within the sector.
+ uint32_t this_sector = address & (~(SPI_FLASH_ERASE_SIZE - 1));
+ uint8_t block_index = (address / FILESYSTEM_BLOCK_SIZE) % (SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE);
+ uint8_t mask = 1 << (block_index);
+ // We're reading from the currently cached sector.
+ if (current_sector == this_sector && (mask & dirty_mask) > 0) {
+ if (MP_STATE_VM(flash_ram_cache) != NULL) {
+ uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE;
+ for (int i = 0; i < pages_per_block; i++) {
+ memcpy(dest + i * SPI_FLASH_PAGE_SIZE,
+ MP_STATE_VM(flash_ram_cache)[block_index * pages_per_block + i],
+ SPI_FLASH_PAGE_SIZE);
+ }
+ return true;
+ } else {
+ uint32_t scratch_address = flash_device->total_size - SPI_FLASH_ERASE_SIZE + block_index * FILESYSTEM_BLOCK_SIZE;
+ return read_flash(scratch_address, dest, FILESYSTEM_BLOCK_SIZE);
+ }
+ }
+ return read_flash(address, dest, FILESYSTEM_BLOCK_SIZE);
+}
+
+static bool external_flash_write_block(const uint8_t *data, uint32_t block) {
+ // Non-MBR block, copy to cache
+ int32_t address = convert_block_to_flash_addr(block);
+ if (address == -1) {
+ // bad block number
+ return false;
+ }
+ // Wait for any previous writes to finish.
+ wait_for_flash_ready();
+ // Mask out the lower bits that designate the address within the sector.
+ uint32_t this_sector = address & (~(SPI_FLASH_ERASE_SIZE - 1));
+ uint8_t block_index = (address / FILESYSTEM_BLOCK_SIZE) % (SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE);
+ uint8_t mask = 1 << (block_index);
+ // Flush the cache if we're moving onto a sector or we're writing the
+ // same block again.
+ if (current_sector != this_sector || (mask & dirty_mask) > 0) {
+ // Check to see if we'd write to an erased page. In that case we
+ // can write directly.
+ if (page_erased(address)) {
+ return write_flash(address, data, FILESYSTEM_BLOCK_SIZE);
+ }
+ if (current_sector != NO_SECTOR_LOADED) {
+ supervisor_flash_flush();
+ }
+ if (MP_STATE_VM(flash_ram_cache) == NULL && !allocate_ram_cache()) {
+ erase_sector(flash_device->total_size - SPI_FLASH_ERASE_SIZE);
+ wait_for_flash_ready();
+ }
+ current_sector = this_sector;
+ dirty_mask = 0;
+ }
+ dirty_mask |= mask;
+ // Copy the block to the appropriate cache.
+ if (MP_STATE_VM(flash_ram_cache) != NULL) {
+ uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE;
+ for (int i = 0; i < pages_per_block; i++) {
+ memcpy(MP_STATE_VM(flash_ram_cache)[block_index * pages_per_block + i],
+ data + i * SPI_FLASH_PAGE_SIZE,
+ SPI_FLASH_PAGE_SIZE);
+ }
+ return true;
+ } else {
+ uint32_t scratch_address = flash_device->total_size - SPI_FLASH_ERASE_SIZE + block_index * FILESYSTEM_BLOCK_SIZE;
+ return write_flash(scratch_address, data, FILESYSTEM_BLOCK_SIZE);
+ }
+}
+
+mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block_num, uint32_t num_blocks) {
+ for (size_t i = 0; i < num_blocks; i++) {
+ if (!external_flash_read_block(dest + i * FILESYSTEM_BLOCK_SIZE, block_num + i)) {
+ return 1; // error
+ }
+ }
+ return 0; // success
+}
+
+mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t num_blocks) {
+ for (size_t i = 0; i < num_blocks; i++) {
+ if (!external_flash_write_block(src + i * FILESYSTEM_BLOCK_SIZE, block_num + i)) {
+ return 1; // error
+ }
+ }
+ return 0; // success
+}
+
+void MP_WEAK external_flash_setup(void) {
+}
diff --git a/circuitpython/supervisor/shared/external_flash/external_flash.h b/circuitpython/supervisor/shared/external_flash/external_flash.h
new file mode 100644
index 0000000..7966b64
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/external_flash.h
@@ -0,0 +1,55 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_EXTERNAL_FLASH_H
+#define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_EXTERNAL_FLASH_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "py/mpconfig.h"
+
+// Erase sector size.
+#define SPI_FLASH_SECTOR_SIZE (0x1000 - 100)
+
+// These are common across all NOR Flash.
+#define SPI_FLASH_ERASE_SIZE (1 << 12)
+#define SPI_FLASH_PAGE_SIZE (256)
+
+#define SPI_FLASH_SYSTICK_MASK (0x1ff) // 512ms
+#define SPI_FLASH_IDLE_TICK(tick) (((tick) & SPI_FLASH_SYSTICK_MASK) == 2)
+
+#ifndef SPI_FLASH_MAX_BAUDRATE
+#define SPI_FLASH_MAX_BAUDRATE 8000000
+#endif
+
+void supervisor_external_flash_flush(void);
+
+// Configure anything that needs to get set up before the external flash
+// is init'ed. For example, if GPIO needs to be configured to enable the
+// flash chip, as is the case on some boards.
+void external_flash_setup(void);
+
+#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_EXTERNAL_FLASH_H
diff --git a/circuitpython/supervisor/shared/external_flash/external_flash_root_pointers.h b/circuitpython/supervisor/shared/external_flash/external_flash_root_pointers.h
new file mode 100644
index 0000000..0613c9a
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/external_flash_root_pointers.h
@@ -0,0 +1,35 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_EXTERNAL_FLASH_ROOT_POINTERS_H
+#define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_EXTERNAL_FLASH_ROOT_POINTERS_H
+
+#include <stdint.h>
+
+// We use this when we can allocate the whole cache in RAM.
+#define FLASH_ROOT_POINTERS \
+ uint8_t **flash_ram_cache; \
+
+#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_EXTERNAL_FLASH_ROOT_POINTERS_H
diff --git a/circuitpython/supervisor/shared/external_flash/qspi_flash.c b/circuitpython/supervisor/shared/external_flash/qspi_flash.c
new file mode 100644
index 0000000..293654b
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/qspi_flash.c
@@ -0,0 +1,57 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016, 2017, 2018 Scott Shawcroft for Adafruit Industries
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "supervisor/spi_flash_api.h"
+
+#include "supervisor/shared/external_flash/common_commands.h"
+#include "supervisor/shared/external_flash/qspi_flash.h"
+
+void check_quad_enable(const external_flash_device *device) {
+ if (device->quad_enable_bit_mask == 0x00) {
+ return;
+ }
+
+ // Verify that QSPI mode is enabled.
+ uint8_t status;
+ if (device->single_status_byte) {
+ spi_flash_read_command(CMD_READ_STATUS, &status, 1);
+ } else {
+ spi_flash_read_command(CMD_READ_STATUS2, &status, 1);
+ }
+
+ // Check the quad enable bit.
+ if ((status & device->quad_enable_bit_mask) == 0) {
+ uint8_t full_status[2] = {0x00, device->quad_enable_bit_mask};
+ spi_flash_command(CMD_ENABLE_WRITE);
+ if (device->write_status_register_split) {
+ spi_flash_write_command(CMD_WRITE_STATUS_BYTE2, full_status + 1, 1);
+ } else if (device->single_status_byte) {
+ spi_flash_write_command(CMD_WRITE_STATUS_BYTE1, full_status + 1, 1);
+ } else {
+ spi_flash_write_command(CMD_WRITE_STATUS_BYTE1, full_status, 2);
+ }
+ }
+}
diff --git a/circuitpython/supervisor/shared/external_flash/qspi_flash.h b/circuitpython/supervisor/shared/external_flash/qspi_flash.h
new file mode 100644
index 0000000..c0c089e
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/qspi_flash.h
@@ -0,0 +1,31 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_QSPI_FLASH_H
+#define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_QSPI_FLASH_H
+
+void check_quad_enable(const external_flash_device *device);
+
+#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_QSPI_FLASH_H
diff --git a/circuitpython/supervisor/shared/external_flash/spi_flash.c b/circuitpython/supervisor/shared/external_flash/spi_flash.c
new file mode 100644
index 0000000..b47508e
--- /dev/null
+++ b/circuitpython/supervisor/shared/external_flash/spi_flash.c
@@ -0,0 +1,166 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016, 2017 Scott Shawcroft for Adafruit Industries
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#include "supervisor/spi_flash_api.h"
+
+#include <stdint.h>
+#include <string.h>
+
+#include "shared-bindings/busio/SPI.h"
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "supervisor/shared/external_flash/common_commands.h"
+#include "supervisor/shared/external_flash/external_flash.h"
+#include "py/mpconfig.h"
+
+digitalio_digitalinout_obj_t cs_pin;
+busio_spi_obj_t supervisor_flash_spi_bus;
+
+const external_flash_device *flash_device;
+uint32_t spi_flash_baudrate;
+
+// Enable the flash over SPI.
+static bool flash_enable(void) {
+ if (common_hal_busio_spi_try_lock(&supervisor_flash_spi_bus)) {
+ common_hal_digitalio_digitalinout_set_value(&cs_pin, false);
+ return true;
+ }
+ return false;
+}
+
+// Disable the flash over SPI.
+static void flash_disable(void) {
+ common_hal_digitalio_digitalinout_set_value(&cs_pin, true);
+ common_hal_busio_spi_unlock(&supervisor_flash_spi_bus);
+}
+
+static bool transfer(uint8_t *command, uint32_t command_length, uint8_t *data_in, uint8_t *data_out, uint32_t data_length) {
+ if (!flash_enable()) {
+ return false;
+ }
+ bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, command, command_length);
+ if (status) {
+ if (data_in != NULL && data_out != NULL) {
+ status = common_hal_busio_spi_transfer(&supervisor_flash_spi_bus, data_out, data_in, data_length);
+ } else if (data_out != NULL) {
+ status = common_hal_busio_spi_read(&supervisor_flash_spi_bus, data_out, data_length, 0xff);
+ } else if (data_in != NULL) {
+ status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, data_in, data_length);
+ }
+ }
+ flash_disable();
+ return status;
+}
+
+static bool transfer_command(uint8_t command, uint8_t *data_in, uint8_t *data_out, uint32_t data_length) {
+ return transfer(&command, 1, data_in, data_out, data_length);
+}
+
+bool spi_flash_command(uint8_t command) {
+ return transfer_command(command, NULL, NULL, 0);
+}
+
+bool spi_flash_read_command(uint8_t command, uint8_t *data, uint32_t data_length) {
+ return transfer_command(command, NULL, data, data_length);
+}
+
+bool spi_flash_write_command(uint8_t command, uint8_t *data, uint32_t data_length) {
+ return transfer_command(command, data, NULL, data_length);
+}
+
+// Pack the low 24 bits of the address into a uint8_t array.
+static void address_to_bytes(uint32_t address, uint8_t *bytes) {
+ bytes[0] = (address >> 16) & 0xff;
+ bytes[1] = (address >> 8) & 0xff;
+ bytes[2] = address & 0xff;
+}
+
+bool spi_flash_sector_command(uint8_t command, uint32_t address) {
+ uint8_t request[4] = {command, 0x00, 0x00, 0x00};
+ address_to_bytes(address, request + 1);
+ return transfer(request, 4, NULL, NULL, 0);
+}
+
+bool spi_flash_write_data(uint32_t address, uint8_t *data, uint32_t data_length) {
+ uint8_t request[4] = {CMD_PAGE_PROGRAM, 0x00, 0x00, 0x00};
+ common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8);
+ // Write the SPI flash write address into the bytes following the command byte.
+ address_to_bytes(address, request + 1);
+ if (!flash_enable()) {
+ return false;
+ }
+ bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, 4);
+ if (status) {
+ status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, data, data_length);
+ }
+ flash_disable();
+ return status;
+}
+
+bool spi_flash_read_data(uint32_t address, uint8_t *data, uint32_t data_length) {
+ uint8_t request[5] = {CMD_READ_DATA, 0x00, 0x00, 0x00};
+ uint8_t command_length = 4;
+ if (flash_device->supports_fast_read) {
+ request[0] = CMD_FAST_READ_DATA;
+ command_length = 5;
+ }
+ common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8);
+ // Write the SPI flash read address into the bytes following the command byte.
+ address_to_bytes(address, request + 1);
+ if (!flash_enable()) {
+ return false;
+ }
+ bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, command_length);
+ if (status) {
+ status = common_hal_busio_spi_read(&supervisor_flash_spi_bus, data, data_length, 0xff);
+ }
+ flash_disable();
+ return status;
+}
+
+void spi_flash_init(void) {
+ cs_pin.base.type = &digitalio_digitalinout_type;
+ common_hal_digitalio_digitalinout_construct(&cs_pin, SPI_FLASH_CS_PIN);
+
+ // Set CS high (disabled).
+ common_hal_digitalio_digitalinout_switch_to_output(&cs_pin, true, DRIVE_MODE_PUSH_PULL);
+ common_hal_digitalio_digitalinout_never_reset(&cs_pin);
+
+ supervisor_flash_spi_bus.base.type = &busio_spi_type;
+ common_hal_busio_spi_construct(&supervisor_flash_spi_bus, SPI_FLASH_SCK_PIN, SPI_FLASH_MOSI_PIN, SPI_FLASH_MISO_PIN, false);
+ common_hal_busio_spi_never_reset(&supervisor_flash_spi_bus);
+
+ return;
+}
+
+void spi_flash_init_device(const external_flash_device *device) {
+ flash_device = device;
+ spi_flash_baudrate = device->max_clock_speed_mhz * 1000000;
+ if (spi_flash_baudrate > SPI_FLASH_MAX_BAUDRATE) {
+ spi_flash_baudrate = SPI_FLASH_MAX_BAUDRATE;
+ }
+ common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8);
+ return;
+}