xref: /netbsd-src/lib/libc/db/btree/bt_put.c (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1 /*	$NetBSD: bt_put.c,v 1.15 2007/02/03 23:46:09 christos 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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #if defined(LIBC_SCCS) && !defined(lint)
37 #if 0
38 static char sccsid[] = "@(#)bt_put.c	8.8 (Berkeley) 7/26/94";
39 #else
40 __RCSID("$NetBSD: bt_put.c,v 1.15 2007/02/03 23:46:09 christos Exp $");
41 #endif
42 #endif /* LIBC_SCCS and not lint */
43 
44 #include "namespace.h"
45 #include <sys/types.h>
46 
47 #include <assert.h>
48 #include <errno.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 
53 #include <db.h>
54 #include "btree.h"
55 
56 static EPG *bt_fast(BTREE *, const DBT *, const DBT *, int *);
57 
58 /*
59  * __BT_PUT -- Add a btree item to the tree.
60  *
61  * Parameters:
62  *	dbp:	pointer to access method
63  *	key:	key
64  *	data:	data
65  *	flag:	R_NOOVERWRITE
66  *
67  * Returns:
68  *	RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key is already in the
69  *	tree and R_NOOVERWRITE specified.
70  */
71 int
72 __bt_put(const DB *dbp, DBT *key, const DBT *data, u_int flags)
73 {
74 	BTREE *t;
75 	DBT tkey, tdata;
76 	EPG *e = NULL; /* pacify gcc */
77 	PAGE *h;
78 	indx_t idx, nxtindex;
79 	pgno_t pg;
80 	u_int32_t nbytes, temp;
81 	int dflags, exact, status;
82 	char *dest, db[NOVFLSIZE], kb[NOVFLSIZE];
83 
84 	t = dbp->internal;
85 
86 	/* Toss any page pinned across calls. */
87 	if (t->bt_pinned != NULL) {
88 		mpool_put(t->bt_mp, t->bt_pinned, 0);
89 		t->bt_pinned = NULL;
90 	}
91 
92 	/* Check for change to a read-only tree. */
93 	if (F_ISSET(t, B_RDONLY)) {
94 		errno = EPERM;
95 		return (RET_ERROR);
96 	}
97 
98 	switch (flags) {
99 	case 0:
100 	case R_NOOVERWRITE:
101 		break;
102 	case R_CURSOR:
103 		/*
104 		 * If flags is R_CURSOR, put the cursor.  Must already
105 		 * have started a scan and not have already deleted it.
106 		 */
107 		if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
108 		    !F_ISSET(&t->bt_cursor,
109 		        CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE))
110 			break;
111 		/* FALLTHROUGH */
112 	default:
113 		errno = EINVAL;
114 		return (RET_ERROR);
115 	}
116 
117 	/*
118 	 * If the key/data pair won't fit on a page, store it on overflow
119 	 * pages.  Only put the key on the overflow page if the pair are
120 	 * still too big after moving the data to an overflow page.
121 	 *
122 	 * XXX
123 	 * If the insert fails later on, the overflow pages aren't recovered.
124 	 */
125 	dflags = 0;
126 	if (key->size + data->size > t->bt_ovflsize) {
127 		if (key->size > t->bt_ovflsize) {
128 storekey:		if (__ovfl_put(t, key, &pg) == RET_ERROR)
129 				return (RET_ERROR);
130 			tkey.data = kb;
131 			tkey.size = NOVFLSIZE;
132 			memmove(kb, &pg, sizeof(pgno_t));
133 			memmove(kb + sizeof(pgno_t),
134 			    &key->size, sizeof(u_int32_t));
135 			dflags |= P_BIGKEY;
136 			key = &tkey;
137 		}
138 		if (key->size + data->size > t->bt_ovflsize) {
139 			if (__ovfl_put(t, data, &pg) == RET_ERROR)
140 				return (RET_ERROR);
141 			tdata.data = db;
142 			tdata.size = NOVFLSIZE;
143 			memmove(db, &pg, sizeof(pgno_t));
144 			_DBFIT(data->size, u_int32_t);
145 			temp = (u_int32_t)data->size;
146 			(void)memmove(db + sizeof(pgno_t),
147 			    &temp, sizeof(u_int32_t));
148 			dflags |= P_BIGDATA;
149 			data = &tdata;
150 		}
151 		if (key->size + data->size > t->bt_ovflsize)
152 			goto storekey;
153 	}
154 
155 	/* Replace the cursor. */
156 	if (flags == R_CURSOR) {
157 		if ((h = mpool_get(t->bt_mp, t->bt_cursor.pg.pgno, 0)) == NULL)
158 			return (RET_ERROR);
159 		idx = t->bt_cursor.pg.index;
160 		goto delete;
161 	}
162 
163 	/*
164 	 * Find the key to delete, or, the location at which to insert.
165 	 * Bt_fast and __bt_search both pin the returned page.
166 	 */
167 	if (t->bt_order == NOT || (e = bt_fast(t, key, data, &exact)) == NULL)
168 		if ((e = __bt_search(t, key, &exact)) == NULL)
169 			return (RET_ERROR);
170 	h = e->page;
171 	idx = e->index;
172 
173 	/*
174 	 * Add the key/data pair to the tree.  If an identical key is already
175 	 * in the tree, and R_NOOVERWRITE is set, an error is returned.  If
176 	 * R_NOOVERWRITE is not set, the key is either added (if duplicates are
177 	 * permitted) or an error is returned.
178 	 */
179 	switch (flags) {
180 	case R_NOOVERWRITE:
181 		if (!exact)
182 			break;
183 		mpool_put(t->bt_mp, h, 0);
184 		return (RET_SPECIAL);
185 	default:
186 		if (!exact || !F_ISSET(t, B_NODUPS))
187 			break;
188 		/*
189 		 * !!!
190 		 * Note, the delete may empty the page, so we need to put a
191 		 * new entry into the page immediately.
192 		 */
193 delete:		if (__bt_dleaf(t, key, h, (u_int)idx) == RET_ERROR) {
194 			mpool_put(t->bt_mp, h, 0);
195 			return (RET_ERROR);
196 		}
197 		break;
198 	}
199 
200 	/*
201 	 * If not enough room, or the user has put a ceiling on the number of
202 	 * keys permitted in the page, split the page.  The split code will
203 	 * insert the key and data and unpin the current page.  If inserting
204 	 * into the offset array, shift the pointers up.
205 	 */
206 	nbytes = NBLEAFDBT(key->size, data->size);
207 	if (h->upper - h->lower < nbytes + sizeof(indx_t)) {
208 		if ((status = __bt_split(t, h, key,
209 		    data, dflags, nbytes, (u_int)idx)) != RET_SUCCESS)
210 			return (status);
211 		goto success;
212 	}
213 
214 	if (idx < (nxtindex = NEXTINDEX(h)))
215 		memmove(h->linp + idx + 1, h->linp + idx,
216 		    (nxtindex - idx) * sizeof(indx_t));
217 	h->lower += sizeof(indx_t);
218 
219 	h->linp[idx] = h->upper -= nbytes;
220 	dest = (char *)(void *)h + h->upper;
221 	WR_BLEAF(dest, key, data, dflags);
222 
223 	/* If the cursor is on this page, adjust it as necessary. */
224 	if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
225 	    !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) &&
226 	    t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index >= idx)
227 		++t->bt_cursor.pg.index;
228 
229 	if (t->bt_order == NOT) {
230 		if (h->nextpg == P_INVALID) {
231 			if (idx == NEXTINDEX(h) - 1) {
232 				t->bt_order = FORWARD;
233 				t->bt_last.index = idx;
234 				t->bt_last.pgno = h->pgno;
235 			}
236 		} else if (h->prevpg == P_INVALID) {
237 			if (idx == 0) {
238 				t->bt_order = BACK;
239 				t->bt_last.index = 0;
240 				t->bt_last.pgno = h->pgno;
241 			}
242 		}
243 	}
244 
245 	mpool_put(t->bt_mp, h, MPOOL_DIRTY);
246 
247 success:
248 	if (flags == R_SETCURSOR)
249 		__bt_setcur(t, e->page->pgno, (u_int)e->index);
250 
251 	F_SET(t, B_MODIFIED);
252 	return (RET_SUCCESS);
253 }
254 
255 #ifdef STATISTICS
256 u_long bt_cache_hit, bt_cache_miss;
257 #endif
258 
259 /*
260  * BT_FAST -- Do a quick check for sorted data.
261  *
262  * Parameters:
263  *	t:	tree
264  *	key:	key to insert
265  *
266  * Returns:
267  * 	EPG for new record or NULL if not found.
268  */
269 static EPG *
270 bt_fast(BTREE *t, const DBT *key, const DBT *data, int *exactp)
271 {
272 	PAGE *h;
273 	u_int32_t nbytes;
274 	int cmp;
275 
276 	if ((h = mpool_get(t->bt_mp, t->bt_last.pgno, 0)) == NULL) {
277 		t->bt_order = NOT;
278 		return (NULL);
279 	}
280 	t->bt_cur.page = h;
281 	t->bt_cur.index = t->bt_last.index;
282 
283 	/*
284 	 * If won't fit in this page or have too many keys in this page,
285 	 * have to search to get split stack.
286 	 */
287 	nbytes = NBLEAFDBT(key->size, data->size);
288 	if (h->upper - h->lower < nbytes + sizeof(indx_t))
289 		goto miss;
290 
291 	if (t->bt_order == FORWARD) {
292 		if (t->bt_cur.page->nextpg != P_INVALID)
293 			goto miss;
294 		if (t->bt_cur.index != NEXTINDEX(h) - 1)
295 			goto miss;
296 		if ((cmp = __bt_cmp(t, key, &t->bt_cur)) < 0)
297 			goto miss;
298 		t->bt_last.index = cmp ? ++t->bt_cur.index : t->bt_cur.index;
299 	} else {
300 		if (t->bt_cur.page->prevpg != P_INVALID)
301 			goto miss;
302 		if (t->bt_cur.index != 0)
303 			goto miss;
304 		if ((cmp = __bt_cmp(t, key, &t->bt_cur)) > 0)
305 			goto miss;
306 		t->bt_last.index = 0;
307 	}
308 	*exactp = cmp == 0;
309 #ifdef STATISTICS
310 	++bt_cache_hit;
311 #endif
312 	return (&t->bt_cur);
313 
314 miss:
315 #ifdef STATISTICS
316 	++bt_cache_miss;
317 #endif
318 	t->bt_order = NOT;
319 	mpool_put(t->bt_mp, h, 0);
320 	return (NULL);
321 }
322