92416079d8f4776c1b039dde23f10d9f4c19e856
[bertos.git] / bertos / fs / battfs.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
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.
10  *
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.
15  *
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
19  *
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.
28  *
29  * Copyright 2007 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief BattFS: a filesystem for embedded platforms (implementation).
34  *
35  * \version $Id:$
36  *
37  * \author Francesco Sacchi <batt@develer.com>
38  *
39  */
40
41 #include "battfs.h"
42
43 #include <cfg/debug.h>
44 #include <cfg/macros.h> /* MIN, MAX */
45 #include <cpu/byteorder.h> /* cpu_to_xx */
46
47 #define LOG_LEVEL       LOG_LVL_INFO
48 #define LOG_FORMAT      LOG_FMT_VERBOSE
49 #include <cfg/log.h>
50
51 #include <string.h> /* memset, memmove */
52
53
54 /**
55  * Convert from memory representation to disk structure.
56  * \note filesystem is in little-endian format.
57  */
58 INLINE void battfs_to_disk(struct BattFsPageHeader *hdr, uint8_t *buf)
59 {
60         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
61         buf[0] = hdr->inode;
62
63         buf[1] = hdr->fill;
64         buf[2] = hdr->fill >> 8;
65
66         buf[3] = hdr->pgoff;
67         buf[4] = hdr->pgoff >> 8;
68
69         /*
70          * Sequence number is 40 bits long.
71          * No need to take care of wraparonds: the memory will die first!
72          */
73         buf[5] = hdr->seq;
74         buf[6] = hdr->seq >> 8;
75         buf[7] = hdr->seq >> 16;
76         buf[8] = hdr->seq >> 24;
77         buf[9] = hdr->seq >> 32;
78
79         /*
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.
83          */
84         buf[10] = hdr->fcs;
85         buf[11] = hdr->fcs >> 8;
86 }
87
88 /**
89  * Convert from disk structure to memory representation.
90  * \note filesystem is in little-endian format.
91  */
92 INLINE void disk_to_battfs(uint8_t *buf, struct BattFsPageHeader *hdr)
93 {
94         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
95         hdr->inode = buf[0];
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];
100 }
101
102 /**
103  * Compute the fcs of the header.
104  */
105 static fcs_t computeFcs(struct BattFsPageHeader *hdr)
106 {
107         uint8_t buf[BATTFS_HEADER_LEN];
108         fcs_t cks;
109
110         battfs_to_disk(hdr, buf);
111         rotating_init(&cks);
112         /* fcs is at the end of whole header */
113         rotating_update(buf, BATTFS_HEADER_LEN - sizeof(fcs_t), &cks);
114         return cks;
115 }
116
117 /**
118  * Read from disk.
119  * If available, the cache will be used.
120  * \return the number of bytes read.
121  */
122 static size_t diskRead(struct BattFsSuper *disk, pgcnt_t page, pgaddr_t addr, void *buf, size_t size)
123 {
124         /* Try to read from cache */
125         if (page == disk->curr_page)
126                 return disk->bufferRead(disk, addr, buf, size);
127         /* Read from disk */
128         else
129                 return disk->read(disk, page, addr, buf, size);
130 }
131
132
133 /**
134  * Read header of \a page in \a hdr.
135  * \return true on success, false otherwise.
136  */
137 static bool readHdr(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
138 {
139         uint8_t buf[BATTFS_HEADER_LEN];
140         /*
141          * Read header from disk.
142          * Header is actually a footer, and so
143          * resides at page end.
144          */
145         if (diskRead(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
146             != BATTFS_HEADER_LEN)
147         {
148                 LOG_ERR("page[%d]\n", page);
149                 return false;
150         }
151
152         /* Fill header */
153         disk_to_battfs(buf, hdr);
154
155         return true;
156 }
157
158 /**
159  * Set header on current \a disk page buffer.
160  * \return true on success, false otherwise.
161  */
162 static bool setBufferHdr(struct BattFsSuper *disk, struct BattFsPageHeader *hdr)
163 {
164         uint8_t buf[BATTFS_HEADER_LEN];
165
166         #warning FIXME:refactor computeFcs to save time and stack
167         hdr->fcs = computeFcs(hdr);
168         /* Fill buffer */
169         battfs_to_disk(hdr, buf);
170
171         /*
172          * write header to buffer.
173          * Header is actually a footer, and so
174          * resides at page end.
175          */
176         if (disk->bufferWrite(disk, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
177             != BATTFS_HEADER_LEN)
178         {
179                 LOG_ERR("writing to buffer\n");
180                 return false;
181         }
182         return true;
183 }
184
185 /**
186  * Count the number of pages from
187  * inode 0 to \a inode in \a filelen_table.
188  */
189 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
190 {
191         pgcnt_t cnt = 0;
192
193         for (inode_t i = 0; i < inode; i++)
194                 cnt += filelen_table[i];
195
196         return cnt;
197 }
198
199 /**
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).
202  */
203 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
204 {
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));
208
209         if (offset < 0)
210         {
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;
214         }
215 }
216
217 /**
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.
222  *
223  * \return true if ok, false on disk read errors.
224  * \note The whole disk is scanned once.
225  */
226 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
227 {
228         BattFsPageHeader hdr;
229         disk->free_page_start = 0;
230
231         /* Count the number of disk page per file */
232         for (pgcnt_t page = 0; page < disk->page_count; page++)
233         {
234                 if (!readHdr(disk, page, &hdr))
235                         return false;
236
237                 /* Increase free space */
238                 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
239
240                 /* Check header FCS */
241                 if (hdr.fcs == computeFcs(&hdr))
242                 {
243                         ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
244
245                         /* Page is valid and is owned by a file */
246                         filelen_table[hdr.inode]++;
247
248                         /* Keep trace of free space */
249                         disk->free_bytes -= hdr.fill;
250                         disk->free_page_start++;
251                 }
252         }
253         LOG_INFO("free_bytes:%d, free_page_start:%d\n", disk->free_bytes, disk->free_page_start);
254
255         return true;
256 }
257
258 /**
259  * Fill page allocation array of \a disk
260  * using file lenghts in \a filelen_table.
261  *
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
264  * inside file.
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.
268  *
269  * \return true if ok, false on disk read errors.
270  * \note The whole disk is scanned at max twice.
271  */
272 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
273 {
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++)
278         {
279                 if (!readHdr(disk, page, &hdr))
280                         return false;
281
282                 /* Check header FCS */
283                 if (hdr.fcs == computeFcs(&hdr))
284                 {
285                         /* Compute array position */
286                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
287                         array_pos += hdr.pgoff;
288
289
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;
293                         else
294                         {
295                                 BattFsPageHeader hdr_prv;
296
297                                 if (!readHdr(disk, disk->page_array[array_pos], &hdr_prv))
298                                         return false;
299
300                                 /* Check header FCS */
301                                 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
302
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);
307
308                                 pgcnt_t new_page, old_page;
309                                 fill_t old_fill;
310
311                                 /*
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
317                                  * compare here.
318                                  */
319                                 if (hdr.seq > hdr_prv.seq)
320                                 {
321                                         /* Current header is newer than the previuos one */
322                                         old_page = disk->page_array[array_pos];
323                                         new_page = page;
324                                         old_fill = hdr_prv.fill;
325                                 }
326                                 else
327                                 {
328                                         /* Previous header is newer than the current one */
329                                         old_page = page;
330                                         new_page = disk->page_array[array_pos];
331                                         old_fill = hdr.fill;
332                                 }
333
334                                 /* Set new page */
335                                 disk->page_array[array_pos] = new_page;
336                                 /* Add free space */
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--;
345                                 curr_free_page--;
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;
349
350                         }
351                 }
352                 else
353                 {
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;
358                 }
359         }
360         return true;
361 }
362
363
364 /**
365  * Flush the current \a disk buffer.
366  * \return true if ok, false on errors.
367  */
368 static bool flushBuffer(struct BattFsSuper *disk)
369 {
370         if (disk->cache_dirty)
371         {
372                 LOG_INFO("Flushing to disk page %d\n", disk->curr_page);
373
374                 if (!(setBufferHdr(disk, &disk->curr_hdr)
375                         && disk->erase(disk, disk->curr_page)
376                         && disk->save(disk, disk->curr_page)))
377                         return false;
378
379                 disk->cache_dirty = false;
380         }
381         return true;
382 }
383
384 /**
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
387  * flushed first.
388  * \return true if ok, false on errors.
389  */
390 static bool loadPage(struct BattFsSuper *disk, pgcnt_t new_page)
391 {
392         if (disk->curr_page == new_page)
393                 return true;
394
395         LOG_INFO("Loading page %d\n", new_page);
396
397         if (!(flushBuffer(disk)
398                 && disk->load(disk, new_page)))
399                 return false;
400
401         disk->curr_page = new_page;
402
403         /* Load current header */
404         if (!readHdr(disk, disk->curr_page, &disk->curr_hdr))
405                 return false;
406
407         return true;
408 }
409
410
411 /**
412  * Initialize and mount disk described by
413  * \a disk.
414  * \return false on errors, true otherwise.
415  */
416 bool battfs_init(struct BattFsSuper *disk)
417 {
418         pgoff_t filelen_table[BATTFS_MAX_FILES];
419
420         /* Sanity check */
421         ASSERT(disk->open);
422
423         /* Init disk device */
424         if (!disk->open(disk))
425         {
426                 LOG_ERR("open error\n");
427                 return false;
428         }
429
430         /* Disk open must set all of these */
431         ASSERT(disk->read);
432         ASSERT(disk->load);
433         ASSERT(disk->bufferWrite);
434         ASSERT(disk->bufferRead);
435         ASSERT(disk->save);
436         ASSERT(disk->erase);
437         ASSERT(disk->close);
438         ASSERT(disk->page_size);
439         ASSERT(disk->page_count);
440         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
441         ASSERT(disk->page_array);
442
443         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
444
445         disk->free_bytes = 0;
446         disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
447
448         /* Initialize page buffer cache */
449         disk->cache_dirty = false;
450         disk->curr_page = 0;
451         disk->load(disk, disk->curr_page);
452         readHdr(disk, disk->curr_page, &disk->curr_hdr);
453
454         /* Count pages per file */
455         if (!countDiskFilePages(disk, filelen_table))
456         {
457                 LOG_ERR("counting file pages\n");
458                 return false;
459         }
460
461         /* Once here, we have filelen_table filled with file lengths */
462
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;
466
467         /* Fill page allocation array using filelen_table */
468         if (!fillPageArray(disk, filelen_table))
469         {
470                 LOG_ERR("filling page array\n");
471                 return false;
472         }
473         #warning TODO: shuffle free blocks
474
475         /* Init list for opened files. */
476         LIST_INIT(&disk->file_opened_list);
477         return true;
478 }
479
480 /**
481  * Flush file \a fd.
482  * \return 0 if ok, EOF on errors.
483  */
484 static int battfs_flush(struct KFile *fd)
485 {
486         BattFs *fdb = BATTFS_CAST(fd);
487
488         if (flushBuffer(fdb->disk))
489                 return 0;
490         else
491                 return EOF;
492 }
493
494 /**
495  * Close file \a fd.
496  * \return 0 if ok, EOF on errors.
497  */
498 static int battfs_fileclose(struct KFile *fd)
499 {
500         BattFs *fdb = BATTFS_CAST(fd);
501
502         battfs_flush(fd);
503         REMOVE(&fdb->link);
504         return 0;
505 }
506
507
508 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff)
509 {
510         if (disk->free_page_start >= disk->page_count)
511         {
512                 #warning TODO space over!
513                 LOG_INFO("No disk space available\n");
514                 return false;
515         }
516         flushBuffer(disk);
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;
523
524         disk->curr_hdr.inode = inode;
525         disk->curr_hdr.pgoff =  pgoff;
526         disk->curr_hdr.fill = 0;
527         disk->curr_hdr.seq = 0;
528         return true;
529 }
530
531 /**
532  * Write to file \a fd \a size bytes from \a buf.
533  * \return The number of bytes written.
534  */
535 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
536 {
537         BattFs *fdb = BATTFS_CAST(fd);
538         const uint8_t *buf = (const uint8_t *)_buf;
539
540         size_t total_write = 0;
541         pgoff_t pg_offset;
542         pgaddr_t addr_offset;
543         pgaddr_t wr_len;
544
545         #warning TODO seek_pos > size?
546
547         while (size)
548         {
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));
552
553                 /* Handle write outside EOF */
554                 if (pg_offset > fdb->max_off)
555                 {
556                         if (!getNewPage(fdb->disk, (fdb->disk->page_array - fdb->start) + pg_offset, fdb->inode, pg_offset))
557                                 return total_write;
558                         fdb->max_off = pg_offset;
559                 }
560                 /* Handle cache load of a new page*/
561                 else if (fdb->start[pg_offset] != fdb->disk->curr_page)
562                 {
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]))
565                         {
566                                 #warning TODO set error?
567                                 return total_write;
568                         }
569
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);
573
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++;
580                 }
581
582
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)
585                 {
586                         #warning TODO set error?
587                 }
588                 fdb->disk->cache_dirty = true;
589
590                 size -= wr_len;
591                 fd->seek_pos += wr_len;
592                 total_write += wr_len;
593                 buf += 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);
599         }
600         return total_write;
601 }
602
603
604 /**
605  * Read from file \a fd \a size bytes in \a buf.
606  * \return The number of bytes read.
607  */
608 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
609 {
610         BattFs *fdb = BATTFS_CAST(fd);
611         uint8_t *buf = (uint8_t *)_buf;
612
613         size_t total_read = 0;
614         pgoff_t pg_offset;
615         pgaddr_t addr_offset;
616         pgaddr_t read_len;
617
618         size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
619
620         while (size)
621         {
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));
625
626                 /* Read from disk */
627                 if (diskRead(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
628                 {
629                         #warning TODO set error?
630                 }
631
632                 size -= read_len;
633                 fd->seek_pos += read_len;
634                 total_read += read_len;
635                 buf += read_len;
636         }
637         return total_read;
638 }
639
640
641 /**
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.
648  */
649 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
650 {
651         BattFsPageHeader hdr;
652         pgcnt_t first = 0, page;
653         *last = disk->free_page_start;
654         fcs_t fcs;
655
656         while (first < *last)
657         {
658                 page = (first + *last) / 2;
659
660                 if (!readHdr(disk, disk->page_array[page], &hdr))
661                         return false;
662
663                 fcs = computeFcs(&hdr);
664                 if (hdr.fcs == fcs && hdr.inode == inode)
665                 {
666                         *last = page - hdr.pgoff;
667                         return true;
668                 }
669                 else if (hdr.fcs == fcs && hdr.inode < inode)
670                         first = page + 1;
671                 else
672                         *last = page - 1;
673         }
674
675         return false;
676 }
677
678 /**
679  * \return true if file \a inode exists on \a disk, false otherwise.
680  */
681 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
682 {
683         pgcnt_t dummy;
684         return findFile(disk, inode, &dummy);
685 }
686
687 /**
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.
691  */
692 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
693 {
694         file_size_t size = 0;
695         BattFsPageHeader hdr;
696
697         for (;;)
698         {
699                 if (!readHdr(disk, *start++, &hdr))
700                         return EOF;
701                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
702                         size += hdr.fill;
703                 else
704                         return size;
705         }
706 }
707
708 /**
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.
712  */
713 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
714 {
715         Node *n;
716
717         memset(fd, 0, sizeof(*fd));
718
719         /* Search file start point in disk page array */
720         pgcnt_t start_pos;
721         if (!findFile(disk, inode, &start_pos))
722         {
723                 if (!(mode & BATTFS_CREATE))
724                         return false;
725                 /* Create the file */
726                 if (!(getNewPage(disk, start_pos, inode, 0)))
727                         return false;
728         }
729         fd->start = &disk->page_array[start_pos];
730
731         /* Fill file size */
732         if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
733                 return false;
734         fd->max_off = fd->fd.size / (disk->page_size - BATTFS_HEADER_LEN);
735
736         /* Reset seek position */
737         fd->fd.seek_pos = 0;
738
739         /* Insert file handle in list, ordered by inode, ascending. */
740         FOREACH_NODE(n, &disk->file_opened_list)
741         {
742                 BattFs *file = containerof(n, BattFs, link);
743                 if (file->inode >= inode)
744                         break;
745         }
746         INSERT_BEFORE(&fd->link, n);
747
748         /* Fill in data */
749         fd->inode = inode;
750         fd->mode = mode;
751         fd->disk = disk;
752
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;
759
760 #warning TODO battfs_error, battfs_clearerr
761 #if 0
762         fd->fd.error = battfs_error;
763         fd->fd.clearerr = battfs_clearerr;
764 #endif
765
766         DB(fd->fd._type = KFT_BATTFS);
767
768         return true;
769 }
770
771 /**
772  * Close \a disk.
773  */
774 bool battfs_close(struct BattFsSuper *disk)
775 {
776         Node *n;
777         int res = 0;
778
779         /* Close all open files */
780         FOREACH_NODE(n, &disk->file_opened_list)
781         {
782                 BattFs *file = containerof(n, BattFs, link);
783                 res += battfs_fileclose(&file->fd);
784         }
785
786         /* Close disk */
787         return disk->close(disk) && (res == 0);
788 }
789
790 #if UNIT_TEST
791 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
792 {
793         BattFsPageHeader hdr;
794
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);
799
800         hdr.inode = inode;
801         hdr.fill = fill;
802         hdr.pgoff = pgoff;
803         hdr.seq = seq;
804         hdr.fcs = computeFcs(&hdr);
805
806         if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
807         {
808                 LOG_ERR("error writing hdr\n");
809                 return false;
810         }
811
812         return true;
813 }
814 #endif