]> git.saurik.com Git - apple/libc.git/blob - db/btree/bt_open.c
Libc-320.1.3.tar.gz
[apple/libc.git] / db / btree / bt_open.c
1 /*
2 * Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 /*-
24 * Copyright (c) 1990, 1993, 1994
25 * The Regents of the University of California. All rights reserved.
26 *
27 * This code is derived from software contributed to Berkeley by
28 * Mike Olson.
29 *
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38 * 3. All advertising materials mentioning features or use of this software
39 * must display the following acknowledgement:
40 * This product includes software developed by the University of
41 * California, Berkeley and its contributors.
42 * 4. Neither the name of the University nor the names of its contributors
43 * may be used to endorse or promote products derived from this software
44 * without specific prior written permission.
45 *
46 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56 * SUCH DAMAGE.
57 */
58
59 #if defined(LIBC_SCCS) && !defined(lint)
60 static char sccsid[] = "@(#)bt_open.c 8.10 (Berkeley) 8/17/94";
61 #endif /* LIBC_SCCS and not lint */
62 #include <sys/cdefs.h>
63
64 /*
65 * Implementation of btree access method for 4.4BSD.
66 *
67 * The design here was originally based on that of the btree access method
68 * used in the Postgres database system at UC Berkeley. This implementation
69 * is wholly independent of the Postgres code.
70 */
71
72 #include <sys/param.h>
73 #include <sys/stat.h>
74
75 #include <errno.h>
76 #include <fcntl.h>
77 #include <limits.h>
78 #include <signal.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <unistd.h>
83
84 #include <db.h>
85 #include "btree.h"
86
87 #ifdef DEBUG
88 #undef MINPSIZE
89 #define MINPSIZE 128
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(fname, flags, mode, openinfo, dflags)
114 const char *fname;
115 int flags, mode, dflags;
116 const BTREEINFO *openinfo;
117 {
118 struct stat sb;
119 BTMETA m;
120 BTREE *t;
121 BTREEINFO b;
122 DB *dbp;
123 pgno_t ncache;
124 ssize_t nr;
125 int machine_lorder;
126
127 t = NULL;
128
129 /*
130 * Intention is to make sure all of the user's selections are okay
131 * here and then use them without checking. Can't be complete, since
132 * we don't know the right page size, lorder or flags until the backing
133 * file is opened. Also, the file's page size can cause the cachesize
134 * to change.
135 */
136 machine_lorder = byteorder();
137 if (openinfo) {
138 b = *openinfo;
139
140 /* Flags: R_DUP. */
141 if (b.flags & ~(R_DUP))
142 goto einval;
143
144 /*
145 * Page size must be indx_t aligned and >= MINPSIZE. Default
146 * page size is set farther on, based on the underlying file
147 * transfer size.
148 */
149 if (b.psize &&
150 (b.psize < MINPSIZE || b.psize > MAX_PAGE_OFFSET + 1 ||
151 b.psize & (sizeof(indx_t) - 1) ))
152 goto einval;
153
154 /* Minimum number of keys per page; absolute minimum is 2. */
155 if (b.minkeypage) {
156 if (b.minkeypage < 2)
157 goto einval;
158 } else
159 b.minkeypage = DEFMINKEYPAGE;
160
161 /* If no comparison, use default comparison and prefix. */
162 if (b.compare == NULL) {
163 b.compare = __bt_defcmp;
164 if (b.prefix == NULL)
165 b.prefix = __bt_defpfx;
166 }
167
168 if (b.lorder == 0)
169 b.lorder = machine_lorder;
170 } else {
171 b.compare = __bt_defcmp;
172 b.cachesize = 0;
173 b.flags = 0;
174 b.lorder = machine_lorder;
175 b.minkeypage = DEFMINKEYPAGE;
176 b.prefix = __bt_defpfx;
177 b.psize = 0;
178 }
179
180 /* Check for the ubiquitous PDP-11. */
181 if (b.lorder != BIG_ENDIAN && b.lorder != LITTLE_ENDIAN)
182 goto einval;
183
184 /* Allocate and initialize DB and BTREE structures. */
185 if ((t = (BTREE *)malloc(sizeof(BTREE))) == NULL)
186 goto err;
187 memset(t, 0, sizeof(BTREE));
188 t->bt_fd = -1; /* Don't close unopened fd on error. */
189 t->bt_lorder = b.lorder;
190 t->bt_order = NOT;
191 t->bt_cmp = b.compare;
192 t->bt_pfx = b.prefix;
193 t->bt_rfd = -1;
194
195 if ((t->bt_dbp = dbp = (DB *)malloc(sizeof(DB))) == NULL)
196 goto err;
197 memset(t->bt_dbp, 0, sizeof(DB));
198 if (t->bt_lorder != machine_lorder)
199 F_SET(t, B_NEEDSWAP);
200
201 dbp->type = DB_BTREE;
202 dbp->internal = t;
203 dbp->close = __bt_close;
204 dbp->del = __bt_delete;
205 dbp->fd = __bt_fd;
206 dbp->get = __bt_get;
207 dbp->put = __bt_put;
208 dbp->seq = __bt_seq;
209 dbp->sync = __bt_sync;
210
211 /*
212 * If no file name was supplied, this is an in-memory btree and we
213 * open a backing temporary file. Otherwise, it's a disk-based tree.
214 */
215 if (fname) {
216 switch (flags & O_ACCMODE) {
217 case O_RDONLY:
218 F_SET(t, B_RDONLY);
219 break;
220 case O_RDWR:
221 break;
222 case O_WRONLY:
223 default:
224 goto einval;
225 }
226
227 if ((t->bt_fd = open(fname, flags, mode)) < 0)
228 goto err;
229
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, 1) == -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 b.psize = sb.st_blksize;
286 if (b.psize < MINPSIZE)
287 b.psize = MINPSIZE;
288 if (b.psize > MAX_PAGE_OFFSET + 1)
289 b.psize = MAX_PAGE_OFFSET + 1;
290 }
291
292 /* Set flag if duplicates permitted. */
293 if (!(b.flags & R_DUP))
294 F_SET(t, B_NODUPS);
295
296 t->bt_free = P_INVALID;
297 t->bt_nrecs = 0;
298 F_SET(t, B_METADIRTY);
299 }
300
301 t->bt_psize = b.psize;
302
303 /* Set the cache size; must be a multiple of the page size. */
304 if (b.cachesize && b.cachesize & (b.psize - 1) )
305 b.cachesize += (~b.cachesize & (b.psize - 1) ) + 1;
306 if (b.cachesize < b.psize * MINCACHE)
307 b.cachesize = b.psize * MINCACHE;
308
309 /* Calculate number of pages to cache. */
310 ncache = (b.cachesize + t->bt_psize - 1) / t->bt_psize;
311
312 /*
313 * The btree data structure requires that at least two keys can fit on
314 * a page, but other than that there's no fixed requirement. The user
315 * specified a minimum number per page, and we translated that into the
316 * number of bytes a key/data pair can use before being placed on an
317 * overflow page. This calculation includes the page header, the size
318 * of the index referencing the leaf item and the size of the leaf item
319 * structure. Also, don't let the user specify a minkeypage such that
320 * a key/data pair won't fit even if both key and data are on overflow
321 * pages.
322 */
323 t->bt_ovflsize = (t->bt_psize - BTDATAOFF) / b.minkeypage -
324 (sizeof(indx_t) + NBLEAFDBT(0, 0));
325 if (t->bt_ovflsize < NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t))
326 t->bt_ovflsize =
327 NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t);
328
329 /* Initialize the buffer pool. */
330 if ((t->bt_mp =
331 mpool_open(NULL, t->bt_fd, t->bt_psize, ncache)) == NULL)
332 goto err;
333 if (!F_ISSET(t, B_INMEM))
334 mpool_filter(t->bt_mp, __bt_pgin, __bt_pgout, t);
335
336 /* Create a root page if new tree. */
337 if (nroot(t) == RET_ERROR)
338 goto err;
339
340 /* Global flags. */
341 if (dflags & DB_LOCK)
342 F_SET(t, B_DB_LOCK);
343 if (dflags & DB_SHMEM)
344 F_SET(t, B_DB_SHMEM);
345 if (dflags & DB_TXN)
346 F_SET(t, B_DB_TXN);
347
348 return (dbp);
349
350 einval: errno = EINVAL;
351 goto err;
352
353 eftype: errno = EFTYPE;
354 goto err;
355
356 err: if (t) {
357 if (t->bt_dbp)
358 free(t->bt_dbp);
359 if (t->bt_fd != -1)
360 (void)close(t->bt_fd);
361 free(t);
362 }
363 return (NULL);
364 }
365
366 /*
367 * NROOT -- Create the root of a new tree.
368 *
369 * Parameters:
370 * t: tree
371 *
372 * Returns:
373 * RET_ERROR, RET_SUCCESS
374 */
375 static int
376 nroot(t)
377 BTREE *t;
378 {
379 PAGE *meta, *root;
380 pgno_t npg;
381
382 if ((meta = mpool_get(t->bt_mp, 0, 0)) != NULL) {
383 mpool_put(t->bt_mp, meta, 0);
384 return (RET_SUCCESS);
385 }
386 if (errno != EINVAL) /* It's OK to not exist. */
387 return (RET_ERROR);
388 errno = 0;
389
390 if ((meta = mpool_new(t->bt_mp, &npg)) == NULL)
391 return (RET_ERROR);
392
393 if ((root = mpool_new(t->bt_mp, &npg)) == NULL)
394 return (RET_ERROR);
395
396 if (npg != P_ROOT)
397 return (RET_ERROR);
398 root->pgno = npg;
399 root->prevpg = root->nextpg = P_INVALID;
400 root->lower = BTDATAOFF;
401 root->upper = t->bt_psize;
402 root->flags = P_BLEAF;
403 memset(meta, 0, t->bt_psize);
404 mpool_put(t->bt_mp, meta, MPOOL_DIRTY);
405 mpool_put(t->bt_mp, root, MPOOL_DIRTY);
406 return (RET_SUCCESS);
407 }
408
409 static int
410 tmp()
411 {
412 sigset_t set, oset;
413 int fd;
414 char *envtmp = NULL;
415 char path[MAXPATHLEN];
416
417 if (issetugid() == 0)
418 envtmp = getenv("TMPDIR");
419 (void)snprintf(path,
420 sizeof(path), "%s/bt.XXXXXXXXXX", envtmp ? envtmp : "/tmp");
421
422 (void)sigfillset(&set);
423 (void)sigprocmask(SIG_BLOCK, &set, &oset);
424 if ((fd = mkstemp(path)) != -1)
425 (void)unlink(path);
426 (void)sigprocmask(SIG_SETMASK, &oset, NULL);
427 return(fd);
428 }
429
430 static int
431 byteorder()
432 {
433 u_int32_t x;
434 u_char *p;
435
436 x = 0x01020304;
437 p = (u_char *)&x;
438 switch (*p) {
439 case 1:
440 return (BIG_ENDIAN);
441 case 4:
442 return (LITTLE_ENDIAN);
443 default:
444 return (0);
445 }
446 }
447
448 int
449 __bt_fd(dbp)
450 const DB *dbp;
451 {
452 BTREE *t;
453
454 t = dbp->internal;
455
456 /* Toss any page pinned across calls. */
457 if (t->bt_pinned != NULL) {
458 mpool_put(t->bt_mp, t->bt_pinned, 0);
459 t->bt_pinned = NULL;
460 }
461
462 /* In-memory database can't have a file descriptor. */
463 if (F_ISSET(t, B_INMEM)) {
464 errno = ENOENT;
465 return (-1);
466 }
467 return (t->bt_fd);
468 }