updates
[inav.git] / src / main / io / flashfs.c
blob3140e0e1d52ca42cdc13d432c0207c2db7f7e821
1 /*
2 * This file is part of Cleanflight.
4 * Cleanflight is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Cleanflight is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * This provides a stream interface to a flash chip if one is present.
21 * On statup, call flashfsInit() after initialising the flash chip in order to init the filesystem. This will
22 * result in the file pointer being pointed at the first free block found, or at the end of the device if the
23 * flash chip is full.
25 * Note that bits can only be set to 0 when writing, not back to 1 from 0. You must erase sectors in order
26 * to bring bits back to 1 again.
29 #include <stdint.h>
30 #include <stdbool.h>
31 #include <string.h>
33 #include "platform.h"
35 #if defined(USE_FLASHFS)
37 #include "drivers/flash.h"
39 #include "io/flashfs.h"
41 static flashPartition_t *flashPartition;
43 static uint8_t flashWriteBuffer[FLASHFS_WRITE_BUFFER_SIZE];
45 /* The position of our head and tail in the circular flash write buffer.
47 * The head is the index that a byte would be inserted into on writing, while the tail is the index of the
48 * oldest byte that has yet to be written to flash.
50 * When the circular buffer is empty, head == tail
52 static uint8_t bufferHead = 0, bufferTail = 0;
54 // The position of the buffer's tail in the overall flash address space:
55 static uint32_t tailAddress = 0;
57 static void flashfsClearBuffer(void)
59 bufferTail = bufferHead = 0;
62 static bool flashfsBufferIsEmpty(void)
64 return bufferTail == bufferHead;
67 static void flashfsSetTailAddress(uint32_t address)
69 tailAddress = address;
72 void flashfsEraseCompletely(void)
74 flashPartitionErase(flashPartition);
75 flashfsClearBuffer();
76 flashfsSetTailAddress(0);
79 void flashfsClose(void)
81 const flashGeometry_t *geometry = flashGetGeometry();
83 switch(geometry->flashType) {
84 case FLASH_TYPE_NOR:
85 break;
87 case FLASH_TYPE_NAND:
88 flashFlush();
89 // Advance tailAddress to next page boundary.
90 uint32_t pageSize = geometry->pageSize;
91 flashfsSetTailAddress((tailAddress + pageSize - 1) & ~(pageSize - 1));
92 break;
96 /**
97 * Start and end must lie on sector boundaries, or they will be rounded out to sector boundaries such that
98 * all the bytes in the range [start...end) are erased.
100 void flashfsEraseRange(uint32_t start, uint32_t end)
102 const flashGeometry_t *geometry = flashGetGeometry();
104 if (geometry->sectorSize <= 0)
105 return;
107 // Round the start down to a sector boundary
108 int startSector = start / geometry->sectorSize;
110 // And the end upward
111 int endSector = end / geometry->sectorSize;
112 int endRemainder = end % geometry->sectorSize;
114 if (endRemainder > 0) {
115 endSector++;
118 for (int i = startSector; i < endSector; i++) {
119 flashEraseSector(i * geometry->sectorSize);
124 * Return true if the flash is not currently occupied with an operation.
126 bool flashfsIsReady(void)
128 return !!flashPartition;
131 uint32_t flashfsGetSize(void)
133 return flashPartitionSize(flashPartition);
136 static uint32_t flashfsTransmitBufferUsed(void)
138 if (bufferHead >= bufferTail)
139 return bufferHead - bufferTail;
141 return FLASHFS_WRITE_BUFFER_SIZE - bufferTail + bufferHead;
145 * Get the size of the largest single write that flashfs could ever accept without blocking or data loss.
147 uint32_t flashfsGetWriteBufferSize(void)
149 return FLASHFS_WRITE_BUFFER_USABLE;
153 * Get the number of bytes that can currently be written to flashfs without any blocking or data loss.
155 uint32_t flashfsGetWriteBufferFreeSpace(void)
157 return flashfsGetWriteBufferSize() - flashfsTransmitBufferUsed();
161 * Write the given buffers to flash sequentially at the current tail address, advancing the tail address after
162 * each write.
164 * In synchronous mode, waits for the flash to become ready before writing so that every byte requested can be written.
166 * In asynchronous mode, if the flash is busy, then the write is aborted and the routine returns immediately.
167 * In this case the returned number of bytes written will be less than the total amount requested.
169 * Modifies the supplied buffer pointers and sizes to reflect how many bytes remain in each of them.
171 * bufferCount: the number of buffers provided
172 * buffers: an array of pointers to the beginning of buffers
173 * bufferSizes: an array of the sizes of those buffers
174 * sync: true if we should wait for the device to be idle before writes, otherwise if the device is busy the
175 * write will be aborted and this routine will return immediately.
177 * Returns the number of bytes written
179 static uint32_t flashfsWriteBuffers(uint8_t const **buffers, uint32_t *bufferSizes, int bufferCount, bool sync)
181 const flashGeometry_t *geometry = flashGetGeometry();
183 uint32_t bytesTotal = 0;
185 int i;
187 for (i = 0; i < bufferCount; i++) {
188 bytesTotal += bufferSizes[i];
191 if (!sync && !flashIsReady()) {
192 return 0;
195 uint32_t bytesTotalRemaining = bytesTotal;
197 while (bytesTotalRemaining > 0) {
198 uint32_t bytesTotalThisIteration;
199 uint32_t bytesRemainThisIteration;
200 uint32_t currentFlashAddress = tailAddress;
203 * Each page needs to be saved in a separate program operation, so
204 * if we would cross a page boundary, only write up to the boundary in this iteration:
206 if (tailAddress % geometry->pageSize + bytesTotalRemaining > geometry->pageSize) {
207 bytesTotalThisIteration = geometry->pageSize - tailAddress % geometry->pageSize;
208 } else {
209 bytesTotalThisIteration = bytesTotalRemaining;
212 // Are we at EOF already? Abort.
213 if (flashfsIsEOF()) {
214 // May as well throw away any buffered data
215 flashfsClearBuffer();
217 break;
220 bytesRemainThisIteration = bytesTotalThisIteration;
222 for (i = 0; i < bufferCount; i++) {
223 if (bufferSizes[i] > 0) {
224 // Is buffer larger than our write limit? Write our limit out of it
225 if (bufferSizes[i] >= bytesRemainThisIteration) {
226 currentFlashAddress = flashPageProgram(currentFlashAddress, buffers[i], bytesRemainThisIteration);
228 buffers[i] += bytesRemainThisIteration;
229 bufferSizes[i] -= bytesRemainThisIteration;
231 bytesRemainThisIteration = 0;
232 break;
233 } else {
234 // We'll still have more to write after finishing this buffer off
235 currentFlashAddress = flashPageProgram(currentFlashAddress, buffers[i], bufferSizes[i]);
237 bytesRemainThisIteration -= bufferSizes[i];
239 buffers[i] += bufferSizes[i];
240 bufferSizes[i] = 0;
245 bytesTotalRemaining -= bytesTotalThisIteration;
247 // Advance the cursor in the file system to match the bytes we wrote
248 flashfsSetTailAddress(tailAddress + bytesTotalThisIteration);
251 * We'll have to wait for that write to complete before we can issue the next one, so if
252 * the user requested asynchronous writes, break now.
254 if (!sync)
255 break;
258 return bytesTotal - bytesTotalRemaining;
262 * Since the buffered data might wrap around the end of the circular buffer, we can have two segments of data to write,
263 * an initial portion and a possible wrapped portion.
265 * This routine will fill the details of those buffers into the provided arrays, which must be at least 2 elements long.
267 static void flashfsGetDirtyDataBuffers(uint8_t const *buffers[], uint32_t bufferSizes[])
269 buffers[0] = flashWriteBuffer + bufferTail;
270 buffers[1] = flashWriteBuffer + 0;
272 if (bufferHead >= bufferTail) {
273 bufferSizes[0] = bufferHead - bufferTail;
274 bufferSizes[1] = 0;
275 } else {
276 bufferSizes[0] = FLASHFS_WRITE_BUFFER_SIZE - bufferTail;
277 bufferSizes[1] = bufferHead;
282 * Get the current offset of the file pointer within the volume.
284 uint32_t flashfsGetOffset(void)
286 uint8_t const * buffers[2];
287 uint32_t bufferSizes[2];
289 // Dirty data in the buffers contributes to the offset
291 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
293 return tailAddress + bufferSizes[0] + bufferSizes[1];
297 * Called after bytes have been written from the buffer to advance the position of the tail by the given amount.
299 static void flashfsAdvanceTailInBuffer(uint32_t delta)
301 bufferTail += delta;
303 // Wrap tail around the end of the buffer
304 if (bufferTail >= FLASHFS_WRITE_BUFFER_SIZE) {
305 bufferTail -= FLASHFS_WRITE_BUFFER_SIZE;
308 if (flashfsBufferIsEmpty()) {
309 flashfsClearBuffer(); // Bring buffer pointers back to the start to be tidier
314 * If the flash is ready to accept writes, flush the buffer to it.
316 * Returns true if all data in the buffer has been flushed to the device, or false if
317 * there is still data to be written (call flush again later).
319 bool flashfsFlushAsync(void)
321 if (flashfsBufferIsEmpty()) {
322 return true; // Nothing to flush
325 uint8_t const * buffers[2];
326 uint32_t bufferSizes[2];
327 uint32_t bytesWritten;
329 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
330 bytesWritten = flashfsWriteBuffers(buffers, bufferSizes, 2, false);
331 flashfsAdvanceTailInBuffer(bytesWritten);
333 return flashfsBufferIsEmpty();
337 * Wait for the flash to become ready and begin flushing any buffered data to flash.
339 * The flash will still be busy some time after this sync completes, but space will
340 * be freed up to accept more writes in the write buffer.
342 void flashfsFlushSync(void)
344 if (flashfsBufferIsEmpty()) {
345 return; // Nothing to flush
348 uint8_t const * buffers[2];
349 uint32_t bufferSizes[2];
351 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
352 flashfsWriteBuffers(buffers, bufferSizes, 2, true);
354 // We've written our entire buffer now:
355 flashfsClearBuffer();
357 flashFlush();
360 void flashfsSeekAbs(uint32_t offset)
362 flashfsFlushSync();
364 flashfsSetTailAddress(offset);
367 void flashfsSeekRel(int32_t offset)
369 flashfsFlushSync();
371 flashfsSetTailAddress(tailAddress + offset);
375 * Write the given byte asynchronously to the flash. If the buffer overflows, data is silently discarded.
377 void flashfsWriteByte(uint8_t byte)
379 flashWriteBuffer[bufferHead++] = byte;
381 if (bufferHead >= FLASHFS_WRITE_BUFFER_SIZE) {
382 bufferHead = 0;
385 if (flashfsTransmitBufferUsed() >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN) {
386 flashfsFlushAsync();
391 * Write the given buffer to the flash either synchronously or asynchronously depending on the 'sync' parameter.
393 * If writing asynchronously, data will be silently discarded if the buffer overflows.
394 * If writing synchronously, the routine will block waiting for the flash to become ready so will never drop data.
396 void flashfsWrite(const uint8_t *data, unsigned int len, bool sync)
398 uint8_t const * buffers[3];
399 uint32_t bufferSizes[3];
401 // There could be two dirty buffers to write out already:
402 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
404 // Plus the buffer the user supplied:
405 buffers[2] = data;
406 bufferSizes[2] = len;
409 * Would writing this data to our buffer cause our buffer to reach the flush threshold? If so try to write through
410 * to the flash now
412 if (bufferSizes[0] + bufferSizes[1] + bufferSizes[2] >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN) {
413 uint32_t bytesWritten;
415 // Attempt to write all three buffers through to the flash asynchronously
416 bytesWritten = flashfsWriteBuffers(buffers, bufferSizes, 3, false);
418 if (bufferSizes[0] == 0 && bufferSizes[1] == 0) {
419 // We wrote all the data that was previously buffered
420 flashfsClearBuffer();
422 if (bufferSizes[2] == 0) {
423 // And we wrote all the data the user supplied! Job done!
424 return;
426 } else {
427 // We only wrote a portion of the old data, so advance the tail to remove the bytes we did write from the buffer
428 flashfsAdvanceTailInBuffer(bytesWritten);
431 // Is the remainder of the data to be written too big to fit in the buffers?
432 if (bufferSizes[0] + bufferSizes[1] + bufferSizes[2] > FLASHFS_WRITE_BUFFER_USABLE) {
433 if (sync) {
434 // Write it through synchronously
435 flashfsWriteBuffers(buffers, bufferSizes, 3, true);
436 flashfsClearBuffer();
437 } else {
439 * Silently drop the data the user asked to write (i.e. no-op) since we can't buffer it and they
440 * requested async.
444 return;
447 // Fall through and add the remainder of the incoming data to our buffer
448 data = buffers[2];
449 len = bufferSizes[2];
452 // Buffer up the data the user supplied instead of writing it right away
454 // First write the portion before we wrap around the end of the circular buffer
455 unsigned int bufferBytesBeforeWrap = FLASHFS_WRITE_BUFFER_SIZE - bufferHead;
457 unsigned int firstPortion = len < bufferBytesBeforeWrap ? len : bufferBytesBeforeWrap;
459 memcpy(flashWriteBuffer + bufferHead, data, firstPortion);
461 bufferHead += firstPortion;
463 data += firstPortion;
464 len -= firstPortion;
466 // If we wrap the head around, write the remainder to the start of the buffer (if any)
467 if (bufferHead == FLASHFS_WRITE_BUFFER_SIZE) {
468 memcpy(flashWriteBuffer + 0, data, len);
470 bufferHead = len;
475 * Read `len` bytes from the given address into the supplied buffer.
477 * Returns the number of bytes actually read which may be less than that requested.
479 int flashfsReadAbs(uint32_t address, uint8_t *buffer, unsigned int len)
481 int bytesRead;
483 // Did caller try to read past the end of the volume?
484 if (address + len > flashfsGetSize()) {
485 // Truncate their request
486 len = flashfsGetSize() - address;
489 // Since the read could overlap data in our dirty buffers, force a sync to clear those first
490 flashfsFlushSync();
492 bytesRead = flashReadBytes(address, buffer, len);
494 return bytesRead;
498 * Find the offset of the start of the free space on the device (or the size of the device if it is full).
500 int flashfsIdentifyStartOfFreeSpace(void)
502 /* Find the start of the free space on the device by examining the beginning of blocks with a binary search,
503 * looking for ones that appear to be erased. We can achieve this with good accuracy because an erased block
504 * is all bits set to 1, which pretty much never appears in reasonable size substrings of blackbox logs.
506 * To do better we might write a volume header instead, which would mark how much free space remains. But keeping
507 * a header up to date while logging would incur more writes to the flash, which would consume precious write
508 * bandwidth and block more often.
511 enum {
512 /* We can choose whatever power of 2 size we like, which determines how much wastage of free space we'll have
513 * at the end of the last written data. But smaller blocksizes will require more searching.
515 FREE_BLOCK_SIZE = 2048,
517 /* We don't expect valid data to ever contain this many consecutive uint32_t's of all 1 bits: */
518 FREE_BLOCK_TEST_SIZE_INTS = 4, // i.e. 16 bytes
519 FREE_BLOCK_TEST_SIZE_BYTES = FREE_BLOCK_TEST_SIZE_INTS * sizeof(uint32_t),
522 union {
523 uint8_t bytes[FREE_BLOCK_TEST_SIZE_BYTES];
524 uint32_t ints[FREE_BLOCK_TEST_SIZE_INTS];
525 } testBuffer;
527 int left = 0; // Smallest block index in the search region
528 int right = flashfsGetSize() / FREE_BLOCK_SIZE; // One past the largest block index in the search region
529 int mid;
530 int result = right;
531 int i;
532 bool blockErased;
534 while (left < right) {
535 mid = (left + right) / 2;
537 if (flashReadBytes(mid * FREE_BLOCK_SIZE, testBuffer.bytes, FREE_BLOCK_TEST_SIZE_BYTES) < FREE_BLOCK_TEST_SIZE_BYTES) {
538 // Unexpected timeout from flash, so bail early (reporting the device fuller than it really is)
539 break;
542 // Checking the buffer 4 bytes at a time like this is probably faster than byte-by-byte, but I didn't benchmark it :)
543 blockErased = true;
544 for (i = 0; i < FREE_BLOCK_TEST_SIZE_INTS; i++) {
545 if (testBuffer.ints[i] != 0xFFFFFFFF) {
546 blockErased = false;
547 break;
551 if (blockErased) {
552 /* This erased block might be the leftmost erased block in the volume, but we'll need to continue the
553 * search leftwards to find out:
555 result = mid;
557 right = mid;
558 } else {
559 left = mid + 1;
563 return result * FREE_BLOCK_SIZE;
567 * Returns true if the file pointer is at the end of the device.
569 bool flashfsIsEOF(void)
571 return tailAddress >= flashfsGetSize();
575 * Call after initializing the flash chip in order to set up the filesystem.
577 void flashfsInit(void)
579 flashPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_FLASHFS);
581 if (flashPartition) {
582 // Start the file pointer off at the beginning of free space so caller can start writing immediately
583 flashfsSeekAbs(flashfsIdentifyStartOfFreeSpace());
587 #endif