Rework caching of data blocks to eliminate double-caching.
[bluesky.git] / bluesky / bluesky.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 #ifndef _BLUESKY_H
10 #define _BLUESKY_H
11
12 #include <stdint.h>
13 #include <inttypes.h>
14 #include <glib.h>
15
16 #ifdef __cplusplus
17 extern "C" {
18 #endif
19
20 /* Various options to tweak for performance benchmarking purposes. */
21 typedef struct {
22     /* Perform all get/put operations synchronously. */
23     int synchronous_stores;
24
25     /* Write data in cache immediately after file is modified. */
26     int writethrough_cache;
27
28     /* Can inodes be fetched asynchronously?  (Inode object is initially
29      * created in a pending state, and not unlocked until the data is actually
30      * available.) */
31     int sync_inode_fetches;
32
33     /* Should frontends handle requests serially or allow operations to proceed
34      * in parallel? */
35     int sync_frontends;
36 } BlueSkyOptions;
37
38 extern BlueSkyOptions bluesky_options;
39
40 /* Maximum number of threads to use in any particular thread pool, or -1 for no
41  * limit */
42 extern int bluesky_max_threads;
43
44 /* A general-purpose counter for gathering run-time statistics. */
45 struct bluesky_stats {
46     const char *name;
47     int64_t count;
48     int64_t sum;
49 };
50 struct bluesky_stats *bluesky_stats_new(const char *name);
51 void bluesky_stats_add(struct bluesky_stats *stats, int64_t value);
52 void bluesky_stats_dump_all();
53
54 /* BlueSky status and error codes.  Various frontends should translate these to
55  * the appropriate error code for whatever protocol they implement. */
56 typedef enum {
57     BSTATUS_OK = 0,             /* No error */
58     BSTATUS_IOERR,              /* I/O error of some form */
59     BSTATUS_NOENT,              /* File does not exist */
60 } BlueSkyStatus;
61
62 void bluesky_init(void);
63
64 gchar *bluesky_lowercase(const gchar *s);
65
66 struct _BlueSkyMmap;
67 typedef struct _BlueSkyMmap BlueSkyMmap;
68
69 typedef struct {
70     gint refcount;
71     BlueSkyMmap *mmap;
72     gchar *data;
73     gsize len;
74 } BlueSkyRCStr;
75
76 BlueSkyRCStr *bluesky_string_new(gpointer data, gsize len);
77 BlueSkyRCStr *bluesky_string_new_from_gstring(GString *s);
78 BlueSkyRCStr *bluesky_string_new_from_mmap(BlueSkyMmap *mmap,
79                                            int offset, gsize len);
80 void bluesky_string_ref(BlueSkyRCStr *string);
81 void bluesky_string_unref(BlueSkyRCStr *string);
82 BlueSkyRCStr *bluesky_string_dup(BlueSkyRCStr *string);
83 void bluesky_string_resize(BlueSkyRCStr *string, gsize len);
84
85 /* Cryptographic operations. */
86 #define CRYPTO_BLOCK_SIZE 16        /* 128-bit AES */
87 #define CRYPTO_KEY_SIZE   16
88
89 void bluesky_crypt_init();
90 void bluesky_crypt_hash_key(const char *keystr, uint8_t *out);
91 void bluesky_crypt_random_bytes(guchar *buf, gint len);
92 BlueSkyRCStr *bluesky_crypt_encrypt(BlueSkyRCStr *in, const uint8_t *key);
93 BlueSkyRCStr *bluesky_crypt_decrypt(BlueSkyRCStr *in, const uint8_t *key);
94
95 /* Storage interface.  This presents a key-value store abstraction, and can
96  * have multiple implementations: in-memory, on-disk, in-cloud. */
97 struct _BlueSkyStore;
98 typedef struct _BlueSkyStore BlueSkyStore;
99
100 struct _BlueSkyLog;
101 typedef struct _BlueSkyLog BlueSkyLog;
102
103 struct _BlueSkyCloudLogState;
104 typedef struct _BlueSkyCloudLogState BlueSkyCloudLogState;
105
106 struct _BlueSkyCloudLog;
107 typedef struct _BlueSkyCloudLog BlueSkyCloudLog;
108
109 void bluesky_store_init();
110 BlueSkyStore *bluesky_store_new(const gchar *type);
111 void bluesky_store_free(BlueSkyStore *store);
112 BlueSkyRCStr *bluesky_store_get(BlueSkyStore *store, const gchar *key);
113 void bluesky_store_put(BlueSkyStore *store,
114                        const gchar *key, BlueSkyRCStr *val);
115
116 /* File types.  The numeric values are chosen to match with those used in
117  * NFSv3. */
118 typedef enum {
119     BLUESKY_REGULAR = 1,
120     BLUESKY_DIRECTORY = 2,
121     BLUESKY_BLOCK = 3,
122     BLUESKY_CHARACTER = 4,
123     BLUESKY_SYMLINK = 5,
124     BLUESKY_SOCKET = 6,
125     BLUESKY_FIFO = 7,
126
127     /* Special types used only internally. */
128     BLUESKY_PENDING = 0,    /* Inode being loaded; type not yet determined */
129     BLUESKY_INVALID = -1,   /* Inode is invalid (failed to load) */
130 } BlueSkyFileType;
131
132 /* Filesystem state.  Each filesystem which is exported is represented by a
133  * single bluesky_fs structure in memory. */
134 typedef struct {
135     GMutex *lock;
136
137     gchar *name;                /* Descriptive name for the filesystem */
138     GHashTable *inodes;         /* Cached inodes */
139     uint64_t next_inum;         /* Next available inode for allocation */
140
141     BlueSkyStore *store;
142     BlueSkyLog *log;
143     BlueSkyCloudLogState *log_state;
144
145     /* Accounting for memory used for caches.  Space is measured in blocks, not
146      * bytes.  We track both total data in the caches and dirty data (total
147      * data includes dirty data).  Updates to these variables must be made
148      * atomically. */
149     gint cache_total, cache_dirty;
150
151     /* Linked list of inodes, sorted by access/modification times for cache
152      * management.  Editing these lists is protected by the filesystem lock; to
153      * avoid deadlock do not attempt to take any other locks while the FS lock
154      * is held for list editing purposes.  Items at the head of the list are
155      * most recently accessed/modified. */
156     GList unlogged_list;        // Changes not yet synced to journal
157     GList dirty_list;           // Not yet written to cloud storage
158     GList accessed_list;        // All in-memory inodes
159
160     /* Mutex for the flush daemon, to prevent concurrent execution. */
161     GMutex *flushd_lock;
162
163     /* Mapping of object identifiers (blocks, inodes) to physical location (in
164      * the local cache or in the logs in the cloud). */
165     GHashTable *locations;
166 } BlueSkyFS;
167
168 /* Inode number of the root directory. */
169 #define BLUESKY_ROOT_INUM 1
170
171 /* Timestamp, measured in microseconds since the Unix epoch. */
172 typedef int64_t bluesky_time;
173
174 /* High-resolution timer, measured in nanoseconds. */
175 typedef int64_t bluesky_time_hires;
176 bluesky_time_hires bluesky_now_hires();
177
178 /* In-memory representation of an inode within a Blue Sky server.  This
179  * corresponds roughly with information that is committed to persistent
180  * storage.  Locking/refcounting rules:
181  *   - To access or modify any data fields, the lock must be held.  This
182  *     includes file blocks.
183  *   - One reference is held by the BlueSkyFS inode hash table.  If that is the
184  *     only reference (and the inode is unlocked), the inode is subject to
185  *     dropping from the cache.
186  *   - Any pending operations should hold extra references to the inode as
187  *     appropriate to keep it available until the operation completes.
188  *   - Locking dependency order is, when multiple locks are to be acquired, to
189  *     acquire locks on parents in the filesystem tree before children.
190  *     (TODO: What about rename when we acquire locks in unrelated parts of the
191  *     filesystem?)
192  *   - An inode should not be locked while the filesystem lock is already held,
193  *     since some code may do an inode lookup (which acquires the filesystem
194  *     lock) while a different inode is locked.
195  * */
196 typedef struct {
197     GMutex *lock;
198     gint refcount;
199
200     BlueSkyFS *fs;
201
202     BlueSkyFileType type;
203     uint32_t mode;
204     uint32_t uid, gid;
205     uint32_t nlink;
206
207     /* Rather than track an inode number and generation number, we will simply
208      * never re-use a fileid after a file is deleted.  64 bits should be enough
209      * that we don't exhaust the identifier space. */
210     uint64_t inum;
211
212     /* change_count is increased with every operation which modifies the inode,
213      * and can be used to determine if cached data is still valid.
214      * change_commit is the value of change_count when the inode was last
215      * committed to stable storage (the log).
216      * change_cloud tracks which version was last commited to cloud storage. */
217     uint64_t change_count, change_commit, change_cloud;
218
219     /* Timestamp for controlling when modified data is flushed to stable
220      * storage.  When an inode is first modified from a clean state, this is
221      * set to the current time.  If the inode is clean, it is set to zero. */
222     int64_t change_time;
223
224     /* Last access time to this inode, for controlling cache evictions. */
225     int64_t access_time;
226
227     /* Version of the object last serialized and committed to storage. */
228     BlueSkyCloudLog *committed_item;
229
230     /* Pointers to the linked-list elements for this inode in the accessed and
231      * dirty linked lists.  We re-use the GList structure, using ->next to
232      * point to the head of the list and ->prev to point to the tail.  The data
233      * element is unused. */
234     GList *unlogged_list, *accessed_list, *dirty_list;
235
236     int64_t atime;              /* Microseconds since the Unix epoch */
237     int64_t ctime;
238     int64_t mtime;
239     int64_t ntime;              /* "new time": time object was created */
240
241     /* File-specific fields */
242     uint64_t size;
243     GArray *blocks;
244
245     /* Directory-specific fields */
246     GSequence *dirents;         /* List of entries for READDIR */
247     GHashTable *dirhash;        /* Hash table by name for LOOKUP */
248     GHashTable *dirhash_folded; /* As above, but case-folded */
249     uint64_t parent_inum;       /* inode for ".."; 0 if the root directory */
250
251     /* Symlink-specific fields */
252     gchar *symlink_contents;
253 } BlueSkyInode;
254
255 /* A directory entry.  The name is UTF-8 and is a freshly-allocated string.
256  * Each directory entry is listed in two indices: dirents is indexed by cookie
257  * and dirhash by name.  The cookie is a randomly-assigned 32-bit value, unique
258  * within the directory, that remains unchanged until the entry is deleted.  It
259  * is used to provide a stable key for restarting a READDIR call. */
260 typedef struct {
261     gchar *name;
262     gchar *name_folded;         /* Name, folded for case-insensitive lookup */
263     uint32_t cookie;
264     uint64_t inum;
265 } BlueSkyDirent;
266
267 /* File data is divided into fixed-size blocks (except the last block which may
268  * be short?).  These blocks are backed by storage in a key/value store, but
269  * may also be dirty if modifications have been made in-memory that have not
270  * been committed. */
271 #define BLUESKY_BLOCK_SIZE 32768ULL
272 #define BLUESKY_MAX_FILE_SIZE (BLUESKY_BLOCK_SIZE << 24)
273 typedef enum {
274     BLUESKY_BLOCK_ZERO = 0,     /* Data is all zeroes, not explicitly stored */
275     BLUESKY_BLOCK_REF = 1,      /* Reference to cloud log item, data clean */
276     BLUESKY_BLOCK_DIRTY = 2,    /* Data needs to be committed to store */
277 } BlueSkyBlockType;
278
279 typedef struct {
280     BlueSkyBlockType type;
281     BlueSkyCloudLog *ref;       /* if REF: cloud log entry with data */
282     BlueSkyRCStr *dirty;        /* if DIRTY: raw data in memory */
283 } BlueSkyBlock;
284
285 BlueSkyFS *bluesky_init_fs(gchar *name, BlueSkyStore *store);
286 void bluesky_superblock_flush(BlueSkyFS *fs);
287
288 gboolean bluesky_inode_is_ready(BlueSkyInode *inode);
289
290 int64_t bluesky_get_current_time();
291 void bluesky_inode_update_ctime(BlueSkyInode *inode, gboolean update_mtime);
292 uint64_t bluesky_fs_alloc_inode(BlueSkyFS *fs);
293 void bluesky_init_inode(BlueSkyInode *i, BlueSkyFileType type);
294 BlueSkyInode *bluesky_new_inode(uint64_t inum, BlueSkyFS *fs, BlueSkyFileType type);
295
296 BlueSkyInode *bluesky_get_inode(BlueSkyFS *fs, uint64_t inum);
297 void bluesky_inode_ref(BlueSkyInode *inode);
298 void bluesky_inode_unref(BlueSkyInode *inode);
299 void bluesky_insert_inode(BlueSkyFS *fs, BlueSkyInode *inode);
300
301 void bluesky_dirent_destroy(gpointer dirent);
302 uint64_t bluesky_directory_lookup(BlueSkyInode *inode, gchar *name);
303 uint64_t bluesky_directory_ilookup(BlueSkyInode *inode, gchar *name);
304 BlueSkyDirent *bluesky_directory_read(BlueSkyInode *dir, uint32_t cookie);
305 gboolean bluesky_directory_insert(BlueSkyInode *dir, const gchar *name,
306                                   uint64_t inum);
307 void bluesky_directory_dump(BlueSkyInode *dir);
308
309 void bluesky_file_truncate(BlueSkyInode *inode, uint64_t size);
310 void bluesky_file_write(BlueSkyInode *inode, uint64_t offset,
311                         const char *data, gint len);
312 void bluesky_file_read(BlueSkyInode *inode, uint64_t offset,
313                        char *buf, gint len);
314
315 void bluesky_inode_fetch(BlueSkyFS *fs, uint64_t inum);
316
317 gint bluesky_dirent_compare(gconstpointer a, gconstpointer b,
318                             gpointer unused);
319
320 void bluesky_flushd_invoke(BlueSkyFS *fs);
321 void bluesky_flushd_invoke_conditional(BlueSkyFS *fs);
322 void bluesky_inode_do_sync(BlueSkyInode *inode);
323 void bluesky_flushd_thread_launch(BlueSkyFS *fs);
324
325 void bluesky_debug_dump(BlueSkyFS *fs);
326
327 #ifdef __cplusplus
328 }
329 #endif
330
331 #endif