deef25ccb0d53aeb67e44704e0394840e91557c2
[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         /* Uneeded, the first time will be overwritten but useful to silence
526          * the warning for uninitialized value */
527         FSCHECK(readHdr(disk, 0, &prev_hdr));
528         for (pgcnt_t page = 0; page < disk->page_count; page++)
529         {
530                 FSCHECK(readHdr(disk, disk->page_array[page], &hdr));
531                 free_bytes += disk->data_size;
532
533                 if (page < disk->free_page_start)
534                 {
535                         FSCHECK(computeFcs(&hdr) == hdr.fcs);
536                         page_used++;
537                         free_bytes -= hdr.fill;
538                         if (hdr.inode != prev_hdr.inode || start)
539                         {
540                                 if (LIKELY(!start))
541                                         FSCHECK(hdr.inode > prev_hdr.inode);
542                                 else
543                                         start = false;
544
545                                 FSCHECK(hdr.pgoff == 0);
546                                 files++;
547                         }
548                         else
549                         {
550                                 FSCHECK(hdr.fill != 0);
551                                 FSCHECK(prev_hdr.fill == disk->data_size);
552                                 FSCHECK(hdr.pgoff == prev_hdr.pgoff + 1);
553                         }
554                         prev_hdr = hdr;
555                 }
556         }
557
558         FSCHECK(page_used == disk->free_page_start);
559         FSCHECK(free_bytes == disk->free_bytes);
560
561         return true;
562 }
563
564 /**
565  * Flush file \a fd.
566  * \return 0 if ok, EOF on errors.
567  */
568 static int battfs_flush(struct KFile *fd)
569 {
570         BattFs *fdb = BATTFS_CAST(fd);
571
572         if (flushBuffer(fdb->disk))
573                 return 0;
574         else
575         {
576                 fdb->errors |= BATTFS_DISK_FLUSHBUF_ERR;
577                 return EOF;
578         }
579 }
580
581 /**
582  * Close file \a fd.
583  * \return 0 if ok, EOF on errors.
584  */
585 static int battfs_fileclose(struct KFile *fd)
586 {
587         BattFs *fdb = BATTFS_CAST(fd);
588
589         if (battfs_flush(fd) == 0)
590         {
591                 REMOVE(&fdb->link);
592                 return 0;
593         }
594         else
595                 return EOF;
596 }
597
598
599 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff, BattFsPageHeader *new_hdr)
600 {
601         if (SPACE_OVER(disk))
602         {
603                 LOG_ERR("No disk space available!\n");
604                 return false;
605         }
606         flushBuffer(disk);
607         LOG_INFO("Getting new page %d, pos %d\n", disk->page_array[disk->free_page_start], new_pos);
608         disk->curr_page = disk->page_array[disk->free_page_start++];
609         memmove(&disk->page_array[new_pos + 1], &disk->page_array[new_pos], (disk->free_page_start - new_pos - 1) * sizeof(pgcnt_t));
610
611         Node *n;
612         /* Move following file start point one position ahead. */
613         FOREACH_NODE(n, &disk->file_opened_list)
614         {
615                 BattFs *file = containerof(n, BattFs, link);
616                 if (file->inode > inode)
617                 {
618                         LOG_INFO("Move file %d start pos\n", file->inode);
619                         file->start++;
620                 }
621         }
622
623         disk->page_array[new_pos] = disk->curr_page;
624         disk->cache_dirty = true;
625
626         new_hdr->inode = inode;
627         new_hdr->pgoff = pgoff;
628         new_hdr->fill = 0;
629         new_hdr->seq = 0;
630         return setBufferHdr(disk, new_hdr);
631 }
632
633 /**
634  * Write to file \a fd \a size bytes from \a buf.
635  * \return The number of bytes written.
636  */
637 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
638 {
639         BattFs *fdb = BATTFS_CAST(fd);
640         BattFsSuper *disk = fdb->disk;
641         const uint8_t *buf = (const uint8_t *)_buf;
642
643         size_t total_write = 0;
644         pgoff_t pg_offset;
645         pgaddr_t addr_offset;
646         pgaddr_t wr_len;
647         BattFsPageHeader curr_hdr;
648
649         if (fd->seek_pos < 0)
650         {
651                 fdb->errors |= BATTFS_NEGATIVE_SEEK_ERR;
652                 return total_write;
653         }
654
655         if (fd->seek_pos > fd->size)
656         {
657                 /* Handle writing when seek pos if far over EOF */
658                 if (!loadPage(disk, fdb->start[fdb->max_off], &curr_hdr))
659                 {
660                         fdb->errors |= BATTFS_DISK_LOADPAGE_ERR;
661                         return total_write;
662                 }
663
664                 /* Fill unused space of first page with 0s */
665                 uint8_t dummy = 0;
666                 pgaddr_t zero_bytes = MIN(fd->seek_pos - fd->size, (kfile_off_t)(disk->data_size - curr_hdr.fill));
667                 while (zero_bytes--)
668                 {
669                         if (disk->bufferWrite(disk, curr_hdr.fill, &dummy, 1) != 1)
670                         {
671                                 fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
672                                 return total_write;
673                         }
674                         curr_hdr.fill++;
675                         fd->size++;
676                         disk->free_bytes--;
677                         disk->cache_dirty = true;
678                 }
679                 setBufferHdr(disk, &curr_hdr);
680
681                 /* Allocate the missing pages first. */
682                 pgoff_t missing_pages = fd->seek_pos / disk->data_size - fdb->max_off;
683
684                 if (missing_pages)
685                 {
686                         LOG_INFO("missing pages: %d\n", missing_pages);
687                         flushBuffer(disk);
688
689                         /* Fill page buffer with 0 to avoid filling unused pages with garbage */
690                         for (pgaddr_t off = 0; off < disk->data_size; off++)
691                         {
692                                 if (disk->bufferWrite(disk, off, &dummy, 1) != 1)
693                                 {
694                                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
695                                         return total_write;
696                                 }
697                         }
698
699                         while (missing_pages--)
700                         {
701                                 zero_bytes = MIN((kfile_off_t)disk->data_size, fd->seek_pos - fd->size);
702                                 /* Get the new page needed */
703                                 if (!getNewPage(disk, (fdb->start - disk->page_array) + fdb->max_off + 1, fdb->inode, fdb->max_off + 1, &curr_hdr))
704                                 {
705                                         fdb->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
706                                         return total_write;
707                                 }
708
709                                 /* Update size and free space left */
710                                 fd->size += zero_bytes;
711                                 disk->free_bytes -= zero_bytes;
712
713                                 curr_hdr.fill = zero_bytes;
714                                 setBufferHdr(disk, &curr_hdr);
715
716                                 fdb->max_off++;
717                         }
718                 }
719         }
720         else if (!getBufferHdr(disk, &curr_hdr))
721         {
722                 fdb->errors |=  BATTFS_DISK_BUFFERRD_ERR;
723                 return total_write;
724         }
725
726         while (size)
727         {
728                 pg_offset = fd->seek_pos / disk->data_size;
729                 addr_offset = fd->seek_pos % disk->data_size;
730                 wr_len = MIN(size, (size_t)(disk->data_size - addr_offset));
731
732                 /* Handle write outside EOF */
733                 if (pg_offset > fdb->max_off)
734                 {
735                         LOG_INFO("New page needed, pg_offset %d, pos %d\n", pg_offset, (int)((fdb->start - disk->page_array) + pg_offset));
736                         if (!getNewPage(disk, (fdb->start - disk->page_array) + pg_offset, fdb->inode, pg_offset, &curr_hdr))
737                         {
738                                 fdb->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
739                                 return total_write;
740                         }
741
742                         fdb->max_off = pg_offset;
743                 }
744                 /* Handle cache load of a new page*/
745                 else if (fdb->start[pg_offset] != disk->curr_page)
746                 {
747                         if (SPACE_OVER(disk))
748                         {
749                                 LOG_ERR("No disk space available!\n");
750                                 fdb->errors |= BATTFS_DISK_SPACEOVER_ERR;
751                                 return total_write;
752                         }
753                         LOG_INFO("Re-writing page %d to %d\n", fdb->start[pg_offset], disk->page_array[disk->free_page_start]);
754                         if (!loadPage(disk, fdb->start[pg_offset], &curr_hdr))
755                         {
756                                 fdb->errors |= BATTFS_DISK_LOADPAGE_ERR;
757                                 return total_write;
758                         }
759
760                         /* Get a free page */
761                         disk->curr_page = disk->page_array[disk->free_page_start];
762                         movePages(disk, disk->free_page_start + 1, -1);
763
764                         /* Insert previous page in free blocks list */
765                         LOG_INFO("Setting page %d as free\n", fdb->start[pg_offset]);
766                         disk->page_array[disk->page_count - 1] = fdb->start[pg_offset];
767                         /* Assign new page */
768                         fdb->start[pg_offset] = disk->curr_page;
769                         curr_hdr.seq++;
770                 }
771
772                 //LOG_INFO("writing to buffer for page %d, offset %d, size %d\n", disk->curr_page, addr_offset, wr_len);
773                 if (disk->bufferWrite(disk, addr_offset, buf, wr_len) != wr_len)
774                 {
775                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
776                         return total_write;
777                 }
778                 disk->cache_dirty = true;
779
780                 size -= wr_len;
781                 fd->seek_pos += wr_len;
782                 total_write += wr_len;
783                 buf += wr_len;
784                 fill_t fill_delta = MAX((int32_t)(addr_offset + wr_len) - curr_hdr.fill, (int32_t)0);
785                 disk->free_bytes -= fill_delta;
786                 fd->size += fill_delta;
787                 curr_hdr.fill += fill_delta;
788
789                 if (!setBufferHdr(disk, &curr_hdr))
790                 {
791                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
792                         return total_write;
793                 }
794
795                 //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);
796         }
797         return total_write;
798 }
799
800
801 /**
802  * Read from file \a fd \a size bytes in \a buf.
803  * \return The number of bytes read.
804  */
805 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
806 {
807         BattFs *fdb = BATTFS_CAST(fd);
808         BattFsSuper *disk = fdb->disk;
809         uint8_t *buf = (uint8_t *)_buf;
810
811         size_t total_read = 0;
812         pgoff_t pg_offset;
813         pgaddr_t addr_offset;
814         pgaddr_t read_len;
815
816         if (fd->seek_pos < 0)
817         {
818                 fdb->errors |= BATTFS_NEGATIVE_SEEK_ERR;
819                 return total_read;
820         }
821
822         size = MIN((kfile_off_t)size, MAX(fd->size - fd->seek_pos, (kfile_off_t)0));
823
824         while (size)
825         {
826                 pg_offset = fd->seek_pos / disk->data_size;
827                 addr_offset = fd->seek_pos % disk->data_size;
828                 read_len = MIN(size, (size_t)(disk->data_size - addr_offset));
829
830                 //LOG_INFO("reading from page %d, offset %d, size %d\n", fdb->start[pg_offset], addr_offset, read_len);
831                 /* Read from disk */
832                 if (diskRead(disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
833                 {
834                         fdb->errors |= BATTFS_DISK_READ_ERR;
835                         return total_read;
836                 }
837
838                 #ifdef _DEBUG
839                         BattFsPageHeader hdr;
840                         readHdr(disk, fdb->start[pg_offset], &hdr);
841                         ASSERT(hdr.inode == fdb->inode);
842                 #endif
843
844                 size -= read_len;
845                 fd->seek_pos += read_len;
846                 total_read += read_len;
847                 buf += read_len;
848         }
849         return total_read;
850 }
851
852
853 /**
854  * Search file \a inode in \a disk using a binary search.
855  * \a last is filled with array offset of file start
856  * in disk->page_array if file is found, otherwise
857  * \a last is filled with the correct insert position
858  * for creating a file with the given \a inode.
859  * \return true if file is found, false otherwisr.
860  */
861 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
862 {
863         BattFsPageHeader hdr;
864         pgcnt_t first = 0, page;
865         *last = disk->free_page_start;
866         fcs_t fcs;
867
868         while (first < *last)
869         {
870                 page = (first + *last) / 2;
871                 LOG_INFO("first %d, last %d, page %d\n", first, *last, page);
872                 if (!readHdr(disk, disk->page_array[page], &hdr))
873                         return false;
874                 LOG_INFO("inode read: %d\n", hdr.inode);
875                 fcs = computeFcs(&hdr);
876                 if (hdr.fcs == fcs && hdr.inode == inode)
877                 {
878                         *last = page - hdr.pgoff;
879                         LOG_INFO("Found: %d\n", *last);
880                         return true;
881                 }
882                 else if (hdr.fcs == fcs && hdr.inode < inode)
883                         first = page + 1;
884                 else
885                         *last = page;
886         }
887         LOG_INFO("Not found: last %d\n", *last);
888         return false;
889 }
890
891 /**
892  * \return true if file \a inode exists on \a disk, false otherwise.
893  */
894 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
895 {
896         pgcnt_t dummy;
897         return findFile(disk, inode, &dummy);
898 }
899
900 /**
901  * Count size of file \a inode on \a disk, starting at pointer \a start
902  * in disk->page_array. Size is written in \a size.
903  * \return true if all s ok, false on disk read errors.
904  */
905 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
906 {
907         file_size_t size = 0;
908         BattFsPageHeader hdr;
909
910         while (start < &disk->page_array[disk->free_page_start])
911         {
912                 if (!readHdr(disk, *start++, &hdr))
913                         return EOF;
914                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
915                         size += hdr.fill;
916                 else
917                         break;
918         }
919         return size;
920 }
921
922 static int battfs_error(struct KFile *fd)
923 {
924         BattFs *fdb = BATTFS_CAST(fd);
925         return fdb->errors;
926 }
927
928
929 static void battfs_clearerr(struct KFile *fd)
930 {
931         BattFs *fdb = BATTFS_CAST(fd);
932         fdb->errors = 0;
933 }
934
935 /**
936  * Open file \a inode from \a disk in \a mode.
937  * File context is stored in \a fd.
938  * \return true if ok, false otherwise.
939  */
940 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
941 {
942         Node *n;
943
944         memset(fd, 0, sizeof(*fd));
945
946         /* Search file start point in disk page array */
947         pgcnt_t start_pos;
948         if (!findFile(disk, inode, &start_pos))
949         {
950                 LOG_INFO("file %d not found\n", inode);
951                 if (!(mode & BATTFS_CREATE))
952                 {
953                         fd->errors |= BATTFS_FILE_NOT_FOUND_ERR;
954                         return false;
955                 }
956                 /* Create the file */
957                 BattFsPageHeader hdr;
958                 if (!(getNewPage(disk, start_pos, inode, 0, &hdr)))
959                 {
960                         fd->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
961                         return false;
962                 }
963         }
964         fd->start = &disk->page_array[start_pos];
965         LOG_INFO("Start pos %d\n", start_pos);
966
967         /* Fill file size */
968         if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
969         {
970                 fd->errors |= BATTFS_DISK_READ_ERR;
971                 return false;
972         }
973         fd->max_off = fd->fd.size / disk->data_size;
974
975         /* Reset seek position */
976         fd->fd.seek_pos = 0;
977
978         /* Insert file handle in list, ordered by inode, ascending. */
979         FOREACH_NODE(n, &disk->file_opened_list)
980         {
981                 BattFs *file = containerof(n, BattFs, link);
982                 if (file->inode >= inode)
983                         break;
984         }
985         INSERT_BEFORE(&fd->link, n);
986
987         /* Fill in data */
988         fd->inode = inode;
989         fd->mode = mode;
990         fd->disk = disk;
991
992         fd->fd.close = battfs_fileclose;
993         fd->fd.flush = battfs_flush;
994         fd->fd.read = battfs_read;
995         fd->fd.reopen = kfile_genericReopen;
996         fd->fd.seek = kfile_genericSeek;
997         fd->fd.write = battfs_write;
998
999         fd->fd.error = battfs_error;
1000         fd->fd.clearerr = battfs_clearerr;
1001
1002         DB(fd->fd._type = KFT_BATTFS);
1003
1004         return true;
1005 }
1006
1007
1008 /**
1009  * Umount \a disk.
1010  */
1011 bool battfs_umount(struct BattFsSuper *disk)
1012 {
1013         Node *n;
1014         int res = 0;
1015
1016         /* Close all open files */
1017         FOREACH_NODE(n, &disk->file_opened_list)
1018         {
1019                 BattFs *file = containerof(n, BattFs, link);
1020                 res += battfs_fileclose(&file->fd);
1021         }
1022
1023         /* Close disk */
1024         return disk->close(disk) && (res == 0);
1025 }
1026
1027 #if UNIT_TEST
1028
1029 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
1030 {
1031         BattFsPageHeader hdr;
1032
1033         /* Reset page to all 0xff */
1034         uint8_t buf[disk->page_size];
1035         memset(buf, 0xFF, disk->page_size);
1036         disk->bufferWrite(disk, 0, buf, disk->page_size);
1037
1038         hdr.inode = inode;
1039         hdr.fill = fill;
1040         hdr.pgoff = pgoff;
1041         hdr.seq = seq;
1042         hdr.fcs = computeFcs(&hdr);
1043
1044         if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
1045         {
1046                 LOG_ERR("error writing hdr\n");
1047                 return false;
1048         }
1049
1050         return true;
1051 }
1052 #endif