2 * Copyright (c) 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)bt_split.c 8.9 (Berkeley) 7/26/94
37 * $DragonFly: src/lib/libc/db/btree/bt_split.c,v 1.4 2003/11/12 20:21:22 eirikn Exp $
40 #include <sys/types.h>
50 static int bt_broot (BTREE *, PAGE *, PAGE *, PAGE *);
52 (BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
53 static int bt_preserve (BTREE *, pgno_t);
54 static PAGE *bt_psplit
55 (BTREE *, PAGE *, PAGE *, PAGE *, indx_t *, size_t);
57 (BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
58 static int bt_rroot (BTREE *, PAGE *, PAGE *, PAGE *);
59 static recno_t rec_total (PAGE *);
62 u_long bt_rootsplit, bt_split, bt_sortsplit, bt_pfxsaved;
66 * __BT_SPLIT -- Split the tree.
72 * data: data to insert
73 * flags: BIGKEY/BIGDATA flags
75 * skip: index to leave open
78 * RET_ERROR, RET_SUCCESS
81 __bt_split(t, sp, key, data, flags, ilen, argskip)
84 const DBT *key, *data;
93 PAGE *h, *l, *r, *lchild, *rchild;
96 u_int32_t n, nbytes, nksize;
101 * Split the page into two pages, l and r. The split routines return
102 * a pointer to the page into which the key should be inserted and with
103 * skip set to the offset which should be used. Additionally, l and r
107 h = sp->pgno == P_ROOT ?
108 bt_root(t, sp, &l, &r, &skip, ilen) :
109 bt_page(t, sp, &l, &r, &skip, ilen);
114 * Insert the new key/data pair into the leaf page. (Key inserts
115 * always cause a leaf page to split first.)
117 h->linp[skip] = h->upper -= ilen;
118 dest = (char *)h + h->upper;
119 if (F_ISSET(t, R_RECNO))
120 WR_RLEAF(dest, data, flags)
122 WR_BLEAF(dest, key, data, flags)
124 /* If the root page was split, make it look right. */
125 if (sp->pgno == P_ROOT &&
126 (F_ISSET(t, R_RECNO) ?
127 bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
131 * Now we walk the parent page stack -- a LIFO stack of the pages that
132 * were traversed when we searched for the page that split. Each stack
133 * entry is a page number and a page index offset. The offset is for
134 * the page traversed on the search. We've just split a page, so we
135 * have to insert a new key into the parent page.
137 * If the insert into the parent page causes it to split, may have to
138 * continue splitting all the way up the tree. We stop if the root
139 * splits or the page inserted into didn't have to split to hold the
140 * new key. Some algorithms replace the key for the old page as well
141 * as the new page. We don't, as there's no reason to believe that the
142 * first key on the old page is any better than the key we have, and,
143 * in the case of a key being placed at index 0 causing the split, the
144 * key is unavailable.
146 * There are a maximum of 5 pages pinned at any time. We keep the left
147 * and right pages pinned while working on the parent. The 5 are the
148 * two children, left parent and right parent (when the parent splits)
149 * and the root page or the overflow key page when calling bt_preserve.
150 * This code must make sure that all pins are released other than the
151 * root page or overflow page which is unlocked elsewhere.
153 while ((parent = BT_POP(t)) != NULL) {
157 /* Get the parent page. */
158 if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
162 * The new key goes ONE AFTER the index, because the split
165 skip = parent->index + 1;
168 * Calculate the space needed on the parent page.
170 * Prefix trees: space hack when inserting into BINTERNAL
171 * pages. Retain only what's needed to distinguish between
172 * the new entry and the LAST entry on the page to its left.
173 * If the keys compare equal, retain the entire key. Note,
174 * we don't touch overflow keys, and the entire key must be
175 * retained for the next-to-left most key on the leftmost
176 * page of each level, or the search will fail. Applicable
177 * ONLY to internal pages that have leaf pages as children.
178 * Further reduction of the key between pairs of internal
179 * pages loses too much information.
181 switch (rchild->flags & P_TYPE) {
183 bi = GETBINTERNAL(rchild, 0);
184 nbytes = NBINTERNAL(bi->ksize);
187 bl = GETBLEAF(rchild, 0);
188 nbytes = NBINTERNAL(bl->ksize);
189 if (t->bt_pfx && !(bl->flags & P_BIGKEY) &&
190 (h->prevpg != P_INVALID || skip > 1)) {
191 tbl = GETBLEAF(lchild, NEXTINDEX(lchild) - 1);
196 nksize = t->bt_pfx(&a, &b);
197 n = NBINTERNAL(nksize);
200 bt_pfxsaved += nbytes - n;
216 /* Split the parent page if necessary or shift the indices. */
217 if (h->upper - h->lower < nbytes + sizeof(indx_t)) {
219 h = h->pgno == P_ROOT ?
220 bt_root(t, h, &l, &r, &skip, nbytes) :
221 bt_page(t, h, &l, &r, &skip, nbytes);
226 if (skip < (nxtindex = NEXTINDEX(h)))
227 memmove(h->linp + skip + 1, h->linp + skip,
228 (nxtindex - skip) * sizeof(indx_t));
229 h->lower += sizeof(indx_t);
233 /* Insert the key into the parent page. */
234 switch (rchild->flags & P_TYPE) {
236 h->linp[skip] = h->upper -= nbytes;
237 dest = (char *)h + h->linp[skip];
238 memmove(dest, bi, nbytes);
239 ((BINTERNAL *)dest)->pgno = rchild->pgno;
242 h->linp[skip] = h->upper -= nbytes;
243 dest = (char *)h + h->linp[skip];
244 WR_BINTERNAL(dest, nksize ? nksize : bl->ksize,
245 rchild->pgno, bl->flags & P_BIGKEY);
246 memmove(dest, bl->bytes, nksize ? nksize : bl->ksize);
247 if (bl->flags & P_BIGKEY &&
248 bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR)
253 * Update the left page count. If split
254 * added at index 0, fix the correct page.
257 dest = (char *)h + h->linp[skip - 1];
259 dest = (char *)l + l->linp[NEXTINDEX(l) - 1];
260 ((RINTERNAL *)dest)->nrecs = rec_total(lchild);
261 ((RINTERNAL *)dest)->pgno = lchild->pgno;
263 /* Update the right page count. */
264 h->linp[skip] = h->upper -= nbytes;
265 dest = (char *)h + h->linp[skip];
266 ((RINTERNAL *)dest)->nrecs = rec_total(rchild);
267 ((RINTERNAL *)dest)->pgno = rchild->pgno;
271 * Update the left page count. If split
272 * added at index 0, fix the correct page.
275 dest = (char *)h + h->linp[skip - 1];
277 dest = (char *)l + l->linp[NEXTINDEX(l) - 1];
278 ((RINTERNAL *)dest)->nrecs = NEXTINDEX(lchild);
279 ((RINTERNAL *)dest)->pgno = lchild->pgno;
281 /* Update the right page count. */
282 h->linp[skip] = h->upper -= nbytes;
283 dest = (char *)h + h->linp[skip];
284 ((RINTERNAL *)dest)->nrecs = NEXTINDEX(rchild);
285 ((RINTERNAL *)dest)->pgno = rchild->pgno;
291 /* Unpin the held pages. */
293 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
297 /* If the root page was split, make it look right. */
298 if (sp->pgno == P_ROOT &&
299 (F_ISSET(t, R_RECNO) ?
300 bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
303 mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
304 mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
307 /* Unpin the held pages. */
308 mpool_put(t->bt_mp, l, MPOOL_DIRTY);
309 mpool_put(t->bt_mp, r, MPOOL_DIRTY);
311 /* Clear any pages left on the stack. */
312 return (RET_SUCCESS);
315 * If something fails in the above loop we were already walking back
316 * up the tree and the tree is now inconsistent. Nothing much we can
317 * do about it but release any memory we're holding.
319 err1: mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
320 mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
322 err2: mpool_put(t->bt_mp, l, 0);
323 mpool_put(t->bt_mp, r, 0);
324 __dbpanic(t->bt_dbp);
329 * BT_PAGE -- Split a non-root page of a btree.
334 * lp: pointer to left page pointer
335 * rp: pointer to right page pointer
336 * skip: pointer to index to leave open
337 * ilen: insert length
340 * Pointer to page in which to insert or NULL on error.
343 bt_page(t, h, lp, rp, skip, ilen)
355 /* Put the new right page for the split into place. */
356 if ((r = __bt_new(t, &npg)) == NULL)
359 r->lower = BTDATAOFF;
360 r->upper = t->bt_psize;
361 r->nextpg = h->nextpg;
363 r->flags = h->flags & P_TYPE;
366 * If we're splitting the last page on a level because we're appending
367 * a key to it (skip is NEXTINDEX()), it's likely that the data is
368 * sorted. Adding an empty page on the side of the level is less work
369 * and can push the fill factor much higher than normal. If we're
370 * wrong it's no big deal, we'll just do the split the right way next
371 * time. It may look like it's equally easy to do a similar hack for
372 * reverse sorted data, that is, split the tree left, but it's not.
375 if (h->nextpg == P_INVALID && *skip == NEXTINDEX(h)) {
380 r->lower = BTDATAOFF + sizeof(indx_t);
387 /* Put the new left page for the split into place. */
388 if ((l = (PAGE *)malloc(t->bt_psize)) == NULL) {
389 mpool_put(t->bt_mp, r, 0);
393 memset(l, 0xff, t->bt_psize);
397 l->prevpg = h->prevpg;
398 l->lower = BTDATAOFF;
399 l->upper = t->bt_psize;
400 l->flags = h->flags & P_TYPE;
402 /* Fix up the previous pointer of the page after the split page. */
403 if (h->nextpg != P_INVALID) {
404 if ((tp = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) {
406 /* XXX mpool_free(t->bt_mp, r->pgno); */
409 tp->prevpg = r->pgno;
410 mpool_put(t->bt_mp, tp, MPOOL_DIRTY);
414 * Split right. The key/data pairs aren't sorted in the btree page so
415 * it's simpler to copy the data from the split page onto two new pages
416 * instead of copying half the data to the right page and compacting
417 * the left page in place. Since the left page can't change, we have
418 * to swap the original and the allocated left page after the split.
420 tp = bt_psplit(t, h, l, r, skip, ilen);
422 /* Move the new left page onto the old left page. */
423 memmove(h, l, t->bt_psize);
434 * BT_ROOT -- Split the root page of a btree.
439 * lp: pointer to left page pointer
440 * rp: pointer to right page pointer
441 * skip: pointer to index to leave open
442 * ilen: insert length
445 * Pointer to page in which to insert or NULL on error.
448 bt_root(t, h, lp, rp, skip, ilen)
461 /* Put the new left and right pages for the split into place. */
462 if ((l = __bt_new(t, &lnpg)) == NULL ||
463 (r = __bt_new(t, &rnpg)) == NULL)
469 l->prevpg = r->nextpg = P_INVALID;
470 l->lower = r->lower = BTDATAOFF;
471 l->upper = r->upper = t->bt_psize;
472 l->flags = r->flags = h->flags & P_TYPE;
474 /* Split the root page. */
475 tp = bt_psplit(t, h, l, r, skip, ilen);
483 * BT_RROOT -- Fix up the recno root page after it has been split.
492 * RET_ERROR, RET_SUCCESS
501 /* Insert the left and right keys, set the header information. */
502 h->linp[0] = h->upper = t->bt_psize - NRINTERNAL;
503 dest = (char *)h + h->upper;
505 l->flags & P_RLEAF ? NEXTINDEX(l) : rec_total(l), l->pgno);
507 h->linp[1] = h->upper -= NRINTERNAL;
508 dest = (char *)h + h->upper;
510 r->flags & P_RLEAF ? NEXTINDEX(r) : rec_total(r), r->pgno);
512 h->lower = BTDATAOFF + 2 * sizeof(indx_t);
514 /* Unpin the root page, set to recno internal page. */
516 h->flags |= P_RINTERNAL;
517 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
519 return (RET_SUCCESS);
523 * BT_BROOT -- Fix up the btree root page after it has been split.
532 * RET_ERROR, RET_SUCCESS
545 * If the root page was a leaf page, change it into an internal page.
546 * We copy the key we split on (but not the key's data, in the case of
547 * a leaf page) to the new root page.
549 * The btree comparison code guarantees that the left-most key on any
550 * level of the tree is never used, so it doesn't need to be filled in.
552 nbytes = NBINTERNAL(0);
553 h->linp[0] = h->upper = t->bt_psize - nbytes;
554 dest = (char *)h + h->upper;
555 WR_BINTERNAL(dest, 0, l->pgno, 0);
557 switch (h->flags & P_TYPE) {
560 nbytes = NBINTERNAL(bl->ksize);
561 h->linp[1] = h->upper -= nbytes;
562 dest = (char *)h + h->upper;
563 WR_BINTERNAL(dest, bl->ksize, r->pgno, 0);
564 memmove(dest, bl->bytes, bl->ksize);
567 * If the key is on an overflow page, mark the overflow chain
568 * so it isn't deleted when the leaf copy of the key is deleted.
570 if (bl->flags & P_BIGKEY &&
571 bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR)
575 bi = GETBINTERNAL(r, 0);
576 nbytes = NBINTERNAL(bi->ksize);
577 h->linp[1] = h->upper -= nbytes;
578 dest = (char *)h + h->upper;
579 memmove(dest, bi, nbytes);
580 ((BINTERNAL *)dest)->pgno = r->pgno;
586 /* There are two keys on the page. */
587 h->lower = BTDATAOFF + 2 * sizeof(indx_t);
589 /* Unpin the root page, set to btree internal page. */
591 h->flags |= P_BINTERNAL;
592 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
594 return (RET_SUCCESS);
598 * BT_PSPLIT -- Do the real work of splitting the page.
602 * h: page to be split
603 * l: page to put lower half of data
604 * r: page to put upper half of data
605 * pskip: pointer to index to leave open
606 * ilen: insert length
609 * Pointer to page in which to insert.
612 bt_psplit(t, h, l, r, pskip, ilen)
624 indx_t full, half, nxt, off, skip, top, used;
626 int bigkeycnt, isbigkey;
629 * Split the data to the left and right pages. Leave the skip index
630 * open. Additionally, make some effort not to split on an overflow
631 * key. This makes internal page processing faster and can save
632 * space as overflow keys used by internal pages are never deleted.
636 full = t->bt_psize - BTDATAOFF;
639 for (nxt = off = 0, top = NEXTINDEX(h); nxt < top; ++off) {
642 isbigkey = 0; /* XXX: not really known. */
644 switch (h->flags & P_TYPE) {
646 src = bi = GETBINTERNAL(h, nxt);
647 nbytes = NBINTERNAL(bi->ksize);
648 isbigkey = bi->flags & P_BIGKEY;
651 src = bl = GETBLEAF(h, nxt);
653 isbigkey = bl->flags & P_BIGKEY;
656 src = GETRINTERNAL(h, nxt);
661 src = rl = GETRLEAF(h, nxt);
670 * If the key/data pairs are substantial fractions of the max
671 * possible size for the page, it's possible to get situations
672 * where we decide to try and copy too much onto the left page.
673 * Make sure that doesn't happen.
676 used + nbytes + sizeof(indx_t) >= full || nxt == top - 1) {
681 /* Copy the key/data pair, if not the skipped index. */
685 l->linp[off] = l->upper -= nbytes;
686 memmove((char *)l + l->upper, src, nbytes);
689 used += nbytes + sizeof(indx_t);
691 if (!isbigkey || bigkeycnt == 3)
699 * Off is the last offset that's valid for the left page.
700 * Nxt is the first offset to be placed on the right page.
702 l->lower += (off + 1) * sizeof(indx_t);
705 * If splitting the page that the cursor was on, the cursor has to be
706 * adjusted to point to the same record as before the split. If the
707 * cursor is at or past the skipped slot, the cursor is incremented by
708 * one. If the cursor is on the right page, it is decremented by the
709 * number of records split to the left page.
712 if (F_ISSET(c, CURS_INIT) && c->pg.pgno == h->pgno) {
713 if (c->pg.index >= skip)
715 if (c->pg.index < nxt) /* Left page. */
716 c->pg.pgno = l->pgno;
717 else { /* Right page. */
718 c->pg.pgno = r->pgno;
724 * If the skipped index was on the left page, just return that page.
725 * Otherwise, adjust the skip index to reflect the new position on
736 for (off = 0; nxt < top; ++off) {
741 switch (h->flags & P_TYPE) {
743 src = bi = GETBINTERNAL(h, nxt);
744 nbytes = NBINTERNAL(bi->ksize);
747 src = bl = GETBLEAF(h, nxt);
751 src = GETRINTERNAL(h, nxt);
755 src = rl = GETRLEAF(h, nxt);
762 r->linp[off] = r->upper -= nbytes;
763 memmove((char *)r + r->upper, src, nbytes);
765 r->lower += off * sizeof(indx_t);
767 /* If the key is being appended to the page, adjust the index. */
769 r->lower += sizeof(indx_t);
775 * BT_PRESERVE -- Mark a chain of pages as used by an internal node.
777 * Chains of indirect blocks pointed to by leaf nodes get reclaimed when the
778 * record that references them gets deleted. Chains pointed to by internal
779 * pages never get deleted. This routine marks a chain as pointed to by an
784 * pg: page number of first page in the chain.
787 * RET_SUCCESS, RET_ERROR.
796 if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
798 h->flags |= P_PRESERVE;
799 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
800 return (RET_SUCCESS);
804 * REC_TOTAL -- Return the number of recno entries below a page.
810 * The number of recno entries below a page.
813 * These values could be set by the bt_psplit routine. The problem is that the
814 * entry has to be popped off of the stack etc. or the values have to be passed
815 * all the way back to bt_split/bt_rroot and it's not very clean.
824 for (recs = 0, nxt = 0, top = NEXTINDEX(h); nxt < top; ++nxt)
825 recs += GETRINTERNAL(h, nxt)->nrecs;