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