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