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