1 #define _XOPEN_SOURCE 500
8 #include "kerncompat.h"
9 #include "radix-tree.h"
13 static int allocated_blocks = 0;
17 } __attribute__ ((__packed__));
19 static int get_free_block(struct ctree_root *root, u64 *block)
25 ret = fstat(root->fp, &st);
26 if (st.st_size > sizeof(struct ctree_header)) {
27 *block = (st.st_size -
28 sizeof(struct ctree_header)) / CTREE_BLOCKSIZE;
32 ret = ftruncate(root->fp, sizeof(struct ctree_header) + (*block + 1) *
37 struct tree_buffer *alloc_tree_block(struct ctree_root *root, u64 blocknr)
39 struct tree_buffer *buf;
41 buf = malloc(sizeof(struct tree_buffer));
45 buf->blocknr = blocknr;
47 radix_tree_preload(GFP_KERNEL);
48 ret = radix_tree_insert(&root->cache_radix, blocknr, buf);
49 radix_tree_preload_end();
57 struct tree_buffer *alloc_free_block(struct ctree_root *root)
61 struct tree_buffer * buf;
62 ret = get_free_block(root, &free_block);
67 buf = alloc_tree_block(root, free_block);
73 struct tree_buffer *read_tree_block(struct ctree_root *root, u64 blocknr)
75 loff_t offset = blocknr * CTREE_BLOCKSIZE + sizeof(struct ctree_header);
76 struct tree_buffer *buf;
79 buf = radix_tree_lookup(&root->cache_radix, blocknr);
82 if (buf->blocknr != blocknr)
84 if (buf->blocknr != buf->node.header.blocknr)
88 buf = alloc_tree_block(root, blocknr);
91 ret = pread(root->fp, &buf->node, CTREE_BLOCKSIZE, offset);
92 if (ret != CTREE_BLOCKSIZE) {
96 if (buf->blocknr != buf->node.header.blocknr)
101 int write_tree_block(struct ctree_root *root, struct tree_buffer *buf)
103 u64 blocknr = buf->blocknr;
104 loff_t offset = blocknr * CTREE_BLOCKSIZE + sizeof(struct ctree_header);
107 if (buf->blocknr != buf->node.header.blocknr)
109 ret = pwrite(root->fp, &buf->node, CTREE_BLOCKSIZE, offset);
110 if (ret != CTREE_BLOCKSIZE)
112 if (buf == root->node)
113 return update_root_block(root);
117 struct ctree_root *open_ctree(char *filename)
119 struct ctree_root *root = malloc(sizeof(struct ctree_root));
124 fp = open(filename, O_CREAT | O_RDWR);
130 INIT_RADIX_TREE(&root->cache_radix, GFP_KERNEL);
131 ret = pread(fp, &root_block, sizeof(u64), 0);
132 if (ret == sizeof(u64)) {
133 printf("reading root node at block %lu\n", root_block);
134 root->node = read_tree_block(root, root_block);
140 int close_ctree(struct ctree_root *root)
144 tree_block_release(root, root->node);
146 printf("on close %d blocks are allocated\n", allocated_blocks);
150 int update_root_block(struct ctree_root *root)
153 u64 root_block = root->node->blocknr;
155 ret = pwrite(root->fp, &root_block, sizeof(u64), 0);
156 if (ret != sizeof(u64))
161 void tree_block_release(struct ctree_root *root, struct tree_buffer *buf)
164 if (buf->count == 0) {
165 if (!radix_tree_lookup(&root->cache_radix, buf->blocknr))
167 radix_tree_delete(&root->cache_radix, buf->blocknr);
168 memset(buf, 0, sizeof(*buf));
170 BUG_ON(allocated_blocks == 0);