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("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];
166 #warning FIXME:refactor computeFcs to save time and stack
167 hdr->fcs = computeFcs(hdr);
169 battfs_to_disk(hdr, buf);
172 * write header to buffer.
173 * Header is actually a footer, and so
174 * resides at page end.
176 if (disk->bufferWrite(disk, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
177 != BATTFS_HEADER_LEN)
179 LOG_ERR("writing to buffer\n");
186 * Count the number of pages from
187 * inode 0 to \a inode in \a filelen_table.
189 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
193 for (inode_t i = 0; i < inode; i++)
194 cnt += filelen_table[i];
200 * Move all pages in page allocation array from \a src to \a src + \a offset.
201 * The number of pages moved is page_count - MAX(dst, src).
203 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
205 pgcnt_t dst = src + offset;
206 LOG_INFO("src %d, offset %d, size %d\n", src, offset, (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
207 memmove(&disk->page_array[dst], &disk->page_array[src], (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
211 /* Fill empty space in array with sentinel */
212 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
213 disk->page_array[page] = PAGE_UNSET_SENTINEL;
218 * Count number of pages per file on \a disk.
219 * This information is registered in \a filelen_table.
220 * Array index represent file inode, while value contained
221 * is the number of pages used by that file.
223 * \return true if ok, false on disk read errors.
224 * \note The whole disk is scanned once.
226 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
228 BattFsPageHeader hdr;
229 disk->free_page_start = 0;
231 /* Count the number of disk page per file */
232 for (pgcnt_t page = 0; page < disk->page_count; page++)
234 if (!readHdr(disk, page, &hdr))
237 /* Increase free space */
238 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
240 /* Check header FCS */
241 if (hdr.fcs == computeFcs(&hdr))
243 ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
245 /* Page is valid and is owned by a file */
246 filelen_table[hdr.inode]++;
248 /* Keep trace of free space */
249 disk->free_bytes -= hdr.fill;
250 disk->free_page_start++;
253 LOG_INFO("free_bytes:%d, free_page_start:%d\n", disk->free_bytes, disk->free_page_start);
259 * Fill page allocation array of \a disk
260 * using file lenghts in \a filelen_table.
262 * The page allocation array is an array containings all file infos.
263 * Is ordered by file, and within each file is ordered by page offset
265 * e.g. : at page array[0] you will find page address of the first page
266 * of the first file (if present).
267 * Free blocks are allocated after the last file.
269 * \return true if ok, false on disk read errors.
270 * \note The whole disk is scanned at max twice.
272 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
274 BattFsPageHeader hdr;
275 pgcnt_t curr_free_page = disk->free_page_start;
276 /* Fill page allocation array */
277 for (pgcnt_t page = 0; page < disk->page_count; page++)
279 if (!readHdr(disk, page, &hdr))
282 /* Check header FCS */
283 if (hdr.fcs == computeFcs(&hdr))
285 /* Compute array position */
286 pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
287 array_pos += hdr.pgoff;
290 /* Check if position is already used by another page of the same file */
291 if (disk->page_array[array_pos] == PAGE_UNSET_SENTINEL)
292 disk->page_array[array_pos] = page;
295 BattFsPageHeader hdr_prv;
297 if (!readHdr(disk, disk->page_array[array_pos], &hdr_prv))
300 /* Check header FCS */
301 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
303 /* Only the very same page with a different seq number can be here */
304 ASSERT(hdr.inode == hdr_prv.inode);
305 ASSERT(hdr.pgoff == hdr_prv.pgoff);
306 ASSERT(hdr.seq != hdr_prv.seq);
308 pgcnt_t new_page, old_page;
312 * Sequence number comparison: since
313 * seq is 40 bits wide, it wraps once
314 * every 1.1E12 times.
315 * The memory will not live enough to
316 * see a wraparound, so we can use a simple
319 if (hdr.seq > hdr_prv.seq)
321 /* Current header is newer than the previuos one */
322 old_page = disk->page_array[array_pos];
324 old_fill = hdr_prv.fill;
328 /* Previous header is newer than the current one */
330 new_page = disk->page_array[array_pos];
335 disk->page_array[array_pos] = new_page;
337 disk->free_bytes += old_fill;
338 /* Shift all array one position to the left, overwriting duplicate page */
339 array_pos -= hdr.pgoff;
340 array_pos += filelen_table[hdr.inode];
341 movePages(disk, array_pos, -1);
342 /* Move back all indexes */
343 filelen_table[hdr.inode]--;
344 disk->free_page_start--;
346 /* Set old page as free */
347 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
348 disk->page_array[curr_free_page++] = old_page;
354 /* Invalid page, keep as free */
355 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
356 LOG_INFO("Page %d invalid, keeping as free\n", page);
357 disk->page_array[curr_free_page++] = page;
365 * Flush the current \a disk buffer.
366 * \return true if ok, false on errors.
368 static bool flushBuffer(struct BattFsSuper *disk)
370 if (disk->cache_dirty)
372 LOG_INFO("Flushing to disk page %d\n", disk->curr_page);
374 if (!(setBufferHdr(disk, &disk->curr_hdr)
375 && disk->erase(disk, disk->curr_page)
376 && disk->save(disk, disk->curr_page)))
379 disk->cache_dirty = false;
385 * Load \a new_page from \a disk in disk page buffer.
386 * If a previuos page is still dirty in the buffer, will be
388 * \return true if ok, false on errors.
390 static bool loadPage(struct BattFsSuper *disk, pgcnt_t new_page)
392 if (disk->curr_page == new_page)
395 LOG_INFO("Loading page %d\n", new_page);
397 if (!(flushBuffer(disk)
398 && disk->load(disk, new_page)))
401 disk->curr_page = new_page;
403 /* Load current header */
404 if (!readHdr(disk, disk->curr_page, &disk->curr_hdr))
412 * Initialize and mount disk described by
414 * \return false on errors, true otherwise.
416 bool battfs_init(struct BattFsSuper *disk)
418 pgoff_t filelen_table[BATTFS_MAX_FILES];
423 /* Init disk device */
424 if (!disk->open(disk))
426 LOG_ERR("open error\n");
430 /* Disk open must set all of these */
433 ASSERT(disk->bufferWrite);
434 ASSERT(disk->bufferRead);
438 ASSERT(disk->page_size);
439 ASSERT(disk->page_count);
440 ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
441 ASSERT(disk->page_array);
443 memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
445 disk->free_bytes = 0;
446 disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
448 /* Initialize page buffer cache */
449 disk->cache_dirty = false;
451 disk->load(disk, disk->curr_page);
452 readHdr(disk, disk->curr_page, &disk->curr_hdr);
454 /* Count pages per file */
455 if (!countDiskFilePages(disk, filelen_table))
457 LOG_ERR("counting file pages\n");
461 /* Once here, we have filelen_table filled with file lengths */
463 /* Fill page array with sentinel */
464 for (pgcnt_t page = 0; page < disk->page_count; page++)
465 disk->page_array[page] = PAGE_UNSET_SENTINEL;
467 /* Fill page allocation array using filelen_table */
468 if (!fillPageArray(disk, filelen_table))
470 LOG_ERR("filling page array\n");
473 #warning TODO: shuffle free blocks
475 /* Init list for opened files. */
476 LIST_INIT(&disk->file_opened_list);
482 * \return 0 if ok, EOF on errors.
484 static int battfs_flush(struct KFile *fd)
486 BattFs *fdb = BATTFS_CAST(fd);
488 if (flushBuffer(fdb->disk))
496 * \return 0 if ok, EOF on errors.
498 static int battfs_fileclose(struct KFile *fd)
500 BattFs *fdb = BATTFS_CAST(fd);
508 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff)
510 if (disk->free_page_start >= disk->page_count)
512 #warning TODO space over!
513 LOG_INFO("No disk space available\n");
517 LOG_INFO("Getting new page %d, pos %d\n", disk->page_array[disk->free_page_start], new_pos);
518 disk->curr_page = disk->page_array[disk->free_page_start++];
519 memmove(&disk->page_array[new_pos + 1], &disk->page_array[new_pos], (disk->free_page_start - new_pos - 1) * sizeof(pgcnt_t));
520 #warning TODO: move other files!
521 disk->page_array[new_pos] = disk->curr_page;
522 disk->cache_dirty = true;
524 disk->curr_hdr.inode = inode;
525 disk->curr_hdr.pgoff = pgoff;
526 disk->curr_hdr.fill = 0;
527 disk->curr_hdr.seq = 0;
532 * Write to file \a fd \a size bytes from \a buf.
533 * \return The number of bytes written.
535 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
537 BattFs *fdb = BATTFS_CAST(fd);
538 const uint8_t *buf = (const uint8_t *)_buf;
540 size_t total_write = 0;
542 pgaddr_t addr_offset;
545 #warning TODO seek_pos > size?
549 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
550 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
551 wr_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
553 /* Handle write outside EOF */
554 if (pg_offset > fdb->max_off)
556 if (!getNewPage(fdb->disk, (fdb->disk->page_array - fdb->start) + pg_offset, fdb->inode, pg_offset))
558 fdb->max_off = pg_offset;
560 /* Handle cache load of a new page*/
561 else if (fdb->start[pg_offset] != fdb->disk->curr_page)
563 LOG_INFO("Re-writing page %d to %d\n", fdb->start[pg_offset], fdb->disk->page_array[fdb->disk->free_page_start]);
564 if (!loadPage(fdb->disk, fdb->start[pg_offset]))
566 #warning TODO set error?
570 /* Get a free page */
571 fdb->disk->curr_page = fdb->disk->page_array[fdb->disk->free_page_start];
572 movePages(fdb->disk, fdb->disk->free_page_start + 1, -1);
574 /* Insert previous page in free blocks list */
575 LOG_INFO("Setting page %d as free\n", fdb->start[pg_offset]);
576 fdb->disk->page_array[fdb->disk->page_count - 1] = fdb->start[pg_offset];
577 /* Assign new page */
578 fdb->start[pg_offset] = fdb->disk->curr_page;
579 fdb->disk->curr_hdr.seq++;
583 LOG_INFO("writing to buffer for page %d, offset %d, size %d\n", fdb->disk->curr_page, addr_offset, wr_len);
584 if (fdb->disk->bufferWrite(fdb->disk, addr_offset, buf, wr_len) != wr_len)
586 #warning TODO set error?
588 fdb->disk->cache_dirty = true;
591 fd->seek_pos += wr_len;
592 total_write += wr_len;
594 fill_t fill_delta = MAX((int32_t)(addr_offset + wr_len) - fdb->disk->curr_hdr.fill, (int32_t)0);
595 fdb->disk->free_bytes -= fill_delta;
596 fdb->disk->curr_hdr.fill += fill_delta;
597 fd->size += fill_delta;
598 LOG_INFO("free_bytes %ld, seek_pos %ld, size %ld, curr_hdr.fill %ld\n", fdb->disk->free_bytes, fd->seek_pos, fd->size, fdb->disk->curr_hdr.fill);
605 * Read from file \a fd \a size bytes in \a buf.
606 * \return The number of bytes read.
608 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
610 BattFs *fdb = BATTFS_CAST(fd);
611 uint8_t *buf = (uint8_t *)_buf;
613 size_t total_read = 0;
615 pgaddr_t addr_offset;
618 size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
622 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
623 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
624 read_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
627 if (diskRead(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
629 #warning TODO set error?
633 fd->seek_pos += read_len;
634 total_read += read_len;
642 * Search file \a inode in \a disk using a binary search.
643 * \a last is filled with array offset of file start
644 * in disk->page_array if filse is found, otherwise
645 * \a last is filled with the correct insert position
646 * for creating a file with the given \a inode.
647 * \return true if file is found, false otherwisr.
649 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
651 BattFsPageHeader hdr;
652 pgcnt_t first = 0, page;
653 *last = disk->free_page_start;
656 while (first < *last)
658 page = (first + *last) / 2;
660 if (!readHdr(disk, disk->page_array[page], &hdr))
663 fcs = computeFcs(&hdr);
664 if (hdr.fcs == fcs && hdr.inode == inode)
666 *last = page - hdr.pgoff;
669 else if (hdr.fcs == fcs && hdr.inode < inode)
679 * \return true if file \a inode exists on \a disk, false otherwise.
681 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
684 return findFile(disk, inode, &dummy);
688 * Count size of file \a inode on \a disk, starting at pointer \a start
689 * in disk->page_array. Size is written in \a size.
690 * \return true if all s ok, false on disk read errors.
692 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
694 file_size_t size = 0;
695 BattFsPageHeader hdr;
699 if (!readHdr(disk, *start++, &hdr))
701 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
709 * Open file \a inode from \a disk in \a mode.
710 * File context is stored in \a fd.
711 * \return true if ok, false otherwise.
713 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
717 memset(fd, 0, sizeof(*fd));
719 /* Search file start point in disk page array */
721 if (!findFile(disk, inode, &start_pos))
723 if (!(mode & BATTFS_CREATE))
725 /* Create the file */
726 if (!(getNewPage(disk, start_pos, inode, 0)))
729 fd->start = &disk->page_array[start_pos];
732 if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
734 fd->max_off = fd->fd.size / (disk->page_size - BATTFS_HEADER_LEN);
736 /* Reset seek position */
739 /* Insert file handle in list, ordered by inode, ascending. */
740 FOREACH_NODE(n, &disk->file_opened_list)
742 BattFs *file = containerof(n, BattFs, link);
743 if (file->inode >= inode)
746 INSERT_BEFORE(&fd->link, n);
753 fd->fd.close = battfs_fileclose;
754 fd->fd.flush = battfs_flush;
755 fd->fd.read = battfs_read;
756 fd->fd.reopen = kfile_genericReopen;
757 fd->fd.seek = kfile_genericSeek;
758 fd->fd.write = battfs_write;
760 #warning TODO battfs_error, battfs_clearerr
762 fd->fd.error = battfs_error;
763 fd->fd.clearerr = battfs_clearerr;
766 DB(fd->fd._type = KFT_BATTFS);
774 bool battfs_close(struct BattFsSuper *disk)
779 /* Close all open files */
780 FOREACH_NODE(n, &disk->file_opened_list)
782 BattFs *file = containerof(n, BattFs, link);
783 res += battfs_fileclose(&file->fd);
787 return disk->close(disk) && (res == 0);
791 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
793 BattFsPageHeader hdr;
795 /* Reset page to all 0xff */
796 uint8_t buf[disk->page_size];
797 memset(buf, 0xFF, disk->page_size);
798 disk->bufferWrite(disk, 0, buf, disk->page_size);
804 hdr.fcs = computeFcs(&hdr);
806 if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
808 LOG_ERR("error writing hdr\n");