Merged from external project:
[bertos.git] / bertos / fs / battfs.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2007 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief BattFS: a filesystem for embedded platforms (implementation).
34  *
35  * \version $Id:$
36  *
37  * \author Francesco Sacchi <batt@develer.com>
38  *
39  */
40
41 #include "battfs.h"
42
43 #include <cfg/debug.h>
44 #include <cfg/macros.h> /* MIN, MAX */
45 #include <cfg/test.h>
46 #include <cpu/byteorder.h> /* cpu_to_xx */
47
48 #define LOG_LEVEL       LOG_LVL_INFO
49 #define LOG_FORMAT      LOG_FMT_VERBOSE
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         #warning TODO: shuffle free blocks
494         //#if LOG_LEVEL > LOG_LVL_INFO
495         //      dumpPageArray(disk);
496         //#endif
497         /* Init list for opened files. */
498         LIST_INIT(&disk->file_opened_list);
499         return true;
500 }
501
502 /**
503  * Check the filesystem.
504  * \return true if ok, false on errors.
505  */
506 bool battfs_fsck(struct BattFsSuper *disk)
507 {
508         #define FSCHECK(cond) do { if(!(cond)) { LOG_ERR("\"" #cond "\"\n"); return false; } } while (0)
509
510         FSCHECK(disk->free_page_start <= disk->page_count);
511         FSCHECK(disk->data_size < disk->page_size);
512         FSCHECK(disk->free_bytes <= disk->disk_size);
513
514         disk_size_t free_bytes = 0;
515         BattFsPageHeader hdr, prev_hdr;
516         inode_t files = 0;
517         pgcnt_t page_used = 0;
518
519         bool start = true;
520
521         for (pgcnt_t page = 0; page < disk->page_count; page++)
522         {
523                 FSCHECK(readHdr(disk, disk->page_array[page], &hdr));
524                 free_bytes += disk->data_size;
525
526                 if (page < disk->free_page_start)
527                 {
528                         FSCHECK(computeFcs(&hdr) == hdr.fcs);
529                         page_used++;
530                         free_bytes -= hdr.fill;
531                         if (hdr.inode != prev_hdr.inode || start)
532                         {
533                                 if (LIKELY(!start))
534                                         FSCHECK(hdr.inode > prev_hdr.inode);
535                                 else
536                                         start = false;
537
538                                 FSCHECK(hdr.pgoff == 0);
539                                 files++;
540                         }
541                         else
542                         {
543                                 FSCHECK(hdr.fill != 0);
544                                 FSCHECK(prev_hdr.fill == disk->data_size);
545                                 FSCHECK(hdr.pgoff == prev_hdr.pgoff + 1);
546                         }
547                         prev_hdr = hdr;
548                 }
549         }
550
551         FSCHECK(page_used == disk->free_page_start);
552         FSCHECK(free_bytes == disk->free_bytes);
553
554         return true;
555 }
556
557 /**
558  * Flush file \a fd.
559  * \return 0 if ok, EOF on errors.
560  */
561 static int battfs_flush(struct KFile *fd)
562 {
563         BattFs *fdb = BATTFS_CAST(fd);
564
565         if (flushBuffer(fdb->disk))
566                 return 0;
567         else
568         {
569                 fdb->errors |= BATTFS_DISK_FLUSHBUF_ERR;
570                 return EOF;
571         }
572 }
573
574 /**
575  * Close file \a fd.
576  * \return 0 if ok, EOF on errors.
577  */
578 static int battfs_fileclose(struct KFile *fd)
579 {
580         BattFs *fdb = BATTFS_CAST(fd);
581
582         if (battfs_flush(fd) == 0)
583         {
584                 REMOVE(&fdb->link);
585                 return 0;
586         }
587         else
588                 return EOF;
589 }
590
591
592 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff, BattFsPageHeader *new_hdr)
593 {
594         if (SPACE_OVER(disk))
595         {
596                 LOG_ERR("No disk space available!\n");
597                 return false;
598         }
599         flushBuffer(disk);
600         LOG_INFO("Getting new page %d, pos %d\n", disk->page_array[disk->free_page_start], new_pos);
601         disk->curr_page = disk->page_array[disk->free_page_start++];
602         memmove(&disk->page_array[new_pos + 1], &disk->page_array[new_pos], (disk->free_page_start - new_pos - 1) * sizeof(pgcnt_t));
603
604         Node *n;
605         /* Move following file start point one position ahead. */
606         FOREACH_NODE(n, &disk->file_opened_list)
607         {
608                 BattFs *file = containerof(n, BattFs, link);
609                 if (file->inode > inode)
610                 {
611                         LOG_INFO("Move file %d start pos\n", file->inode);
612                         file->start++;
613                 }
614         }
615
616         disk->page_array[new_pos] = disk->curr_page;
617         disk->cache_dirty = true;
618
619         new_hdr->inode = inode;
620         new_hdr->pgoff = pgoff;
621         new_hdr->fill = 0;
622         new_hdr->seq = 0;
623         return setBufferHdr(disk, new_hdr);
624 }
625
626 /**
627  * Write to file \a fd \a size bytes from \a buf.
628  * \return The number of bytes written.
629  */
630 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
631 {
632         BattFs *fdb = BATTFS_CAST(fd);
633         BattFsSuper *disk = fdb->disk;
634         const uint8_t *buf = (const uint8_t *)_buf;
635
636         size_t total_write = 0;
637         pgoff_t pg_offset;
638         pgaddr_t addr_offset;
639         pgaddr_t wr_len;
640         BattFsPageHeader curr_hdr;
641
642         if (fd->seek_pos < 0)
643         {
644                 fdb->errors |= BATTFS_NEGATIVE_SEEK_ERR;
645                 return total_write;
646         }
647
648         if (fd->seek_pos > fd->size)
649         {
650                 /* Handle writing when seek pos if far over EOF */
651                 if (!loadPage(disk, fdb->start[fdb->max_off], &curr_hdr))
652                 {
653                         fdb->errors |= BATTFS_DISK_LOADPAGE_ERR;
654                         return total_write;
655                 }
656
657                 /* Fill unused space of first page with 0s */
658                 uint8_t dummy = 0;
659                 pgaddr_t zero_bytes = MIN(fd->seek_pos - fd->size, (kfile_off_t)(disk->data_size - curr_hdr.fill));
660                 while (zero_bytes--)
661                 {
662                         if (disk->bufferWrite(disk, curr_hdr.fill, &dummy, 1) != 1)
663                         {
664                                 fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
665                                 return total_write;
666                         }
667                         curr_hdr.fill++;
668                         fd->size++;
669                         disk->free_bytes--;
670                         disk->cache_dirty = true;
671                 }
672                 setBufferHdr(disk, &curr_hdr);
673
674                 /* Allocate the missing pages first. */
675                 pgoff_t missing_pages = fd->seek_pos / disk->data_size - fdb->max_off;
676
677                 if (missing_pages)
678                 {
679                         LOG_INFO("missing pages: %d\n", missing_pages);
680                         flushBuffer(disk);
681
682                         /* Fill page buffer with 0 to avoid filling unused pages with garbage */
683                         for (pgaddr_t off = 0; off < disk->data_size; off++)
684                         {
685                                 if (disk->bufferWrite(disk, off, &dummy, 1) != 1)
686                                 {
687                                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
688                                         return total_write;
689                                 }
690                         }
691
692                         while (missing_pages--)
693                         {
694                                 zero_bytes = MIN((kfile_off_t)disk->data_size, fd->seek_pos - fd->size);
695                                 /* Get the new page needed */
696                                 if (!getNewPage(disk, (fdb->start - disk->page_array) + fdb->max_off + 1, fdb->inode, fdb->max_off + 1, &curr_hdr))
697                                 {
698                                         fdb->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
699                                         return total_write;
700                                 }
701
702                                 /* Update size and free space left */
703                                 fd->size += zero_bytes;
704                                 disk->free_bytes -= zero_bytes;
705
706                                 curr_hdr.fill = zero_bytes;
707                                 setBufferHdr(disk, &curr_hdr);
708
709                                 fdb->max_off++;
710                         }
711                 }
712         }
713         else if (!getBufferHdr(disk, &curr_hdr))
714         {
715                 fdb->errors |=  BATTFS_DISK_BUFFERRD_ERR;
716                 return total_write;
717         }
718
719         while (size)
720         {
721                 pg_offset = fd->seek_pos / disk->data_size;
722                 addr_offset = fd->seek_pos % disk->data_size;
723                 wr_len = MIN(size, (size_t)(disk->data_size - addr_offset));
724
725                 /* Handle write outside EOF */
726                 if (pg_offset > fdb->max_off)
727                 {
728                         LOG_INFO("New page needed, pg_offset %d, pos %d\n", pg_offset, (int)((fdb->start - disk->page_array) + pg_offset));
729                         if (!getNewPage(disk, (fdb->start - disk->page_array) + pg_offset, fdb->inode, pg_offset, &curr_hdr))
730                         {
731                                 fdb->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
732                                 return total_write;
733                         }
734
735                         fdb->max_off = pg_offset;
736                 }
737                 /* Handle cache load of a new page*/
738                 else if (fdb->start[pg_offset] != disk->curr_page)
739                 {
740                         if (SPACE_OVER(disk))
741                         {
742                                 LOG_ERR("No disk space available!\n");
743                                 fdb->errors |= BATTFS_DISK_SPACEOVER_ERR;
744                                 return total_write;
745                         }
746                         LOG_INFO("Re-writing page %d to %d\n", fdb->start[pg_offset], disk->page_array[disk->free_page_start]);
747                         if (!loadPage(disk, fdb->start[pg_offset], &curr_hdr))
748                         {
749                                 fdb->errors |= BATTFS_DISK_LOADPAGE_ERR;
750                                 return total_write;
751                         }
752
753                         /* Get a free page */
754                         disk->curr_page = disk->page_array[disk->free_page_start];
755                         movePages(disk, disk->free_page_start + 1, -1);
756
757                         /* Insert previous page in free blocks list */
758                         LOG_INFO("Setting page %d as free\n", fdb->start[pg_offset]);
759                         disk->page_array[disk->page_count - 1] = fdb->start[pg_offset];
760                         /* Assign new page */
761                         fdb->start[pg_offset] = disk->curr_page;
762                         curr_hdr.seq++;
763                 }
764
765                 //LOG_INFO("writing to buffer for page %d, offset %d, size %d\n", disk->curr_page, addr_offset, wr_len);
766                 if (disk->bufferWrite(disk, addr_offset, buf, wr_len) != wr_len)
767                 {
768                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
769                         return total_write;
770                 }
771                 disk->cache_dirty = true;
772
773                 size -= wr_len;
774                 fd->seek_pos += wr_len;
775                 total_write += wr_len;
776                 buf += wr_len;
777                 fill_t fill_delta = MAX((int32_t)(addr_offset + wr_len) - curr_hdr.fill, (int32_t)0);
778                 disk->free_bytes -= fill_delta;
779                 fd->size += fill_delta;
780                 curr_hdr.fill += fill_delta;
781
782                 if (!setBufferHdr(disk, &curr_hdr))
783                 {
784                         fdb->errors |= BATTFS_DISK_BUFFERWR_ERR;
785                         return total_write;
786                 }
787
788                 //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);
789         }
790         return total_write;
791 }
792
793
794 /**
795  * Read from file \a fd \a size bytes in \a buf.
796  * \return The number of bytes read.
797  */
798 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
799 {
800         BattFs *fdb = BATTFS_CAST(fd);
801         BattFsSuper *disk = fdb->disk;
802         uint8_t *buf = (uint8_t *)_buf;
803
804         size_t total_read = 0;
805         pgoff_t pg_offset;
806         pgaddr_t addr_offset;
807         pgaddr_t read_len;
808
809         if (fd->seek_pos < 0)
810         {
811                 fdb->errors |= BATTFS_NEGATIVE_SEEK_ERR;
812                 return total_read;
813         }
814
815         size = MIN((kfile_off_t)size, MAX(fd->size - fd->seek_pos, (kfile_off_t)0));
816
817         while (size)
818         {
819                 pg_offset = fd->seek_pos / disk->data_size;
820                 addr_offset = fd->seek_pos % disk->data_size;
821                 read_len = MIN(size, (size_t)(disk->data_size - addr_offset));
822
823                 //LOG_INFO("reading from page %d, offset %d, size %d\n", fdb->start[pg_offset], addr_offset, read_len);
824                 /* Read from disk */
825                 if (diskRead(disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
826                 {
827                         fdb->errors |= BATTFS_DISK_READ_ERR;
828                         return total_read;
829                 }
830
831                 #if _DEBUG
832                         BattFsPageHeader hdr;
833                         readHdr(disk, fdb->start[pg_offset], &hdr);
834                         ASSERT(hdr.inode == fdb->inode);
835                 #endif
836
837                 size -= read_len;
838                 fd->seek_pos += read_len;
839                 total_read += read_len;
840                 buf += read_len;
841         }
842         return total_read;
843 }
844
845
846 /**
847  * Search file \a inode in \a disk using a binary search.
848  * \a last is filled with array offset of file start
849  * in disk->page_array if file is found, otherwise
850  * \a last is filled with the correct insert position
851  * for creating a file with the given \a inode.
852  * \return true if file is found, false otherwisr.
853  */
854 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
855 {
856         BattFsPageHeader hdr;
857         pgcnt_t first = 0, page;
858         *last = disk->free_page_start;
859         fcs_t fcs;
860
861         while (first < *last)
862         {
863                 page = (first + *last) / 2;
864                 LOG_INFO("first %d, last %d, page %d\n", first, *last, page);
865                 if (!readHdr(disk, disk->page_array[page], &hdr))
866                         return false;
867                 LOG_INFO("inode read: %d\n", hdr.inode);
868                 fcs = computeFcs(&hdr);
869                 if (hdr.fcs == fcs && hdr.inode == inode)
870                 {
871                         *last = page - hdr.pgoff;
872                         LOG_INFO("Found: %d\n", *last);
873                         return true;
874                 }
875                 else if (hdr.fcs == fcs && hdr.inode < inode)
876                         first = page + 1;
877                 else
878                         *last = page + 1;
879         }
880         LOG_INFO("Not found: last %d\n", *last);
881         return false;
882 }
883
884 /**
885  * \return true if file \a inode exists on \a disk, false otherwise.
886  */
887 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
888 {
889         pgcnt_t dummy;
890         return findFile(disk, inode, &dummy);
891 }
892
893 /**
894  * Count size of file \a inode on \a disk, starting at pointer \a start
895  * in disk->page_array. Size is written in \a size.
896  * \return true if all s ok, false on disk read errors.
897  */
898 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
899 {
900         file_size_t size = 0;
901         BattFsPageHeader hdr;
902
903         while (start < &disk->page_array[disk->free_page_start])
904         {
905                 if (!readHdr(disk, *start++, &hdr))
906                         return EOF;
907                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
908                         size += hdr.fill;
909                 else
910                         break;
911         }
912         return size;
913 }
914
915 static int battfs_error(struct KFile *fd)
916 {
917         BattFs *fdb = BATTFS_CAST(fd);
918         return fdb->errors;
919 }
920
921
922 static void battfs_clearerr(struct KFile *fd)
923 {
924         BattFs *fdb = BATTFS_CAST(fd);
925         fdb->errors = 0;
926 }
927
928 /**
929  * Open file \a inode from \a disk in \a mode.
930  * File context is stored in \a fd.
931  * \return true if ok, false otherwise.
932  */
933 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
934 {
935         Node *n;
936
937         memset(fd, 0, sizeof(*fd));
938
939         /* Search file start point in disk page array */
940         pgcnt_t start_pos;
941         if (!findFile(disk, inode, &start_pos))
942         {
943                 LOG_INFO("file %d not found\n", inode);
944                 if (!(mode & BATTFS_CREATE))
945                 {
946                         fd->errors |= BATTFS_FILE_NOT_FOUND_ERR;
947                         return false;
948                 }
949                 /* Create the file */
950                 BattFsPageHeader hdr;
951                 if (!(getNewPage(disk, start_pos, inode, 0, &hdr)))
952                 {
953                         fd->errors |= BATTFS_DISK_GETNEWPAGE_ERR;
954                         return false;
955                 }
956         }
957         fd->start = &disk->page_array[start_pos];
958         LOG_INFO("Start pos %d\n", start_pos);
959
960         /* Fill file size */
961         if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
962         {
963                 fd->errors |= BATTFS_DISK_READ_ERR;
964                 return false;
965         }
966         fd->max_off = fd->fd.size / disk->data_size;
967
968         /* Reset seek position */
969         fd->fd.seek_pos = 0;
970
971         /* Insert file handle in list, ordered by inode, ascending. */
972         FOREACH_NODE(n, &disk->file_opened_list)
973         {
974                 BattFs *file = containerof(n, BattFs, link);
975                 if (file->inode >= inode)
976                         break;
977         }
978         INSERT_BEFORE(&fd->link, n);
979
980         /* Fill in data */
981         fd->inode = inode;
982         fd->mode = mode;
983         fd->disk = disk;
984
985         fd->fd.close = battfs_fileclose;
986         fd->fd.flush = battfs_flush;
987         fd->fd.read = battfs_read;
988         fd->fd.reopen = kfile_genericReopen;
989         fd->fd.seek = kfile_genericSeek;
990         fd->fd.write = battfs_write;
991
992         fd->fd.error = battfs_error;
993         fd->fd.clearerr = battfs_clearerr;
994
995         DB(fd->fd._type = KFT_BATTFS);
996
997         return true;
998 }
999
1000
1001 /**
1002  * Umount \a disk.
1003  */
1004 bool battfs_umount(struct BattFsSuper *disk)
1005 {
1006         Node *n;
1007         int res = 0;
1008
1009         /* Close all open files */
1010         FOREACH_NODE(n, &disk->file_opened_list)
1011         {
1012                 BattFs *file = containerof(n, BattFs, link);
1013                 res += battfs_fileclose(&file->fd);
1014         }
1015
1016         /* Close disk */
1017         return disk->close(disk) && (res == 0);
1018 }
1019
1020 #if UNIT_TEST
1021
1022 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
1023 {
1024         BattFsPageHeader hdr;
1025
1026         /* Reset page to all 0xff */
1027         uint8_t buf[disk->page_size];
1028         memset(buf, 0xFF, disk->page_size);
1029         disk->bufferWrite(disk, 0, buf, disk->page_size);
1030
1031         hdr.inode = inode;
1032         hdr.fill = fill;
1033         hdr.pgoff = pgoff;
1034         hdr.seq = seq;
1035         hdr.fcs = computeFcs(&hdr);
1036
1037         if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
1038         {
1039                 LOG_ERR("error writing hdr\n");
1040                 return false;
1041         }
1042
1043         return true;
1044 }
1045 #endif