Add an option to disable aggregating reads in the proxy
[bluesky.git] / bluesky / cloudlog.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2009  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <glib.h>
12 #include <string.h>
13
14 #include "bluesky-private.h"
15
16 // Rough size limit for a log segment.  This is not a firm limit and there are
17 // no absolute guarantees on the size of a log segment.
18 #define CLOUDLOG_SEGMENT_SIZE (4 << 20)
19
20 // Maximum number of segments to attempt to upload concurrently
21 int cloudlog_concurrent_uploads = 32;
22
23 BlueSkyCloudID bluesky_cloudlog_new_id()
24 {
25     BlueSkyCloudID id;
26     bluesky_crypt_random_bytes((uint8_t *)&id.bytes, sizeof(id));
27     return id;
28 }
29
30 gchar *bluesky_cloudlog_id_to_string(BlueSkyCloudID id)
31 {
32     char buf[sizeof(BlueSkyCloudID) * 2 + 1];
33     buf[0] = '\0';
34
35     for (int i = 0; i < sizeof(BlueSkyCloudID); i++) {
36         sprintf(&buf[2*i], "%02x", (uint8_t)(id.bytes[i]));
37     }
38
39     return g_strdup(buf);
40 }
41
42 BlueSkyCloudID bluesky_cloudlog_id_from_string(const gchar *idstr)
43 {
44     BlueSkyCloudID id;
45     memset(&id, 0, sizeof(id));
46     for (int i = 0; i < 2*sizeof(BlueSkyCloudID); i++) {
47         char c = idstr[i];
48         if (c == '\0') {
49             g_warning("Short cloud id: %s\n", idstr);
50             break;
51         }
52         int val = 0;
53         if (c >= '0' && c <= '9')
54             val = c - '0';
55         else if (c >= 'a' && c <= 'f')
56             val = c - 'a' + 10;
57         else
58             g_warning("Bad character in cloud id: %s\n", idstr);
59         id.bytes[i / 2] += val << (i % 2 ? 0 : 4);
60     }
61     return id;
62 }
63
64 gboolean bluesky_cloudlog_equal(gconstpointer a, gconstpointer b)
65 {
66     BlueSkyCloudID *id1 = (BlueSkyCloudID *)a, *id2 = (BlueSkyCloudID *)b;
67
68     return memcmp(id1, id2, sizeof(BlueSkyCloudID)) == 0;
69 }
70
71 guint bluesky_cloudlog_hash(gconstpointer a)
72 {
73     BlueSkyCloudID *id = (BlueSkyCloudID *)a;
74
75     // Assume that bits in the ID are randomly chosen so that any subset of the
76     // bits can be used as a hash key.
77     return *(guint *)(&id->bytes);
78 }
79
80 /* Formatting of cloud log segments.  This handles grouping items together
81  * before writing a batch to the cloud, handling indirection through items like
82  * the inode map, etc. */
83
84 BlueSkyCloudLog *bluesky_cloudlog_new(BlueSkyFS *fs, const BlueSkyCloudID *id)
85 {
86     BlueSkyCloudLog *log = g_new0(BlueSkyCloudLog, 1);
87
88     log->lock = g_mutex_new();
89     log->cond = g_cond_new();
90     log->fs = fs;
91     log->type = LOGTYPE_UNKNOWN;
92     if (id != NULL)
93         memcpy(&log->id, id, sizeof(BlueSkyCloudID));
94     else
95         log->id = bluesky_cloudlog_new_id();
96     log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
97     g_atomic_int_set(&log->refcount, 1);
98
99     return log;
100 }
101
102 /* Helper function for updating memory usage statistics for a filesystem (the
103  * cache_log_* variables).  This will increment (type=1) or decrement (type=-1)
104  * the counter associated with the current state of the cloud log item.  The
105  * item should be locked or otherwise protected from concurrent access. */
106 void bluesky_cloudlog_stats_update(BlueSkyCloudLog *log, int type)
107 {
108     BlueSkyFS *fs = log->fs;
109
110     if (log->location_flags & CLOUDLOG_CLOUD) {
111         g_atomic_int_add(&fs->cache_log_cloud, type);
112     } else if (log->location_flags & CLOUDLOG_JOURNAL) {
113         g_atomic_int_add(&fs->cache_log_journal, type);
114     } else if (log->pending_write & CLOUDLOG_JOURNAL) {
115         g_atomic_int_add(&fs->cache_log_journal, type);
116     } else if (log->data != NULL) {
117         g_atomic_int_add(&fs->cache_log_dirty, type);
118     }
119 }
120
121 /* The reference held by the hash table does not count towards the reference
122  * count.  When a new object is created, it initially has a reference count of
123  * 1 for the creator, and similarly fetching an item from the hash table will
124  * also create a reference.  If the reference count drops to zero,
125  * bluesky_cloudlog_unref attempts to remove the object from the hash
126  * table--but there is a potential race since another thread might read the
127  * object from the hash table at the same time.  So an object with a reference
128  * count of zero may still be resurrected, in which case we need to abort the
129  * destruction.  Once the object is gone from the hash table, and if the
130  * reference count is still zero, it can actually be deleted. */
131 void bluesky_cloudlog_ref(BlueSkyCloudLog *log)
132 {
133     if (log == NULL)
134         return;
135
136     g_atomic_int_inc(&log->refcount);
137 }
138
139 void bluesky_cloudlog_unref(BlueSkyCloudLog *log)
140 {
141     if (log == NULL)
142         return;
143
144     if (g_atomic_int_dec_and_test(&log->refcount)) {
145         BlueSkyFS *fs = log->fs;
146
147         g_mutex_lock(fs->lock);
148         if (g_atomic_int_get(&log->refcount) > 0) {
149             g_mutex_unlock(fs->lock);
150             return;
151         }
152
153         if (!g_hash_table_remove(fs->locations, &log->id)) {
154             if (bluesky_verbose)
155                 g_warning("Could not find and remove cloud log item from hash table!");
156         }
157         g_mutex_unlock(fs->lock);
158
159         bluesky_cloudlog_stats_update(log, -1);
160         log->type = LOGTYPE_INVALID;
161         g_mutex_free(log->lock);
162         g_cond_free(log->cond);
163         for (int i = 0; i < log->links->len; i++) {
164             BlueSkyCloudLog *c = g_array_index(log->links,
165                                                BlueSkyCloudLog *, i);
166             bluesky_cloudlog_unref(c);
167         }
168         g_array_unref(log->links);
169         bluesky_string_unref(log->data);
170         g_free(log);
171     }
172 }
173
174 /* For locking reasons cloudlog unrefs may sometimes need to be performed in
175  * the future.  We launch a thread for handling these delayed unreference
176  * requests. */
177 static gpointer cloudlog_unref_thread(gpointer q)
178 {
179     GAsyncQueue *queue = (GAsyncQueue *)q;
180
181     while (TRUE) {
182         BlueSkyCloudLog *item = (BlueSkyCloudLog *)g_async_queue_pop(queue);
183         bluesky_cloudlog_unref(item);
184     }
185
186     return NULL;
187 }
188
189 void bluesky_cloudlog_unref_delayed(BlueSkyCloudLog *log)
190 {
191     if (log != NULL)
192         g_async_queue_push(log->fs->unref_queue, log);
193 }
194
195 /* Erase the information contained within the in-memory cloud log
196  * representation.  This does not free up the item itself, but frees the data
197  * and references to other log items and resets the type back to unknown.  If
198  * the object was written out to persistent storage, all state about it can be
199  * recovered by loading the object back in.  The object must be locked before
200  * calling this function. */
201 void bluesky_cloudlog_erase(BlueSkyCloudLog *log)
202 {
203     g_assert(log->data_lock_count == 0);
204
205     if (log->type == LOGTYPE_UNKNOWN)
206         return;
207
208     log->type = LOGTYPE_UNKNOWN;
209     log->data_size = 0;
210     bluesky_string_unref(log->data);
211     log->data = NULL;
212     log->data_lock_count = 0;
213
214     for (int i = 0; i < log->links->len; i++) {
215         BlueSkyCloudLog *c = g_array_index(log->links,
216                                            BlueSkyCloudLog *, i);
217         bluesky_cloudlog_unref(c);
218     }
219     g_array_unref(log->links);
220     log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
221 }
222
223 /* Start a write of the object to the local log. */
224 void bluesky_cloudlog_sync(BlueSkyCloudLog *log)
225 {
226     bluesky_log_item_submit(log, log->fs->log);
227 }
228
229 /* Add the given entry to the global hash table containing cloud log entries.
230  * Takes ownership of the caller's reference. */
231 void bluesky_cloudlog_insert_locked(BlueSkyCloudLog *log)
232 {
233     g_hash_table_insert(log->fs->locations, &log->id, log);
234 }
235
236 void bluesky_cloudlog_insert(BlueSkyCloudLog *log)
237 {
238     g_mutex_lock(log->fs->lock);
239     bluesky_cloudlog_insert_locked(log);
240     g_mutex_unlock(log->fs->lock);
241 }
242
243 /* Look up the cloud log entry for the given ID.  If create is TRUE and the
244  * item does not exist, create a special pending entry that can later be filled
245  * in when the real item is loaded.  The returned item has a reference held.
246  * As a special case, if a null ID is provided then NULL is returned. */
247 BlueSkyCloudLog *bluesky_cloudlog_get(BlueSkyFS *fs, BlueSkyCloudID id)
248 {
249     static BlueSkyCloudID id0 = {{0}};
250
251     if (memcmp(&id, &id0, sizeof(BlueSkyCloudID)) == 0)
252         return NULL;
253
254     g_mutex_lock(fs->lock);
255     BlueSkyCloudLog *item;
256     item = g_hash_table_lookup(fs->locations, &id);
257     if (item == NULL) {
258         item = bluesky_cloudlog_new(fs, &id);
259         bluesky_cloudlog_stats_update(item, 1);
260         bluesky_cloudlog_insert_locked(item);
261     } else {
262         bluesky_cloudlog_ref(item);
263     }
264     g_mutex_unlock(fs->lock);
265     return item;
266 }
267
268 /* Work to fetch a cloudlog item in a background thread.  The item will be
269  * locked while the fetch is in progress and unlocked when it completes. */
270 static GThreadPool *fetch_pool;
271
272 static void background_fetch_task(gpointer p, gpointer unused)
273 {
274     BlueSkyCloudLog *item = (BlueSkyCloudLog *)p;
275
276     g_mutex_lock(item->lock);
277     g_mutex_unlock(item->lock);
278     bluesky_cloudlog_unref(item);
279 }
280
281 void bluesky_cloudlog_background_fetch(BlueSkyCloudLog *item)
282 {
283     bluesky_cloudlog_ref(item);
284     g_thread_pool_push(fetch_pool, item, NULL);
285 }
286
287 /* Attempt to prefetch a cloud log item.  This does not guarantee that it will
288  * be made available, but does make it more likely that a future call to
289  * bluesky_cloudlog_fetch will complete quickly.  Item must be locked? */
290 void bluesky_cloudlog_prefetch(BlueSkyCloudLog *item)
291 {
292     if (item->data != NULL)
293         return;
294
295     /* When operating in a non log-structured mode, simply start a background
296      * fetch immediately when asked to prefetch. */
297     if (bluesky_options.disable_aggregation
298         || bluesky_options.disable_read_aggregation) {
299         bluesky_cloudlog_background_fetch(item);
300         return;
301     }
302
303     /* TODO: Some of the code here is duplicated with bluesky_log_map_object.
304      * Refactor to fix that. */
305     BlueSkyFS *fs = item->fs;
306     BlueSkyCacheFile *map = NULL;
307
308     /* First, check to see if the journal still contains a copy of the item and
309      * if so update the atime on the journal so it is likely to be kept around
310      * until we need it. */
311     if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
312         map = bluesky_cachefile_lookup(fs, -1, item->log_seq, TRUE);
313         if (map != NULL) {
314             map->atime = bluesky_get_current_time();
315             bluesky_cachefile_unref(map);
316             g_mutex_unlock(map->lock);
317             return;
318         }
319     }
320
321     item->location_flags &= ~CLOUDLOG_JOURNAL;
322     if (!(item->location_flags & CLOUDLOG_CLOUD))
323         return;
324
325     map = bluesky_cachefile_lookup(fs,
326                                    item->location.directory,
327                                    item->location.sequence,
328                                    FALSE);
329     if (map == NULL)
330         return;
331
332     /* At this point, we have information about the log segment containing the
333      * item we need.  If our item is already fetched, we have nothing to do
334      * except update the atime.  If not, queue up a fetch of our object. */
335     const BlueSkyRangesetItem *rangeitem;
336     rangeitem = bluesky_rangeset_lookup(map->items,
337                                         item->location.offset);
338     if (rangeitem == NULL) {
339         if (map->prefetches == NULL)
340             map->prefetches = bluesky_rangeset_new();
341
342         gchar *id = bluesky_cloudlog_id_to_string(item->id);
343         if (bluesky_verbose)
344             g_print("Need to prefetch %s\n", id);
345         g_free(id);
346
347         bluesky_rangeset_insert(map->prefetches,
348                                 item->location.offset,
349                                 item->location.size, NULL);
350
351         uint64_t start, length;
352         bluesky_rangeset_get_extents(map->prefetches, &start, &length);
353         if (bluesky_verbose)
354             g_print("Range to prefetch: %"PRIu64" + %"PRIu64"\n",
355                     start, length);
356     }
357
358     bluesky_cachefile_unref(map);
359     g_mutex_unlock(map->lock);
360 }
361
362 /* Ensure that a cloud log item is loaded in memory, and if not read it in.
363  * TODO: Make asynchronous, and make this also fetch from the cloud.  Right now
364  * we only read from the log.  Log item must be locked. */
365 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log)
366 {
367     if (log->data != NULL)
368         return;
369
370     BlueSkyProfile *profile = bluesky_profile_get();
371     if (profile != NULL)
372         bluesky_profile_add_event(profile, g_strdup_printf("Fetch log entry"));
373
374     /* There are actually two cases: a full deserialization if we have not ever
375      * read the object before, and a partial deserialization where the metadata
376      * is already in memory and we just need to remap the data.  If the object
377      * type has not yet been set, we'll need to read and parse the metadata.
378      * Once that is done, we can fall through the case of remapping the data
379      * itself. */
380     if (log->type == LOGTYPE_UNKNOWN) {
381         BlueSkyRCStr *raw = bluesky_log_map_object(log, FALSE);
382         g_assert(raw != NULL);
383         bluesky_deserialize_cloudlog(log, raw->data, raw->len);
384         bluesky_string_unref(raw);
385     }
386
387     /* At this point all metadata should be available and we need only remap
388      * the object data. */
389     log->data = bluesky_log_map_object(log, TRUE);
390
391     if (log->data == NULL) {
392         g_error("Unable to fetch cloudlog entry!");
393     }
394
395     if (profile != NULL)
396         bluesky_profile_add_event(profile, g_strdup_printf("Fetch complete"));
397     g_cond_broadcast(log->cond);
398 }
399
400 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
401                                                BlueSkyFS *fs)
402 {
403     BlueSkyCloudLogState *state = fs->log_state;
404
405     if ((log->location_flags | log->pending_write) & CLOUDLOG_CLOUD) {
406         return log->location;
407     }
408
409     for (int i = 0; i < log->links->len; i++) {
410         BlueSkyCloudLog *ref = g_array_index(log->links,
411                                              BlueSkyCloudLog *, i);
412         if (ref != NULL)
413             bluesky_cloudlog_serialize(ref, fs);
414     }
415
416     /* FIXME: Ought lock to be taken earlier? */
417     g_mutex_lock(log->lock);
418     bluesky_cloudlog_fetch(log);
419     g_assert(log->data != NULL);
420
421     bluesky_cloudlog_stats_update(log, -1);
422
423     GString *data1 = g_string_new("");
424     GString *data2 = g_string_new("");
425     GString *data3 = g_string_new("");
426     bluesky_serialize_cloudlog(log, data1, data2, data3);
427
428     log->location = state->location;
429     log->location.offset = state->data->len;
430     log->data_size = data1->len;
431
432     struct cloudlog_header header;
433     memcpy(header.magic, CLOUDLOG_MAGIC, 4);
434     memset(header.crypt_auth, sizeof(header.crypt_auth), 0);
435     memset(header.crypt_iv, sizeof(header.crypt_iv), 0);
436     header.type = log->type + '0';
437     header.size1 = GUINT32_TO_LE(data1->len);
438     header.size2 = GUINT32_TO_LE(data2->len);
439     header.size3 = GUINT32_TO_LE(data3->len);
440     header.id = log->id;
441     header.inum = GUINT64_TO_LE(log->inum);
442
443     g_string_append_len(state->data, (const char *)&header, sizeof(header));
444     g_string_append_len(state->data, data1->str, data1->len);
445     g_string_append_len(state->data, data2->str, data2->len);
446     g_string_append_len(state->data, data3->str, data3->len);
447
448     log->location.size = state->data->len - log->location.offset;
449
450     g_string_free(data1, TRUE);
451     g_string_free(data2, TRUE);
452     g_string_free(data3, TRUE);
453
454     /* If the object we flushed was an inode, update the inode map. */
455     if (log->type == LOGTYPE_INODE) {
456         g_mutex_lock(fs->lock);
457         InodeMapEntry *entry = bluesky_inode_map_lookup(fs->inode_map,
458                                                         log->inum, 1);
459         bluesky_cloudlog_unref_delayed(entry->item);
460         entry->item = log;
461         bluesky_cloudlog_ref(entry->item);
462         g_mutex_unlock(fs->lock);
463     }
464
465     /* TODO: We should mark the objects as committed on the cloud until the
466      * data is flushed and acknowledged. */
467     log->pending_write |= CLOUDLOG_CLOUD;
468     bluesky_cloudlog_stats_update(log, 1);
469     state->writeback_list = g_slist_prepend(state->writeback_list, log);
470     bluesky_cloudlog_ref(log);
471     g_mutex_unlock(log->lock);
472
473     if (state->data->len > CLOUDLOG_SEGMENT_SIZE
474         || bluesky_options.disable_aggregation)
475     {
476         bluesky_cloudlog_flush(fs);
477     }
478
479     return log->location;
480 }
481
482 static void cloudlog_flush_complete(BlueSkyStoreAsync *async,
483                                     SerializedRecord *record)
484 {
485     g_print("Write of %s to cloud complete, status = %d\n",
486             async->key, async->result);
487
488     g_mutex_lock(record->lock);
489     if (async->result >= 0) {
490         while (record->items != NULL) {
491             BlueSkyCloudLog *item = (BlueSkyCloudLog *)record->items->data;
492             g_mutex_lock(item->lock);
493             bluesky_cloudlog_stats_update(item, -1);
494             item->pending_write &= ~CLOUDLOG_CLOUD;
495             item->location_flags |= CLOUDLOG_CLOUD;
496             bluesky_cloudlog_stats_update(item, 1);
497             g_mutex_unlock(item->lock);
498             bluesky_cloudlog_unref(item);
499
500             record->items = g_slist_delete_link(record->items, record->items);
501         }
502
503         bluesky_string_unref(record->data);
504         record->data = NULL;
505         g_slist_free(record->items);
506         record->items = NULL;
507         record->complete = TRUE;
508
509         BlueSkyCloudLogState *state = record->fs->log_state;
510         g_mutex_lock(state->uploads_pending_lock);
511         state->uploads_pending--;
512         g_cond_broadcast(state->uploads_pending_cond);
513         g_mutex_unlock(state->uploads_pending_lock);
514
515         g_cond_broadcast(record->cond);
516     } else {
517         g_print("Write should be resubmitted...\n");
518
519         BlueSkyStoreAsync *async2 = bluesky_store_async_new(async->store);
520         async2->op = STORE_OP_PUT;
521         async2->key = g_strdup(async->key);
522         async2->data = record->data;
523         async2->profile = async->profile;
524         bluesky_string_ref(record->data);
525         bluesky_store_async_submit(async2);
526         bluesky_store_async_add_notifier(async2,
527                                          (GFunc)cloudlog_flush_complete,
528                                          record);
529         bluesky_store_async_unref(async2);
530     }
531     g_mutex_unlock(record->lock);
532 }
533
534 /* Finish up a partially-written cloud log segment and flush it to storage. */
535 static void cloud_flush_background(SerializedRecord *record)
536 {
537     bluesky_cloudlog_encrypt(record->raw_data, record->fs->keys);
538     record->data = bluesky_string_new_from_gstring(record->raw_data);
539     record->raw_data = NULL;
540
541     BlueSkyStoreAsync *async = bluesky_store_async_new(record->fs->store);
542     async->op = STORE_OP_PUT;
543     async->key = record->key;
544     async->data = record->data;
545     bluesky_string_ref(record->data);
546     bluesky_store_async_submit(async);
547     bluesky_store_async_add_notifier(async,
548                                      (GFunc)cloudlog_flush_complete,
549                                      record);
550     bluesky_store_async_unref(async);
551 }
552
553 void bluesky_cloudlog_flush(BlueSkyFS *fs)
554 {
555     BlueSkyCloudLogState *state = fs->log_state;
556     if (state->data == NULL || state->data->len == 0)
557         return;
558
559     g_mutex_lock(state->uploads_pending_lock);
560     while (state->uploads_pending > cloudlog_concurrent_uploads)
561         g_cond_wait(state->uploads_pending_cond, state->uploads_pending_lock);
562     state->uploads_pending++;
563     g_mutex_unlock(state->uploads_pending_lock);
564
565     /* TODO: Append some type of commit record to the log segment? */
566
567     g_print("Serializing %zd bytes of data to cloud\n", state->data->len);
568     SerializedRecord *record = g_new0(SerializedRecord, 1);
569     record->fs = fs;
570     record->raw_data = state->data;
571     record->data = NULL;
572     record->items = state->writeback_list;
573     record->lock = g_mutex_new();
574     record->cond = g_cond_new();
575     state->writeback_list = NULL;
576
577     record->key = g_strdup_printf("log-%08d-%08d",
578                                   state->location.directory,
579                                   state->location.sequence);
580
581     state->pending_segments = g_list_prepend(state->pending_segments, record);
582
583     /* Encryption of data and upload happen in the background, for additional
584      * parallelism when uploading large amounts of data. */
585     g_thread_create((GThreadFunc)cloud_flush_background, record, FALSE, NULL);
586
587     state->location.sequence++;
588     state->location.offset = 0;
589     state->data = g_string_new("");
590 }
591
592 /* Make an encryption pass over a cloud log segment to encrypt private data in
593  * it. */
594 void bluesky_cloudlog_encrypt(GString *segment, BlueSkyCryptKeys *keys)
595 {
596     char *data = segment->str;
597     size_t remaining_size = segment->len;
598
599     while (remaining_size >= sizeof(struct cloudlog_header)) {
600         struct cloudlog_header *header = (struct cloudlog_header *)data;
601         size_t item_size = sizeof(struct cloudlog_header)
602                            + GUINT32_FROM_LE(header->size1)
603                            + GUINT32_FROM_LE(header->size2)
604                            + GUINT32_FROM_LE(header->size3);
605         if (item_size > remaining_size)
606             break;
607         bluesky_crypt_block_encrypt(data, item_size, keys);
608
609         data += item_size;
610         remaining_size -= item_size;
611     }
612 }
613
614 /* Make an decryption pass over a cloud log segment to decrypt items which were
615  * encrypted.  Also computes a list of all offsets which at which valid
616  * cloud log items are found and adds those offsets to items (if non-NULL).
617  *
618  * If allow_unauth is set to true, then allow a limited set of unauthenticated
619  * items that may have been rewritten by a file system cleaner.  These include
620  * the checkpoint and inode map records only; other items must still pass
621  * authentication. */
622 void bluesky_cloudlog_decrypt(char *segment, size_t len,
623                               BlueSkyCryptKeys *keys,
624                               BlueSkyRangeset *items,
625                               gboolean allow_unauth)
626 {
627     char *data = segment;
628     size_t remaining_size = len;
629     size_t offset = 0;
630
631     while (remaining_size >= sizeof(struct cloudlog_header)) {
632         struct cloudlog_header *header = (struct cloudlog_header *)data;
633         size_t item_size = sizeof(struct cloudlog_header)
634                            + GUINT32_FROM_LE(header->size1)
635                            + GUINT32_FROM_LE(header->size2)
636                            + GUINT32_FROM_LE(header->size3);
637         if (item_size > remaining_size)
638             break;
639         if (bluesky_crypt_block_decrypt(data, item_size, keys, allow_unauth)) {
640             if (items != NULL) {
641                 if (bluesky_verbose)
642                     g_print("  data item at %zx\n", offset);
643                 bluesky_rangeset_insert(items, offset, item_size,
644                                         GINT_TO_POINTER(TRUE));
645             }
646         } else {
647             g_warning("Unauthenticated data at offset %zd", offset);
648             if (items != NULL) {
649                 bluesky_rangeset_insert(items, offset, item_size,
650                                         GINT_TO_POINTER(TRUE));
651             }
652         }
653
654         data += item_size;
655         offset += item_size;
656         remaining_size -= item_size;
657     }
658 }
659
660 void bluesky_cloudlog_threads_init(BlueSkyFS *fs)
661 {
662     fs->unref_queue = g_async_queue_new();
663     g_thread_create(cloudlog_unref_thread, fs->unref_queue, FALSE, NULL);
664     fetch_pool = g_thread_pool_new(background_fetch_task, NULL, 40, FALSE,
665                                    NULL);
666 }