4 * This file is part of BeRTOS.
6 * Bertos is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * As a special exception, you may use this file as part of a free software
21 * library without restriction. Specifically, if other files instantiate
22 * templates or use macros or inline functions from this file, or you compile
23 * this file and link it with other files to produce an executable, this
24 * file does not by itself cause the resulting executable to be covered by
25 * the GNU General Public License. This exception does not however
26 * invalidate any other reasons why the executable file might be covered by
27 * the GNU General Public License.
29 * Copyright 2007 Develer S.r.l. (http://www.develer.com/)
33 * \brief BattFS: a filesystem for embedded platforms (implementation).
37 * \author Francesco Sacchi <batt@develer.com>
43 #include <cfg/debug.h>
44 #include <cfg/macros.h> /* MIN, MAX */
45 #include <cpu/byteorder.h> /* cpu_to_xx */
47 #define LOG_LEVEL LOG_LVL_INFO
48 #define LOG_FORMAT LOG_FMT_VERBOSE
51 #include <string.h> /* memset, memmove */
55 * Convert from memory representation to disk structure.
56 * \note filesystem is in little-endian format.
58 INLINE void battfs_to_disk(struct BattFsPageHeader *hdr, uint8_t *buf)
60 STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
64 buf[2] = hdr->fill >> 8;
67 buf[4] = hdr->pgoff >> 8;
70 * Sequence number is 40 bits long.
71 * No need to take care of wraparonds: the memory will die first!
74 buf[6] = hdr->seq >> 8;
75 buf[7] = hdr->seq >> 16;
76 buf[8] = hdr->seq >> 24;
77 buf[9] = hdr->seq >> 32;
80 * This field must be the last one!
81 * This is needed because if the page is only partially
82 * written, we can use this to detect it.
85 buf[11] = hdr->fcs >> 8;
89 * Convert from disk structure to memory representation.
90 * \note filesystem is in little-endian format.
92 INLINE void disk_to_battfs(uint8_t *buf, struct BattFsPageHeader *hdr)
94 STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
96 hdr->fill = buf[2] << 8 | buf[1];
97 hdr->pgoff = buf[4] << 8 | buf[3];
98 hdr->seq = (seq_t)buf[9] << 32 | (seq_t)buf[8] << 24 | (seq_t)buf[7] << 16 | buf[6] << 8 | buf[5];
99 hdr->fcs = buf[11] << 8 | buf[10];
103 * Compute the fcs of the header.
105 static fcs_t computeFcs(struct BattFsPageHeader *hdr)
107 uint8_t buf[BATTFS_HEADER_LEN];
110 battfs_to_disk(hdr, buf);
112 /* fcs is at the end of whole header */
113 rotating_update(buf, BATTFS_HEADER_LEN - sizeof(fcs_t), &cks);
119 * If available, the cache will be used.
120 * \return the number of bytes read.
122 static size_t diskRead(struct BattFsSuper *disk, pgcnt_t page, pgaddr_t addr, void *buf, size_t size)
124 /* Try to read from cache */
125 if (page == disk->curr_page)
126 return disk->bufferRead(disk, addr, buf, size);
129 return disk->read(disk, page, addr, buf, size);
134 * Read header of \a page in \a hdr.
135 * \return true on success, false otherwise.
137 static bool readHdr(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
139 uint8_t buf[BATTFS_HEADER_LEN];
141 * Read header from disk.
142 * Header is actually a footer, and so
143 * resides at page end.
145 if (diskRead(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
146 != BATTFS_HEADER_LEN)
148 LOG_ERR("Error: page[%d]\n", page);
153 disk_to_battfs(buf, hdr);
159 * Set header on current \a disk page buffer.
160 * \return true on success, false otherwise.
162 static bool setBufferHdr(struct BattFsSuper *disk, struct BattFsPageHeader *hdr)
164 uint8_t buf[BATTFS_HEADER_LEN];
167 battfs_to_disk(hdr, buf);
170 * write header to buffer.
171 * Header is actually a footer, and so
172 * resides at page end.
174 if (disk->bufferWrite(disk, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
175 != BATTFS_HEADER_LEN)
177 LOG_ERR("Error writing to buffer\n");
184 * Count the number of pages from
185 * inode 0 to \a inode in \a filelen_table.
187 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
191 for (inode_t i = 0; i < inode; i++)
192 cnt += filelen_table[i];
198 * Move all pages in page allocation array from \a src to \a src + \a offset.
199 * The number of pages moved is page_count - MAX(dst, src).
201 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
203 pgcnt_t dst = src + offset;
204 memmove(&disk->page_array[dst], &disk->page_array[src], (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
208 /* Fill empty space in array with sentinel */
209 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
210 disk->page_array[page] = PAGE_UNSET_SENTINEL;
215 * Count number of pages per file on \a disk.
216 * This information is registered in \a filelen_table.
217 * Array index represent file inode, while value contained
218 * is the number of pages used by that file.
220 * \return true if ok, false on disk read errors.
221 * \note The whole disk is scanned once.
223 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
225 BattFsPageHeader hdr;
226 disk->free_page_start = 0;
228 /* Count the number of disk page per file */
229 for (pgcnt_t page = 0; page < disk->page_count; page++)
231 if (!readHdr(disk, page, &hdr))
234 /* Increase free space */
235 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
237 /* Check header FCS */
238 if (hdr.fcs == computeFcs(&hdr))
240 ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
242 /* Page is valid and is owned by a file */
243 filelen_table[hdr.inode]++;
245 /* Keep trace of free space */
246 disk->free_bytes -= hdr.fill;
247 disk->free_page_start++;
250 LOG_INFO("free_bytes:%d, free_page_start:%d\n", disk->free_bytes, disk->free_page_start);
256 * Fill page allocation array of \a disk
257 * using file lenghts in \a filelen_table.
259 * The page allocation array is an array containings all file infos.
260 * Is ordered by file, and within each file is ordered by page offset
262 * e.g. : at page array[0] you will find page address of the first page
263 * of the first file (if present).
264 * Free blocks are allocated after the last file.
266 * \return true if ok, false on disk read errors.
267 * \note The whole disk is scanned at max twice.
269 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
271 BattFsPageHeader hdr;
272 pgcnt_t curr_free_page = disk->free_page_start;
273 /* Fill page allocation array */
274 for (pgcnt_t page = 0; page < disk->page_count; page++)
276 if (!readHdr(disk, page, &hdr))
279 /* Check header FCS */
280 if (hdr.fcs == computeFcs(&hdr))
282 /* Compute array position */
283 pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
284 array_pos += hdr.pgoff;
287 /* Check if position is already used by another page of the same file */
288 if (disk->page_array[array_pos] == PAGE_UNSET_SENTINEL)
289 disk->page_array[array_pos] = page;
292 BattFsPageHeader hdr_prv;
294 if (!readHdr(disk, disk->page_array[array_pos], &hdr_prv))
297 /* Check header FCS */
298 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
300 /* Only the very same page with a different seq number can be here */
301 ASSERT(hdr.inode == hdr_prv.inode);
302 ASSERT(hdr.pgoff == hdr_prv.pgoff);
303 ASSERT(hdr.seq != hdr_prv.seq);
305 pgcnt_t new_page, old_page;
309 * Sequence number comparison: since
310 * seq is 40 bits wide, it wraps once
311 * every 1.1E12 times.
312 * The memory will not live enough to
313 * see a wraparound, so we can use a simple
316 if (hdr.seq > hdr_prv.seq)
318 /* Current header is newer than the previuos one */
319 old_page = disk->page_array[array_pos];
321 old_fill = hdr_prv.fill;
325 /* Previous header is newer than the current one */
327 new_page = disk->page_array[array_pos];
332 disk->page_array[array_pos] = new_page;
334 disk->free_bytes += old_fill;
335 /* Shift all array one position to the left, overwriting duplicate page */
336 array_pos -= hdr.pgoff;
337 array_pos += filelen_table[hdr.inode];
338 movePages(disk, array_pos, -1);
339 /* Move back all indexes */
340 filelen_table[hdr.inode]--;
341 disk->free_page_start--;
343 /* Set old page as free */
344 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
345 disk->page_array[curr_free_page++] = old_page;
351 /* Invalid page, keep as free */
352 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
353 LOG_INFO("Page %d invalid, keeping as free\n", page);
354 disk->page_array[curr_free_page++] = page;
362 * Flush the current \a disk buffer.
363 * \return true if ok, false on errors.
365 static bool flushBuffer(struct BattFsSuper *disk)
367 if (disk->cache_dirty)
369 LOG_INFO("Flushing to disk page %d\n", disk->curr_page);
371 if (!(setBufferHdr(disk, &disk->curr_hdr)
372 && disk->erase(disk, disk->curr_page)
373 && disk->save(disk, disk->curr_page)))
376 disk->cache_dirty = false;
382 * Load \a new_page from \a disk in disk page buffer.
383 * If a previuos page is still dirty in the buffer, will be
385 * \return true if ok, false on errors.
387 static bool loadPage(struct BattFsSuper *disk, pgcnt_t new_page)
389 if (disk->curr_page == new_page)
392 LOG_INFO("Loading page %d\n", new_page);
394 if (!(flushBuffer(disk)
395 && disk->load(disk, new_page)))
398 disk->curr_page = new_page;
400 /* Load current header */
401 if (!readHdr(disk, disk->curr_page, &disk->curr_hdr))
409 * Initialize and mount disk described by
411 * \return false on errors, true otherwise.
413 bool battfs_init(struct BattFsSuper *disk)
415 pgoff_t filelen_table[BATTFS_MAX_FILES];
420 /* Init disk device */
421 if (!disk->open(disk))
423 LOG_ERR("open error\n");
427 /* Disk open must set all of these */
430 ASSERT(disk->bufferWrite);
431 ASSERT(disk->bufferRead);
435 ASSERT(disk->page_size);
436 ASSERT(disk->page_count);
437 ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
438 ASSERT(disk->page_array);
440 memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
442 disk->free_bytes = 0;
443 disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
445 /* Initialize page buffer cache */
446 disk->cache_dirty = false;
448 disk->load(disk, disk->curr_page);
449 readHdr(disk, disk->curr_page, &disk->curr_hdr);
451 /* Count pages per file */
452 if (!countDiskFilePages(disk, filelen_table))
454 LOG_ERR("error counting file pages\n");
458 /* Once here, we have filelen_table filled with file lengths */
460 /* Fill page array with sentinel */
461 for (pgcnt_t page = 0; page < disk->page_count; page++)
462 disk->page_array[page] = PAGE_UNSET_SENTINEL;
464 /* Fill page allocation array using filelen_table */
465 if (!fillPageArray(disk, filelen_table))
467 LOG_ERR("error filling page array\n");
470 #warning TODO: shuffle free blocks
472 /* Init list for opened files. */
473 LIST_INIT(&disk->file_opened_list);
479 * \return 0 if ok, EOF on errors.
481 static int battfs_flush(struct KFile *fd)
483 BattFs *fdb = BATTFS_CAST(fd);
485 if (flushBuffer(fdb->disk))
493 * \return 0 if ok, EOF on errors.
495 static int battfs_fileclose(struct KFile *fd)
497 BattFs *fdb = BATTFS_CAST(fd);
505 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff)
507 if (disk->free_page_start >= disk->page_count)
509 #warning TODO space over!
510 LOG_INFO("No disk space available\n");
514 LOG_INFO("Getting new page: %d\n", disk->page_array[disk->free_page_start]);
515 disk->curr_page = disk->page_array[disk->free_page_start++];
516 movePages(disk, new_pos, +1);
517 #warning TODO: move other files!
518 disk->page_array[new_pos] = disk->curr_page;
520 disk->curr_hdr.inode = inode;
521 disk->curr_hdr.pgoff = pgoff;
522 disk->curr_hdr.fill = 0;
523 disk->curr_hdr.seq = 0;
528 * Write to file \a fd \a size bytes from \a buf.
529 * \return The number of bytes written.
531 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
533 BattFs *fdb = BATTFS_CAST(fd);
534 const uint8_t *buf = (const uint8_t *)_buf;
536 size_t total_write = 0;
538 pgaddr_t addr_offset;
540 pgoff_t max_off = fd->size / (fdb->disk->page_size - BATTFS_HEADER_LEN);
542 #warning TODO seek_pos > size?
543 size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
547 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
548 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
549 wr_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
551 /* Handle write outside EOF */
552 if (pg_offset > max_off)
554 if (!getNewPage(fdb->disk, (fdb->disk->page_array - fdb->start) + max_off, fdb->inode, pg_offset))
559 /* Handle cache load of a new page*/
560 if (fdb->start[pg_offset] != fdb->disk->curr_page)
562 LOG_INFO("Re-writing page %d to %d\n", fdb->start[pg_offset], fdb->disk->page_array[fdb->disk->free_page_start]);
563 if (!loadPage(fdb->disk, fdb->start[pg_offset]))
565 #warning TODO set error?
569 /* Get a free page */
570 fdb->disk->curr_page = fdb->disk->page_array[fdb->disk->free_page_start];
571 movePages(fdb->disk, fdb->disk->free_page_start + 1, -1);
573 /* Insert previous page in free blocks list */
574 LOG_INFO("Setting page %d as free\n", fdb->start[pg_offset]);
575 fdb->disk->page_array[fdb->disk->page_count - 1] = fdb->start[pg_offset];
576 /* Assign new page */
577 fdb->start[pg_offset] = fdb->disk->curr_page;
578 fdb->disk->curr_hdr.seq++;
582 LOG_INFO("writing to buffer for page %d, offset %d, size %d\n", fdb->disk->curr_page, addr_offset, wr_len);
583 if (fdb->disk->bufferWrite(fdb->disk, addr_offset, buf, wr_len) != wr_len)
585 #warning TODO set error?
587 fdb->disk->cache_dirty = true;
590 fd->seek_pos += wr_len;
591 total_write += wr_len;
593 fill_t fill_delta = MAX((int32_t)(addr_offset + wr_len) - fdb->disk->curr_hdr.fill, (int32_t)0);
594 fdb->disk->free_bytes -= fill_delta;
595 fdb->disk->curr_hdr.fill += fill_delta;
596 fdb->fd.size += fill_delta;
603 * Read from file \a fd \a size bytes in \a buf.
604 * \return The number of bytes read.
606 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
608 BattFs *fdb = BATTFS_CAST(fd);
609 uint8_t *buf = (uint8_t *)_buf;
611 size_t total_read = 0;
613 pgaddr_t addr_offset;
616 size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
620 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
621 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
622 read_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
625 if (diskRead(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
627 #warning TODO set error?
631 fd->seek_pos += read_len;
632 total_read += read_len;
640 * Search file \a inode in \a disk using a binary search.
641 * \a last is filled with array offset of file start
642 * in disk->page_array if filse is found, otherwise
643 * \a last is filled with the correct insert position
644 * for creating a file with the given \a inode.
645 * \return true if file is found, false otherwisr.
647 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
649 BattFsPageHeader hdr;
650 pgcnt_t first = 0, page;
651 *last = disk->free_page_start;
654 while (first < *last)
656 page = (first + *last) / 2;
658 if (!readHdr(disk, disk->page_array[page], &hdr))
661 fcs = computeFcs(&hdr);
662 if (hdr.fcs == fcs && hdr.inode == inode)
664 *last = page - hdr.pgoff;
667 else if (hdr.fcs == fcs && hdr.inode < inode)
677 * \return true if file \a inode exists on \a disk, false otherwise.
679 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
682 return findFile(disk, inode, &dummy);
686 * Count size of file \a inode on \a disk, starting at pointer \a start
687 * in disk->page_array. Size is written in \a size.
688 * \return true if all s ok, false on disk read errors.
690 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
692 file_size_t size = 0;
693 BattFsPageHeader hdr;
697 if (!readHdr(disk, *start++, &hdr))
699 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
707 * Open file \a inode from \a disk in \a mode.
708 * File context is stored in \a fd.
709 * \return true if ok, false otherwise.
711 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
715 memset(fd, 0, sizeof(*fd));
717 /* Search file start point in disk page array */
719 if (!findFile(disk, inode, &start_pos))
721 if (!(mode & BATTFS_CREATE))
723 /* Create the file */
724 if (!(getNewPage(disk, start_pos, inode, 0)))
727 fd->start = &disk->page_array[start_pos];
730 if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
733 /* Reset seek position */
736 /* Insert file handle in list, ordered by inode, ascending. */
737 FOREACH_NODE(n, &disk->file_opened_list)
739 BattFs *file = containerof(n, BattFs, link);
740 if (file->inode >= inode)
743 INSERT_BEFORE(&fd->link, n);
750 fd->fd.close = battfs_fileclose;
751 fd->fd.flush = battfs_flush;
752 fd->fd.read = battfs_read;
753 fd->fd.reopen = kfile_genericReopen;
754 fd->fd.seek = kfile_genericSeek;
755 fd->fd.write = battfs_write;
757 #warning TODO battfs_error, battfs_clearerr
759 fd->fd.error = battfs_error;
760 fd->fd.clearerr = battfs_clearerr;
763 DB(fd->fd._type = KFT_BATTFS);
771 bool battfs_close(struct BattFsSuper *disk)
776 /* Close all open files */
777 FOREACH_NODE(n, &disk->file_opened_list)
779 BattFs *file = containerof(n, BattFs, link);
780 res += battfs_fileclose(&file->fd);
784 return disk->close(disk) && (res == 0);
788 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
790 BattFsPageHeader hdr;
792 /* Reset page to all 0xff */
793 uint8_t buf[disk->page_size];
794 memset(buf, 0xFF, disk->page_size);
795 disk->bufferWrite(disk, 0, buf, disk->page_size);
801 hdr.fcs = computeFcs(&hdr);
803 if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
805 LOG_ERR("error writing hdr\n");