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