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