Subversion Repositories HelenOS-historic

Rev

Rev 1221 | Rev 1483 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 1221 Rev 1248
1
/*
1
/*
2
 * Copyright (C) 2006 Jakub Jermar
2
 * Copyright (C) 2006 Jakub Jermar
3
 * All rights reserved.
3
 * All rights reserved.
4
 *
4
 *
5
 * Redistribution and use in source and binary forms, with or without
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
6
 * modification, are permitted provided that the following conditions
7
 * are met:
7
 * are met:
8
 *
8
 *
9
 * - Redistributions of source code must retain the above copyright
9
 * - Redistributions of source code must retain the above copyright
10
 *   notice, this list of conditions and the following disclaimer.
10
 *   notice, this list of conditions and the following disclaimer.
11
 * - Redistributions in binary form must reproduce the above copyright
11
 * - Redistributions in binary form must reproduce the above copyright
12
 *   notice, this list of conditions and the following disclaimer in the
12
 *   notice, this list of conditions and the following disclaimer in the
13
 *   documentation and/or other materials provided with the distribution.
13
 *   documentation and/or other materials provided with the distribution.
14
 * - The name of the author may not be used to endorse or promote products
14
 * - The name of the author may not be used to endorse or promote products
15
 *   derived from this software without specific prior written permission.
15
 *   derived from this software without specific prior written permission.
16
 *
16
 *
17
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
 */
27
 */
28
 
28
 
29
/*
29
/**
-
 
30
 * @file    btree.c
-
 
31
 * @brief   B+tree implementation.
-
 
32
 *
-
 
33
 * This file implements B+tree type and operations.
-
 
34
 *
30
 * This B-tree has the following properties:
35
 * The B+tree has the following properties:
31
 * - it is a ballanced 3-4-5 tree (i.e. BTREE_M = 5)
36
 * @li it is a ballanced 3-4-5 tree (i.e. BTREE_M = 5)
32
 * - values (i.e. pointers to values) are stored only in leaves
37
 * @li values (i.e. pointers to values) are stored only in leaves
33
 * - leaves are linked in a list
38
 * @li leaves are linked in a list
34
 * - technically, it is a B+tree (because of the previous properties)
-
 
35
 *
39
 *
36
 * Be carefull when using these trees. They need to allocate
40
 * Be carefull when using these trees. They need to allocate
37
 * and deallocate memory for their index nodes and as such
41
 * and deallocate memory for their index nodes and as such
38
 * can sleep.
42
 * can sleep.
39
 */
43
 */
40
 
44
 
41
#include <adt/btree.h>
45
#include <adt/btree.h>
42
#include <adt/list.h>
46
#include <adt/list.h>
43
#include <mm/slab.h>
47
#include <mm/slab.h>
44
#include <debug.h>
48
#include <debug.h>
45
#include <panic.h>
49
#include <panic.h>
46
#include <typedefs.h>
50
#include <typedefs.h>
47
#include <print.h>
51
#include <print.h>
48
 
52
 
49
static void _btree_insert(btree_t *t, btree_key_t key, void *value, btree_node_t *rsubtree, btree_node_t *node);
53
static void _btree_insert(btree_t *t, btree_key_t key, void *value, btree_node_t *rsubtree, btree_node_t *node);
50
static void _btree_remove(btree_t *t, btree_key_t key, btree_node_t *node);
54
static void _btree_remove(btree_t *t, btree_key_t key, btree_node_t *node);
51
static void node_initialize(btree_node_t *node);
55
static void node_initialize(btree_node_t *node);
52
static void node_insert_key_and_lsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *lsubtree);
56
static void node_insert_key_and_lsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *lsubtree);
53
static void node_insert_key_and_rsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree);
57
static void node_insert_key_and_rsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree);
54
static void node_remove_key_and_lsubtree(btree_node_t *node, btree_key_t key);
58
static void node_remove_key_and_lsubtree(btree_node_t *node, btree_key_t key);
55
static void node_remove_key_and_rsubtree(btree_node_t *node, btree_key_t key);
59
static void node_remove_key_and_rsubtree(btree_node_t *node, btree_key_t key);
56
static btree_node_t *node_split(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree, btree_key_t *median);
60
static btree_node_t *node_split(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree, btree_key_t *median);
57
static btree_node_t *node_combine(btree_node_t *node);
61
static btree_node_t *node_combine(btree_node_t *node);
58
static index_t find_key_by_subtree(btree_node_t *node, btree_node_t *subtree, bool right);
62
static index_t find_key_by_subtree(btree_node_t *node, btree_node_t *subtree, bool right);
59
static void rotate_from_right(btree_node_t *lnode, btree_node_t *rnode, index_t idx);
63
static void rotate_from_right(btree_node_t *lnode, btree_node_t *rnode, index_t idx);
60
static void rotate_from_left(btree_node_t *lnode, btree_node_t *rnode, index_t idx);
64
static void rotate_from_left(btree_node_t *lnode, btree_node_t *rnode, index_t idx);
61
static bool try_insert_by_rotation_to_left(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree);
65
static bool try_insert_by_rotation_to_left(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree);
62
static bool try_insert_by_rotation_to_right(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree);
66
static bool try_insert_by_rotation_to_right(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree);
63
static bool try_rotation_from_left(btree_node_t *rnode);
67
static bool try_rotation_from_left(btree_node_t *rnode);
64
static bool try_rotation_from_right(btree_node_t *lnode);
68
static bool try_rotation_from_right(btree_node_t *lnode);
65
 
69
 
66
#define ROOT_NODE(n)        (!(n)->parent)
70
#define ROOT_NODE(n)        (!(n)->parent)
67
#define INDEX_NODE(n)       ((n)->subtree[0] != NULL)
71
#define INDEX_NODE(n)       ((n)->subtree[0] != NULL)
68
#define LEAF_NODE(n)        ((n)->subtree[0] == NULL)
72
#define LEAF_NODE(n)        ((n)->subtree[0] == NULL)
69
 
73
 
70
#define FILL_FACTOR     ((BTREE_M-1)/2)
74
#define FILL_FACTOR     ((BTREE_M-1)/2)
71
 
75
 
72
#define MEDIAN_LOW_INDEX(n) (((n)->keys-1)/2)
76
#define MEDIAN_LOW_INDEX(n) (((n)->keys-1)/2)
73
#define MEDIAN_HIGH_INDEX(n)    ((n)->keys/2)
77
#define MEDIAN_HIGH_INDEX(n)    ((n)->keys/2)
74
#define MEDIAN_LOW(n)       ((n)->key[MEDIAN_LOW_INDEX((n))]);
78
#define MEDIAN_LOW(n)       ((n)->key[MEDIAN_LOW_INDEX((n))]);
75
#define MEDIAN_HIGH(n)      ((n)->key[MEDIAN_HIGH_INDEX((n))]);
79
#define MEDIAN_HIGH(n)      ((n)->key[MEDIAN_HIGH_INDEX((n))]);
76
 
80
 
77
static slab_cache_t *btree_node_slab;
81
static slab_cache_t *btree_node_slab;
78
 
82
 
79
/** Initialize B-trees. */
83
/** Initialize B-trees. */
80
void btree_init(void)
84
void btree_init(void)
81
{
85
{
82
    btree_node_slab = slab_cache_create("btree_node_slab", sizeof(btree_node_t), 0, NULL, NULL, SLAB_CACHE_MAGDEFERRED);
86
    btree_node_slab = slab_cache_create("btree_node_slab", sizeof(btree_node_t), 0, NULL, NULL, SLAB_CACHE_MAGDEFERRED);
83
}
87
}
84
 
88
 
85
/** Create empty B-tree.
89
/** Create empty B-tree.
86
 *
90
 *
87
 * @param t B-tree.
91
 * @param t B-tree.
88
 */
92
 */
89
void btree_create(btree_t *t)
93
void btree_create(btree_t *t)
90
{
94
{
91
    list_initialize(&t->leaf_head);
95
    list_initialize(&t->leaf_head);
92
    t->root = (btree_node_t *) slab_alloc(btree_node_slab, 0);
96
    t->root = (btree_node_t *) slab_alloc(btree_node_slab, 0);
93
    node_initialize(t->root);
97
    node_initialize(t->root);
94
    list_append(&t->root->leaf_link, &t->leaf_head);
98
    list_append(&t->root->leaf_link, &t->leaf_head);
95
}
99
}
96
 
100
 
97
/** Destroy empty B-tree. */
101
/** Destroy empty B-tree. */
98
void btree_destroy(btree_t *t)
102
void btree_destroy(btree_t *t)
99
{
103
{
100
    ASSERT(!t->root->keys);
104
    ASSERT(!t->root->keys);
101
    slab_free(btree_node_slab, t->root);
105
    slab_free(btree_node_slab, t->root);
102
}
106
}
103
 
107
 
104
/** Insert key-value pair into B-tree.
108
/** Insert key-value pair into B-tree.
105
 *
109
 *
106
 * @param t B-tree.
110
 * @param t B-tree.
107
 * @param key Key to be inserted.
111
 * @param key Key to be inserted.
108
 * @param value Value to be inserted.
112
 * @param value Value to be inserted.
109
 * @param leaf_node Leaf node where the insertion should begin.
113
 * @param leaf_node Leaf node where the insertion should begin.
110
 */
114
 */
111
void btree_insert(btree_t *t, btree_key_t key, void *value, btree_node_t *leaf_node)
115
void btree_insert(btree_t *t, btree_key_t key, void *value, btree_node_t *leaf_node)
112
{
116
{
113
    btree_node_t *lnode;
117
    btree_node_t *lnode;
114
   
118
   
115
    ASSERT(value);
119
    ASSERT(value);
116
   
120
   
117
    lnode = leaf_node;
121
    lnode = leaf_node;
118
    if (!lnode) {
122
    if (!lnode) {
119
        if (btree_search(t, key, &lnode)) {
123
        if (btree_search(t, key, &lnode)) {
120
            panic("B-tree %p already contains key %d\n", t, key);
124
            panic("B-tree %p already contains key %d\n", t, key);
121
        }
125
        }
122
    }
126
    }
123
   
127
   
124
    _btree_insert(t, key, value, NULL, lnode);
128
    _btree_insert(t, key, value, NULL, lnode);
125
}
129
}
126
 
130
 
127
/** Recursively insert into B-tree.
131
/** Recursively insert into B-tree.
128
 *
132
 *
129
 * @param t B-tree.
133
 * @param t B-tree.
130
 * @param key Key to be inserted.
134
 * @param key Key to be inserted.
131
 * @param value Value to be inserted.
135
 * @param value Value to be inserted.
132
 * @param rsubtree Right subtree of the inserted key.
136
 * @param rsubtree Right subtree of the inserted key.
133
 * @param node Start inserting into this node.
137
 * @param node Start inserting into this node.
134
 */
138
 */
135
void _btree_insert(btree_t *t, btree_key_t key, void *value, btree_node_t *rsubtree, btree_node_t *node)
139
void _btree_insert(btree_t *t, btree_key_t key, void *value, btree_node_t *rsubtree, btree_node_t *node)
136
{
140
{
137
    if (node->keys < BTREE_MAX_KEYS) {
141
    if (node->keys < BTREE_MAX_KEYS) {
138
        /*
142
        /*
139
         * Node conatins enough space, the key can be stored immediately.
143
         * Node conatins enough space, the key can be stored immediately.
140
         */
144
         */
141
        node_insert_key_and_rsubtree(node, key, value, rsubtree);
145
        node_insert_key_and_rsubtree(node, key, value, rsubtree);
142
    } else if (try_insert_by_rotation_to_left(node, key, value, rsubtree)) {
146
    } else if (try_insert_by_rotation_to_left(node, key, value, rsubtree)) {
143
        /*
147
        /*
144
         * The key-value-rsubtree triplet has been inserted because
148
         * The key-value-rsubtree triplet has been inserted because
145
         * some keys could have been moved to the left sibling.
149
         * some keys could have been moved to the left sibling.
146
         */
150
         */
147
    } else if (try_insert_by_rotation_to_right(node, key, value, rsubtree)) {
151
    } else if (try_insert_by_rotation_to_right(node, key, value, rsubtree)) {
148
        /*
152
        /*
149
         * The key-value-rsubtree triplet has been inserted because
153
         * The key-value-rsubtree triplet has been inserted because
150
         * some keys could have been moved to the right sibling.
154
         * some keys could have been moved to the right sibling.
151
         */
155
         */
152
    } else {
156
    } else {
153
        btree_node_t *rnode;
157
        btree_node_t *rnode;
154
        btree_key_t median;
158
        btree_key_t median;
155
       
159
       
156
        /*
160
        /*
157
         * Node is full and both siblings (if both exist) are full too.
161
         * Node is full and both siblings (if both exist) are full too.
158
         * Split the node and insert the smallest key from the node containing
162
         * Split the node and insert the smallest key from the node containing
159
         * bigger keys (i.e. the new node) into its parent.
163
         * bigger keys (i.e. the new node) into its parent.
160
         */
164
         */
161
 
165
 
162
        rnode = node_split(node, key, value, rsubtree, &median);
166
        rnode = node_split(node, key, value, rsubtree, &median);
163
 
167
 
164
        if (LEAF_NODE(node)) {
168
        if (LEAF_NODE(node)) {
165
            list_prepend(&rnode->leaf_link, &node->leaf_link);
169
            list_prepend(&rnode->leaf_link, &node->leaf_link);
166
        }
170
        }
167
       
171
       
168
        if (ROOT_NODE(node)) {
172
        if (ROOT_NODE(node)) {
169
            /*
173
            /*
170
             * We split the root node. Create new root.
174
             * We split the root node. Create new root.
171
             */
175
             */
172
            t->root = (btree_node_t *) slab_alloc(btree_node_slab, 0);
176
            t->root = (btree_node_t *) slab_alloc(btree_node_slab, 0);
173
            node->parent = t->root;
177
            node->parent = t->root;
174
            rnode->parent = t->root;
178
            rnode->parent = t->root;
175
            node_initialize(t->root);
179
            node_initialize(t->root);
176
           
180
           
177
            /*
181
            /*
178
             * Left-hand side subtree will be the old root (i.e. node).
182
             * Left-hand side subtree will be the old root (i.e. node).
179
             * Right-hand side subtree will be rnode.
183
             * Right-hand side subtree will be rnode.
180
             */        
184
             */        
181
            t->root->subtree[0] = node;
185
            t->root->subtree[0] = node;
182
 
186
 
183
            t->root->depth = node->depth + 1;
187
            t->root->depth = node->depth + 1;
184
        }
188
        }
185
        _btree_insert(t, median, NULL, rnode, node->parent);
189
        _btree_insert(t, median, NULL, rnode, node->parent);
186
    }  
190
    }  
187
       
191
       
188
}
192
}
189
 
193
 
190
/** Remove B-tree node.
194
/** Remove B-tree node.
191
 *
195
 *
192
 * @param B-tree.
196
 * @param B-tree.
193
 * @param key Key to be removed from the B-tree along with its associated value.
197
 * @param key Key to be removed from the B-tree along with its associated value.
194
 * @param leaf_node If not NULL, pointer to the leaf node where the key is found.
198
 * @param leaf_node If not NULL, pointer to the leaf node where the key is found.
195
 */
199
 */
196
void btree_remove(btree_t *t, btree_key_t key, btree_node_t *leaf_node)
200
void btree_remove(btree_t *t, btree_key_t key, btree_node_t *leaf_node)
197
{
201
{
198
    btree_node_t *lnode;
202
    btree_node_t *lnode;
199
   
203
   
200
    lnode = leaf_node;
204
    lnode = leaf_node;
201
    if (!lnode) {
205
    if (!lnode) {
202
        if (!btree_search(t, key, &lnode)) {
206
        if (!btree_search(t, key, &lnode)) {
203
            panic("B-tree %p does not contain key %d\n", t, key);
207
            panic("B-tree %p does not contain key %d\n", t, key);
204
        }
208
        }
205
    }
209
    }
206
   
210
   
207
    _btree_remove(t, key, lnode);
211
    _btree_remove(t, key, lnode);
208
}
212
}
209
 
213
 
210
/** Recursively remove B-tree node.
214
/** Recursively remove B-tree node.
211
 *
215
 *
212
 * @param B-tree.
216
 * @param B-tree.
213
 * @param key Key to be removed from the B-tree along with its associated value.
217
 * @param key Key to be removed from the B-tree along with its associated value.
214
 * @param node Node where the key being removed resides.
218
 * @param node Node where the key being removed resides.
215
 */
219
 */
216
void _btree_remove(btree_t *t, btree_key_t key, btree_node_t *node)
220
void _btree_remove(btree_t *t, btree_key_t key, btree_node_t *node)
217
{
221
{
218
    if (ROOT_NODE(node)) {
222
    if (ROOT_NODE(node)) {
219
        if (node->keys == 1 && node->subtree[0]) {
223
        if (node->keys == 1 && node->subtree[0]) {
220
            /*
224
            /*
221
             * Free the current root and set new root.
225
             * Free the current root and set new root.
222
             */
226
             */
223
            t->root = node->subtree[0];
227
            t->root = node->subtree[0];
224
            t->root->parent = NULL;
228
            t->root->parent = NULL;
225
            slab_free(btree_node_slab, node);
229
            slab_free(btree_node_slab, node);
226
        } else {
230
        } else {
227
            /*
231
            /*
228
             * Remove the key from the root node.
232
             * Remove the key from the root node.
229
             * Note that the right subtree is removed because when
233
             * Note that the right subtree is removed because when
230
             * combining two nodes, the left-side sibling is preserved
234
             * combining two nodes, the left-side sibling is preserved
231
             * and the right-side sibling is freed.
235
             * and the right-side sibling is freed.
232
             */
236
             */
233
            node_remove_key_and_rsubtree(node, key);
237
            node_remove_key_and_rsubtree(node, key);
234
        }
238
        }
235
        return;
239
        return;
236
    }
240
    }
237
   
241
   
238
    if (node->keys <= FILL_FACTOR) {
242
    if (node->keys <= FILL_FACTOR) {
239
        /*
243
        /*
240
         * If the node is below the fill factor,
244
         * If the node is below the fill factor,
241
         * try to borrow keys from left or right sibling.
245
         * try to borrow keys from left or right sibling.
242
         */
246
         */
243
        if (!try_rotation_from_left(node))
247
        if (!try_rotation_from_left(node))
244
            try_rotation_from_right(node);
248
            try_rotation_from_right(node);
245
    }
249
    }
246
   
250
   
247
    if (node->keys > FILL_FACTOR) {
251
    if (node->keys > FILL_FACTOR) {
248
        int i;
252
        int i;
249
 
253
 
250
        /*
254
        /*
251
         * The key can be immediatelly removed.
255
         * The key can be immediatelly removed.
252
         *
256
         *
253
         * Note that the right subtree is removed because when
257
         * Note that the right subtree is removed because when
254
         * combining two nodes, the left-side sibling is preserved
258
         * combining two nodes, the left-side sibling is preserved
255
         * and the right-side sibling is freed.
259
         * and the right-side sibling is freed.
256
         */
260
         */
257
        node_remove_key_and_rsubtree(node, key);
261
        node_remove_key_and_rsubtree(node, key);
258
        for (i = 0; i < node->parent->keys; i++) {
262
        for (i = 0; i < node->parent->keys; i++) {
259
            if (node->parent->key[i] == key)
263
            if (node->parent->key[i] == key)
260
                node->parent->key[i] = node->key[0];
264
                node->parent->key[i] = node->key[0];
261
        }
265
        }
262
       
266
       
263
    } else {
267
    } else {
264
        index_t idx;
268
        index_t idx;
265
        btree_node_t *rnode, *parent;
269
        btree_node_t *rnode, *parent;
266
 
270
 
267
        /*
271
        /*
268
         * The node is below the fill factor as well as its left and right sibling.
272
         * The node is below the fill factor as well as its left and right sibling.
269
         * Resort to combining the node with one of its siblings.
273
         * Resort to combining the node with one of its siblings.
270
         * The node which is on the left is preserved and the node on the right is
274
         * The node which is on the left is preserved and the node on the right is
271
         * freed.
275
         * freed.
272
         */
276
         */
273
        parent = node->parent;
277
        parent = node->parent;
274
        node_remove_key_and_rsubtree(node, key);
278
        node_remove_key_and_rsubtree(node, key);
275
        rnode = node_combine(node);
279
        rnode = node_combine(node);
276
        if (LEAF_NODE(rnode))
280
        if (LEAF_NODE(rnode))
277
            list_remove(&rnode->leaf_link);
281
            list_remove(&rnode->leaf_link);
278
        idx = find_key_by_subtree(parent, rnode, true);
282
        idx = find_key_by_subtree(parent, rnode, true);
279
        ASSERT((int) idx != -1);
283
        ASSERT((int) idx != -1);
280
        slab_free(btree_node_slab, rnode);
284
        slab_free(btree_node_slab, rnode);
281
        _btree_remove(t, parent->key[idx], parent);
285
        _btree_remove(t, parent->key[idx], parent);
282
    }
286
    }
283
}
287
}
284
 
288
 
285
/** Search key in a B-tree.
289
/** Search key in a B-tree.
286
 *
290
 *
287
 * @param t B-tree.
291
 * @param t B-tree.
288
 * @param key Key to be searched.
292
 * @param key Key to be searched.
289
 * @param leaf_node Address where to put pointer to visited leaf node.
293
 * @param leaf_node Address where to put pointer to visited leaf node.
290
 *
294
 *
291
 * @return Pointer to value or NULL if there is no such key.
295
 * @return Pointer to value or NULL if there is no such key.
292
 */
296
 */
293
void *btree_search(btree_t *t, btree_key_t key, btree_node_t **leaf_node)
297
void *btree_search(btree_t *t, btree_key_t key, btree_node_t **leaf_node)
294
{
298
{
295
    btree_node_t *cur, *next;
299
    btree_node_t *cur, *next;
296
   
300
   
297
    /*
301
    /*
298
     * Iteratively descend to the leaf that can contain the searched key.
302
     * Iteratively descend to the leaf that can contain the searched key.
299
     */
303
     */
300
    for (cur = t->root; cur; cur = next) {
304
    for (cur = t->root; cur; cur = next) {
301
 
305
 
302
        /* Last iteration will set this with proper leaf node address. */
306
        /* Last iteration will set this with proper leaf node address. */
303
        *leaf_node = cur;
307
        *leaf_node = cur;
304
       
308
       
305
        /*
309
        /*
306
         * The key can be in the leftmost subtree.
310
         * The key can be in the leftmost subtree.
307
         * Test it separately.
311
         * Test it separately.
308
         */
312
         */
309
        if (key < cur->key[0]) {
313
        if (key < cur->key[0]) {
310
            next = cur->subtree[0];
314
            next = cur->subtree[0];
311
            continue;
315
            continue;
312
        } else {
316
        } else {
313
            void *val;
317
            void *val;
314
            int i;
318
            int i;
315
       
319
       
316
            /*
320
            /*
317
             * Now if the key is smaller than cur->key[i]
321
             * Now if the key is smaller than cur->key[i]
318
             * it can only mean that the value is in cur->subtree[i]
322
             * it can only mean that the value is in cur->subtree[i]
319
             * or it is not in the tree at all.
323
             * or it is not in the tree at all.
320
             */
324
             */
321
            for (i = 1; i < cur->keys; i++) {
325
            for (i = 1; i < cur->keys; i++) {
322
                if (key < cur->key[i]) {
326
                if (key < cur->key[i]) {
323
                    next = cur->subtree[i];
327
                    next = cur->subtree[i];
324
                    val = cur->value[i - 1];
328
                    val = cur->value[i - 1];
325
 
329
 
326
                    if (LEAF_NODE(cur))
330
                    if (LEAF_NODE(cur))
327
                        return key == cur->key[i - 1] ? val : NULL;
331
                        return key == cur->key[i - 1] ? val : NULL;
328
 
332
 
329
                    goto descend;
333
                    goto descend;
330
                }
334
                }
331
            }
335
            }
332
           
336
           
333
            /*
337
            /*
334
             * Last possibility is that the key is in the rightmost subtree.
338
             * Last possibility is that the key is in the rightmost subtree.
335
             */
339
             */
336
            next = cur->subtree[i];
340
            next = cur->subtree[i];
337
            val = cur->value[i - 1];
341
            val = cur->value[i - 1];
338
            if (LEAF_NODE(cur))
342
            if (LEAF_NODE(cur))
339
                return key == cur->key[i - 1] ? val : NULL;
343
                return key == cur->key[i - 1] ? val : NULL;
340
        }
344
        }
341
        descend:
345
        descend:
342
            ;
346
            ;
343
    }
347
    }
344
 
348
 
345
    /*
349
    /*
346
     * The key was not found in the *leaf_node and is smaller than any of its keys.
350
     * The key was not found in the *leaf_node and is smaller than any of its keys.
347
     */
351
     */
348
    return NULL;
352
    return NULL;
349
}
353
}
350
 
354
 
351
/** Return pointer to B-tree leaf node's left neighbour.
355
/** Return pointer to B-tree leaf node's left neighbour.
352
 *
356
 *
353
 * @param t B-tree.
357
 * @param t B-tree.
354
 * @param node Node whose left neighbour will be returned.
358
 * @param node Node whose left neighbour will be returned.
355
 *
359
 *
356
 * @return Left neighbour of the node or NULL if the node does not have the left neighbour.
360
 * @return Left neighbour of the node or NULL if the node does not have the left neighbour.
357
 */
361
 */
358
btree_node_t *btree_leaf_node_left_neighbour(btree_t *t, btree_node_t *node)
362
btree_node_t *btree_leaf_node_left_neighbour(btree_t *t, btree_node_t *node)
359
{
363
{
360
    ASSERT(LEAF_NODE(node));
364
    ASSERT(LEAF_NODE(node));
361
    if (node->leaf_link.prev != &t->leaf_head)
365
    if (node->leaf_link.prev != &t->leaf_head)
362
        return list_get_instance(node->leaf_link.prev, btree_node_t, leaf_link);
366
        return list_get_instance(node->leaf_link.prev, btree_node_t, leaf_link);
363
    else
367
    else
364
        return NULL;
368
        return NULL;
365
}
369
}
366
 
370
 
367
/** Return pointer to B-tree leaf node's right neighbour.
371
/** Return pointer to B-tree leaf node's right neighbour.
368
 *
372
 *
369
 * @param t B-tree.
373
 * @param t B-tree.
370
 * @param node Node whose right neighbour will be returned.
374
 * @param node Node whose right neighbour will be returned.
371
 *
375
 *
372
 * @return Right neighbour of the node or NULL if the node does not have the right neighbour.
376
 * @return Right neighbour of the node or NULL if the node does not have the right neighbour.
373
 */
377
 */
374
btree_node_t *btree_leaf_node_right_neighbour(btree_t *t, btree_node_t *node)
378
btree_node_t *btree_leaf_node_right_neighbour(btree_t *t, btree_node_t *node)
375
{
379
{
376
    ASSERT(LEAF_NODE(node));
380
    ASSERT(LEAF_NODE(node));
377
    if (node->leaf_link.next != &t->leaf_head)
381
    if (node->leaf_link.next != &t->leaf_head)
378
        return list_get_instance(node->leaf_link.next, btree_node_t, leaf_link);
382
        return list_get_instance(node->leaf_link.next, btree_node_t, leaf_link);
379
    else
383
    else
380
        return NULL;
384
        return NULL;
381
}
385
}
382
 
386
 
383
/** Initialize B-tree node.
387
/** Initialize B-tree node.
384
 *
388
 *
385
 * @param node B-tree node.
389
 * @param node B-tree node.
386
 */
390
 */
387
void node_initialize(btree_node_t *node)
391
void node_initialize(btree_node_t *node)
388
{
392
{
389
    int i;
393
    int i;
390
 
394
 
391
    node->keys = 0;
395
    node->keys = 0;
392
   
396
   
393
    /* Clean also space for the extra key. */
397
    /* Clean also space for the extra key. */
394
    for (i = 0; i < BTREE_MAX_KEYS + 1; i++) {
398
    for (i = 0; i < BTREE_MAX_KEYS + 1; i++) {
395
        node->key[i] = 0;
399
        node->key[i] = 0;
396
        node->value[i] = NULL;
400
        node->value[i] = NULL;
397
        node->subtree[i] = NULL;
401
        node->subtree[i] = NULL;
398
    }
402
    }
399
    node->subtree[i] = NULL;
403
    node->subtree[i] = NULL;
400
   
404
   
401
    node->parent = NULL;
405
    node->parent = NULL;
402
   
406
   
403
    link_initialize(&node->leaf_link);
407
    link_initialize(&node->leaf_link);
404
 
408
 
405
    link_initialize(&node->bfs_link);
409
    link_initialize(&node->bfs_link);
406
    node->depth = 0;
410
    node->depth = 0;
407
}
411
}
408
 
412
 
409
/** Insert key-value-lsubtree triplet into B-tree node.
413
/** Insert key-value-lsubtree triplet into B-tree node.
410
 *
414
 *
411
 * It is actually possible to have more keys than BTREE_MAX_KEYS.
415
 * It is actually possible to have more keys than BTREE_MAX_KEYS.
412
 * This feature is used during insert by right rotation.
416
 * This feature is used during insert by right rotation.
413
 *
417
 *
414
 * @param node B-tree node into wich the new key is to be inserted.
418
 * @param node B-tree node into wich the new key is to be inserted.
415
 * @param key The key to be inserted.
419
 * @param key The key to be inserted.
416
 * @param value Pointer to value to be inserted.
420
 * @param value Pointer to value to be inserted.
417
 * @param lsubtree Pointer to the left subtree.
421
 * @param lsubtree Pointer to the left subtree.
418
 */
422
 */
419
void node_insert_key_and_lsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *lsubtree)
423
void node_insert_key_and_lsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *lsubtree)
420
{
424
{
421
    int i;
425
    int i;
422
 
426
 
423
    for (i = 0; i < node->keys; i++) {
427
    for (i = 0; i < node->keys; i++) {
424
        if (key < node->key[i]) {
428
        if (key < node->key[i]) {
425
            int j;
429
            int j;
426
       
430
       
427
            for (j = node->keys; j > i; j--) {
431
            for (j = node->keys; j > i; j--) {
428
                node->key[j] = node->key[j - 1];
432
                node->key[j] = node->key[j - 1];
429
                node->value[j] = node->value[j - 1];
433
                node->value[j] = node->value[j - 1];
430
                node->subtree[j + 1] = node->subtree[j];
434
                node->subtree[j + 1] = node->subtree[j];
431
            }
435
            }
432
            node->subtree[j + 1] = node->subtree[j];
436
            node->subtree[j + 1] = node->subtree[j];
433
            break; 
437
            break; 
434
        }
438
        }
435
    }
439
    }
436
    node->key[i] = key;
440
    node->key[i] = key;
437
    node->value[i] = value;
441
    node->value[i] = value;
438
    node->subtree[i] = lsubtree;
442
    node->subtree[i] = lsubtree;
439
           
443
           
440
    node->keys++;
444
    node->keys++;
441
}
445
}
442
 
446
 
443
/** Insert key-value-rsubtree triplet into B-tree node.
447
/** Insert key-value-rsubtree triplet into B-tree node.
444
 *
448
 *
445
 * It is actually possible to have more keys than BTREE_MAX_KEYS.
449
 * It is actually possible to have more keys than BTREE_MAX_KEYS.
446
 * This feature is used during splitting the node when the
450
 * This feature is used during splitting the node when the
447
 * number of keys is BTREE_MAX_KEYS + 1. Insert by left rotation
451
 * number of keys is BTREE_MAX_KEYS + 1. Insert by left rotation
448
 * also makes use of this feature.
452
 * also makes use of this feature.
449
 *
453
 *
450
 * @param node B-tree node into wich the new key is to be inserted.
454
 * @param node B-tree node into wich the new key is to be inserted.
451
 * @param key The key to be inserted.
455
 * @param key The key to be inserted.
452
 * @param value Pointer to value to be inserted.
456
 * @param value Pointer to value to be inserted.
453
 * @param rsubtree Pointer to the right subtree.
457
 * @param rsubtree Pointer to the right subtree.
454
 */
458
 */
455
void node_insert_key_and_rsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree)
459
void node_insert_key_and_rsubtree(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree)
456
{
460
{
457
    int i;
461
    int i;
458
 
462
 
459
    for (i = 0; i < node->keys; i++) {
463
    for (i = 0; i < node->keys; i++) {
460
        if (key < node->key[i]) {
464
        if (key < node->key[i]) {
461
            int j;
465
            int j;
462
       
466
       
463
            for (j = node->keys; j > i; j--) {
467
            for (j = node->keys; j > i; j--) {
464
                node->key[j] = node->key[j - 1];
468
                node->key[j] = node->key[j - 1];
465
                node->value[j] = node->value[j - 1];
469
                node->value[j] = node->value[j - 1];
466
                node->subtree[j + 1] = node->subtree[j];
470
                node->subtree[j + 1] = node->subtree[j];
467
            }
471
            }
468
            break; 
472
            break; 
469
        }
473
        }
470
    }
474
    }
471
    node->key[i] = key;
475
    node->key[i] = key;
472
    node->value[i] = value;
476
    node->value[i] = value;
473
    node->subtree[i + 1] = rsubtree;
477
    node->subtree[i + 1] = rsubtree;
474
           
478
           
475
    node->keys++;
479
    node->keys++;
476
}
480
}
477
 
481
 
478
/** Remove key and its left subtree pointer from B-tree node.
482
/** Remove key and its left subtree pointer from B-tree node.
479
 *
483
 *
480
 * Remove the key and eliminate gaps in node->key array.
484
 * Remove the key and eliminate gaps in node->key array.
481
 * Note that the value pointer and the left subtree pointer
485
 * Note that the value pointer and the left subtree pointer
482
 * is removed from the node as well.
486
 * is removed from the node as well.
483
 *
487
 *
484
 * @param node B-tree node.
488
 * @param node B-tree node.
485
 * @param key Key to be removed.
489
 * @param key Key to be removed.
486
 */
490
 */
487
void node_remove_key_and_lsubtree(btree_node_t *node, btree_key_t key)
491
void node_remove_key_and_lsubtree(btree_node_t *node, btree_key_t key)
488
{
492
{
489
    int i, j;
493
    int i, j;
490
   
494
   
491
    for (i = 0; i < node->keys; i++) {
495
    for (i = 0; i < node->keys; i++) {
492
        if (key == node->key[i]) {
496
        if (key == node->key[i]) {
493
            for (j = i + 1; j < node->keys; j++) {
497
            for (j = i + 1; j < node->keys; j++) {
494
                node->key[j - 1] = node->key[j];
498
                node->key[j - 1] = node->key[j];
495
                node->value[j - 1] = node->value[j];
499
                node->value[j - 1] = node->value[j];
496
                node->subtree[j - 1] = node->subtree[j];
500
                node->subtree[j - 1] = node->subtree[j];
497
            }
501
            }
498
            node->subtree[j - 1] = node->subtree[j];
502
            node->subtree[j - 1] = node->subtree[j];
499
            node->keys--;
503
            node->keys--;
500
            return;
504
            return;
501
        }
505
        }
502
    }
506
    }
503
    panic("node %p does not contain key %d\n", node, key);
507
    panic("node %p does not contain key %d\n", node, key);
504
}
508
}
505
 
509
 
506
/** Remove key and its right subtree pointer from B-tree node.
510
/** Remove key and its right subtree pointer from B-tree node.
507
 *
511
 *
508
 * Remove the key and eliminate gaps in node->key array.
512
 * Remove the key and eliminate gaps in node->key array.
509
 * Note that the value pointer and the right subtree pointer
513
 * Note that the value pointer and the right subtree pointer
510
 * is removed from the node as well.
514
 * is removed from the node as well.
511
 *
515
 *
512
 * @param node B-tree node.
516
 * @param node B-tree node.
513
 * @param key Key to be removed.
517
 * @param key Key to be removed.
514
 */
518
 */
515
void node_remove_key_and_rsubtree(btree_node_t *node, btree_key_t key)
519
void node_remove_key_and_rsubtree(btree_node_t *node, btree_key_t key)
516
{
520
{
517
    int i, j;
521
    int i, j;
518
   
522
   
519
    for (i = 0; i < node->keys; i++) {
523
    for (i = 0; i < node->keys; i++) {
520
        if (key == node->key[i]) {
524
        if (key == node->key[i]) {
521
            for (j = i + 1; j < node->keys; j++) {
525
            for (j = i + 1; j < node->keys; j++) {
522
                node->key[j - 1] = node->key[j];
526
                node->key[j - 1] = node->key[j];
523
                node->value[j - 1] = node->value[j];
527
                node->value[j - 1] = node->value[j];
524
                node->subtree[j] = node->subtree[j + 1];
528
                node->subtree[j] = node->subtree[j + 1];
525
            }
529
            }
526
            node->keys--;
530
            node->keys--;
527
            return;
531
            return;
528
        }
532
        }
529
    }
533
    }
530
    panic("node %p does not contain key %d\n", node, key);
534
    panic("node %p does not contain key %d\n", node, key);
531
}
535
}
532
 
536
 
533
/** Split full B-tree node and insert new key-value-right-subtree triplet.
537
/** Split full B-tree node and insert new key-value-right-subtree triplet.
534
 *
538
 *
535
 * This function will split a node and return pointer to a newly created
539
 * This function will split a node and return pointer to a newly created
536
 * node containing keys greater than or equal to the greater of medians
540
 * node containing keys greater than or equal to the greater of medians
537
 * (or median) of the old keys and the newly added key. It will also write
541
 * (or median) of the old keys and the newly added key. It will also write
538
 * the median key to a memory address supplied by the caller.
542
 * the median key to a memory address supplied by the caller.
539
 *
543
 *
540
 * If the node being split is an index node, the median will not be
544
 * If the node being split is an index node, the median will not be
541
 * included in the new node. If the node is a leaf node,
545
 * included in the new node. If the node is a leaf node,
542
 * the median will be copied there.
546
 * the median will be copied there.
543
 *
547
 *
544
 * @param node B-tree node wich is going to be split.
548
 * @param node B-tree node wich is going to be split.
545
 * @param key The key to be inserted.
549
 * @param key The key to be inserted.
546
 * @param value Pointer to the value to be inserted.
550
 * @param value Pointer to the value to be inserted.
547
 * @param rsubtree Pointer to the right subtree of the key being added.
551
 * @param rsubtree Pointer to the right subtree of the key being added.
548
 * @param median Address in memory, where the median key will be stored.
552
 * @param median Address in memory, where the median key will be stored.
549
 *
553
 *
550
 * @return Newly created right sibling of node.
554
 * @return Newly created right sibling of node.
551
 */
555
 */
552
btree_node_t *node_split(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree, btree_key_t *median)
556
btree_node_t *node_split(btree_node_t *node, btree_key_t key, void *value, btree_node_t *rsubtree, btree_key_t *median)
553
{
557
{
554
    btree_node_t *rnode;
558
    btree_node_t *rnode;
555
    int i, j;
559
    int i, j;
556
 
560
 
557
    ASSERT(median);
561
    ASSERT(median);
558
    ASSERT(node->keys == BTREE_MAX_KEYS);
562
    ASSERT(node->keys == BTREE_MAX_KEYS);
559
 
563
 
560
    /*
564
    /*
561
     * Use the extra space to store the extra node.
565
     * Use the extra space to store the extra node.
562
     */
566
     */
563
    node_insert_key_and_rsubtree(node, key, value, rsubtree);
567
    node_insert_key_and_rsubtree(node, key, value, rsubtree);
564
 
568
 
565
    /*
569
    /*
566
     * Compute median of keys.
570
     * Compute median of keys.
567
     */
571
     */
568
    *median = MEDIAN_HIGH(node);
572
    *median = MEDIAN_HIGH(node);
569
       
573
       
570
    /*
574
    /*
571
     * Allocate and initialize new right sibling.
575
     * Allocate and initialize new right sibling.
572
     */
576
     */
573
    rnode = (btree_node_t *) slab_alloc(btree_node_slab, 0);
577
    rnode = (btree_node_t *) slab_alloc(btree_node_slab, 0);
574
    node_initialize(rnode);
578
    node_initialize(rnode);
575
    rnode->parent = node->parent;
579
    rnode->parent = node->parent;
576
    rnode->depth = node->depth;
580
    rnode->depth = node->depth;
577
   
581
   
578
    /*
582
    /*
579
     * Copy big keys, values and subtree pointers to the new right sibling.
583
     * Copy big keys, values and subtree pointers to the new right sibling.
580
     * If this is an index node, do not copy the median.
584
     * If this is an index node, do not copy the median.
581
     */
585
     */
582
    i = (int) INDEX_NODE(node);
586
    i = (int) INDEX_NODE(node);
583
    for (i += MEDIAN_HIGH_INDEX(node), j = 0; i < node->keys; i++, j++) {
587
    for (i += MEDIAN_HIGH_INDEX(node), j = 0; i < node->keys; i++, j++) {
584
        rnode->key[j] = node->key[i];
588
        rnode->key[j] = node->key[i];
585
        rnode->value[j] = node->value[i];
589
        rnode->value[j] = node->value[i];
586
        rnode->subtree[j] = node->subtree[i];
590
        rnode->subtree[j] = node->subtree[i];
587
       
591
       
588
        /*
592
        /*
589
         * Fix parent links in subtrees.
593
         * Fix parent links in subtrees.
590
         */
594
         */
591
        if (rnode->subtree[j])
595
        if (rnode->subtree[j])
592
            rnode->subtree[j]->parent = rnode;
596
            rnode->subtree[j]->parent = rnode;
593
           
597
           
594
    }
598
    }
595
    rnode->subtree[j] = node->subtree[i];
599
    rnode->subtree[j] = node->subtree[i];
596
    if (rnode->subtree[j])
600
    if (rnode->subtree[j])
597
        rnode->subtree[j]->parent = rnode;
601
        rnode->subtree[j]->parent = rnode;
598
 
602
 
599
    rnode->keys = j;    /* Set number of keys of the new node. */
603
    rnode->keys = j;    /* Set number of keys of the new node. */
600
    node->keys /= 2;    /* Shrink the old node. */
604
    node->keys /= 2;    /* Shrink the old node. */
601
       
605
       
602
    return rnode;
606
    return rnode;
603
}
607
}
604
 
608
 
605
/** Combine node with any of its siblings.
609
/** Combine node with any of its siblings.
606
 *
610
 *
607
 * The siblings are required to be below the fill factor.
611
 * The siblings are required to be below the fill factor.
608
 *
612
 *
609
 * @param node Node to combine with one of its siblings.
613
 * @param node Node to combine with one of its siblings.
610
 *
614
 *
611
 * @return Pointer to the rightmost of the two nodes.
615
 * @return Pointer to the rightmost of the two nodes.
612
 */
616
 */
613
btree_node_t *node_combine(btree_node_t *node)
617
btree_node_t *node_combine(btree_node_t *node)
614
{
618
{
615
    index_t idx;
619
    index_t idx;
616
    btree_node_t *rnode;
620
    btree_node_t *rnode;
617
    int i;
621
    int i;
618
 
622
 
619
    ASSERT(!ROOT_NODE(node));
623
    ASSERT(!ROOT_NODE(node));
620
   
624
   
621
    idx = find_key_by_subtree(node->parent, node, false);
625
    idx = find_key_by_subtree(node->parent, node, false);
622
    if (idx == node->parent->keys) {
626
    if (idx == node->parent->keys) {
623
        /*
627
        /*
624
         * Rightmost subtree of its parent, combine with the left sibling.
628
         * Rightmost subtree of its parent, combine with the left sibling.
625
         */
629
         */
626
        idx--;
630
        idx--;
627
        rnode = node;
631
        rnode = node;
628
        node = node->parent->subtree[idx];
632
        node = node->parent->subtree[idx];
629
    } else {
633
    } else {
630
        rnode = node->parent->subtree[idx + 1];
634
        rnode = node->parent->subtree[idx + 1];
631
    }
635
    }
632
 
636
 
633
    /* Index nodes need to insert parent node key in between left and right node. */
637
    /* Index nodes need to insert parent node key in between left and right node. */
634
    if (INDEX_NODE(node))
638
    if (INDEX_NODE(node))
635
        node->key[node->keys++] = node->parent->key[idx];
639
        node->key[node->keys++] = node->parent->key[idx];
636
   
640
   
637
    /* Copy the key-value-subtree triplets from the right node. */
641
    /* Copy the key-value-subtree triplets from the right node. */
638
    for (i = 0; i < rnode->keys; i++) {
642
    for (i = 0; i < rnode->keys; i++) {
639
        node->key[node->keys + i] = rnode->key[i];
643
        node->key[node->keys + i] = rnode->key[i];
640
        node->value[node->keys + i] = rnode->value[i];
644
        node->value[node->keys + i] = rnode->value[i];
641
        if (INDEX_NODE(node)) {
645
        if (INDEX_NODE(node)) {
642
            node->subtree[node->keys + i] = rnode->subtree[i];
646
            node->subtree[node->keys + i] = rnode->subtree[i];
643
            rnode->subtree[i]->parent = node;
647
            rnode->subtree[i]->parent = node;
644
        }
648
        }
645
    }
649
    }
646
    if (INDEX_NODE(node)) {
650
    if (INDEX_NODE(node)) {
647
        node->subtree[node->keys + i] = rnode->subtree[i];
651
        node->subtree[node->keys + i] = rnode->subtree[i];
648
        rnode->subtree[i]->parent = node;
652
        rnode->subtree[i]->parent = node;
649
    }
653
    }
650
 
654
 
651
    node->keys += rnode->keys;
655
    node->keys += rnode->keys;
652
 
656
 
653
    return rnode;
657
    return rnode;
654
}
658
}
655
 
659
 
656
/** Find key by its left or right subtree.
660
/** Find key by its left or right subtree.
657
 *
661
 *
658
 * @param node B-tree node.
662
 * @param node B-tree node.
659
 * @param subtree Left or right subtree of a key found in node.
663
 * @param subtree Left or right subtree of a key found in node.
660
 * @param right If true, subtree is a right subtree. If false, subtree is a left subtree.
664
 * @param right If true, subtree is a right subtree. If false, subtree is a left subtree.
661
 *
665
 *
662
 * @return Index of the key associated with the subtree.
666
 * @return Index of the key associated with the subtree.
663
 */
667
 */
664
index_t find_key_by_subtree(btree_node_t *node, btree_node_t *subtree, bool right)
668
index_t find_key_by_subtree(btree_node_t *node, btree_node_t *subtree, bool right)
665
{
669
{
666
    int i;
670
    int i;
667
   
671
   
668
    for (i = 0; i < node->keys + 1; i++) {
672
    for (i = 0; i < node->keys + 1; i++) {
669
        if (subtree == node->subtree[i])
673
        if (subtree == node->subtree[i])
670
            return i - (int) (right != false);
674
            return i - (int) (right != false);
671
    }
675
    }
672
    panic("node %p does not contain subtree %p\n", node, subtree);
676
    panic("node %p does not contain subtree %p\n", node, subtree);
673
}
677
}
674
 
678
 
675
/** Rotate one key-value-rsubtree triplet from the left sibling to the right sibling.
679
/** Rotate one key-value-rsubtree triplet from the left sibling to the right sibling.
676
 *
680
 *
677
 * The biggest key and its value and right subtree is rotated from the left node
681
 * The biggest key and its value and right subtree is rotated from the left node
678
 * to the right. If the node is an index node, than the parent node key belonging to
682
 * to the right. If the node is an index node, than the parent node key belonging to
679
 * the left node takes part in the rotation.
683
 * the left node takes part in the rotation.
680
 *
684
 *
681
 * @param lnode Left sibling.
685
 * @param lnode Left sibling.
682
 * @param rnode Right sibling.
686
 * @param rnode Right sibling.
683
 * @param idx Index of the parent node key that is taking part in the rotation.
687
 * @param idx Index of the parent node key that is taking part in the rotation.
684
 */
688
 */
685
void rotate_from_left(btree_node_t *lnode, btree_node_t *rnode, index_t idx)
689
void rotate_from_left(btree_node_t *lnode, btree_node_t *rnode, index_t idx)
686
{
690
{
687
    btree_key_t key;
691
    btree_key_t key;
688
 
692
 
689
    key = lnode->key[lnode->keys - 1];
693
    key = lnode->key[lnode->keys - 1];
690
       
694
       
691
    if (LEAF_NODE(lnode)) {
695
    if (LEAF_NODE(lnode)) {
692
        void *value;
696
        void *value;
693
 
697
 
694
        value = lnode->value[lnode->keys - 1];
698
        value = lnode->value[lnode->keys - 1];
695
        node_remove_key_and_rsubtree(lnode, key);
699
        node_remove_key_and_rsubtree(lnode, key);
696
        node_insert_key_and_lsubtree(rnode, key, value, NULL);
700
        node_insert_key_and_lsubtree(rnode, key, value, NULL);
697
        lnode->parent->key[idx] = key;
701
        lnode->parent->key[idx] = key;
698
    } else {
702
    } else {
699
        btree_node_t *rsubtree;
703
        btree_node_t *rsubtree;
700
 
704
 
701
        rsubtree = lnode->subtree[lnode->keys];
705
        rsubtree = lnode->subtree[lnode->keys];
702
        node_remove_key_and_rsubtree(lnode, key);
706
        node_remove_key_and_rsubtree(lnode, key);
703
        node_insert_key_and_lsubtree(rnode, lnode->parent->key[idx], NULL, rsubtree);
707
        node_insert_key_and_lsubtree(rnode, lnode->parent->key[idx], NULL, rsubtree);
704
        lnode->parent->key[idx] = key;
708
        lnode->parent->key[idx] = key;
705
 
709
 
706
        /* Fix parent link of the reconnected right subtree. */
710
        /* Fix parent link of the reconnected right subtree. */
707
        rsubtree->parent = rnode;
711
        rsubtree->parent = rnode;
708
    }
712
    }
709
 
713
 
710
}
714
}
711
 
715
 
712
/** Rotate one key-value-lsubtree triplet from the right sibling to the left sibling.
716
/** Rotate one key-value-lsubtree triplet from the right sibling to the left sibling.
713
 *
717
 *
714
 * The smallest key and its value and left subtree is rotated from the right node
718
 * The smallest key and its value and left subtree is rotated from the right node
715
 * to the left. If the node is an index node, than the parent node key belonging to
719
 * to the left. If the node is an index node, than the parent node key belonging to
716
 * the right node takes part in the rotation.
720
 * the right node takes part in the rotation.
717
 *
721
 *
718
 * @param lnode Left sibling.
722
 * @param lnode Left sibling.
719
 * @param rnode Right sibling.
723
 * @param rnode Right sibling.
720
 * @param idx Index of the parent node key that is taking part in the rotation.
724
 * @param idx Index of the parent node key that is taking part in the rotation.
721
 */
725
 */
722
void rotate_from_right(btree_node_t *lnode, btree_node_t *rnode, index_t idx)
726
void rotate_from_right(btree_node_t *lnode, btree_node_t *rnode, index_t idx)
723
{
727
{
724
    btree_key_t key;
728
    btree_key_t key;
725
 
729
 
726
    key = rnode->key[0];
730
    key = rnode->key[0];
727
       
731
       
728
    if (LEAF_NODE(rnode)) {
732
    if (LEAF_NODE(rnode)) {
729
        void *value;
733
        void *value;
730
 
734
 
731
        value = rnode->value[0];
735
        value = rnode->value[0];
732
        node_remove_key_and_lsubtree(rnode, key);
736
        node_remove_key_and_lsubtree(rnode, key);
733
        node_insert_key_and_rsubtree(lnode, key, value, NULL);
737
        node_insert_key_and_rsubtree(lnode, key, value, NULL);
734
        rnode->parent->key[idx] = rnode->key[0];
738
        rnode->parent->key[idx] = rnode->key[0];
735
    } else {
739
    } else {
736
        btree_node_t *lsubtree;
740
        btree_node_t *lsubtree;
737
 
741
 
738
        lsubtree = rnode->subtree[0];
742
        lsubtree = rnode->subtree[0];
739
        node_remove_key_and_lsubtree(rnode, key);
743
        node_remove_key_and_lsubtree(rnode, key);
740
        node_insert_key_and_rsubtree(lnode, rnode->parent->key[idx], NULL, lsubtree);
744
        node_insert_key_and_rsubtree(lnode, rnode->parent->key[idx], NULL, lsubtree);
741
        rnode->parent->key[idx] = key;
745
        rnode->parent->key[idx] = key;
742
 
746
 
743
        /* Fix parent link of the reconnected left subtree. */
747
        /* Fix parent link of the reconnected left subtree. */
744
        lsubtree->parent = lnode;
748
        lsubtree->parent = lnode;
745
    }
749
    }
746
 
750
 
747
}
751
}
748
 
752
 
749
/** Insert key-value-rsubtree triplet and rotate the node to the left, if this operation can be done.
753
/** Insert key-value-rsubtree triplet and rotate the node to the left, if this operation can be done.
750
 *
754
 *
751
 * Left sibling of the node (if it exists) is checked for free space.
755
 * Left sibling of the node (if it exists) is checked for free space.
752
 * If there is free space, the key is inserted and the smallest key of
756
 * If there is free space, the key is inserted and the smallest key of
753
 * the node is moved there. The index node which is the parent of both
757
 * the node is moved there. The index node which is the parent of both
754
 * nodes is fixed.
758
 * nodes is fixed.
755
 *
759
 *
756
 * @param node B-tree node.
760
 * @param node B-tree node.
757
 * @param inskey Key to be inserted.
761
 * @param inskey Key to be inserted.
758
 * @param insvalue Value to be inserted.
762
 * @param insvalue Value to be inserted.
759
 * @param rsubtree Right subtree of inskey.
763
 * @param rsubtree Right subtree of inskey.
760
 *
764
 *
761
 * @return True if the rotation was performed, false otherwise.
765
 * @return True if the rotation was performed, false otherwise.
762
 */
766
 */
763
bool try_insert_by_rotation_to_left(btree_node_t *node, btree_key_t inskey, void *insvalue, btree_node_t *rsubtree)
767
bool try_insert_by_rotation_to_left(btree_node_t *node, btree_key_t inskey, void *insvalue, btree_node_t *rsubtree)
764
{
768
{
765
    index_t idx;
769
    index_t idx;
766
    btree_node_t *lnode;
770
    btree_node_t *lnode;
767
 
771
 
768
    /*
772
    /*
769
     * If this is root node, the rotation can not be done.
773
     * If this is root node, the rotation can not be done.
770
     */
774
     */
771
    if (ROOT_NODE(node))
775
    if (ROOT_NODE(node))
772
        return false;
776
        return false;
773
   
777
   
774
    idx = find_key_by_subtree(node->parent, node, true);
778
    idx = find_key_by_subtree(node->parent, node, true);
775
    if ((int) idx == -1) {
779
    if ((int) idx == -1) {
776
        /*
780
        /*
777
         * If this node is the leftmost subtree of its parent,
781
         * If this node is the leftmost subtree of its parent,
778
         * the rotation can not be done.
782
         * the rotation can not be done.
779
         */
783
         */
780
        return false;
784
        return false;
781
    }
785
    }
782
       
786
       
783
    lnode = node->parent->subtree[idx];
787
    lnode = node->parent->subtree[idx];
784
    if (lnode->keys < BTREE_MAX_KEYS) {
788
    if (lnode->keys < BTREE_MAX_KEYS) {
785
        /*
789
        /*
786
         * The rotaion can be done. The left sibling has free space.
790
         * The rotaion can be done. The left sibling has free space.
787
         */
791
         */
788
        node_insert_key_and_rsubtree(node, inskey, insvalue, rsubtree);
792
        node_insert_key_and_rsubtree(node, inskey, insvalue, rsubtree);
789
        rotate_from_right(lnode, node, idx);
793
        rotate_from_right(lnode, node, idx);
790
        return true;
794
        return true;
791
    }
795
    }
792
 
796
 
793
    return false;
797
    return false;
794
}
798
}
795
 
799
 
796
/** Insert key-value-rsubtree triplet and rotate the node to the right, if this operation can be done.
800
/** Insert key-value-rsubtree triplet and rotate the node to the right, if this operation can be done.
797
 *
801
 *
798
 * Right sibling of the node (if it exists) is checked for free space.
802
 * Right sibling of the node (if it exists) is checked for free space.
799
 * If there is free space, the key is inserted and the biggest key of
803
 * If there is free space, the key is inserted and the biggest key of
800
 * the node is moved there. The index node which is the parent of both
804
 * the node is moved there. The index node which is the parent of both
801
 * nodes is fixed.
805
 * nodes is fixed.
802
 *
806
 *
803
 * @param node B-tree node.
807
 * @param node B-tree node.
804
 * @param inskey Key to be inserted.
808
 * @param inskey Key to be inserted.
805
 * @param insvalue Value to be inserted.
809
 * @param insvalue Value to be inserted.
806
 * @param rsubtree Right subtree of inskey.
810
 * @param rsubtree Right subtree of inskey.
807
 *
811
 *
808
 * @return True if the rotation was performed, false otherwise.
812
 * @return True if the rotation was performed, false otherwise.
809
 */
813
 */
810
bool try_insert_by_rotation_to_right(btree_node_t *node, btree_key_t inskey, void *insvalue, btree_node_t *rsubtree)
814
bool try_insert_by_rotation_to_right(btree_node_t *node, btree_key_t inskey, void *insvalue, btree_node_t *rsubtree)
811
{
815
{
812
    index_t idx;
816
    index_t idx;
813
    btree_node_t *rnode;
817
    btree_node_t *rnode;
814
 
818
 
815
    /*
819
    /*
816
     * If this is root node, the rotation can not be done.
820
     * If this is root node, the rotation can not be done.
817
     */
821
     */
818
    if (ROOT_NODE(node))
822
    if (ROOT_NODE(node))
819
        return false;
823
        return false;
820
   
824
   
821
    idx = find_key_by_subtree(node->parent, node, false);
825
    idx = find_key_by_subtree(node->parent, node, false);
822
    if (idx == node->parent->keys) {
826
    if (idx == node->parent->keys) {
823
        /*
827
        /*
824
         * If this node is the rightmost subtree of its parent,
828
         * If this node is the rightmost subtree of its parent,
825
         * the rotation can not be done.
829
         * the rotation can not be done.
826
         */
830
         */
827
        return false;
831
        return false;
828
    }
832
    }
829
       
833
       
830
    rnode = node->parent->subtree[idx + 1];
834
    rnode = node->parent->subtree[idx + 1];
831
    if (rnode->keys < BTREE_MAX_KEYS) {
835
    if (rnode->keys < BTREE_MAX_KEYS) {
832
        /*
836
        /*
833
         * The rotaion can be done. The right sibling has free space.
837
         * The rotaion can be done. The right sibling has free space.
834
         */
838
         */
835
        node_insert_key_and_rsubtree(node, inskey, insvalue, rsubtree);
839
        node_insert_key_and_rsubtree(node, inskey, insvalue, rsubtree);
836
        rotate_from_left(node, rnode, idx);
840
        rotate_from_left(node, rnode, idx);
837
        return true;
841
        return true;
838
    }
842
    }
839
 
843
 
840
    return false;
844
    return false;
841
}
845
}
842
 
846
 
843
/** Rotate in a key from the left sibling or from the index node, if this operation can be done.
847
/** Rotate in a key from the left sibling or from the index node, if this operation can be done.
844
 *
848
 *
845
 * @param rnode Node into which to add key from its left sibling or from the index node.
849
 * @param rnode Node into which to add key from its left sibling or from the index node.
846
 *
850
 *
847
 * @return True if the rotation was performed, false otherwise.
851
 * @return True if the rotation was performed, false otherwise.
848
 */
852
 */
849
bool try_rotation_from_left(btree_node_t *rnode)
853
bool try_rotation_from_left(btree_node_t *rnode)
850
{
854
{
851
    index_t idx;
855
    index_t idx;
852
    btree_node_t *lnode;
856
    btree_node_t *lnode;
853
 
857
 
854
    /*
858
    /*
855
     * If this is root node, the rotation can not be done.
859
     * If this is root node, the rotation can not be done.
856
     */
860
     */
857
    if (ROOT_NODE(rnode))
861
    if (ROOT_NODE(rnode))
858
        return false;
862
        return false;
859
   
863
   
860
    idx = find_key_by_subtree(rnode->parent, rnode, true);
864
    idx = find_key_by_subtree(rnode->parent, rnode, true);
861
    if ((int) idx == -1) {
865
    if ((int) idx == -1) {
862
        /*
866
        /*
863
         * If this node is the leftmost subtree of its parent,
867
         * If this node is the leftmost subtree of its parent,
864
         * the rotation can not be done.
868
         * the rotation can not be done.
865
         */
869
         */
866
        return false;
870
        return false;
867
    }
871
    }
868
       
872
       
869
    lnode = rnode->parent->subtree[idx];
873
    lnode = rnode->parent->subtree[idx];
870
    if (lnode->keys > FILL_FACTOR) {
874
    if (lnode->keys > FILL_FACTOR) {
871
        rotate_from_left(lnode, rnode, idx);
875
        rotate_from_left(lnode, rnode, idx);
872
        return true;
876
        return true;
873
    }
877
    }
874
   
878
   
875
    return false;
879
    return false;
876
}
880
}
877
 
881
 
878
/** Rotate in a key from the right sibling or from the index node, if this operation can be done.
882
/** Rotate in a key from the right sibling or from the index node, if this operation can be done.
879
 *
883
 *
880
 * @param rnode Node into which to add key from its right sibling or from the index node.
884
 * @param rnode Node into which to add key from its right sibling or from the index node.
881
 *
885
 *
882
 * @return True if the rotation was performed, false otherwise.
886
 * @return True if the rotation was performed, false otherwise.
883
 */
887
 */
884
bool try_rotation_from_right(btree_node_t *lnode)
888
bool try_rotation_from_right(btree_node_t *lnode)
885
{
889
{
886
    index_t idx;
890
    index_t idx;
887
    btree_node_t *rnode;
891
    btree_node_t *rnode;
888
 
892
 
889
    /*
893
    /*
890
     * If this is root node, the rotation can not be done.
894
     * If this is root node, the rotation can not be done.
891
     */
895
     */
892
    if (ROOT_NODE(lnode))
896
    if (ROOT_NODE(lnode))
893
        return false;
897
        return false;
894
   
898
   
895
    idx = find_key_by_subtree(lnode->parent, lnode, false);
899
    idx = find_key_by_subtree(lnode->parent, lnode, false);
896
    if (idx == lnode->parent->keys) {
900
    if (idx == lnode->parent->keys) {
897
        /*
901
        /*
898
         * If this node is the rightmost subtree of its parent,
902
         * If this node is the rightmost subtree of its parent,
899
         * the rotation can not be done.
903
         * the rotation can not be done.
900
         */
904
         */
901
        return false;
905
        return false;
902
    }
906
    }
903
       
907
       
904
    rnode = lnode->parent->subtree[idx + 1];
908
    rnode = lnode->parent->subtree[idx + 1];
905
    if (rnode->keys > FILL_FACTOR) {
909
    if (rnode->keys > FILL_FACTOR) {
906
        rotate_from_right(lnode, rnode, idx);
910
        rotate_from_right(lnode, rnode, idx);
907
        return true;
911
        return true;
908
    }  
912
    }  
909
 
913
 
910
    return false;
914
    return false;
911
}
915
}
912
 
916
 
913
/** Print B-tree.
917
/** Print B-tree.
914
 *
918
 *
915
 * @param t Print out B-tree.
919
 * @param t Print out B-tree.
916
 */
920
 */
917
void btree_print(btree_t *t)
921
void btree_print(btree_t *t)
918
{
922
{
919
    int i, depth = t->root->depth;
923
    int i, depth = t->root->depth;
920
    link_t head, *cur;
924
    link_t head, *cur;
921
 
925
 
922
    printf("Printing B-tree:\n");
926
    printf("Printing B-tree:\n");
923
    list_initialize(&head);
927
    list_initialize(&head);
924
    list_append(&t->root->bfs_link, &head);
928
    list_append(&t->root->bfs_link, &head);
925
 
929
 
926
    /*
930
    /*
927
     * Use BFS search to print out the tree.
931
     * Use BFS search to print out the tree.
928
     * Levels are distinguished from one another by node->depth.
932
     * Levels are distinguished from one another by node->depth.
929
     */
933
     */
930
    while (!list_empty(&head)) {
934
    while (!list_empty(&head)) {
931
        link_t *hlp;
935
        link_t *hlp;
932
        btree_node_t *node;
936
        btree_node_t *node;
933
       
937
       
934
        hlp = head.next;
938
        hlp = head.next;
935
        ASSERT(hlp != &head);
939
        ASSERT(hlp != &head);
936
        node = list_get_instance(hlp, btree_node_t, bfs_link);
940
        node = list_get_instance(hlp, btree_node_t, bfs_link);
937
        list_remove(hlp);
941
        list_remove(hlp);
938
       
942
       
939
        ASSERT(node);
943
        ASSERT(node);
940
       
944
       
941
        if (node->depth != depth) {
945
        if (node->depth != depth) {
942
            printf("\n");
946
            printf("\n");
943
            depth = node->depth;
947
            depth = node->depth;
944
        }
948
        }
945
 
949
 
946
        printf("(");
950
        printf("(");
947
        for (i = 0; i < node->keys; i++) {
951
        for (i = 0; i < node->keys; i++) {
948
            printf("%lld%s", node->key[i], i < node->keys - 1 ? "," : "");
952
            printf("%lld%s", node->key[i], i < node->keys - 1 ? "," : "");
949
            if (node->depth && node->subtree[i]) {
953
            if (node->depth && node->subtree[i]) {
950
                list_append(&node->subtree[i]->bfs_link, &head);
954
                list_append(&node->subtree[i]->bfs_link, &head);
951
            }
955
            }
952
        }
956
        }
953
        if (node->depth && node->subtree[i]) {
957
        if (node->depth && node->subtree[i]) {
954
            list_append(&node->subtree[i]->bfs_link, &head);
958
            list_append(&node->subtree[i]->bfs_link, &head);
955
        }
959
        }
956
        printf(")");
960
        printf(")");
957
    }
961
    }
958
    printf("\n");
962
    printf("\n");
959
   
963
   
960
    printf("Printing list of leaves:\n");
964
    printf("Printing list of leaves:\n");
961
    for (cur = t->leaf_head.next; cur != &t->leaf_head; cur = cur->next) {
965
    for (cur = t->leaf_head.next; cur != &t->leaf_head; cur = cur->next) {
962
        btree_node_t *node;
966
        btree_node_t *node;
963
       
967
       
964
        node = list_get_instance(cur, btree_node_t, leaf_link);
968
        node = list_get_instance(cur, btree_node_t, leaf_link);
965
       
969
       
966
        ASSERT(node);
970
        ASSERT(node);
967
 
971
 
968
        printf("(");
972
        printf("(");
969
        for (i = 0; i < node->keys; i++)
973
        for (i = 0; i < node->keys; i++)
970
            printf("%lld%s", node->key[i], i < node->keys - 1 ? "," : "");
974
            printf("%lld%s", node->key[i], i < node->keys - 1 ? "," : "");
971
        printf(")");
975
        printf(")");
972
    }
976
    }
973
    printf("\n");
977
    printf("\n");
974
}
978
}
975
 
979