/*-1* SPDX-License-Identifier: BSD-3-Clause2*3* Copyright (c) 1990, 1993, 19944* The Regents of the University of California. All rights reserved.5*6* This code is derived from software contributed to Berkeley by7* Mike Olson.8*9* Redistribution and use in source and binary forms, with or without10* modification, are permitted provided that the following conditions11* are met:12* 1. Redistributions of source code must retain the above copyright13* notice, this list of conditions and the following disclaimer.14* 2. Redistributions in binary form must reproduce the above copyright15* notice, this list of conditions and the following disclaimer in the16* documentation and/or other materials provided with the distribution.17* 3. Neither the name of the University nor the names of its contributors18* may be used to endorse or promote products derived from this software19* without specific prior written permission.20*21* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND22* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE23* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE24* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE25* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL26* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS27* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)28* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT29* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY30* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF31* SUCH DAMAGE.32*/3334/*35* Implementation of btree access method for 4.4BSD.36*37* The design here was originally based on that of the btree access method38* used in the Postgres database system at UC Berkeley. This implementation39* is wholly independent of the Postgres code.40*/4142#include "namespace.h"43#include <sys/param.h>44#include <sys/stat.h>4546#include <errno.h>47#include <fcntl.h>48#include <limits.h>49#include <signal.h>50#include <stdio.h>51#include <stdlib.h>52#include <string.h>53#include <unistd.h>54#include "un-namespace.h"55#include "libc_private.h"5657#include <db.h>58#include "btree.h"5960#ifdef DEBUG61#undef MINPSIZE62#define MINPSIZE 12863#endif6465static int byteorder(void);66static int nroot(BTREE *);67static int tmp(void);6869/*70* __BT_OPEN -- Open a btree.71*72* Creates and fills a DB struct, and calls the routine that actually73* opens the btree.74*75* Parameters:76* fname: filename (NULL for in-memory trees)77* flags: open flag bits78* mode: open permission bits79* b: BTREEINFO pointer80*81* Returns:82* NULL on failure, pointer to DB on success.83*84*/85DB *86__bt_open(const char *fname, int flags, int mode, const BTREEINFO *openinfo, int dflags)87{88struct stat sb;89BTMETA m;90BTREE *t;91BTREEINFO b;92DB *dbp;93pgno_t ncache;94ssize_t nr;95int machine_lorder, saved_errno;9697t = NULL;9899/*100* Intention is to make sure all of the user's selections are okay101* here and then use them without checking. Can't be complete, since102* we don't know the right page size, lorder or flags until the backing103* file is opened. Also, the file's page size can cause the cachesize104* to change.105*/106machine_lorder = byteorder();107if (openinfo) {108b = *openinfo;109110/* Flags: R_DUP. */111if (b.flags & ~(R_DUP))112goto einval;113114/*115* Page size must be indx_t aligned and >= MINPSIZE. Default116* page size is set farther on, based on the underlying file117* transfer size.118*/119if (b.psize &&120(b.psize < MINPSIZE || b.psize > MAX_PAGE_OFFSET + 1 ||121b.psize & (sizeof(indx_t) - 1) ))122goto einval;123124/* Minimum number of keys per page; absolute minimum is 2. */125if (b.minkeypage) {126if (b.minkeypage < 2)127goto einval;128} else129b.minkeypage = DEFMINKEYPAGE;130131/* If no comparison, use default comparison and prefix. */132if (b.compare == NULL) {133b.compare = __bt_defcmp;134if (b.prefix == NULL)135b.prefix = __bt_defpfx;136}137138if (b.lorder == 0)139b.lorder = machine_lorder;140} else {141b.compare = __bt_defcmp;142b.cachesize = 0;143b.flags = 0;144b.lorder = machine_lorder;145b.minkeypage = DEFMINKEYPAGE;146b.prefix = __bt_defpfx;147b.psize = 0;148}149150/* Check for the ubiquitous PDP-11. */151if (b.lorder != BIG_ENDIAN && b.lorder != LITTLE_ENDIAN)152goto einval;153154/* Allocate and initialize DB and BTREE structures. */155if ((t = (BTREE *)calloc(1, sizeof(BTREE))) == NULL)156goto err;157t->bt_fd = -1; /* Don't close unopened fd on error. */158t->bt_lorder = b.lorder;159t->bt_order = NOT;160t->bt_cmp = b.compare;161t->bt_pfx = b.prefix;162t->bt_rfd = -1;163164if ((t->bt_dbp = dbp = (DB *)calloc(1, sizeof(DB))) == NULL)165goto err;166if (t->bt_lorder != machine_lorder)167F_SET(t, B_NEEDSWAP);168169dbp->type = DB_BTREE;170dbp->internal = t;171dbp->close = __bt_close;172dbp->del = __bt_delete;173dbp->fd = __bt_fd;174dbp->get = __bt_get;175dbp->put = __bt_put;176dbp->seq = __bt_seq;177dbp->sync = __bt_sync;178179/*180* If no file name was supplied, this is an in-memory btree and we181* open a backing temporary file. Otherwise, it's a disk-based tree.182*/183if (fname) {184switch (flags & O_ACCMODE) {185case O_RDONLY:186F_SET(t, B_RDONLY);187break;188case O_RDWR:189break;190case O_WRONLY:191default:192goto einval;193}194195if ((t->bt_fd = _open(fname, flags | O_CLOEXEC, mode)) < 0)196goto err;197198} else {199if ((flags & O_ACCMODE) != O_RDWR)200goto einval;201if ((t->bt_fd = tmp()) == -1)202goto err;203F_SET(t, B_INMEM);204}205206if (_fstat(t->bt_fd, &sb))207goto err;208if (sb.st_size) {209if ((nr = _read(t->bt_fd, &m, sizeof(BTMETA))) < 0)210goto err;211if (nr != sizeof(BTMETA))212goto eftype;213214/*215* Read in the meta-data. This can change the notion of what216* the lorder, page size and flags are, and, when the page size217* changes, the cachesize value can change too. If the user218* specified the wrong byte order for an existing database, we219* don't bother to return an error, we just clear the NEEDSWAP220* bit.221*/222if (m.magic == BTREEMAGIC)223F_CLR(t, B_NEEDSWAP);224else {225F_SET(t, B_NEEDSWAP);226M_32_SWAP(m.magic);227M_32_SWAP(m.version);228M_32_SWAP(m.psize);229M_32_SWAP(m.free);230M_32_SWAP(m.nrecs);231M_32_SWAP(m.flags);232}233if (m.magic != BTREEMAGIC || m.version != BTREEVERSION)234goto eftype;235if (m.psize < MINPSIZE || m.psize > MAX_PAGE_OFFSET + 1 ||236m.psize & (sizeof(indx_t) - 1) )237goto eftype;238if (m.flags & ~SAVEMETA)239goto eftype;240b.psize = m.psize;241F_SET(t, m.flags);242t->bt_free = m.free;243t->bt_nrecs = m.nrecs;244} else {245/*246* Set the page size to the best value for I/O to this file.247* Don't overflow the page offset type.248*/249if (b.psize == 0) {250b.psize = sb.st_blksize;251if (b.psize < MINPSIZE)252b.psize = MINPSIZE;253if (b.psize > MAX_PAGE_OFFSET + 1)254b.psize = MAX_PAGE_OFFSET + 1;255}256257/* Set flag if duplicates permitted. */258if (!(b.flags & R_DUP))259F_SET(t, B_NODUPS);260261t->bt_free = P_INVALID;262t->bt_nrecs = 0;263F_SET(t, B_METADIRTY);264}265266t->bt_psize = b.psize;267268/* Set the cache size; must be a multiple of the page size. */269if (b.cachesize && b.cachesize & (b.psize - 1) )270b.cachesize += (~b.cachesize & (b.psize - 1) ) + 1;271if (b.cachesize < b.psize * MINCACHE)272b.cachesize = b.psize * MINCACHE;273274/* Calculate number of pages to cache. */275ncache = howmany(b.cachesize, t->bt_psize);276277/*278* The btree data structure requires that at least two keys can fit on279* a page, but other than that there's no fixed requirement. The user280* specified a minimum number per page, and we translated that into the281* number of bytes a key/data pair can use before being placed on an282* overflow page. This calculation includes the page header, the size283* of the index referencing the leaf item and the size of the leaf item284* structure. Also, don't let the user specify a minkeypage such that285* a key/data pair won't fit even if both key and data are on overflow286* pages.287*/288t->bt_ovflsize = (t->bt_psize - BTDATAOFF) / b.minkeypage -289(sizeof(indx_t) + NBLEAFDBT(0, 0));290if (t->bt_ovflsize < NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t))291t->bt_ovflsize =292NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t);293294/* Initialize the buffer pool. */295if ((t->bt_mp =296mpool_open(NULL, t->bt_fd, t->bt_psize, ncache)) == NULL)297goto err;298if (!F_ISSET(t, B_INMEM))299mpool_filter(t->bt_mp, __bt_pgin, __bt_pgout, t);300301/* Create a root page if new tree. */302if (nroot(t) == RET_ERROR)303goto err;304305/* Global flags. */306if (dflags & DB_LOCK)307F_SET(t, B_DB_LOCK);308if (dflags & DB_SHMEM)309F_SET(t, B_DB_SHMEM);310if (dflags & DB_TXN)311F_SET(t, B_DB_TXN);312313return (dbp);314315einval: errno = EINVAL;316goto err;317318eftype: errno = EFTYPE;319goto err;320321err: saved_errno = errno;322if (t) {323if (t->bt_dbp)324free(t->bt_dbp);325if (t->bt_fd != -1)326(void)_close(t->bt_fd);327free(t);328}329errno = saved_errno;330return (NULL);331}332333/*334* NROOT -- Create the root of a new tree.335*336* Parameters:337* t: tree338*339* Returns:340* RET_ERROR, RET_SUCCESS341*/342static int343nroot(BTREE *t)344{345PAGE *meta, *root;346pgno_t npg;347348if ((root = mpool_get(t->bt_mp, 1, 0)) != NULL) {349if (root->lower == 0 &&350root->pgno == 0 &&351root->linp[0] == 0) {352mpool_delete(t->bt_mp, root);353errno = EINVAL;354} else {355mpool_put(t->bt_mp, root, 0);356return (RET_SUCCESS);357}358}359if (errno != EINVAL) /* It's OK to not exist. */360return (RET_ERROR);361errno = 0;362363if ((meta = mpool_new(t->bt_mp, &npg, MPOOL_PAGE_NEXT)) == NULL)364return (RET_ERROR);365366if ((root = mpool_new(t->bt_mp, &npg, MPOOL_PAGE_NEXT)) == NULL)367return (RET_ERROR);368369if (npg != P_ROOT)370return (RET_ERROR);371root->pgno = npg;372root->prevpg = root->nextpg = P_INVALID;373root->lower = BTDATAOFF;374root->upper = t->bt_psize;375root->flags = P_BLEAF;376memset(meta, 0, t->bt_psize);377mpool_put(t->bt_mp, meta, MPOOL_DIRTY);378mpool_put(t->bt_mp, root, MPOOL_DIRTY);379return (RET_SUCCESS);380}381382static int383tmp(void)384{385sigset_t set, oset;386int fd, len;387char *envtmp;388char path[MAXPATHLEN];389390envtmp = secure_getenv("TMPDIR");391len = snprintf(path,392sizeof(path), "%s/bt.XXXXXXXXXX", envtmp ? envtmp : "/tmp");393if (len < 0 || len >= (int)sizeof(path)) {394errno = ENAMETOOLONG;395return(-1);396}397398(void)sigfillset(&set);399(void)__libc_sigprocmask(SIG_BLOCK, &set, &oset);400if ((fd = mkostemp(path, O_CLOEXEC)) != -1)401(void)unlink(path);402(void)__libc_sigprocmask(SIG_SETMASK, &oset, NULL);403return(fd);404}405406static int407byteorder(void)408{409u_int32_t x;410u_char *p;411412x = 0x01020304;413p = (u_char *)&x;414switch (*p) {415case 1:416return (BIG_ENDIAN);417case 4:418return (LITTLE_ENDIAN);419default:420return (0);421}422}423424int425__bt_fd(const DB *dbp)426{427BTREE *t;428429t = dbp->internal;430431/* Toss any page pinned across calls. */432if (t->bt_pinned != NULL) {433mpool_put(t->bt_mp, t->bt_pinned, 0);434t->bt_pinned = NULL;435}436437/* In-memory database can't have a file descriptor. */438if (F_ISSET(t, B_INMEM)) {439errno = ENOENT;440return (-1);441}442return (t->bt_fd);443}444445446