Remove unneeded if block, add some TODOs.
[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->dev->blk_cnt; 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 header of \a page in \a hdr.
133  * \return true on success, false otherwise.
134  */
135 static bool readHdr(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
136 {
137         uint8_t buf[BATTFS_HEADER_LEN];
138
139         /*
140          * Read header from disk.
141          * Header is actually a footer, and so
142          * resides at page end.
143          */
144         if (kblock_read(disk->dev, page, buf, disk->data_size, BATTFS_HEADER_LEN)
145             != BATTFS_HEADER_LEN)
146         {
147                 LOG_ERR("page[%d]\n", page);
148                 return false;
149         }
150
151         /* Fill header */
152         disk_to_battfs(buf, hdr);
153
154         return true;
155 }
156
157 static bool writeHdr(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
158 {
159         uint8_t buf[BATTFS_HEADER_LEN];
160
161         #warning FIXME:refactor computeFcs to save time and stack
162         hdr->fcs = computeFcs(hdr);
163         /* Fill buffer */
164         battfs_to_disk(hdr, buf);
165
166         /*
167          * write header to disk.
168          * Header is actually a footer, and so
169          * resides at page end.
170          */
171         if (kblock_write(disk->dev, page, buf, disk->data_size, BATTFS_HEADER_LEN)
172             != BATTFS_HEADER_LEN)
173         {
174                 LOG_ERR("writing to buffer\n");
175                 return false;
176         }
177         return true;
178 }
179
180
181 /**
182  * Count the number of pages from
183  * inode 0 to \a inode in \a filelen_table.
184  */
185 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
186 {
187         pgcnt_t cnt = 0;
188
189         for (inode_t i = 0; i < inode; i++)
190                 cnt += filelen_table[i];
191
192         return cnt;
193 }
194
195 /**
196  * Move all pages in page allocation array from \a src to \a src + \a offset.
197  * The number of pages moved is page_count - MAX(dst, src).
198  */
199 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
200 {
201         pgcnt_t dst = src + offset;
202         LOG_INFO("src %d, offset %d, size %d\n", src, offset, (unsigned int)((disk->dev->blk_cnt - MAX(dst, src)) * sizeof(pgcnt_t)));
203         memmove(&disk->page_array[dst], &disk->page_array[src], (disk->dev->blk_cnt - MAX(dst, src)) * sizeof(pgcnt_t));
204
205         if (offset < 0)
206         {
207                 /* Fill empty space in array with sentinel */
208                 for (pgcnt_t page = disk->dev->blk_cnt + offset; page < disk->dev->blk_cnt; page++)
209                         disk->page_array[page] = PAGE_UNSET_SENTINEL;
210         }
211 }
212
213 /**
214  * Count number of pages per file on \a disk.
215  * This information is registered in \a filelen_table.
216  * Array index represent file inode, while value contained
217  * is the number of pages used by that file.
218  *
219  * \return true if ok, false on disk read errors.
220  * \note The whole disk is scanned once.
221  */
222 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
223 {
224         BattFsPageHeader hdr;
225         disk->free_page_start = 0;
226
227         /* Count the number of disk page per file */
228         for (pgcnt_t page = 0; page < disk->dev->blk_cnt; page++)
229         {
230                 if (!readHdr(disk, page, &hdr))
231                         return false;
232
233                 /* Increase free space */
234                 disk->free_bytes += disk->data_size;
235
236                 /* Check header FCS */
237                 if (hdr.fcs == computeFcs(&hdr))
238                 {
239                         ASSERT(hdr.fill <= disk->data_size);
240
241                         /* Page is valid and is owned by a file */
242                         filelen_table[hdr.inode]++;
243
244                         /* Keep trace of free space */
245                         disk->free_bytes -= hdr.fill;
246                         disk->free_page_start++;
247                 }
248         }
249         LOG_INFO("free_bytes:%ld, free_page_start:%d\n", (long)disk->free_bytes, disk->free_page_start);
250
251         return true;
252 }
253
254 /**
255  * Fill page allocation array of \a disk
256  * using file lenghts in \a filelen_table.
257  *
258  * The page allocation array is an array containings all file infos.
259  * Is ordered by file, and within each file is ordered by page offset
260  * inside file.
261  * e.g. : at page array[0] you will find page address of the first page
262  * of the first file (if present).
263  * Free blocks are allocated after the last file.
264  *
265  * \return true if ok, false on disk read errors.
266  * \note The whole disk is scanned at max twice.
267  */
268 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
269 {
270         BattFsPageHeader hdr;
271         pgcnt_t curr_free_page = disk->free_page_start;
272         /* Fill page allocation array */
273         for (pgcnt_t page = 0; page < disk->dev->blk_cnt; page++)
274         {
275                 if (!readHdr(disk, page, &hdr))
276                         return false;
277
278                 /* Check header FCS */
279                 if (hdr.fcs == computeFcs(&hdr))
280                 {
281                         /* Compute array position */
282                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
283                         array_pos += hdr.pgoff;
284
285
286                         /* Check if position is already used by another page of the same file */
287                         if (disk->page_array[array_pos] == PAGE_UNSET_SENTINEL)
288                                 disk->page_array[array_pos] = page;
289                         else
290                         {
291                                 BattFsPageHeader hdr_prv;
292
293                                 if (!readHdr(disk, disk->page_array[array_pos], &hdr_prv))
294                                         return false;
295
296                                 /* Check header FCS */
297                                 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
298
299                                 /* Only the very same page with a different seq number can be here */
300                                 ASSERT(hdr.inode == hdr_prv.inode);
301                                 ASSERT(hdr.pgoff == hdr_prv.pgoff);
302                                 ASSERT(hdr.seq != hdr_prv.seq);
303
304                                 pgcnt_t new_page, old_page;
305                                 fill_t old_fill;
306
307                                 /*
308                                  * Sequence number comparison: since
309                                  * seq is 40 bits wide, it wraps once
310                                  * every 1.1E12 times.
311                                  * The memory will not live enough to
312                                  * see a wraparound, so we can use a simple
313                                  * compare here.
314                                  */
315                                 if (hdr.seq > hdr_prv.seq)
316                                 {
317                                         /* Current header is newer than the previuos one */
318                                         old_page = disk->page_array[array_pos];
319                                         new_page = page;
320                                         old_fill = hdr_prv.fill;
321                                 }
322                                 else
323                                 {
324                                         /* Previous header is newer than the current one */
325                                         old_page = page;
326                                         new_page = disk->page_array[array_pos];
327                                         old_fill = hdr.fill;
328                                 }
329
330                                 /* Set new page */
331                                 disk->page_array[array_pos] = new_page;
332                                 /* Add free space */
333                                 disk->free_bytes += old_fill;
334                                 /* Shift all array one position to the left, overwriting duplicate page */
335                                 array_pos -= hdr.pgoff;
336                                 array_pos += filelen_table[hdr.inode];
337                                 movePages(disk, array_pos, -1);
338                                 /* Move back all indexes */
339                                 filelen_table[hdr.inode]--;
340                                 disk->free_page_start--;
341                                 curr_free_page--;
342                                 /* Set old page as free */
343                                 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
344                                 disk->page_array[curr_free_page++] = old_page;
345
346                         }
347                 }
348                 else
349                 {
350                         /* Invalid page, keep as free */
351                         ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
352                         //LOG_INFO("Page %d invalid, keeping as free\n", page);
353                         disk->page_array[curr_free_page++] = page;
354                 }
355         }
356         return true;
357 }
358
359
360 /**
361  * Initialize and mount disk described by
362  * \a disk.
363  * \return false on errors, true otherwise.
364  */
365 bool battfs_mount(struct BattFsSuper *disk, struct KBlock *dev, pgcnt_t *page_array, size_t array_size)
366 {
367         pgoff_t filelen_table[BATTFS_MAX_FILES];
368
369         ASSERT(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                 // TODO: renew this last page only if needed
587                 if (!readHdr(disk, fdb->start[fdb->max_off], &curr_hdr))
588                 {
589                         fdb->errors |= BATTFS_DISK_READ_ERR;
590                         return total_write;
591                 }
592
593                 new_page = renewPage(disk, fdb->start[fdb->max_off]);
594                 if (new_page == NO_SPACE)
595                 {
596                         fdb->errors |= BATTFS_DISK_SPACEOVER_ERR;
597                         return total_write;
598                 }
599
600                 kblock_copy(disk->dev, fdb->start[fdb->max_off], new_page);
601                 fdb->start[fdb->max_off] = new_page;
602
603                 /* Fill unused space of first page with 0s */
604                 uint8_t dummy = 0;
605                 // TODO: write in blocks to speed up things
606                 pgaddr_t zero_bytes = MIN(fd->seek_pos - fd->size, (kfile_off_t)(disk->data_size - curr_hdr.fill));
607                 while (zero_bytes--)
608                 {
609                         if (kblock_write(disk->dev, new_page, &dummy, curr_hdr.fill, 1) != 1)
610                         {
611                                 fdb->errors |= BATTFS_DISK_WRITE_ERR;
612                                 return total_write;
613                         }
614                         curr_hdr.fill++;
615                         fd->size++;
616                         disk->free_bytes--;
617                 }
618                 curr_hdr.seq++;
619                 if (!writeHdr(disk, new_page, &curr_hdr))
620                 {
621                         fdb->errors |= BATTFS_DISK_WRITE_ERR;
622                         return total_write;
623                 }
624
625                 /* Allocate the missing pages first. */
626                 pgoff_t missing_pages = fd->seek_pos / disk->data_size - fdb->max_off;
627
628                 LOG_INFO("missing pages: %d\n", missing_pages);
629
630                 while (missing_pages--)
631                 {
632                         zero_bytes = MIN((kfile_off_t)disk->data_size, fd->seek_pos - fd->size);
633
634                         new_page = allocateNewPage(disk, (fdb->start - disk->page_array) + fdb->max_off + 1, fdb->inode);
635                         if (new_page == NO_SPACE)
636                         {
637                                 fdb->errors |= BATTFS_DISK_SPACEOVER_ERR;
638                                 return total_write;
639                         }
640
641
642                         // TODO: write in blocks to speed up things
643                         /* Fill page buffer with 0 to avoid filling unused pages with garbage */
644                         for (pgaddr_t off = 0; off < disk->data_size; off++)
645                         {
646                                 if (kblock_write(disk->dev, new_page, &dummy, off, 1) != 1)
647                                 {
648                                         fdb->errors |= BATTFS_DISK_WRITE_ERR;
649                                         return total_write;
650                                 }
651                         }
652                         curr_hdr.inode = fdb->inode;
653                         curr_hdr.pgoff = ++fdb->max_off;
654                         curr_hdr.fill = zero_bytes;
655                         curr_hdr.seq = 0;
656
657                         if (!writeHdr(disk, new_page, &curr_hdr))
658                         {
659                                 fdb->errors |= BATTFS_DISK_WRITE_ERR;
660                                 return total_write;
661                         }
662
663                         /* Update size and free space left */
664                         fd->size += zero_bytes;
665                         disk->free_bytes -= zero_bytes;
666                 }
667         }
668
669         while (size)
670         {
671                 pg_offset = fd->seek_pos / disk->data_size;
672                 addr_offset = fd->seek_pos % disk->data_size;
673                 wr_len = MIN(size, (size_t)(disk->data_size - addr_offset));
674
675                 /* Handle write outside EOF */
676                 if (pg_offset > fdb->max_off)
677                 {
678                         LOG_INFO("New page needed, pg_offset %d, pos %d\n", pg_offset, (int)((fdb->start - disk->page_array) + pg_offset));
679
680                         new_page = allocateNewPage(disk, (fdb->start - disk->page_array) + pg_offset, fdb->inode);
681                         if (new_page == NO_SPACE)
682                         {
683                                 fdb->errors |= BATTFS_DISK_SPACEOVER_ERR;
684                                 return total_write;
685                         }
686
687                         curr_hdr.inode = fdb->inode;
688                         curr_hdr.pgoff = pg_offset;
689                         curr_hdr.fill = 0;
690                         curr_hdr.seq = 0;
691                         fdb->max_off = pg_offset;
692                 }
693                 else
694                 {
695                         // TODO: do not renew page if its cached
696                         if (!readHdr(disk, fdb->start[pg_offset], &curr_hdr))
697                         {
698                                 fdb->errors |= BATTFS_DISK_READ_ERR;
699                                 return total_write;
700                         }
701
702                         new_page = renewPage(disk, fdb->start[pg_offset]);
703                         if (new_page == NO_SPACE)
704                         {
705                                 fdb->errors |= BATTFS_DISK_SPACEOVER_ERR;
706                                 return total_write;
707                         }
708
709                         LOG_INFO("Re-writing page %d to %d\n", fdb->start[pg_offset], new_page);
710                         if (kblock_copy(disk->dev, fdb->start[pg_offset], new_page) != 0)
711                         {
712                                 fdb->errors |= BATTFS_DISK_WRITE_ERR;
713                                 return total_write;
714                         }
715                         fdb->start[pg_offset] = new_page;
716                         curr_hdr.seq++;
717                 }
718                 //LOG_INFO("writing to buffer for page %d, offset %d, size %d\n", disk->curr_page, addr_offset, wr_len);
719                 if (kblock_write(disk->dev, new_page, buf, addr_offset, wr_len) != wr_len)
720                 {
721                         fdb->errors |= BATTFS_DISK_WRITE_ERR;
722                         return total_write;
723                 }
724
725                 size -= wr_len;
726                 fd->seek_pos += wr_len;
727                 total_write += wr_len;
728                 buf += wr_len;
729                 fill_t fill_delta = MAX((int32_t)(addr_offset + wr_len) - curr_hdr.fill, (int32_t)0);
730                 disk->free_bytes -= fill_delta;
731                 fd->size += fill_delta;
732                 curr_hdr.fill += fill_delta;
733
734                 if (!writeHdr(disk, new_page, &curr_hdr))
735                 {
736                         fdb->errors |= BATTFS_DISK_WRITE_ERR;
737                         return total_write;
738                 }
739
740                 //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);
741         }
742         return total_write;
743 }
744
745
746 /**
747  * Read from file \a fd \a size bytes in \a buf.
748  * \return The number of bytes read.
749  */
750 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
751 {
752         BattFs *fdb = BATTFS_CAST(fd);
753         BattFsSuper *disk = fdb->disk;
754         uint8_t *buf = (uint8_t *)_buf;
755
756         size_t total_read = 0;
757         pgoff_t pg_offset;
758         pgaddr_t addr_offset;
759         pgaddr_t read_len;
760
761         if (fd->seek_pos < 0)
762         {
763                 fdb->errors |= BATTFS_NEGATIVE_SEEK_ERR;
764                 return total_read;
765         }
766
767         size = MIN((kfile_off_t)size, MAX(fd->size - fd->seek_pos, (kfile_off_t)0));
768
769         while (size)
770         {
771                 pg_offset = fd->seek_pos / disk->data_size;
772                 addr_offset = fd->seek_pos % disk->data_size;
773                 read_len = MIN(size, (size_t)(disk->data_size - addr_offset));
774
775                 //LOG_INFO("reading from page %d, offset %d, size %d\n", fdb->start[pg_offset], addr_offset, read_len);
776                 /* Read from disk */
777                 if (kblock_read(disk->dev, fdb->start[pg_offset], buf, addr_offset, read_len) != read_len)
778                 {
779                         fdb->errors |= BATTFS_DISK_READ_ERR;
780                         return total_read;
781                 }
782
783                 #ifdef _DEBUG
784                         BattFsPageHeader hdr;
785                         readHdr(disk, fdb->start[pg_offset], &hdr);
786                         ASSERT(hdr.inode == fdb->inode);
787                 #endif
788
789                 size -= read_len;
790                 fd->seek_pos += read_len;
791                 total_read += read_len;
792                 buf += read_len;
793         }
794         return total_read;
795 }
796
797
798 /**
799  * Search file \a inode in \a disk using a binary search.
800  * \a last is filled with array offset of file start
801  * in disk->page_array if file is found, otherwise
802  * \a last is filled with the correct insert position
803  * for creating a file with the given \a inode.
804  * \return true if file is found, false otherwisr.
805  */
806 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
807 {
808         BattFsPageHeader hdr;
809         pgcnt_t first = 0, page;
810         *last = disk->free_page_start;
811         fcs_t fcs;
812
813         while (first < *last)
814         {
815                 page = (first + *last) / 2;
816                 LOG_INFO("first %d, last %d, page %d\n", first, *last, page);
817                 if (!readHdr(disk, disk->page_array[page], &hdr))
818                         return false;
819                 LOG_INFO("inode read: %d\n", hdr.inode);
820                 fcs = computeFcs(&hdr);
821                 if (hdr.fcs == fcs && hdr.inode == inode)
822                 {
823                         *last = page - hdr.pgoff;
824                         LOG_INFO("Found: %d\n", *last);
825                         return true;
826                 }
827                 else if (hdr.fcs == fcs && hdr.inode < inode)
828                         first = page + 1;
829                 else
830                         *last = page;
831         }
832         LOG_INFO("Not found: last %d\n", *last);
833         return false;
834 }
835
836 /**
837  * \return true if file \a inode exists on \a disk, false otherwise.
838  */
839 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
840 {
841         pgcnt_t dummy;
842         return findFile(disk, inode, &dummy);
843 }
844
845 /**
846  * Count size of file \a inode on \a disk, starting at pointer \a start
847  * in disk->page_array. Size is written in \a size.
848  * \return true if all s ok, false on disk read errors.
849  */
850 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
851 {
852         file_size_t size = 0;
853         BattFsPageHeader hdr;
854
855         while (start < &disk->page_array[disk->free_page_start])
856         {
857                 if (!readHdr(disk, *start++, &hdr))
858                         return EOF;
859                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
860                         size += hdr.fill;
861                 else
862                         break;
863         }
864         return size;
865 }
866
867 static int battfs_error(struct KFile *fd)
868 {
869         BattFs *fdb = BATTFS_CAST(fd);
870         return fdb->errors;
871 }
872
873
874 static void battfs_clearerr(struct KFile *fd)
875 {
876         BattFs *fdb = BATTFS_CAST(fd);
877         fdb->errors = 0;
878 }
879
880 /**
881  * Open file \a inode from \a disk in \a mode.
882  * File context is stored in \a fd.
883  * \return true if ok, false otherwise.
884  */
885 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
886 {
887         Node *n;
888
889         memset(fd, 0, sizeof(*fd));
890
891         /* Search file start point in disk page array */
892         pgcnt_t start_pos;
893         if (!findFile(disk, inode, &start_pos))
894         {
895                 LOG_INFO("file %d not found\n", inode);
896                 if (!(mode & BATTFS_CREATE))
897                 {
898                         fd->errors |= BATTFS_FILE_NOT_FOUND_ERR;
899                         return false;
900                 }
901                 /* Create the file */
902                 BattFsPageHeader hdr;
903
904                 if (allocateNewPage(disk, start_pos, inode) == NO_SPACE)
905                 {
906                         fd->errors |= BATTFS_DISK_SPACEOVER_ERR;
907                         return false;
908                 }
909
910                 hdr.inode = inode;
911                 hdr.pgoff = 0;
912                 hdr.fill = 0;
913                 hdr.seq = 0;
914                 if (!writeHdr(disk, disk->page_array[start_pos], &hdr))
915                 {
916                         fd->errors |= BATTFS_DISK_WRITE_ERR;
917                         return false;
918                 }
919         }
920         fd->start = &disk->page_array[start_pos];
921         LOG_INFO("Start pos %d\n", start_pos);
922
923         /* Fill file size */
924         if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
925         {
926                 fd->errors |= BATTFS_DISK_READ_ERR;
927                 return false;
928         }
929         fd->max_off = fd->fd.size / disk->data_size;
930
931         /* Reset seek position */
932         fd->fd.seek_pos = 0;
933
934         /* Insert file handle in list, ordered by inode, ascending. */
935         FOREACH_NODE(n, &disk->file_opened_list)
936         {
937                 BattFs *file = containerof(n, BattFs, link);
938                 if (file->inode >= inode)
939                         break;
940         }
941         INSERT_BEFORE(&fd->link, n);
942
943         /* Fill in data */
944         fd->inode = inode;
945         fd->mode = mode;
946         fd->disk = disk;
947
948         fd->fd.close = battfs_fileclose;
949         fd->fd.flush = battfs_flush;
950         fd->fd.read = battfs_read;
951         fd->fd.reopen = kfile_genericReopen;
952         fd->fd.seek = kfile_genericSeek;
953         fd->fd.write = battfs_write;
954
955         fd->fd.error = battfs_error;
956         fd->fd.clearerr = battfs_clearerr;
957
958         DB(fd->fd._type = KFT_BATTFS);
959
960         return true;
961 }
962
963
964 /**
965  * Umount \a disk.
966  */
967 bool battfs_umount(struct BattFsSuper *disk)
968 {
969         Node *n;
970         int res = 0;
971
972         /* Close all open files */
973         FOREACH_NODE(n, &disk->file_opened_list)
974         {
975                 BattFs *file = containerof(n, BattFs, link);
976                 res += battfs_fileclose(&file->fd);
977         }
978
979         /* Close disk */
980         return (kblock_flush(disk->dev) == 0) && (kblock_close(disk->dev) == 0) && (res == 0);
981 }
982
983 #if UNIT_TEST
984
985 void battfs_writeTestBlock(KBlock *dev, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
986 {
987         uint8_t buf[BATTFS_HEADER_LEN];
988         battfs_eraseBlock(dev, page);
989
990         BattFsPageHeader hdr;
991         hdr.inode = inode;
992         hdr.fill = fill;
993         hdr.pgoff = pgoff;
994         hdr.seq = seq;
995         hdr.fcs = computeFcs(&hdr);
996
997         battfs_to_disk(&hdr, buf);
998
999         ASSERT(kblock_write(dev, page, buf, dev->blk_size - BATTFS_HEADER_LEN, BATTFS_HEADER_LEN) == BATTFS_HEADER_LEN);
1000         ASSERT(kblock_flush(dev) == 0);
1001 }
1002
1003 void battfs_eraseBlock(KBlock *dev, pgcnt_t page)
1004 {
1005         /* Reset page to all 0xff */
1006         uint8_t buf[dev->blk_size];
1007         memset(buf, 0xFF, dev->blk_size);
1008         ASSERT(kblock_write(dev, page, buf, 0, dev->blk_size) == dev->blk_size);
1009         ASSERT(kblock_flush(dev) == 0);
1010 }
1011
1012 #endif