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