Change free_min to free_start and free_max to free_next; cosmetic fixes.
[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_start);
201         ASSERT(mark < disk->free_next);
202
203         pgcnt_t free_pos = countPages(filelen_table, BATTFS_MAX_FILES - 1);
204         free_pos += mark - disk->free_start;
205         TRACEMSG("mark:%d, page:%d, free_start:%d, free_next:%d, free_pos:%d\n",
206                 mark, page, disk->free_start, disk->free_next, 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_next of \a disk is used as \a page free marker
215  * and is increased by 1.
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_next;
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         {
232                 disk->free_next++;
233                 return true;
234         }
235 }
236
237
238 /**
239  * Initialize and mount disk described by
240  * \a d.
241  * \return false on errors, true otherwise.
242  */
243 bool battfs_init(struct BattFsSuper *disk)
244 {
245         BattFsPageHeader hdr;
246         pgoff_t filelen_table[BATTFS_MAX_FILES];
247         mark_t minl, maxl, minh, maxh;
248
249         /* Sanity check */
250         ASSERT(disk->open);
251
252         /* Init disk device */
253         if (!disk->open(disk))
254         {
255                 TRACEMSG("open error\n");
256                 return false;
257         }
258
259         /* Disk open must set all of these */
260         ASSERT(disk->read);
261         ASSERT(disk->write);
262         ASSERT(disk->erase);
263         ASSERT(disk->close);
264         ASSERT(disk->page_size);
265         ASSERT(disk->page_count);
266         ASSERT(disk->page_count < PAGE_UNSET_SENTINEL - 1);
267         ASSERT(disk->page_array);
268
269         memset(filelen_table, 0, BATTFS_MAX_FILES * sizeof(pgoff_t));
270
271         /* Initialize min and max counters to keep trace od free blocks */
272         minl = MAX_PAGE_ADDR;
273         maxl = 0;
274         minh = MAX_PAGE_ADDR | MARK_HALF_SIZE;
275         maxh = 0 | MARK_HALF_SIZE;
276
277         disk->free_bytes = 0;
278         disk->disk_size = (disk_size_t)(disk->page_size - BATTFS_HEADER_LEN) * disk->page_count;
279
280         /* Count the number of disk page per file */
281         for (pgcnt_t page = 0; page < disk->page_count; page++)
282         {
283                 if (!battfs_readHeader(disk, page, &hdr))
284                         return false;
285
286                 /* Check header FCS */
287                 if (hdr.fcs == computeFcs(&hdr))
288                 {
289                         ASSERT(hdr.mark == MARK_PAGE_VALID);
290                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
291                         ASSERT(hdr.fill <= disk->page_size - BATTFS_HEADER_LEN);
292
293                         /* Page is valid and is owned by a file */
294                         filelen_table[hdr.inode]++;
295
296                         /* Keep trace of free space */
297                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN - hdr.fill;
298                 }
299                 else
300                 {
301                         /* Increase free space */
302                         disk->free_bytes += disk->page_size - BATTFS_HEADER_LEN;
303                         
304                         /* Check if page is marked free */
305                         if (hdr.fcs_free == computeFcsFree(&hdr))
306                         {
307                                 /*
308                                  * This page is a valid and marked free page.
309                                  * Update min and max free page markers.
310                                  */
311                                 if (hdr.mark < MARK_HALF_SIZE)
312                                 {
313                                         minl = MIN(minl, hdr.mark);
314                                         maxl = MAX(maxl, hdr.mark);
315                                 }
316                                 else
317                                 {
318                                         minh = MIN(minh, hdr.mark);
319                                         maxl = MAX(maxl, hdr.mark);
320                                 }
321                         }
322                         else
323                                 TRACEMSG("page [%d] invalid, keeping as free\n", page);
324                 }
325         }
326
327         /* Once here, we have filelen_table filled with file lengths */
328
329         /* Fill page array with sentinel */
330         for (pgcnt_t page = 0; page < disk->page_count; page++)
331                 disk->page_array[page] = PAGE_UNSET_SENTINEL;
332
333         /* Determine free_start & free_next */
334         if (maxl >= minl)
335         {
336                 if (maxh >= minh)
337                 {
338                         if (maxl == minh - 1)
339                         {
340                                 disk->free_start = minl;
341                                 disk->free_next = maxh;
342                         }
343                         else
344                         {
345                                 ASSERT(minl == 0);
346                                 ASSERT(maxh == (MAX_PAGE_ADDR | MARK_HALF_SIZE));
347
348                                 disk->free_start = minh;
349                                 disk->free_next = maxl;
350                         }
351                 }
352                 else
353                 {
354                         disk->free_start = minl;
355                         disk->free_next = maxl;
356                 }
357         }
358         else if (maxh >= minh)
359         {
360                 disk->free_start = minh;
361                 disk->free_next = maxh;
362         }
363         else
364         {
365                 TRACEMSG("No valid marked free block found\n");
366                 disk->free_start = 0;
367                 disk->free_next = -1;
368         }
369
370         /* free_next should contain the first usable address */
371         disk->free_next++;
372
373         TRACEMSG("Free markers:\n minl %u\n maxl %u\n minh %u\n maxh %u\n free_start %u\n free_next %u\n",
374                 minl, maxl, minh, maxh, disk->free_start, disk->free_next);
375
376
377         /* Fill page allocation array */
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                         /* Page is valid and is owned by a file */
387                         ASSERT(hdr.mark == MARK_PAGE_VALID);
388                         ASSERT(hdr.fcs_free == FCS_FREE_VALID);
389
390                         /* Compute array position */
391                         pgcnt_t array_pos = countPages(filelen_table, hdr.inode);
392                         array_pos += hdr.pgoff;
393
394                         /* Check if position is already used by another page of the same file */
395                         if (LIKELY(disk->page_array[array_pos] == PAGE_UNSET_SENTINEL))
396                                 disk->page_array[array_pos] = page;
397                         else
398                         {
399                                 BattFsPageHeader hdr_old;
400                                 
401                                 if (!battfs_readHeader(disk, disk->page_array[array_pos], &hdr_old))
402                                         return false;
403
404                                 /* Check header FCS */
405                                 ASSERT(hdr_old.fcs == computeFcs(&hdr_old));
406
407                                 /* Only the very same page with a different seq number can be here */
408                                 ASSERT(hdr.inode == hdr_old.inode);
409                                 ASSERT(hdr.pgoff == hdr_old.pgoff);
410                                 ASSERT(hdr.mark == hdr_old.mark);
411                                 ASSERT(hdr.fcs_free == hdr_old.fcs_free);
412                                 ASSERT(hdr.seq != hdr_old.seq);
413
414                                 pgcnt_t new_page, old_page;
415                                 fill_t old_fill;
416
417                                 /* Fancy check to handle seq wraparound */
418                                 #define HALF_SEQ (1 << ((sizeof(seq_t) * CPU_BITS_PER_CHAR) - 1))
419                                 if ((hdr.seq - hdr_old.seq) < HALF_SEQ)
420                                 {
421                                         /* Current header is newer than the previuos one */
422                                         old_page = disk->page_array[array_pos];
423                                         new_page = page;
424                                         old_fill = hdr_old.fill;
425                                 }
426                                 else
427                                 {
428                                         /* Previous header is newer than the current one */
429                                         old_page = page;
430                                         new_page = disk->page_array[array_pos];
431                                         old_fill = hdr.fill;
432                                 }
433
434                                 /* Set new page */
435                                 disk->page_array[array_pos] = new_page;
436
437                                 /* Add free space */
438                                 disk->free_bytes += old_fill;
439
440                                 /* Shift all array one position to the left, overwriting duplicate page */
441                                 array_pos -= hdr.pgoff;
442                                 array_pos += filelen_table[hdr.inode];
443                                 movePages(disk, array_pos, -1);
444                                 
445                                 /* Decrease file page count */
446                                 filelen_table[hdr.inode]--;
447
448                                 /* Add old page to free pages pool */
449                                 if (!battfs_markFree(disk, &hdr, old_page))
450                                         return false;
451
452                                 insertFreePage(disk, filelen_table, hdr.mark, old_page);
453                         }
454                 }
455                 else
456                 {
457                         /* Check if page is free */
458                         if (hdr.fcs_free != computeFcsFree(&hdr))
459                                 /* Page is not a valid marked page, insert at the end of list */
460                                 hdr.mark = disk->free_next++;
461
462                         insertFreePage(disk, filelen_table, hdr.mark, page);
463                 }
464         }
465
466         #warning Test me!       
467         return true;    
468 }
469
470