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