Disk size is computed by driver.
[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 == 13);
57         buf[0] = hdr->inode;
58
59         buf[1] = hdr->seq;
60
61         buf[2] = hdr->fill;
62         buf[3] = hdr->fill >> 8;
63
64         buf[4] = hdr->pgoff;
65         buf[5] = hdr->pgoff >> 8;
66
67         /*
68          * Mark is at least 1 bit longer than page address.
69          * Needed to take care of wraparonds.
70          */
71         buf[6] = hdr->mark;
72         buf[7] = hdr->mark >> 8;
73         buf[8] = hdr->mark >> 16;
74
75         /*
76          * This field must be the before the last one!
77          */
78         buf[9] = hdr->fcs_free;
79         buf[10] = hdr->fcs_free >> 8;
80
81         /*
82          * This field must be the last one!
83          * This is needed because if the page is only partially
84          * written, we can use this to detect it.
85          */
86         buf[11] = hdr->fcs;
87         buf[12] = hdr->fcs >> 8;
88 }
89
90 /**
91  * Convert from disk structure to memory representation.
92  * \note filesystem is in little-endian format.
93  */
94 INLINE void disk_to_battfs(uint8_t *buf, struct BattFsPageHeader *hdr)
95 {
96         STATIC_ASSERT(BATTFS_HEADER_LEN == 13);
97         hdr->inode = buf[0];
98         hdr->seq = buf[1];
99         hdr->fill = buf[3] << 8 | buf[2];
100         hdr->pgoff = buf[5] << 8 | buf[4];
101         hdr->mark = (mark_t)buf[8] << 16 | buf[7] << 8 | buf[6];
102         hdr->fcs_free = buf[10] << 8 | buf[9];
103         hdr->fcs = buf[12] << 8 | buf[11];
104 }
105
106 /**
107  * Compute the fcs of the header.
108  */
109 static fcs_t computeFcs(struct BattFsPageHeader *hdr)
110 {
111         uint8_t buf[BATTFS_HEADER_LEN];
112         fcs_t cks;
113
114         battfs_to_disk(hdr, buf);
115         rotating_init(&cks);
116         /* fcs is at the end of whole header */
117         rotating_update(buf,BATTFS_HEADER_LEN - sizeof(fcs_t), &cks);
118         return cks;
119 }
120
121 /**
122  * Compute the fcs of the header marked as free.
123  */
124 static fcs_t computeFcsFree(struct BattFsPageHeader *hdr)
125 {
126         uint8_t buf[BATTFS_HEADER_LEN];
127         fcs_t cks;
128
129         battfs_to_disk(hdr, buf);
130         rotating_init(&cks);
131         /* fcs_free is just before fcs of whole header */
132         rotating_update(buf,BATTFS_HEADER_LEN - 2 * sizeof(fcs_t), &cks);
133         return cks;
134 }
135
136
137 /**
138  * Read header of page \a page.
139  * \return true on success, false otherwise.
140  * \note \a hdr is dirtyed even on errors.
141  */
142 static bool battfs_readHeader(struct BattFsSuper *disk, pgcnt_t page, struct BattFsPageHeader *hdr)
143 {
144         uint8_t buf[BATTFS_HEADER_LEN];
145         /*
146          * Read header from disk.
147          * header is actually a footer, and so
148          * resides at page end.
149          */
150         if (disk->read(disk, page, disk->page_size - BATTFS_HEADER_LEN - 1, buf, BATTFS_HEADER_LEN)
151             != BATTFS_HEADER_LEN)
152         {
153                 TRACEMSG("Error: page[%d]\n", page);
154                 return false;
155         }
156
157         /* Fill header */
158         disk_to_battfs(buf, hdr);
159
160         return true;
161 }
162
163 /**
164  * Count the number of pages from
165  * inode 0 to \a inode in \a filelen_table.
166  */
167 static pgcnt_t countPages(pgoff_t *filelen_table, inode_t inode)
168 {
169         pgcnt_t cnt = 0;
170
171         for (inode_t i = 0; i < inode; i++)
172                 cnt += filelen_table[i];
173
174         return cnt;
175 }
176
177 /**
178  * Move all pages in page allocation array from \a src to \a src + \a offset.
179  * The number of pages moved is page_count - MAX(dst, src).
180  */
181 static void movePages(struct BattFsSuper *disk, pgcnt_t src, int offset)
182 {
183         pgcnt_t dst = src + offset;
184         memmove(&disk->page_array[dst], &disk->page_array[src], disk->page_count - MAX(dst, src) * sizeof(pgcnt_t));
185         
186         if (offset < 0)
187         {
188                 /* Fill empty space in array with sentinel */
189                 for (pgcnt_t page = disk->page_count + offset; page < disk->page_count; page++)
190                         disk->page_array[page] = PAGE_UNSET_SENTINEL;
191         }
192 }
193
194 /**
195  * Insert \a page into page allocation array of \a disk, using \a filelen_table and
196  * \a free_number to compute position.
197  */
198 static void insertFreePage(struct BattFsSuper *disk, pgoff_t *filelen_table, mark_t mark, pgcnt_t page)
199 {
200         ASSERT(mark >= disk->free_min);
201         ASSERT(mark <= disk->free_max);
202
203         pgcnt_t free_pos = countPages(filelen_table, BATTFS_MAX_FILES - 1);
204         free_pos += mark - disk->free_min;
205         TRACEMSG("mark:%d, page:%d, free_min:%d, free_max:%d, free_pos:%d\n",
206                 mark, page, disk->free_min, disk->free_max, free_pos);
207
208         ASSERT(disk->page_array[free_pos] == PAGE_UNSET_SENTINEL);
209         disk->page_array[free_pos] = page;
210 }
211
212 /**
213  * Mark \a page of \a disk as free.
214  * \note free_max of \a disk is increased by 1 and is used as
215  *       \a page free marker.
216  */
217 static bool battfs_markFree(struct BattFsSuper *disk, struct BattFsPageHeader *hdr, pgcnt_t page)
218 {
219         uint8_t buf[BATTFS_HEADER_LEN];
220
221         hdr->mark = disk->free_max++;
222         hdr->fcs_free = computeFcsFree(hdr);
223         battfs_to_disk(hdr, buf);
224
225         if (!disk->write(disk, page, disk->page_size - BATTFS_HEADER_LEN - 1, buf, BATTFS_HEADER_LEN))
226         {
227                 TRACEMSG("error marking page [%d]\n", page);
228                 return false;
229         }
230         else
231                 return true;
232 }
233
234
235 /**
236  * Initialize and mount disk described by
237  * \a d.
238  * \return false on errors, true otherwise.
239  */
240 bool battfs_init(struct BattFsSuper *disk)
241 {
242         BattFsPageHeader hdr;
243         pgoff_t filelen_table[BATTFS_MAX_FILES];
244         mark_t minl, maxl, minh, maxh;
245
246         /* Sanity checks */
247         ASSERT(disk->open);
248         ASSERT(disk->read);
249         ASSERT(disk->write);
250         ASSERT(disk->erase);
251         ASSERT(disk->close);
252         ASSERT(disk->page_size);
253         ASSERT(disk->page_count);
254         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
255         ASSERT(disk->page_array);
256         
257         /* Init disk device */
258         if (!disk->open(disk))
259         {
260                 TRACEMSG("open error\n");
261                 return false;
262         }
263
264         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
265
266         /* Initialize min and max counters to keep trace od fre blocks */
267         minl = MAX_PAGE_ADDR;
268         maxl = 0;
269         minh = MAX_PAGE_ADDR | MARK_HALF_SIZE;
270         maxh = 0 | MARK_HALF_SIZE;
271
272         disk->free_bytes =0;
273         disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
274
275         /* Count the number of disk page per file */
276         for (pgcnt_t page = 0; page < disk->page_count; page++)
277         {
278                 if (!battfs_readHeader(disk, page, &hdr))
279                         return false;
280
281                 /* Check header FCS */
282                 if (hdr.fcs == computeFcs(&hdr))
283                 {
284                         /* Page is valid and is owned by a file */
285                         filelen_table[hdr.inode]++;
286
287                         ASSERT(hdr.mark == MARK_PAGE_VALID);
288                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
289                         ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
290                         /* Keep trace of free space */
291                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN - hdr.fill;
292                 }
293                 else
294                 {
295                         /* Increase free space */
296                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
297                         
298                         /* Check if page is free */
299                         if (hdr.fcs_free == computeFcsFree(&hdr))
300                         {
301                                 /*
302                                  * This page is a valid and marked free page.
303                                  * Update min and max free page markers.
304                                  */
305                                 if (hdr.mark < MARK_HALF_SIZE)
306                                 {
307                                         minl = MIN(minl, hdr.mark);
308                                         maxl = MAX(maxl, hdr.mark);
309                                 }
310                                 else
311                                 {
312                                         minh = MIN(minh, hdr.mark);
313                                         maxl = MAX(maxl, hdr.mark);
314                                 }
315                         }
316                         else
317                                 TRACEMSG("page [%d] invalid, keeping as free\n", page);
318                 }
319         }
320
321         /* Once here, we have filelen_table filled with file lengths */
322
323         /* Fill page array with sentinel */
324         for (pgcnt_t page = 0; page < disk->page_count; page++)
325                 disk->page_array[page] = PAGE_UNSET_SENTINEL;
326
327         /* Determine free_min & free_max */
328         if (maxl >= minl)
329         {
330                 if (maxh >= minh)
331                 {
332                         if (maxl == minh - 1)
333                         {
334                                 disk->free_min = minl;
335                                 disk->free_max = maxh;
336                         }
337                         else
338                         {
339                                 ASSERT(minl == 0);
340                                 ASSERT(maxh == (MAX_PAGE_ADDR | MARK_HALF_SIZE));
341
342                                 disk->free_min = minh;
343                                 disk->free_max = maxl;
344                         }
345                 }
346                 else
347                 {
348                         disk->free_min = minl;
349                         disk->free_max = maxl;
350                 }
351         }
352         else if (maxh >= minh)
353         {
354                 disk->free_min = minh;
355                 disk->free_max = maxh;
356         }
357         else
358         {
359                 TRACEMSG("No valid marked free block found\n");
360                 disk->free_min = 0;
361                 #warning Check this!
362                 disk->free_max = -1;
363         }
364         TRACEMSG("Free markers:\n minl %u\n maxl %u\n minh %u\n maxh %u\n free_min %u\n free_max %u\n",
365                 minl, maxl, minh, maxh, disk->free_min, disk->free_max);
366
367
368         /* Fill page allocation array */
369         for (pgcnt_t page = 0; page < disk->page_count; page++)
370         {
371                 if (!battfs_readHeader(disk, page, &hdr))
372                         return false;
373
374                 /* Check header FCS */
375                 if (hdr.fcs == computeFcs(&hdr))
376                 {
377                         /* Page is valid and is owned by a file */
378                         ASSERT(hdr.mark == MARK_PAGE_VALID);
379                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
380
381                         /* Compute array position */
382                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
383                         array_pos += hdr.pgoff;
384
385                         /* Check if position is already used by another page of the same file */
386                         if (LIKELY(disk->page_array[array_pos] == PAGE_UNSET_SENTINEL))
387                                 disk->page_array[array_pos] = page;
388                         else
389                         {
390                                 BattFsPageHeader hdr_old;
391                                 
392                                 if (!battfs_readHeader(disk, disk->page_array[array_pos], &hdr_old))
393                                         return false;
394
395                                 /* Check header FCS */
396                                 ASSERT(hdr_old.fcs == computeFcs(&hdr_old));
397
398                                 /* Only the very same page with a different seq number can be here */
399                                 ASSERT(hdr.inode == hdr_old.inode);
400                                 ASSERT(hdr.pgoff == hdr_old.pgoff);
401                                 ASSERT(hdr.mark == hdr_old.mark);
402                                 ASSERT(hdr.fcs_free == hdr_old.fcs_free);
403                                 ASSERT(hdr.seq != hdr_old.seq);
404
405                                 pgcnt_t new_page, old_page;
406                                 fill_t old_fill;
407
408                                 /* Fancy check to handle seq wraparound */
409                                 #define HALF_SEQ (1 << ((sizeof(seq_t) * CPU_BITS_PER_CHAR) - 1))
410                                 if ((hdr.seq - hdr_old.seq) < HALF_SEQ)
411                                 {
412                                         /* Current header is newer than the previuos one */
413                                         old_page = disk->page_array[array_pos];
414                                         new_page = page;
415                                         old_fill = hdr_old.fill;
416                                 }
417                                 else
418                                 {
419                                         /* Previous header is newer than the current one */
420                                         old_page = page;
421                                         new_page = disk->page_array[array_pos];
422                                         old_fill = hdr.fill;
423                                 }
424
425                                 /* Set new page */
426                                 disk->page_array[array_pos] = new_page;
427
428                                 /* Add free space */
429                                 disk->free_bytes += old_fill;
430
431                                 /* Shift all array one position to the left, overwriting duplicate page */
432                                 array_pos -= hdr.pgoff;
433                                 array_pos += filelen_table[hdr.inode];
434                                 movePages(disk, array_pos, -1);
435                                 
436                                 /* Decrease file page count */
437                                 filelen_table[hdr.inode]--;
438
439                                 /* Add old page to free pages pool */
440                                 if (!battfs_markFree(disk, &hdr, old_page))
441                                         return false;
442
443                                 insertFreePage(disk, filelen_table, disk->free_max, old_page);
444                         }
445                 }
446                 else
447                 {
448                         /* Check if page is free */
449                         if (hdr.fcs_free != computeFcsFree(&hdr))
450                                 /* Page is not a valid marked page, insert at the end of list */
451                                 hdr.mark = ++disk->free_max;
452
453                         insertFreePage(disk, filelen_table, hdr.mark, page);
454                 }
455         }
456
457         #warning Test me!       
458         return true;    
459 }
460
461