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