Version 1.0 bump
[inav/snaewe.git] / src / main / io / flashfs.c
blobd1cc136f973a499460955c9c4bade38c34713276
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.
28 * In future, we can add support for multiple different flash chips by adding a flash device driver vtable
29 * and make calls through that, at the moment flashfs just calls m25p16_* routines explicitly.
32 #include <stdint.h>
33 #include <stdbool.h>
34 #include <string.h>
36 #include "drivers/flash_m25p16.h"
37 #include "flashfs.h"
39 static uint8_t flashWriteBuffer[FLASHFS_WRITE_BUFFER_SIZE];
41 /* The position of our head and tail in the circular flash write buffer.
43 * The head is the index that a byte would be inserted into on writing, while the tail is the index of the
44 * oldest byte that has yet to be written to flash.
46 * When the circular buffer is empty, head == tail
48 static uint8_t bufferHead = 0, bufferTail = 0;
50 // The position of the buffer's tail in the overall flash address space:
51 static uint32_t tailAddress = 0;
53 static void flashfsClearBuffer()
55 bufferTail = bufferHead = 0;
58 static bool flashfsBufferIsEmpty()
60 return bufferTail == bufferHead;
63 static void flashfsSetTailAddress(uint32_t address)
65 tailAddress = address;
68 void flashfsEraseCompletely()
70 m25p16_eraseCompletely();
72 flashfsClearBuffer();
74 flashfsSetTailAddress(0);
77 /**
78 * Start and end must lie on sector boundaries, or they will be rounded out to sector boundaries such that
79 * all the bytes in the range [start...end) are erased.
81 void flashfsEraseRange(uint32_t start, uint32_t end)
83 const flashGeometry_t *geometry = m25p16_getGeometry();
85 if (geometry->sectorSize <= 0)
86 return;
88 // Round the start down to a sector boundary
89 int startSector = start / geometry->sectorSize;
91 // And the end upward
92 int endSector = end / geometry->sectorSize;
93 int endRemainder = end % geometry->sectorSize;
95 if (endRemainder > 0) {
96 endSector++;
99 for (int i = startSector; i < endSector; i++) {
100 m25p16_eraseSector(i * geometry->sectorSize);
105 * Return true if the flash is not currently occupied with an operation.
107 bool flashfsIsReady()
109 return m25p16_isReady();
112 uint32_t flashfsGetSize()
114 return m25p16_getGeometry()->totalSize;
117 static uint32_t flashfsTransmitBufferUsed()
119 if (bufferHead >= bufferTail)
120 return bufferHead - bufferTail;
122 return FLASHFS_WRITE_BUFFER_SIZE - bufferTail + bufferHead;
126 * Get the size of the largest single write that flashfs could ever accept without blocking or data loss.
128 uint32_t flashfsGetWriteBufferSize()
130 return FLASHFS_WRITE_BUFFER_USABLE;
134 * Get the number of bytes that can currently be written to flashfs without any blocking or data loss.
136 uint32_t flashfsGetWriteBufferFreeSpace()
138 return flashfsGetWriteBufferSize() - flashfsTransmitBufferUsed();
141 const flashGeometry_t* flashfsGetGeometry()
143 return m25p16_getGeometry();
147 * Write the given buffers to flash sequentially at the current tail address, advancing the tail address after
148 * each write.
150 * In synchronous mode, waits for the flash to become ready before writing so that every byte requested can be written.
152 * In asynchronous mode, if the flash is busy, then the write is aborted and the routine returns immediately.
153 * In this case the returned number of bytes written will be less than the total amount requested.
155 * Modifies the supplied buffer pointers and sizes to reflect how many bytes remain in each of them.
157 * bufferCount: the number of buffers provided
158 * buffers: an array of pointers to the beginning of buffers
159 * bufferSizes: an array of the sizes of those buffers
160 * sync: true if we should wait for the device to be idle before writes, otherwise if the device is busy the
161 * write will be aborted and this routine will return immediately.
163 * Returns the number of bytes written
165 static uint32_t flashfsWriteBuffers(uint8_t const **buffers, uint32_t *bufferSizes, int bufferCount, bool sync)
167 uint32_t bytesTotal = 0;
169 int i;
171 for (i = 0; i < bufferCount; i++) {
172 bytesTotal += bufferSizes[i];
175 if (!sync && !m25p16_isReady()) {
176 return 0;
179 uint32_t bytesTotalRemaining = bytesTotal;
181 while (bytesTotalRemaining > 0) {
182 uint32_t bytesTotalThisIteration;
183 uint32_t bytesRemainThisIteration;
186 * Each page needs to be saved in a separate program operation, so
187 * if we would cross a page boundary, only write up to the boundary in this iteration:
189 if (tailAddress % M25P16_PAGESIZE + bytesTotalRemaining > M25P16_PAGESIZE) {
190 bytesTotalThisIteration = M25P16_PAGESIZE - tailAddress % M25P16_PAGESIZE;
191 } else {
192 bytesTotalThisIteration = bytesTotalRemaining;
195 // Are we at EOF already? Abort.
196 if (flashfsIsEOF()) {
197 // May as well throw away any buffered data
198 flashfsClearBuffer();
200 break;
203 m25p16_pageProgramBegin(tailAddress);
205 bytesRemainThisIteration = bytesTotalThisIteration;
207 for (i = 0; i < bufferCount; i++) {
208 if (bufferSizes[i] > 0) {
209 // Is buffer larger than our write limit? Write our limit out of it
210 if (bufferSizes[i] >= bytesRemainThisIteration) {
211 m25p16_pageProgramContinue(buffers[i], bytesRemainThisIteration);
213 buffers[i] += bytesRemainThisIteration;
214 bufferSizes[i] -= bytesRemainThisIteration;
216 bytesRemainThisIteration = 0;
217 break;
218 } else {
219 // We'll still have more to write after finishing this buffer off
220 m25p16_pageProgramContinue(buffers[i], bufferSizes[i]);
222 bytesRemainThisIteration -= bufferSizes[i];
224 buffers[i] += bufferSizes[i];
225 bufferSizes[i] = 0;
230 m25p16_pageProgramFinish();
232 bytesTotalRemaining -= bytesTotalThisIteration;
234 // Advance the cursor in the file system to match the bytes we wrote
235 flashfsSetTailAddress(tailAddress + bytesTotalThisIteration);
238 * We'll have to wait for that write to complete before we can issue the next one, so if
239 * the user requested asynchronous writes, break now.
241 if (!sync)
242 break;
245 return bytesTotal - bytesTotalRemaining;
249 * Since the buffered data might wrap around the end of the circular buffer, we can have two segments of data to write,
250 * an initial portion and a possible wrapped portion.
252 * This routine will fill the details of those buffers into the provided arrays, which must be at least 2 elements long.
254 static void flashfsGetDirtyDataBuffers(uint8_t const *buffers[], uint32_t bufferSizes[])
256 buffers[0] = flashWriteBuffer + bufferTail;
257 buffers[1] = flashWriteBuffer + 0;
259 if (bufferHead >= bufferTail) {
260 bufferSizes[0] = bufferHead - bufferTail;
261 bufferSizes[1] = 0;
262 } else {
263 bufferSizes[0] = FLASHFS_WRITE_BUFFER_SIZE - bufferTail;
264 bufferSizes[1] = bufferHead;
269 * Get the current offset of the file pointer within the volume.
271 uint32_t flashfsGetOffset()
273 uint8_t const * buffers[2];
274 uint32_t bufferSizes[2];
276 // Dirty data in the buffers contributes to the offset
278 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
280 return tailAddress + bufferSizes[0] + bufferSizes[1];
284 * Called after bytes have been written from the buffer to advance the position of the tail by the given amount.
286 static void flashfsAdvanceTailInBuffer(uint32_t delta)
288 bufferTail += delta;
290 // Wrap tail around the end of the buffer
291 if (bufferTail >= FLASHFS_WRITE_BUFFER_SIZE) {
292 bufferTail -= FLASHFS_WRITE_BUFFER_SIZE;
295 if (flashfsBufferIsEmpty()) {
296 flashfsClearBuffer(); // Bring buffer pointers back to the start to be tidier
301 * If the flash is ready to accept writes, flush the buffer to it.
303 * Returns true if all data in the buffer has been flushed to the device, or false if
304 * there is still data to be written (call flush again later).
306 bool flashfsFlushAsync()
308 if (flashfsBufferIsEmpty()) {
309 return true; // Nothing to flush
312 uint8_t const * buffers[2];
313 uint32_t bufferSizes[2];
314 uint32_t bytesWritten;
316 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
317 bytesWritten = flashfsWriteBuffers(buffers, bufferSizes, 2, false);
318 flashfsAdvanceTailInBuffer(bytesWritten);
320 return flashfsBufferIsEmpty();
324 * Wait for the flash to become ready and begin flushing any buffered data to flash.
326 * The flash will still be busy some time after this sync completes, but space will
327 * be freed up to accept more writes in the write buffer.
329 void flashfsFlushSync()
331 if (flashfsBufferIsEmpty()) {
332 return; // Nothing to flush
335 uint8_t const * buffers[2];
336 uint32_t bufferSizes[2];
338 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
339 flashfsWriteBuffers(buffers, bufferSizes, 2, true);
341 // We've written our entire buffer now:
342 flashfsClearBuffer();
345 void flashfsSeekAbs(uint32_t offset)
347 flashfsFlushSync();
349 flashfsSetTailAddress(offset);
352 void flashfsSeekRel(int32_t offset)
354 flashfsFlushSync();
356 flashfsSetTailAddress(tailAddress + offset);
360 * Write the given byte asynchronously to the flash. If the buffer overflows, data is silently discarded.
362 void flashfsWriteByte(uint8_t byte)
364 flashWriteBuffer[bufferHead++] = byte;
366 if (bufferHead >= FLASHFS_WRITE_BUFFER_SIZE) {
367 bufferHead = 0;
370 if (flashfsTransmitBufferUsed() >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN) {
371 flashfsFlushAsync();
376 * Write the given buffer to the flash either synchronously or asynchronously depending on the 'sync' parameter.
378 * If writing asynchronously, data will be silently discarded if the buffer overflows.
379 * If writing synchronously, the routine will block waiting for the flash to become ready so will never drop data.
381 void flashfsWrite(const uint8_t *data, unsigned int len, bool sync)
383 uint8_t const * buffers[3];
384 uint32_t bufferSizes[3];
386 // There could be two dirty buffers to write out already:
387 flashfsGetDirtyDataBuffers(buffers, bufferSizes);
389 // Plus the buffer the user supplied:
390 buffers[2] = data;
391 bufferSizes[2] = len;
394 * Would writing this data to our buffer cause our buffer to reach the flush threshold? If so try to write through
395 * to the flash now
397 if (bufferSizes[0] + bufferSizes[1] + bufferSizes[2] >= FLASHFS_WRITE_BUFFER_AUTO_FLUSH_LEN) {
398 uint32_t bytesWritten;
400 // Attempt to write all three buffers through to the flash asynchronously
401 bytesWritten = flashfsWriteBuffers(buffers, bufferSizes, 3, false);
403 if (bufferSizes[0] == 0 && bufferSizes[1] == 0) {
404 // We wrote all the data that was previously buffered
405 flashfsClearBuffer();
407 if (bufferSizes[2] == 0) {
408 // And we wrote all the data the user supplied! Job done!
409 return;
411 } else {
412 // We only wrote a portion of the old data, so advance the tail to remove the bytes we did write from the buffer
413 flashfsAdvanceTailInBuffer(bytesWritten);
416 // Is the remainder of the data to be written too big to fit in the buffers?
417 if (bufferSizes[0] + bufferSizes[1] + bufferSizes[2] > FLASHFS_WRITE_BUFFER_USABLE) {
418 if (sync) {
419 // Write it through synchronously
420 flashfsWriteBuffers(buffers, bufferSizes, 3, true);
421 flashfsClearBuffer();
422 } else {
424 * Silently drop the data the user asked to write (i.e. no-op) since we can't buffer it and they
425 * requested async.
429 return;
432 // Fall through and add the remainder of the incoming data to our buffer
433 data = buffers[2];
434 len = bufferSizes[2];
437 // Buffer up the data the user supplied instead of writing it right away
439 // First write the portion before we wrap around the end of the circular buffer
440 unsigned int bufferBytesBeforeWrap = FLASHFS_WRITE_BUFFER_SIZE - bufferHead;
442 unsigned int firstPortion = len < bufferBytesBeforeWrap ? len : bufferBytesBeforeWrap;
444 memcpy(flashWriteBuffer + bufferHead, data, firstPortion);
446 bufferHead += firstPortion;
448 data += firstPortion;
449 len -= firstPortion;
451 // If we wrap the head around, write the remainder to the start of the buffer (if any)
452 if (bufferHead == FLASHFS_WRITE_BUFFER_SIZE) {
453 memcpy(flashWriteBuffer + 0, data, len);
455 bufferHead = len;
460 * Read `len` bytes from the given address into the supplied buffer.
462 * Returns the number of bytes actually read which may be less than that requested.
464 int flashfsReadAbs(uint32_t address, uint8_t *buffer, unsigned int len)
466 int bytesRead;
468 // Did caller try to read past the end of the volume?
469 if (address + len > flashfsGetSize()) {
470 // Truncate their request
471 len = flashfsGetSize() - address;
474 // Since the read could overlap data in our dirty buffers, force a sync to clear those first
475 flashfsFlushSync();
477 bytesRead = m25p16_readBytes(address, buffer, len);
479 return bytesRead;
483 * Find the offset of the start of the free space on the device (or the size of the device if it is full).
485 int flashfsIdentifyStartOfFreeSpace()
487 /* Find the start of the free space on the device by examining the beginning of blocks with a binary search,
488 * looking for ones that appear to be erased. We can achieve this with good accuracy because an erased block
489 * is all bits set to 1, which pretty much never appears in reasonable size substrings of blackbox logs.
491 * To do better we might write a volume header instead, which would mark how much free space remains. But keeping
492 * a header up to date while logging would incur more writes to the flash, which would consume precious write
493 * bandwidth and block more often.
496 enum {
497 /* We can choose whatever power of 2 size we like, which determines how much wastage of free space we'll have
498 * at the end of the last written data. But smaller blocksizes will require more searching.
500 FREE_BLOCK_SIZE = 2048,
502 /* We don't expect valid data to ever contain this many consecutive uint32_t's of all 1 bits: */
503 FREE_BLOCK_TEST_SIZE_INTS = 4, // i.e. 16 bytes
504 FREE_BLOCK_TEST_SIZE_BYTES = FREE_BLOCK_TEST_SIZE_INTS * sizeof(uint32_t),
507 union {
508 uint8_t bytes[FREE_BLOCK_TEST_SIZE_BYTES];
509 uint32_t ints[FREE_BLOCK_TEST_SIZE_INTS];
510 } testBuffer;
512 int left = 0; // Smallest block index in the search region
513 int right = flashfsGetSize() / FREE_BLOCK_SIZE; // One past the largest block index in the search region
514 int mid;
515 int result = right;
516 int i;
517 bool blockErased;
519 while (left < right) {
520 mid = (left + right) / 2;
522 if (m25p16_readBytes(mid * FREE_BLOCK_SIZE, testBuffer.bytes, FREE_BLOCK_TEST_SIZE_BYTES) < FREE_BLOCK_TEST_SIZE_BYTES) {
523 // Unexpected timeout from flash, so bail early (reporting the device fuller than it really is)
524 break;
527 // Checking the buffer 4 bytes at a time like this is probably faster than byte-by-byte, but I didn't benchmark it :)
528 blockErased = true;
529 for (i = 0; i < FREE_BLOCK_TEST_SIZE_INTS; i++) {
530 if (testBuffer.ints[i] != 0xFFFFFFFF) {
531 blockErased = false;
532 break;
536 if (blockErased) {
537 /* This erased block might be the leftmost erased block in the volume, but we'll need to continue the
538 * search leftwards to find out:
540 result = mid;
542 right = mid;
543 } else {
544 left = mid + 1;
548 return result * FREE_BLOCK_SIZE;
552 * Returns true if the file pointer is at the end of the device.
554 bool flashfsIsEOF() {
555 return tailAddress >= flashfsGetSize();
559 * Call after initializing the flash chip in order to set up the filesystem.
561 void flashfsInit()
563 // If we have a flash chip present at all
564 if (flashfsGetSize() > 0) {
565 // Start the file pointer off at the beginning of free space so caller can start writing immediately
566 flashfsSeekAbs(flashfsIdentifyStartOfFreeSpace());