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