Add battfs config file; add shuffle for free blocks.
[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 #include "cfg/cfg_battfs.h"
43 #include <cfg/debug.h>
44 #include <cfg/macros.h> /* MIN, MAX */
45 #include <cfg/test.h>
46 #include <cpu/byteorder.h> /* cpu_to_xx */
47
48 #define LOG_LEVEL       BATTFS_LOG_LEVEL
49 #define LOG_FORMAT      BATTFS_LOG_FORMAT
50 #include <cfg/log.h>
51
52 #include <string.h> /* memset, memmove */
53
54 #if LOG_LEVEL >= LOG_LVL_INFO
55 static void dumpPageArray(struct BattFsSuper *disk)
56 {
57         kprintf("Page array dump, free_page_start %d:", disk->free_page_start);
58         for (pgcnt_t i = 0; i < disk->page_count; i++)
59         {
60                 if (!(i % 16))
61                         kputchar('\n');
62                 kprintf("%04d ", disk->page_array[i]);
63         }
64         kputchar('\n');
65 }
66 #endif
67
68 /**
69  * Convert from memory representation to disk structure.
70  * \note filesystem is in little-endian format.
71  */
72 INLINE void battfs_to_disk(struct BattFsPageHeader *hdr, uint8_t *buf)
73 {
74         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
75         buf[0] = hdr->inode;
76
77         buf[1] = hdr->fill;
78         buf[2] = hdr->fill >> 8;
79
80         buf[3] = hdr->pgoff;
81         buf[4] = hdr->pgoff >> 8;
82
83         /*
84          * Sequence number is 40 bits long.
85          * No need to take care of wraparonds: the memory will die first!
86          */
87         buf[5] = hdr->seq;
88         buf[6] = hdr->seq >> 8;
89         buf[7] = hdr->seq >> 16;
90         buf[8] = hdr->seq >> 24;
91         buf[9] = hdr->seq >> 32;
92
93         /*
94          * This field must be the last one!
95          * This is needed because if the page is only partially
96          * written, we can use this to detect it.
97          */
98         buf[10] = hdr->fcs;
99         buf[11] = hdr->fcs >> 8;
100 }
101
102 /**
103  * Convert from disk structure to memory representation.
104  * \note filesystem is in little-endian format.
105  */
106 INLINE void disk_to_battfs(uint8_t *buf, struct BattFsPageHeader *hdr)
107 {
108         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
109         hdr->inode = buf[0];
110         hdr->fill = buf[2] << 8 | buf[1];
111         hdr->pgoff = buf[4] << 8 | buf[3];
112         hdr->seq = (seq_t)buf[9] << 32 | (seq_t)buf[8] << 24 | (seq_t)buf[7] << 16 | buf[6] << 8 | buf[5];
113         hdr->fcs = buf[11] << 8 | buf[10];
114 }
115
116 /**
117  * Compute the fcs of the header.
118  */
119 static fcs_t computeFcs(struct BattFsPageHeader *hdr)
120 {
121         uint8_t buf[BATTFS_HEADER_LEN];
122         fcs_t cks;
123
124         battfs_to_disk(hdr, buf);
125         rotating_init(&cks);
126         /* fcs is at the end of whole header */
127         rotating_update(buf, BATTFS_HEADER_LEN - sizeof(fcs_t), &cks);
128         return cks;
129 }
130
131 /**
132  * Read from disk.
133  * If available, the cache will be used.
134  * \return the number of bytes read.
135  */
136 static size_t diskRead(struct BattFsSuper *disk, pgcnt_t page, pgaddr_t addr, void *buf, size_t size)
137 {
138         /* Try to read from cache */
139         if (page == disk->curr_page)
140                 return disk->bufferRead(disk, addr, buf, size);
141         /* Read from disk */
142         else
143                 return disk->read(disk, page, addr, buf, size);
144 }
145
146
147 /**
148  * Read header of \a page in \a hdr.
149  * \return true on success, false otherwise.
150  */
151 static bool readHdr(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
152 {
153         uint8_t buf[BATTFS_HEADER_LEN];
154         /*
155          * Read header from disk.
156          * Header is actually a footer, and so
157          * resides at page end.
158          */
159         if (diskRead(disk, page, disk->data_size, buf, BATTFS_HEADER_LEN)
160             != BATTFS_HEADER_LEN)
161         {
162                 LOG_ERR("page[%d]\n", page);
163                 return false;
164         }
165
166         /* Fill header */
167         disk_to_battfs(buf, hdr);
168
169         return true;
170 }
171
172 /**
173  * Set header on current \a disk page buffer.
174  * \return true on success, false otherwise.
175  */
176 static bool setBufferHdr(struct BattFsSuper *disk, struct BattFsPageHeader *hdr)
177 {
178         uint8_t buf[BATTFS_HEADER_LEN];
179
180         #warning FIXME:refactor computeFcs to save time and stack
181         hdr->fcs = computeFcs(hdr);
182         /* Fill buffer */
183         battfs_to_disk(hdr, buf);
184
185         /*
186          * write header to buffer.
187          * Header is actually a footer, and so
188          * resides at page end.
189          */
190         if (disk->bufferWrite(disk, disk->data_size, buf, BATTFS_HEADER_LEN)
191             != BATTFS_HEADER_LEN)
192         {
193                 LOG_ERR("writing to buffer\n");
194                 return false;
195         }
196         return true;
197 }
198
199 static bool getBufferHdr(struct BattFsSuper *disk, struct BattFsPageHeader *hdr)
200 {
201         uint8_t buf[BATTFS_HEADER_LEN];
202
203         if (disk->bufferRead(disk, disk->data_size, buf, BATTFS_HEADER_LEN)
204             != BATTFS_HEADER_LEN)
205         {
206                 LOG_ERR("reading from buffer\n");
207                 return false;
208         }
209
210         disk_to_battfs(buf, hdr);
211
212         return true;
213 }
214
215 /**
216  * Count the number of pages from
217  * inode 0 to \a inode in \a filelen_table.
218  */
219 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
220 {
221         pgcnt_t cnt = 0;
222
223         for (inode_t i = 0; i < inode; i++)
224                 cnt += filelen_table[i];
225
226         return cnt;
227 }
228
229 /**
230  * Move all pages in page allocation array from \a src to \a src + \a offset.
231  * The number of pages moved is page_count - MAX(dst, src).
232  */
233 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
234 {
235         pgcnt_t dst = src + offset;
236         LOG_INFO("src %d, offset %d, size %d\n", src, offset, (unsigned int)((disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t)));
237         memmove(&disk->page_array[dst], &disk->page_array[src], (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
238
239         if (offset < 0)
240         {
241                 /* Fill empty space in array with sentinel */
242                 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
243                         disk->page_array[page] = PAGE_UNSET_SENTINEL;
244         }
245 }
246
247 /**
248  * Count number of pages per file on \a disk.
249  * This information is registered in \a filelen_table.
250  * Array index represent file inode, while value contained
251  * is the number of pages used by that file.
252  *
253  * \return true if ok, false on disk read errors.
254  * \note The whole disk is scanned once.
255  */
256 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
257 {
258         BattFsPageHeader hdr;
259         disk->free_page_start = 0;
260
261         /* Count the number of disk page per file */
262         for (pgcnt_t page = 0; page < disk->page_count; page++)
263         {
264                 if (!readHdr(disk, page, &hdr))
265                         return false;
266
267                 /* Increase free space */
268                 disk->free_bytes += disk->data_size;
269
270                 /* Check header FCS */
271                 if (hdr.fcs == computeFcs(&hdr))
272                 {
273                         ASSERT(hdr.fill <= disk->data_size);
274
275                         /* Page is valid and is owned by a file */
276                         filelen_table[hdr.inode]++;
277
278                         /* Keep trace of free space */
279                         disk->free_bytes -= hdr.fill;
280                         disk->free_page_start++;
281                 }
282         }
283         LOG_INFO("free_bytes:%ld, free_page_start:%d\n", (long)disk->free_bytes, disk->free_page_start);
284
285         return true;
286 }
287
288 /**
289  * Fill page allocation array of \a disk
290  * using file lenghts in \a filelen_table.
291  *
292  * The page allocation array is an array containings all file infos.
293  * Is ordered by file, and within each file is ordered by page offset
294  * inside file.
295  * e.g. : at page array[0] you will find page address of the first page
296  * of the first file (if present).
297  * Free blocks are allocated after the last file.
298  *
299  * \return true if ok, false on disk read errors.
300  * \note The whole disk is scanned at max twice.
301  */
302 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
303 {
304         BattFsPageHeader hdr;
305         pgcnt_t curr_free_page = disk->free_page_start;
306         /* Fill page allocation array */
307         for (pgcnt_t page = 0; page < disk->page_count; page++)
308         {
309                 if (!readHdr(disk, page, &hdr))
310                         return false;
311
312                 /* Check header FCS */
313                 if (hdr.fcs == computeFcs(&hdr))
314                 {
315                         /* Compute array position */
316                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
317                         array_pos += hdr.pgoff;
318
319
320                         /* Check if position is already used by another page of the same file */
321                         if (disk->page_array[array_pos] == PAGE_UNSET_SENTINEL)
322                                 disk->page_array[array_pos] = page;
323                         else
324                         {
325                                 BattFsPageHeader hdr_prv;
326
327                                 if (!readHdr(disk, disk->page_array[array_pos], &hdr_prv))
328                                         return false;
329
330                                 /* Check header FCS */
331                                 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
332
333                                 /* Only the very same page with a different seq number can be here */
334                                 ASSERT(hdr.inode == hdr_prv.inode);
335                                 ASSERT(hdr.pgoff == hdr_prv.pgoff);
336                                 ASSERT(hdr.seq != hdr_prv.seq);
337
338                                 pgcnt_t new_page, old_page;
339                                 fill_t old_fill;
340
341                                 /*
342                                  * Sequence number comparison: since
343                                  * seq is 40 bits wide, it wraps once
344                                  * every 1.1E12 times.
345                                  * The memory will not live enough to
346                                  * see a wraparound, so we can use a simple
347                                  * compare here.
348                                  */
349                                 if (hdr.seq > hdr_prv.seq)
350                                 {
351                                         /* Current header is newer than the previuos one */
352                                         old_page = disk->page_array[array_pos];
353                                         new_page = page;
354                                         old_fill = hdr_prv.fill;
355                                 }
356                                 else
357                                 {
358                                         /* Previous header is newer than the current one */
359                                         old_page = page;
360                                         new_page = disk->page_array[array_pos];
361                                         old_fill = hdr.fill;
362                                 }
363
364                                 /* Set new page */
365                                 disk->page_array[array_pos] = new_page;
366                                 /* Add free space */
367                                 disk->free_bytes += old_fill;
368                                 /* Shift all array one position to the left, overwriting duplicate page */
369                                 array_pos -= hdr.pgoff;
370                                 array_pos += filelen_table[hdr.inode];
371                                 movePages(disk, array_pos, -1);
372                                 /* Move back all indexes */
373                                 filelen_table[hdr.inode]--;
374                                 disk->free_page_start--;
375                                 curr_free_page--;
376                                 /* Set old page as free */
377                                 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
378                                 disk->page_array[curr_free_page++] = old_page;
379
380                         }
381                 }
382                 else
383                 {
384                         /* Invalid page, keep as free */
385                         ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
386                         //LOG_INFO("Page %d invalid, keeping as free\n", page);
387                         disk->page_array[curr_free_page++] = page;
388                 }
389         }
390         return true;
391 }
392
393
394 /**
395  * Flush the current \a disk buffer.
396  * \return true if ok, false on errors.
397  */
398 static bool flushBuffer(struct BattFsSuper *disk)
399 {
400         if (disk->cache_dirty)
401         {
402                 LOG_INFO("Flushing to disk page %d\n", disk->curr_page);
403
404                 if (!(disk->erase(disk, disk->curr_page)
405                         && disk->save(disk, disk->curr_page)))
406                         return false;
407
408                 disk->cache_dirty = false;
409         }
410         return true;
411 }
412
413 /**
414  * Load \a new_page from \a disk in disk page buffer.
415  * If a previuos page is still dirty in the buffer, will be
416  * flushed first. The new page header loaded will be put in \a new_hdr.
417  * \return true if ok, false on errors.
418  */
419 static bool loadPage(struct BattFsSuper *disk, pgcnt_t new_page, BattFsPageHeader *new_hdr)
420 {
421         if (disk->curr_page == new_page)
422                 return getBufferHdr(disk, new_hdr);
423
424         LOG_INFO("Loading page %d\n", new_page);
425
426         if (!(flushBuffer(disk)
427                 && disk->load(disk, new_page)
428                 && getBufferHdr(disk, new_hdr)))
429                 return false;
430
431         disk->curr_page = new_page;
432
433         return true;
434 }
435
436
437 /**
438  * Initialize and mount disk described by
439  * \a disk.
440  * \return false on errors, true otherwise.
441  */
442 bool battfs_mount(struct BattFsSuper *disk)
443 {
444         pgoff_t filelen_table[BATTFS_MAX_FILES];
445
446         /* Disk open must set all of these */
447         ASSERT(disk->read);
448         ASSERT(disk->load);
449         ASSERT(disk->bufferWrite);
450         ASSERT(disk->bufferRead);
451         ASSERT(disk->save);
452         ASSERT(disk->erase);
453         ASSERT(disk->close);
454         ASSERT(disk->page_size > BATTFS_HEADER_LEN);
455         /* Fill page_size with the usable space */
456         disk->data_size = disk->page_size - BATTFS_HEADER_LEN;
457         ASSERT(disk->page_count);
458         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
459         ASSERT(disk->page_array);
460
461         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
462
463         disk->free_bytes = 0;
464         disk->disk_size = (disk_size_t)disk->data_size * disk->page_count;
465
466         /* Initialize page buffer cache */
467         disk->cache_dirty = false;
468         disk->curr_page = 0;
469         disk->load(disk, disk->curr_page);
470
471         /* Count pages per file */
472         if (!countDiskFilePages(disk, filelen_table))
473         {
474                 LOG_ERR("counting file pages\n");
475                 return false;
476         }
477
478         /* Once here, we have filelen_table filled with file lengths */
479
480         /* Fill page array with sentinel */
481         for (pgcnt_t page = 0; page < disk->page_count; page++)
482                 disk->page_array[page] = PAGE_UNSET_SENTINEL;
483
484         /* Fill page allocation array using filelen_table */
485         if (!fillPageArray(disk, filelen_table))
486         {
487                 LOG_ERR("filling page array\n");
488                 return false;
489         }
490         #if LOG_LEVEL >= LOG_LVL_INFO
491                 dumpPageArray(disk);
492         #endif
493         #if CONFIG_BATTFS_SHUFFLE_FREE_PAGES
494                 SHUFFLE(&disk->page_array[disk->free_page_start], disk->page_count - disk->free_page_start);
495
496                 LOG_INFO("Page array after shuffle:\n");
497                 #if LOG_LEVEL >= LOG_LVL_INFO
498                         dumpPageArray(disk);
499                 #endif
500         #endif
501         /* Init list for opened files. */
502         LIST_INIT(&disk->file_opened_list);
503         return true;
504 }
505
506 /**
507  * Check the filesystem.
508  * \return true if ok, false on errors.
509  */
510 bool battfs_fsck(struct BattFsSuper *disk)
511 {
512         #define FSCHECK(cond) do { if(!(cond)) { LOG_ERR("\"" #cond "\"\n"); return false; } } while (0)
513
514         FSCHECK(disk->free_page_start <= disk->page_count);
515         FSCHECK(disk->data_size < disk->page_size);
516         FSCHECK(disk->free_bytes <= disk->disk_size);
517
518         disk_size_t free_bytes = 0;
519         BattFsPageHeader hdr, prev_hdr;
520         inode_t files = 0;
521         pgcnt_t page_used = 0;
522
523         bool start = true;
524
525         for (pgcnt_t page = 0; page < disk->page_count; page++)
526         {
527                 FSCHECK(readHdr(disk, disk->page_array[page], &hdr));
528                 free_bytes += disk->data_size;
529
530                 if (page < disk->free_page_start)
531                 {
532                         FSCHECK(computeFcs(&hdr) == hdr.fcs);
533                         page_used++;
534                         free_bytes -= hdr.fill;
535                         if (hdr.inode != prev_hdr.inode || start)
536                         {
537                                 if (LIKELY(!start))
538                                         FSCHECK(hdr.inode > prev_hdr.inode);
539                                 else
540                                         start = false;
541
542                                 FSCHECK(hdr.pgoff == 0);
543                                 files++;
544                         }
545                         else
546                         {
547                                 FSCHECK(hdr.fill != 0);
548                                 FSCHECK(prev_hdr.fill == disk->data_size);
549                                 FSCHECK(hdr.pgoff == prev_hdr.pgoff + 1);
550                         }
551                         prev_hdr = hdr;
552                 }
553         }
554
555         FSCHECK(page_used == disk->free_page_start);
556         FSCHECK(free_bytes == disk->free_bytes);
557
558         return true;
559 }
560
561 /**
562  * Flush file \a fd.
563  * \return 0 if ok, EOF on errors.
564  */
565 static int battfs_flush(struct KFile *fd)
566 {
567         BattFs *fdb = BATTFS_CAST(fd);
568
569         if (flushBuffer(fdb->disk))
570                 return 0;
571         else
572         {
573                 fdb->errors |= BATTFS_DISK_FLUSHBUF_ERR;
574                 return EOF;
575         }
576 }
577
578 /**
579  * Close file \a fd.
580  * \return 0 if ok, EOF on errors.
581  */
582 static int battfs_fileclose(struct KFile *fd)
583 {
584         BattFs *fdb = BATTFS_CAST(fd);
585
586         if (battfs_flush(fd) == 0)
587         {
588                 REMOVE(&fdb->link);
589                 return 0;
590         }
591         else
592                 return EOF;
593 }
594
595
596 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff, BattFsPageHeader *new_hdr)
597 {
598         if (SPACE_OVER(disk))
599         {
600                 LOG_ERR("No disk space available!\n");
601                 return false;
602         }
603         flushBuffer(disk);
604         LOG_INFO("Getting new page %d, pos %d\n", disk->page_array[disk->free_page_start], new_pos);
605         disk->curr_page = disk->page_array[disk->free_page_start++];
606         memmove(&disk->page_array[new_pos + 1], &disk->page_array[new_pos], (disk->free_page_start - new_pos - 1) * sizeof(pgcnt_t));
607
608         Node *n;
609         /* Move following file start point one position ahead. */
610         FOREACH_NODE(n, &disk->file_opened_list)
611         {
612                 BattFs *file = containerof(n, BattFs, link);
613                 if (file->inode > inode)
614                 {
615                         LOG_INFO("Move file %d start pos\n", file->inode);
616                         file->start++;
617                 }
618         }
619
620         disk->page_array[new_pos] = disk->curr_page;
621         disk->cache_dirty = true;
622
623         new_hdr->inode = inode;
624         new_hdr->pgoff = pgoff;
625         new_hdr->fill = 0;
626         new_hdr->seq = 0;
627         return setBufferHdr(disk, new_hdr);
628 }
629
630 /**
631  * Write to file \a fd \a size bytes from \a buf.
632  * \return The number of bytes written.
633  */
634 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
635 {
636         BattFs *fdb = BATTFS_CAST(fd);
637         BattFsSuper *disk = fdb->disk;
638         const uint8_t *buf = (const uint8_t *)_buf;
639
640         size_t total_write = 0;
641         pgoff_t pg_offset;
642         pgaddr_t addr_offset;
643         pgaddr_t wr_len;
644         BattFsPageHeader curr_hdr;
645
646         if (fd->seek_pos < 0)
647         {
648                 fdb->errors |= BATTFS_NEGATIVE_SEEK_ERR;
649                 return total_write;
650         }
651
652         if (fd->seek_pos > fd->size)
653         {
654                 /* Handle writing when seek pos if far over EOF */
655                 if (!loadPage(disk, fdb->start[fdb->max_off], &curr_hdr))
656                 {
657                         fdb->errors |= BATTFS_DISK_LOADPAGE_ERR;
658                         return total_write;
659                 }
660
661                 /* Fill unused space of first page with 0s */
662                 uint8_t dummy = 0;
663                 pgaddr_t zero_bytes = MIN(fd->seek_pos - fd->size, (kfile_off_t)(disk->data_size - curr_hdr.fill));
664                 while (zero_bytes--)
665                 {
666                         if (disk->bufferWrite(disk, curr_hdr.fill, &dummy, 1) != 1)
667                         {
668                                 fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
669                                 return total_write;
670                         }
671                         curr_hdr.fill++;
672                         fd->size++;
673                         disk->free_bytes--;
674                         disk->cache_dirty = true;
675                 }
676                 setBufferHdr(disk, &curr_hdr);
677
678                 /* Allocate the missing pages first. */
679                 pgoff_t missing_pages = fd->seek_pos / disk->data_size - fdb->max_off;
680
681                 if (missing_pages)
682                 {
683                         LOG_INFO("missing pages: %d\n", missing_pages);
684                         flushBuffer(disk);
685
686                         /* Fill page buffer with 0 to avoid filling unused pages with garbage */
687                         for (pgaddr_t off = 0; off < disk->data_size; off++)
688                         {
689                                 if (disk->bufferWrite(disk, off, &dummy, 1) != 1)
690                                 {
691                                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
692                                         return total_write;
693                                 }
694                         }
695
696                         while (missing_pages--)
697                         {
698                                 zero_bytes = MIN((kfile_off_t)disk->data_size, fd->seek_pos - fd->size);
699                                 /* Get the new page needed */
700                                 if (!getNewPage(disk, (fdb->start - disk->page_array) + fdb->max_off + 1, fdb->inode, fdb->max_off + 1, &curr_hdr))
701                                 {
702                                         fdb->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
703                                         return total_write;
704                                 }
705
706                                 /* Update size and free space left */
707                                 fd->size += zero_bytes;
708                                 disk->free_bytes -= zero_bytes;
709
710                                 curr_hdr.fill = zero_bytes;
711                                 setBufferHdr(disk, &curr_hdr);
712
713                                 fdb->max_off++;
714                         }
715                 }
716         }
717         else if (!getBufferHdr(disk, &curr_hdr))
718         {
719                 fdb->errors |=  BATTFS_DISK_BUFFERRD_ERR;
720                 return total_write;
721         }
722
723         while (size)
724         {
725                 pg_offset = fd->seek_pos / disk->data_size;
726                 addr_offset = fd->seek_pos % disk->data_size;
727                 wr_len = MIN(size, (size_t)(disk->data_size - addr_offset));
728
729                 /* Handle write outside EOF */
730                 if (pg_offset > fdb->max_off)
731                 {
732                         LOG_INFO("New page needed, pg_offset %d, pos %d\n", pg_offset, (int)((fdb->start - disk->page_array) + pg_offset));
733                         if (!getNewPage(disk, (fdb->start - disk->page_array) + pg_offset, fdb->inode, pg_offset, &curr_hdr))
734                         {
735                                 fdb->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
736                                 return total_write;
737                         }
738
739                         fdb->max_off = pg_offset;
740                 }
741                 /* Handle cache load of a new page*/
742                 else if (fdb->start[pg_offset] != disk->curr_page)
743                 {
744                         if (SPACE_OVER(disk))
745                         {
746                                 LOG_ERR("No disk space available!\n");
747                                 fdb->errors |= BATTFS_DISK_SPACEOVER_ERR;
748                                 return total_write;
749                         }
750                         LOG_INFO("Re-writing page %d to %d\n", fdb->start[pg_offset], disk->page_array[disk->free_page_start]);
751                         if (!loadPage(disk, fdb->start[pg_offset], &curr_hdr))
752                         {
753                                 fdb->errors |= BATTFS_DISK_LOADPAGE_ERR;
754                                 return total_write;
755                         }
756
757                         /* Get a free page */
758                         disk->curr_page = disk->page_array[disk->free_page_start];
759                         movePages(disk, disk->free_page_start + 1, -1);
760
761                         /* Insert previous page in free blocks list */
762                         LOG_INFO("Setting page %d as free\n", fdb->start[pg_offset]);
763                         disk->page_array[disk->page_count - 1] = fdb->start[pg_offset];
764                         /* Assign new page */
765                         fdb->start[pg_offset] = disk->curr_page;
766                         curr_hdr.seq++;
767                 }
768
769                 //LOG_INFO("writing to buffer for page %d, offset %d, size %d\n", disk->curr_page, addr_offset, wr_len);
770                 if (disk->bufferWrite(disk, addr_offset, buf, wr_len) != wr_len)
771                 {
772                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
773                         return total_write;
774                 }
775                 disk->cache_dirty = true;
776
777                 size -= wr_len;
778                 fd->seek_pos += wr_len;
779                 total_write += wr_len;
780                 buf += wr_len;
781                 fill_t fill_delta = MAX((int32_t)(addr_offset + wr_len) - curr_hdr.fill, (int32_t)0);
782                 disk->free_bytes -= fill_delta;
783                 fd->size += fill_delta;
784                 curr_hdr.fill += fill_delta;
785
786                 if (!setBufferHdr(disk, &curr_hdr))
787                 {
788                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
789                         return total_write;
790                 }
791
792                 //LOG_INFO("free_bytes %d, seek_pos %d, size %d, curr_hdr.fill %d\n", disk->free_bytes, fd->seek_pos, fd->size, curr_hdr.fill);
793         }
794         return total_write;
795 }
796
797
798 /**
799  * Read from file \a fd \a size bytes in \a buf.
800  * \return The number of bytes read.
801  */
802 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
803 {
804         BattFs *fdb = BATTFS_CAST(fd);
805         BattFsSuper *disk = fdb->disk;
806         uint8_t *buf = (uint8_t *)_buf;
807
808         size_t total_read = 0;
809         pgoff_t pg_offset;
810         pgaddr_t addr_offset;
811         pgaddr_t read_len;
812
813         if (fd->seek_pos < 0)
814         {
815                 fdb->errors |= BATTFS_NEGATIVE_SEEK_ERR;
816                 return total_read;
817         }
818
819         size = MIN((kfile_off_t)size, MAX(fd->size - fd->seek_pos, (kfile_off_t)0));
820
821         while (size)
822         {
823                 pg_offset = fd->seek_pos / disk->data_size;
824                 addr_offset = fd->seek_pos % disk->data_size;
825                 read_len = MIN(size, (size_t)(disk->data_size - addr_offset));
826
827                 //LOG_INFO("reading from page %d, offset %d, size %d\n", fdb->start[pg_offset], addr_offset, read_len);
828                 /* Read from disk */
829                 if (diskRead(disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
830                 {
831                         fdb->errors |= BATTFS_DISK_READ_ERR;
832                         return total_read;
833                 }
834
835                 #if _DEBUG
836                         BattFsPageHeader hdr;
837                         readHdr(disk, fdb->start[pg_offset], &hdr);
838                         ASSERT(hdr.inode == fdb->inode);
839                 #endif
840
841                 size -= read_len;
842                 fd->seek_pos += read_len;
843                 total_read += read_len;
844                 buf += read_len;
845         }
846         return total_read;
847 }
848
849
850 /**
851  * Search file \a inode in \a disk using a binary search.
852  * \a last is filled with array offset of file start
853  * in disk->page_array if file is found, otherwise
854  * \a last is filled with the correct insert position
855  * for creating a file with the given \a inode.
856  * \return true if file is found, false otherwisr.
857  */
858 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
859 {
860         BattFsPageHeader hdr;
861         pgcnt_t first = 0, page;
862         *last = disk->free_page_start;
863         fcs_t fcs;
864
865         while (first < *last)
866         {
867                 page = (first + *last) / 2;
868                 LOG_INFO("first %d, last %d, page %d\n", first, *last, page);
869                 if (!readHdr(disk, disk->page_array[page], &hdr))
870                         return false;
871                 LOG_INFO("inode read: %d\n", hdr.inode);
872                 fcs = computeFcs(&hdr);
873                 if (hdr.fcs == fcs && hdr.inode == inode)
874                 {
875                         *last = page - hdr.pgoff;
876                         LOG_INFO("Found: %d\n", *last);
877                         return true;
878                 }
879                 else if (hdr.fcs == fcs && hdr.inode < inode)
880                         first = page + 1;
881                 else
882                         *last = page;
883         }
884         LOG_INFO("Not found: last %d\n", *last);
885         return false;
886 }
887
888 /**
889  * \return true if file \a inode exists on \a disk, false otherwise.
890  */
891 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
892 {
893         pgcnt_t dummy;
894         return findFile(disk, inode, &dummy);
895 }
896
897 /**
898  * Count size of file \a inode on \a disk, starting at pointer \a start
899  * in disk->page_array. Size is written in \a size.
900  * \return true if all s ok, false on disk read errors.
901  */
902 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
903 {
904         file_size_t size = 0;
905         BattFsPageHeader hdr;
906
907         while (start < &disk->page_array[disk->free_page_start])
908         {
909                 if (!readHdr(disk, *start++, &hdr))
910                         return EOF;
911                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
912                         size += hdr.fill;
913                 else
914                         break;
915         }
916         return size;
917 }
918
919 static int battfs_error(struct KFile *fd)
920 {
921         BattFs *fdb = BATTFS_CAST(fd);
922         return fdb->errors;
923 }
924
925
926 static void battfs_clearerr(struct KFile *fd)
927 {
928         BattFs *fdb = BATTFS_CAST(fd);
929         fdb->errors = 0;
930 }
931
932 /**
933  * Open file \a inode from \a disk in \a mode.
934  * File context is stored in \a fd.
935  * \return true if ok, false otherwise.
936  */
937 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
938 {
939         Node *n;
940
941         memset(fd, 0, sizeof(*fd));
942
943         /* Search file start point in disk page array */
944         pgcnt_t start_pos;
945         if (!findFile(disk, inode, &start_pos))
946         {
947                 LOG_INFO("file %d not found\n", inode);
948                 if (!(mode & BATTFS_CREATE))
949                 {
950                         fd->errors |= BATTFS_FILE_NOT_FOUND_ERR;
951                         return false;
952                 }
953                 /* Create the file */
954                 BattFsPageHeader hdr;
955                 if (!(getNewPage(disk, start_pos, inode, 0, &hdr)))
956                 {
957                         fd->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
958                         return false;
959                 }
960         }
961         fd->start = &disk->page_array[start_pos];
962         LOG_INFO("Start pos %d\n", start_pos);
963
964         /* Fill file size */
965         if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
966         {
967                 fd->errors |= BATTFS_DISK_READ_ERR;
968                 return false;
969         }
970         fd->max_off = fd->fd.size / disk->data_size;
971
972         /* Reset seek position */
973         fd->fd.seek_pos = 0;
974
975         /* Insert file handle in list, ordered by inode, ascending. */
976         FOREACH_NODE(n, &disk->file_opened_list)
977         {
978                 BattFs *file = containerof(n, BattFs, link);
979                 if (file->inode >= inode)
980                         break;
981         }
982         INSERT_BEFORE(&fd->link, n);
983
984         /* Fill in data */
985         fd->inode = inode;
986         fd->mode = mode;
987         fd->disk = disk;
988
989         fd->fd.close = battfs_fileclose;
990         fd->fd.flush = battfs_flush;
991         fd->fd.read = battfs_read;
992         fd->fd.reopen = kfile_genericReopen;
993         fd->fd.seek = kfile_genericSeek;
994         fd->fd.write = battfs_write;
995
996         fd->fd.error = battfs_error;
997         fd->fd.clearerr = battfs_clearerr;
998
999         DB(fd->fd._type = KFT_BATTFS);
1000
1001         return true;
1002 }
1003
1004
1005 /**
1006  * Umount \a disk.
1007  */
1008 bool battfs_umount(struct BattFsSuper *disk)
1009 {
1010         Node *n;
1011         int res = 0;
1012
1013         /* Close all open files */
1014         FOREACH_NODE(n, &disk->file_opened_list)
1015         {
1016                 BattFs *file = containerof(n, BattFs, link);
1017                 res += battfs_fileclose(&file->fd);
1018         }
1019
1020         /* Close disk */
1021         return disk->close(disk) && (res == 0);
1022 }
1023
1024 #if UNIT_TEST
1025
1026 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
1027 {
1028         BattFsPageHeader hdr;
1029
1030         /* Reset page to all 0xff */
1031         uint8_t buf[disk->page_size];
1032         memset(buf, 0xFF, disk->page_size);
1033         disk->bufferWrite(disk, 0, buf, disk->page_size);
1034
1035         hdr.inode = inode;
1036         hdr.fill = fill;
1037         hdr.pgoff = pgoff;
1038         hdr.seq = seq;
1039         hdr.fcs = computeFcs(&hdr);
1040
1041         if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
1042         {
1043                 LOG_ERR("error writing hdr\n");
1044                 return false;
1045         }
1046
1047         return true;
1048 }
1049 #endif