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