Add doc.
[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("Error: 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         /* Fill buffer */
167         battfs_to_disk(hdr, buf);
168
169         /*
170          * write header to buffer.
171          * Header is actually a footer, and so
172          * resides at page end.
173          */
174         if (disk->bufferWrite(disk, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
175             != BATTFS_HEADER_LEN)
176         {
177                 LOG_ERR("Error writing to buffer\n");
178                 return false;
179         }
180         return true;
181 }
182
183 /**
184  * Count the number of pages from
185  * inode 0 to \a inode in \a filelen_table.
186  */
187 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
188 {
189         pgcnt_t cnt = 0;
190
191         for (inode_t i = 0; i < inode; i++)
192                 cnt += filelen_table[i];
193
194         return cnt;
195 }
196
197 /**
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).
200  */
201 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
202 {
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));
205
206         if (offset < 0)
207         {
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;
211         }
212 }
213
214 /**
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.
219  *
220  * \return true if ok, false on disk read errors.
221  * \note The whole disk is scanned once.
222  */
223 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
224 {
225         BattFsPageHeader hdr;
226         disk->free_page_start = 0;
227
228         /* Count the number of disk page per file */
229         for (pgcnt_t page = 0; page < disk->page_count; page++)
230         {
231                 if (!readHdr(disk, page, &hdr))
232                         return false;
233
234                 /* Increase free space */
235                 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
236
237                 /* Check header FCS */
238                 if (hdr.fcs == computeFcs(&hdr))
239                 {
240                         ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
241
242                         /* Page is valid and is owned by a file */
243                         filelen_table[hdr.inode]++;
244
245                         /* Keep trace of free space */
246                         disk->free_bytes -= hdr.fill;
247                         disk->free_page_start++;
248                 }
249         }
250         LOG_INFO("free_bytes:%d, free_page_start:%d\n", disk->free_bytes, disk->free_page_start);
251
252         return true;
253 }
254
255 /**
256  * Fill page allocation array of \a disk
257  * using file lenghts in \a filelen_table.
258  *
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
261  * inside file.
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.
265  *
266  * \return true if ok, false on disk read errors.
267  * \note The whole disk is scanned at max twice.
268  */
269 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
270 {
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++)
275         {
276                 if (!readHdr(disk, page, &hdr))
277                         return false;
278
279                 /* Check header FCS */
280                 if (hdr.fcs == computeFcs(&hdr))
281                 {
282                         /* Compute array position */
283                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
284                         array_pos += hdr.pgoff;
285
286
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;
290                         else
291                         {
292                                 BattFsPageHeader hdr_prv;
293
294                                 if (!readHdr(disk, disk->page_array[array_pos], &hdr_prv))
295                                         return false;
296
297                                 /* Check header FCS */
298                                 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
299
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);
304
305                                 pgcnt_t new_page, old_page;
306                                 fill_t old_fill;
307
308                                 /*
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
314                                  * compare here.
315                                  */
316                                 if (hdr.seq > hdr_prv.seq)
317                                 {
318                                         /* Current header is newer than the previuos one */
319                                         old_page = disk->page_array[array_pos];
320                                         new_page = page;
321                                         old_fill = hdr_prv.fill;
322                                 }
323                                 else
324                                 {
325                                         /* Previous header is newer than the current one */
326                                         old_page = page;
327                                         new_page = disk->page_array[array_pos];
328                                         old_fill = hdr.fill;
329                                 }
330
331                                 /* Set new page */
332                                 disk->page_array[array_pos] = new_page;
333                                 /* Add free space */
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--;
342                                 curr_free_page--;
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;
346
347                         }
348                 }
349                 else
350                 {
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;
355                 }
356         }
357         return true;
358 }
359
360
361 /**
362  * Flush the current \a disk buffer.
363  * \return true if ok, false on errors.
364  */
365 static bool flushBuffer(struct BattFsSuper *disk)
366 {
367         if (disk->cache_dirty)
368         {
369                 LOG_INFO("Flushing to disk page %d\n", disk->curr_page);
370
371                 if (!(setBufferHdr(disk, &disk->curr_hdr)
372                         && disk->erase(disk, disk->curr_page)
373                         && disk->save(disk, disk->curr_page)))
374                         return false;
375
376                 disk->cache_dirty = false;
377         }
378         return true;
379 }
380
381 /**
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
384  * flushed first.
385  * \return true if ok, false on errors.
386  */
387 static bool loadPage(struct BattFsSuper *disk, pgcnt_t new_page)
388 {
389         if (disk->curr_page == new_page)
390                 return true;
391
392         LOG_INFO("Loading page %d\n", new_page);
393
394         if (!(flushBuffer(disk)
395                 && disk->load(disk, new_page)))
396                 return false;
397
398         disk->curr_page = new_page;
399
400         /* Load current header */
401         if (!readHdr(disk, disk->curr_page, &disk->curr_hdr))
402                 return false;
403
404         return true;
405 }
406
407
408 /**
409  * Initialize and mount disk described by
410  * \a disk.
411  * \return false on errors, true otherwise.
412  */
413 bool battfs_init(struct BattFsSuper *disk)
414 {
415         pgoff_t filelen_table[BATTFS_MAX_FILES];
416
417         /* Sanity check */
418         ASSERT(disk->open);
419
420         /* Init disk device */
421         if (!disk->open(disk))
422         {
423                 LOG_ERR("open error\n");
424                 return false;
425         }
426
427         /* Disk open must set all of these */
428         ASSERT(disk->read);
429         ASSERT(disk->load);
430         ASSERT(disk->bufferWrite);
431         ASSERT(disk->bufferRead);
432         ASSERT(disk->save);
433         ASSERT(disk->erase);
434         ASSERT(disk->close);
435         ASSERT(disk->page_size);
436         ASSERT(disk->page_count);
437         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
438         ASSERT(disk->page_array);
439
440         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
441
442         disk->free_bytes = 0;
443         disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
444
445         /* Initialize page buffer cache */
446         disk->cache_dirty = false;
447         disk->curr_page = 0;
448         disk->load(disk, disk->curr_page);
449         readHdr(disk, disk->curr_page, &disk->curr_hdr);
450
451         /* Count pages per file */
452         if (!countDiskFilePages(disk, filelen_table))
453         {
454                 LOG_ERR("error counting file pages\n");
455                 return false;
456         }
457
458         /* Once here, we have filelen_table filled with file lengths */
459
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;
463
464         /* Fill page allocation array using filelen_table */
465         if (!fillPageArray(disk, filelen_table))
466         {
467                 LOG_ERR("error filling page array\n");
468                 return false;
469         }
470         #warning TODO: shuffle free blocks
471
472         /* Init list for opened files. */
473         LIST_INIT(&disk->file_opened_list);
474         return true;
475 }
476
477 /**
478  * Flush file \a fd.
479  * \return 0 if ok, EOF on errors.
480  */
481 static int battfs_flush(struct KFile *fd)
482 {
483         BattFs *fdb = BATTFS_CAST(fd);
484
485         if (flushBuffer(fdb->disk))
486                 return 0;
487         else
488                 return EOF;
489 }
490
491 /**
492  * Close file \a fd.
493  * \return 0 if ok, EOF on errors.
494  */
495 static int battfs_fileclose(struct KFile *fd)
496 {
497         BattFs *fdb = BATTFS_CAST(fd);
498
499         battfs_flush(fd);
500         REMOVE(&fdb->link);
501         return 0;
502 }
503
504
505 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff)
506 {
507         if (disk->free_page_start >= disk->page_count)
508         {
509                 #warning TODO space over!
510                 LOG_INFO("No disk space available\n");
511                 return false;
512         }
513         flushBuffer(disk);
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;
519
520         disk->curr_hdr.inode = inode;
521         disk->curr_hdr.pgoff =  pgoff;
522         disk->curr_hdr.fill = 0;
523         disk->curr_hdr.seq = 0;
524         return true;
525 }
526
527 /**
528  * Write to file \a fd \a size bytes from \a buf.
529  * \return The number of bytes written.
530  */
531 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
532 {
533         BattFs *fdb = BATTFS_CAST(fd);
534         const uint8_t *buf = (const uint8_t *)_buf;
535
536         size_t total_write = 0;
537         pgoff_t pg_offset;
538         pgaddr_t addr_offset;
539         pgaddr_t wr_len;
540         pgoff_t max_off = fd->size / (fdb->disk->page_size - BATTFS_HEADER_LEN);
541
542         #warning TODO seek_pos > size?
543         size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
544
545         while (size)
546         {
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));
550
551                 /* Handle write outside EOF */
552                 if (pg_offset > max_off)
553                 {
554                         if (!getNewPage(fdb->disk, (fdb->disk->page_array - fdb->start) + max_off, fdb->inode, pg_offset))
555                                 return total_write;
556                         max_off = pg_offset;
557                 }
558
559                 /* Handle cache load of a new page*/
560                 if (fdb->start[pg_offset] != fdb->disk->curr_page)
561                 {
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]))
564                         {
565                                 #warning TODO set error?
566                                 return total_write;
567                         }
568
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);
572
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++;
579                 }
580
581
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)
584                 {
585                         #warning TODO set error?
586                 }
587                 fdb->disk->cache_dirty = true;
588
589                 size -= wr_len;
590                 fd->seek_pos += wr_len;
591                 total_write += wr_len;
592                 buf += 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;
597         }
598         return total_write;
599 }
600
601
602 /**
603  * Read from file \a fd \a size bytes in \a buf.
604  * \return The number of bytes read.
605  */
606 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
607 {
608         BattFs *fdb = BATTFS_CAST(fd);
609         uint8_t *buf = (uint8_t *)_buf;
610
611         size_t total_read = 0;
612         pgoff_t pg_offset;
613         pgaddr_t addr_offset;
614         pgaddr_t read_len;
615
616         size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
617
618         while (size)
619         {
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));
623
624                 /* Read from disk */
625                 if (diskRead(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
626                 {
627                         #warning TODO set error?
628                 }
629
630                 size -= read_len;
631                 fd->seek_pos += read_len;
632                 total_read += read_len;
633                 buf += read_len;
634         }
635         return total_read;
636 }
637
638
639 /**
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.
646  */
647 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
648 {
649         BattFsPageHeader hdr;
650         pgcnt_t first = 0, page;
651         *last = disk->free_page_start;
652         fcs_t fcs;
653
654         while (first < *last)
655         {
656                 page = (first + *last) / 2;
657
658                 if (!readHdr(disk, disk->page_array[page], &hdr))
659                         return false;
660
661                 fcs = computeFcs(&hdr);
662                 if (hdr.fcs == fcs && hdr.inode == inode)
663                 {
664                         *last = page - hdr.pgoff;
665                         return true;
666                 }
667                 else if (hdr.fcs == fcs && hdr.inode < inode)
668                         first = page + 1;
669                 else
670                         *last = page - 1;
671         }
672
673         return false;
674 }
675
676 /**
677  * \return true if file \a inode exists on \a disk, false otherwise.
678  */
679 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
680 {
681         pgcnt_t dummy;
682         return findFile(disk, inode, &dummy);
683 }
684
685 /**
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.
689  */
690 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
691 {
692         file_size_t size = 0;
693         BattFsPageHeader hdr;
694
695         for (;;)
696         {
697                 if (!readHdr(disk, *start++, &hdr))
698                         return EOF;
699                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
700                         size += hdr.fill;
701                 else
702                         return size;
703         }
704 }
705
706 /**
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.
710  */
711 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
712 {
713         Node *n;
714
715         memset(fd, 0, sizeof(*fd));
716
717         /* Search file start point in disk page array */
718         pgcnt_t start_pos;
719         if (!findFile(disk, inode, &start_pos))
720         {
721                 if (!(mode & BATTFS_CREATE))
722                         return false;
723                 /* Create the file */
724                 if (!(getNewPage(disk, start_pos, inode, 0)))
725                         return false;
726         }
727         fd->start = &disk->page_array[start_pos];
728
729         /* Fill file size */
730         if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
731                 return false;
732
733         /* Reset seek position */
734         fd->fd.seek_pos = 0;
735
736         /* Insert file handle in list, ordered by inode, ascending. */
737         FOREACH_NODE(n, &disk->file_opened_list)
738         {
739                 BattFs *file = containerof(n, BattFs, link);
740                 if (file->inode >= inode)
741                         break;
742         }
743         INSERT_BEFORE(&fd->link, n);
744
745         /* Fill in data */
746         fd->inode = inode;
747         fd->mode = mode;
748         fd->disk = disk;
749
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;
756
757 #warning TODO battfs_error, battfs_clearerr
758 #if 0
759         fd->fd.error = battfs_error;
760         fd->fd.clearerr = battfs_clearerr;
761 #endif
762
763         DB(fd->fd._type = KFT_BATTFS);
764
765         return true;
766 }
767
768 /**
769  * Close \a disk.
770  */
771 bool battfs_close(struct BattFsSuper *disk)
772 {
773         Node *n;
774         int res = 0;
775
776         /* Close all open files */
777         FOREACH_NODE(n, &disk->file_opened_list)
778         {
779                 BattFs *file = containerof(n, BattFs, link);
780                 res += battfs_fileclose(&file->fd);
781         }
782
783         /* Close disk */
784         return disk->close(disk) && (res == 0);
785 }
786
787 #if UNIT_TEST
788 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
789 {
790         BattFsPageHeader hdr;
791
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);
796
797         hdr.inode = inode;
798         hdr.fill = fill;
799         hdr.pgoff = pgoff;
800         hdr.seq = seq;
801         hdr.fcs = computeFcs(&hdr);
802
803         if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
804         {
805                 LOG_ERR("error writing hdr\n");
806                 return false;
807         }
808
809         return true;
810 }
811 #endif