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 /*
36 * Implementation of btree access method for 4.4BSD.
37 *
38 * The design here was originally based on that of the btree access method
39 * used in the Postgres database system at UC Berkeley. This implementation
40 * is wholly independent of the Postgres code.
41 */
42
43 #include "namespace.h"
44 #include <sys/param.h>
45 #include <sys/stat.h>
46
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <limits.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include "un-namespace.h"
56 #include "libc_private.h"
57
58 #include <db.h>
59 #include "btree.h"
60
61 #ifdef DEBUG
62 #undef MINPSIZE
63 #define MINPSIZE 128
64 #endif
65
66 static int byteorder(void);
67 static int nroot(BTREE *);
68 static int tmp(void);
69
70 /*
71 * __BT_OPEN -- Open a btree.
72 *
73 * Creates and fills a DB struct, and calls the routine that actually
74 * opens the btree.
75 *
76 * Parameters:
77 * fname: filename (NULL for in-memory trees)
78 * flags: open flag bits
79 * mode: open permission bits
80 * b: BTREEINFO pointer
81 *
82 * Returns:
83 * NULL on failure, pointer to DB on success.
84 *
85 */
86 DB *
__bt_open(const char * fname,int flags,int mode,const BTREEINFO * openinfo,int dflags)87 __bt_open(const char *fname, int flags, int mode, const BTREEINFO *openinfo, int dflags)
88 {
89 struct stat sb;
90 BTMETA m;
91 BTREE *t;
92 BTREEINFO b;
93 DB *dbp;
94 pgno_t ncache;
95 ssize_t nr;
96 int machine_lorder, saved_errno;
97
98 t = NULL;
99
100 /*
101 * Intention is to make sure all of the user's selections are okay
102 * here and then use them without checking. Can't be complete, since
103 * we don't know the right page size, lorder or flags until the backing
104 * file is opened. Also, the file's page size can cause the cachesize
105 * to change.
106 */
107 machine_lorder = byteorder();
108 if (openinfo) {
109 b = *openinfo;
110
111 /* Flags: R_DUP. */
112 if (b.flags & ~(R_DUP))
113 goto einval;
114
115 /*
116 * Page size must be indx_t aligned and >= MINPSIZE. Default
117 * page size is set farther on, based on the underlying file
118 * transfer size.
119 */
120 if (b.psize &&
121 (b.psize < MINPSIZE || b.psize > MAX_PAGE_OFFSET + 1 ||
122 b.psize & (sizeof(indx_t) - 1) ))
123 goto einval;
124
125 /* Minimum number of keys per page; absolute minimum is 2. */
126 if (b.minkeypage) {
127 if (b.minkeypage < 2)
128 goto einval;
129 } else
130 b.minkeypage = DEFMINKEYPAGE;
131
132 /* If no comparison, use default comparison and prefix. */
133 if (b.compare == NULL) {
134 b.compare = __bt_defcmp;
135 if (b.prefix == NULL)
136 b.prefix = __bt_defpfx;
137 }
138
139 if (b.lorder == 0)
140 b.lorder = machine_lorder;
141 } else {
142 b.compare = __bt_defcmp;
143 b.cachesize = 0;
144 b.flags = 0;
145 b.lorder = machine_lorder;
146 b.minkeypage = DEFMINKEYPAGE;
147 b.prefix = __bt_defpfx;
148 b.psize = 0;
149 }
150
151 /* Check for the ubiquitous PDP-11. */
152 if (b.lorder != BIG_ENDIAN && b.lorder != LITTLE_ENDIAN)
153 goto einval;
154
155 /* Allocate and initialize DB and BTREE structures. */
156 if ((t = (BTREE *)calloc(1, sizeof(BTREE))) == NULL)
157 goto err;
158 t->bt_fd = -1; /* Don't close unopened fd on error. */
159 t->bt_lorder = b.lorder;
160 t->bt_order = NOT;
161 t->bt_cmp = b.compare;
162 t->bt_pfx = b.prefix;
163 t->bt_rfd = -1;
164
165 if ((t->bt_dbp = dbp = (DB *)calloc(1, sizeof(DB))) == NULL)
166 goto err;
167 if (t->bt_lorder != machine_lorder)
168 F_SET(t, B_NEEDSWAP);
169
170 dbp->type = DB_BTREE;
171 dbp->internal = t;
172 dbp->close = __bt_close;
173 dbp->del = __bt_delete;
174 dbp->fd = __bt_fd;
175 dbp->get = __bt_get;
176 dbp->put = __bt_put;
177 dbp->seq = __bt_seq;
178 dbp->sync = __bt_sync;
179
180 /*
181 * If no file name was supplied, this is an in-memory btree and we
182 * open a backing temporary file. Otherwise, it's a disk-based tree.
183 */
184 if (fname) {
185 switch (flags & O_ACCMODE) {
186 case O_RDONLY:
187 F_SET(t, B_RDONLY);
188 break;
189 case O_RDWR:
190 break;
191 case O_WRONLY:
192 default:
193 goto einval;
194 }
195
196 if ((t->bt_fd = _open(fname, flags | O_CLOEXEC, mode)) < 0)
197 goto err;
198
199 } else {
200 if ((flags & O_ACCMODE) != O_RDWR)
201 goto einval;
202 if ((t->bt_fd = tmp()) == -1)
203 goto err;
204 F_SET(t, B_INMEM);
205 }
206
207 if (_fstat(t->bt_fd, &sb))
208 goto err;
209 if (sb.st_size) {
210 if ((nr = _read(t->bt_fd, &m, sizeof(BTMETA))) < 0)
211 goto err;
212 if (nr != sizeof(BTMETA))
213 goto eftype;
214
215 /*
216 * Read in the meta-data. This can change the notion of what
217 * the lorder, page size and flags are, and, when the page size
218 * changes, the cachesize value can change too. If the user
219 * specified the wrong byte order for an existing database, we
220 * don't bother to return an error, we just clear the NEEDSWAP
221 * bit.
222 */
223 if (m.magic == BTREEMAGIC)
224 F_CLR(t, B_NEEDSWAP);
225 else {
226 F_SET(t, B_NEEDSWAP);
227 M_32_SWAP(m.magic);
228 M_32_SWAP(m.version);
229 M_32_SWAP(m.psize);
230 M_32_SWAP(m.free);
231 M_32_SWAP(m.nrecs);
232 M_32_SWAP(m.flags);
233 }
234 if (m.magic != BTREEMAGIC || m.version != BTREEVERSION)
235 goto eftype;
236 if (m.psize < MINPSIZE || m.psize > MAX_PAGE_OFFSET + 1 ||
237 m.psize & (sizeof(indx_t) - 1) )
238 goto eftype;
239 if (m.flags & ~SAVEMETA)
240 goto eftype;
241 b.psize = m.psize;
242 F_SET(t, m.flags);
243 t->bt_free = m.free;
244 t->bt_nrecs = m.nrecs;
245 } else {
246 /*
247 * Set the page size to the best value for I/O to this file.
248 * Don't overflow the page offset type.
249 */
250 if (b.psize == 0) {
251 b.psize = sb.st_blksize;
252 if (b.psize < MINPSIZE)
253 b.psize = MINPSIZE;
254 if (b.psize > MAX_PAGE_OFFSET + 1)
255 b.psize = MAX_PAGE_OFFSET + 1;
256 }
257
258 /* Set flag if duplicates permitted. */
259 if (!(b.flags & R_DUP))
260 F_SET(t, B_NODUPS);
261
262 t->bt_free = P_INVALID;
263 t->bt_nrecs = 0;
264 F_SET(t, B_METADIRTY);
265 }
266
267 t->bt_psize = b.psize;
268
269 /* Set the cache size; must be a multiple of the page size. */
270 if (b.cachesize && b.cachesize & (b.psize - 1) )
271 b.cachesize += (~b.cachesize & (b.psize - 1) ) + 1;
272 if (b.cachesize < b.psize * MINCACHE)
273 b.cachesize = b.psize * MINCACHE;
274
275 /* Calculate number of pages to cache. */
276 ncache = howmany(b.cachesize, t->bt_psize);
277
278 /*
279 * The btree data structure requires that at least two keys can fit on
280 * a page, but other than that there's no fixed requirement. The user
281 * specified a minimum number per page, and we translated that into the
282 * number of bytes a key/data pair can use before being placed on an
283 * overflow page. This calculation includes the page header, the size
284 * of the index referencing the leaf item and the size of the leaf item
285 * structure. Also, don't let the user specify a minkeypage such that
286 * a key/data pair won't fit even if both key and data are on overflow
287 * pages.
288 */
289 t->bt_ovflsize = (t->bt_psize - BTDATAOFF) / b.minkeypage -
290 (sizeof(indx_t) + NBLEAFDBT(0, 0));
291 if (t->bt_ovflsize < NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t))
292 t->bt_ovflsize =
293 NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t);
294
295 /* Initialize the buffer pool. */
296 if ((t->bt_mp =
297 mpool_open(NULL, t->bt_fd, t->bt_psize, ncache)) == NULL)
298 goto err;
299 if (!F_ISSET(t, B_INMEM))
300 mpool_filter(t->bt_mp, __bt_pgin, __bt_pgout, t);
301
302 /* Create a root page if new tree. */
303 if (nroot(t) == RET_ERROR)
304 goto err;
305
306 /* Global flags. */
307 if (dflags & DB_LOCK)
308 F_SET(t, B_DB_LOCK);
309 if (dflags & DB_SHMEM)
310 F_SET(t, B_DB_SHMEM);
311 if (dflags & DB_TXN)
312 F_SET(t, B_DB_TXN);
313
314 return (dbp);
315
316 einval: errno = EINVAL;
317 goto err;
318
319 eftype: errno = EFTYPE;
320 goto err;
321
322 err: saved_errno = errno;
323 if (t) {
324 if (t->bt_dbp)
325 free(t->bt_dbp);
326 if (t->bt_fd != -1)
327 (void)_close(t->bt_fd);
328 free(t);
329 }
330 errno = saved_errno;
331 return (NULL);
332 }
333
334 /*
335 * NROOT -- Create the root of a new tree.
336 *
337 * Parameters:
338 * t: tree
339 *
340 * Returns:
341 * RET_ERROR, RET_SUCCESS
342 */
343 static int
nroot(BTREE * t)344 nroot(BTREE *t)
345 {
346 PAGE *meta, *root;
347 pgno_t npg;
348
349 if ((root = mpool_get(t->bt_mp, 1, 0)) != NULL) {
350 if (root->lower == 0 &&
351 root->pgno == 0 &&
352 root->linp[0] == 0) {
353 mpool_delete(t->bt_mp, root);
354 errno = EINVAL;
355 } else {
356 mpool_put(t->bt_mp, root, 0);
357 return (RET_SUCCESS);
358 }
359 }
360 if (errno != EINVAL) /* It's OK to not exist. */
361 return (RET_ERROR);
362 errno = 0;
363
364 if ((meta = mpool_new(t->bt_mp, &npg, MPOOL_PAGE_NEXT)) == NULL)
365 return (RET_ERROR);
366
367 if ((root = mpool_new(t->bt_mp, &npg, MPOOL_PAGE_NEXT)) == NULL)
368 return (RET_ERROR);
369
370 if (npg != P_ROOT)
371 return (RET_ERROR);
372 root->pgno = npg;
373 root->prevpg = root->nextpg = P_INVALID;
374 root->lower = BTDATAOFF;
375 root->upper = t->bt_psize;
376 root->flags = P_BLEAF;
377 memset(meta, 0, t->bt_psize);
378 mpool_put(t->bt_mp, meta, MPOOL_DIRTY);
379 mpool_put(t->bt_mp, root, MPOOL_DIRTY);
380 return (RET_SUCCESS);
381 }
382
383 static int
tmp(void)384 tmp(void)
385 {
386 sigset_t set, oset;
387 int fd, len;
388 char *envtmp;
389 char path[MAXPATHLEN];
390
391 envtmp = secure_getenv("TMPDIR");
392 len = snprintf(path,
393 sizeof(path), "%s/bt.XXXXXXXXXX", envtmp ? envtmp : "/tmp");
394 if (len < 0 || len >= (int)sizeof(path)) {
395 errno = ENAMETOOLONG;
396 return(-1);
397 }
398
399 (void)sigfillset(&set);
400 (void)__libc_sigprocmask(SIG_BLOCK, &set, &oset);
401 if ((fd = mkostemp(path, O_CLOEXEC)) != -1)
402 (void)unlink(path);
403 (void)__libc_sigprocmask(SIG_SETMASK, &oset, NULL);
404 return(fd);
405 }
406
407 static int
byteorder(void)408 byteorder(void)
409 {
410 u_int32_t x;
411 u_char *p;
412
413 x = 0x01020304;
414 p = (u_char *)&x;
415 switch (*p) {
416 case 1:
417 return (BIG_ENDIAN);
418 case 4:
419 return (LITTLE_ENDIAN);
420 default:
421 return (0);
422 }
423 }
424
425 int
__bt_fd(const DB * dbp)426 __bt_fd(const DB *dbp)
427 {
428 BTREE *t;
429
430 t = dbp->internal;
431
432 /* Toss any page pinned across calls. */
433 if (t->bt_pinned != NULL) {
434 mpool_put(t->bt_mp, t->bt_pinned, 0);
435 t->bt_pinned = NULL;
436 }
437
438 /* In-memory database can't have a file descriptor. */
439 if (F_ISSET(t, B_INMEM)) {
440 errno = ENOENT;
441 return (-1);
442 }
443 return (t->bt_fd);
444 }
445