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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)bt_split.c 8.10 (Berkeley) 1/9/95";
35 #endif /* LIBC_SCCS and not lint */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/types.h>
40 #include <sys/param.h>
50 static int bt_broot(BTREE *, PAGE *, PAGE *, PAGE *);
51 static PAGE *bt_page(BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
52 static int bt_preserve(BTREE *, pgno_t);
53 static PAGE *bt_psplit(BTREE *, PAGE *, PAGE *, PAGE *, indx_t *, size_t);
54 static PAGE *bt_root(BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
55 static int bt_rroot(BTREE *, PAGE *, PAGE *, PAGE *);
56 static recno_t rec_total(PAGE *);
59 u_long bt_rootsplit, bt_split, bt_sortsplit, bt_pfxsaved;
63 * __BT_SPLIT -- Split the tree.
69 * data: data to insert
70 * flags: BIGKEY/BIGDATA flags
72 * skip: index to leave open
75 * RET_ERROR, RET_SUCCESS
78 __bt_split(BTREE *t, PAGE *sp, const DBT *key, const DBT *data, int flags,
79 size_t ilen, u_int32_t argskip)
85 PAGE *h, *l, *r, *lchild, *rchild;
88 u_int32_t n, nbytes, nksize;
93 * Split the page into two pages, l and r. The split routines return
94 * a pointer to the page into which the key should be inserted and with
95 * skip set to the offset which should be used. Additionally, l and r
99 h = sp->pgno == P_ROOT ?
100 bt_root(t, sp, &l, &r, &skip, ilen) :
101 bt_page(t, sp, &l, &r, &skip, ilen);
106 * Insert the new key/data pair into the leaf page. (Key inserts
107 * always cause a leaf page to split first.)
109 h->linp[skip] = h->upper -= ilen;
110 dest = (char *)h + h->upper;
111 if (F_ISSET(t, R_RECNO))
112 WR_RLEAF(dest, data, flags)
114 WR_BLEAF(dest, key, data, flags)
116 /* If the root page was split, make it look right. */
117 if (sp->pgno == P_ROOT &&
118 (F_ISSET(t, R_RECNO) ?
119 bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
123 * Now we walk the parent page stack -- a LIFO stack of the pages that
124 * were traversed when we searched for the page that split. Each stack
125 * entry is a page number and a page index offset. The offset is for
126 * the page traversed on the search. We've just split a page, so we
127 * have to insert a new key into the parent page.
129 * If the insert into the parent page causes it to split, may have to
130 * continue splitting all the way up the tree. We stop if the root
131 * splits or the page inserted into didn't have to split to hold the
132 * new key. Some algorithms replace the key for the old page as well
133 * as the new page. We don't, as there's no reason to believe that the
134 * first key on the old page is any better than the key we have, and,
135 * in the case of a key being placed at index 0 causing the split, the
136 * key is unavailable.
138 * There are a maximum of 5 pages pinned at any time. We keep the left
139 * and right pages pinned while working on the parent. The 5 are the
140 * two children, left parent and right parent (when the parent splits)
141 * and the root page or the overflow key page when calling bt_preserve.
142 * This code must make sure that all pins are released other than the
143 * root page or overflow page which is unlocked elsewhere.
145 while ((parent = BT_POP(t)) != NULL) {
149 /* Get the parent page. */
150 if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
154 * The new key goes ONE AFTER the index, because the split
157 skip = parent->index + 1;
160 * Calculate the space needed on the parent page.
162 * Prefix trees: space hack when inserting into BINTERNAL
163 * pages. Retain only what's needed to distinguish between
164 * the new entry and the LAST entry on the page to its left.
165 * If the keys compare equal, retain the entire key. Note,
166 * we don't touch overflow keys, and the entire key must be
167 * retained for the next-to-left most key on the leftmost
168 * page of each level, or the search will fail. Applicable
169 * ONLY to internal pages that have leaf pages as children.
170 * Further reduction of the key between pairs of internal
171 * pages loses too much information.
173 switch (rchild->flags & P_TYPE) {
175 bi = GETBINTERNAL(rchild, 0);
176 nbytes = NBINTERNAL(bi->ksize);
179 bl = GETBLEAF(rchild, 0);
180 nbytes = NBINTERNAL(bl->ksize);
181 if (t->bt_pfx && !(bl->flags & P_BIGKEY) &&
182 (h->prevpg != P_INVALID || skip > 1)) {
183 tbl = GETBLEAF(lchild, NEXTINDEX(lchild) - 1);
188 nksize = t->bt_pfx(&a, &b);
189 n = NBINTERNAL(nksize);
192 bt_pfxsaved += nbytes - n;
208 /* Split the parent page if necessary or shift the indices. */
209 if ((u_int32_t)(h->upper - h->lower) < nbytes + sizeof(indx_t)) {
211 h = h->pgno == P_ROOT ?
212 bt_root(t, h, &l, &r, &skip, nbytes) :
213 bt_page(t, h, &l, &r, &skip, nbytes);
218 if (skip < (nxtindex = NEXTINDEX(h)))
219 memmove(h->linp + skip + 1, h->linp + skip,
220 (nxtindex - skip) * sizeof(indx_t));
221 h->lower += sizeof(indx_t);
225 /* Insert the key into the parent page. */
226 switch (rchild->flags & P_TYPE) {
228 h->linp[skip] = h->upper -= nbytes;
229 dest = (char *)h + h->linp[skip];
230 memmove(dest, bi, nbytes);
231 ((BINTERNAL *)dest)->pgno = rchild->pgno;
234 h->linp[skip] = h->upper -= nbytes;
235 dest = (char *)h + h->linp[skip];
236 WR_BINTERNAL(dest, nksize ? nksize : bl->ksize,
237 rchild->pgno, bl->flags & P_BIGKEY);
238 memmove(dest, bl->bytes, nksize ? nksize : bl->ksize);
239 if (bl->flags & P_BIGKEY &&
240 bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR)
245 * Update the left page count. If split
246 * added at index 0, fix the correct page.
249 dest = (char *)h + h->linp[skip - 1];
251 dest = (char *)l + l->linp[NEXTINDEX(l) - 1];
252 ((RINTERNAL *)dest)->nrecs = rec_total(lchild);
253 ((RINTERNAL *)dest)->pgno = lchild->pgno;
255 /* Update the right page count. */
256 h->linp[skip] = h->upper -= nbytes;
257 dest = (char *)h + h->linp[skip];
258 ((RINTERNAL *)dest)->nrecs = rec_total(rchild);
259 ((RINTERNAL *)dest)->pgno = rchild->pgno;
263 * Update the left page count. If split
264 * added at index 0, fix the correct page.
267 dest = (char *)h + h->linp[skip - 1];
269 dest = (char *)l + l->linp[NEXTINDEX(l) - 1];
270 ((RINTERNAL *)dest)->nrecs = NEXTINDEX(lchild);
271 ((RINTERNAL *)dest)->pgno = lchild->pgno;
273 /* Update the right page count. */
274 h->linp[skip] = h->upper -= nbytes;
275 dest = (char *)h + h->linp[skip];
276 ((RINTERNAL *)dest)->nrecs = NEXTINDEX(rchild);
277 ((RINTERNAL *)dest)->pgno = rchild->pgno;
283 /* Unpin the held pages. */
285 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
289 /* If the root page was split, make it look right. */
290 if (sp->pgno == P_ROOT &&
291 (F_ISSET(t, R_RECNO) ?
292 bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
295 mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
296 mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
299 /* Unpin the held pages. */
300 mpool_put(t->bt_mp, l, MPOOL_DIRTY);
301 mpool_put(t->bt_mp, r, MPOOL_DIRTY);
303 /* Clear any pages left on the stack. */
304 return (RET_SUCCESS);
307 * If something fails in the above loop we were already walking back
308 * up the tree and the tree is now inconsistent. Nothing much we can
309 * do about it but release any memory we're holding.
311 err1: mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
312 mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
314 err2: mpool_put(t->bt_mp, l, 0);
315 mpool_put(t->bt_mp, r, 0);
316 __dbpanic(t->bt_dbp);
321 * BT_PAGE -- Split a non-root page of a btree.
326 * lp: pointer to left page pointer
327 * rp: pointer to right page pointer
328 * skip: pointer to index to leave open
329 * ilen: insert length
332 * Pointer to page in which to insert or NULL on error.
335 bt_page(BTREE *t, PAGE *h, PAGE **lp, PAGE **rp, indx_t *skip, size_t ilen)
343 /* Put the new right page for the split into place. */
344 if ((r = __bt_new(t, &npg)) == NULL)
347 r->lower = BTDATAOFF;
348 r->upper = t->bt_psize;
349 r->nextpg = h->nextpg;
351 r->flags = h->flags & P_TYPE;
354 * If we're splitting the last page on a level because we're appending
355 * a key to it (skip is NEXTINDEX()), it's likely that the data is
356 * sorted. Adding an empty page on the side of the level is less work
357 * and can push the fill factor much higher than normal. If we're
358 * wrong it's no big deal, we'll just do the split the right way next
359 * time. It may look like it's equally easy to do a similar hack for
360 * reverse sorted data, that is, split the tree left, but it's not.
363 if (h->nextpg == P_INVALID && *skip == NEXTINDEX(h)) {
368 r->lower = BTDATAOFF + sizeof(indx_t);
375 /* Put the new left page for the split into place. */
376 if ((l = (PAGE *)calloc(1, t->bt_psize)) == NULL) {
377 mpool_put(t->bt_mp, r, 0);
382 l->prevpg = h->prevpg;
383 l->lower = BTDATAOFF;
384 l->upper = t->bt_psize;
385 l->flags = h->flags & P_TYPE;
387 /* Fix up the previous pointer of the page after the split page. */
388 if (h->nextpg != P_INVALID) {
389 if ((tp = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) {
391 /* XXX mpool_free(t->bt_mp, r->pgno); */
394 tp->prevpg = r->pgno;
395 mpool_put(t->bt_mp, tp, MPOOL_DIRTY);
399 * Split right. The key/data pairs aren't sorted in the btree page so
400 * it's simpler to copy the data from the split page onto two new pages
401 * instead of copying half the data to the right page and compacting
402 * the left page in place. Since the left page can't change, we have
403 * to swap the original and the allocated left page after the split.
405 tp = bt_psplit(t, h, l, r, skip, ilen);
407 /* Move the new left page onto the old left page. */
408 memmove(h, l, t->bt_psize);
419 * BT_ROOT -- Split the root page of a btree.
424 * lp: pointer to left page pointer
425 * rp: pointer to right page pointer
426 * skip: pointer to index to leave open
427 * ilen: insert length
430 * Pointer to page in which to insert or NULL on error.
433 bt_root(BTREE *t, PAGE *h, PAGE **lp, PAGE **rp, indx_t *skip, size_t ilen)
442 /* Put the new left and right pages for the split into place. */
443 if ((l = __bt_new(t, &lnpg)) == NULL ||
444 (r = __bt_new(t, &rnpg)) == NULL)
450 l->prevpg = r->nextpg = P_INVALID;
451 l->lower = r->lower = BTDATAOFF;
452 l->upper = r->upper = t->bt_psize;
453 l->flags = r->flags = h->flags & P_TYPE;
455 /* Split the root page. */
456 tp = bt_psplit(t, h, l, r, skip, ilen);
464 * BT_RROOT -- Fix up the recno root page after it has been split.
473 * RET_ERROR, RET_SUCCESS
476 bt_rroot(BTREE *t, PAGE *h, PAGE *l, PAGE *r)
480 /* Insert the left and right keys, set the header information. */
481 h->linp[0] = h->upper = t->bt_psize - NRINTERNAL;
482 dest = (char *)h + h->upper;
484 l->flags & P_RLEAF ? NEXTINDEX(l) : rec_total(l), l->pgno);
486 __PAST_END(h->linp, 1) = h->upper -= NRINTERNAL;
487 dest = (char *)h + h->upper;
489 r->flags & P_RLEAF ? NEXTINDEX(r) : rec_total(r), r->pgno);
491 h->lower = BTDATAOFF + 2 * sizeof(indx_t);
493 /* Unpin the root page, set to recno internal page. */
495 h->flags |= P_RINTERNAL;
496 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
498 return (RET_SUCCESS);
502 * BT_BROOT -- Fix up the btree root page after it has been split.
511 * RET_ERROR, RET_SUCCESS
514 bt_broot(BTREE *t, PAGE *h, PAGE *l, PAGE *r)
522 * If the root page was a leaf page, change it into an internal page.
523 * We copy the key we split on (but not the key's data, in the case of
524 * a leaf page) to the new root page.
526 * The btree comparison code guarantees that the left-most key on any
527 * level of the tree is never used, so it doesn't need to be filled in.
529 nbytes = NBINTERNAL(0);
530 h->linp[0] = h->upper = t->bt_psize - nbytes;
531 dest = (char *)h + h->upper;
532 WR_BINTERNAL(dest, 0, l->pgno, 0);
534 switch (h->flags & P_TYPE) {
537 nbytes = NBINTERNAL(bl->ksize);
538 __PAST_END(h->linp, 1) = h->upper -= nbytes;
539 dest = (char *)h + h->upper;
540 WR_BINTERNAL(dest, bl->ksize, r->pgno, 0);
541 memmove(dest, bl->bytes, bl->ksize);
544 * If the key is on an overflow page, mark the overflow chain
545 * so it isn't deleted when the leaf copy of the key is deleted.
547 if (bl->flags & P_BIGKEY &&
548 bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR)
552 bi = GETBINTERNAL(r, 0);
553 nbytes = NBINTERNAL(bi->ksize);
554 __PAST_END(h->linp, 1) = h->upper -= nbytes;
555 dest = (char *)h + h->upper;
556 memmove(dest, bi, nbytes);
557 ((BINTERNAL *)dest)->pgno = r->pgno;
563 /* There are two keys on the page. */
564 h->lower = BTDATAOFF + 2 * sizeof(indx_t);
566 /* Unpin the root page, set to btree internal page. */
568 h->flags |= P_BINTERNAL;
569 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
571 return (RET_SUCCESS);
575 * BT_PSPLIT -- Do the real work of splitting the page.
579 * h: page to be split
580 * l: page to put lower half of data
581 * r: page to put upper half of data
582 * pskip: pointer to index to leave open
583 * ilen: insert length
586 * Pointer to page in which to insert.
589 bt_psplit(BTREE *t, PAGE *h, PAGE *l, PAGE *r, indx_t *pskip, size_t ilen)
597 indx_t full, half, nxt, off, skip, top, used;
599 int bigkeycnt, isbigkey;
602 * Split the data to the left and right pages. Leave the skip index
603 * open. Additionally, make some effort not to split on an overflow
604 * key. This makes internal page processing faster and can save
605 * space as overflow keys used by internal pages are never deleted.
609 full = t->bt_psize - BTDATAOFF;
612 for (nxt = off = 0, top = NEXTINDEX(h); nxt < top; ++off) {
615 isbigkey = 0; /* XXX: not really known. */
617 switch (h->flags & P_TYPE) {
619 src = bi = GETBINTERNAL(h, nxt);
620 nbytes = NBINTERNAL(bi->ksize);
621 isbigkey = bi->flags & P_BIGKEY;
624 src = bl = GETBLEAF(h, nxt);
626 isbigkey = bl->flags & P_BIGKEY;
629 src = GETRINTERNAL(h, nxt);
634 src = rl = GETRLEAF(h, nxt);
643 * If the key/data pairs are substantial fractions of the max
644 * possible size for the page, it's possible to get situations
645 * where we decide to try and copy too much onto the left page.
646 * Make sure that doesn't happen.
648 if ((skip <= off && used + nbytes + sizeof(indx_t) >= full) ||
654 /* Copy the key/data pair, if not the skipped index. */
658 l->linp[off] = l->upper -= nbytes;
659 memmove((char *)l + l->upper, src, nbytes);
662 used += nbytes + sizeof(indx_t);
664 if (!isbigkey || bigkeycnt == 3)
672 * Off is the last offset that's valid for the left page.
673 * Nxt is the first offset to be placed on the right page.
675 l->lower += (off + 1) * sizeof(indx_t);
678 * If splitting the page that the cursor was on, the cursor has to be
679 * adjusted to point to the same record as before the split. If the
680 * cursor is at or past the skipped slot, the cursor is incremented by
681 * one. If the cursor is on the right page, it is decremented by the
682 * number of records split to the left page.
685 if (F_ISSET(c, CURS_INIT) && c->pg.pgno == h->pgno) {
686 if (c->pg.index >= skip)
688 if (c->pg.index < nxt) /* Left page. */
689 c->pg.pgno = l->pgno;
690 else { /* Right page. */
691 c->pg.pgno = r->pgno;
697 * If the skipped index was on the left page, just return that page.
698 * Otherwise, adjust the skip index to reflect the new position on
702 skip = MAX_PAGE_OFFSET;
709 for (off = 0; nxt < top; ++off) {
712 skip = MAX_PAGE_OFFSET;
714 switch (h->flags & P_TYPE) {
716 src = bi = GETBINTERNAL(h, nxt);
717 nbytes = NBINTERNAL(bi->ksize);
720 src = bl = GETBLEAF(h, nxt);
724 src = GETRINTERNAL(h, nxt);
728 src = rl = GETRLEAF(h, nxt);
735 r->linp[off] = r->upper -= nbytes;
736 memmove((char *)r + r->upper, src, nbytes);
738 r->lower += off * sizeof(indx_t);
740 /* If the key is being appended to the page, adjust the index. */
742 r->lower += sizeof(indx_t);
748 * BT_PRESERVE -- Mark a chain of pages as used by an internal node.
750 * Chains of indirect blocks pointed to by leaf nodes get reclaimed when the
751 * record that references them gets deleted. Chains pointed to by internal
752 * pages never get deleted. This routine marks a chain as pointed to by an
757 * pg: page number of first page in the chain.
760 * RET_SUCCESS, RET_ERROR.
763 bt_preserve(BTREE *t, pgno_t pg)
767 if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
769 h->flags |= P_PRESERVE;
770 mpool_put(t->bt_mp, h, MPOOL_DIRTY);
771 return (RET_SUCCESS);
775 * REC_TOTAL -- Return the number of recno entries below a page.
781 * The number of recno entries below a page.
784 * These values could be set by the bt_psplit routine. The problem is that the
785 * entry has to be popped off of the stack etc. or the values have to be passed
786 * all the way back to bt_split/bt_rroot and it's not very clean.
794 for (recs = 0, nxt = 0, top = NEXTINDEX(h); nxt < top; ++nxt)
795 recs += GETRINTERNAL(h, nxt)->nrecs;