+BlueSkyFS *bluesky_init_fs(gchar *name, BlueSkyStore *store)
+{
+ BlueSkyRCStr *data = bluesky_store_get(store, "superblock");
+ if (data != NULL) {
+ BlueSkyFS *fs = bluesky_deserialize_superblock(data->data);
+ if (fs != NULL) {
+ fs->store = store;
+ g_print("Loaded filesystem superblock\n");
+ g_free(fs->name);
+ fs->name = g_strdup(name);
+ return fs;
+ }
+ bluesky_string_unref(data);
+ }
+
+ g_print("Initializing fresh filesystem\n");
+ BlueSkyFS *fs = bluesky_new_fs(name);
+ fs->store = store;
+
+ BlueSkyInode *root = bluesky_new_inode(BLUESKY_ROOT_INUM, fs,
+ BLUESKY_DIRECTORY);
+ root->nlink = 1;
+ root->mode = 0755;
+ bluesky_insert_inode(fs, root);
+ bluesky_inode_update_ctime(root, TRUE);
+
+ bluesky_inode_flush(fs, root);
+ bluesky_superblock_flush(fs);
+
+ return fs;
+}
+
+/* Inode reference counting. */
+void bluesky_inode_ref(BlueSkyInode *inode)
+{
+ g_atomic_int_inc(&inode->refcount);
+}
+
+void bluesky_inode_unref(BlueSkyInode *inode)
+{
+ if (g_atomic_int_dec_and_test(&inode->refcount)) {
+ if (bluesky_verbose) {
+ g_log("bluesky/inode", G_LOG_LEVEL_DEBUG,
+ "Reference count for inode %"PRIu64" dropped to zero.",
+ inode->inum);
+ }
+
+ /* Sanity check: Is the inode clean? */
+ if (inode->change_commit < inode->change_count
+ || inode->accessed_list != NULL
+ || inode->dirty_list != NULL) {
+ g_warning("Dropping inode which is not clean (commit %"PRIi64" < change %"PRIi64"; accessed_list = %p; dirty_list = %p)\n", inode->change_commit, inode->change_count, inode->accessed_list, inode->dirty_list);
+ }
+
+ /* These shouldn't be needed, but in case the above warning fires and
+ * we delete the inode anyway, we ought to be sure the inode is not on
+ * any LRU list. */
+ g_mutex_lock(inode->fs->lock);
+ bluesky_list_unlink(&inode->fs->accessed_list, inode->accessed_list);
+ bluesky_list_unlink(&inode->fs->dirty_list, inode->dirty_list);
+ g_mutex_unlock(inode->fs->lock);
+
+ /* Free file type specific data. It should be an error for there to be
+ * dirty data to commit when the reference count has reaches zero. */
+ switch (inode->type) {
+ case BLUESKY_REGULAR:
+ for (int i = 0; i < inode->blocks->len; i++) {
+ BlueSkyBlock *b = &g_array_index(inode->blocks,
+ BlueSkyBlock, i);
+ if (b->type == BLUESKY_BLOCK_DIRTY) {
+ g_error("Deleting an inode with dirty file data!");
+ }
+ g_free(b->ref);
+ bluesky_string_unref(b->data);
+ }
+ g_array_unref(inode->blocks);
+ break;
+
+ case BLUESKY_DIRECTORY:
+ g_hash_table_destroy(inode->dirhash);
+ g_hash_table_destroy(inode->dirhash_folded);
+ g_sequence_free(inode->dirents);
+ break;
+
+ case BLUESKY_SYMLINK:
+ g_free(inode->symlink_contents);
+ break;
+
+ default:
+ break;
+ }
+
+ g_mutex_free(inode->lock);
+
+ g_free(inode);
+ }
+}
+