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