Add in some support for journal replay.
[bluesky.git] / bluesky / log.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2010  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 #define _GNU_SOURCE
10 #define _ATFILE_SOURCE
11
12 #include <stdio.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <glib.h>
16 #include <string.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <sys/mman.h>
23
24 #include "bluesky-private.h"
25
26 /* The logging layer for BlueSky.  This is used to write filesystem changes
27  * durably to disk so that they can be recovered in the event of a system
28  * crash. */
29
30 /* The logging layer takes care out writing out a sequence of log records to
31  * disk.  On disk, each record consists of a header, a data payload, and a
32  * footer.  The footer contains a checksum of the record, meant to help with
33  * identifying corrupt log records (we would assume because the log record was
34  * only incompletely written out before a crash, which should only happen for
35  * log records that were not considered committed). */
36
37 // Rough size limit for a log segment.  This is not a firm limit and there are
38 // no absolute guarantees on the size of a log segment.
39 #define LOG_SEGMENT_SIZE (1 << 22)
40
41 #define HEADER_MAGIC 0x676f4c0a
42 #define FOOTER_MAGIC 0x2e435243
43
44 struct log_header {
45     uint32_t magic;             // HEADER_MAGIC
46     uint8_t type;               // Object type + '0'
47     uint32_t offset;            // Starting byte offset of the log header
48     uint32_t size;              // Size of the data item (bytes)
49     uint64_t inum;              // Inode which owns this data, if any
50     BlueSkyCloudID id;          // Object identifier
51 } __attribute__((packed));
52
53 struct log_footer {
54     uint32_t magic;             // FOOTER_MAGIC
55     uint32_t crc;               // Computed from log_header to log_footer.magic
56 } __attribute__((packed));
57
58 static void writebuf(int fd, const char *buf, size_t len)
59 {
60     while (len > 0) {
61         ssize_t written;
62         written = write(fd, buf, len);
63         if (written < 0 && errno == EINTR)
64             continue;
65         g_assert(written >= 0);
66         buf += written;
67         len -= written;
68     }
69 }
70
71 static void log_commit(BlueSkyLog *log)
72 {
73     int batchsize = 0;
74
75     if (log->fd < 0)
76         return;
77
78     fdatasync(log->fd);
79     while (log->committed != NULL) {
80         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log->committed->data;
81         g_mutex_lock(item->lock);
82         bluesky_cloudlog_stats_update(item, -1);
83         item->pending_write &= ~CLOUDLOG_JOURNAL;
84         item->location_flags |= CLOUDLOG_JOURNAL;
85         bluesky_cloudlog_stats_update(item, 1);
86         g_cond_signal(item->cond);
87         g_mutex_unlock(item->lock);
88         log->committed = g_slist_delete_link(log->committed, log->committed);
89         bluesky_cloudlog_unref(item);
90         batchsize++;
91     }
92
93     if (bluesky_verbose && batchsize > 1)
94         g_print("Log batch size: %d\n", batchsize);
95 }
96
97 static gboolean log_open(BlueSkyLog *log)
98 {
99     char logname[64];
100
101     if (log->fd >= 0) {
102         log_commit(log);
103         close(log->fd);
104         log->seq_num++;
105         log->fd = -1;
106     }
107
108     if (log->current_log != NULL) {
109         bluesky_cachefile_unref(log->current_log);
110         log->current_log = NULL;
111     }
112
113     while (log->fd < 0) {
114         g_snprintf(logname, sizeof(logname), "journal-%08d", log->seq_num);
115         log->fd = openat(log->dirfd, logname, O_CREAT|O_WRONLY|O_EXCL, 0600);
116         if (log->fd < 0 && errno == EEXIST) {
117             fprintf(stderr, "Log file %s already exists...\n", logname);
118             log->seq_num++;
119             continue;
120         } else if (log->fd < 0) {
121             fprintf(stderr, "Error opening logfile %s: %m\n", logname);
122             return FALSE;
123         }
124     }
125
126     log->current_log = bluesky_cachefile_lookup(log->fs, -1, log->seq_num);
127     g_assert(log->current_log != NULL);
128     g_mutex_unlock(log->current_log->lock);
129
130     if (ftruncate(log->fd, LOG_SEGMENT_SIZE) < 0) {
131         fprintf(stderr, "Unable to truncate logfile %s: %m\n", logname);
132     }
133     fsync(log->fd);
134     fsync(log->dirfd);
135     return TRUE;
136 }
137
138 /* All log writes (at least for a single log) are made by one thread, so we
139  * don't need to worry about concurrent access to the log file.  Log items to
140  * write are pulled off a queue (and so may be posted by any thread).
141  * fdatasync() is used to ensure the log items are stable on disk.
142  *
143  * The log is broken up into separate files, roughly of size LOG_SEGMENT_SIZE
144  * each.  If a log segment is not currently open (log->fd is negative), a new
145  * one is created.  Log segment filenames are assigned sequentially.
146  *
147  * Log replay ought to be implemented later, and ought to set the initial
148  * sequence number appropriately.
149  */
150 static gpointer log_thread(gpointer d)
151 {
152     BlueSkyLog *log = (BlueSkyLog *)d;
153
154     while (TRUE) {
155         if (log->fd < 0) {
156             if (!log_open(log)) {
157                 return NULL;
158             }
159         }
160
161         BlueSkyCloudLog *item
162             = (BlueSkyCloudLog *)g_async_queue_pop(log->queue);
163         g_mutex_lock(item->lock);
164         g_assert(item->data != NULL);
165
166         /* The item may have already been written to the journal... */
167         if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
168             g_mutex_unlock(item->lock);
169             bluesky_cloudlog_unref(item);
170             g_atomic_int_add(&item->data_lock_count, -1);
171             continue;
172         }
173
174         bluesky_cloudlog_stats_update(item, -1);
175         item->pending_write |= CLOUDLOG_JOURNAL;
176         bluesky_cloudlog_stats_update(item, 1);
177
178         struct log_header header;
179         struct log_footer footer;
180         size_t size = sizeof(header) + sizeof(footer) + item->data->len;
181         off_t offset = 0;
182         if (log->fd >= 0)
183             offset = lseek(log->fd, 0, SEEK_CUR);
184
185         /* Check whether the item would overflow the allocated journal size.
186          * If so, start a new log segment.  We only allow oversized log
187          * segments if they contain a single log entry. */
188         if (offset + size >= LOG_SEGMENT_SIZE && offset > 0) {
189             log_open(log);
190             offset = 0;
191         }
192
193         header.magic = GUINT32_TO_LE(HEADER_MAGIC);
194         header.offset = GUINT32_TO_LE(offset);
195         header.size = GUINT32_TO_LE(item->data->len);
196         header.type = item->type + '0';
197         header.id = item->id;
198         header.inum = GUINT64_TO_LE(item->inum);
199         footer.magic = GUINT32_TO_LE(FOOTER_MAGIC);
200
201         uint32_t crc = BLUESKY_CRC32C_SEED;
202
203         writebuf(log->fd, (const char *)&header, sizeof(header));
204         crc = crc32c(crc, (const char *)&header, sizeof(header));
205
206         writebuf(log->fd, item->data->data, item->data->len);
207         crc = crc32c(crc, item->data->data, item->data->len);
208
209         crc = crc32c(crc, (const char *)&footer,
210                      sizeof(footer) - sizeof(uint32_t));
211         footer.crc = crc32c_finalize(crc);
212         writebuf(log->fd, (const char *)&footer, sizeof(footer));
213
214         item->log_seq = log->seq_num;
215         item->log_offset = offset + sizeof(header);
216         item->log_size = item->data->len;
217
218         offset += sizeof(header) + sizeof(footer) + item->data->len;
219
220         /* Replace the log item's string data with a memory-mapped copy of the
221          * data, now that it has been written to the log file.  (Even if it
222          * isn't yet on disk, it should at least be in the page cache and so
223          * available to memory map.) */
224         bluesky_string_unref(item->data);
225         item->data = NULL;
226         bluesky_cloudlog_fetch(item);
227
228         log->committed  = g_slist_prepend(log->committed, item);
229         g_atomic_int_add(&item->data_lock_count, -1);
230         g_mutex_unlock(item->lock);
231
232         /* Force an if there are no other log items currently waiting to be
233          * written. */
234         if (g_async_queue_length(log->queue) <= 0)
235             log_commit(log);
236     }
237
238     return NULL;
239 }
240
241 BlueSkyLog *bluesky_log_new(const char *log_directory)
242 {
243     BlueSkyLog *log = g_new0(BlueSkyLog, 1);
244
245     log->log_directory = g_strdup(log_directory);
246     log->fd = -1;
247     log->seq_num = 0;
248     log->queue = g_async_queue_new();
249     log->mmap_lock = g_mutex_new();
250     log->mmap_cache = g_hash_table_new(g_str_hash, g_str_equal);
251
252     log->dirfd = open(log->log_directory, O_DIRECTORY);
253     if (log->dirfd < 0) {
254         fprintf(stderr, "Unable to open logging directory: %m\n");
255         return NULL;
256     }
257
258     g_thread_create(log_thread, log, FALSE, NULL);
259
260     return log;
261 }
262
263 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log)
264 {
265     bluesky_cloudlog_ref(item);
266     g_atomic_int_add(&item->data_lock_count, 1);
267     g_async_queue_push(log->queue, item);
268 }
269
270 void bluesky_log_finish_all(GList *log_items)
271 {
272     while (log_items != NULL) {
273         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log_items->data;
274
275         g_mutex_lock(item->lock);
276         while ((item->pending_write & CLOUDLOG_JOURNAL))
277             g_cond_wait(item->cond, item->lock);
278         g_mutex_unlock(item->lock);
279         bluesky_cloudlog_unref(item);
280
281         log_items = g_list_delete_link(log_items, log_items);
282     }
283 }
284
285 /* Memory-map the given log object into memory (read-only) and return a pointer
286  * to it. */
287 static int page_size = 0;
288
289 void bluesky_cachefile_unref(BlueSkyCacheFile *cachefile)
290 {
291     g_atomic_int_add(&cachefile->refcount, -1);
292 }
293
294 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
295                                     BlueSkyCacheFile *cachefile);
296
297 static void cloudlog_fetch_start(BlueSkyCacheFile *cachefile)
298 {
299     g_atomic_int_inc(&cachefile->refcount);
300     cachefile->fetching = TRUE;
301     g_print("Starting fetch of %s from cloud\n", cachefile->filename);
302     BlueSkyStoreAsync *async = bluesky_store_async_new(cachefile->fs->store);
303     async->op = STORE_OP_GET;
304     async->key = g_strdup(cachefile->filename);
305     bluesky_store_async_add_notifier(async,
306                                      (GFunc)cloudlog_fetch_complete,
307                                      cachefile);
308     bluesky_store_async_submit(async);
309     bluesky_store_async_unref(async);
310 }
311
312 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
313                                     BlueSkyCacheFile *cachefile)
314 {
315     g_print("Fetch of %s from cloud complete, status = %d\n",
316             async->key, async->result);
317
318     g_mutex_lock(cachefile->lock);
319     if (async->result >= 0) {
320         char *pathname = g_strdup_printf("%s/%s",
321                                          cachefile->log->log_directory,
322                                          cachefile->filename);
323         if (!g_file_set_contents(pathname, async->data->data, async->data->len,
324                                  NULL))
325             g_print("Error writing out fetched file to cache!\n");
326         g_free(pathname);
327
328         cachefile->fetching = FALSE;
329         cachefile->ready = TRUE;
330     } else {
331         g_print("Error fetching from cloud, retrying...\n");
332         cloudlog_fetch_start(cachefile);
333     }
334
335     bluesky_cachefile_unref(cachefile);
336     g_cond_broadcast(cachefile->cond);
337     g_mutex_unlock(cachefile->lock);
338 }
339
340 /* Find the BlueSkyCacheFile object for the given journal or cloud log segment.
341  * Returns the object in the locked state and with a reference taken. */
342 BlueSkyCacheFile *bluesky_cachefile_lookup(BlueSkyFS *fs,
343                                            int clouddir, int log_seq)
344 {
345     if (page_size == 0) {
346         page_size = getpagesize();
347     }
348
349     BlueSkyLog *log = fs->log;
350
351     struct stat statbuf;
352     char logname[64];
353     int type;
354
355     // A request for a local log file
356     if (clouddir < 0) {
357         sprintf(logname, "journal-%08d", log_seq);
358         type = CLOUDLOG_JOURNAL;
359     } else {
360         sprintf(logname, "log-%08d-%08d", clouddir, log_seq);
361         type = CLOUDLOG_CLOUD;
362     }
363
364     BlueSkyCacheFile *map;
365     g_mutex_lock(log->mmap_lock);
366     map = g_hash_table_lookup(log->mmap_cache, logname);
367
368     if (map == NULL
369         && type == CLOUDLOG_JOURNAL
370         && fstatat(log->dirfd, logname, &statbuf, 0) < 0) {
371         /* A stale reference to a journal file which doesn't exist any longer
372          * because it was reclaimed.  Return NULL. */
373     } else if (map == NULL) {
374         g_print("Adding cache file %s\n", logname);
375
376         map = g_new0(BlueSkyCacheFile, 1);
377         map->fs = fs;
378         map->type = type;
379         map->lock = g_mutex_new();
380         map->type = type;
381         g_mutex_lock(map->lock);
382         map->cond = g_cond_new();
383         map->filename = g_strdup(logname);
384         map->log_seq = log_seq;
385         map->log = log;
386         g_atomic_int_set(&map->mapcount, 0);
387         g_atomic_int_set(&map->refcount, 0);
388
389         g_hash_table_insert(log->mmap_cache, map->filename, map);
390
391         // If the log file is stored in the cloud, we may need to fetch it
392         if (clouddir >= 0)
393             cloudlog_fetch_start(map);
394     } else {
395         g_mutex_lock(map->lock);
396     }
397
398     g_mutex_unlock(log->mmap_lock);
399     if (map != NULL)
400         g_atomic_int_inc(&map->refcount);
401     return map;
402 }
403
404 BlueSkyRCStr *bluesky_log_map_object(BlueSkyFS *fs, int log_dir,
405                                      int log_seq, int log_offset, int log_size)
406 {
407     if (page_size == 0) {
408         page_size = getpagesize();
409     }
410
411     BlueSkyLog *log = fs->log;
412     BlueSkyCacheFile *map = bluesky_cachefile_lookup(fs, log_dir, log_seq);
413
414     if (map == NULL) {
415         return NULL;
416     }
417
418     if (map->addr == NULL) {
419         while (!map->ready && map->fetching) {
420             g_print("Waiting for log segment to be fetched from cloud...\n");
421             g_cond_wait(map->cond, map->lock);
422         }
423
424         int fd = openat(log->dirfd, map->filename, O_RDONLY);
425
426         if (fd < 0) {
427             fprintf(stderr, "Error opening logfile %s: %m\n", map->filename);
428             bluesky_cachefile_unref(map);
429             g_mutex_unlock(map->lock);
430             return NULL;
431         }
432
433         off_t length = lseek(fd, 0, SEEK_END);
434         map->addr = (const char *)mmap(NULL, length, PROT_READ, MAP_SHARED,
435                                        fd, 0);
436         g_atomic_int_add(&log->disk_used, -(map->len / 1024));
437         map->len = length;
438         g_atomic_int_add(&log->disk_used, map->len / 1024);
439
440         g_print("Re-mapped log segment %d...\n", log_seq);
441         g_atomic_int_inc(&map->refcount);
442
443         close(fd);
444     }
445
446     g_mutex_unlock(log->mmap_lock);
447
448     BlueSkyRCStr *str;
449     map->atime = bluesky_get_current_time();
450     str = bluesky_string_new_from_mmap(map, log_offset, log_size);
451     bluesky_cachefile_unref(map);
452     g_mutex_unlock(map->lock);
453     return str;
454 }
455
456 void bluesky_mmap_unref(BlueSkyCacheFile *mmap)
457 {
458     if (mmap == NULL)
459         return;
460
461     if (g_atomic_int_dec_and_test(&mmap->mapcount)) {
462         g_mutex_lock(mmap->lock);
463         if (g_atomic_int_get(&mmap->mapcount) == 0) {
464             g_print("Unmapped log segment %d...\n", mmap->log_seq);
465             munmap((void *)mmap->addr, mmap->len);
466             mmap->addr = NULL;
467             g_atomic_int_add(&mmap->refcount, -1);
468         }
469         g_mutex_unlock(mmap->lock);
470     }
471 }
472
473 /* Scan through all currently-stored files in the journal/cache and garbage
474  * collect old unused ones, if needed. */
475 static void gather_cachefiles(gpointer key, gpointer value, gpointer user_data)
476 {
477     GList **files = (GList **)user_data;
478     *files = g_list_prepend(*files, value);
479 }
480
481 static gint compare_cachefiles(gconstpointer a, gconstpointer b)
482 {
483     int64_t ta, tb;
484
485     ta = ((BlueSkyCacheFile *)a)->atime;
486     tb = ((BlueSkyCacheFile *)b)->atime;
487     if (ta < tb)
488         return -1;
489     else if (ta > tb)
490         return 1;
491     else
492         return 0;
493 }
494
495 void bluesky_cachefile_gc(BlueSkyFS *fs)
496 {
497     GList *files = NULL;
498
499     g_mutex_lock(fs->log->mmap_lock);
500     g_hash_table_foreach(fs->log->mmap_cache, gather_cachefiles, &files);
501
502     /* Sort based on atime.  The atime should be stable since it shouln't be
503      * updated except by threads which can grab the mmap_lock, which we already
504      * hold. */
505     files = g_list_sort(files, compare_cachefiles);
506
507     /* Walk the list of files, starting with the oldest, deleting files if
508      * possible until enough space has been reclaimed. */
509     g_print("\nScanning cache: (total size = %d kB)\n", fs->log->disk_used);
510     while (files != NULL) {
511         BlueSkyCacheFile *cachefile = (BlueSkyCacheFile *)files->data;
512         /* Try to lock the structure, but if the lock is held by another thread
513          * then we'll just skip the file on this pass. */
514         if (g_mutex_trylock(cachefile->lock)) {
515             int64_t age = bluesky_get_current_time() - cachefile->atime;
516             g_print("%s addr=%p mapcount=%d refcount=%d atime_age=%f",
517                     cachefile->filename, cachefile->addr, cachefile->mapcount,
518                     cachefile->refcount, age / 1e6);
519             if (cachefile->fetching)
520                 g_print(" (fetching)");
521             g_print("\n");
522
523             gboolean deletion_candidate = FALSE;
524             if (g_atomic_int_get(&fs->log->disk_used)
525                     > bluesky_options.cache_size
526                 && g_atomic_int_get(&cachefile->refcount) == 0
527                 && g_atomic_int_get(&cachefile->mapcount) == 0)
528             {
529                 deletion_candidate = TRUE;
530             }
531
532             /* Don't allow journal files to be reclaimed until all data is
533              * known to be durably stored in the cloud. */
534             if (cachefile->type == CLOUDLOG_JOURNAL
535                 && cachefile->log_seq >= fs->log->journal_watermark)
536             {
537                 deletion_candidate = FALSE;
538             }
539
540             if (deletion_candidate) {
541                 g_print("   ...deleting\n");
542                 if (unlinkat(fs->log->dirfd, cachefile->filename, 0) < 0) {
543                     fprintf(stderr, "Unable to unlink journal %s: %m\n",
544                             cachefile->filename);
545                 }
546
547                 g_atomic_int_add(&fs->log->disk_used, -(cachefile->len / 1024));
548                 g_hash_table_remove(fs->log->mmap_cache, cachefile->filename);
549                 g_mutex_unlock(cachefile->lock);
550                 g_mutex_free(cachefile->lock);
551                 g_cond_free(cachefile->cond);
552                 g_free(cachefile->filename);
553                 g_free(cachefile);
554             } else {
555                 g_mutex_unlock(cachefile->lock);
556             }
557         }
558         files = g_list_delete_link(files, files);
559     }
560     g_list_free(files);
561
562     g_mutex_unlock(fs->log->mmap_lock);
563 }
564
565 /******************************* JOURNAL REPLAY *******************************
566  * The journal replay code is used to recover filesystem state after a
567  * filesystem restart.  We first look for the most recent commit record in the
568  * journal, which indicates the point before which all data in the journal has
569  * also been committed to the cloud.  Then, we read in all data in the log past
570  * that point.
571  */
572 static GList *directory_contents(const char *dirname)
573 {
574     GList *contents = NULL;
575     GDir *dir = g_dir_open(dirname, 0, NULL);
576     if (dir == NULL) {
577         g_warning("Unable to open journal directory: %s", dirname);
578         return NULL;
579     }
580
581     const gchar *file;
582     while ((file = g_dir_read_name(dir)) != NULL) {
583         if (strncmp(file, "journal-", 8) == 0)
584             contents = g_list_prepend(contents, g_strdup(file));
585     }
586     g_dir_close(dir);
587
588     contents = g_list_sort(contents, (GCompareFunc)strcmp);
589
590     return contents;
591 }
592
593 static gboolean validate_journal_item(const char *buf, size_t len, off_t offset)
594 {
595     const struct log_header *header;
596     const struct log_footer *footer;
597
598     if (offset + sizeof(struct log_header) + sizeof(struct log_footer) > len)
599         return FALSE;
600
601     header = (const struct log_header *)(buf + offset);
602     if (GUINT32_FROM_LE(header->magic) != HEADER_MAGIC)
603         return FALSE;
604     if (GUINT32_FROM_LE(header->offset) != offset)
605         return FALSE;
606     size_t size = GUINT32_FROM_LE(header->size);
607
608     off_t footer_offset = offset + sizeof(struct log_header) + size;
609     if (footer_offset + sizeof(struct log_footer) > len)
610         return FALSE;
611     footer = (const struct log_footer *)(buf + footer_offset);
612
613     if (GUINT32_FROM_LE(footer->magic) != FOOTER_MAGIC)
614         return FALSE;
615
616     uint32_t crc = crc32c(BLUESKY_CRC32C_SEED, buf + offset,
617                           sizeof(struct log_header) + sizeof(struct log_footer)
618                           + size);
619     if (crc != 0)
620         return FALSE;
621
622     return TRUE;
623 }
624
625 /* Scan through a journal segment to extract correctly-written items (those
626  * that pass sanity checks and have a valid checksum). */
627 static void bluesky_replay_scan_journal(const char *buf, size_t len)
628 {
629     const struct log_header *header;
630     off_t offset = 0;
631
632     while (validate_journal_item(buf, len, offset)) {
633         header = (const struct log_header *)(buf + offset);
634         size_t size = GUINT32_FROM_LE(header->size);
635         offset += sizeof(struct log_header) + size + sizeof(struct log_footer);
636     }
637 }
638
639 static void bluesky_replay_scan_journal2(BlueSkyFS *fs, GList **objects,
640                                          int log_seq,
641                                          const char *buf, size_t len)
642 {
643     const struct log_header *header;
644     off_t offset = 0;
645
646     while (validate_journal_item(buf, len, offset)) {
647         header = (const struct log_header *)(buf + offset);
648         g_print("In replay found valid item at offset %zd\n", offset);
649         size_t size = GUINT32_FROM_LE(header->size);
650
651         g_mutex_lock(fs->lock);
652         BlueSkyCloudLog *log_item;
653         log_item = g_hash_table_lookup(fs->locations, &header->id);
654         if (log_item == NULL) {
655             log_item = bluesky_cloudlog_new(fs, &header->id);
656             g_hash_table_insert(fs->locations, &log_item->id, log_item);
657             g_mutex_lock(log_item->lock);
658         } else {
659             bluesky_cloudlog_ref(log_item);
660             g_mutex_lock(log_item->lock);
661         }
662         g_mutex_unlock(fs->lock);
663         *objects = g_list_prepend(*objects, log_item);
664
665         bluesky_string_unref(log_item->data);
666         log_item->location_flags = CLOUDLOG_JOURNAL;
667         log_item->data = NULL;
668         log_item->log_seq = log_seq;
669         log_item->log_offset = offset + sizeof(struct log_header);
670         log_item->log_size = header->size;
671         g_mutex_unlock(log_item->lock);
672
673         offset += sizeof(struct log_header) + size + sizeof(struct log_footer);
674     }
675 }
676
677 void bluesky_replay(BlueSkyFS *fs)
678 {
679     BlueSkyLog *log = fs->log;
680     GList *logfiles = directory_contents(log->log_directory);
681
682     /* Scan through log files in reverse order to find the most recent commit
683      * record. */
684     logfiles = g_list_reverse(logfiles);
685     while (logfiles != NULL) {
686         char *filename = g_strdup_printf("%s/%s", log->log_directory,
687                                          (char *)logfiles->data);
688         g_print("Scanning file %s\n", filename);
689         GMappedFile *map = g_mapped_file_new(filename, FALSE, NULL);
690         if (map == NULL) {
691             g_warning("Mapping logfile %s failed!\n", filename);
692         } else {
693             bluesky_replay_scan_journal(g_mapped_file_get_contents(map),
694                                         g_mapped_file_get_length(map));
695             g_mapped_file_unref(map);
696         }
697         g_free(filename);
698
699         g_free(logfiles->data);
700         logfiles = g_list_delete_link(logfiles, logfiles);
701     }
702     g_list_foreach(logfiles, (GFunc)g_free, NULL);
703     g_list_free(logfiles);
704
705     /* Now, scan forward starting from the given point in the log to
706      * reconstruct all filesystem state.  As we reload objects we hold a
707      * reference to each loaded object.  At the end we free all these
708      * references, so that any objects which were not linked into persistent
709      * filesystem data structures are freed. */
710     GList *objects = NULL;
711     int seq_num = 0;
712     while (TRUE) {
713         char *filename = g_strdup_printf("%s/journal-%08d",
714                                          log->log_directory, seq_num);
715         g_print("Replaying file %s\n", filename);
716         GMappedFile *map = g_mapped_file_new(filename, FALSE, NULL);
717         g_free(filename);
718         if (map == NULL) {
719             g_warning("Mapping logfile failed, assuming end of journal\n");
720             break;
721         }
722
723         bluesky_replay_scan_journal2(fs, &objects, seq_num,
724                                      g_mapped_file_get_contents(map),
725                                      g_mapped_file_get_length(map));
726         g_mapped_file_unref(map);
727         seq_num++;
728     }
729
730     while (objects != NULL) {
731         bluesky_cloudlog_unref((BlueSkyCloudLog *)objects->data);
732         objects = g_list_delete_link(objects, objects);
733     }
734 }