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_WARNING
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 * Read header of page \a page.
120 * \return true on success, false otherwise.
122 static bool battfs_readHeader(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
124 uint8_t buf[BATTFS_HEADER_LEN];
126 * Read header from disk.
127 * Header is actually a footer, and so
128 * resides at page end.
130 if (disk->read(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
131 != BATTFS_HEADER_LEN)
133 LOG_ERR("Error: page[%d]\n", page);
138 disk_to_battfs(buf, hdr);
144 * Write header of page \a page.
145 * \return true on success, false otherwise.
147 static bool battfs_writeHeader(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
149 uint8_t buf[BATTFS_HEADER_LEN];
152 battfs_to_disk(hdr, buf);
155 * write header to disk.
156 * Header is actually a footer, and so
157 * resides at page end.
159 if (!(disk->bufferWrite(disk, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
160 == BATTFS_HEADER_LEN && disk->save(disk, page)))
162 LOG_ERR("Error: page[%d]\n", page);
169 * Count the number of pages from
170 * inode 0 to \a inode in \a filelen_table.
172 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
176 for (inode_t i = 0; i < inode; i++)
177 cnt += filelen_table[i];
183 * Move all pages in page allocation array from \a src to \a src + \a offset.
184 * The number of pages moved is page_count - MAX(dst, src).
186 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
188 pgcnt_t dst = src + offset;
189 memmove(&disk->page_array[dst], &disk->page_array[src], (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
193 /* Fill empty space in array with sentinel */
194 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
195 disk->page_array[page] = PAGE_UNSET_SENTINEL;
200 * Count number of pages per file on \a disk.
201 * This information is registered in \a filelen_table.
202 * Array index represent file inode, while value contained
203 * is the number of pages used by that file.
205 * \return true if ok, false on disk read errors.
206 * \note The whole disk is scanned once.
208 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
210 BattFsPageHeader hdr;
211 disk->free_page_start = 0;
213 /* Count the number of disk page per file */
214 for (pgcnt_t page = 0; page < disk->page_count; page++)
216 if (!battfs_readHeader(disk, page, &hdr))
219 /* Increase free space */
220 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
222 /* Check header FCS */
223 if (hdr.fcs == computeFcs(&hdr))
225 ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
227 /* Page is valid and is owned by a file */
228 filelen_table[hdr.inode]++;
230 /* Keep trace of free space */
231 disk->free_bytes -= hdr.fill;
232 disk->free_page_start++;
235 LOG_INFO("free_bytes:%d, free_page_start:%d\n", disk->free_bytes, disk->free_page_start);
241 * Fill page allocation array of \a disk
242 * using file lenghts in \a filelen_table.
244 * The page allocation array is an array containings all file infos.
245 * Is ordered by file, and within each file is ordered by page offset
247 * e.g. : at page array[0] you will find page address of the first page
248 * of the first file (if present).
249 * Free blocks are allocated after the last file.
251 * \return true if ok, false on disk read errors.
252 * \note The whole disk is scanned at max twice.
254 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
256 BattFsPageHeader hdr;
257 pgcnt_t curr_free_page = disk->free_page_start;
258 /* Fill page allocation array */
259 for (pgcnt_t page = 0; page < disk->page_count; page++)
261 if (!battfs_readHeader(disk, page, &hdr))
264 /* Check header FCS */
265 if (hdr.fcs == computeFcs(&hdr))
267 /* Compute array position */
268 pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
269 array_pos += hdr.pgoff;
272 /* Check if position is already used by another page of the same file */
273 if (disk->page_array[array_pos] == PAGE_UNSET_SENTINEL)
274 disk->page_array[array_pos] = page;
277 BattFsPageHeader hdr_prv;
279 if (!battfs_readHeader(disk, disk->page_array[array_pos], &hdr_prv))
282 /* Check header FCS */
283 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
285 /* Only the very same page with a different seq number can be here */
286 ASSERT(hdr.inode == hdr_prv.inode);
287 ASSERT(hdr.pgoff == hdr_prv.pgoff);
288 ASSERT(hdr.seq != hdr_prv.seq);
290 pgcnt_t new_page, old_page;
294 * Sequence number comparison: since
295 * seq is 40 bits wide, it wraps once
296 * every 1.1E12 times.
297 * The memory will not live enough to
298 * see a wraparound, so we can use a simple
301 if (hdr.seq > hdr_prv.seq)
303 /* Current header is newer than the previuos one */
304 old_page = disk->page_array[array_pos];
306 old_fill = hdr_prv.fill;
310 /* Previous header is newer than the current one */
312 new_page = disk->page_array[array_pos];
317 disk->page_array[array_pos] = new_page;
319 disk->free_bytes += old_fill;
320 /* Shift all array one position to the left, overwriting duplicate page */
321 array_pos -= hdr.pgoff;
322 array_pos += filelen_table[hdr.inode];
323 movePages(disk, array_pos, -1);
324 /* Move back all indexes */
325 filelen_table[hdr.inode]--;
326 disk->free_page_start--;
328 /* Set old page as free */
329 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
330 disk->page_array[curr_free_page++] = old_page;
336 /* Invalid page, keep as free */
337 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
338 LOG_INFO("Page %d invalid, keeping as free\n", page);
339 disk->page_array[curr_free_page++] = page;
347 * Flush the current \a disk buffer.
348 * \return true if ok, false on errors.
350 static bool battfs_flushBuffer(struct BattFsSuper *disk)
352 if (disk->cache_dirty)
355 if (!disk->save(disk, disk->curr_page))
357 disk->cache_dirty = false;
363 * Load \a new_page from \a disk in disk page buffer.
364 * If a previuos page is still dirty in the buffer, will be
366 * \return true if ok, false on errors.
368 static bool battfs_loadPage(struct BattFsSuper *disk, pgcnt_t new_page)
370 if (disk->curr_page == new_page)
373 if (battfs_flushBuffer(disk))
376 if (!disk->load(disk, new_page))
378 disk->curr_page = new_page;
384 * Initialize and mount disk described by
386 * \return false on errors, true otherwise.
388 bool battfs_init(struct BattFsSuper *disk)
390 pgoff_t filelen_table[BATTFS_MAX_FILES];
395 /* Init disk device */
396 if (!disk->open(disk))
398 LOG_ERR("open error\n");
402 /* Disk open must set all of these */
405 ASSERT(disk->bufferWrite);
409 ASSERT(disk->page_size);
410 ASSERT(disk->page_count);
411 ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
412 ASSERT(disk->page_array);
414 memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
416 disk->free_bytes = 0;
417 disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
419 /* Count pages per file */
420 if (!countDiskFilePages(disk, filelen_table))
422 LOG_ERR("error counting file pages\n");
426 /* Once here, we have filelen_table filled with file lengths */
428 /* Fill page array with sentinel */
429 for (pgcnt_t page = 0; page < disk->page_count; page++)
430 disk->page_array[page] = PAGE_UNSET_SENTINEL;
432 /* Fill page allocation array using filelen_table */
433 if (!fillPageArray(disk, filelen_table))
435 LOG_ERR("error filling page array\n");
438 #warning TODO: shuffle free blocks
440 /* Initialize page buffer cache */
441 disk->cache_dirty = false;
443 disk->load(disk, disk->curr_page);
445 /* Init list for opened files. */
446 LIST_INIT(&disk->file_opened_list);
452 * \return 0 if ok, EOF on errors.
454 static int battfs_flush(struct KFile *fd)
456 BattFs *fdb = BATTFS_CAST(fd);
458 if (battfs_flushBuffer(fdb->disk))
466 * \return 0 if ok, EOF on errors.
468 static int battfs_fileclose(struct KFile *fd)
470 BattFs *fdb = BATTFS_CAST(fd);
479 * Write to file \a fd \a size bytes from \a buf.
480 * \return The number of bytes written.
482 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
484 BattFs *fdb = BATTFS_CAST(fd);
485 const uint8_t *buf = (const uint8_t *)_buf;
487 size_t total_write = 0;
489 pgaddr_t addr_offset;
492 size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
496 #warning TODO: outside EOF?
498 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
499 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
500 wr_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
503 if (fdb->start[pg_offset] != fdb->disk->curr_page)
505 if (!battfs_loadPage(fdb->disk, fdb->start[pg_offset]))
507 #warning TODO set error?
511 /* Get a free page */
512 fdb->disk->curr_page = fdb->disk->page_array[fdb->disk->free_page_start];
513 movePages(fdb->disk, fdb->disk->free_page_start + 1, -1);
515 /* Insert previous page in free blocks list */
516 fdb->disk->page_array[fdb->disk->page_count - 1] = fdb->start[pg_offset];
517 /* Assign new page */
518 fdb->start[pg_offset] = fdb->disk->curr_page;
519 #warning TODO: hdr have to be updated!
523 if (fdb->disk->bufferWrite(fdb->disk, addr_offset, buf, wr_len) != wr_len)
525 #warning TODO set error?
527 fdb->disk->cache_dirty = true;
530 fd->seek_pos += wr_len;
531 total_write += wr_len;
533 #warning TODO: hdr have to be updated!
541 * Read from file \a fd \a size bytes in \a buf.
542 * \return The number of bytes read.
544 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
546 BattFs *fdb = BATTFS_CAST(fd);
547 uint8_t *buf = (uint8_t *)_buf;
549 size_t total_read = 0;
551 pgaddr_t addr_offset;
554 size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
558 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
559 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
560 read_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
562 /* Flush current page if needed */
563 if (fdb->start[pg_offset] == fdb->disk->curr_page)
564 battfs_flushBuffer(fdb->disk);
567 if (fdb->disk->read(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
569 #warning TODO set error?
573 fd->seek_pos += read_len;
574 total_read += read_len;
582 * Search file \a inode in \a disk using a binary search.
583 * \return pointer to file start in disk->page_array
584 * if file exists, NULL otherwise.
586 static pgcnt_t *findFile(BattFsSuper *disk, inode_t inode)
588 BattFsPageHeader hdr;
589 pgcnt_t first = 0, page, last = disk->free_page_start;
594 page = (first + last) / 2;
596 if (!battfs_readHeader(disk, disk->page_array[page], &hdr))
599 fcs = computeFcs(&hdr);
600 if (hdr.fcs == fcs && hdr.inode == inode)
601 return (&disk->page_array[page]) - hdr.pgoff;
602 else if (hdr.fcs == fcs && hdr.inode < inode)
612 * \return true if file \a inode exists on \a disk, false otherwise.
614 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
616 return findFile(disk, inode) != NULL;
620 * Count size of file \a inode on \a disk, starting at pointer \a start
621 * in disk->page_array. Size is written in \a size.
622 * \return true if all s ok, false on disk read errors.
624 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
626 file_size_t size = 0;
627 BattFsPageHeader hdr;
631 if (!battfs_readHeader(disk, *start++, &hdr))
633 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
641 * Open file \a inode from \a disk in \a mode.
642 * File context is stored in \a fd.
643 * \return true if ok, false otherwise.
645 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
649 memset(fd, 0, sizeof(*fd));
651 /* Search file start point in disk page array */
652 fd->start = findFile(disk, inode);
653 if (fd->start == NULL)
655 if (!(mode & BATTFS_CREATE))
658 /* File does not exist, create it */
659 BattFsPageHeader hdr;
664 hdr.fcs = computeFcs(&hdr);
665 #warning TODO: get a free block and write on disk!
669 if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
672 /* Reset seek position */
675 /* Insert file handle in list, ordered by inode, ascending. */
676 FOREACH_NODE(n, &disk->file_opened_list)
678 BattFs *file = containerof(n, BattFs, link);
679 if (file->inode >= inode)
682 INSERT_BEFORE(&fd->link, n);
689 fd->fd.close = battfs_fileclose;
690 fd->fd.flush = battfs_flush;
691 fd->fd.read = battfs_read;
692 fd->fd.reopen = kfile_genericReopen;
693 fd->fd.seek = kfile_genericSeek;
694 fd->fd.write = battfs_write;
696 #warning TODO battfs_error, battfs_clearerr
698 fd->fd.error = battfs_error;
699 fd->fd.clearerr = battfs_clearerr;
702 DB(fd->fd._type = KFT_BATTFS);
710 bool battfs_close(struct BattFsSuper *disk)
715 /* Close all open files */
716 FOREACH_NODE(n, &disk->file_opened_list)
718 BattFs *file = containerof(n, BattFs, link);
719 res += battfs_fileclose(&file->fd);
723 return disk->close(disk) && (res == 0);
727 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
729 BattFsPageHeader hdr;
731 /* Reset page to all 0xff */
732 uint8_t buf[disk->page_size];
733 memset(buf, 0xFF, disk->page_size);
734 disk->bufferWrite(disk, 0, buf, disk->page_size);
740 hdr.fcs = computeFcs(&hdr);
742 if (!battfs_writeHeader(disk, page, &hdr))
744 LOG_ERR("error writing hdr\n");