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