Subversion Repositories HelenOS-historic

Rev

Rev 1248 | Rev 1702 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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