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