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