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