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