xref: /netbsd-src/lib/libc/db/btree/bt_split.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: bt_split.c,v 1.19 2009/04/22 18:44:06 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Mike Olson.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #if HAVE_NBTOOL_CONFIG_H
36 #include "nbtool_config.h"
37 #endif
38 
39 #include <sys/cdefs.h>
40 __RCSID("$NetBSD: bt_split.c,v 1.19 2009/04/22 18:44:06 christos Exp $");
41 
42 #include "namespace.h"
43 #include <sys/types.h>
44 
45 #include <assert.h>
46 #include <limits.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include <db.h>
52 #include "btree.h"
53 
54 static int	 bt_broot(BTREE *, PAGE *, PAGE *, PAGE *);
55 static PAGE	*bt_page(BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
56 static int	 bt_preserve(BTREE *, pgno_t);
57 static PAGE	*bt_psplit(BTREE *, PAGE *, PAGE *, PAGE *, indx_t *, size_t);
58 static PAGE	*bt_root(BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
59 static int	 bt_rroot(BTREE *, PAGE *, PAGE *, PAGE *);
60 static recno_t	 rec_total(PAGE *);
61 
62 #ifdef STATISTICS
63 unsigned long	bt_rootsplit, bt_split, bt_sortsplit, bt_pfxsaved;
64 #endif
65 
66 /*
67  * __BT_SPLIT -- Split the tree.
68  *
69  * Parameters:
70  *	t:	tree
71  *	sp:	page to split
72  *	key:	key to insert
73  *	data:	data to insert
74  *	flags:	BIGKEY/BIGDATA flags
75  *	ilen:	insert length
76  *	skip:	index to leave open
77  *
78  * Returns:
79  *	RET_ERROR, RET_SUCCESS
80  */
81 int
82 __bt_split(BTREE *t, PAGE *sp, const DBT *key, const DBT *data, int flags,
83     size_t ilen, uint32_t argskip)
84 {
85 	BINTERNAL *bi = NULL;	/* pacify gcc */
86 	BLEAF *bl = NULL, *tbl;	/* pacify gcc */
87 	DBT a, b;
88 	EPGNO *parent;
89 	PAGE *h, *l, *r, *lchild, *rchild;
90 	indx_t nxtindex;
91 	uint16_t skip;
92 	uint32_t n, nbytes, nksize = 0; /* pacify gcc */
93 	int parentsplit;
94 	char *dest;
95 
96 	/*
97 	 * Split the page into two pages, l and r.  The split routines return
98 	 * a pointer to the page into which the key should be inserted and with
99 	 * skip set to the offset which should be used.  Additionally, l and r
100 	 * are pinned.
101 	 */
102 	skip = argskip;
103 	h = sp->pgno == P_ROOT ?
104 	    bt_root(t, sp, &l, &r, &skip, ilen) :
105 	    bt_page(t, sp, &l, &r, &skip, ilen);
106 	if (h == NULL)
107 		return (RET_ERROR);
108 
109 	/*
110 	 * Insert the new key/data pair into the leaf page.  (Key inserts
111 	 * always cause a leaf page to split first.)
112 	 */
113 	_DBFIT(ilen, indx_t);
114 	h->upper -= (indx_t)ilen;
115 	h->linp[skip] = h->upper;
116 	dest = (char *)(void *)h + h->upper;
117 	if (F_ISSET(t, R_RECNO))
118 		WR_RLEAF(dest, data, flags);
119 	else
120 		WR_BLEAF(dest, key, data, flags);
121 
122 	/* If the root page was split, make it look right. */
123 	if (sp->pgno == P_ROOT &&
124 	    (F_ISSET(t, R_RECNO) ?
125 	    bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
126 		goto err2;
127 
128 	/*
129 	 * Now we walk the parent page stack -- a LIFO stack of the pages that
130 	 * were traversed when we searched for the page that split.  Each stack
131 	 * entry is a page number and a page index offset.  The offset is for
132 	 * the page traversed on the search.  We've just split a page, so we
133 	 * have to insert a new key into the parent page.
134 	 *
135 	 * If the insert into the parent page causes it to split, may have to
136 	 * continue splitting all the way up the tree.  We stop if the root
137 	 * splits or the page inserted into didn't have to split to hold the
138 	 * new key.  Some algorithms replace the key for the old page as well
139 	 * as the new page.  We don't, as there's no reason to believe that the
140 	 * first key on the old page is any better than the key we have, and,
141 	 * in the case of a key being placed at index 0 causing the split, the
142 	 * key is unavailable.
143 	 *
144 	 * There are a maximum of 5 pages pinned at any time.  We keep the left
145 	 * and right pages pinned while working on the parent.   The 5 are the
146 	 * two children, left parent and right parent (when the parent splits)
147 	 * and the root page or the overflow key page when calling bt_preserve.
148 	 * This code must make sure that all pins are released other than the
149 	 * root page or overflow page which is unlocked elsewhere.
150 	 */
151 	while ((parent = BT_POP(t)) != NULL) {
152 		lchild = l;
153 		rchild = r;
154 
155 		/* Get the parent page. */
156 		if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
157 			goto err2;
158 
159 	 	/*
160 		 * The new key goes ONE AFTER the index, because the split
161 		 * was to the right.
162 		 */
163 		skip = parent->index + 1;
164 
165 		/*
166 		 * Calculate the space needed on the parent page.
167 		 *
168 		 * Prefix trees: space hack when inserting into BINTERNAL
169 		 * pages.  Retain only what's needed to distinguish between
170 		 * the new entry and the LAST entry on the page to its left.
171 		 * If the keys compare equal, retain the entire key.  Note,
172 		 * we don't touch overflow keys, and the entire key must be
173 		 * retained for the next-to-left most key on the leftmost
174 		 * page of each level, or the search will fail.  Applicable
175 		 * ONLY to internal pages that have leaf pages as children.
176 		 * Further reduction of the key between pairs of internal
177 		 * pages loses too much information.
178 		 */
179 		switch (rchild->flags & P_TYPE) {
180 		case P_BINTERNAL:
181 			bi = GETBINTERNAL(rchild, 0);
182 			nbytes = NBINTERNAL(bi->ksize);
183 			break;
184 		case P_BLEAF:
185 			bl = GETBLEAF(rchild, 0);
186 			nbytes = NBINTERNAL(bl->ksize);
187 			if (t->bt_pfx && !(bl->flags & P_BIGKEY) &&
188 			    (h->prevpg != P_INVALID || skip > 1)) {
189 				size_t temp;
190 				tbl = GETBLEAF(lchild, NEXTINDEX(lchild) - 1);
191 				a.size = tbl->ksize;
192 				a.data = tbl->bytes;
193 				b.size = bl->ksize;
194 				b.data = bl->bytes;
195 				temp = t->bt_pfx(&a, &b);
196 				_DBFIT(temp, uint32_t);
197 				nksize = (uint32_t)temp;
198 				n = NBINTERNAL(nksize);
199 				if (n < nbytes) {
200 #ifdef STATISTICS
201 					bt_pfxsaved += nbytes - n;
202 #endif
203 					nbytes = n;
204 				} else
205 					nksize = 0;
206 			} else
207 				nksize = 0;
208 			break;
209 		case P_RINTERNAL:
210 		case P_RLEAF:
211 			nbytes = NRINTERNAL;
212 			break;
213 		default:
214 			abort();
215 		}
216 
217 		/* Split the parent page if necessary or shift the indices. */
218 		if ((uint32_t)h->upper - (uint32_t)h->lower < nbytes + sizeof(indx_t)) {
219 			sp = h;
220 			h = h->pgno == P_ROOT ?
221 			    bt_root(t, h, &l, &r, &skip, nbytes) :
222 			    bt_page(t, h, &l, &r, &skip, nbytes);
223 			if (h == NULL)
224 				goto err1;
225 			parentsplit = 1;
226 		} else {
227 			if (skip < (nxtindex = NEXTINDEX(h)))
228 				memmove(h->linp + skip + 1, h->linp + skip,
229 				    (nxtindex - skip) * sizeof(indx_t));
230 			h->lower += sizeof(indx_t);
231 			parentsplit = 0;
232 		}
233 
234 		/* Insert the key into the parent page. */
235 		switch (rchild->flags & P_TYPE) {
236 		case P_BINTERNAL:
237 			h->linp[skip] = h->upper -= nbytes;
238 			dest = (char *)(void *)h + h->linp[skip];
239 			memmove(dest, bi, nbytes);
240 			((BINTERNAL *)(void *)dest)->pgno = rchild->pgno;
241 			break;
242 		case P_BLEAF:
243 			h->linp[skip] = h->upper -= nbytes;
244 			dest = (char *)(void *)h + h->linp[skip];
245 			WR_BINTERNAL(dest, nksize ? nksize : bl->ksize,
246 			    rchild->pgno, bl->flags & P_BIGKEY);
247 			memmove(dest, bl->bytes, nksize ? nksize : bl->ksize);
248 			if (bl->flags & P_BIGKEY &&
249 			    bt_preserve(t, *(pgno_t *)(void *)bl->bytes) ==
250 			    RET_ERROR)
251 				goto err1;
252 			break;
253 		case P_RINTERNAL:
254 			/*
255 			 * Update the left page count.  If split
256 			 * added at index 0, fix the correct page.
257 			 */
258 			if (skip > 0)
259 				dest = (char *)(void *)h + h->linp[skip - 1];
260 			else
261 				dest = (char *)(void *)l + l->linp[NEXTINDEX(l) - 1];
262 			((RINTERNAL *)(void *)dest)->nrecs = rec_total(lchild);
263 			((RINTERNAL *)(void *)dest)->pgno = lchild->pgno;
264 
265 			/* Update the right page count. */
266 			h->linp[skip] = h->upper -= nbytes;
267 			dest = (char *)(void *)h + h->linp[skip];
268 			((RINTERNAL *)(void *)dest)->nrecs = rec_total(rchild);
269 			((RINTERNAL *)(void *)dest)->pgno = rchild->pgno;
270 			break;
271 		case P_RLEAF:
272 			/*
273 			 * Update the left page count.  If split
274 			 * added at index 0, fix the correct page.
275 			 */
276 			if (skip > 0)
277 				dest = (char *)(void *)h + h->linp[skip - 1];
278 			else
279 				dest = (char *)(void *)l + l->linp[NEXTINDEX(l) - 1];
280 			((RINTERNAL *)(void *)dest)->nrecs = NEXTINDEX(lchild);
281 			((RINTERNAL *)(void *)dest)->pgno = lchild->pgno;
282 
283 			/* Update the right page count. */
284 			h->linp[skip] = h->upper -= nbytes;
285 			dest = (char *)(void *)h + h->linp[skip];
286 			((RINTERNAL *)(void *)dest)->nrecs = NEXTINDEX(rchild);
287 			((RINTERNAL *)(void *)dest)->pgno = rchild->pgno;
288 			break;
289 		default:
290 			abort();
291 		}
292 
293 		/* Unpin the held pages. */
294 		if (!parentsplit) {
295 			mpool_put(t->bt_mp, h, MPOOL_DIRTY);
296 			break;
297 		}
298 
299 		/* If the root page was split, make it look right. */
300 		if (sp->pgno == P_ROOT &&
301 		    (F_ISSET(t, R_RECNO) ?
302 		    bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
303 			goto err1;
304 
305 		mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
306 		mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
307 	}
308 
309 	/* Unpin the held pages. */
310 	mpool_put(t->bt_mp, l, MPOOL_DIRTY);
311 	mpool_put(t->bt_mp, r, MPOOL_DIRTY);
312 
313 	/* Clear any pages left on the stack. */
314 	return (RET_SUCCESS);
315 
316 	/*
317 	 * If something fails in the above loop we were already walking back
318 	 * up the tree and the tree is now inconsistent.  Nothing much we can
319 	 * do about it but release any memory we're holding.
320 	 */
321 err1:	mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
322 	mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
323 
324 err2:	mpool_put(t->bt_mp, l, 0);
325 	mpool_put(t->bt_mp, r, 0);
326 	__dbpanic(t->bt_dbp);
327 	return (RET_ERROR);
328 }
329 
330 /*
331  * BT_PAGE -- Split a non-root page of a btree.
332  *
333  * Parameters:
334  *	t:	tree
335  *	h:	root page
336  *	lp:	pointer to left page pointer
337  *	rp:	pointer to right page pointer
338  *	skip:	pointer to index to leave open
339  *	ilen:	insert length
340  *
341  * Returns:
342  *	Pointer to page in which to insert or NULL on error.
343  */
344 static PAGE *
345 bt_page(BTREE *t, PAGE *h, PAGE **lp, PAGE **rp, indx_t *skip, size_t ilen)
346 {
347 	PAGE *l, *r, *tp;
348 	pgno_t npg;
349 
350 #ifdef STATISTICS
351 	++bt_split;
352 #endif
353 	/* Put the new right page for the split into place. */
354 	if ((r = __bt_new(t, &npg)) == NULL)
355 		return (NULL);
356 	r->pgno = npg;
357 	r->lower = BTDATAOFF;
358 	r->upper = t->bt_psize;
359 	r->nextpg = h->nextpg;
360 	r->prevpg = h->pgno;
361 	r->flags = h->flags & P_TYPE;
362 
363 	/*
364 	 * If we're splitting the last page on a level because we're appending
365 	 * a key to it (skip is NEXTINDEX()), it's likely that the data is
366 	 * sorted.  Adding an empty page on the side of the level is less work
367 	 * and can push the fill factor much higher than normal.  If we're
368 	 * wrong it's no big deal, we'll just do the split the right way next
369 	 * time.  It may look like it's equally easy to do a similar hack for
370 	 * reverse sorted data, that is, split the tree left, but it's not.
371 	 * Don't even try.
372 	 */
373 	if (h->nextpg == P_INVALID && *skip == NEXTINDEX(h)) {
374 #ifdef STATISTICS
375 		++bt_sortsplit;
376 #endif
377 		h->nextpg = r->pgno;
378 		r->lower = BTDATAOFF + sizeof(indx_t);
379 		*skip = 0;
380 		*lp = h;
381 		*rp = r;
382 		return (r);
383 	}
384 
385 	/* Put the new left page for the split into place. */
386 	if ((l = calloc(1, t->bt_psize)) == NULL) {
387 		mpool_put(t->bt_mp, r, 0);
388 		return (NULL);
389 	}
390 #ifdef PURIFY
391 	memset(l, 0xff, t->bt_psize);
392 #endif
393 	l->pgno = h->pgno;
394 	l->nextpg = r->pgno;
395 	l->prevpg = h->prevpg;
396 	l->lower = BTDATAOFF;
397 	l->upper = t->bt_psize;
398 	l->flags = h->flags & P_TYPE;
399 
400 	/* Fix up the previous pointer of the page after the split page. */
401 	if (h->nextpg != P_INVALID) {
402 		if ((tp = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) {
403 			free(l);
404 			/* XXX mpool_free(t->bt_mp, r->pgno); */
405 			return (NULL);
406 		}
407 		tp->prevpg = r->pgno;
408 		mpool_put(t->bt_mp, tp, MPOOL_DIRTY);
409 	}
410 
411 	/*
412 	 * Split right.  The key/data pairs aren't sorted in the btree page so
413 	 * it's simpler to copy the data from the split page onto two new pages
414 	 * instead of copying half the data to the right page and compacting
415 	 * the left page in place.  Since the left page can't change, we have
416 	 * to swap the original and the allocated left page after the split.
417 	 */
418 	tp = bt_psplit(t, h, l, r, skip, ilen);
419 
420 	/* Move the new left page onto the old left page. */
421 	memmove(h, l, t->bt_psize);
422 	if (tp == l)
423 		tp = h;
424 	free(l);
425 
426 	*lp = h;
427 	*rp = r;
428 	return (tp);
429 }
430 
431 /*
432  * BT_ROOT -- Split the root page of a btree.
433  *
434  * Parameters:
435  *	t:	tree
436  *	h:	root page
437  *	lp:	pointer to left page pointer
438  *	rp:	pointer to right page pointer
439  *	skip:	pointer to index to leave open
440  *	ilen:	insert length
441  *
442  * Returns:
443  *	Pointer to page in which to insert or NULL on error.
444  */
445 static PAGE *
446 bt_root(BTREE *t, PAGE *h, PAGE **lp, PAGE **rp, indx_t *skip, size_t ilen)
447 {
448 	PAGE *l, *r, *tp;
449 	pgno_t lnpg, rnpg;
450 
451 #ifdef STATISTICS
452 	++bt_split;
453 	++bt_rootsplit;
454 #endif
455 	/* Put the new left and right pages for the split into place. */
456 	if ((l = __bt_new(t, &lnpg)) == NULL ||
457 	    (r = __bt_new(t, &rnpg)) == NULL)
458 		return (NULL);
459 	l->pgno = lnpg;
460 	r->pgno = rnpg;
461 	l->nextpg = r->pgno;
462 	r->prevpg = l->pgno;
463 	l->prevpg = r->nextpg = P_INVALID;
464 	l->lower = r->lower = BTDATAOFF;
465 	l->upper = r->upper = t->bt_psize;
466 	l->flags = r->flags = h->flags & P_TYPE;
467 
468 	/* Split the root page. */
469 	tp = bt_psplit(t, h, l, r, skip, ilen);
470 
471 	*lp = l;
472 	*rp = r;
473 	return (tp);
474 }
475 
476 /*
477  * BT_RROOT -- Fix up the recno root page after it has been split.
478  *
479  * Parameters:
480  *	t:	tree
481  *	h:	root page
482  *	l:	left page
483  *	r:	right page
484  *
485  * Returns:
486  *	RET_ERROR, RET_SUCCESS
487  */
488 static int
489 bt_rroot(BTREE *t, PAGE *h, PAGE *l, PAGE *r)
490 {
491 	char *dest;
492 	uint32_t sz;
493 	size_t temp;
494 
495 	temp = t->bt_psize - NRINTERNAL;
496 	_DBFIT(temp, uint32_t);
497 	sz = (uint32_t)temp;
498 
499 	/* Insert the left and right keys, set the header information. */
500 	_DBFIT(sz, indx_t);
501 	h->linp[0] = h->upper = (indx_t)sz;
502 	dest = (char *)(void *)h + h->upper;
503 	WR_RINTERNAL(dest,
504 	    l->flags & P_RLEAF ? NEXTINDEX(l) : rec_total(l), l->pgno);
505 
506 	h->linp[1] = h->upper -= NRINTERNAL;
507 	dest = (char *)(void *)h + h->upper;
508 	WR_RINTERNAL(dest,
509 	    r->flags & P_RLEAF ? NEXTINDEX(r) : rec_total(r), r->pgno);
510 
511 	h->lower = BTDATAOFF + 2 * sizeof(indx_t);
512 
513 	/* Unpin the root page, set to recno internal page. */
514 	h->flags &= ~P_TYPE;
515 	h->flags |= P_RINTERNAL;
516 	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
517 
518 	return (RET_SUCCESS);
519 }
520 
521 /*
522  * BT_BROOT -- Fix up the btree root page after it has been split.
523  *
524  * Parameters:
525  *	t:	tree
526  *	h:	root page
527  *	l:	left page
528  *	r:	right page
529  *
530  * Returns:
531  *	RET_ERROR, RET_SUCCESS
532  */
533 static int
534 bt_broot(BTREE *t, PAGE *h, PAGE *l, PAGE *r)
535 {
536 	BINTERNAL *bi = NULL;	/* pacify gcc */
537 	BLEAF *bl;
538 	uint32_t nbytes;
539 	char *dest;
540 
541 	/*
542 	 * If the root page was a leaf page, change it into an internal page.
543 	 * We copy the key we split on (but not the key's data, in the case of
544 	 * a leaf page) to the new root page.
545 	 *
546 	 * The btree comparison code guarantees that the left-most key on any
547 	 * level of the tree is never used, so it doesn't need to be filled in.
548 	 */
549 	nbytes = NBINTERNAL(0);
550 	h->linp[0] = h->upper = t->bt_psize - nbytes;
551 	dest = (char *)(void *)h + h->upper;
552 	WR_BINTERNAL(dest, 0, l->pgno, 0);
553 
554 	switch (h->flags & P_TYPE) {
555 	case P_BLEAF:
556 		bl = GETBLEAF(r, 0);
557 		nbytes = NBINTERNAL(bl->ksize);
558 		h->linp[1] = h->upper -= nbytes;
559 		dest = (char *)(void *)h + h->upper;
560 		WR_BINTERNAL(dest, bl->ksize, r->pgno, 0);
561 		memmove(dest, bl->bytes, bl->ksize);
562 
563 		/*
564 		 * If the key is on an overflow page, mark the overflow chain
565 		 * so it isn't deleted when the leaf copy of the key is deleted.
566 		 */
567 		if (bl->flags & P_BIGKEY &&
568 		    bt_preserve(t, *(pgno_t *)(void *)bl->bytes) == RET_ERROR)
569 			return (RET_ERROR);
570 		break;
571 	case P_BINTERNAL:
572 		bi = GETBINTERNAL(r, 0);
573 		nbytes = NBINTERNAL(bi->ksize);
574 		h->linp[1] = h->upper -= nbytes;
575 		dest = (char *)(void *)h + h->upper;
576 		memmove(dest, bi, nbytes);
577 		((BINTERNAL *)(void *)dest)->pgno = r->pgno;
578 		break;
579 	default:
580 		abort();
581 	}
582 
583 	/* There are two keys on the page. */
584 	h->lower = BTDATAOFF + 2 * sizeof(indx_t);
585 
586 	/* Unpin the root page, set to btree internal page. */
587 	h->flags &= ~P_TYPE;
588 	h->flags |= P_BINTERNAL;
589 	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
590 
591 	return (RET_SUCCESS);
592 }
593 
594 /*
595  * BT_PSPLIT -- Do the real work of splitting the page.
596  *
597  * Parameters:
598  *	t:	tree
599  *	h:	page to be split
600  *	l:	page to put lower half of data
601  *	r:	page to put upper half of data
602  *	pskip:	pointer to index to leave open
603  *	ilen:	insert length
604  *
605  * Returns:
606  *	Pointer to page in which to insert.
607  */
608 static PAGE *
609 bt_psplit(BTREE *t, PAGE *h, PAGE *l, PAGE *r, indx_t *pskip, size_t ilen)
610 {
611 	BINTERNAL *bi;
612 	BLEAF *bl;
613 	CURSOR *c;
614 	RLEAF *rl;
615 	PAGE *rval;
616 	void *src = NULL;	/* pacify gcc */
617 	indx_t full, half, nxt, off, skip, top, used;
618 	uint32_t nbytes;
619 	size_t temp;
620 	int bigkeycnt, isbigkey;
621 
622 	/*
623 	 * Split the data to the left and right pages.  Leave the skip index
624 	 * open.  Additionally, make some effort not to split on an overflow
625 	 * key.  This makes internal page processing faster and can save
626 	 * space as overflow keys used by internal pages are never deleted.
627 	 */
628 	bigkeycnt = 0;
629 	skip = *pskip;
630 	temp = t->bt_psize - BTDATAOFF;
631 	_DBFIT(temp, indx_t);
632 	full = (indx_t)temp;
633 	half = full / 2;
634 	used = 0;
635 	for (nxt = off = 0, top = NEXTINDEX(h); nxt < top; ++off) {
636 		if (skip == off) {
637 			_DBFIT(ilen, uint32_t);
638 			nbytes = (uint32_t)ilen;
639 			isbigkey = 0;		/* XXX: not really known. */
640 		} else
641 			switch (h->flags & P_TYPE) {
642 			case P_BINTERNAL:
643 				src = bi = GETBINTERNAL(h, nxt);
644 				nbytes = NBINTERNAL(bi->ksize);
645 				isbigkey = bi->flags & P_BIGKEY;
646 				break;
647 			case P_BLEAF:
648 				src = bl = GETBLEAF(h, nxt);
649 				nbytes = NBLEAF(bl);
650 				isbigkey = bl->flags & P_BIGKEY;
651 				break;
652 			case P_RINTERNAL:
653 				src = GETRINTERNAL(h, nxt);
654 				nbytes = NRINTERNAL;
655 				isbigkey = 0;
656 				break;
657 			case P_RLEAF:
658 				src = rl = GETRLEAF(h, nxt);
659 				nbytes = NRLEAF(rl);
660 				isbigkey = 0;
661 				break;
662 			default:
663 				abort();
664 			}
665 
666 		/*
667 		 * If the key/data pairs are substantial fractions of the max
668 		 * possible size for the page, it's possible to get situations
669 		 * where we decide to try and copy too much onto the left page.
670 		 * Make sure that doesn't happen.
671 		 */
672 		if ((skip <= off && used + nbytes + sizeof(indx_t) >= full) ||
673 		    nxt == top - 1) {
674 			--off;
675 			break;
676 		}
677 
678 		/* Copy the key/data pair, if not the skipped index. */
679 		if (skip != off) {
680 			++nxt;
681 
682 			l->linp[off] = l->upper -= nbytes;
683 			memmove((char *)(void *)l + l->upper, src, nbytes);
684 		}
685 
686 		temp = nbytes + sizeof(indx_t);
687 		_DBFIT(temp, indx_t);
688 		used += (indx_t)temp;
689 		if (used >= half) {
690 			if (!isbigkey || bigkeycnt == 3)
691 				break;
692 			else
693 				++bigkeycnt;
694 		}
695 	}
696 
697 	/*
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.
700 	 */
701 	temp = (off + 1) * sizeof(indx_t);
702 	_DBFIT(temp, indx_t);
703 	l->lower += (indx_t)temp;
704 
705 	/*
706 	 * If splitting the page that the cursor was on, the cursor has to be
707 	 * adjusted to point to the same record as before the split.  If the
708 	 * cursor is at or past the skipped slot, the cursor is incremented by
709 	 * one.  If the cursor is on the right page, it is decremented by the
710 	 * number of records split to the left page.
711 	 */
712 	c = &t->bt_cursor;
713 	if (F_ISSET(c, CURS_INIT) && c->pg.pgno == h->pgno) {
714 		if (c->pg.index >= skip)
715 			++c->pg.index;
716 		if (c->pg.index < nxt)			/* Left page. */
717 			c->pg.pgno = l->pgno;
718 		else {					/* Right page. */
719 			c->pg.pgno = r->pgno;
720 			c->pg.index -= nxt;
721 		}
722 	}
723 
724 	/*
725 	 * If the skipped index was on the left page, just return that page.
726 	 * Otherwise, adjust the skip index to reflect the new position on
727 	 * the right page.
728 	 */
729 	if (skip <= off) {
730 		skip = MAX_PAGE_OFFSET;
731 		rval = l;
732 	} else {
733 		rval = r;
734 		*pskip -= nxt;
735 	}
736 
737 	for (off = 0; nxt < top; ++off) {
738 		if (skip == nxt) {
739 			++off;
740 			skip = MAX_PAGE_OFFSET;
741 		}
742 		switch (h->flags & P_TYPE) {
743 		case P_BINTERNAL:
744 			src = bi = GETBINTERNAL(h, nxt);
745 			nbytes = NBINTERNAL(bi->ksize);
746 			break;
747 		case P_BLEAF:
748 			src = bl = GETBLEAF(h, nxt);
749 			nbytes = NBLEAF(bl);
750 			break;
751 		case P_RINTERNAL:
752 			src = GETRINTERNAL(h, nxt);
753 			nbytes = NRINTERNAL;
754 			break;
755 		case P_RLEAF:
756 			src = rl = GETRLEAF(h, nxt);
757 			nbytes = NRLEAF(rl);
758 			break;
759 		default:
760 			abort();
761 		}
762 		++nxt;
763 		r->linp[off] = r->upper -= nbytes;
764 		memmove((char *)(void *)r + r->upper, src, nbytes);
765 	}
766 	temp = off * sizeof(indx_t);
767 	_DBFIT(temp, indx_t);
768 	r->lower += (indx_t)temp;
769 
770 	/* If the key is being appended to the page, adjust the index. */
771 	if (skip == top)
772 		r->lower += sizeof(indx_t);
773 
774 	return (rval);
775 }
776 
777 /*
778  * BT_PRESERVE -- Mark a chain of pages as used by an internal node.
779  *
780  * Chains of indirect blocks pointed to by leaf nodes get reclaimed when the
781  * record that references them gets deleted.  Chains pointed to by internal
782  * pages never get deleted.  This routine marks a chain as pointed to by an
783  * internal page.
784  *
785  * Parameters:
786  *	t:	tree
787  *	pg:	page number of first page in the chain.
788  *
789  * Returns:
790  *	RET_SUCCESS, RET_ERROR.
791  */
792 static int
793 bt_preserve(BTREE *t, pgno_t pg)
794 {
795 	PAGE *h;
796 
797 	if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
798 		return (RET_ERROR);
799 	h->flags |= P_PRESERVE;
800 	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
801 	return (RET_SUCCESS);
802 }
803 
804 /*
805  * REC_TOTAL -- Return the number of recno entries below a page.
806  *
807  * Parameters:
808  *	h:	page
809  *
810  * Returns:
811  *	The number of recno entries below a page.
812  *
813  * XXX
814  * These values could be set by the bt_psplit routine.  The problem is that the
815  * entry has to be popped off of the stack etc. or the values have to be passed
816  * all the way back to bt_split/bt_rroot and it's not very clean.
817  */
818 static recno_t
819 rec_total(PAGE *h)
820 {
821 	recno_t recs;
822 	indx_t nxt, top;
823 
824 	for (recs = 0, nxt = 0, top = NEXTINDEX(h); nxt < top; ++nxt)
825 		recs += GETRINTERNAL(h, nxt)->nrecs;
826 	return (recs);
827 }
828