Subversion Repositories HelenOS

Rev

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

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