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