Add some debug features.
[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->page_size - BATTFS_HEADER_LEN, 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->page_size - BATTFS_HEADER_LEN, 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 /**
199  * Count the number of pages from
200  * inode 0 to \a inode in \a filelen_table.
201  */
202 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
203 {
204         pgcnt_t cnt = 0;
205
206         for (inode_t i = 0; i < inode; i++)
207                 cnt += filelen_table[i];
208
209         return cnt;
210 }
211
212 /**
213  * Move all pages in page allocation array from \a src to \a src + \a offset.
214  * The number of pages moved is page_count - MAX(dst, src).
215  */
216 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
217 {
218         pgcnt_t dst = src + offset;
219         LOG_INFO("src %d, offset %d, size %ld\n", src, offset, (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
220         memmove(&disk->page_array[dst], &disk->page_array[src], (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
221
222         if (offset < 0)
223         {
224                 /* Fill empty space in array with sentinel */
225                 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
226                         disk->page_array[page] = PAGE_UNSET_SENTINEL;
227         }
228 }
229
230 /**
231  * Count number of pages per file on \a disk.
232  * This information is registered in \a filelen_table.
233  * Array index represent file inode, while value contained
234  * is the number of pages used by that file.
235  *
236  * \return true if ok, false on disk read errors.
237  * \note The whole disk is scanned once.
238  */
239 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
240 {
241         BattFsPageHeader hdr;
242         disk->free_page_start = 0;
243
244         /* Count the number of disk page per file */
245         for (pgcnt_t page = 0; page < disk->page_count; page++)
246         {
247                 if (!readHdr(disk, page, &hdr))
248                         return false;
249
250                 /* Increase free space */
251                 disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
252
253                 /* Check header FCS */
254                 if (hdr.fcs == computeFcs(&hdr))
255                 {
256                         ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
257
258                         /* Page is valid and is owned by a file */
259                         filelen_table[hdr.inode]++;
260
261                         /* Keep trace of free space */
262                         disk->free_bytes -= hdr.fill;
263                         disk->free_page_start++;
264                 }
265         }
266         LOG_INFO("free_bytes:%d, free_page_start:%d\n", disk->free_bytes, disk->free_page_start);
267
268         return true;
269 }
270
271 /**
272  * Fill page allocation array of \a disk
273  * using file lenghts in \a filelen_table.
274  *
275  * The page allocation array is an array containings all file infos.
276  * Is ordered by file, and within each file is ordered by page offset
277  * inside file.
278  * e.g. : at page array[0] you will find page address of the first page
279  * of the first file (if present).
280  * Free blocks are allocated after the last file.
281  *
282  * \return true if ok, false on disk read errors.
283  * \note The whole disk is scanned at max twice.
284  */
285 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
286 {
287         BattFsPageHeader hdr;
288         pgcnt_t curr_free_page = disk->free_page_start;
289         /* Fill page allocation array */
290         for (pgcnt_t page = 0; page < disk->page_count; page++)
291         {
292                 if (!readHdr(disk, page, &hdr))
293                         return false;
294
295                 /* Check header FCS */
296                 if (hdr.fcs == computeFcs(&hdr))
297                 {
298                         /* Compute array position */
299                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
300                         array_pos += hdr.pgoff;
301
302
303                         /* Check if position is already used by another page of the same file */
304                         if (disk->page_array[array_pos] == PAGE_UNSET_SENTINEL)
305                                 disk->page_array[array_pos] = page;
306                         else
307                         {
308                                 BattFsPageHeader hdr_prv;
309
310                                 if (!readHdr(disk, disk->page_array[array_pos], &hdr_prv))
311                                         return false;
312
313                                 /* Check header FCS */
314                                 ASSERT(hdr_prv.fcs == computeFcs(&hdr_prv));
315
316                                 /* Only the very same page with a different seq number can be here */
317                                 ASSERT(hdr.inode == hdr_prv.inode);
318                                 ASSERT(hdr.pgoff == hdr_prv.pgoff);
319                                 ASSERT(hdr.seq != hdr_prv.seq);
320
321                                 pgcnt_t new_page, old_page;
322                                 fill_t old_fill;
323
324                                 /*
325                                  * Sequence number comparison: since
326                                  * seq is 40 bits wide, it wraps once
327                                  * every 1.1E12 times.
328                                  * The memory will not live enough to
329                                  * see a wraparound, so we can use a simple
330                                  * compare here.
331                                  */
332                                 if (hdr.seq > hdr_prv.seq)
333                                 {
334                                         /* Current header is newer than the previuos one */
335                                         old_page = disk->page_array[array_pos];
336                                         new_page = page;
337                                         old_fill = hdr_prv.fill;
338                                 }
339                                 else
340                                 {
341                                         /* Previous header is newer than the current one */
342                                         old_page = page;
343                                         new_page = disk->page_array[array_pos];
344                                         old_fill = hdr.fill;
345                                 }
346
347                                 /* Set new page */
348                                 disk->page_array[array_pos] = new_page;
349                                 /* Add free space */
350                                 disk->free_bytes += old_fill;
351                                 /* Shift all array one position to the left, overwriting duplicate page */
352                                 array_pos -= hdr.pgoff;
353                                 array_pos += filelen_table[hdr.inode];
354                                 movePages(disk, array_pos, -1);
355                                 /* Move back all indexes */
356                                 filelen_table[hdr.inode]--;
357                                 disk->free_page_start--;
358                                 curr_free_page--;
359                                 /* Set old page as free */
360                                 ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
361                                 disk->page_array[curr_free_page++] = old_page;
362
363                         }
364                 }
365                 else
366                 {
367                         /* Invalid page, keep as free */
368                         ASSERT(disk->page_array[curr_free_page] == PAGE_UNSET_SENTINEL);
369                         LOG_INFO("Page %d invalid, keeping as free\n", page);
370                         disk->page_array[curr_free_page++] = page;
371                 }
372         }
373         return true;
374 }
375
376
377 /**
378  * Flush the current \a disk buffer.
379  * \return true if ok, false on errors.
380  */
381 static bool flushBuffer(struct BattFsSuper *disk)
382 {
383         if (disk->cache_dirty)
384         {
385                 LOG_INFO("Flushing to disk page %d\n", disk->curr_page);
386
387                 if (!(setBufferHdr(disk, &disk->curr_hdr)
388                         && disk->erase(disk, disk->curr_page)
389                         && disk->save(disk, disk->curr_page)))
390                         return false;
391
392                 disk->cache_dirty = false;
393         }
394         return true;
395 }
396
397 /**
398  * Load \a new_page from \a disk in disk page buffer.
399  * If a previuos page is still dirty in the buffer, will be
400  * flushed first.
401  * \return true if ok, false on errors.
402  */
403 static bool loadPage(struct BattFsSuper *disk, pgcnt_t new_page)
404 {
405         if (disk->curr_page == new_page)
406                 return true;
407
408         LOG_INFO("Loading page %d\n", new_page);
409
410         if (!(flushBuffer(disk)
411                 && disk->load(disk, new_page)))
412                 return false;
413
414         disk->curr_page = new_page;
415
416         /* Load current header */
417         if (!readHdr(disk, disk->curr_page, &disk->curr_hdr))
418                 return false;
419
420         return true;
421 }
422
423
424 /**
425  * Initialize and mount disk described by
426  * \a disk.
427  * \return false on errors, true otherwise.
428  */
429 bool battfs_init(struct BattFsSuper *disk)
430 {
431         pgoff_t filelen_table[BATTFS_MAX_FILES];
432
433         /* Sanity check */
434         ASSERT(disk->open);
435
436         /* Init disk device */
437         if (!disk->open(disk))
438         {
439                 LOG_ERR("open error\n");
440                 return false;
441         }
442
443         /* Disk open must set all of these */
444         ASSERT(disk->read);
445         ASSERT(disk->load);
446         ASSERT(disk->bufferWrite);
447         ASSERT(disk->bufferRead);
448         ASSERT(disk->save);
449         ASSERT(disk->erase);
450         ASSERT(disk->close);
451         ASSERT(disk->page_size);
452         ASSERT(disk->page_count);
453         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
454         ASSERT(disk->page_array);
455
456         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
457
458         disk->free_bytes = 0;
459         disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
460
461         /* Initialize page buffer cache */
462         disk->cache_dirty = false;
463         disk->curr_page = 0;
464         disk->load(disk, disk->curr_page);
465         readHdr(disk, disk->curr_page, &disk->curr_hdr);
466
467         /* Count pages per file */
468         if (!countDiskFilePages(disk, filelen_table))
469         {
470                 LOG_ERR("counting file pages\n");
471                 return false;
472         }
473
474         /* Once here, we have filelen_table filled with file lengths */
475
476         /* Fill page array with sentinel */
477         for (pgcnt_t page = 0; page < disk->page_count; page++)
478                 disk->page_array[page] = PAGE_UNSET_SENTINEL;
479
480         /* Fill page allocation array using filelen_table */
481         if (!fillPageArray(disk, filelen_table))
482         {
483                 LOG_ERR("filling page array\n");
484                 return false;
485         }
486         #if LOG_LEVEL > LOG_LVL_INFO
487                 dumpPageArray(disk)
488         #endif
489         #warning TODO: shuffle free blocks
490         //#if LOG_LEVEL > LOG_LVL_INFO
491         //      dumpPageArray(disk)
492         //#endif
493         /* Init list for opened files. */
494         LIST_INIT(&disk->file_opened_list);
495         return true;
496 }
497
498 /**
499  * Flush file \a fd.
500  * \return 0 if ok, EOF on errors.
501  */
502 static int battfs_flush(struct KFile *fd)
503 {
504         BattFs *fdb = BATTFS_CAST(fd);
505
506         if (flushBuffer(fdb->disk))
507                 return 0;
508         else
509                 return EOF;
510 }
511
512 /**
513  * Close file \a fd.
514  * \return 0 if ok, EOF on errors.
515  */
516 static int battfs_fileclose(struct KFile *fd)
517 {
518         BattFs *fdb = BATTFS_CAST(fd);
519
520         battfs_flush(fd);
521         REMOVE(&fdb->link);
522         return 0;
523 }
524
525
526 static bool getNewPage(struct BattFsSuper *disk, pgcnt_t new_pos, inode_t inode, pgoff_t pgoff)
527 {
528         if (disk->free_page_start >= disk->page_count)
529         {
530                 #warning TODO space over!
531                 LOG_INFO("No disk space available\n");
532                 return false;
533         }
534         flushBuffer(disk);
535         LOG_INFO("Getting new page %d, pos %d\n", disk->page_array[disk->free_page_start], new_pos);
536         disk->curr_page = disk->page_array[disk->free_page_start++];
537         memmove(&disk->page_array[new_pos + 1], &disk->page_array[new_pos], (disk->free_page_start - new_pos - 1) * sizeof(pgcnt_t));
538         #warning TODO: move other files!
539         disk->page_array[new_pos] = disk->curr_page;
540         disk->cache_dirty = true;
541
542         disk->curr_hdr.inode = inode;
543         disk->curr_hdr.pgoff =  pgoff;
544         disk->curr_hdr.fill = 0;
545         disk->curr_hdr.seq = 0;
546         return true;
547 }
548
549 /**
550  * Write to file \a fd \a size bytes from \a buf.
551  * \return The number of bytes written.
552  */
553 static size_t battfs_write(struct KFile *fd, const void *_buf, size_t size)
554 {
555         BattFs *fdb = BATTFS_CAST(fd);
556         const uint8_t *buf = (const uint8_t *)_buf;
557
558         size_t total_write = 0;
559         pgoff_t pg_offset;
560         pgaddr_t addr_offset;
561         pgaddr_t wr_len;
562
563         #warning TODO seek_pos > size?
564
565         while (size)
566         {
567                 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
568                 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
569                 wr_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
570
571                 /* Handle write outside EOF */
572                 if (pg_offset > fdb->max_off)
573                 {
574                         if (!getNewPage(fdb->disk, (fdb->disk->page_array - fdb->start) + pg_offset, fdb->inode, pg_offset))
575                                 return total_write;
576                         fdb->max_off = pg_offset;
577                 }
578                 /* Handle cache load of a new page*/
579                 else if (fdb->start[pg_offset] != fdb->disk->curr_page)
580                 {
581                         LOG_INFO("Re-writing page %d to %d\n", fdb->start[pg_offset], fdb->disk->page_array[fdb->disk->free_page_start]);
582                         if (!loadPage(fdb->disk, fdb->start[pg_offset]))
583                         {
584                                 #warning TODO set error?
585                                 return total_write;
586                         }
587
588                         /* Get a free page */
589                         fdb->disk->curr_page = fdb->disk->page_array[fdb->disk->free_page_start];
590                         movePages(fdb->disk, fdb->disk->free_page_start + 1, -1);
591
592                         /* Insert previous page in free blocks list */
593                         LOG_INFO("Setting page %d as free\n", fdb->start[pg_offset]);
594                         fdb->disk->page_array[fdb->disk->page_count - 1] = fdb->start[pg_offset];
595                         /* Assign new page */
596                         fdb->start[pg_offset] = fdb->disk->curr_page;
597                         fdb->disk->curr_hdr.seq++;
598                 }
599
600
601                 LOG_INFO("writing to buffer for page %d, offset %d, size %d\n", fdb->disk->curr_page, addr_offset, wr_len);
602                 if (fdb->disk->bufferWrite(fdb->disk, addr_offset, buf, wr_len) != wr_len)
603                 {
604                         #warning TODO set error?
605                 }
606                 fdb->disk->cache_dirty = true;
607
608                 size -= wr_len;
609                 fd->seek_pos += wr_len;
610                 total_write += wr_len;
611                 buf += wr_len;
612                 fill_t fill_delta = MAX((int32_t)(addr_offset + wr_len) - fdb->disk->curr_hdr.fill, (int32_t)0);
613                 fdb->disk->free_bytes -= fill_delta;
614                 fdb->disk->curr_hdr.fill += fill_delta;
615                 fd->size += fill_delta;
616                 LOG_INFO("free_bytes %d, seek_pos %d, size %d, curr_hdr.fill %d\n", fdb->disk->free_bytes, fd->seek_pos, fd->size, fdb->disk->curr_hdr.fill);
617         }
618         return total_write;
619 }
620
621
622 /**
623  * Read from file \a fd \a size bytes in \a buf.
624  * \return The number of bytes read.
625  */
626 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
627 {
628         BattFs *fdb = BATTFS_CAST(fd);
629         uint8_t *buf = (uint8_t *)_buf;
630
631         size_t total_read = 0;
632         pgoff_t pg_offset;
633         pgaddr_t addr_offset;
634         pgaddr_t read_len;
635
636         size = MIN((kfile_off_t)size, fd->size - fd->seek_pos);
637
638         while (size)
639         {
640                 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
641                 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
642                 read_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
643
644                 /* Read from disk */
645                 if (diskRead(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
646                 {
647                         #warning TODO set error?
648                 }
649
650                 size -= read_len;
651                 fd->seek_pos += read_len;
652                 total_read += read_len;
653                 buf += read_len;
654         }
655         return total_read;
656 }
657
658
659 /**
660  * Search file \a inode in \a disk using a binary search.
661  * \a last is filled with array offset of file start
662  * in disk->page_array if file is found, otherwise
663  * \a last is filled with the correct insert position
664  * for creating a file with the given \a inode.
665  * \return true if file is found, false otherwisr.
666  */
667 static bool findFile(BattFsSuper *disk, inode_t inode, pgcnt_t *last)
668 {
669         BattFsPageHeader hdr;
670         pgcnt_t first = 0, page;
671         *last = disk->free_page_start;
672         fcs_t fcs;
673
674         while (first < *last)
675         {
676                 page = (first + *last) / 2;
677                 LOG_INFO("first %d, last %d, page %d\n", first, *last, page);
678                 if (!readHdr(disk, disk->page_array[page], &hdr))
679                         return false;
680
681                 fcs = computeFcs(&hdr);
682                 if (hdr.fcs == fcs && hdr.inode == inode)
683                 {
684                         *last = page - hdr.pgoff;
685                         return true;
686                 }
687                 else if (hdr.fcs == fcs && hdr.inode < inode)
688                         first = page + 1;
689                 else
690                         *last = page - 1;
691         }
692
693         return false;
694 }
695
696 /**
697  * \return true if file \a inode exists on \a disk, false otherwise.
698  */
699 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
700 {
701         pgcnt_t dummy;
702         return findFile(disk, inode, &dummy);
703 }
704
705 /**
706  * Count size of file \a inode on \a disk, starting at pointer \a start
707  * in disk->page_array. Size is written in \a size.
708  * \return true if all s ok, false on disk read errors.
709  */
710 static file_size_t countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode)
711 {
712         file_size_t size = 0;
713         BattFsPageHeader hdr;
714
715         while (start < &disk->page_array[disk->free_page_start])
716         {
717                 if (!readHdr(disk, *start++, &hdr))
718                         return EOF;
719                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
720                         size += hdr.fill;
721                 else
722                         break;
723         }
724         return size;
725 }
726
727 /**
728  * Open file \a inode from \a disk in \a mode.
729  * File context is stored in \a fd.
730  * \return true if ok, false otherwise.
731  */
732 bool battfs_fileopen(BattFsSuper *disk, BattFs *fd, inode_t inode, filemode_t mode)
733 {
734         Node *n;
735
736         memset(fd, 0, sizeof(*fd));
737
738         /* Search file start point in disk page array */
739         pgcnt_t start_pos;
740         if (!findFile(disk, inode, &start_pos))
741         {
742                 LOG_INFO("file %d not found\n", inode);
743                 if (!(mode & BATTFS_CREATE))
744                         return false;
745                 /* Create the file */
746                 if (!(getNewPage(disk, start_pos, inode, 0)))
747                         return false;
748         }
749         fd->start = &disk->page_array[start_pos];
750         LOG_INFO("Start pos %d\n", start_pos);
751
752         /* Fill file size */
753         if ((fd->fd.size = countFileSize(disk, fd->start, inode)) == EOF)
754                 return false;
755         fd->max_off = fd->fd.size / (disk->page_size - BATTFS_HEADER_LEN);
756
757         /* Reset seek position */
758         fd->fd.seek_pos = 0;
759
760         /* Insert file handle in list, ordered by inode, ascending. */
761         FOREACH_NODE(n, &disk->file_opened_list)
762         {
763                 BattFs *file = containerof(n, BattFs, link);
764                 if (file->inode >= inode)
765                         break;
766         }
767         INSERT_BEFORE(&fd->link, n);
768
769         /* Fill in data */
770         fd->inode = inode;
771         fd->mode = mode;
772         fd->disk = disk;
773
774         fd->fd.close = battfs_fileclose;
775         fd->fd.flush = battfs_flush;
776         fd->fd.read = battfs_read;
777         fd->fd.reopen = kfile_genericReopen;
778         fd->fd.seek = kfile_genericSeek;
779         fd->fd.write = battfs_write;
780
781 #warning TODO battfs_error, battfs_clearerr
782 #if 0
783         fd->fd.error = battfs_error;
784         fd->fd.clearerr = battfs_clearerr;
785 #endif
786
787         DB(fd->fd._type = KFT_BATTFS);
788
789         return true;
790 }
791
792 /**
793  * Close \a disk.
794  */
795 bool battfs_close(struct BattFsSuper *disk)
796 {
797         Node *n;
798         int res = 0;
799
800         /* Close all open files */
801         FOREACH_NODE(n, &disk->file_opened_list)
802         {
803                 BattFs *file = containerof(n, BattFs, link);
804                 res += battfs_fileclose(&file->fd);
805         }
806
807         /* Close disk */
808         return disk->close(disk) && (res == 0);
809 }
810
811 #if UNIT_TEST
812
813 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff)
814 {
815         BattFsPageHeader hdr;
816
817         /* Reset page to all 0xff */
818         uint8_t buf[disk->page_size];
819         memset(buf, 0xFF, disk->page_size);
820         disk->bufferWrite(disk, 0, buf, disk->page_size);
821
822         hdr.inode = inode;
823         hdr.fill = fill;
824         hdr.pgoff = pgoff;
825         hdr.seq = seq;
826         hdr.fcs = computeFcs(&hdr);
827
828         if (!(setBufferHdr(disk, &hdr) && disk->save(disk, page)))
829         {
830                 LOG_ERR("error writing hdr\n");
831                 return false;
832         }
833
834         return true;
835 }
836 #endif