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