xref: /openbsd-src/lib/libc/db/btree/bt_split.c (revision bec2d00aee11811f26f3f148c6197e34c35176ed)
1 /*	$NetBSD: bt_split.c,v 1.6 1996/05/03 21:50:56 cgd 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.9 (Berkeley) 7/26/94";
42 #else
43 static char rcsid[] = "$NetBSD: bt_split.c,v 1.6 1996/05/03 21:50:56 cgd 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 __P((BTREE *, PAGE *, PAGE *, PAGE *));
58 static PAGE	*bt_page
59 		    __P((BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t));
60 static int	 bt_preserve __P((BTREE *, pgno_t));
61 static PAGE	*bt_psplit
62 		    __P((BTREE *, PAGE *, PAGE *, PAGE *, indx_t *, size_t));
63 static PAGE	*bt_root
64 		    __P((BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t));
65 static int	 bt_rroot __P((BTREE *, PAGE *, PAGE *, PAGE *));
66 static recno_t	 rec_total __P((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 #ifdef PURIFY
400 	memset(l, 0xff, t->bt_psize);
401 #endif
402 	l->pgno = h->pgno;
403 	l->nextpg = r->pgno;
404 	l->prevpg = h->prevpg;
405 	l->lower = BTDATAOFF;
406 	l->upper = t->bt_psize;
407 	l->flags = h->flags & P_TYPE;
408 
409 	/* Fix up the previous pointer of the page after the split page. */
410 	if (h->nextpg != P_INVALID) {
411 		if ((tp = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) {
412 			free(l);
413 			/* XXX mpool_free(t->bt_mp, r->pgno); */
414 			return (NULL);
415 		}
416 		tp->prevpg = r->pgno;
417 		mpool_put(t->bt_mp, tp, MPOOL_DIRTY);
418 	}
419 
420 	/*
421 	 * Split right.  The key/data pairs aren't sorted in the btree page so
422 	 * it's simpler to copy the data from the split page onto two new pages
423 	 * instead of copying half the data to the right page and compacting
424 	 * the left page in place.  Since the left page can't change, we have
425 	 * to swap the original and the allocated left page after the split.
426 	 */
427 	tp = bt_psplit(t, h, l, r, skip, ilen);
428 
429 	/* Move the new left page onto the old left page. */
430 	memmove(h, l, t->bt_psize);
431 	if (tp == l)
432 		tp = h;
433 	free(l);
434 
435 	*lp = h;
436 	*rp = r;
437 	return (tp);
438 }
439 
440 /*
441  * BT_ROOT -- Split the root page of a btree.
442  *
443  * Parameters:
444  *	t:	tree
445  *	h:	root page
446  *	lp:	pointer to left page pointer
447  *	rp:	pointer to right page pointer
448  *	skip:	pointer to index to leave open
449  *	ilen:	insert length
450  *
451  * Returns:
452  *	Pointer to page in which to insert or NULL on error.
453  */
454 static PAGE *
455 bt_root(t, h, lp, rp, skip, ilen)
456 	BTREE *t;
457 	PAGE *h, **lp, **rp;
458 	indx_t *skip;
459 	size_t ilen;
460 {
461 	PAGE *l, *r, *tp;
462 	pgno_t lnpg, rnpg;
463 
464 #ifdef STATISTICS
465 	++bt_split;
466 	++bt_rootsplit;
467 #endif
468 	/* Put the new left and right pages for the split into place. */
469 	if ((l = __bt_new(t, &lnpg)) == NULL ||
470 	    (r = __bt_new(t, &rnpg)) == NULL)
471 		return (NULL);
472 	l->pgno = lnpg;
473 	r->pgno = rnpg;
474 	l->nextpg = r->pgno;
475 	r->prevpg = l->pgno;
476 	l->prevpg = r->nextpg = P_INVALID;
477 	l->lower = r->lower = BTDATAOFF;
478 	l->upper = r->upper = t->bt_psize;
479 	l->flags = r->flags = h->flags & P_TYPE;
480 
481 	/* Split the root page. */
482 	tp = bt_psplit(t, h, l, r, skip, ilen);
483 
484 	*lp = l;
485 	*rp = r;
486 	return (tp);
487 }
488 
489 /*
490  * BT_RROOT -- Fix up the recno root page after it has been split.
491  *
492  * Parameters:
493  *	t:	tree
494  *	h:	root page
495  *	l:	left page
496  *	r:	right page
497  *
498  * Returns:
499  *	RET_ERROR, RET_SUCCESS
500  */
501 static int
502 bt_rroot(t, h, l, r)
503 	BTREE *t;
504 	PAGE *h, *l, *r;
505 {
506 	char *dest;
507 
508 	/* Insert the left and right keys, set the header information. */
509 	h->linp[0] = h->upper = t->bt_psize - NRINTERNAL;
510 	dest = (char *)h + h->upper;
511 	WR_RINTERNAL(dest,
512 	    l->flags & P_RLEAF ? NEXTINDEX(l) : rec_total(l), l->pgno);
513 
514 	h->linp[1] = h->upper -= NRINTERNAL;
515 	dest = (char *)h + h->upper;
516 	WR_RINTERNAL(dest,
517 	    r->flags & P_RLEAF ? NEXTINDEX(r) : rec_total(r), r->pgno);
518 
519 	h->lower = BTDATAOFF + 2 * sizeof(indx_t);
520 
521 	/* Unpin the root page, set to recno internal page. */
522 	h->flags &= ~P_TYPE;
523 	h->flags |= P_RINTERNAL;
524 	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
525 
526 	return (RET_SUCCESS);
527 }
528 
529 /*
530  * BT_BROOT -- Fix up the btree root page after it has been split.
531  *
532  * Parameters:
533  *	t:	tree
534  *	h:	root page
535  *	l:	left page
536  *	r:	right page
537  *
538  * Returns:
539  *	RET_ERROR, RET_SUCCESS
540  */
541 static int
542 bt_broot(t, h, l, r)
543 	BTREE *t;
544 	PAGE *h, *l, *r;
545 {
546 	BINTERNAL *bi;
547 	BLEAF *bl;
548 	u_int32_t nbytes;
549 	char *dest;
550 
551 	/*
552 	 * If the root page was a leaf page, change it into an internal page.
553 	 * We copy the key we split on (but not the key's data, in the case of
554 	 * a leaf page) to the new root page.
555 	 *
556 	 * The btree comparison code guarantees that the left-most key on any
557 	 * level of the tree is never used, so it doesn't need to be filled in.
558 	 */
559 	nbytes = NBINTERNAL(0);
560 	h->linp[0] = h->upper = t->bt_psize - nbytes;
561 	dest = (char *)h + h->upper;
562 	WR_BINTERNAL(dest, 0, l->pgno, 0);
563 
564 	switch (h->flags & P_TYPE) {
565 	case P_BLEAF:
566 		bl = GETBLEAF(r, 0);
567 		nbytes = NBINTERNAL(bl->ksize);
568 		h->linp[1] = h->upper -= nbytes;
569 		dest = (char *)h + h->upper;
570 		WR_BINTERNAL(dest, bl->ksize, r->pgno, 0);
571 		memmove(dest, bl->bytes, bl->ksize);
572 
573 		/*
574 		 * If the key is on an overflow page, mark the overflow chain
575 		 * so it isn't deleted when the leaf copy of the key is deleted.
576 		 */
577 		if (bl->flags & P_BIGKEY &&
578 		    bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR)
579 			return (RET_ERROR);
580 		break;
581 	case P_BINTERNAL:
582 		bi = GETBINTERNAL(r, 0);
583 		nbytes = NBINTERNAL(bi->ksize);
584 		h->linp[1] = h->upper -= nbytes;
585 		dest = (char *)h + h->upper;
586 		memmove(dest, bi, nbytes);
587 		((BINTERNAL *)dest)->pgno = r->pgno;
588 		break;
589 	default:
590 		abort();
591 	}
592 
593 	/* There are two keys on the page. */
594 	h->lower = BTDATAOFF + 2 * sizeof(indx_t);
595 
596 	/* Unpin the root page, set to btree internal page. */
597 	h->flags &= ~P_TYPE;
598 	h->flags |= P_BINTERNAL;
599 	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
600 
601 	return (RET_SUCCESS);
602 }
603 
604 /*
605  * BT_PSPLIT -- Do the real work of splitting the page.
606  *
607  * Parameters:
608  *	t:	tree
609  *	h:	page to be split
610  *	l:	page to put lower half of data
611  *	r:	page to put upper half of data
612  *	pskip:	pointer to index to leave open
613  *	ilen:	insert length
614  *
615  * Returns:
616  *	Pointer to page in which to insert.
617  */
618 static PAGE *
619 bt_psplit(t, h, l, r, pskip, ilen)
620 	BTREE *t;
621 	PAGE *h, *l, *r;
622 	indx_t *pskip;
623 	size_t ilen;
624 {
625 	BINTERNAL *bi;
626 	BLEAF *bl;
627 	CURSOR *c;
628 	RLEAF *rl;
629 	PAGE *rval;
630 	void *src;
631 	indx_t full, half, nxt, off, skip, top, used;
632 	u_int32_t nbytes;
633 	int bigkeycnt, isbigkey;
634 
635 	/*
636 	 * Split the data to the left and right pages.  Leave the skip index
637 	 * open.  Additionally, make some effort not to split on an overflow
638 	 * key.  This makes internal page processing faster and can save
639 	 * space as overflow keys used by internal pages are never deleted.
640 	 */
641 	bigkeycnt = 0;
642 	skip = *pskip;
643 	full = t->bt_psize - BTDATAOFF;
644 	half = full / 2;
645 	used = 0;
646 	for (nxt = off = 0, top = NEXTINDEX(h); nxt < top; ++off) {
647 		if (skip == off) {
648 			nbytes = ilen;
649 			isbigkey = 0;		/* XXX: not really known. */
650 		} else
651 			switch (h->flags & P_TYPE) {
652 			case P_BINTERNAL:
653 				src = bi = GETBINTERNAL(h, nxt);
654 				nbytes = NBINTERNAL(bi->ksize);
655 				isbigkey = bi->flags & P_BIGKEY;
656 				break;
657 			case P_BLEAF:
658 				src = bl = GETBLEAF(h, nxt);
659 				nbytes = NBLEAF(bl);
660 				isbigkey = bl->flags & P_BIGKEY;
661 				break;
662 			case P_RINTERNAL:
663 				src = GETRINTERNAL(h, nxt);
664 				nbytes = NRINTERNAL;
665 				isbigkey = 0;
666 				break;
667 			case P_RLEAF:
668 				src = rl = GETRLEAF(h, nxt);
669 				nbytes = NRLEAF(rl);
670 				isbigkey = 0;
671 				break;
672 			default:
673 				abort();
674 			}
675 
676 		/*
677 		 * If the key/data pairs are substantial fractions of the max
678 		 * possible size for the page, it's possible to get situations
679 		 * where we decide to try and copy too much onto the left page.
680 		 * Make sure that doesn't happen.
681 		 */
682 		if (skip <= off && used + nbytes >= full) {
683 			--off;
684 			break;
685 		}
686 
687 		/* Copy the key/data pair, if not the skipped index. */
688 		if (skip != off) {
689 			++nxt;
690 
691 			l->linp[off] = l->upper -= nbytes;
692 			memmove((char *)l + l->upper, src, nbytes);
693 		}
694 
695 		used += nbytes;
696 		if (used >= half) {
697 			if (!isbigkey || bigkeycnt == 3)
698 				break;
699 			else
700 				++bigkeycnt;
701 		}
702 	}
703 
704 	/*
705 	 * Off is the last offset that's valid for the left page.
706 	 * Nxt is the first offset to be placed on the right page.
707 	 */
708 	l->lower += (off + 1) * sizeof(indx_t);
709 
710 	/*
711 	 * If splitting the page that the cursor was on, the cursor has to be
712 	 * adjusted to point to the same record as before the split.  If the
713 	 * cursor is at or past the skipped slot, the cursor is incremented by
714 	 * one.  If the cursor is on the right page, it is decremented by the
715 	 * number of records split to the left page.
716 	 */
717 	c = &t->bt_cursor;
718 	if (F_ISSET(c, CURS_INIT) && c->pg.pgno == h->pgno) {
719 		if (c->pg.index >= skip)
720 			++c->pg.index;
721 		if (c->pg.index < nxt)			/* Left page. */
722 			c->pg.pgno = l->pgno;
723 		else {					/* Right page. */
724 			c->pg.pgno = r->pgno;
725 			c->pg.index -= nxt;
726 		}
727 	}
728 
729 	/*
730 	 * If the skipped index was on the left page, just return that page.
731 	 * Otherwise, adjust the skip index to reflect the new position on
732 	 * the right page.
733 	 */
734 	if (skip <= off) {
735 		skip = 0;
736 		rval = l;
737 	} else {
738 		rval = r;
739 		*pskip -= nxt;
740 	}
741 
742 	for (off = 0; nxt < top; ++off) {
743 		if (skip == nxt) {
744 			++off;
745 			skip = 0;
746 		}
747 		switch (h->flags & P_TYPE) {
748 		case P_BINTERNAL:
749 			src = bi = GETBINTERNAL(h, nxt);
750 			nbytes = NBINTERNAL(bi->ksize);
751 			break;
752 		case P_BLEAF:
753 			src = bl = GETBLEAF(h, nxt);
754 			nbytes = NBLEAF(bl);
755 			break;
756 		case P_RINTERNAL:
757 			src = GETRINTERNAL(h, nxt);
758 			nbytes = NRINTERNAL;
759 			break;
760 		case P_RLEAF:
761 			src = rl = GETRLEAF(h, nxt);
762 			nbytes = NRLEAF(rl);
763 			break;
764 		default:
765 			abort();
766 		}
767 		++nxt;
768 		r->linp[off] = r->upper -= nbytes;
769 		memmove((char *)r + r->upper, src, nbytes);
770 	}
771 	r->lower += off * sizeof(indx_t);
772 
773 	/* If the key is being appended to the page, adjust the index. */
774 	if (skip == top)
775 		r->lower += sizeof(indx_t);
776 
777 	return (rval);
778 }
779 
780 /*
781  * BT_PRESERVE -- Mark a chain of pages as used by an internal node.
782  *
783  * Chains of indirect blocks pointed to by leaf nodes get reclaimed when the
784  * record that references them gets deleted.  Chains pointed to by internal
785  * pages never get deleted.  This routine marks a chain as pointed to by an
786  * internal page.
787  *
788  * Parameters:
789  *	t:	tree
790  *	pg:	page number of first page in the chain.
791  *
792  * Returns:
793  *	RET_SUCCESS, RET_ERROR.
794  */
795 static int
796 bt_preserve(t, pg)
797 	BTREE *t;
798 	pgno_t pg;
799 {
800 	PAGE *h;
801 
802 	if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
803 		return (RET_ERROR);
804 	h->flags |= P_PRESERVE;
805 	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
806 	return (RET_SUCCESS);
807 }
808 
809 /*
810  * REC_TOTAL -- Return the number of recno entries below a page.
811  *
812  * Parameters:
813  *	h:	page
814  *
815  * Returns:
816  *	The number of recno entries below a page.
817  *
818  * XXX
819  * These values could be set by the bt_psplit routine.  The problem is that the
820  * entry has to be popped off of the stack etc. or the values have to be passed
821  * all the way back to bt_split/bt_rroot and it's not very clean.
822  */
823 static recno_t
824 rec_total(h)
825 	PAGE *h;
826 {
827 	recno_t recs;
828 	indx_t nxt, top;
829 
830 	for (recs = 0, nxt = 0, top = NEXTINDEX(h); nxt < top; ++nxt)
831 		recs += GETRINTERNAL(h, nxt)->nrecs;
832 	return (recs);
833 }
834