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