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