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