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
39 #include <sys/types.h>
49 static int bt_broot __P((BTREE *, PAGE *, PAGE *, PAGE *));
51 __P((BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t));
52 static int bt_preserve __P((BTREE *, pgno_t));
53 static PAGE *bt_psplit
54 __P((BTREE *, PAGE *, PAGE *, PAGE *, indx_t *, size_t));
56 __P((BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t));
57 static int bt_rroot __P((BTREE *, PAGE *, PAGE *, PAGE *));
58 static recno_t rec_total __P((PAGE *));
61 u_long bt_rootsplit, bt_split, bt_sortsplit, bt_pfxsaved;
65 * __BT_SPLIT -- Split the tree.
71 * data: data to insert
72 * flags: BIGKEY/BIGDATA flags
74 * skip: index to leave open
77 * RET_ERROR, RET_SUCCESS
80 __bt_split(t, sp, key, data, flags, ilen, argskip)
83 const DBT *key, *data;
92 PAGE *h, *l, *r, *lchild, *rchild;
95 u_int32_t n, nbytes, nksize;
100 * Split the page into two pages, l and r. The split routines return
101 * a pointer to the page into which the key should be inserted and with
102 * skip set to the offset which should be used. Additionally, l and r
106 h = sp->pgno == P_ROOT ?
107 bt_root(t, sp, &l, &r, &skip, ilen) :
108 bt_page(t, sp, &l, &r, &skip, ilen);
113 * Insert the new key/data pair into the leaf page. (Key inserts
114 * always cause a leaf page to split first.)
116 h->linp[skip] = h->upper -= ilen;
117 dest = (char *)h + h->upper;
118 if (F_ISSET(t, R_RECNO))
119 WR_RLEAF(dest, data, flags)
121 WR_BLEAF(dest, key, data, flags)
123 /* If the root page was split, make it look right. */
124 if (sp->pgno == P_ROOT &&
125 (F_ISSET(t, R_RECNO) ?
126 bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
130 * Now we walk the parent page stack -- a LIFO stack of the pages that
131 * were traversed when we searched for the page that split. Each stack
132 * entry is a page number and a page index offset. The offset is for
133 * the page traversed on the search. We've just split a page, so we
134 * have to insert a new key into the parent page.
136 * If the insert into the parent page causes it to split, may have to
137 * continue splitting all the way up the tree. We stop if the root
138 * splits or the page inserted into didn't have to split to hold the
139 * new key. Some algorithms replace the key for the old page as well
140 * as the new page. We don't, as there's no reason to believe that the
141 * first key on the old page is any better than the key we have, and,
142 * in the case of a key being placed at index 0 causing the split, the
143 * key is unavailable.
145 * There are a maximum of 5 pages pinned at any time. We keep the left
146 * and right pages pinned while working on the parent. The 5 are the
147 * two children, left parent and right parent (when the parent splits)
148 * and the root page or the overflow key page when calling bt_preserve.
149 * This code must make sure that all pins are released other than the
150 * root page or overflow page which is unlocked elsewhere.
152 while ((parent = BT_POP(t)) != NULL) {
156 /* Get the parent page. */
157 if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
161 * The new key goes ONE AFTER the index, because the split
164 skip = parent->index + 1;
167 * Calculate the space needed on the parent page.
169 * Prefix trees: space hack when inserting into BINTERNAL
170 * pages. Retain only what's needed to distinguish between
171 * the new entry and the LAST entry on the page to its left.
172 * If the keys compare equal, retain the entire key. Note,
173 * we don't touch overflow keys, and the entire key must be
174 * retained for the next-to-left most key on the leftmost
175 * page of each level, or the search will fail. Applicable
176 * ONLY to internal pages that have leaf pages as children.
177 * Further reduction of the key between pairs of internal
178 * pages loses too much information.
180 switch (rchild->flags & P_TYPE) {
182 bi = GETBINTERNAL(rchild, 0);
183 nbytes = NBINTERNAL(bi->ksize);
186 bl = GETBLEAF(rchild, 0);
187 nbytes = NBINTERNAL(bl->ksize);
188 if (t->bt_pfx && !(bl->flags & P_BIGKEY) &&
189 (h->prevpg != P_INVALID || skip > 1)) {
190 tbl = GETBLEAF(lchild, NEXTINDEX(lchild) - 1);
195 nksize = t->bt_pfx(&a, &b);
196 n = NBINTERNAL(nksize);
199 bt_pfxsaved += nbytes - n;
215 /* Split the parent page if necessary or shift the indices. */
216 if (h->upper - h->lower < nbytes + sizeof(indx_t)) {
218 h = h->pgno == P_ROOT ?
219 bt_root(t, h, &l, &r, &skip, nbytes) :
220 bt_page(t, h, &l, &r, &skip, nbytes);
225 if (skip < (nxtindex = NEXTINDEX(h)))
226 memmove(h->linp + skip + 1, h->linp + skip,
227 (nxtindex - skip) * sizeof(indx_t));
228 h->lower += sizeof(indx_t);
232 /* Insert the key into the parent page. */
233 switch (rchild->flags & P_TYPE) {
235 h->linp[skip] = h->upper -= nbytes;
236 dest = (char *)h + h->linp[skip];
237 memmove(dest, bi, nbytes);
238 ((BINTERNAL *)dest)->pgno = rchild->pgno;
241 h->linp[skip] = h->upper -= nbytes;
242 dest = (char *)h + h->linp[skip];
243 WR_BINTERNAL(dest, nksize ? nksize : bl->ksize,
244 rchild->pgno, bl->flags & P_BIGKEY);
245 memmove(dest, bl->bytes, nksize ? nksize : bl->ksize);
246 if (bl->flags & P_BIGKEY &&
247 bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR)
252 * Update the left page count. If split
253 * added at index 0, fix the correct page.
256 dest = (char *)h + h->linp[skip - 1];
258 dest = (char *)l + l->linp[NEXTINDEX(l) - 1];
259 ((RINTERNAL *)dest)->nrecs = rec_total(lchild);
260 ((RINTERNAL *)dest)->pgno = lchild->pgno;
262 /* Update the right page count. */
263 h->linp[skip] = h->upper -= nbytes;
264 dest = (char *)h + h->linp[skip];
265 ((RINTERNAL *)dest)->nrecs = rec_total(rchild);
266 ((RINTERNAL *)dest)->pgno = rchild->pgno;
270 * Update the left page count. If split
271 * added at index 0, fix the correct page.
274 dest = (char *)h + h->linp[skip - 1];
276 dest = (char *)l + l->linp[NEXTINDEX(l) - 1];
277 ((RINTERNAL *)dest)->nrecs = NEXTINDEX(lchild);
278 ((RINTERNAL *)dest)->pgno = lchild->pgno;
280 /* Update the right page count. */
281 h->linp[skip] = h->upper -= nbytes;
282 dest = (char *)h + h->linp[skip];
283 ((RINTERNAL *)dest)->nrecs = NEXTINDEX(rchild);
284 ((RINTERNAL *)dest)->pgno = rchild->pgno;
290 /* Unpin the held pages. */
292 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
296 /* If the root page was split, make it look right. */
297 if (sp->pgno == P_ROOT &&
298 (F_ISSET(t, R_RECNO) ?
299 bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
302 mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
303 mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
306 /* Unpin the held pages. */
307 mpool_put(t->bt_mp, l, MPOOL_DIRTY);
308 mpool_put(t->bt_mp, r, MPOOL_DIRTY);
310 /* Clear any pages left on the stack. */
311 return (RET_SUCCESS);
314 * If something fails in the above loop we were already walking back
315 * up the tree and the tree is now inconsistent. Nothing much we can
316 * do about it but release any memory we're holding.
318 err1: mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
319 mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
321 err2: mpool_put(t->bt_mp, l, 0);
322 mpool_put(t->bt_mp, r, 0);
323 __dbpanic(t->bt_dbp);
328 * BT_PAGE -- Split a non-root page of a btree.
333 * lp: pointer to left page pointer
334 * rp: pointer to right page pointer
335 * skip: pointer to index to leave open
336 * ilen: insert length
339 * Pointer to page in which to insert or NULL on error.
342 bt_page(t, h, lp, rp, skip, ilen)
354 /* Put the new right page for the split into place. */
355 if ((r = __bt_new(t, &npg)) == NULL)
358 r->lower = BTDATAOFF;
359 r->upper = t->bt_psize;
360 r->nextpg = h->nextpg;
362 r->flags = h->flags & P_TYPE;
365 * If we're splitting the last page on a level because we're appending
366 * a key to it (skip is NEXTINDEX()), it's likely that the data is
367 * sorted. Adding an empty page on the side of the level is less work
368 * and can push the fill factor much higher than normal. If we're
369 * wrong it's no big deal, we'll just do the split the right way next
370 * time. It may look like it's equally easy to do a similar hack for
371 * reverse sorted data, that is, split the tree left, but it's not.
374 if (h->nextpg == P_INVALID && *skip == NEXTINDEX(h)) {
379 r->lower = BTDATAOFF + sizeof(indx_t);
386 /* Put the new left page for the split into place. */
387 if ((l = (PAGE *)malloc(t->bt_psize)) == NULL) {
388 mpool_put(t->bt_mp, r, 0);
392 memset(l, 0xff, t->bt_psize);
396 l->prevpg = h->prevpg;
397 l->lower = BTDATAOFF;
398 l->upper = t->bt_psize;
399 l->flags = h->flags & P_TYPE;
401 /* Fix up the previous pointer of the page after the split page. */
402 if (h->nextpg != P_INVALID) {
403 if ((tp = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) {
405 /* XXX mpool_free(t->bt_mp, r->pgno); */
408 tp->prevpg = r->pgno;
409 mpool_put(t->bt_mp, tp, MPOOL_DIRTY);
413 * Split right. The key/data pairs aren't sorted in the btree page so
414 * it's simpler to copy the data from the split page onto two new pages
415 * instead of copying half the data to the right page and compacting
416 * the left page in place. Since the left page can't change, we have
417 * to swap the original and the allocated left page after the split.
419 tp = bt_psplit(t, h, l, r, skip, ilen);
421 /* Move the new left page onto the old left page. */
422 memmove(h, l, t->bt_psize);
433 * BT_ROOT -- Split the root page of a btree.
438 * lp: pointer to left page pointer
439 * rp: pointer to right page pointer
440 * skip: pointer to index to leave open
441 * ilen: insert length
444 * Pointer to page in which to insert or NULL on error.
447 bt_root(t, h, lp, rp, skip, ilen)
460 /* Put the new left and right pages for the split into place. */
461 if ((l = __bt_new(t, &lnpg)) == NULL ||
462 (r = __bt_new(t, &rnpg)) == NULL)
468 l->prevpg = r->nextpg = P_INVALID;
469 l->lower = r->lower = BTDATAOFF;
470 l->upper = r->upper = t->bt_psize;
471 l->flags = r->flags = h->flags & P_TYPE;
473 /* Split the root page. */
474 tp = bt_psplit(t, h, l, r, skip, ilen);
482 * BT_RROOT -- Fix up the recno root page after it has been split.
491 * RET_ERROR, RET_SUCCESS
500 /* Insert the left and right keys, set the header information. */
501 h->linp[0] = h->upper = t->bt_psize - NRINTERNAL;
502 dest = (char *)h + h->upper;
504 l->flags & P_RLEAF ? NEXTINDEX(l) : rec_total(l), l->pgno);
506 h->linp[1] = h->upper -= NRINTERNAL;
507 dest = (char *)h + h->upper;
509 r->flags & P_RLEAF ? NEXTINDEX(r) : rec_total(r), r->pgno);
511 h->lower = BTDATAOFF + 2 * sizeof(indx_t);
513 /* Unpin the root page, set to recno internal page. */
515 h->flags |= P_RINTERNAL;
516 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
518 return (RET_SUCCESS);
522 * BT_BROOT -- Fix up the btree root page after it has been split.
531 * RET_ERROR, RET_SUCCESS
544 * If the root page was a leaf page, change it into an internal page.
545 * We copy the key we split on (but not the key's data, in the case of
546 * a leaf page) to the new root page.
548 * The btree comparison code guarantees that the left-most key on any
549 * level of the tree is never used, so it doesn't need to be filled in.
551 nbytes = NBINTERNAL(0);
552 h->linp[0] = h->upper = t->bt_psize - nbytes;
553 dest = (char *)h + h->upper;
554 WR_BINTERNAL(dest, 0, l->pgno, 0);
556 switch (h->flags & P_TYPE) {
559 nbytes = NBINTERNAL(bl->ksize);
560 h->linp[1] = h->upper -= nbytes;
561 dest = (char *)h + h->upper;
562 WR_BINTERNAL(dest, bl->ksize, r->pgno, 0);
563 memmove(dest, bl->bytes, bl->ksize);
566 * If the key is on an overflow page, mark the overflow chain
567 * so it isn't deleted when the leaf copy of the key is deleted.
569 if (bl->flags & P_BIGKEY &&
570 bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR)
574 bi = GETBINTERNAL(r, 0);
575 nbytes = NBINTERNAL(bi->ksize);
576 h->linp[1] = h->upper -= nbytes;
577 dest = (char *)h + h->upper;
578 memmove(dest, bi, nbytes);
579 ((BINTERNAL *)dest)->pgno = r->pgno;
585 /* There are two keys on the page. */
586 h->lower = BTDATAOFF + 2 * sizeof(indx_t);
588 /* Unpin the root page, set to btree internal page. */
590 h->flags |= P_BINTERNAL;
591 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
593 return (RET_SUCCESS);
597 * BT_PSPLIT -- Do the real work of splitting the page.
601 * h: page to be split
602 * l: page to put lower half of data
603 * r: page to put upper half of data
604 * pskip: pointer to index to leave open
605 * ilen: insert length
608 * Pointer to page in which to insert.
611 bt_psplit(t, h, l, r, pskip, ilen)
623 indx_t full, half, nxt, off, skip, top, used;
625 int bigkeycnt, isbigkey;
628 * Split the data to the left and right pages. Leave the skip index
629 * open. Additionally, make some effort not to split on an overflow
630 * key. This makes internal page processing faster and can save
631 * space as overflow keys used by internal pages are never deleted.
635 full = t->bt_psize - BTDATAOFF;
638 for (nxt = off = 0, top = NEXTINDEX(h); nxt < top; ++off) {
641 isbigkey = 0; /* XXX: not really known. */
643 switch (h->flags & P_TYPE) {
645 src = bi = GETBINTERNAL(h, nxt);
646 nbytes = NBINTERNAL(bi->ksize);
647 isbigkey = bi->flags & P_BIGKEY;
650 src = bl = GETBLEAF(h, nxt);
652 isbigkey = bl->flags & P_BIGKEY;
655 src = GETRINTERNAL(h, nxt);
660 src = rl = GETRLEAF(h, nxt);
669 * If the key/data pairs are substantial fractions of the max
670 * possible size for the page, it's possible to get situations
671 * where we decide to try and copy too much onto the left page.
672 * Make sure that doesn't happen.
675 used + nbytes + sizeof(indx_t) >= full || nxt == top - 1) {
680 /* Copy the key/data pair, if not the skipped index. */
684 l->linp[off] = l->upper -= nbytes;
685 memmove((char *)l + l->upper, src, nbytes);
688 used += nbytes + sizeof(indx_t);
690 if (!isbigkey || bigkeycnt == 3)
698 * Off is the last offset that's valid for the left page.
699 * Nxt is the first offset to be placed on the right page.
701 l->lower += (off + 1) * sizeof(indx_t);
704 * If splitting the page that the cursor was on, the cursor has to be
705 * adjusted to point to the same record as before the split. If the
706 * cursor is at or past the skipped slot, the cursor is incremented by
707 * one. If the cursor is on the right page, it is decremented by the
708 * number of records split to the left page.
711 if (F_ISSET(c, CURS_INIT) && c->pg.pgno == h->pgno) {
712 if (c->pg.index >= skip)
714 if (c->pg.index < nxt) /* Left page. */
715 c->pg.pgno = l->pgno;
716 else { /* Right page. */
717 c->pg.pgno = r->pgno;
723 * If the skipped index was on the left page, just return that page.
724 * Otherwise, adjust the skip index to reflect the new position on
735 for (off = 0; nxt < top; ++off) {
740 switch (h->flags & P_TYPE) {
742 src = bi = GETBINTERNAL(h, nxt);
743 nbytes = NBINTERNAL(bi->ksize);
746 src = bl = GETBLEAF(h, nxt);
750 src = GETRINTERNAL(h, nxt);
754 src = rl = GETRLEAF(h, nxt);
761 r->linp[off] = r->upper -= nbytes;
762 memmove((char *)r + r->upper, src, nbytes);
764 r->lower += off * sizeof(indx_t);
766 /* If the key is being appended to the page, adjust the index. */
768 r->lower += sizeof(indx_t);
774 * BT_PRESERVE -- Mark a chain of pages as used by an internal node.
776 * Chains of indirect blocks pointed to by leaf nodes get reclaimed when the
777 * record that references them gets deleted. Chains pointed to by internal
778 * pages never get deleted. This routine marks a chain as pointed to by an
783 * pg: page number of first page in the chain.
786 * RET_SUCCESS, RET_ERROR.
795 if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
797 h->flags |= P_PRESERVE;
798 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
799 return (RET_SUCCESS);
803 * REC_TOTAL -- Return the number of recno entries below a page.
809 * The number of recno entries below a page.
812 * These values could be set by the bt_psplit routine. The problem is that the
813 * entry has to be popped off of the stack etc. or the values have to be passed
814 * all the way back to bt_split/bt_rroot and it's not very clean.
823 for (recs = 0, nxt = 0, top = NEXTINDEX(h); nxt < top; ++nxt)
824 recs += GETRINTERNAL(h, nxt)->nrecs;