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