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)
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/>.
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
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.
41 #include "common/printf.h"
42 #include "drivers/flash.h"
44 #include "io/flashfs.h"
46 static const flashPartition_t
*flashPartition
= NULL
;
47 static const flashGeometry_t
*flashGeometry
= NULL
;
48 static uint32_t flashfsSize
= 0;
50 static DMA_DATA_ZERO_INIT
uint8_t flashWriteBuffer
[FLASHFS_WRITE_BUFFER_SIZE
];
52 /* The position of our head and tail in the circular flash write buffer.
54 * The head is the index that a byte would be inserted into on writing, while the tail is the index of the
55 * oldest byte that has yet to be written to flash.
57 * When the circular buffer is empty, head == tail
59 * The tail is advanced once a write is complete up to the location behind head. The tail is advanced
60 * by a callback from the FLASH write routine. This prevents data being overwritten whilst a write is in progress.
62 static uint8_t bufferHead
= 0;
63 static volatile uint8_t bufferTail
= 0;
65 /* Track if there is new data to write. Until the contents of the buffer have been completely
66 * written flashfsFlushAsync() will be repeatedly called. The tail pointer is only updated
67 * once an asynchronous write has completed. To do so any earlier could result in data being
68 * overwritten in the ring buffer. This routine checks that flashfsFlushAsync() should attempt
69 * to write new data and avoids it writing old data during the race condition that occurs if
70 * its called again before the previous write to FLASH has completed.
72 static volatile bool dataWritten
= true;
77 // Write an incrementing sequence of bytes instead of the requested data and verify
78 DMA_DATA
uint8_t checkFlashBuffer
[FLASHFS_WRITE_BUFFER_SIZE
];
79 uint32_t checkFlashPtr
= 0;
80 uint32_t checkFlashLen
= 0;
81 uint8_t checkFlashWrite
= 0x00;
82 uint8_t checkFlashExpected
= 0x00;
83 uint32_t checkFlashErrors
= 0;
86 // The position of the buffer's tail in the overall flash address space:
87 static uint32_t tailAddress
= 0;
89 static void flashfsClearBuffer(void)
91 bufferTail
= bufferHead
= 0;
94 static bool flashfsBufferIsEmpty(void)
96 return bufferTail
== bufferHead
;
99 static void flashfsSetTailAddress(uint32_t address
)
101 tailAddress
= address
;
104 void flashfsEraseCompletely(void)
106 if (flashGeometry
->sectors
> 0 && flashPartitionCount() > 0) {
107 // if there's a single FLASHFS partition and it uses the entire flash then do a full erase
108 const bool doFullErase
= (flashPartitionCount() == 1) && (FLASH_PARTITION_SECTOR_COUNT(flashPartition
) == flashGeometry
->sectors
);
110 flashEraseCompletely();
113 // TODO - the partial sector-based erase needs to be completely reworked.
114 // All calls to flashfsEraseCompletely() currently expect the erase to run
115 // asynchronously and return immediately. The current implementation performs
116 // the erase synchronously and doesn't return until complete. This breaks calls
117 // from MSP and runtime mode-switched erasing.
119 for (flashSector_t sectorIndex
= flashPartition
->startSector
; sectorIndex
<= flashPartition
->endSector
; sectorIndex
++) {
120 uint32_t sectorAddress
= sectorIndex
* flashGeometry
->sectorSize
;
121 flashEraseSector(sectorAddress
);
126 flashfsClearBuffer();
128 flashfsSetTailAddress(0);
132 * Start and end must lie on sector boundaries, or they will be rounded out to sector boundaries such that
133 * all the bytes in the range [start...end) are erased.
135 void flashfsEraseRange(uint32_t start
, uint32_t end
)
137 if (flashGeometry
->sectorSize
<= 0)
140 // Round the start down to a sector boundary
141 int startSector
= start
/ flashGeometry
->sectorSize
;
143 // And the end upward
144 int endSector
= end
/ flashGeometry
->sectorSize
;
145 int endRemainder
= end
% flashGeometry
->sectorSize
;
147 if (endRemainder
> 0) {
151 for (int sectorIndex
= startSector
; sectorIndex
< endSector
; sectorIndex
++) {
152 uint32_t sectorAddress
= sectorIndex
* flashGeometry
->sectorSize
;
153 flashEraseSector(sectorAddress
);
158 * Return true if the flash is not currently occupied with an operation.
160 bool flashfsIsReady(void)
162 // Check for flash chip existence first, then check if ready.
164 return (flashfsIsSupported() && flashIsReady());
167 bool flashfsIsSupported(void)
169 return flashfsSize
> 0;
172 uint32_t flashfsGetSize(void)
177 static uint32_t flashfsTransmitBufferUsed(void)
179 if (bufferHead
>= bufferTail
)
180 return bufferHead
- bufferTail
;
182 return FLASHFS_WRITE_BUFFER_SIZE
- bufferTail
+ bufferHead
;
186 * Get the size of the largest single write that flashfs could ever accept without blocking or data loss.
188 uint32_t flashfsGetWriteBufferSize(void)
190 return FLASHFS_WRITE_BUFFER_USABLE
;
194 * Get the number of bytes that can currently be written to flashfs without any blocking or data loss.
196 uint32_t flashfsGetWriteBufferFreeSpace(void)
198 return flashfsGetWriteBufferSize() - flashfsTransmitBufferUsed();
202 * Called after bytes have been written from the buffer to advance the position of the tail by the given amount.
204 static void flashfsAdvanceTailInBuffer(uint32_t delta
)
208 // Wrap tail around the end of the buffer
209 if (bufferTail
>= FLASHFS_WRITE_BUFFER_SIZE
) {
210 bufferTail
-= FLASHFS_WRITE_BUFFER_SIZE
;
215 * Write the given buffers to flash sequentially at the current tail address, advancing the tail address after
218 * In synchronous mode, waits for the flash to become ready before writing so that every byte requested can be written.
220 * In asynchronous mode, if the flash is busy, then the write is aborted and the routine returns immediately.
221 * In this case the returned number of bytes written will be less than the total amount requested.
223 * Modifies the supplied buffer pointers and sizes to reflect how many bytes remain in each of them.
225 * bufferCount: the number of buffers provided
226 * buffers: an array of pointers to the beginning of buffers
227 * bufferSizes: an array of the sizes of those buffers
228 * sync: true if we should wait for the device to be idle before writes, otherwise if the device is busy the
229 * write will be aborted and this routine will return immediately.
231 * Returns the number of bytes written
233 void flashfsWriteCallback(uint32_t arg
)
235 // Advance the cursor in the file system to match the bytes we wrote
236 flashfsSetTailAddress(tailAddress
+ arg
);
238 // Free bytes in the ring buffer
239 flashfsAdvanceTailInBuffer(arg
);
241 // Mark that data has been written from the buffer
245 static uint32_t flashfsWriteBuffers(uint8_t const **buffers
, uint32_t *bufferSizes
, int bufferCount
, bool sync
)
247 uint32_t bytesWritten
;
249 // It's OK to overwrite the buffer addresses/lengths being passed in
251 // If sync is true, block until the FLASH device is ready, otherwise return 0 if the device isn't ready
253 while (!flashIsReady());
255 if (!flashIsReady()) {
260 // Are we at EOF already? Abort.
261 if (flashfsIsEOF()) {
266 checkFlashPtr
= tailAddress
;
269 flashPageProgramBegin(tailAddress
, flashfsWriteCallback
);
271 /* Mark that data has yet to be written. There is no race condition as the DMA engine is known
272 * to be idle at this point
276 bytesWritten
= flashPageProgramContinue(buffers
, bufferSizes
, bufferCount
);
279 checkFlashLen
= bytesWritten
;
282 flashPageProgramFinish();
288 * Since the buffered data might wrap around the end of the circular buffer, we can have two segments of data to write,
289 * an initial portion and a possible wrapped portion.
291 * This routine will fill the details of those buffers into the provided arrays, which must be at least 2 elements long.
293 static int flashfsGetDirtyDataBuffers(uint8_t const *buffers
[], uint32_t bufferSizes
[])
295 buffers
[0] = flashWriteBuffer
+ bufferTail
;
296 buffers
[1] = flashWriteBuffer
+ 0;
298 if (bufferHead
> bufferTail
) {
299 bufferSizes
[0] = bufferHead
- bufferTail
;
302 } else if (bufferHead
< bufferTail
) {
303 bufferSizes
[0] = FLASHFS_WRITE_BUFFER_SIZE
- bufferTail
;
304 bufferSizes
[1] = bufferHead
;
305 if (bufferSizes
[1] == 0) {
319 static bool flashfsNewData()
326 * Get the current offset of the file pointer within the volume.
328 uint32_t flashfsGetOffset(void)
330 uint8_t const * buffers
[2];
331 uint32_t bufferSizes
[2];
333 // Dirty data in the buffers contributes to the offset
335 flashfsGetDirtyDataBuffers(buffers
, bufferSizes
);
337 return tailAddress
+ bufferSizes
[0] + bufferSizes
[1];
341 * If the flash is ready to accept writes, flush the buffer to it.
343 * Returns true if all data in the buffer has been flushed to the device, or false if
344 * there is still data to be written (call flush again later).
346 bool flashfsFlushAsync(void)
348 uint8_t const * buffers
[2];
349 uint32_t bufferSizes
[2];
352 if (flashfsBufferIsEmpty()) {
353 return true; // Nothing to flush
356 if (!flashfsNewData()) {
357 // The previous write has yet to complete
362 // Verify the data written last time
364 while (!flashIsReady());
365 flashReadBytes(checkFlashPtr
, checkFlashBuffer
, checkFlashLen
);
367 for (uint32_t i
= 0; i
< checkFlashLen
; i
++) {
368 if (checkFlashBuffer
[i
] != checkFlashExpected
++) {
369 checkFlashErrors
++; // <-- insert breakpoint here to catch errors
375 bufCount
= flashfsGetDirtyDataBuffers(buffers
, bufferSizes
);
377 flashfsWriteBuffers(buffers
, bufferSizes
, bufCount
, false);
380 return flashfsBufferIsEmpty();
384 * Wait for the flash to become ready and begin flushing any buffered data to flash.
386 * The flash will still be busy some time after this sync completes, but space will
387 * be freed up to accept more writes in the write buffer.
389 void flashfsFlushSync(void)
391 uint8_t const * buffers
[2];
392 uint32_t bufferSizes
[2];
395 if (flashfsBufferIsEmpty()) {
396 return; // Nothing to flush
399 bufCount
= flashfsGetDirtyDataBuffers(buffers
, bufferSizes
);
401 flashfsWriteBuffers(buffers
, bufferSizes
, bufCount
, true);
404 while (!flashIsReady());
407 void flashfsSeekAbs(uint32_t offset
)
411 flashfsSetTailAddress(offset
);
415 * Write the given byte asynchronously to the flash. If the buffer overflows, data is silently discarded.
417 void flashfsWriteByte(uint8_t byte
)
420 byte
= checkFlashWrite
++;
423 flashWriteBuffer
[bufferHead
++] = byte
;
425 if (bufferHead
>= FLASHFS_WRITE_BUFFER_SIZE
) {
429 if (flashfsTransmitBufferUsed() >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN
) {
435 * Write the given buffer to the flash either synchronously or asynchronously depending on the 'sync' parameter.
437 * If writing asynchronously, data will be silently discarded if the buffer overflows.
438 * If writing synchronously, the routine will block waiting for the flash to become ready so will never drop data.
440 void flashfsWrite(const uint8_t *data
, unsigned int len
, bool sync
)
442 uint8_t const * buffers
[2];
443 uint32_t bufferSizes
[2];
445 uint32_t totalBufSize
;
447 // Buffer up the data the user supplied instead of writing it right away
448 for (unsigned int i
= 0; i
< len
; i
++) {
449 flashfsWriteByte(data
[i
]);
452 // There could be two dirty buffers to write out already:
453 bufCount
= flashfsGetDirtyDataBuffers(buffers
, bufferSizes
);
454 totalBufSize
= bufferSizes
[0] + bufferSizes
[1];
457 * Would writing this data to our buffer cause our buffer to reach the flush threshold? If so try to write through
460 if (bufCount
&& (totalBufSize
>= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN
)) {
461 flashfsWriteBuffers(buffers
, bufferSizes
, bufCount
, sync
);
466 * Read `len` bytes from the given address into the supplied buffer.
468 * Returns the number of bytes actually read which may be less than that requested.
470 int flashfsReadAbs(uint32_t address
, uint8_t *buffer
, unsigned int len
)
474 // Did caller try to read past the end of the volume?
475 if (address
+ len
> flashfsSize
) {
476 // Truncate their request
477 len
= flashfsSize
- address
;
480 // Since the read could overlap data in our dirty buffers, force a sync to clear those first
483 bytesRead
= flashReadBytes(address
, buffer
, len
);
489 * Find the offset of the start of the free space on the device (or the size of the device if it is full).
491 int flashfsIdentifyStartOfFreeSpace(void)
493 /* Find the start of the free space on the device by examining the beginning of blocks with a binary search,
494 * looking for ones that appear to be erased. We can achieve this with good accuracy because an erased block
495 * is all bits set to 1, which pretty much never appears in reasonable size substrings of blackbox logs.
497 * To do better we might write a volume header instead, which would mark how much free space remains. But keeping
498 * a header up to date while logging would incur more writes to the flash, which would consume precious write
499 * bandwidth and block more often.
503 /* We can choose whatever power of 2 size we like, which determines how much wastage of free space we'll have
504 * at the end of the last written data. But smaller blocksizes will require more searching.
506 FREE_BLOCK_SIZE
= 2048, // XXX This can't be smaller than page size for underlying flash device.
508 /* We don't expect valid data to ever contain this many consecutive uint32_t's of all 1 bits: */
509 FREE_BLOCK_TEST_SIZE_INTS
= 4, // i.e. 16 bytes
510 FREE_BLOCK_TEST_SIZE_BYTES
= FREE_BLOCK_TEST_SIZE_INTS
* sizeof(uint32_t)
513 STATIC_ASSERT(FREE_BLOCK_SIZE
>= FLASH_MAX_PAGE_SIZE
, FREE_BLOCK_SIZE_too_small
);
515 STATIC_DMA_DATA_AUTO
union {
516 uint8_t bytes
[FREE_BLOCK_TEST_SIZE_BYTES
];
517 uint32_t ints
[FREE_BLOCK_TEST_SIZE_INTS
];
520 int left
= 0; // Smallest block index in the search region
521 int right
= flashfsSize
/ FREE_BLOCK_SIZE
; // One past the largest block index in the search region
527 while (left
< right
) {
528 mid
= (left
+ right
) / 2;
530 if (flashReadBytes(mid
* FREE_BLOCK_SIZE
, testBuffer
.bytes
, FREE_BLOCK_TEST_SIZE_BYTES
) < FREE_BLOCK_TEST_SIZE_BYTES
) {
531 // Unexpected timeout from flash, so bail early (reporting the device fuller than it really is)
535 // Checking the buffer 4 bytes at a time like this is probably faster than byte-by-byte, but I didn't benchmark it :)
537 for (i
= 0; i
< FREE_BLOCK_TEST_SIZE_INTS
; i
++) {
538 if (testBuffer
.ints
[i
] != 0xFFFFFFFF) {
545 /* This erased block might be the leftmost erased block in the volume, but we'll need to continue the
546 * search leftwards to find out:
556 return result
* FREE_BLOCK_SIZE
;
560 * Returns true if the file pointer is at the end of the device.
562 bool flashfsIsEOF(void)
564 return tailAddress
>= flashfsSize
;
567 void flashfsClose(void)
569 switch(flashGeometry
->flashType
) {
573 case FLASH_TYPE_NAND
:
576 // Advance tailAddress to next page boundary.
577 uint32_t pageSize
= flashGeometry
->pageSize
;
578 flashfsSetTailAddress((tailAddress
+ pageSize
- 1) & ~(pageSize
- 1));
585 * Call after initializing the flash chip in order to set up the filesystem.
587 void flashfsInit(void)
591 flashPartition
= flashPartitionFindByType(FLASH_PARTITION_TYPE_FLASHFS
);
592 flashGeometry
= flashGetGeometry();
594 if (!flashPartition
) {
598 flashfsSize
= FLASH_PARTITION_SECTOR_COUNT(flashPartition
) * flashGeometry
->sectorSize
;
600 // Start the file pointer off at the beginning of free space so caller can start writing immediately
601 flashfsSeekAbs(flashfsIdentifyStartOfFreeSpace());
604 #ifdef USE_FLASH_TOOLS
605 bool flashfsVerifyEntireFlash(void)
607 flashfsEraseCompletely();
610 uint32_t address
= 0;
611 flashfsSeekAbs(address
);
613 const int bufferSize
= 32;
614 char buffer
[bufferSize
+ 1];
616 const uint32_t testLimit
= flashfsGetSize();
618 for (address
= 0; address
< testLimit
; address
+= bufferSize
) {
619 tfp_sprintf(buffer
, "%08x >> **0123456789ABCDEF**", address
);
620 flashfsWrite((uint8_t*)buffer
, strlen(buffer
), true);
625 char expectedBuffer
[bufferSize
+ 1];
629 int verificationFailures
= 0;
630 for (address
= 0; address
< testLimit
; address
+= bufferSize
) {
631 tfp_sprintf(expectedBuffer
, "%08x >> **0123456789ABCDEF**", address
);
633 memset(buffer
, 0, sizeof(buffer
));
634 int bytesRead
= flashfsReadAbs(address
, (uint8_t *)buffer
, bufferSize
);
636 int result
= strncmp(buffer
, expectedBuffer
, bufferSize
);
637 if (result
!= 0 || bytesRead
!= bufferSize
) {
638 verificationFailures
++;
641 return verificationFailures
== 0;
643 #endif // USE_FLASH_TOOLS