Merge pull request #11795 from bw1129/dyn_notch_minHz_mod
[betaflight.git] / src / main / io / flashfs.c
blob9cd7e869f9fc6016baa3a21c2040b25e8c976d6e
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 /**
22 * This provides a stream interface to a flash chip if one is present.
24 * On statup, call flashfsInit() after initialising the flash chip in order to init the filesystem. This will
25 * result in the file pointer being pointed at the first free block found, or at the end of the device if the
26 * flash chip is full.
28 * Note that bits can only be set to 0 when writing, not back to 1 from 0. You must erase sectors in order
29 * to bring bits back to 1 again.
31 * In future, we can add support for multiple different flash chips by adding a flash device driver vtable
32 * and make calls through that, at the moment flashfs just calls m25p16_* routines explicitly.
35 #include <stdint.h>
36 #include <stdbool.h>
37 #include <string.h>
39 #include "platform.h"
41 #include "build/debug.h"
42 #include "common/printf.h"
43 #include "drivers/flash.h"
44 #include "drivers/light_led.h"
46 #include "io/flashfs.h"
48 typedef enum {
49 FLASHFS_IDLE,
50 FLASHFS_ERASING,
51 } flashfsState_e;
53 static const flashPartition_t *flashPartition = NULL;
54 static const flashGeometry_t *flashGeometry = NULL;
55 static uint32_t flashfsSize = 0;
56 static flashfsState_e flashfsState = FLASHFS_IDLE;
57 static flashSector_t eraseSectorCurrent = 0;
59 static DMA_DATA_ZERO_INIT uint8_t flashWriteBuffer[FLASHFS_WRITE_BUFFER_SIZE];
61 /* The position of our head and tail in the circular flash write buffer.
63 * The head is the index that a byte would be inserted into on writing, while the tail is the index of the
64 * oldest byte that has yet to be written to flash.
66 * When the circular buffer is empty, head == tail
68 * The tail is advanced once a write is complete up to the location behind head. The tail is advanced
69 * by a callback from the FLASH write routine. This prevents data being overwritten whilst a write is in progress.
71 static uint8_t bufferHead = 0;
72 static volatile uint8_t bufferTail = 0;
74 /* Track if there is new data to write. Until the contents of the buffer have been completely
75 * written flashfsFlushAsync() will be repeatedly called. The tail pointer is only updated
76 * once an asynchronous write has completed. To do so any earlier could result in data being
77 * overwritten in the ring buffer. This routine checks that flashfsFlushAsync() should attempt
78 * to write new data and avoids it writing old data during the race condition that occurs if
79 * its called again before the previous write to FLASH has completed.
81 static volatile bool dataWritten = true;
83 //#define CHECK_FLASH
85 #ifdef CHECK_FLASH
86 // Write an incrementing sequence of bytes instead of the requested data and verify
87 DMA_DATA uint8_t checkFlashBuffer[FLASHFS_WRITE_BUFFER_SIZE];
88 uint32_t checkFlashPtr = 0;
89 uint32_t checkFlashLen = 0;
90 uint8_t checkFlashWrite = 0x00;
91 uint8_t checkFlashExpected = 0x00;
92 uint32_t checkFlashErrors = 0;
93 #endif
95 // The position of the buffer's tail in the overall flash address space:
96 static uint32_t tailAddress = 0;
98 static void flashfsClearBuffer(void)
100 bufferTail = bufferHead = 0;
103 static bool flashfsBufferIsEmpty(void)
105 return bufferTail == bufferHead;
108 static void flashfsSetTailAddress(uint32_t address)
110 tailAddress = address;
113 void flashfsEraseCompletely(void)
115 if (flashGeometry->sectors > 0 && flashPartitionCount() > 0) {
116 // if there's a single FLASHFS partition and it uses the entire flash then do a full erase
117 const bool doFullErase = (flashPartitionCount() == 1) && (FLASH_PARTITION_SECTOR_COUNT(flashPartition) == flashGeometry->sectors);
118 if (doFullErase) {
119 flashEraseCompletely();
120 } else {
121 // start asynchronous erase of all sectors
122 eraseSectorCurrent = flashPartition->startSector;
123 flashfsState = FLASHFS_ERASING;
127 flashfsClearBuffer();
129 flashfsSetTailAddress(0);
133 * Start and end must lie on sector boundaries, or they will be rounded out to sector boundaries such that
134 * all the bytes in the range [start...end) are erased.
136 void flashfsEraseRange(uint32_t start, uint32_t end)
138 if (flashGeometry->sectorSize <= 0)
139 return;
141 // Round the start down to a sector boundary
142 int startSector = start / flashGeometry->sectorSize;
144 // And the end upward
145 int endSector = end / flashGeometry->sectorSize;
146 int endRemainder = end % flashGeometry->sectorSize;
148 if (endRemainder > 0) {
149 endSector++;
152 for (int sectorIndex = startSector; sectorIndex < endSector; sectorIndex++) {
153 uint32_t sectorAddress = sectorIndex * flashGeometry->sectorSize;
154 flashEraseSector(sectorAddress);
159 * Return true if the flash is not currently occupied with an operation.
161 bool flashfsIsReady(void)
163 // Check for flash chip existence first, then check if idle and ready.
165 return (flashfsIsSupported() && (flashfsState == FLASHFS_IDLE) && flashIsReady());
168 bool flashfsIsSupported(void)
170 return flashfsSize > 0;
173 uint32_t flashfsGetSize(void)
175 return flashfsSize;
178 static uint32_t flashfsTransmitBufferUsed(void)
180 if (bufferHead >= bufferTail)
181 return bufferHead - bufferTail;
183 return FLASHFS_WRITE_BUFFER_SIZE - bufferTail + bufferHead;
187 * Get the size of the largest single write that flashfs could ever accept without blocking or data loss.
189 uint32_t flashfsGetWriteBufferSize(void)
191 return FLASHFS_WRITE_BUFFER_USABLE;
195 * Get the number of bytes that can currently be written to flashfs without any blocking or data loss.
197 uint32_t flashfsGetWriteBufferFreeSpace(void)
199 return flashfsGetWriteBufferSize() - flashfsTransmitBufferUsed();
203 * Called after bytes have been written from the buffer to advance the position of the tail by the given amount.
205 static void flashfsAdvanceTailInBuffer(uint32_t delta)
207 bufferTail += delta;
209 // Wrap tail around the end of the buffer
210 if (bufferTail >= FLASHFS_WRITE_BUFFER_SIZE) {
211 bufferTail -= FLASHFS_WRITE_BUFFER_SIZE;
216 * Write the given buffers to flash sequentially at the current tail address, advancing the tail address after
217 * each write.
219 * In synchronous mode, waits for the flash to become ready before writing so that every byte requested can be written.
221 * In asynchronous mode, if the flash is busy, then the write is aborted and the routine returns immediately.
222 * In this case the returned number of bytes written will be less than the total amount requested.
224 * Modifies the supplied buffer pointers and sizes to reflect how many bytes remain in each of them.
226 * bufferCount: the number of buffers provided
227 * buffers: an array of pointers to the beginning of buffers
228 * bufferSizes: an array of the sizes of those buffers
229 * sync: true if we should wait for the device to be idle before writes, otherwise if the device is busy the
230 * write will be aborted and this routine will return immediately.
232 * Returns the number of bytes written
234 void flashfsWriteCallback(uint32_t arg)
236 // Advance the cursor in the file system to match the bytes we wrote
237 flashfsSetTailAddress(tailAddress + arg);
239 // Free bytes in the ring buffer
240 flashfsAdvanceTailInBuffer(arg);
242 // Mark that data has been written from the buffer
243 dataWritten = true;
246 static uint32_t flashfsWriteBuffers(uint8_t const **buffers, uint32_t *bufferSizes, int bufferCount, bool sync)
248 uint32_t bytesWritten;
250 // It's OK to overwrite the buffer addresses/lengths being passed in
252 // If sync is true, block until the FLASH device is ready, otherwise return 0 if the device isn't ready
253 if (sync) {
254 while (!flashIsReady());
255 } else {
256 if (!flashIsReady()) {
257 return 0;
261 // Are we at EOF already? Abort.
262 if (flashfsIsEOF()) {
263 return 0;
266 #ifdef CHECK_FLASH
267 checkFlashPtr = tailAddress;
268 #endif
270 flashPageProgramBegin(tailAddress, flashfsWriteCallback);
272 /* Mark that data has yet to be written. There is no race condition as the DMA engine is known
273 * to be idle at this point
275 dataWritten = false;
277 bytesWritten = flashPageProgramContinue(buffers, bufferSizes, bufferCount);
279 #ifdef CHECK_FLASH
280 checkFlashLen = bytesWritten;
281 #endif
283 flashPageProgramFinish();
285 return bytesWritten;
289 * Since the buffered data might wrap around the end of the circular buffer, we can have two segments of data to write,
290 * an initial portion and a possible wrapped portion.
292 * This routine will fill the details of those buffers into the provided arrays, which must be at least 2 elements long.
294 static int flashfsGetDirtyDataBuffers(uint8_t const *buffers[], uint32_t bufferSizes[])
296 buffers[0] = flashWriteBuffer + bufferTail;
297 buffers[1] = flashWriteBuffer + 0;
299 if (bufferHead > bufferTail) {
300 bufferSizes[0] = bufferHead - bufferTail;
301 bufferSizes[1] = 0;
302 return 1;
303 } else if (bufferHead < bufferTail) {
304 bufferSizes[0] = FLASHFS_WRITE_BUFFER_SIZE - bufferTail;
305 bufferSizes[1] = bufferHead;
306 if (bufferSizes[1] == 0) {
307 return 1;
308 } else {
309 return 2;
313 bufferSizes[0] = 0;
314 bufferSizes[1] = 0;
316 return 0;
320 static bool flashfsNewData()
322 return dataWritten;
327 * Get the current offset of the file pointer within the volume.
329 uint32_t flashfsGetOffset(void)
331 uint8_t const * buffers[2];
332 uint32_t bufferSizes[2];
334 // Dirty data in the buffers contributes to the offset
336 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
338 return tailAddress + bufferSizes[0] + bufferSizes[1];
342 * If the flash is ready to accept writes, flush the buffer to it.
344 * Returns true if all data in the buffer has been flushed to the device, or false if
345 * there is still data to be written (call flush again later).
347 bool flashfsFlushAsync(bool force)
349 uint8_t const * buffers[2];
350 uint32_t bufferSizes[2];
351 int bufCount;
353 if (flashfsBufferIsEmpty()) {
354 return true; // Nothing to flush
357 if (!flashfsNewData()) {
358 // The previous write has yet to complete
359 return false;
362 #ifdef CHECK_FLASH
363 // Verify the data written last time
364 if (checkFlashLen) {
365 while (!flashIsReady());
366 flashReadBytes(checkFlashPtr, checkFlashBuffer, checkFlashLen);
368 for (uint32_t i = 0; i < checkFlashLen; i++) {
369 if (checkFlashBuffer[i] != checkFlashExpected++) {
370 checkFlashErrors++; // <-- insert breakpoint here to catch errors
374 #endif
376 bufCount = flashfsGetDirtyDataBuffers(buffers, bufferSizes);
377 uint32_t bufferedBytes = bufferSizes[0] + bufferSizes[1];
379 if (bufCount && (force || (bufferedBytes >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN))) {
380 flashfsWriteBuffers(buffers, bufferSizes, bufCount, false);
383 return flashfsBufferIsEmpty();
387 * Wait for the flash to become ready and begin flushing any buffered data to flash.
389 * The flash will still be busy some time after this sync completes, but space will
390 * be freed up to accept more writes in the write buffer.
392 void flashfsFlushSync(void)
394 uint8_t const * buffers[2];
395 uint32_t bufferSizes[2];
396 int bufCount;
398 if (flashfsBufferIsEmpty()) {
399 return; // Nothing to flush
402 bufCount = flashfsGetDirtyDataBuffers(buffers, bufferSizes);
403 if (bufCount) {
404 flashfsWriteBuffers(buffers, bufferSizes, bufCount, true);
407 while (!flashIsReady());
411 * Asynchronously erase the flash: Check if ready and then erase sector.
413 void flashfsEraseAsync(void)
415 if (flashfsState == FLASHFS_ERASING) {
416 if ((flashfsIsSupported() && flashIsReady())) {
417 if (eraseSectorCurrent <= flashPartition->endSector) {
418 // Erase sector
419 uint32_t sectorAddress = eraseSectorCurrent * flashGeometry->sectorSize;
420 flashEraseSector(sectorAddress);
421 eraseSectorCurrent++;
422 LED1_TOGGLE;
423 } else {
424 // Done erasing
425 flashfsState = FLASHFS_IDLE;
426 LED1_OFF;
432 void flashfsSeekAbs(uint32_t offset)
434 flashfsFlushSync();
436 flashfsSetTailAddress(offset);
440 * Write the given byte asynchronously to the flash. If the buffer overflows, data is silently discarded.
442 void flashfsWriteByte(uint8_t byte)
444 #ifdef CHECK_FLASH
445 byte = checkFlashWrite++;
446 #endif
448 flashWriteBuffer[bufferHead++] = byte;
450 if (bufferHead >= FLASHFS_WRITE_BUFFER_SIZE) {
451 bufferHead = 0;
454 if (flashfsTransmitBufferUsed() >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN) {
455 flashfsFlushAsync(false);
460 * Write the given buffer to the flash either synchronously or asynchronously depending on the 'sync' parameter.
462 * If writing asynchronously, data will be silently discarded if the buffer overflows.
463 * If writing synchronously, the routine will block waiting for the flash to become ready so will never drop data.
465 void flashfsWrite(const uint8_t *data, unsigned int len, bool sync)
467 uint8_t const * buffers[2];
468 uint32_t bufferSizes[2];
469 int bufCount;
470 uint32_t totalBufSize;
472 // Buffer up the data the user supplied instead of writing it right away
473 for (unsigned int i = 0; i < len; i++) {
474 flashfsWriteByte(data[i]);
477 // There could be two dirty buffers to write out already:
478 bufCount = flashfsGetDirtyDataBuffers(buffers, bufferSizes);
479 totalBufSize = bufferSizes[0] + bufferSizes[1];
482 * Would writing this data to our buffer cause our buffer to reach the flush threshold? If so try to write through
483 * to the flash now
485 if (bufCount && (totalBufSize >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN)) {
486 flashfsWriteBuffers(buffers, bufferSizes, bufCount, sync);
491 * Read `len` bytes from the given address into the supplied buffer.
493 * Returns the number of bytes actually read which may be less than that requested.
495 int flashfsReadAbs(uint32_t address, uint8_t *buffer, unsigned int len)
497 int bytesRead;
499 // Did caller try to read past the end of the volume?
500 if (address + len > flashfsSize) {
501 // Truncate their request
502 len = flashfsSize - address;
505 // Since the read could overlap data in our dirty buffers, force a sync to clear those first
506 flashfsFlushSync();
508 bytesRead = flashReadBytes(address, buffer, len);
510 return bytesRead;
514 * Find the offset of the start of the free space on the device (or the size of the device if it is full).
516 int flashfsIdentifyStartOfFreeSpace(void)
518 /* Find the start of the free space on the device by examining the beginning of blocks with a binary search,
519 * looking for ones that appear to be erased. We can achieve this with good accuracy because an erased block
520 * is all bits set to 1, which pretty much never appears in reasonable size substrings of blackbox logs.
522 * To do better we might write a volume header instead, which would mark how much free space remains. But keeping
523 * a header up to date while logging would incur more writes to the flash, which would consume precious write
524 * bandwidth and block more often.
527 enum {
528 /* We can choose whatever power of 2 size we like, which determines how much wastage of free space we'll have
529 * at the end of the last written data. But smaller blocksizes will require more searching.
531 FREE_BLOCK_SIZE = 2048, // XXX This can't be smaller than page size for underlying flash device.
533 /* We don't expect valid data to ever contain this many consecutive uint32_t's of all 1 bits: */
534 FREE_BLOCK_TEST_SIZE_INTS = 4, // i.e. 16 bytes
535 FREE_BLOCK_TEST_SIZE_BYTES = FREE_BLOCK_TEST_SIZE_INTS * sizeof(uint32_t)
538 STATIC_ASSERT(FREE_BLOCK_SIZE >= FLASH_MAX_PAGE_SIZE, FREE_BLOCK_SIZE_too_small);
540 STATIC_DMA_DATA_AUTO union {
541 uint8_t bytes[FREE_BLOCK_TEST_SIZE_BYTES];
542 uint32_t ints[FREE_BLOCK_TEST_SIZE_INTS];
543 } testBuffer;
545 int left = 0; // Smallest block index in the search region
546 int right = flashfsSize / FREE_BLOCK_SIZE; // One past the largest block index in the search region
547 int mid;
548 int result = right;
549 int i;
550 bool blockErased;
552 while (left < right) {
553 mid = (left + right) / 2;
555 if (flashReadBytes(mid * FREE_BLOCK_SIZE, testBuffer.bytes, FREE_BLOCK_TEST_SIZE_BYTES) < FREE_BLOCK_TEST_SIZE_BYTES) {
556 // Unexpected timeout from flash, so bail early (reporting the device fuller than it really is)
557 break;
560 // Checking the buffer 4 bytes at a time like this is probably faster than byte-by-byte, but I didn't benchmark it :)
561 blockErased = true;
562 for (i = 0; i < FREE_BLOCK_TEST_SIZE_INTS; i++) {
563 if (testBuffer.ints[i] != 0xFFFFFFFF) {
564 blockErased = false;
565 break;
569 if (blockErased) {
570 /* This erased block might be the leftmost erased block in the volume, but we'll need to continue the
571 * search leftwards to find out:
573 result = mid;
575 right = mid;
576 } else {
577 left = mid + 1;
581 return result * FREE_BLOCK_SIZE;
585 * Returns true if the file pointer is at the end of the device.
587 bool flashfsIsEOF(void)
589 return tailAddress >= flashfsSize;
592 void flashfsClose(void)
594 switch(flashGeometry->flashType) {
595 case FLASH_TYPE_NOR:
596 break;
598 case FLASH_TYPE_NAND:
599 flashFlush();
601 // Advance tailAddress to next page boundary.
602 uint32_t pageSize = flashGeometry->pageSize;
603 flashfsSetTailAddress((tailAddress + pageSize - 1) & ~(pageSize - 1));
605 break;
610 * Call after initializing the flash chip in order to set up the filesystem.
612 void flashfsInit(void)
614 flashfsSize = 0;
616 flashPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_FLASHFS);
617 flashGeometry = flashGetGeometry();
619 if (!flashPartition) {
620 return;
623 flashfsSize = FLASH_PARTITION_SECTOR_COUNT(flashPartition) * flashGeometry->sectorSize;
625 // Start the file pointer off at the beginning of free space so caller can start writing immediately
626 flashfsSeekAbs(flashfsIdentifyStartOfFreeSpace());
629 #ifdef USE_FLASH_TOOLS
630 bool flashfsVerifyEntireFlash(void)
632 flashfsEraseCompletely();
633 flashfsInit();
635 uint32_t address = 0;
636 flashfsSeekAbs(address);
638 const int bufferSize = 32;
639 char buffer[bufferSize + 1];
641 const uint32_t testLimit = flashfsGetSize();
643 for (address = 0; address < testLimit; address += bufferSize) {
644 tfp_sprintf(buffer, "%08x >> **0123456789ABCDEF**", address);
645 flashfsWrite((uint8_t*)buffer, strlen(buffer), true);
647 flashfsFlushSync();
648 flashfsClose();
650 char expectedBuffer[bufferSize + 1];
652 flashfsSeekAbs(0);
654 int verificationFailures = 0;
655 for (address = 0; address < testLimit; address += bufferSize) {
656 tfp_sprintf(expectedBuffer, "%08x >> **0123456789ABCDEF**", address);
658 memset(buffer, 0, sizeof(buffer));
659 int bytesRead = flashfsReadAbs(address, (uint8_t *)buffer, bufferSize);
661 int result = strncmp(buffer, expectedBuffer, bufferSize);
662 if (result != 0 || bytesRead != bufferSize) {
663 verificationFailures++;
666 return verificationFailures == 0;
668 #endif // USE_FLASH_TOOLS