Refactor battfs_init in 2 separate functions; add some docs.
[bertos.git] / 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  * \version $Id:$
34  *
35  * \author Francesco Sacchi <batt@develer.com>
36  *
37  * \brief BattFS: a filesystem for embedded platforms (implementation).
38  */
39
40 #include "battfs.h"
41
42 #include <cfg/debug.h>
43 #include <cfg/macros.h> /* MIN, MAX */
44 #include <mware/byteorder.h> /* cpu_to_xx */
45
46
47 #include <string.h> /* memset, memmove */
48
49
50 /**
51  * Convert from memory representation to disk structure.
52  * \note filesystem is in little-endian format.
53  */
54 INLINE void battfs_to_disk(struct BattFsPageHeader *hdr, uint8_t *buf)
55 {
56         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
57         buf[0] = hdr->inode;
58
59         buf[1] = hdr->fill;
60         buf[2] = hdr->fill >> 8;
61
62         buf[3] = hdr->pgoff;
63         buf[4] = hdr->pgoff >> 8;
64
65         /*
66          * Mark is at least 1 bit longer than page address.
67          * Needed to take care of wraparonds.
68          */
69         buf[5] = hdr->mark;
70         buf[6] = hdr->mark >> 8;
71
72         /*
73          * First bit used by mark, last 2 bits used by seq.
74          * Since only 2 pages with the same inode and pgoff
75          * can exist at the same time, 2 bit for seq are enough.
76          */
77         buf[7] = ((hdr->mark >> 16) & 0x01) | (hdr->seq << 6);
78
79         /*
80          * This field must be the before the last one!
81          */
82         buf[8] = hdr->fcs_free;
83         buf[9] = hdr->fcs_free >> 8;
84
85         /*
86          * This field must be the last one!
87          * This is needed because if the page is only partially
88          * written, we can use this to detect it.
89          */
90         buf[10] = hdr->fcs;
91         buf[11] = hdr->fcs >> 8;
92 }
93
94 /**
95  * Convert from disk structure to memory representation.
96  * \note filesystem is in little-endian format.
97  */
98 INLINE void disk_to_battfs(uint8_t *buf, struct BattFsPageHeader *hdr)
99 {
100         STATIC_ASSERT(BATTFS_HEADER_LEN == 12);
101         hdr->inode = buf[0];
102         hdr->fill = buf[2] << 8 | buf[1];
103         hdr->pgoff = buf[4] << 8 | buf[3];
104         hdr->mark = (mark_t)(buf[7] & 0x01) << 16 | buf[6] << 8 | buf[5];
105         hdr->seq = buf[7] >> 6;
106         hdr->fcs_free = buf[9] << 8 | buf[8];
107         hdr->fcs = buf[11] << 8 | buf[10];
108 }
109
110 /**
111  * Compute the fcs of the header.
112  */
113 static fcs_t computeFcs(struct BattFsPageHeader *hdr)
114 {
115         uint8_t buf[BATTFS_HEADER_LEN];
116         fcs_t cks;
117
118         battfs_to_disk(hdr, buf);
119         rotating_init(&cks);
120         /* fcs is at the end of whole header */
121         rotating_update(buf, BATTFS_HEADER_LEN - sizeof(fcs_t), &cks);
122         return cks;
123 }
124
125 /**
126  * Compute the fcs of the header marked as free.
127  */
128 static fcs_t computeFcsFree(struct BattFsPageHeader *hdr)
129 {
130         uint8_t buf[BATTFS_HEADER_LEN];
131         fcs_t cks;
132
133         battfs_to_disk(hdr, buf);
134         rotating_init(&cks);
135         /* fcs_free is just before fcs of whole header */
136         rotating_update(buf, BATTFS_HEADER_LEN - 2 * sizeof(fcs_t), &cks);
137         return cks;
138 }
139
140
141 /**
142  * Read header of page \a page.
143  * \return true on success, false otherwise.
144  * \note \a hdr is dirtyed even on errors.
145  */
146 static bool battfs_readHeader(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
147 {
148         uint8_t buf[BATTFS_HEADER_LEN];
149         /*
150          * Read header from disk.
151          * Header is actually a footer, and so
152          * resides at page end.
153          */
154         if (disk->read(disk, page, disk->page_size - BATTFS_HEADER_LEN - 1, buf, BATTFS_HEADER_LEN)
155             != BATTFS_HEADER_LEN)
156         {
157                 TRACEMSG("Error: page[%d]\n", page);
158                 return false;
159         }
160
161         /* Fill header */
162         disk_to_battfs(buf, hdr);
163
164         return true;
165 }
166
167 /**
168  * Count the number of pages from
169  * inode 0 to \a inode in \a filelen_table.
170  */
171 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
172 {
173         pgcnt_t cnt = 0;
174
175         for (inode_t i = 0; i < inode; i++)
176                 cnt += filelen_table[i];
177
178         return cnt;
179 }
180
181 /**
182  * Move all pages in page allocation array from \a src to \a src + \a offset.
183  * The number of pages moved is page_count - MAX(dst, src).
184  */
185 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
186 {
187         pgcnt_t dst = src + offset;
188         memmove(&disk->page_array[dst], &disk->page_array[src], disk->page_count - MAX(dst, src) * sizeof(pgcnt_t));
189         
190         if (offset < 0)
191         {
192                 /* Fill empty space in array with sentinel */
193                 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
194                         disk->page_array[page] = PAGE_UNSET_SENTINEL;
195         }
196 }
197
198 /**
199  * Insert \a page into page allocation array of \a disk,
200  * using  \a mark to compute position.
201  */
202 static void insertFreePage(struct BattFsSuper *disk, mark_t mark, pgcnt_t page)
203 {
204         ASSERT(mark - disk->free_start < disk->free_next - disk->free_start);
205
206         pgcnt_t free_pos = disk->page_count - disk->free_next + mark;
207         ASSERT(free_pos < disk->page_count);
208
209         TRACEMSG("mark:%u, page:%u, free_start:%u, free_next:%u, free_pos:%u\n",
210                 mark, page, disk->free_start, disk->free_next, free_pos);
211
212         ASSERT(disk->page_array[free_pos] == PAGE_UNSET_SENTINEL);
213         disk->page_array[free_pos] = page;
214 }
215
216 /**
217  * Mark \a page of \a disk as free.
218  * \note free_next of \a disk is used as \a page free marker
219  * and is increased by 1.
220  */
221 static bool battfs_markFree(struct BattFsSuper *disk, struct BattFsPageHeader *hdr, pgcnt_t page)
222 {
223         uint8_t buf[BATTFS_HEADER_LEN];
224
225         hdr->mark = disk->free_next;
226         hdr->fcs_free = computeFcsFree(hdr);
227         battfs_to_disk(hdr, buf);
228
229         if (!disk->write(disk, page, disk->page_size - BATTFS_HEADER_LEN - 1, buf, BATTFS_HEADER_LEN))
230         {
231                 TRACEMSG("error marking page [%d]\n", page);
232                 return false;
233         }
234         else
235         {
236                 disk->free_next++;
237                 return true;
238         }
239 }
240
241 /**
242  * Determine free_start and free_next blocks for \a disk
243  * using \a minl, \a maxl, \a minh, \a maxh.
244  *
245  * Mark_t is a type that has at least 1 bit more than
246  * pgaddr_t. So all free blocks can be numbered unsing
247  * at most half numbers of an mark_t type.
248  * The free blocks algorith increments by 1 the disk->free_next
249  * every time a page becomes free. So the free block sequence is
250  * guaranteed to be countiguous.
251  * Only wrap arounds may happen, but due to half size sequence limitation,
252  * there are only 4 possible situations:
253  *
254  * \verbatim
255  *    |------lower half------|-------upper half-------|
256  *
257  * 1) |------minl*****maxl---|------------------------|
258  * 2) |------minl********maxl|minh******maxh----------|
259  * 3) |----------------------|----minh*******maxh-----|
260  * 4) |minl******maxl--------|------------minh****maxh|
261  * \endverbatim
262  *
263  * Situations 1 and 3 are easy to detect, while 2 and 4 require more care.
264  */
265 static void findFreeStartNext(struct BattFsSuper *disk, mark_t minl, mark_t maxl, mark_t minh, mark_t maxh)
266 {
267         /* Determine free_start & free_next */
268         if (maxl >= minl)
269         {
270                 /* Valid interval found in lower half */
271                 if (maxh >= minh)
272                 {
273                         /* Valid interval also found in upper half */
274                         if (maxl == minh - 1)
275                         {
276                                 /* Interval starts in lower half and end in upper */
277                                 disk->free_start = minl;
278                                 disk->free_next = maxh;
279                         }
280                         else
281                         {
282                                 /* Interval starts in upper half and end in lower */
283                                 ASSERT(minl == 0);
284                                 ASSERT(maxh == (MAX_PAGE_ADDR | MARK_HALF_SIZE));
285
286                                 disk->free_start = minh;
287                                 disk->free_next = maxl;
288                         }
289                 }
290                 else
291                 {
292                         /*
293                          * Upper interval is invalid.
294                          * Use lower values.
295                          */
296                         
297                         disk->free_start = minl;
298                         disk->free_next = maxl;
299                 }
300         }
301         else if (maxh >= minh)
302         {
303                 /*
304                  * Lower interval is invalid.
305                  * Use upper values.
306                  */
307                 disk->free_start = minh;
308                 disk->free_next = maxh;
309         }
310         else
311         {
312                 /*
313                  * No valid interval found.
314                  * Hopefully the disk is brand new.
315                  */
316                 TRACEMSG("No valid marked free block found, new disk?\n");
317                 disk->free_start = 0;
318                 disk->free_next = -1; //to be incremented ahead
319         }
320
321         /* free_next should contain the first usable address */
322         disk->free_next++;
323
324         TRACEMSG("Free markers:\n minl %u\n maxl %u\n minh %u\n maxh %u\n free_start %u\n free_next %u\n",
325                 minl, maxl, minh, maxh, disk->free_start, disk->free_next);
326 }
327
328 /**
329  * Count number of pages per file on \a disk.
330  * This information is registered in \a filelen_table.
331  * Array index represent file inode, while value contained
332  * is the number of pages used by that file.
333  *
334  * \return true if ok, false on disk read errors.
335  * \note The whole disk is scanned once.
336  */
337 static bool countDiskFilePages(struct BattFsSuper *disk, pgoff_t *filelen_table)
338 {
339         BattFsPageHeader hdr;
340         mark_t minl, maxl, minh, maxh;
341
342         /* Initialize min and max counters to keep trace od free blocks */
343         minl = MAX_PAGE_ADDR;
344         maxl = 0;
345         minh = MAX_PAGE_ADDR | MARK_HALF_SIZE;
346         maxh = 0 | MARK_HALF_SIZE;
347
348
349         /* Count the number of disk page per file */
350         for (pgcnt_t page = 0; page < disk->page_count; page++)
351         {
352                 if (!battfs_readHeader(disk, page, &hdr))
353                         return false;
354
355                 /* Check header FCS */
356                 if (hdr.fcs == computeFcs(&hdr))
357                 {
358                         ASSERT(hdr.mark == MARK_PAGE_VALID);
359                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
360                         ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
361
362                         /* Page is valid and is owned by a file */
363                         filelen_table[hdr.inode]++;
364
365                         /* Keep trace of free space */
366                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN - hdr.fill;
367                 }
368                 else
369                 {
370                         /* Increase free space */
371                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
372                         
373                         /* Check if page is marked free */
374                         if (hdr.fcs_free == computeFcsFree(&hdr))
375                         {
376                                 /*
377                                  * This page is a valid and marked free page.
378                                  * Update min and max free page markers.
379                                  */
380                                 if (hdr.mark < MARK_HALF_SIZE)
381                                 {
382                                         minl = MIN(minl, hdr.mark);
383                                         maxl = MAX(maxl, hdr.mark);
384                                 }
385                                 else
386                                 {
387                                         minh = MIN(minh, hdr.mark);
388                                         maxh = MAX(maxh, hdr.mark);
389                                 }
390                         }
391                         else
392                                 TRACEMSG("page [%d] invalid, keeping as free\n", page);
393                 }
394         }
395         findFreeStartNext(disk, minl, maxl, minh, maxh);
396         return true;
397 }
398
399 /**
400  * Fill page allocation array of \a disk
401  * using file lenghts in \a filelen_table.
402  *
403  * The page allocation array is an array containings all files info.
404  * Is ordered by file, and within each file is ordered by page offset
405  * inside file.
406  * e.g. : at page array[0] you will find page address of the first page
407  * of the first file (if present).
408  * Free blocks are allocated after the last file starting from invalid ones
409  * and continuing with the marked free ones.
410  *
411  * \return true if ok, false on disk read errors.
412  * \note The whole disk is scanned once.
413  */
414 static bool fillPageArray(struct BattFsSuper *disk, pgoff_t *filelen_table)
415 {
416         BattFsPageHeader hdr;
417         /* Fill page allocation array */
418         for (pgcnt_t page = 0; page < disk->page_count; page++)
419         {
420                 if (!battfs_readHeader(disk, page, &hdr))
421                         return false;
422
423                 /* Check header FCS */
424                 if (hdr.fcs == computeFcs(&hdr))
425                 {
426                         /* Page is valid and is owned by a file */
427                         ASSERT(hdr.mark == MARK_PAGE_VALID);
428                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
429
430                         /* Compute array position */
431                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
432                         array_pos += hdr.pgoff;
433
434                         /* Check if position is already used by another page of the same file */
435                         if (LIKELY(disk->page_array[array_pos] == PAGE_UNSET_SENTINEL))
436                                 disk->page_array[array_pos] = page;
437                         else
438                         {
439                                 BattFsPageHeader hdr_old;
440                                 
441                                 if (!battfs_readHeader(disk, disk->page_array[array_pos], &hdr_old))
442                                         return false;
443
444                                 /* Check header FCS */
445                                 ASSERT(hdr_old.fcs == computeFcs(&hdr_old));
446
447                                 /* Only the very same page with a different seq number can be here */
448                                 ASSERT(hdr.inode == hdr_old.inode);
449                                 ASSERT(hdr.pgoff == hdr_old.pgoff);
450                                 ASSERT(hdr.mark == hdr_old.mark);
451                                 ASSERT(hdr.fcs_free == hdr_old.fcs_free);
452                                 ASSERT(hdr.seq != hdr_old.seq);
453
454                                 pgcnt_t new_page, old_page;
455                                 fill_t old_fill;
456
457                                 /* Fancy check to handle seq wraparound (2 bits only) */
458                                 if (((hdr.seq - hdr_old.seq) & 0x03) < 2)
459                                 {
460                                         /* Current header is newer than the previuos one */
461                                         old_page = disk->page_array[array_pos];
462                                         new_page = page;
463                                         old_fill = hdr_old.fill;
464                                 }
465                                 else
466                                 {
467                                         /* Previous header is newer than the current one */
468                                         old_page = page;
469                                         new_page = disk->page_array[array_pos];
470                                         old_fill = hdr.fill;
471                                 }
472
473                                 /* Set new page */
474                                 disk->page_array[array_pos] = new_page;
475
476                                 /* Add free space */
477                                 disk->free_bytes += old_fill;
478
479                                 /* Shift all array one position to the left, overwriting duplicate page */
480                                 array_pos -= hdr.pgoff;
481                                 array_pos += filelen_table[hdr.inode];
482                                 movePages(disk, array_pos, -1);
483                                 
484                                 /* Decrease file page count */
485                                 filelen_table[hdr.inode]--;
486
487                                 /* Add old page to free pages pool */
488                                 if (!battfs_markFree(disk, &hdr, old_page))
489                                         return false;
490
491                                 insertFreePage(disk, hdr.mark, old_page);
492                         }
493                 }
494                 else
495                 {
496                         /* Check if page is free */
497                         if (hdr.fcs_free != computeFcsFree(&hdr))
498                                 /* Page is not a valid marked page, insert at list beginning */
499                                 hdr.mark = --disk->free_start;
500
501                         insertFreePage(disk, hdr.mark, page);
502                 }
503         }
504         return true;
505 }
506
507 /**
508  * Initialize and mount disk described by
509  * \a disk.
510  * \return false on errors, true otherwise.
511  */
512 bool battfs_init(struct BattFsSuper *disk)
513 {
514         pgoff_t filelen_table[BATTFS_MAX_FILES];
515
516         /* Sanity check */
517         ASSERT(disk->open);
518
519         /* Init disk device */
520         if (!disk->open(disk))
521         {
522                 TRACEMSG("open error\n");
523                 return false;
524         }
525
526         /* Disk open must set all of these */
527         ASSERT(disk->read);
528         ASSERT(disk->write);
529         ASSERT(disk->erase);
530         ASSERT(disk->close);
531         ASSERT(disk->page_size);
532         ASSERT(disk->page_count);
533         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
534         ASSERT(disk->page_array);
535
536         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
537
538         disk->free_bytes = 0;
539         disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
540
541         /* Count pages per file */
542         if (!countDiskFilePages(disk, filelen_table))
543         {
544                 TRACEMSG("error counting file pages\n");
545                 return false;
546         }
547
548         /* Once here, we have filelen_table filled with file lengths */
549
550         /* Fill page array with sentinel */
551         for (pgcnt_t page = 0; page < disk->page_count; page++)
552                 disk->page_array[page] = PAGE_UNSET_SENTINEL;
553
554         /* Fill page allocation array using filelen_table */
555         if (!fillPageArray(disk, filelen_table))
556         {
557                 TRACEMSG("error filling page array\n");
558                 return false;
559         }
560
561         return true;    
562 }
563
564