1#pragma ident	"%Z%%M%	%I%	%E% SMI"
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)
40static char sccsid[] = "@(#)bt_put.c	8.8 (Berkeley) 7/26/94";
41#endif /* LIBC_SCCS and not lint */
42
43#include <sys/types.h>
44
45#include <errno.h>
46#include <stdio.h>
47#include <stdlib.h>
48#include <string.h>
49
50#include "db-int.h"
51#include "btree.h"
52
53static EPG *bt_fast __P((BTREE *, const DBT *, const DBT *, int *));
54
55/*
56 * __BT_PUT -- Add a btree item to the tree.
57 *
58 * Parameters:
59 *	dbp:	pointer to access method
60 *	key:	key
61 *	data:	data
62 *	flag:	R_NOOVERWRITE
63 *
64 * Returns:
65 *	RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key is already in the
66 *	tree and R_NOOVERWRITE specified.
67 */
68int
69__bt_put(dbp, key, data, flags)
70	const DB *dbp;
71	DBT *key;
72	const DBT *data;
73	u_int flags;
74{
75	BTREE *t;
76	DBT tkey, tdata;
77	EPG *e = 0;
78	PAGE *h;
79	indx_t idx, nxtindex;
80	db_pgno_t pg;
81	u_int32_t nbytes;
82	int dflags, exact, status;
83	char *dest, db[NOVFLSIZE], kb[NOVFLSIZE];
84
85	t = dbp->internal;
86
87	/* Toss any page pinned across calls. */
88	if (t->bt_pinned != NULL) {
89		mpool_put(t->bt_mp, t->bt_pinned, 0);
90		t->bt_pinned = NULL;
91	}
92
93	/* Check for change to a read-only tree. */
94	if (F_ISSET(t, B_RDONLY)) {
95		errno = EPERM;
96		return (RET_ERROR);
97	}
98
99	switch (flags) {
100	case 0:
101	case R_NOOVERWRITE:
102		break;
103	case R_CURSOR:
104		/*
105		 * If flags is R_CURSOR, put the cursor.  Must already
106		 * have started a scan and not have already deleted it.
107		 */
108		if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
109		    !F_ISSET(&t->bt_cursor,
110		        CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE))
111			break;
112		/* FALLTHROUGH */
113	default:
114		errno = EINVAL;
115		return (RET_ERROR);
116	}
117
118	/*
119	 * If the key/data pair won't fit on a page, store it on overflow
120	 * pages.  Only put the key on the overflow page if the pair are
121	 * still too big after moving the data to an overflow page.
122	 *
123	 * XXX
124	 * If the insert fails later on, the overflow pages aren't recovered.
125	 */
126	dflags = 0;
127	if (key->size + data->size > t->bt_ovflsize) {
128		if (key->size > t->bt_ovflsize) {
129			u_int32_t yuck_this_is_gross_code;
130storekey:		if (__ovfl_put(t, key, &pg) == RET_ERROR)
131				return (RET_ERROR);
132			tkey.data = kb;
133			tkey.size = NOVFLSIZE;
134			memmove(kb, &pg, sizeof(db_pgno_t));
135			yuck_this_is_gross_code = key->size;
136			if (yuck_this_is_gross_code != key->size)
137				abort ();
138			memmove(kb + sizeof(db_pgno_t),
139				&yuck_this_is_gross_code, sizeof(u_int32_t));
140			dflags |= P_BIGKEY;
141			key = &tkey;
142		}
143		if (key->size + data->size > t->bt_ovflsize) {
144			u_int32_t yuck_this_is_gross_code = data->size;
145			if (__ovfl_put(t, data, &pg) == RET_ERROR)
146				return (RET_ERROR);
147			tdata.data = db;
148			tdata.size = NOVFLSIZE;
149			memmove(db, &pg, sizeof(db_pgno_t));
150			if (yuck_this_is_gross_code != data->size)
151				abort ();
152			memmove(db + sizeof(db_pgno_t),
153				&yuck_this_is_gross_code, sizeof(u_int32_t));
154			dflags |= P_BIGDATA;
155			data = &tdata;
156		}
157		if (key->size + data->size > t->bt_ovflsize)
158			goto storekey;
159	}
160
161	/* Replace the cursor. */
162	if (flags == R_CURSOR) {
163		if ((h = mpool_get(t->bt_mp, t->bt_cursor.pg.pgno, 0)) == NULL)
164			return (RET_ERROR);
165		idx = t->bt_cursor.pg.index;
166		goto delete;
167	}
168
169	/*
170	 * Find the key to delete, or, the location at which to insert.
171	 * Bt_fast and __bt_search both pin the returned page.
172	 */
173	if (t->bt_order == NOT || (e = bt_fast(t, key, data, &exact)) == NULL)
174		if ((e = __bt_search(t, key, &exact)) == NULL)
175			return (RET_ERROR);
176	h = e->page;
177	idx = e->index;
178
179	/*
180	 * Add the key/data pair to the tree.  If an identical key is already
181	 * in the tree, and R_NOOVERWRITE is set, an error is returned.  If
182	 * R_NOOVERWRITE is not set, the key is either added (if duplicates are
183	 * permitted) or an error is returned.
184	 */
185	switch (flags) {
186	case R_NOOVERWRITE:
187		if (!exact)
188			break;
189		mpool_put(t->bt_mp, h, 0);
190		return (RET_SPECIAL);
191	default:
192		if (!exact || !F_ISSET(t, B_NODUPS))
193			break;
194		/*
195		 * !!!
196		 * Note, the delete may empty the page, so we need to put a
197		 * new entry into the page immediately.
198		 */
199delete:		if (__bt_dleaf(t, key, h, idx) == RET_ERROR) {
200			mpool_put(t->bt_mp, h, 0);
201			return (RET_ERROR);
202		}
203		break;
204	}
205
206	/*
207	 * If not enough room, or the user has put a ceiling on the number of
208	 * keys permitted in the page, split the page.  The split code will
209	 * insert the key and data and unpin the current page.  If inserting
210	 * into the offset array, shift the pointers up.
211	 */
212	nbytes = NBLEAFDBT(key->size, data->size);
213	if (h->upper - h->lower < nbytes + sizeof(indx_t)) {
214		if ((status = __bt_split(t, h, key,
215		    data, dflags, nbytes, idx)) != RET_SUCCESS)
216			return (status);
217		goto success;
218	}
219
220	if (idx < (nxtindex = NEXTINDEX(h)))
221		memmove(h->linp + idx + 1, h->linp + idx,
222		    (nxtindex - idx) * sizeof(indx_t));
223	h->lower += sizeof(indx_t);
224
225	h->linp[idx] = h->upper -= nbytes;
226	dest = (char *)h + h->upper;
227	WR_BLEAF(dest, key, data, dflags);
228
229	/* If the cursor is on this page, adjust it as necessary. */
230	if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
231	    !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) &&
232	    t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index >= idx)
233		++t->bt_cursor.pg.index;
234
235	if (t->bt_order == NOT) {
236		if (h->nextpg == P_INVALID) {
237			if (idx == NEXTINDEX(h) - 1) {
238				t->bt_order = FORWARD;
239				t->bt_last.index = idx;
240				t->bt_last.pgno = h->pgno;
241			}
242		} else if (h->prevpg == P_INVALID) {
243			if (idx == 0) {
244				t->bt_order = BACK;
245				t->bt_last.index = 0;
246				t->bt_last.pgno = h->pgno;
247			}
248		}
249	}
250
251	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
252
253success:
254	if (flags == R_SETCURSOR)
255		__bt_setcur(t, e->page->pgno, e->index);
256
257	F_SET(t, B_MODIFIED);
258	return (RET_SUCCESS);
259}
260
261#ifdef STATISTICS
262u_long bt_cache_hit, bt_cache_miss;
263#endif
264
265/*
266 * BT_FAST -- Do a quick check for sorted data.
267 *
268 * Parameters:
269 *	t:	tree
270 *	key:	key to insert
271 *
272 * Returns:
273 * 	EPG for new record or NULL if not found.
274 */
275static EPG *
276bt_fast(t, key, data, exactp)
277	BTREE *t;
278	const DBT *key, *data;
279	int *exactp;
280{
281	PAGE *h;
282	u_int32_t nbytes;
283	int cmp;
284
285	if ((h = mpool_get(t->bt_mp, t->bt_last.pgno, 0)) == NULL) {
286		t->bt_order = NOT;
287		return (NULL);
288	}
289	t->bt_cur.page = h;
290	t->bt_cur.index = t->bt_last.index;
291
292	/*
293	 * If won't fit in this page or have too many keys in this page,
294	 * have to search to get split stack.
295	 */
296	nbytes = NBLEAFDBT(key->size, data->size);
297	if (h->upper - h->lower < nbytes + sizeof(indx_t))
298		goto miss;
299
300	if (t->bt_order == FORWARD) {
301		if (t->bt_cur.page->nextpg != P_INVALID)
302			goto miss;
303		if (t->bt_cur.index != NEXTINDEX(h) - 1)
304			goto miss;
305		if ((cmp = __bt_cmp(t, key, &t->bt_cur)) < 0)
306			goto miss;
307		t->bt_last.index = cmp ? ++t->bt_cur.index : t->bt_cur.index;
308	} else {
309		if (t->bt_cur.page->prevpg != P_INVALID)
310			goto miss;
311		if (t->bt_cur.index != 0)
312			goto miss;
313		if ((cmp = __bt_cmp(t, key, &t->bt_cur)) > 0)
314			goto miss;
315		t->bt_last.index = 0;
316	}
317	*exactp = cmp == 0;
318#ifdef STATISTICS
319	++bt_cache_hit;
320#endif
321	return (&t->bt_cur);
322
323miss:
324#ifdef STATISTICS
325	++bt_cache_miss;
326#endif
327	t->bt_order = NOT;
328	mpool_put(t->bt_mp, h, 0);
329	return (NULL);
330}
331