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