Rework the checkpoint record format to include a version vector.
[bluesky.git] / bluesky / bluesky-private.h
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 /* Declarations internal to the BlueSky library.  This header file should not
10  * be included by any users of the library (such as any filesystem
11  * proxy)--external users should only include bluesky.h. */
12
13 #ifndef _BLUESKY_PRIVATE_H
14 #define _BLUESKY_PRIVATE_H
15
16 #include "bluesky.h"
17
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21
22 extern int bluesky_verbose;
23
24 /* Target cache size levels. */
25 extern int bluesky_watermark_low_dirty;
26 extern int bluesky_watermark_medium_dirty;
27 extern int bluesky_watermark_high_dirty;
28
29 extern int bluesky_watermark_low_total;
30 extern int bluesky_watermark_medium_total;
31 extern int bluesky_watermark_high_total;
32
33 /* TODO: Make this go away entirely. */
34 BlueSkyFS *bluesky_new_fs(gchar *name);
35
36 void bluesky_inode_free_resources(BlueSkyInode *inode);
37
38 /* Linked list update functions for LRU lists. */
39 void bluesky_list_unlink(GList *head, GList *item);
40 GList *bluesky_list_prepend(GList *head, BlueSkyInode *inode);
41 GList *bluesky_list_append(GList *head, BlueSkyInode *inode);
42 BlueSkyInode *bluesky_list_head(GList *head);
43 BlueSkyInode *bluesky_list_tail(GList *head);
44
45 /* Serialization and deserialization of filesystem data for storing to
46  * persistent storage. */
47 void bluesky_serialize_superblock(GString *out, BlueSkyFS *fs);
48 BlueSkyFS *bluesky_deserialize_superblock(const gchar *buf);
49 BlueSkyCloudLog *bluesky_serialize_inode(BlueSkyInode *inode);
50 gboolean bluesky_deserialize_inode(BlueSkyInode *inode, BlueSkyCloudLog *item);
51
52 void bluesky_deserialize_cloudlog(BlueSkyCloudLog *item,
53                                   const char *data,
54                                   size_t len);
55
56 void bluesky_serialize_cloudlog(BlueSkyCloudLog *log,
57                                 GString *encrypted,
58                                 GString *authenticated,
59                                 GString *writable);
60
61 /* Cryptographic operations. */
62 #define CRYPTO_BLOCK_SIZE 16        /* 128-bit AES */
63 #define CRYPTO_KEY_SIZE   16
64 #define CRYPTO_HASH_SIZE  32        /* SHA-256 */
65
66 typedef struct BlueSkyCryptKeys {
67     uint8_t encryption_key[CRYPTO_KEY_SIZE];
68     uint8_t authentication_key[CRYPTO_HASH_SIZE];
69 } BlueSkyCryptKeys;
70
71 void bluesky_crypt_init();
72 void bluesky_crypt_hash_key(const char *keystr, uint8_t *out);
73 void bluesky_crypt_random_bytes(guchar *buf, gint len);
74 void bluesky_crypt_derive_keys(BlueSkyCryptKeys *keys, const gchar *master);
75 BlueSkyRCStr *bluesky_crypt_encrypt(BlueSkyRCStr *in, const uint8_t *key);
76 BlueSkyRCStr *bluesky_crypt_decrypt(BlueSkyRCStr *in, const uint8_t *key);
77
78 void bluesky_crypt_block_encrypt(gchar *cloud_block, size_t len,
79                                  BlueSkyCryptKeys *keys);
80 gboolean bluesky_crypt_block_decrypt(gchar *cloud_block, size_t len,
81                                      BlueSkyCryptKeys *keys);
82 void bluesky_cloudlog_encrypt(GString *segment, BlueSkyCryptKeys *keys);
83 void bluesky_cloudlog_decrypt(char *segment, size_t len,
84                               BlueSkyCryptKeys *keys,
85                               BlueSkyRangeset *items);
86
87 /* Storage layer.  Requests can be performed asynchronously, so these objects
88  * help keep track of operations in progress. */
89 typedef enum {
90     STORE_OP_NONE,
91     STORE_OP_GET,
92     STORE_OP_PUT,
93     STORE_OP_DELETE,
94     STORE_OP_BARRIER,       // Waits for other selected operations to complete
95 } BlueSkyStoreOp;
96
97 typedef enum {
98     ASYNC_NEW,              // Operation not yet submitted to storage layer
99     ASYNC_PENDING,          // Submitted to storage layer
100     ASYNC_RUNNING,          // Operation is in progress
101     ASYNC_COMPLETE,         // Operation finished, results available
102 } BlueSkyAsyncStatus;
103
104 struct BlueSkyNotifierList;
105 typedef struct BlueSkyStoreAsync BlueSkyStoreAsync;
106 struct BlueSkyStoreAsync {
107     BlueSkyStore *store;
108
109     GMutex *lock;
110     GCond *completion_cond;     /* Used to wait for operation to complete. */
111
112     gint refcount;              /* Reference count for destruction. */
113
114     BlueSkyAsyncStatus status;
115
116     BlueSkyStoreOp op;
117     gchar *key;                 /* Key to read/write */
118     BlueSkyRCStr *data;         /* Data read/to write */
119
120     /* For range requests on reads: starting byte offset and length; len 0
121      * implies reading to the end of the object.  At completion, the backend
122      * should set range_done if a range read was made; if not set the entire
123      * object was read and the storage layer will select out just the
124      * appropriate bytes. */
125     size_t start, len;
126     gboolean range_done;
127
128     int result;                 /* Result code; 0 for success. */
129     struct BlueSkyNotifierList *notifiers;
130     gint notifier_count;
131
132     /* The barrier waiting on this operation.  Support for more than one
133      * barrier for a single async is not well-supported and should be avoided
134      * if possible. */
135     BlueSkyStoreAsync *barrier;
136
137     bluesky_time_hires start_time;  /* Time operation was submitted. */
138     bluesky_time_hires exec_time;   /* Time processing started on operation. */
139
140     gpointer store_private;     /* For use by the storage implementation */
141
142     /* If storage operations should be charged to any particular profile, which
143      * one? */
144     BlueSkyProfile *profile;
145 };
146
147 /* Support for notification lists.  These are lists of one-shot functions which
148  * can be called when certain events--primarily, competed storage
149  * events--occur.  Multiple notifiers can be added, but no particular order is
150  * guaranteed for the notification functions to be called. */
151 struct BlueSkyNotifierList {
152     struct BlueSkyNotifierList *next;
153     GFunc func;
154     BlueSkyStoreAsync *async;
155     gpointer user_data;     // Passed to the function when called
156 };
157
158 /* The abstraction layer for storage, allowing multiple implementations. */
159 typedef struct {
160     /* Create a new store instance and return a handle to it. */
161     gpointer (*create)(const gchar *path);
162
163     /* Clean up any resources used by this store. */
164     void (*destroy)(gpointer store);
165
166     /* Submit an operation (get/put/delete) to the storage layer to be
167      * performed asynchronously. */
168     void (*submit)(gpointer store, BlueSkyStoreAsync *async);
169
170     /* Clean up any implementation-private data in a BlueSkyStoreAsync. */
171     void (*cleanup)(gpointer store, BlueSkyStoreAsync *async);
172
173     /* Find the lexicographically-largest file starting with the specified
174      * prefix. */
175     char * (*lookup_last)(gpointer store, const gchar *prefix);
176 } BlueSkyStoreImplementation;
177
178 void bluesky_store_register(const BlueSkyStoreImplementation *impl,
179                             const gchar *name);
180
181 char *bluesky_store_lookup_last(BlueSkyStore *store, const char *prefix);
182 BlueSkyStoreAsync *bluesky_store_async_new(BlueSkyStore *store);
183 gpointer bluesky_store_async_get_handle(BlueSkyStoreAsync *async);
184 void bluesky_store_async_ref(BlueSkyStoreAsync *async);
185 void bluesky_store_async_unref(BlueSkyStoreAsync *async);
186 void bluesky_store_async_wait(BlueSkyStoreAsync *async);
187 void bluesky_store_async_add_notifier(BlueSkyStoreAsync *async,
188                                       GFunc func, gpointer user_data);
189 void bluesky_store_async_mark_complete(BlueSkyStoreAsync *async);
190 void bluesky_store_async_submit(BlueSkyStoreAsync *async);
191 void bluesky_store_sync(BlueSkyStore *store);
192
193 void bluesky_store_add_barrier(BlueSkyStoreAsync *barrier,
194                                BlueSkyStoreAsync *async);
195
196 void bluesky_inode_start_sync(BlueSkyInode *inode);
197
198 void bluesky_block_touch(BlueSkyInode *inode, uint64_t i);
199 void bluesky_block_fetch(BlueSkyInode *inode, BlueSkyBlock *block,
200                          BlueSkyStoreAsync *barrier);
201 void bluesky_block_flush(BlueSkyInode *inode, BlueSkyBlock *block,
202                          GList **log_items);
203 void bluesky_file_flush(BlueSkyInode *inode, GList **log_items);
204 void bluesky_file_drop_cached(BlueSkyInode *inode);
205
206 /* Writing of data to the cloud in log segments and tracking the location of
207  * various pieces of data (both where in the cloud and where cached locally).
208  * */
209
210 /* Eventually we'll want to support multiple writers.  But for now, hard-code
211  * separate namespaces in the cloud for the proxy and the cleaner to write to.
212  * */
213 #define BLUESKY_CLOUD_DIR_PRIMARY 0
214 #define BLUESKY_CLOUD_DIR_CLEANER 1
215
216 typedef struct {
217     char bytes[16];
218 } BlueSkyCloudID;
219
220 typedef struct {
221     uint32_t directory;
222     uint32_t sequence;
223     uint32_t offset;
224     uint32_t size;
225 } BlueSkyCloudPointer;
226
227 typedef enum {
228     LOGTYPE_INVALID = -1,
229     LOGTYPE_UNKNOWN = 0,
230     LOGTYPE_DATA = 1,
231     LOGTYPE_INODE = 2,
232     LOGTYPE_INODE_MAP = 3,
233     LOGTYPE_CHECKPOINT = 4,
234
235     /* Used only as metadata in the local journal, not loaded as a
236      * BlueSkyCloudLogState nor stored in the cloud */
237     LOGTYPE_JOURNAL_MARKER = 16,
238     LOGTYPE_JOURNAL_CHECKPOINT = 17,
239 } BlueSkyCloudLogType;
240
241 /* Headers that go on items in local log segments and cloud log segments. */
242 struct log_header {
243     uint32_t magic;             // HEADER_MAGIC
244     uint8_t type;               // Object type + '0'
245     uint32_t offset;            // Starting byte offset of the log header
246     uint32_t size1;             // Size of the data item (bytes)
247     uint32_t size2;             //
248     uint32_t size3;             //
249     uint64_t inum;              // Inode which owns this data, if any
250     BlueSkyCloudID id;          // Object identifier
251 } __attribute__((packed));
252
253 struct log_footer {
254     uint32_t magic;             // FOOTER_MAGIC
255     uint32_t crc;               // Computed from log_header to log_footer.magic
256 } __attribute__((packed));
257
258 struct cloudlog_header {
259     char magic[4];
260     uint8_t crypt_auth[CRYPTO_HASH_SIZE];
261     uint8_t crypt_iv[CRYPTO_BLOCK_SIZE];
262     uint8_t type;
263     BlueSkyCloudID id;
264     uint64_t inum;
265     uint32_t size1, size2, size3;
266 } __attribute__((packed));
267
268 #define JOURNAL_MAGIC "\nLog"
269 #define CLOUDLOG_MAGIC "AgI-"
270 #define CLOUDLOG_MAGIC_ENCRYPTED "AgI="     // CLOUDLOG_MAGIC[3] ^= 0x10
271
272 /* A record which tracks an object which has been written to a local log,
273  * cached, locally, and/or written to the cloud. */
274 #define CLOUDLOG_JOURNAL    0x01
275 #define CLOUDLOG_CLOUD      0x02
276 #define CLOUDLOG_CACHE      0x04
277 #define CLOUDLOG_UNCOMMITTED 0x10
278 struct BlueSkyCloudLog {
279     gint refcount;
280     GMutex *lock;
281     GCond *cond;
282
283     BlueSkyFS *fs;
284
285     BlueSkyCloudLogType type;
286
287     // Bitmask of CLOUDLOG_* flags indicating where the object exists.
288     int location_flags;
289     int pending_read, pending_write;
290
291     // A stable identifier for the object (only changes when authenticated data
292     // is written out, but stays the same when the in-cloud cleaner relocates
293     // the object).
294     BlueSkyCloudID id;
295
296     // The inode which owns this data, if any, and an offset.
297     uint64_t inum;
298     int32_t inum_offset;
299
300     // The size of encrypted object data, not including any headers
301     int data_size;
302
303     // The location of the object in the cloud, if available.
304     BlueSkyCloudPointer location;
305
306     // TODO: Location in journal/cache
307     int log_seq, log_offset, log_size;
308
309     // Pointers to other objects.  Each link counts towards the reference count
310     // of the pointed-to object.  To avoid memory leaks there should be no
311     // cycles in the reference graph.
312     GArray *links;
313
314     // Serialized data, if available in memory (otherwise NULL), and a lock
315     // count which tracks if there are users that require the data to be kept
316     // around.
317     BlueSkyRCStr *data;
318     int data_lock_count;
319 };
320
321 /* Serialize objects into a log segment to be written to the cloud. */
322 struct BlueSkyCloudLogState {
323     GString *data;
324     BlueSkyCloudPointer location;
325     GList *inode_list;
326     GSList *writeback_list;     // Items which are being serialized right now
327     GList *pending_segments;    // Segments which are being uploaded now
328
329     /* What is the most recent sequence number written by the cleaner which we
330      * have processed and incorporated into our own log?  This gets
331      * incorporated into the version vector written out with our checkpoint
332      * records. */
333     int latest_cleaner_seq_seen;
334 };
335
336 gboolean bluesky_cloudlog_equal(gconstpointer a, gconstpointer b);
337 guint bluesky_cloudlog_hash(gconstpointer a);
338 BlueSkyCloudLog *bluesky_cloudlog_new(BlueSkyFS *fs, const BlueSkyCloudID *id);
339 gchar *bluesky_cloudlog_id_to_string(BlueSkyCloudID id);
340 BlueSkyCloudID bluesky_cloudlog_id_from_string(const gchar *idstr);
341 void bluesky_cloudlog_threads_init(BlueSkyFS *fs);
342 void bluesky_cloudlog_ref(BlueSkyCloudLog *log);
343 void bluesky_cloudlog_unref(BlueSkyCloudLog *log);
344 void bluesky_cloudlog_unref_delayed(BlueSkyCloudLog *log);
345 void bluesky_cloudlog_erase(BlueSkyCloudLog *log);
346 void bluesky_cloudlog_stats_update(BlueSkyCloudLog *log, int type);
347 void bluesky_cloudlog_sync(BlueSkyCloudLog *log);
348 void bluesky_cloudlog_insert(BlueSkyCloudLog *log);
349 void bluesky_cloudlog_insert_locked(BlueSkyCloudLog *log);
350 BlueSkyCloudLog *bluesky_cloudlog_get(BlueSkyFS *fs, BlueSkyCloudID id);
351 void bluesky_cloudlog_prefetch(BlueSkyCloudLog *log);
352 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log);
353 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
354                                                BlueSkyFS *fs);
355 void bluesky_cloudlog_flush(BlueSkyFS *fs);
356
357 /* Logging infrastructure for ensuring operations are persistently recorded to
358  * disk. */
359 #define BLUESKY_CRC32C_SEED (~(uint32_t)0)
360 #define BLUESKY_CRC32C_VALIDATOR ((uint32_t)0xb798b438UL)
361 uint32_t crc32c(uint32_t crc, const char *buf, unsigned int length);
362 uint32_t crc32c_finalize(uint32_t crc);
363
364 struct BlueSkyLog {
365     BlueSkyFS *fs;
366     char *log_directory;
367     GAsyncQueue *queue;
368     int fd, dirfd;
369     int seq_num;
370     GSList *committed;
371
372     /* The currently-open log file. */
373     BlueSkyCacheFile *current_log;
374
375     /* Cache of log segments which have been memory-mapped. */
376     GMutex *mmap_lock;
377     GHashTable *mmap_cache;
378
379     /* A count of the disk space consumed (in 1024-byte units) by all files
380      * tracked by mmap_cache (whether mapped or not, actually). */
381     gint disk_used;
382
383     /* The smallest journal sequence number which may still contain data that
384      * must be preserved (since it it not yet in the cloud). */
385     int journal_watermark;
386 };
387
388 /* An object for tracking log files which are stored locally--either the
389  * journal for filesystem consistency or log segments which have been fetched
390  * back from cloud storage. */
391 struct BlueSkyCacheFile {
392     GMutex *lock;
393     GCond *cond;
394     gint refcount;
395     int type;                   // Only one of CLOUDLOG_{JOURNAL,CLOUD}
396     int log_dir;
397     int log_seq;
398     char *filename;             // Local filename, relateive to log directory
399     gint mapcount;              // References to the mmaped data
400     const char *addr;           // May be null if data is not mapped in memory
401     size_t len;
402     int disk_used;
403     BlueSkyFS *fs;
404     BlueSkyLog *log;
405     gboolean fetching, ready;   // Cloud data: downloading or ready for use
406     int64_t atime;              // Access time, for cache management
407     BlueSkyRangeset *items;     // Locations of valid items
408     BlueSkyRangeset *prefetches;// Locations we have been requested to prefetch
409 };
410
411 BlueSkyLog *bluesky_log_new(const char *log_directory);
412 void bluesky_log_item_submit(BlueSkyCloudLog *item, BlueSkyLog *log);
413 void bluesky_log_finish_all(GList *log_items);
414 BlueSkyCloudLog *bluesky_log_get_commit_point(BlueSkyFS *fs);
415 void bluesky_log_write_commit_point(BlueSkyFS *fs, BlueSkyCloudLog *marker);
416
417 BlueSkyRCStr *bluesky_log_map_object(BlueSkyCloudLog *item, gboolean map_data);
418 void bluesky_mmap_unref(BlueSkyCacheFile *mmap);
419 void bluesky_cachefile_unref(BlueSkyCacheFile *cachefile);
420
421 BlueSkyCacheFile *bluesky_cachefile_lookup(BlueSkyFS *fs,
422                                            int clouddir, int log_seq,
423                                            gboolean start_fetch);
424 void bluesky_cachefile_gc(BlueSkyFS *fs);
425
426 void bluesky_replay(BlueSkyFS *fs);
427
428 /* Used to track log segments that are being written to the cloud. */
429 typedef struct {
430     BlueSkyRCStr *data;
431     GSList *items;
432     GMutex *lock;
433     GCond *cond;
434     gboolean complete;
435 } SerializedRecord;
436
437 /***** Inode map management *****/
438
439 /* Mapping information for a single inode number.  These are grouped together
440  * into InodeMapRange objects. */
441 typedef struct {
442     uint64_t inum;
443
444     /* A pointer to the cloud log entry for this inode.  This may or may not
445      * actually have data loaded (it might just contain pointers to the data
446      * location, and in fact this will likely often be the case). */
447     BlueSkyCloudLog *item;
448 } InodeMapEntry;
449
450 typedef struct {
451     /* Starting and ending inode number values that fall in this section.
452      * Endpoint values are inclusive. */
453     uint64_t start, end;
454
455     /* A sorted list (by inode number) of InodeMapEntry objects. */
456     GSequence *map_entries;
457
458     /* The serialized version of the inode map data. */
459     BlueSkyCloudLog *serialized;
460
461     /* Have there been changes that require writing this section out again? */
462     gboolean dirty;
463 } InodeMapRange;
464
465 InodeMapEntry *bluesky_inode_map_lookup(GSequence *inode_map, uint64_t inum,
466                                         int action);
467 BlueSkyCloudLog *bluesky_inode_map_serialize(BlueSkyFS *fs);
468 void bluesky_inode_map_minimize(BlueSkyFS *fs);
469
470 gboolean bluesky_checkpoint_load(BlueSkyFS *fs);
471
472 #ifdef __cplusplus
473 }
474 #endif
475
476 #endif