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