Use new header locations everywhere
[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 #warning TODO:Fix and complete this module.
44
45 #if 0
46 #include <cfg/debug.h>
47 #include <cfg/macros.h> /* MIN, MAX */
48 #include <cpu/byteorder.h> /* cpu_to_xx */
49
50
51 #include <string.h> /* memset, memmove */
52
53
54 /**
55  * Convert from memory representation to disk structure.
56  * \note filesystem is in little-endian format.
57  */
58 INLINE void battfs_to_disk(struct BattFsPageHeader *hdr, uint8_t *buf)
59 {
60         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
61         buf[0] = hdr->inode;
62
63         buf[1] = hdr->fill;
64         buf[2] = hdr->fill >> 8;
65
66         buf[3] = hdr->pgoff;
67         buf[4] = hdr->pgoff >> 8;
68
69         /*
70          * Mark is at least 1 bit longer than page address.
71          * Needed to take care of wraparonds.
72          */
73         buf[5] = hdr->mark;
74         buf[6] = hdr->mark >> 8;
75
76         /*
77          * First bit used by mark, last 2 bits used by seq.
78          * Since only 2 pages with the same inode and pgoff
79          * can exist at the same time, 2 bit for seq are enough.
80          * Unused bits are set to 1.
81          */
82         buf[7] = ((hdr->mark >> 16) & 0x01) | (hdr->seq << 6) | ~(BV(7) | BV(6) | BV(0));
83
84         /*
85          * This field must be the before the last one!
86          */
87         buf[8] = hdr->fcs_free;
88         buf[9] = hdr->fcs_free >> 8;
89
90         /*
91          * This field must be the last one!
92          * This is needed because if the page is only partially
93          * written, we can use this to detect it.
94          */
95         buf[10] = hdr->fcs;
96         buf[11] = hdr->fcs >> 8;
97 }
98
99 /**
100  * Convert from disk structure to memory representation.
101  * \note filesystem is in little-endian format.
102  */
103 INLINE void disk_to_battfs(uint8_t *buf, struct BattFsPageHeader *hdr)
104 {
105         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
106         hdr->inode = buf[0];
107         hdr->fill = buf[2] << 8 | buf[1];
108         hdr->pgoff = buf[4] << 8 | buf[3];
109         hdr->mark = (mark_t)(buf[7] & 0x01) << 16 | buf[6] << 8 | buf[5];
110         hdr->seq = buf[7] >> 6;
111         hdr->fcs_free = buf[9] << 8 | buf[8];
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  * Compute the fcs of the header marked as free.
132  */
133 static fcs_t computeFcsFree(struct BattFsPageHeader *hdr)
134 {
135         uint8_t buf[BATTFS_HEADER_LEN];
136         fcs_t cks;
137
138         battfs_to_disk(hdr, buf);
139         rotating_init(&cks);
140         /* fcs_free is just before fcs of whole header */
141         rotating_update(buf, BATTFS_HEADER_LEN - 2 * sizeof(fcs_t), &cks);
142         return cks;
143 }
144
145
146 /**
147  * Read header of page \a page.
148  * \return true on success, false otherwise.
149  * \note \a hdr is dirtyed even on errors.
150  */
151 static bool battfs_readHeader(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 (disk->read(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
160             != BATTFS_HEADER_LEN)
161         {
162                 TRACEMSG("Error: 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  * Write header of page \a page.
174  * \return true on success, false otherwise.
175  * \note \a hdr is dirtyed even on errors.
176  */
177 static bool battfs_writeHeader(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
178 {
179         uint8_t buf[BATTFS_HEADER_LEN];
180
181         /* Fill buffer */
182         battfs_to_disk(hdr, buf);
183
184         /*
185          * write header to disk.
186          * Header is actually a footer, and so
187          * resides at page end.
188          */
189         if (disk->write(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN)
190             != BATTFS_HEADER_LEN)
191         {
192                 TRACEMSG("Error: page[%d]\n", page);
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         memmove(&disk->page_array[dst], &disk->page_array[src], (disk->page_count - MAX(dst, src)) * sizeof(pgcnt_t));
220
221         if (offset < 0)
222         {
223                 /* Fill empty space in array with sentinel */
224                 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
225                         disk->page_array[page] = PAGE_UNSET_SENTINEL;
226         }
227 }
228
229 /**
230  * Insert \a page into page allocation array of \a disk,
231  * using  \a mark to compute position.
232  */
233 static void insertFreePage(struct BattFsSuper *disk, mark_t mark, pgcnt_t page)
234 {
235         ASSERT(mark - disk->free_start < disk->free_next - disk->free_start);
236
237         pgcnt_t free_pos = disk->page_count - disk->free_next + mark;
238         ASSERT(free_pos < disk->page_count);
239
240         TRACEMSG("mark:%u, page:%u, free_start:%u, free_next:%u, free_pos:%u\n",
241                 mark, page, disk->free_start, disk->free_next, free_pos);
242
243         ASSERT(disk->page_array[free_pos] == PAGE_UNSET_SENTINEL);
244         disk->page_array[free_pos] = page;
245 }
246
247 /**
248  * Mark \a page of \a disk as free.
249  * \note free_next of \a disk is used as \a page free marker
250  * and is increased by 1.
251  */
252 static bool battfs_markFree(struct BattFsSuper *disk, struct BattFsPageHeader *hdr, pgcnt_t page)
253 {
254         uint8_t buf[BATTFS_HEADER_LEN];
255
256         hdr->mark = disk->free_next;
257         hdr->fcs_free = computeFcsFree(hdr);
258         battfs_to_disk(hdr, buf);
259
260         if (!disk->write(disk, page, disk->page_size - BATTFS_HEADER_LEN, buf, BATTFS_HEADER_LEN))
261         {
262                 TRACEMSG("error marking page [%d]\n", page);
263                 return false;
264         }
265         else
266         {
267                 disk->free_next++;
268                 return true;
269         }
270 }
271
272 /**
273  * Determine free_start and free_next blocks for \a disk
274  * using \a minl, \a maxl, \a minh, \a maxh.
275  *
276  * Mark_t is a type that has at least 1 bit more than
277  * pgaddr_t. So all free blocks can be numbered using
278  * at most half numbers of a mark_t type.
279  * The free blocks algorithm increments by 1 the disk->free_next
280  * every time a page becomes free. So the free block sequence is
281  * guaranteed to be countiguous.
282  * Only wrap arounds may happen, but due to half size sequence limitation,
283  * there are only 4 possible situations:
284  *
285  * \verbatim
286  *    |------lower half------|-------upper half-------|
287  *
288  * 1) |------minl*****maxl---|------------------------|
289  * 2) |------minl********maxl|minh******maxh----------|
290  * 3) |----------------------|----minh*******maxh-----|
291  * 4) |minl******maxl--------|------------minh****maxh|
292  * \endverbatim
293  *
294  * Situations 1 and 3 are easy to detect, while 2 and 4 require more care.
295  */
296 static void findFreeStartNext(struct BattFsSuper *disk, mark_t minl, mark_t maxl, mark_t minh, mark_t maxh)
297 {
298         /* Determine free_start & free_next */
299         if (maxl >= minl)
300         {
301                 /* Valid interval found in lower half */
302                 if (maxh >= minh)
303                 {
304                         /* Valid interval also found in upper half */
305                         if (maxl == minh - 1)
306                         {
307                                 /* Interval starts in lower half and ends in upper */
308                                 disk->free_start = minl;
309                                 disk->free_next = maxh;
310                         }
311                         else
312                         {
313                                 /* Interval starts in upper half and ends in lower */
314                                 ASSERT(minl == 0);
315                                 ASSERT(maxh == (MAX_PAGE_ADDR | MARK_HALF_SIZE));
316
317                                 disk->free_start = minh;
318                                 disk->free_next = maxl;
319                         }
320                 }
321                 else
322                 {
323                         /*
324                          * Upper interval is invalid.
325                          * Use lower values.
326                          */
327
328                         disk->free_start = minl;
329                         disk->free_next = maxl;
330                 }
331         }
332         else if (maxh >= minh)
333         {
334                 /*
335                  * Lower interval is invalid.
336                  * Use upper values.
337                  */
338                 disk->free_start = minh;
339                 disk->free_next = maxh;
340         }
341         else
342         {
343                 /*
344                  * No valid interval found.
345                  * Hopefully the disk is brand new (or full).
346                  */
347                 TRACEMSG("No valid marked free block found, new disk or disk full\n");
348                 disk->free_start = 0;
349                 disk->free_next = -1; //to be increased later
350         }
351
352         /* free_next should contain the first usable address */
353         disk->free_next++;
354
355         TRACEMSG("Free markers:\n minl %u\n maxl %u\n minh %u\n maxh %u\n free_start %u\n free_next %u\n",
356                 minl, maxl, minh, maxh, disk->free_start, disk->free_next);
357 }
358
359 /**
360  * Count number of pages per file on \a disk.
361  * This information is registered in \a filelen_table.
362  * Array index represent file inode, while value contained
363  * is the number of pages used by that file.
364  *
365  * \return true if ok, false on disk read errors.
366  * \note The whole disk is scanned once.
367  */
368 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
369 {
370         BattFsPageHeader hdr;
371         mark_t minl, maxl, minh, maxh;
372
373         /* Initialize min and max counters to keep trace od free blocks */
374         minl = MAX_PAGE_ADDR;
375         maxl = 0;
376         minh = MAX_PAGE_ADDR | MARK_HALF_SIZE;
377         maxh = 0 | MARK_HALF_SIZE;
378
379
380         /* Count the number of disk page per file */
381         for (pgcnt_t page = 0; page < disk->page_count; page++)
382         {
383                 if (!battfs_readHeader(disk, page, &hdr))
384                         return false;
385
386                 /* Check header FCS */
387                 if (hdr.fcs == computeFcs(&hdr))
388                 {
389                         ASSERT(hdr.mark == MARK_PAGE_VALID);
390                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
391                         ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
392
393                         /* Page is valid and is owned by a file */
394                         filelen_table[hdr.inode]++;
395
396                         /* Keep trace of free space */
397                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN - hdr.fill;
398                 }
399                 else
400                 {
401                         /* Increase free space */
402                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
403
404                         /* Check if page is marked free */
405                         if (hdr.fcs_free == computeFcsFree(&hdr))
406                         {
407                                 /*
408                                  * This page is a valid and marked free page.
409                                  * Update min and max free page markers.
410                                  */
411                                 if (hdr.mark < MARK_HALF_SIZE)
412                                 {
413                                         minl = MIN(minl, hdr.mark);
414                                         maxl = MAX(maxl, hdr.mark);
415                                 }
416                                 else
417                                 {
418                                         minh = MIN(minh, hdr.mark);
419                                         maxh = MAX(maxh, hdr.mark);
420                                 }
421                         }
422                         else
423                                 TRACEMSG("page [%d] invalid, keeping as free\n", page);
424                 }
425         }
426         findFreeStartNext(disk, minl, maxl, minh, maxh);
427         return true;
428 }
429
430 /**
431  * Fill page allocation array of \a disk
432  * using file lenghts in \a filelen_table.
433  *
434  * The page allocation array is an array containings all file infos.
435  * Is ordered by file, and within each file is ordered by page offset
436  * inside file.
437  * e.g. : at page array[0] you will find page address of the first page
438  * of the first file (if present).
439  * Free blocks are allocated after the last file, starting from invalid ones
440  * and continuing with the marked free ones.
441  *
442  * \return true if ok, false on disk read errors.
443  * \note The whole disk is scanned once.
444  */
445 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
446 {
447         BattFsPageHeader hdr;
448         /* Fill page allocation array */
449         for (pgcnt_t page = 0; page < disk->page_count; page++)
450         {
451                 if (!battfs_readHeader(disk, page, &hdr))
452                         return false;
453
454                 /* Check header FCS */
455                 if (hdr.fcs == computeFcs(&hdr))
456                 {
457                         /* Page is valid and is owned by a file */
458                         ASSERT(hdr.mark == MARK_PAGE_VALID);
459                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
460
461                         /* Compute array position */
462                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
463                         array_pos += hdr.pgoff;
464
465                         /* Check if position is already used by another page of the same file */
466                         if (LIKELY(disk->page_array[array_pos] == PAGE_UNSET_SENTINEL))
467                                 disk->page_array[array_pos] = page;
468                         else
469                         {
470                                 BattFsPageHeader hdr_old;
471
472                                 if (!battfs_readHeader(disk, disk->page_array[array_pos], &hdr_old))
473                                         return false;
474
475                                 /* Check header FCS */
476                                 ASSERT(hdr_old.fcs == computeFcs(&hdr_old));
477
478                                 /* Only the very same page with a different seq number can be here */
479                                 ASSERT(hdr.inode == hdr_old.inode);
480                                 ASSERT(hdr.pgoff == hdr_old.pgoff);
481                                 ASSERT(hdr.mark == hdr_old.mark);
482                                 ASSERT(hdr.fcs_free == hdr_old.fcs_free);
483                                 ASSERT(hdr.seq != hdr_old.seq);
484
485                                 pgcnt_t new_page, old_page;
486                                 fill_t old_fill;
487
488                                 /* Fancy check to handle seq wraparound (2 bits only) */
489                                 if (((hdr.seq - hdr_old.seq) & 0x03) < 2)
490                                 {
491                                         /* Current header is newer than the previuos one */
492                                         old_page = disk->page_array[array_pos];
493                                         new_page = page;
494                                         old_fill = hdr_old.fill;
495                                 }
496                                 else
497                                 {
498                                         /* Previous header is newer than the current one */
499                                         old_page = page;
500                                         new_page = disk->page_array[array_pos];
501                                         old_fill = hdr.fill;
502                                 }
503
504                                 /* Set new page */
505                                 disk->page_array[array_pos] = new_page;
506
507                                 /* Add free space */
508                                 disk->free_bytes += old_fill;
509
510                                 /* Shift all array one position to the left, overwriting duplicate page */
511                                 array_pos -= hdr.pgoff;
512                                 array_pos += filelen_table[hdr.inode];
513                                 movePages(disk, array_pos, -1);
514
515                                 /* Decrease file page count */
516                                 filelen_table[hdr.inode]--;
517
518                                 /* Add old page to free pages pool */
519                                 if (!battfs_markFree(disk, &hdr, old_page))
520                                         return false;
521
522                                 insertFreePage(disk, hdr.mark, old_page);
523                         }
524                 }
525                 else
526                 {
527                         /* Check if page is free */
528                         if (hdr.fcs_free != computeFcsFree(&hdr))
529                                 /* Page is not a valid marked page, insert at list beginning */
530                                 hdr.mark = --disk->free_start;
531
532                         insertFreePage(disk, hdr.mark, page);
533                 }
534         }
535         return true;
536 }
537
538 /**
539  * Initialize and mount disk described by
540  * \a disk.
541  * \return false on errors, true otherwise.
542  */
543 bool battfs_init(struct BattFsSuper *disk)
544 {
545         pgoff_t filelen_table[BATTFS_MAX_FILES];
546
547         /* Sanity check */
548         ASSERT(disk->open);
549
550         /* Init disk device */
551         if (!disk->open(disk))
552         {
553                 TRACEMSG("open error\n");
554                 return false;
555         }
556
557         /* Disk open must set all of these */
558         ASSERT(disk->read);
559         ASSERT(disk->write);
560         ASSERT(disk->erase);
561         ASSERT(disk->close);
562         ASSERT(disk->page_size);
563         ASSERT(disk->page_count);
564         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
565         ASSERT(disk->page_array);
566
567         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
568
569         disk->free_bytes = 0;
570         disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
571
572         /* Count pages per file */
573         if (!countDiskFilePages(disk, filelen_table))
574         {
575                 TRACEMSG("error counting file pages\n");
576                 return false;
577         }
578
579         /* Once here, we have filelen_table filled with file lengths */
580
581         /* Fill page array with sentinel */
582         for (pgcnt_t page = 0; page < disk->page_count; page++)
583                 disk->page_array[page] = PAGE_UNSET_SENTINEL;
584
585         /* Fill page allocation array using filelen_table */
586         if (!fillPageArray(disk, filelen_table))
587         {
588                 TRACEMSG("error filling page array\n");
589                 return false;
590         }
591
592         /* Init list for opened files. */
593         LIST_INIT(&disk->file_opened_list);
594         return true;
595 }
596
597 /**
598  * Flush file \a fd.
599  * \return 0 if ok, EOF on errors.
600  */
601 static int battfs_flush(struct KFile *fd)
602 {
603         (void)fd;
604         #warning TODO
605         return 0;
606 }
607
608 /**
609  * Close file \a fd.
610  * \return 0 if ok, EOF on errors.
611  */
612 static int battfs_fileclose(struct KFile *fd)
613 {
614         BattFS *fdb = BATTFSKFILE(fd);
615
616         battfs_flush(fd);
617         REMOVE(&fdb->link);
618         return 0;
619 }
620
621 /**
622  * Read from file \a fd \a size bytes in \a buf.
623  * \return The number of bytes read.
624  */
625 static size_t battfs_read(struct KFile *fd, void *_buf, size_t size)
626 {
627         BattFS *fdb = BATTFSKFILE(fd);
628         uint8_t *buf = (uint8_t *)_buf;
629
630         size_t total_read = 0;
631         pgoff_t pg_offset;
632         pgaddr_t addr_offset;
633         pgaddr_t read_len;
634
635         size = MIN((kfile_size_t)size, fd->size - fd->seek_pos);
636
637         while (size)
638         {
639                 pg_offset = fd->seek_pos / (fdb->disk->page_size - BATTFS_HEADER_LEN);
640                 addr_offset = fd->seek_pos % (fdb->disk->page_size - BATTFS_HEADER_LEN);
641                 read_len = MIN(size, (size_t)(fdb->disk->page_size - BATTFS_HEADER_LEN - addr_offset));
642
643                 /* Read from disk */
644                 if (fdb->disk->read(fdb->disk, fdb->start[pg_offset], addr_offset, buf, read_len) != read_len)
645                 {
646                         #warning TODO set error?
647                 }
648
649                 size -= read_len;
650                 fd->seek_pos += read_len;
651                 total_read += read_len;
652                 buf += read_len;
653         }
654         return total_read;
655 }
656
657
658 /**
659  * Search file \a inode in \a disk using a binary search.
660  * \return pointer to file start in disk->page_array
661  * if file exists, NULL otherwise.
662  */
663 static pgcnt_t *findFile(BattFsSuper *disk, inode_t inode)
664 {
665         BattFsPageHeader hdr;
666         pgcnt_t first = 0, page, last = disk->page_count -1;
667         fcs_t fcs;
668
669         while (first <= last)
670         {
671                 page = (first + last) / 2;
672
673                 if (!battfs_readHeader(disk, disk->page_array[page], &hdr))
674                         return NULL;
675
676                 fcs = computeFcs(&hdr);
677                 if (hdr.fcs == fcs && hdr.inode == inode)
678                         return (&disk->page_array[page]) - hdr.pgoff;
679                 else if (hdr.fcs == fcs && hdr.inode < inode)
680                         first = page + 1;
681                 else
682                         last = page - 1;
683         }
684
685         return NULL;
686 }
687
688 /**
689  * \return true if file \a inode exists on \a disk, false otherwise.
690  */
691 bool battfs_fileExists(BattFsSuper *disk, inode_t inode)
692 {
693         return findFile(disk, inode) != NULL;
694 }
695
696 /**
697  * Count size of file \a inode on \a disk, starting at pointer \a start
698  * in disk->page_array. Size is written in \a size.
699  * \return true if all s ok, false on disk read errors.
700  */
701 static bool countFileSize(BattFsSuper *disk, pgcnt_t *start, inode_t inode, file_size_t *size)
702 {
703         *size = 0;
704         BattFsPageHeader hdr;
705
706         for (;;)
707         {
708                 if (!battfs_readHeader(disk, *start++, &hdr))
709                         return false;
710                 if (hdr.fcs == computeFcs(&hdr) && hdr.inode == inode)
711                         *size += hdr.fill;
712                 else
713                         return true;
714         }
715 }
716
717 /**
718  * Open file \a inode from \a disk in \a mode.
719  * File context is stored in \a fd.
720  * \return true if ok, false otherwise.
721  */
722 bool battfs_fileopen(BattFsSuper *disk, BattFS *fd, inode_t inode, filemode_t mode)
723 {
724         Node *n;
725
726         memset(fd, 0, sizeof(*fd));
727
728         /* Search file start point in disk page array */
729         fd->start = findFile(disk, inode);
730         if (fd->start == NULL)
731         {
732                 if (!(mode & BATTFS_CREATE))
733                         return false;
734
735                 /* File does not exist, create it */
736                 BattFsPageHeader hdr;
737                 hdr.inode = inode;
738                 hdr.seq = 0;
739                 hdr.fill = 0;
740                 hdr.pgoff = 0;
741                 hdr.mark = MARK_PAGE_VALID;
742                 hdr.fcs_free = FCS_FREE_VALID;
743                 hdr.fcs = computeFcs(&hdr);
744                 #warning TODO: get a free block and write on disk!
745         }
746
747         /* Fill file size */
748         if (!countFileSize(disk, fd->start, inode, &fd->fd.size))
749                 return false;
750
751         /* Reset seek position */
752         fd->fd.seek_pos = 0;
753
754         /* Insert file handle in list, ordered by inode, ascending. */
755         FOREACH_NODE(n, &disk->file_opened_list)
756         {
757                 BattFS *file = containerof(n, BattFS, link);
758                 if (file->inode >= inode)
759                         break;
760         }
761         INSERT_BEFORE(&fd->link, n);
762
763         /* Fill in data */
764         fd->inode = inode;
765         fd->mode = mode;
766         fd->disk = disk;
767
768         fd->fd.close = battfs_fileclose;
769         fd->fd.flush = battfs_flush;
770         fd->fd.read = battfs_read;
771         fd->fd.reopen = kfile_genericReopen;
772         fd->fd.seek = kfile_genericSeek;
773
774 #warning TODO battfs_write, battfs_error, battfs_clearerr
775 #if 0
776         fd->fd.write = battfs_write;
777         fd->fd.error = battfs_error;
778         fd->fd.clearerr = battfs_clearerr;
779 #endif
780
781         DB(fd->fd._type = KFT_BATTFS);
782
783         return true;
784 }
785
786 /**
787  * Close \a disk.
788  */
789 bool battfs_close(struct BattFsSuper *disk)
790 {
791         Node *n;
792         int res = 0;
793
794         /* Close all open files */
795         FOREACH_NODE(n, &disk->file_opened_list)
796         {
797                 BattFS *file = containerof(n, BattFS, link);
798                 res += battfs_fileclose(&file->fd);
799         }
800
801         /* Close disk */
802         return disk->close(disk) && (res == 0);
803 }
804
805
806 bool battfs_writeTestBlock(struct BattFsSuper *disk, pgcnt_t page, inode_t inode, seq_t seq, fill_t fill, pgoff_t pgoff, mark_t mark)
807 {
808         BattFsPageHeader hdr;
809
810         hdr.inode = inode;
811         hdr.seq = seq;
812         hdr.fill = fill;
813         hdr.pgoff = pgoff;
814         hdr.mark = MARK_PAGE_VALID;
815         hdr.fcs_free = FCS_FREE_VALID;
816         hdr.fcs = computeFcs(&hdr);
817         if (mark != MARK_PAGE_VALID)
818         {
819                 hdr.mark = mark;
820                 hdr.fcs_free = computeFcsFree(&hdr);
821         }
822
823         if (!battfs_writeHeader(disk, page, &hdr))
824         {
825                 TRACEMSG("error writing hdr\n");
826                 return false;
827         }
828
829         return true;
830 }
831
832 #endif