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