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