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