Restart journal sequence numbering properly.
[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 static void writebuf(int fd, const char *buf, size_t len)
45 {
46     while (len > 0) {
47         ssize_t written;
48         written = write(fd, buf, len);
49         if (written < 0 && errno == EINTR)
50             continue;
51         g_assert(written >= 0);
52         buf += written;
53         len -= written;
54     }
55 }
56
57 static void log_commit(BlueSkyLog *log)
58 {
59     int batchsize = 0;
60
61     if (log->fd < 0)
62         return;
63
64     fdatasync(log->fd);
65     while (log->committed != NULL) {
66         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log->committed->data;
67         g_mutex_lock(item->lock);
68         bluesky_cloudlog_stats_update(item, -1);
69         item->pending_write &= ~CLOUDLOG_JOURNAL;
70         item->location_flags |= CLOUDLOG_JOURNAL;
71         bluesky_cloudlog_stats_update(item, 1);
72         g_cond_signal(item->cond);
73         g_mutex_unlock(item->lock);
74         log->committed = g_slist_delete_link(log->committed, log->committed);
75         bluesky_cloudlog_unref(item);
76         batchsize++;
77     }
78
79     if (bluesky_verbose && batchsize > 1)
80         g_print("Log batch size: %d\n", batchsize);
81 }
82
83 static gboolean log_open(BlueSkyLog *log)
84 {
85     char logname[64];
86
87     if (log->fd >= 0) {
88         log_commit(log);
89         close(log->fd);
90         log->seq_num++;
91         log->fd = -1;
92     }
93
94     if (log->current_log != NULL) {
95         bluesky_cachefile_unref(log->current_log);
96         log->current_log = NULL;
97     }
98
99     while (log->fd < 0) {
100         g_snprintf(logname, sizeof(logname), "journal-%08d", log->seq_num);
101         log->fd = openat(log->dirfd, logname, O_CREAT|O_WRONLY|O_EXCL, 0600);
102         if (log->fd < 0 && errno == EEXIST) {
103             fprintf(stderr, "Log file %s already exists...\n", logname);
104             log->seq_num++;
105             continue;
106         } else if (log->fd < 0) {
107             fprintf(stderr, "Error opening logfile %s: %m\n", logname);
108             return FALSE;
109         }
110     }
111
112     log->current_log = bluesky_cachefile_lookup(log->fs, -1, log->seq_num);
113     g_assert(log->current_log != NULL);
114     g_mutex_unlock(log->current_log->lock);
115
116     if (ftruncate(log->fd, LOG_SEGMENT_SIZE) < 0) {
117         fprintf(stderr, "Unable to truncate logfile %s: %m\n", logname);
118     }
119     fsync(log->fd);
120     fsync(log->dirfd);
121     return TRUE;
122 }
123
124 /* All log writes (at least for a single log) are made by one thread, so we
125  * don't need to worry about concurrent access to the log file.  Log items to
126  * write are pulled off a queue (and so may be posted by any thread).
127  * fdatasync() is used to ensure the log items are stable on disk.
128  *
129  * The log is broken up into separate files, roughly of size LOG_SEGMENT_SIZE
130  * each.  If a log segment is not currently open (log->fd is negative), a new
131  * one is created.  Log segment filenames are assigned sequentially.
132  *
133  * Log replay ought to be implemented later, and ought to set the initial
134  * sequence number appropriately.
135  */
136 static gpointer log_thread(gpointer d)
137 {
138     BlueSkyLog *log = (BlueSkyLog *)d;
139
140     while (TRUE) {
141         if (log->fd < 0) {
142             if (!log_open(log)) {
143                 return NULL;
144             }
145         }
146
147         BlueSkyCloudLog *item
148             = (BlueSkyCloudLog *)g_async_queue_pop(log->queue);
149         g_mutex_lock(item->lock);
150         g_assert(item->data != NULL);
151
152         /* The item may have already been written to the journal... */
153         if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
154             g_mutex_unlock(item->lock);
155             bluesky_cloudlog_unref(item);
156             g_atomic_int_add(&item->data_lock_count, -1);
157             continue;
158         }
159
160         bluesky_cloudlog_stats_update(item, -1);
161         item->pending_write |= CLOUDLOG_JOURNAL;
162         bluesky_cloudlog_stats_update(item, 1);
163
164         GString *data1 = g_string_new("");
165         GString *data2 = g_string_new("");
166         GString *data3 = g_string_new("");
167         bluesky_serialize_cloudlog(item, data1, data2, data3);
168
169         struct log_header header;
170         struct log_footer footer;
171         size_t size = sizeof(header) + sizeof(footer);
172         size += data1->len + data2->len + data3->len;
173         off_t offset = 0;
174         if (log->fd >= 0)
175             offset = lseek(log->fd, 0, SEEK_CUR);
176
177         /* Check whether the item would overflow the allocated journal size.
178          * If so, start a new log segment.  We only allow oversized log
179          * segments if they contain a single log entry. */
180         if (offset + size >= LOG_SEGMENT_SIZE && offset > 0) {
181             log_open(log);
182             offset = 0;
183         }
184
185         header.magic = GUINT32_TO_LE(HEADER_MAGIC);
186         header.offset = GUINT32_TO_LE(offset);
187         header.size1 = GUINT32_TO_LE(data1->len);
188         header.size2 = GUINT32_TO_LE(data2->len);
189         header.size3 = GUINT32_TO_LE(data3->len);
190         header.type = item->type + '0';
191         header.id = item->id;
192         header.inum = GUINT64_TO_LE(item->inum);
193         footer.magic = GUINT32_TO_LE(FOOTER_MAGIC);
194
195         uint32_t crc = BLUESKY_CRC32C_SEED;
196
197         writebuf(log->fd, (const char *)&header, sizeof(header));
198         crc = crc32c(crc, (const char *)&header, sizeof(header));
199
200         writebuf(log->fd, data1->str, data1->len);
201         crc = crc32c(crc, data1->str, data1->len);
202         writebuf(log->fd, data2->str, data2->len);
203         crc = crc32c(crc, data2->str, data2->len);
204         writebuf(log->fd, data3->str, data3->len);
205         crc = crc32c(crc, data3->str, data3->len);
206
207         crc = crc32c(crc, (const char *)&footer,
208                      sizeof(footer) - sizeof(uint32_t));
209         footer.crc = crc32c_finalize(crc);
210         writebuf(log->fd, (const char *)&footer, sizeof(footer));
211
212         item->log_seq = log->seq_num;
213         item->log_offset = offset;
214         item->log_size = size;
215         item->data_size = item->data->len;
216
217         offset += size;
218
219         g_string_free(data1, TRUE);
220         g_string_free(data2, TRUE);
221         g_string_free(data3, TRUE);
222
223         /* Replace the log item's string data with a memory-mapped copy of the
224          * data, now that it has been written to the log file.  (Even if it
225          * isn't yet on disk, it should at least be in the page cache and so
226          * available to memory map.) */
227         bluesky_string_unref(item->data);
228         item->data = NULL;
229         bluesky_cloudlog_fetch(item);
230
231         log->committed = g_slist_prepend(log->committed, item);
232         g_atomic_int_add(&item->data_lock_count, -1);
233         g_mutex_unlock(item->lock);
234
235         /* Force an if there are no other log items currently waiting to be
236          * written. */
237         if (g_async_queue_length(log->queue) <= 0)
238             log_commit(log);
239     }
240
241     return NULL;
242 }
243
244 BlueSkyLog *bluesky_log_new(const char *log_directory)
245 {
246     BlueSkyLog *log = g_new0(BlueSkyLog, 1);
247
248     log->log_directory = g_strdup(log_directory);
249     log->fd = -1;
250     log->seq_num = 0;
251     log->queue = g_async_queue_new();
252     log->mmap_lock = g_mutex_new();
253     log->mmap_cache = g_hash_table_new(g_str_hash, g_str_equal);
254
255     /* Determine the highest-numbered log file, so that we can start writing
256      * out new journal entries at the next sequence number. */
257     GDir *dir = g_dir_open(log_directory, 0, NULL);
258     if (dir != NULL) {
259         const gchar *file;
260         while ((file = g_dir_read_name(dir)) != NULL) {
261             if (strncmp(file, "journal-", 8) == 0) {
262                 log->seq_num = MAX(log->seq_num, atoi(&file[8]) + 1);
263             }
264         }
265         g_dir_close(dir);
266         g_print("Starting journal at sequence number %d\n", log->seq_num);
267     }
268
269     log->dirfd = open(log->log_directory, O_DIRECTORY);
270     if (log->dirfd < 0) {
271         fprintf(stderr, "Unable to open logging directory: %m\n");
272         return NULL;
273     }
274
275     g_thread_create(log_thread, log, FALSE, NULL);
276
277     return log;
278 }
279
280 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log)
281 {
282     bluesky_cloudlog_ref(item);
283     g_atomic_int_add(&item->data_lock_count, 1);
284     g_async_queue_push(log->queue, item);
285 }
286
287 void bluesky_log_finish_all(GList *log_items)
288 {
289     while (log_items != NULL) {
290         BlueSkyCloudLog *item = (BlueSkyCloudLog *)log_items->data;
291
292         g_mutex_lock(item->lock);
293         while ((item->pending_write & CLOUDLOG_JOURNAL))
294             g_cond_wait(item->cond, item->lock);
295         g_mutex_unlock(item->lock);
296         bluesky_cloudlog_unref(item);
297
298         log_items = g_list_delete_link(log_items, log_items);
299     }
300 }
301
302 /* Return a committed cloud log record that can be used as a watermark for how
303  * much of the journal has been written. */
304 BlueSkyCloudLog *bluesky_log_get_commit_point(BlueSkyFS *fs)
305 {
306     BlueSkyCloudLog *marker = bluesky_cloudlog_new(fs, NULL);
307     marker->type = LOGTYPE_JOURNAL_MARKER;
308     marker->data = bluesky_string_new(g_strdup(""), 0);
309     bluesky_cloudlog_sync(marker);
310
311     g_mutex_lock(marker->lock);
312     while ((marker->pending_write & CLOUDLOG_JOURNAL))
313         g_cond_wait(marker->cond, marker->lock);
314     g_mutex_unlock(marker->lock);
315
316     return marker;
317 }
318
319 void bluesky_log_write_commit_point(BlueSkyFS *fs, BlueSkyCloudLog *marker)
320 {
321     BlueSkyCloudLog *commit = bluesky_cloudlog_new(fs, NULL);
322     commit->type = LOGTYPE_JOURNAL_CHECKPOINT;
323
324     uint32_t seq, offset;
325     seq = GUINT32_TO_LE(marker->log_seq);
326     offset = GUINT32_TO_LE(marker->log_offset);
327     GString *loc = g_string_new("");
328     g_string_append_len(loc, (const gchar *)&seq, sizeof(seq));
329     g_string_append_len(loc, (const gchar *)&offset, sizeof(offset));
330     commit->data = bluesky_string_new_from_gstring(loc);
331     bluesky_cloudlog_sync(commit);
332
333     g_mutex_lock(commit->lock);
334     while ((commit->pending_write & CLOUDLOG_JOURNAL))
335         g_cond_wait(commit->cond, commit->lock);
336     g_mutex_unlock(commit->lock);
337
338     bluesky_cloudlog_unref(marker);
339     bluesky_cloudlog_unref(commit);
340 }
341
342 /* Memory-map the given log object into memory (read-only) and return a pointer
343  * to it. */
344 static int page_size = 0;
345
346 void bluesky_cachefile_unref(BlueSkyCacheFile *cachefile)
347 {
348     g_atomic_int_add(&cachefile->refcount, -1);
349 }
350
351 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
352                                     BlueSkyCacheFile *cachefile);
353
354 static void cloudlog_fetch_start(BlueSkyCacheFile *cachefile)
355 {
356     g_atomic_int_inc(&cachefile->refcount);
357     cachefile->fetching = TRUE;
358     g_print("Starting fetch of %s from cloud\n", cachefile->filename);
359     BlueSkyStoreAsync *async = bluesky_store_async_new(cachefile->fs->store);
360     async->op = STORE_OP_GET;
361     async->key = g_strdup(cachefile->filename);
362     bluesky_store_async_add_notifier(async,
363                                      (GFunc)cloudlog_fetch_complete,
364                                      cachefile);
365     bluesky_store_async_submit(async);
366     bluesky_store_async_unref(async);
367 }
368
369 static void cloudlog_fetch_complete(BlueSkyStoreAsync *async,
370                                     BlueSkyCacheFile *cachefile)
371 {
372     g_print("Fetch of %s from cloud complete, status = %d\n",
373             async->key, async->result);
374
375     g_mutex_lock(cachefile->lock);
376     if (async->result >= 0) {
377         char *pathname = g_strdup_printf("%s/%s",
378                                          cachefile->log->log_directory,
379                                          cachefile->filename);
380         if (!g_file_set_contents(pathname, async->data->data, async->data->len,
381                                  NULL))
382             g_print("Error writing out fetched file to cache!\n");
383         g_free(pathname);
384
385         cachefile->fetching = FALSE;
386         cachefile->ready = TRUE;
387     } else {
388         g_print("Error fetching from cloud, retrying...\n");
389         cloudlog_fetch_start(cachefile);
390     }
391
392     bluesky_cachefile_unref(cachefile);
393     g_cond_broadcast(cachefile->cond);
394     g_mutex_unlock(cachefile->lock);
395 }
396
397 /* Find the BlueSkyCacheFile object for the given journal or cloud log segment.
398  * Returns the object in the locked state and with a reference taken. */
399 BlueSkyCacheFile *bluesky_cachefile_lookup(BlueSkyFS *fs,
400                                            int clouddir, int log_seq)
401 {
402     if (page_size == 0) {
403         page_size = getpagesize();
404     }
405
406     BlueSkyLog *log = fs->log;
407
408     struct stat statbuf;
409     char logname[64];
410     int type;
411
412     // A request for a local log file
413     if (clouddir < 0) {
414         sprintf(logname, "journal-%08d", log_seq);
415         type = CLOUDLOG_JOURNAL;
416     } else {
417         sprintf(logname, "log-%08d-%08d", clouddir, log_seq);
418         type = CLOUDLOG_CLOUD;
419     }
420
421     BlueSkyCacheFile *map;
422     g_mutex_lock(log->mmap_lock);
423     map = g_hash_table_lookup(log->mmap_cache, logname);
424
425     if (map == NULL
426         && type == CLOUDLOG_JOURNAL
427         && fstatat(log->dirfd, logname, &statbuf, 0) < 0) {
428         /* A stale reference to a journal file which doesn't exist any longer
429          * because it was reclaimed.  Return NULL. */
430     } else if (map == NULL) {
431         g_print("Adding cache file %s\n", logname);
432
433         map = g_new0(BlueSkyCacheFile, 1);
434         map->fs = fs;
435         map->type = type;
436         map->lock = g_mutex_new();
437         map->type = type;
438         g_mutex_lock(map->lock);
439         map->cond = g_cond_new();
440         map->filename = g_strdup(logname);
441         map->log_seq = log_seq;
442         map->log = log;
443         g_atomic_int_set(&map->mapcount, 0);
444         g_atomic_int_set(&map->refcount, 0);
445
446         g_hash_table_insert(log->mmap_cache, map->filename, map);
447
448         // If the log file is stored in the cloud, we may need to fetch it
449         if (clouddir >= 0)
450             cloudlog_fetch_start(map);
451     } else {
452         g_mutex_lock(map->lock);
453     }
454
455     g_mutex_unlock(log->mmap_lock);
456     if (map != NULL)
457         g_atomic_int_inc(&map->refcount);
458     return map;
459 }
460
461 BlueSkyRCStr *bluesky_log_map_object(BlueSkyFS *fs, int log_dir,
462                                      int log_seq, int log_offset, int log_size)
463 {
464     if (page_size == 0) {
465         page_size = getpagesize();
466     }
467
468     BlueSkyLog *log = fs->log;
469     BlueSkyCacheFile *map = bluesky_cachefile_lookup(fs, log_dir, log_seq);
470
471     if (map == NULL) {
472         return NULL;
473     }
474
475     if (map->addr == NULL) {
476         while (!map->ready && map->fetching) {
477             g_print("Waiting for log segment to be fetched from cloud...\n");
478             g_cond_wait(map->cond, map->lock);
479         }
480
481         int fd = openat(log->dirfd, map->filename, O_RDONLY);
482
483         if (fd < 0) {
484             fprintf(stderr, "Error opening logfile %s: %m\n", map->filename);
485             bluesky_cachefile_unref(map);
486             g_mutex_unlock(map->lock);
487             return NULL;
488         }
489
490         off_t length = lseek(fd, 0, SEEK_END);
491         map->addr = (const char *)mmap(NULL, length, PROT_READ, MAP_SHARED,
492                                        fd, 0);
493         g_atomic_int_add(&log->disk_used, -(map->len / 1024));
494         map->len = length;
495         g_atomic_int_add(&log->disk_used, map->len / 1024);
496
497         g_print("Re-mapped log segment %d...\n", log_seq);
498         g_atomic_int_inc(&map->refcount);
499
500         close(fd);
501     }
502
503     g_mutex_unlock(log->mmap_lock);
504
505     BlueSkyRCStr *str;
506     map->atime = bluesky_get_current_time();
507     str = bluesky_string_new_from_mmap(map, log_offset, log_size);
508     bluesky_cachefile_unref(map);
509     g_mutex_unlock(map->lock);
510     return str;
511 }
512
513 void bluesky_mmap_unref(BlueSkyCacheFile *mmap)
514 {
515     if (mmap == NULL)
516         return;
517
518     if (g_atomic_int_dec_and_test(&mmap->mapcount)) {
519         g_mutex_lock(mmap->lock);
520         if (g_atomic_int_get(&mmap->mapcount) == 0) {
521             g_print("Unmapped log segment %d...\n", mmap->log_seq);
522             munmap((void *)mmap->addr, mmap->len);
523             mmap->addr = NULL;
524             g_atomic_int_add(&mmap->refcount, -1);
525         }
526         g_mutex_unlock(mmap->lock);
527     }
528 }
529
530 /* Scan through all currently-stored files in the journal/cache and garbage
531  * collect old unused ones, if needed. */
532 static void gather_cachefiles(gpointer key, gpointer value, gpointer user_data)
533 {
534     GList **files = (GList **)user_data;
535     *files = g_list_prepend(*files, value);
536 }
537
538 static gint compare_cachefiles(gconstpointer a, gconstpointer b)
539 {
540     int64_t ta, tb;
541
542     ta = ((BlueSkyCacheFile *)a)->atime;
543     tb = ((BlueSkyCacheFile *)b)->atime;
544     if (ta < tb)
545         return -1;
546     else if (ta > tb)
547         return 1;
548     else
549         return 0;
550 }
551
552 void bluesky_cachefile_gc(BlueSkyFS *fs)
553 {
554     GList *files = NULL;
555
556     g_mutex_lock(fs->log->mmap_lock);
557     g_hash_table_foreach(fs->log->mmap_cache, gather_cachefiles, &files);
558
559     /* Sort based on atime.  The atime should be stable since it shouln't be
560      * updated except by threads which can grab the mmap_lock, which we already
561      * hold. */
562     files = g_list_sort(files, compare_cachefiles);
563
564     /* Walk the list of files, starting with the oldest, deleting files if
565      * possible until enough space has been reclaimed. */
566     g_print("\nScanning cache: (total size = %d kB)\n", fs->log->disk_used);
567     while (files != NULL) {
568         BlueSkyCacheFile *cachefile = (BlueSkyCacheFile *)files->data;
569         /* Try to lock the structure, but if the lock is held by another thread
570          * then we'll just skip the file on this pass. */
571         if (g_mutex_trylock(cachefile->lock)) {
572             int64_t age = bluesky_get_current_time() - cachefile->atime;
573             g_print("%s addr=%p mapcount=%d refcount=%d atime_age=%f",
574                     cachefile->filename, cachefile->addr, cachefile->mapcount,
575                     cachefile->refcount, age / 1e6);
576             if (cachefile->fetching)
577                 g_print(" (fetching)");
578             g_print("\n");
579
580             gboolean deletion_candidate = FALSE;
581             if (g_atomic_int_get(&fs->log->disk_used)
582                     > bluesky_options.cache_size
583                 && g_atomic_int_get(&cachefile->refcount) == 0
584                 && g_atomic_int_get(&cachefile->mapcount) == 0)
585             {
586                 deletion_candidate = TRUE;
587             }
588
589             /* Don't allow journal files to be reclaimed until all data is
590              * known to be durably stored in the cloud. */
591             if (cachefile->type == CLOUDLOG_JOURNAL
592                 && cachefile->log_seq >= fs->log->journal_watermark)
593             {
594                 deletion_candidate = FALSE;
595             }
596
597             if (deletion_candidate) {
598                 g_print("   ...deleting\n");
599                 if (unlinkat(fs->log->dirfd, cachefile->filename, 0) < 0) {
600                     fprintf(stderr, "Unable to unlink journal %s: %m\n",
601                             cachefile->filename);
602                 }
603
604                 g_atomic_int_add(&fs->log->disk_used, -(cachefile->len / 1024));
605                 g_hash_table_remove(fs->log->mmap_cache, cachefile->filename);
606                 g_mutex_unlock(cachefile->lock);
607                 g_mutex_free(cachefile->lock);
608                 g_cond_free(cachefile->cond);
609                 g_free(cachefile->filename);
610                 g_free(cachefile);
611             } else {
612                 g_mutex_unlock(cachefile->lock);
613             }
614         }
615         files = g_list_delete_link(files, files);
616     }
617     g_list_free(files);
618
619     g_mutex_unlock(fs->log->mmap_lock);
620 }
621
622 /******************************* JOURNAL REPLAY *******************************
623  * The journal replay code is used to recover filesystem state after a
624  * filesystem restart.  We first look for the most recent commit record in the
625  * journal, which indicates the point before which all data in the journal has
626  * also been committed to the cloud.  Then, we read in all data in the log past
627  * that point.
628  */
629 static GList *directory_contents(const char *dirname)
630 {
631     GList *contents = NULL;
632     GDir *dir = g_dir_open(dirname, 0, NULL);
633     if (dir == NULL) {
634         g_warning("Unable to open journal directory: %s", dirname);
635         return NULL;
636     }
637
638     const gchar *file;
639     while ((file = g_dir_read_name(dir)) != NULL) {
640         if (strncmp(file, "journal-", 8) == 0)
641             contents = g_list_prepend(contents, g_strdup(file));
642     }
643     g_dir_close(dir);
644
645     contents = g_list_sort(contents, (GCompareFunc)strcmp);
646
647     return contents;
648 }
649
650 static gboolean validate_journal_item(const char *buf, size_t len, off_t offset)
651 {
652     const struct log_header *header;
653     const struct log_footer *footer;
654
655     if (offset + sizeof(struct log_header) + sizeof(struct log_footer) > len)
656         return FALSE;
657
658     header = (const struct log_header *)(buf + offset);
659     if (GUINT32_FROM_LE(header->magic) != HEADER_MAGIC)
660         return FALSE;
661     if (GUINT32_FROM_LE(header->offset) != offset)
662         return FALSE;
663     size_t size = GUINT32_FROM_LE(header->size1)
664                    + GUINT32_FROM_LE(header->size2)
665                    + GUINT32_FROM_LE(header->size3);
666
667     off_t footer_offset = offset + sizeof(struct log_header) + size;
668     if (footer_offset + sizeof(struct log_footer) > len)
669         return FALSE;
670     footer = (const struct log_footer *)(buf + footer_offset);
671
672     if (GUINT32_FROM_LE(footer->magic) != FOOTER_MAGIC)
673         return FALSE;
674
675     uint32_t crc = crc32c(BLUESKY_CRC32C_SEED, buf + offset,
676                           sizeof(struct log_header) + sizeof(struct log_footer)
677                           + size);
678     if (crc != BLUESKY_CRC32C_VALIDATOR) {
679         g_warning("Journal entry failed to validate: CRC %08x != %08x",
680                   crc, BLUESKY_CRC32C_VALIDATOR);
681         return FALSE;
682     }
683
684     return TRUE;
685 }
686
687 /* Scan through a journal segment to extract correctly-written items (those
688  * that pass sanity checks and have a valid checksum). */
689 static void bluesky_replay_scan_journal(const char *buf, size_t len,
690                                         uint32_t *seq, uint32_t *start_offset)
691 {
692     const struct log_header *header;
693     off_t offset = 0;
694
695     while (validate_journal_item(buf, len, offset)) {
696         header = (const struct log_header *)(buf + offset);
697         size_t size = GUINT32_FROM_LE(header->size1)
698                        + GUINT32_FROM_LE(header->size2)
699                        + GUINT32_FROM_LE(header->size3);
700
701         if (header->type - '0' == LOGTYPE_JOURNAL_CHECKPOINT) {
702             const uint32_t *data = (const uint32_t *)((const char *)header + sizeof(struct log_header));
703             *seq = GUINT32_FROM_LE(data[0]);
704             *start_offset = GUINT32_FROM_LE(data[1]);
705         }
706
707         offset += sizeof(struct log_header) + size + sizeof(struct log_footer);
708     }
709 }
710
711 static void reload_item(BlueSkyCloudLog *log_item,
712                         const char *data,
713                         size_t len1, size_t len2, size_t len3)
714 {
715     BlueSkyFS *fs = log_item->fs;
716     /*const char *data1 = data;*/
717     const BlueSkyCloudID *data2
718         = (const BlueSkyCloudID *)(data + len1);
719     /*const BlueSkyCloudPointer *data3
720         = (const BlueSkyCloudPointer *)(data + len1 + len2);*/
721
722     bluesky_string_unref(log_item->data);
723     log_item->data = NULL;
724     log_item->location_flags = CLOUDLOG_JOURNAL;
725
726     BlueSkyCloudID id0;
727     memset(&id0, 0, sizeof(id0));
728
729     int link_count = len2 / sizeof(BlueSkyCloudID);
730     GArray *new_links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
731     for (int i = 0; i < link_count; i++) {
732         BlueSkyCloudID id = data2[i];
733         BlueSkyCloudLog *ref = NULL;
734         if (memcmp(&id, &id0, sizeof(BlueSkyCloudID)) != 0) {
735             g_mutex_lock(fs->lock);
736             ref = g_hash_table_lookup(fs->locations, &id);
737             if (ref != NULL) {
738                 bluesky_cloudlog_ref(ref);
739             }
740             g_mutex_unlock(fs->lock);
741         }
742         g_array_append_val(new_links, ref);
743     }
744
745     for (int i = 0; i < log_item->links->len; i++) {
746         BlueSkyCloudLog *c = g_array_index(log_item->links,
747                                            BlueSkyCloudLog *, i);
748         bluesky_cloudlog_unref(c);
749     }
750     g_array_unref(log_item->links);
751     log_item->links = new_links;
752 }
753
754 static void bluesky_replay_scan_journal2(BlueSkyFS *fs, GList **objects,
755                                          int log_seq, int start_offset,
756                                          const char *buf, size_t len)
757 {
758     const struct log_header *header;
759     off_t offset = start_offset;
760
761     while (validate_journal_item(buf, len, offset)) {
762         header = (const struct log_header *)(buf + offset);
763         g_print("In replay found valid item at offset %zd\n", offset);
764         size_t size = GUINT32_FROM_LE(header->size1)
765                        + GUINT32_FROM_LE(header->size2)
766                        + GUINT32_FROM_LE(header->size3);
767
768         BlueSkyCloudLog *log_item = bluesky_cloudlog_get(fs, header->id);
769         g_mutex_lock(log_item->lock);
770         *objects = g_list_prepend(*objects, log_item);
771
772         log_item->inum = GUINT64_FROM_LE(header->inum);
773         reload_item(log_item, buf + offset + sizeof(struct log_header),
774                     GUINT32_FROM_LE(header->size1),
775                     GUINT32_FROM_LE(header->size2),
776                     GUINT32_FROM_LE(header->size3));
777         log_item->log_seq = log_seq;
778         log_item->log_offset = offset + sizeof(struct log_header);
779         log_item->log_size = header->size1;
780
781         bluesky_string_unref(log_item->data);
782         log_item->data = bluesky_string_new(g_memdup(buf + offset + sizeof(struct log_header), GUINT32_FROM_LE(header->size1)), GUINT32_FROM_LE(header->size1));
783
784         /* For any inodes which were read from the journal, deserialize the
785          * inode information, overwriting any old inode data. */
786         if (header->type - '0' == LOGTYPE_INODE) {
787             uint64_t inum = GUINT64_FROM_LE(header->inum);
788             BlueSkyInode *inode;
789             g_mutex_lock(fs->lock);
790             inode = (BlueSkyInode *)g_hash_table_lookup(fs->inodes, &inum);
791             if (inode == NULL) {
792                 inode = bluesky_new_inode(inum, fs, BLUESKY_PENDING);
793                 inode->change_count = 0;
794                 bluesky_insert_inode(fs, inode);
795             }
796             g_mutex_lock(inode->lock);
797             bluesky_inode_free_resources(inode);
798             if (!bluesky_deserialize_inode(inode, log_item))
799                 g_print("Error deserializing inode %"PRIu64"\n", inum);
800             fs->next_inum = MAX(fs->next_inum, inum + 1);
801             bluesky_list_unlink(&fs->accessed_list, inode->accessed_list);
802             inode->accessed_list = bluesky_list_prepend(&fs->accessed_list, inode);
803             bluesky_list_unlink(&fs->dirty_list, inode->dirty_list);
804             inode->dirty_list = bluesky_list_prepend(&fs->dirty_list, inode);
805             bluesky_list_unlink(&fs->unlogged_list, inode->unlogged_list);
806             inode->unlogged_list = NULL;
807             inode->change_cloud = inode->change_commit;
808             bluesky_cloudlog_ref(log_item);
809             bluesky_cloudlog_unref(inode->committed_item);
810             inode->committed_item = log_item;
811             g_mutex_unlock(inode->lock);
812             g_mutex_unlock(fs->lock);
813         }
814         bluesky_string_unref(log_item->data);
815         log_item->data = NULL;
816         g_mutex_unlock(log_item->lock);
817
818         offset += sizeof(struct log_header) + size + sizeof(struct log_footer);
819     }
820 }
821
822 void bluesky_replay(BlueSkyFS *fs)
823 {
824     BlueSkyLog *log = fs->log;
825     GList *logfiles = directory_contents(log->log_directory);
826
827     /* Scan through log files in reverse order to find the most recent commit
828      * record. */
829     logfiles = g_list_reverse(logfiles);
830     uint32_t seq_num = 0, start_offset = 0;
831     while (logfiles != NULL) {
832         char *filename = g_strdup_printf("%s/%s", log->log_directory,
833                                          (char *)logfiles->data);
834         g_print("Scanning file %s\n", filename);
835         GMappedFile *map = g_mapped_file_new(filename, FALSE, NULL);
836         if (map == NULL) {
837             g_warning("Mapping logfile %s failed!\n", filename);
838         } else {
839             bluesky_replay_scan_journal(g_mapped_file_get_contents(map),
840                                         g_mapped_file_get_length(map),
841                                         &seq_num, &start_offset);
842             g_mapped_file_unref(map);
843         }
844         g_free(filename);
845
846         g_free(logfiles->data);
847         logfiles = g_list_delete_link(logfiles, logfiles);
848         if (seq_num != 0 || start_offset != 0)
849             break;
850     }
851     g_list_foreach(logfiles, (GFunc)g_free, NULL);
852     g_list_free(logfiles);
853
854     /* Now, scan forward starting from the given point in the log to
855      * reconstruct all filesystem state.  As we reload objects we hold a
856      * reference to each loaded object.  At the end we free all these
857      * references, so that any objects which were not linked into persistent
858      * filesystem data structures are freed. */
859     GList *objects = NULL;
860     while (TRUE) {
861         char *filename = g_strdup_printf("%s/journal-%08d",
862                                          log->log_directory, seq_num);
863         g_print("Replaying file %s from offset %d\n", filename, start_offset);
864         GMappedFile *map = g_mapped_file_new(filename, FALSE, NULL);
865         g_free(filename);
866         if (map == NULL) {
867             g_warning("Mapping logfile failed, assuming end of journal\n");
868             break;
869         }
870
871         bluesky_replay_scan_journal2(fs, &objects, seq_num, start_offset,
872                                      g_mapped_file_get_contents(map),
873                                      g_mapped_file_get_length(map));
874         g_mapped_file_unref(map);
875         seq_num++;
876         start_offset = 0;
877     }
878
879     while (objects != NULL) {
880         bluesky_cloudlog_unref((BlueSkyCloudLog *)objects->data);
881         objects = g_list_delete_link(objects, objects);
882     }
883 }