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 */
48 #include <string.h> /* memset, memmove */
52 * Convert from memory representation to disk structure.
53 * \note filesystem is in little-endian format.
55 INLINE void battfs_to_disk(struct BattFsPageHeader *hdr, uint8_t *buf)
57 STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
61 buf[2] = hdr->fill >> 8;
64 buf[4] = hdr->pgoff >> 8;
67 * Mark is at least 1 bit longer than page address.
68 * Needed to take care of wraparonds.
71 buf[6] = hdr->mark >> 8;
74 * First bit used by mark, last 2 bits used by seq.
75 * Since only 2 pages with the same inode and pgoff
76 * can exist at the same time, 2 bit for seq are enough.
77 * Unused bits are set to 1.
79 buf[7] = ((hdr->mark >> 16) & 0x01) | (hdr->seq << 6) | ~(BV(7) | BV(6) | BV(0));
82 * This field must be the before the last one!
84 buf[8] = hdr->fcs_free;
85 buf[9] = hdr->fcs_free >> 8;
88 * This field must be the last one!
89 * This is needed because if the page is only partially
90 * written, we can use this to detect it.
93 buf[11] = hdr->fcs >> 8;
97 * Convert from disk structure to memory representation.
98 * \note filesystem is in little-endian format.
100 INLINE void disk_to_battfs(uint8_t *buf, struct BattFsPageHeader *hdr)
102 STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
104 hdr->fill = buf[2] << 8 | buf[1];
105 hdr->pgoff = buf[4] << 8 | buf[3];
106 hdr->mark = (mark_t)(buf[7] & 0x01) << 16 | buf[6] << 8 | buf[5];
107 hdr->seq = buf[7] >> 6;
108 hdr->fcs_free = buf[9] << 8 | buf[8];
109 hdr->fcs = buf[11] << 8 | buf[10];
113 * Compute the fcs of the header.
115 static fcs_t computeFcs(struct BattFsPageHeader *hdr)
117 uint8_t buf[BATTFS_HEADER_LEN];
120 battfs_to_disk(hdr, buf);
122 /* fcs is at the end of whole header */
123 rotating_update(buf, BATTFS_HEADER_LEN - sizeof(fcs_t), &cks);
128 * Compute the fcs of the header marked as free.
130 static fcs_t computeFcsFree(struct BattFsPageHeader *hdr)
132 uint8_t buf[BATTFS_HEADER_LEN];
135 battfs_to_disk(hdr, buf);
137 /* fcs_free is just before fcs of whole header */
138 rotating_update(buf, BATTFS_HEADER_LEN - 2 * sizeof(fcs_t), &cks);
144 * Read header of page \a page.
145 * \return true on success, false otherwise.
146 * \note \a hdr is dirtyed even on errors.
148 static bool battfs_readHeader(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
150 uint8_t buf[BATTFS_HEADER_LEN];
152 * Read header from disk.
153 * Header is actually a footer, and so
154 * resides at page end.
156 if (disk->read(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
157 != BATTFS_HEADER_LEN)
159 TRACEMSG("Error: page[%d]\n", page);
164 disk_to_battfs(buf, hdr);
170 * Write header of page \a page.
171 * \return true on success, false otherwise.
172 * \note \a hdr is dirtyed even on errors.
174 static bool battfs_writeHeader(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
176 uint8_t buf[BATTFS_HEADER_LEN];
179 battfs_to_disk(hdr, buf);
182 * write header to disk.
183 * Header is actually a footer, and so
184 * resides at page end.
186 if (disk->write(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
187 != BATTFS_HEADER_LEN)
189 TRACEMSG("Error: page[%d]\n", page);
196 * Count the number of pages from
197 * inode 0 to \a inode in \a filelen_table.
199 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
203 for (inode_t i = 0; i < inode; i++)
204 cnt += filelen_table[i];
210 * Move all pages in page allocation array from \a src to \a src + \a offset.
211 * The number of pages moved is page_count - MAX(dst, src).
213 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
215 pgcnt_t dst = src + offset;
216 memmove(&disk->page_array[dst], &disk->page_array[src], (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
220 /* Fill empty space in array with sentinel */
221 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
222 disk->page_array[page] = PAGE_UNSET_SENTINEL;
227 * Insert \a page into page allocation array of \a disk,
228 * using \a mark to compute position.
230 static void insertFreePage(struct BattFsSuper *disk, mark_t mark, pgcnt_t page)
232 ASSERT(mark - disk->free_start < disk->free_next - disk->free_start);
234 pgcnt_t free_pos = disk->page_count - disk->free_next + mark;
235 ASSERT(free_pos < disk->page_count);
237 TRACEMSG("mark:%u, page:%u, free_start:%u, free_next:%u, free_pos:%u\n",
238 mark, page, disk->free_start, disk->free_next, free_pos);
240 ASSERT(disk->page_array[free_pos] == PAGE_UNSET_SENTINEL);
241 disk->page_array[free_pos] = page;
245 * Mark \a page of \a disk as free.
246 * \note free_next of \a disk is used as \a page free marker
247 * and is increased by 1.
249 static bool battfs_markFree(struct BattFsSuper *disk, struct BattFsPageHeader *hdr, pgcnt_t page)
251 uint8_t buf[BATTFS_HEADER_LEN];
253 hdr->mark = disk->free_next;
254 hdr->fcs_free = computeFcsFree(hdr);
255 battfs_to_disk(hdr, buf);
257 if (!disk->write(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN))
259 TRACEMSG("error marking page [%d]\n", page);
270 * Determine free_start and free_next blocks for \a disk
271 * using \a minl, \a maxl, \a minh, \a maxh.
273 * Mark_t is a type that has at least 1 bit more than
274 * pgaddr_t. So all free blocks can be numbered using
275 * at most half numbers of a mark_t type.
276 * The free blocks algorithm increments by 1 the disk->free_next
277 * every time a page becomes free. So the free block sequence is
278 * guaranteed to be countiguous.
279 * Only wrap arounds may happen, but due to half size sequence limitation,
280 * there are only 4 possible situations:
283 * |------lower half------|-------upper half-------|
285 * 1) |------minl*****maxl---|------------------------|
286 * 2) |------minl********maxl|minh******maxh----------|
287 * 3) |----------------------|----minh*******maxh-----|
288 * 4) |minl******maxl--------|------------minh****maxh|
291 * Situations 1 and 3 are easy to detect, while 2 and 4 require more care.
293 static void findFreeStartNext(struct BattFsSuper *disk, mark_t minl, mark_t maxl, mark_t minh, mark_t maxh)
295 /* Determine free_start & free_next */
298 /* Valid interval found in lower half */
301 /* Valid interval also found in upper half */
302 if (maxl == minh - 1)
304 /* Interval starts in lower half and ends in upper */
305 disk->free_start = minl;
306 disk->free_next = maxh;
310 /* Interval starts in upper half and ends in lower */
312 ASSERT(maxh == (MAX_PAGE_ADDR | MARK_HALF_SIZE));
314 disk->free_start = minh;
315 disk->free_next = maxl;
321 * Upper interval is invalid.
325 disk->free_start = minl;
326 disk->free_next = maxl;
329 else if (maxh >= minh)
332 * Lower interval is invalid.
335 disk->free_start = minh;
336 disk->free_next = maxh;
341 * No valid interval found.
342 * Hopefully the disk is brand new (or full).
344 TRACEMSG("No valid marked free block found, new disk or disk full\n");
345 disk->free_start = 0;
346 disk->free_next = -1; //to be increased later
349 /* free_next should contain the first usable address */
352 TRACEMSG("Free markers:\n minl %u\n maxl %u\n minh %u\n maxh %u\n free_start %u\n free_next %u\n",
353 minl, maxl, minh, maxh, disk->free_start, disk->free_next);
357 * Count number of pages per file on \a disk.
358 * This information is registered in \a filelen_table.
359 * Array index represent file inode, while value contained
360 * is the number of pages used by that file.
362 * \return true if ok, false on disk read errors.
363 * \note The whole disk is scanned once.
365 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
367 BattFsPageHeader hdr;
368 mark_t minl, maxl, minh, maxh;
370 /* Initialize min and max counters to keep trace od free blocks */
371 minl = MAX_PAGE_ADDR;
373 minh = MAX_PAGE_ADDR | MARK_HALF_SIZE;
374 maxh = 0 | MARK_HALF_SIZE;
377 /* Count the number of disk page per file */
378 for (pgcnt_t page = 0; page < disk->page_count; page++)
380 if (!battfs_readHeader(disk, page, &hdr))
383 /* Check header FCS */
384 if (hdr.fcs == computeFcs(&hdr))
386 ASSERT(hdr.mark == MARK_PAGE_VALID);
387 ASSERT(hdr.fcs_free == FCS_FREE_VALID);
388 ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
390 /* Page is valid and is owned by a file */
391 filelen_table[hdr.inode]++;
393 /* Keep trace of free space */
394 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN - hdr.fill;
398 /* Increase free space */
399 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
401 /* Check if page is marked free */
402 if (hdr.fcs_free == computeFcsFree(&hdr))
405 * This page is a valid and marked free page.
406 * Update min and max free page markers.
408 if (hdr.mark < MARK_HALF_SIZE)
410 minl = MIN(minl, hdr.mark);
411 maxl = MAX(maxl, hdr.mark);
415 minh = MIN(minh, hdr.mark);
416 maxh = MAX(maxh, hdr.mark);
420 TRACEMSG("page [%d] invalid, keeping as free\n", page);
423 findFreeStartNext(disk, minl, maxl, minh, maxh);
428 * Fill page allocation array of \a disk
429 * using file lenghts in \a filelen_table.
431 * The page allocation array is an array containings all file infos.
432 * Is ordered by file, and within each file is ordered by page offset
434 * e.g. : at page array[0] you will find page address of the first page
435 * of the first file (if present).
436 * Free blocks are allocated after the last file, starting from invalid ones
437 * and continuing with the marked free ones.
439 * \return true if ok, false on disk read errors.
440 * \note The whole disk is scanned once.
442 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
444 BattFsPageHeader hdr;
445 /* Fill page allocation array */
446 for (pgcnt_t page = 0; page < disk->page_count; page++)
448 if (!battfs_readHeader(disk, page, &hdr))
451 /* Check header FCS */
452 if (hdr.fcs == computeFcs(&hdr))
454 /* Page is valid and is owned by a file */
455 ASSERT(hdr.mark == MARK_PAGE_VALID);
456 ASSERT(hdr.fcs_free == FCS_FREE_VALID);
458 /* Compute array position */
459 pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
460 array_pos += hdr.pgoff;
462 /* Check if position is already used by another page of the same file */
463 if (LIKELY(disk->page_array[array_pos] == PAGE_UNSET_SENTINEL))
464 disk->page_array[array_pos] = page;
467 BattFsPageHeader hdr_old;
469 if (!battfs_readHeader(disk, disk->page_array[array_pos], &hdr_old))
472 /* Check header FCS */
473 ASSERT(hdr_old.fcs == computeFcs(&hdr_old));
475 /* Only the very same page with a different seq number can be here */
476 ASSERT(hdr.inode == hdr_old.inode);
477 ASSERT(hdr.pgoff == hdr_old.pgoff);
478 ASSERT(hdr.mark == hdr_old.mark);
479 ASSERT(hdr.fcs_free == hdr_old.fcs_free);
480 ASSERT(hdr.seq != hdr_old.seq);
482 pgcnt_t new_page, old_page;
485 /* Fancy check to handle seq wraparound (2 bits only) */
486 if (((hdr.seq - hdr_old.seq) & 0x03) < 2)
488 /* Current header is newer than the previuos one */
489 old_page = disk->page_array[array_pos];
491 old_fill = hdr_old.fill;
495 /* Previous header is newer than the current one */
497 new_page = disk->page_array[array_pos];
502 disk->page_array[array_pos] = new_page;
505 disk->free_bytes += old_fill;
507 /* Shift all array one position to the left, overwriting duplicate page */
508 array_pos -= hdr.pgoff;
509 array_pos += filelen_table[hdr.inode];
510 movePages(disk, array_pos, -1);
512 /* Decrease file page count */
513 filelen_table[hdr.inode]--;
515 /* Add old page to free pages pool */
516 if (!battfs_markFree(disk, &hdr, old_page))
519 insertFreePage(disk, hdr.mark, old_page);
524 /* Check if page is free */
525 if (hdr.fcs_free != computeFcsFree(&hdr))
526 /* Page is not a valid marked page, insert at list beginning */
527 hdr.mark = --disk->free_start;
529 insertFreePage(disk, hdr.mark, page);
536 * Initialize and mount disk described by
538 * \return false on errors, true otherwise.
540 bool battfs_init(struct BattFsSuper *disk)
542 pgoff_t filelen_table[BATTFS_MAX_FILES];
547 /* Init disk device */
548 if (!disk->open(disk))
550 TRACEMSG("open error\n");
554 /* Disk open must set all of these */
559 ASSERT(disk->page_size);
560 ASSERT(disk->page_count);
561 ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
562 ASSERT(disk->page_array);
564 memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
566 disk->free_bytes = 0;
567 disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
569 /* Count pages per file */
570 if (!countDiskFilePages(disk, filelen_table))
572 TRACEMSG("error counting file pages\n");
576 /* Once here, we have filelen_table filled with file lengths */
578 /* Fill page array with sentinel */
579 for (pgcnt_t page = 0; page < disk->page_count; page++)
580 disk->page_array[page] = PAGE_UNSET_SENTINEL;
582 /* Fill page allocation array using filelen_table */
583 if (!fillPageArray(disk, filelen_table))
585 TRACEMSG("error filling page array\n");
589 /* Init list for opened files. */
590 LIST_INIT(&disk->file_opened_list);
596 * \return 0 if ok, EOF on errors.
598 static int battfs_flush(struct KFile *fd)
607 * \return 0 if ok, EOF on errors.
609 static int battfs_fileclose(struct KFile *fd)
611 BattFS *fdb = BATTFSKFILE(fd);
619 * Read from file \a fd \a size bytes in \a buf.
620 * \return The number of bytes read.
622 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
624 BattFS *fdb = BATTFSKFILE(fd);
625 uint8_t *buf = (uint8_t *)_buf;
627 size_t total_read = 0;
629 pgaddr_t addr_offset;
632 size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
636 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
637 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
638 read_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
641 if (fdb->disk->read(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
643 #warning TODO set error?
647 fd->seek_pos += read_len;
648 total_read += read_len;
656 * Search file \a inode in \a disk using a binary search.
657 * \return pointer to file start in disk->page_array
658 * if file exists, NULL otherwise.
660 static pgcnt_t *findFile(BattFsSuper *disk, inode_t inode)
662 BattFsPageHeader hdr;
663 pgcnt_t first = 0, page, last = disk->page_count -1;
666 while (first <= last)
668 page = (first + last) / 2;
670 if (!battfs_readHeader(disk, disk->page_array[page], &hdr))
673 fcs = computeFcs(&hdr);
674 if (hdr.fcs == fcs && hdr.inode == inode)
675 return (&disk->page_array[page]) - hdr.pgoff;
676 else if (hdr.fcs == fcs && hdr.inode < inode)
686 * \return true if file \a inode exists on \a disk, false otherwise.
688 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
690 return findFile(disk, inode) != NULL;
694 * Count size of file \a inode on \a disk, starting at pointer \a start
695 * in disk->page_array. Size is written in \a size.
696 * \return true if all s ok, false on disk read errors.
698 static bool countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode, file_size_t *size)
701 BattFsPageHeader hdr;
705 if (!battfs_readHeader(disk, *start++, &hdr))
707 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
715 * Open file \a inode from \a disk in \a mode.
716 * File context is stored in \a fd.
717 * \return true if ok, false otherwise.
719 bool battfs_fileopen(BattFsSuper *disk, BattFS *fd, inode_t inode, filemode_t mode)
723 memset(fd, 0, sizeof(*fd));
725 /* Search file start point in disk page array */
726 fd->start = findFile(disk, inode);
727 if (fd->start == NULL)
729 if (!(mode & BATTFS_CREATE))
732 /* File does not exist, create it */
733 BattFsPageHeader hdr;
738 hdr.mark = MARK_PAGE_VALID;
739 hdr.fcs_free = FCS_FREE_VALID;
740 hdr.fcs = computeFcs(&hdr);
741 #warning TODO: get a free block and write on disk!
745 if (!countFileSize(disk, fd->start, inode, &fd->fd.size))
748 /* Reset seek position */
751 /* Insert file handle in list, ordered by inode, ascending. */
752 FOREACH_NODE(n, &disk->file_opened_list)
754 BattFS *file = containerof(n, BattFS, link);
755 if (file->inode >= inode)
758 INSERT_BEFORE(&fd->link, n);
765 fd->fd.close = battfs_fileclose;
766 fd->fd.flush = battfs_flush;
767 fd->fd.read = battfs_read;
768 fd->fd.reopen = kfile_genericReopen;
769 fd->fd.seek = kfile_genericSeek;
771 #warning TODO battfs_write, battfs_error, battfs_clearerr
773 fd->fd.write = battfs_write;
774 fd->fd.error = battfs_error;
775 fd->fd.clearerr = battfs_clearerr;
778 DB(fd->fd._type = KFT_BATTFS);
786 bool battfs_close(struct BattFsSuper *disk)
791 /* Close all open files */
792 FOREACH_NODE(n, &disk->file_opened_list)
794 BattFS *file = containerof(n, BattFS, link);
795 res += battfs_fileclose(&file->fd);
799 return disk->close(disk) && (res == 0);
803 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff, mark_t mark)
805 BattFsPageHeader hdr;
811 hdr.mark = MARK_PAGE_VALID;
812 hdr.fcs_free = FCS_FREE_VALID;
813 hdr.fcs = computeFcs(&hdr);
814 if (mark != MARK_PAGE_VALID)
817 hdr.fcs_free = computeFcsFree(&hdr);
820 if (!battfs_writeHeader(disk, page, &hdr))
822 TRACEMSG("error writing hdr\n");