Fix STM32H750 target support (#12091)
[betaflight.git] / src / main / drivers / flash.c
blob773d9f2399f8b040a1be7937c7a83c640f0b926c
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 if (detected) {
122 flashDevice.geometry.jedecId = chipID;
125 phase++;
126 } while (phase != BAIL && !detected);
128 return detected;
130 #endif // USE_QUADSPI
132 #ifdef USE_SPI
134 void flashPreInit(const flashConfig_t *flashConfig)
136 spiPreinitRegister(flashConfig->csTag, IOCFG_IPU, 1);
139 static bool flashSpiInit(const flashConfig_t *flashConfig)
141 bool detected = false;
142 // Read chip identification and send it to device detect
143 dev = &devInstance;
145 if (flashConfig->csTag) {
146 dev->busType_u.spi.csnPin = IOGetByTag(flashConfig->csTag);
147 } else {
148 return false;
151 if (!IOIsFreeOrPreinit(dev->busType_u.spi.csnPin)) {
152 return false;
155 if (!spiSetBusInstance(dev, flashConfig->spiDevice)) {
156 return false;
159 // Set the callback argument when calling back to this driver for DMA completion
160 dev->callbackArg = (uint32_t)&flashDevice;
162 IOInit(dev->busType_u.spi.csnPin, OWNER_FLASH_CS, 0);
163 IOConfigGPIO(dev->busType_u.spi.csnPin, SPI_IO_CS_CFG);
164 IOHi(dev->busType_u.spi.csnPin);
166 //Maximum speed for standard READ command is 20mHz, other commands tolerate 25mHz
167 spiSetClkDivisor(dev, spiCalculateDivider(FLASH_MAX_SPI_INIT_CLK));
169 flashDevice.io.mode = FLASHIO_SPI;
170 flashDevice.io.handle.dev = dev;
172 delay(50); // short delay required after initialisation of SPI device instance.
175 * Some newer chips require one dummy byte to be read; we can read
176 * 4 bytes for these chips while retaining backward compatibility.
178 uint8_t readIdResponse[4] = { 0 };
180 spiReadRegBuf(dev, FLASH_INSTRUCTION_RDID, readIdResponse, sizeof(readIdResponse));
182 // Manufacturer, memory type, and capacity
183 uint32_t chipID = (readIdResponse[0] << 16) | (readIdResponse[1] << 8) | (readIdResponse[2]);
185 #ifdef USE_FLASH_M25P16
186 if (m25p16_detect(&flashDevice, chipID)) {
187 detected = true;
189 #endif
191 #if defined(USE_FLASH_W25M512) || defined(USE_FLASH_W25M)
192 if (!detected && w25m_detect(&flashDevice, chipID)) {
193 detected = true;
195 #endif
197 if (!detected) {
198 // Newer chips
199 chipID = (readIdResponse[1] << 16) | (readIdResponse[2] << 8) | (readIdResponse[3]);
202 #ifdef USE_FLASH_W25N01G
203 if (!detected && w25n01g_detect(&flashDevice, chipID)) {
204 detected = true;
206 #endif
208 #ifdef USE_FLASH_W25M02G
209 if (!detected && w25m_detect(&flashDevice, chipID)) {
210 detected = true;
212 #endif
214 if (detected) {
215 flashDevice.geometry.jedecId = chipID;
216 return detected;
219 spiPreinitByTag(flashConfig->csTag);
221 return false;
223 #endif // USE_SPI
225 bool flashDeviceInit(const flashConfig_t *flashConfig)
227 #ifdef USE_SPI
228 bool useSpi = (SPI_CFG_TO_DEV(flashConfig->spiDevice) != SPIINVALID);
230 if (useSpi) {
231 return flashSpiInit(flashConfig);
233 #endif
235 #ifdef USE_QUADSPI
236 bool useQuadSpi = (QUADSPI_CFG_TO_DEV(flashConfig->quadSpiDevice) != QUADSPIINVALID);
237 if (useQuadSpi) {
238 return flashQuadSpiInit(flashConfig);
240 #endif
242 return false;
245 bool flashIsReady(void)
247 return flashDevice.vTable->isReady(&flashDevice);
250 bool flashWaitForReady(void)
252 return flashDevice.vTable->waitForReady(&flashDevice);
255 void flashEraseSector(uint32_t address)
257 flashDevice.callback = NULL;
258 flashDevice.vTable->eraseSector(&flashDevice, address);
261 void flashEraseCompletely(void)
263 flashDevice.callback = NULL;
264 flashDevice.vTable->eraseCompletely(&flashDevice);
267 /* The callback, if provided, will receive the totoal number of bytes transfered
268 * by each call to flashPageProgramContinue() once the transfer completes.
270 void flashPageProgramBegin(uint32_t address, void (*callback)(uint32_t length))
272 flashDevice.vTable->pageProgramBegin(&flashDevice, address, callback);
275 uint32_t flashPageProgramContinue(const uint8_t **buffers, uint32_t *bufferSizes, uint32_t bufferCount)
277 uint32_t maxBytesToWrite = flashDevice.geometry.pageSize - (flashDevice.currentWriteAddress % flashDevice.geometry.pageSize);
279 if (bufferCount == 0) {
280 return 0;
283 if (bufferSizes[0] >= maxBytesToWrite) {
284 bufferSizes[0] = maxBytesToWrite;
285 bufferCount = 1;
286 } else {
287 maxBytesToWrite -= bufferSizes[0];
288 if ((bufferCount == 2) && (bufferSizes[1] > maxBytesToWrite)) {
289 bufferSizes[1] = maxBytesToWrite;
293 return flashDevice.vTable->pageProgramContinue(&flashDevice, buffers, bufferSizes, bufferCount);
296 void flashPageProgramFinish(void)
298 flashDevice.vTable->pageProgramFinish(&flashDevice);
301 void flashPageProgram(uint32_t address, const uint8_t *data, uint32_t length, void (*callback)(uint32_t length))
303 flashDevice.vTable->pageProgram(&flashDevice, address, data, length, callback);
306 int flashReadBytes(uint32_t address, uint8_t *buffer, uint32_t length)
308 flashDevice.callback = NULL;
309 return flashDevice.vTable->readBytes(&flashDevice, address, buffer, length);
312 void flashFlush(void)
314 if (flashDevice.vTable->flush) {
315 flashDevice.vTable->flush(&flashDevice);
319 static const flashGeometry_t noFlashGeometry = {
320 .totalSize = 0,
323 const flashGeometry_t *flashGetGeometry(void)
325 if (flashDevice.vTable && flashDevice.vTable->getGeometry) {
326 return flashDevice.vTable->getGeometry(&flashDevice);
329 return &noFlashGeometry;
333 * Flash partitioning
335 * Partition table is not currently stored on the flash, in-memory only.
337 * Partitions are required so that Badblock management (inc spare blocks), FlashFS (Blackbox Logging), Configuration and Firmware can be kept separate and tracked.
339 * XXX FIXME
340 * XXX Note that Flash FS must start at sector 0.
341 * XXX There is existing blackbox/flash FS code the relies on this!!!
342 * XXX This restriction can and will be fixed by creating a set of flash operation functions that take partition as an additional parameter.
345 static void flashConfigurePartitions(void)
347 #if defined(FIRMWARE_SIZE) || defined(CONFIG_IN_EXTERNAL_FLASH) || defined(USE_FLASHFS)
348 const flashGeometry_t *flashGeometry = flashGetGeometry();
349 if (flashGeometry->totalSize == 0) {
350 return;
353 flashSector_t startSector = 0;
354 flashSector_t endSector = flashGeometry->sectors - 1; // 0 based index
356 const flashPartition_t *badBlockPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_BADBLOCK_MANAGEMENT);
357 if (badBlockPartition) {
358 endSector = badBlockPartition->startSector - 1;
360 #endif
362 #if defined(FIRMWARE_SIZE)
363 const uint32_t firmwareSize = (FIRMWARE_SIZE * 1024);
364 flashSector_t firmwareSectors = (firmwareSize / flashGeometry->sectorSize);
366 if (firmwareSize % flashGeometry->sectorSize > 0) {
367 firmwareSectors++; // needs a portion of a sector.
370 startSector = (endSector + 1) - firmwareSectors; // + 1 for inclusive
372 flashPartitionSet(FLASH_PARTITION_TYPE_FIRMWARE, startSector, endSector);
374 endSector = startSector - 1;
375 startSector = 0;
376 #endif
378 #if defined(CONFIG_IN_EXTERNAL_FLASH)
379 const uint32_t configSize = EEPROM_SIZE;
380 flashSector_t configSectors = (configSize / flashGeometry->sectorSize);
382 if (configSize % flashGeometry->sectorSize > 0) {
383 configSectors++; // needs a portion of a sector.
386 startSector = (endSector + 1) - configSectors; // + 1 for inclusive
388 flashPartitionSet(FLASH_PARTITION_TYPE_CONFIG, startSector, endSector);
390 endSector = startSector - 1;
391 startSector = 0;
392 #endif
394 #ifdef USE_FLASHFS
395 flashPartitionSet(FLASH_PARTITION_TYPE_FLASHFS, startSector, endSector);
396 #endif
399 flashPartition_t *flashPartitionFindByType(uint8_t type)
401 for (int index = 0; index < FLASH_MAX_PARTITIONS; index++) {
402 flashPartition_t *candidate = &flashPartitionTable.partitions[index];
403 if (candidate->type == type) {
404 return candidate;
408 return NULL;
411 const flashPartition_t *flashPartitionFindByIndex(uint8_t index)
413 if (index >= flashPartitions) {
414 return NULL;
417 return &flashPartitionTable.partitions[index];
420 void flashPartitionSet(uint8_t type, uint32_t startSector, uint32_t endSector)
422 flashPartition_t *entry = flashPartitionFindByType(type);
424 if (!entry) {
425 if (flashPartitions == FLASH_MAX_PARTITIONS - 1) {
426 return;
428 entry = &flashPartitionTable.partitions[flashPartitions++];
431 entry->type = type;
432 entry->startSector = startSector;
433 entry->endSector = endSector;
436 // Must be in sync with FLASH_PARTITION_TYPE
437 static const char *flashPartitionNames[] = {
438 "UNKNOWN ",
439 "PARTITION",
440 "FLASHFS ",
441 "BBMGMT ",
442 "FIRMWARE ",
443 "CONFIG ",
446 const char *flashPartitionGetTypeName(flashPartitionType_e type)
448 if (type < ARRAYLEN(flashPartitionNames)) {
449 return flashPartitionNames[type];
452 return NULL;
455 bool flashInit(const flashConfig_t *flashConfig)
457 memset(&flashPartitionTable, 0x00, sizeof(flashPartitionTable));
458 flashPartitions = 0;
460 bool haveFlash = flashDeviceInit(flashConfig);
462 flashConfigurePartitions();
464 return haveFlash;
467 int flashPartitionCount(void)
469 return flashPartitions;
471 #endif // USE_FLASH_CHIP