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