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