Fix function brace style
[betaflight.git] / src / main / drivers / flash.c
blob191af158abf4e20dae8e7a1b1937846b59c8f649
1 /*
2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
8 * any later version.
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
21 #include <stdbool.h>
22 #include <stdint.h>
23 #include <string.h>
25 #include "platform.h"
27 #include "build/debug.h"
29 #ifdef USE_FLASH_CHIP
31 #include "flash.h"
32 #include "flash_impl.h"
33 #include "flash_m25p16.h"
34 #include "flash_w25n01g.h"
35 #include "flash_w25q128fv.h"
36 #include "flash_w25m.h"
37 #include "drivers/bus_spi.h"
38 #include "drivers/bus_quadspi.h"
39 #include "drivers/io.h"
40 #include "drivers/time.h"
42 // 20 MHz max SPI frequency
43 #define FLASH_MAX_SPI_CLK_HZ 20000000
44 // 5 MHz max SPI init frequency
45 #define FLASH_MAX_SPI_INIT_CLK 5000000
47 static extDevice_t devInstance;
48 static extDevice_t *dev;
50 static flashDevice_t flashDevice;
51 static flashPartitionTable_t flashPartitionTable;
52 static int flashPartitions = 0;
54 #define FLASH_INSTRUCTION_RDID 0x9F
56 #ifdef USE_QUADSPI
57 static bool flashQuadSpiInit(const flashConfig_t *flashConfig)
59 bool detected = false;
61 enum { TRY_1LINE = 0, TRY_4LINE, BAIL};
62 int phase = TRY_1LINE;
64 QUADSPI_TypeDef *hqspi = quadSpiInstanceByDevice(QUADSPI_CFG_TO_DEV(flashConfig->quadSpiDevice));
66 do {
67 quadSpiSetDivisor(hqspi, QUADSPI_CLOCK_INITIALISATION);
69 // 3 bytes for what we need, but some IC's need 8 dummy cycles after the instruction, so read 4 and make two attempts to
70 // assemble the chip id from the response.
71 uint8_t readIdResponse[4];
73 bool status = false;
74 switch (phase) {
75 case TRY_1LINE:
76 status = quadSpiReceive1LINE(hqspi, FLASH_INSTRUCTION_RDID, 0, readIdResponse, 4);
77 break;
78 case TRY_4LINE:
79 status = quadSpiReceive4LINES(hqspi, FLASH_INSTRUCTION_RDID, 2, readIdResponse, 3);
80 break;
81 default:
82 break;
85 if (!status) {
86 phase++;
87 continue;
90 flashDevice.io.handle.quadSpi = hqspi;
91 flashDevice.io.mode = FLASHIO_QUADSPI;
93 quadSpiSetDivisor(hqspi, QUADSPI_CLOCK_ULTRAFAST);
96 for (uint8_t offset = 0; offset <= 1 && !detected; offset++) {
98 uint32_t chipID = (readIdResponse[offset + 0] << 16) | (readIdResponse[offset + 1] << 8) | (readIdResponse[offset + 2]);
100 if (offset == 0) {
101 #ifdef USE_FLASH_W25Q128FV
102 if (!detected && w25q128fv_detect(&flashDevice, chipID)) {
103 detected = true;
105 #endif
108 if (offset == 1) {
109 #ifdef USE_FLASH_W25N01G
110 if (!detected && w25n01g_detect(&flashDevice, chipID)) {
111 detected = true;
113 #endif
114 #if defined(USE_FLASH_W25M02G)
115 if (!detected && w25m_detect(&flashDevice, chipID)) {
116 detected = true;
118 #endif
121 phase++;
122 } while (phase != BAIL && !detected);
124 return detected;
126 #endif // USE_QUADSPI
128 #ifdef USE_SPI
130 void flashPreInit(const flashConfig_t *flashConfig)
132 spiPreinitRegister(flashConfig->csTag, IOCFG_IPU, 1);
135 static bool flashSpiInit(const flashConfig_t *flashConfig)
137 // Read chip identification and send it to device detect
138 dev = &devInstance;
140 if (flashConfig->csTag) {
141 dev->busType_u.spi.csnPin = IOGetByTag(flashConfig->csTag);
142 } else {
143 return false;
146 if (!IOIsFreeOrPreinit(dev->busType_u.spi.csnPin)) {
147 return false;
150 if (!spiSetBusInstance(dev, flashConfig->spiDevice)) {
151 return false;
154 // Set the callback argument when calling back to this driver for DMA completion
155 dev->callbackArg = (uint32_t)&flashDevice;
157 IOInit(dev->busType_u.spi.csnPin, OWNER_FLASH_CS, 0);
158 IOConfigGPIO(dev->busType_u.spi.csnPin, SPI_IO_CS_CFG);
159 IOHi(dev->busType_u.spi.csnPin);
161 //Maximum speed for standard READ command is 20mHz, other commands tolerate 25mHz
162 spiSetClkDivisor(dev, spiCalculateDivider(FLASH_MAX_SPI_INIT_CLK));
164 flashDevice.io.mode = FLASHIO_SPI;
165 flashDevice.io.handle.dev = dev;
167 delay(50); // short delay required after initialisation of SPI device instance.
170 * Some newer chips require one dummy byte to be read; we can read
171 * 4 bytes for these chips while retaining backward compatibility.
173 uint8_t readIdResponse[4] = { 0 };
175 spiReadRegBuf(dev, FLASH_INSTRUCTION_RDID, readIdResponse, sizeof(readIdResponse));
177 // Manufacturer, memory type, and capacity
178 uint32_t chipID = (readIdResponse[0] << 16) | (readIdResponse[1] << 8) | (readIdResponse[2]);
180 #ifdef USE_FLASH_M25P16
181 if (m25p16_detect(&flashDevice, chipID)) {
182 return true;
184 #endif
186 #ifdef USE_FLASH_W25M512
187 if (w25m_detect(&flashDevice, chipID)) {
188 return true;
190 #endif
192 // Newer chips
193 chipID = (readIdResponse[1] << 16) | (readIdResponse[2] << 8) | (readIdResponse[3]);
195 #ifdef USE_FLASH_W25N01G
196 if (w25n01g_detect(&flashDevice, chipID)) {
197 return true;
199 #endif
201 #ifdef USE_FLASH_W25M02G
202 if (w25m_detect(&flashDevice, chipID)) {
203 return true;
205 #endif
207 spiPreinitByTag(flashConfig->csTag);
209 return false;
211 #endif // USE_SPI
213 bool flashDeviceInit(const flashConfig_t *flashConfig)
215 #ifdef USE_SPI
216 bool useSpi = (SPI_CFG_TO_DEV(flashConfig->spiDevice) != SPIINVALID);
218 if (useSpi) {
219 return flashSpiInit(flashConfig);
221 #endif
223 #ifdef USE_QUADSPI
224 bool useQuadSpi = (QUADSPI_CFG_TO_DEV(flashConfig->quadSpiDevice) != QUADSPIINVALID);
225 if (useQuadSpi) {
226 return flashQuadSpiInit(flashConfig);
228 #endif
230 return false;
233 bool flashIsReady(void)
235 return flashDevice.vTable->isReady(&flashDevice);
238 bool flashWaitForReady(void)
240 return flashDevice.vTable->waitForReady(&flashDevice);
243 void flashEraseSector(uint32_t address)
245 flashDevice.callback = NULL;
246 flashDevice.vTable->eraseSector(&flashDevice, address);
249 void flashEraseCompletely(void)
251 flashDevice.callback = NULL;
252 flashDevice.vTable->eraseCompletely(&flashDevice);
255 /* The callback, if provided, will receive the totoal number of bytes transfered
256 * by each call to flashPageProgramContinue() once the transfer completes.
258 void flashPageProgramBegin(uint32_t address, void (*callback)(uint32_t length))
260 flashDevice.vTable->pageProgramBegin(&flashDevice, address, callback);
263 uint32_t flashPageProgramContinue(const uint8_t **buffers, uint32_t *bufferSizes, uint32_t bufferCount)
265 uint32_t maxBytesToWrite = flashDevice.geometry.pageSize - (flashDevice.currentWriteAddress % flashDevice.geometry.pageSize);
267 if (bufferCount == 0) {
268 return 0;
271 if (bufferSizes[0] >= maxBytesToWrite) {
272 bufferSizes[0] = maxBytesToWrite;
273 bufferCount = 1;
274 } else {
275 maxBytesToWrite -= bufferSizes[0];
276 if ((bufferCount == 2) && (bufferSizes[1] > maxBytesToWrite)) {
277 bufferSizes[1] = maxBytesToWrite;
281 return flashDevice.vTable->pageProgramContinue(&flashDevice, buffers, bufferSizes, bufferCount);
284 void flashPageProgramFinish(void)
286 flashDevice.vTable->pageProgramFinish(&flashDevice);
289 void flashPageProgram(uint32_t address, const uint8_t *data, uint32_t length, void (*callback)(uint32_t length))
291 flashDevice.vTable->pageProgram(&flashDevice, address, data, length, callback);
294 int flashReadBytes(uint32_t address, uint8_t *buffer, uint32_t length)
296 flashDevice.callback = NULL;
297 return flashDevice.vTable->readBytes(&flashDevice, address, buffer, length);
300 void flashFlush(void)
302 if (flashDevice.vTable->flush) {
303 flashDevice.vTable->flush(&flashDevice);
307 static const flashGeometry_t noFlashGeometry = {
308 .totalSize = 0,
311 const flashGeometry_t *flashGetGeometry(void)
313 if (flashDevice.vTable && flashDevice.vTable->getGeometry) {
314 return flashDevice.vTable->getGeometry(&flashDevice);
317 return &noFlashGeometry;
321 * Flash partitioning
323 * Partition table is not currently stored on the flash, in-memory only.
325 * Partitions are required so that Badblock management (inc spare blocks), FlashFS (Blackbox Logging), Configuration and Firmware can be kept separate and tracked.
327 * XXX FIXME
328 * XXX Note that Flash FS must start at sector 0.
329 * XXX There is existing blackbox/flash FS code the relies on this!!!
330 * XXX This restriction can and will be fixed by creating a set of flash operation functions that take partition as an additional parameter.
333 static void flashConfigurePartitions(void)
336 const flashGeometry_t *flashGeometry = flashGetGeometry();
337 if (flashGeometry->totalSize == 0) {
338 return;
341 flashSector_t startSector = 0;
342 flashSector_t endSector = flashGeometry->sectors - 1; // 0 based index
344 const flashPartition_t *badBlockPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_BADBLOCK_MANAGEMENT);
345 if (badBlockPartition) {
346 endSector = badBlockPartition->startSector - 1;
349 #if defined(FIRMWARE_SIZE)
350 const uint32_t firmwareSize = (FIRMWARE_SIZE * 1024);
351 flashSector_t firmwareSectors = (firmwareSize / flashGeometry->sectorSize);
353 if (firmwareSize % flashGeometry->sectorSize > 0) {
354 firmwareSectors++; // needs a portion of a sector.
357 startSector = (endSector + 1) - firmwareSectors; // + 1 for inclusive
359 flashPartitionSet(FLASH_PARTITION_TYPE_FIRMWARE, startSector, endSector);
361 endSector = startSector - 1;
362 startSector = 0;
363 #endif
365 #if defined(CONFIG_IN_EXTERNAL_FLASH)
366 const uint32_t configSize = EEPROM_SIZE;
367 flashSector_t configSectors = (configSize / flashGeometry->sectorSize);
369 if (configSize % flashGeometry->sectorSize > 0) {
370 configSectors++; // needs a portion of a sector.
373 startSector = (endSector + 1) - configSectors; // + 1 for inclusive
375 flashPartitionSet(FLASH_PARTITION_TYPE_CONFIG, startSector, endSector);
377 endSector = startSector - 1;
378 startSector = 0;
379 #endif
381 #ifdef USE_FLASHFS
382 flashPartitionSet(FLASH_PARTITION_TYPE_FLASHFS, startSector, endSector);
383 #endif
386 flashPartition_t *flashPartitionFindByType(uint8_t type)
388 for (int index = 0; index < FLASH_MAX_PARTITIONS; index++) {
389 flashPartition_t *candidate = &flashPartitionTable.partitions[index];
390 if (candidate->type == type) {
391 return candidate;
395 return NULL;
398 const flashPartition_t *flashPartitionFindByIndex(uint8_t index)
400 if (index >= flashPartitions) {
401 return NULL;
404 return &flashPartitionTable.partitions[index];
407 void flashPartitionSet(uint8_t type, uint32_t startSector, uint32_t endSector)
409 flashPartition_t *entry = flashPartitionFindByType(type);
411 if (!entry) {
412 if (flashPartitions == FLASH_MAX_PARTITIONS - 1) {
413 return;
415 entry = &flashPartitionTable.partitions[flashPartitions++];
418 entry->type = type;
419 entry->startSector = startSector;
420 entry->endSector = endSector;
423 // Must be in sync with FLASH_PARTITION_TYPE
424 static const char *flashPartitionNames[] = {
425 "UNKNOWN ",
426 "PARTITION",
427 "FLASHFS ",
428 "BBMGMT ",
429 "FIRMWARE ",
430 "CONFIG ",
433 const char *flashPartitionGetTypeName(flashPartitionType_e type)
435 if (type < ARRAYLEN(flashPartitionNames)) {
436 return flashPartitionNames[type];
439 return NULL;
442 bool flashInit(const flashConfig_t *flashConfig)
444 memset(&flashPartitionTable, 0x00, sizeof(flashPartitionTable));
445 flashPartitions = 0;
447 bool haveFlash = flashDeviceInit(flashConfig);
449 flashConfigurePartitions();
451 return haveFlash;
454 int flashPartitionCount(void)
456 return flashPartitions;
458 #endif // USE_FLASH_CHIP