2 * See the file LICENSE for redistribution information.
4 * Copyright (c) 1996, 1997
5 * Sleepycat Software. All rights reserved.
8 * Copyright (c) 1990, 1993, 1994, 1995, 1996
9 * Keith Bostic. All rights reserved.
12 * Copyright (c) 1990, 1993, 1994, 1995
13 * The Regents of the University of California. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. All advertising materials mentioning features or use of this software
24 * must display the following acknowledgement:
25 * This product includes software developed by the University of
26 * California, Berkeley and its contributors.
27 * 4. Neither the name of the University nor the names of its contributors
28 * may be used to endorse or promote products derived from this software
29 * without specific prior written permission.
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 static const char sccsid[] = "@(#)db.c 10.38 (Sleepycat) 9/2/97";
50 #ifndef NO_SYSTEM_INCLUDES
51 #include <sys/types.h>
72 #include "common_ext.h"
74 static int db_close __P((DB *, int));
75 static int db_fd __P((DB *, int *));
78 * If the metadata page has the flag set, set the local flag. If the page
79 * does NOT have the flag set, return EINVAL if the user's dbinfo argument
80 * caused us to already set the local flag.
82 #define DBINFO_FCHK(dbp, fn, meta_flags, m_name, dbp_name) { \
83 if ((meta_flags) & (m_name)) \
84 F_SET(dbp, dbp_name); \
86 if (F_ISSET(dbp, dbp_name)) { \
88 "%s: %s specified in dbinfo argument but not set in file", \
96 * Main library interface to the DB access methods.
99 db_open(fname, type, flags, mode, dbenv, dbinfo, dbpp)
110 DB_ENV *envp, t_dbenv;
116 int fd, ftype, need_fileid, restore, ret, retry_cnt, swapped;
117 char *real_name, mbuf[512];
119 /* Validate arguments. */
120 #ifdef HAVE_SPINLOCKS
121 #define OKFLAGS (DB_CREATE | DB_NOMMAP | DB_RDONLY | DB_THREAD | DB_TRUNCATE)
123 #define OKFLAGS (DB_CREATE | DB_NOMMAP | DB_RDONLY | DB_TRUNCATE)
125 if ((ret = __db_fchk(dbenv, "db_open", flags, OKFLAGS)) != 0)
128 /* Initialize for error return. */
133 /* Allocate the DB structure, reference the DB_ENV structure. */
134 if ((dbp = (DB *)calloc(1, sizeof(DB))) == NULL) {
135 __db_err(dbenv, "%s", strerror(ENOMEM));
140 /* Convert the dbinfo flags. */
141 if (dbinfo != NULL) {
144 * We can't check for illegal flags until we know what type
145 * of open we're doing.
147 if (F_ISSET(dbinfo, DB_DELIMITER))
148 F_SET(dbp, DB_RE_DELIMITER);
149 if (F_ISSET(dbinfo, DB_DUP))
150 F_SET(dbp, DB_AM_DUP);
151 if (F_ISSET(dbinfo, DB_FIXEDLEN))
152 F_SET(dbp, DB_RE_FIXEDLEN);
153 if (F_ISSET(dbinfo, DB_PAD))
154 F_SET(dbp, DB_RE_PAD);
155 if (F_ISSET(dbinfo, DB_RECNUM))
156 F_SET(dbp, DB_BT_RECNUM);
157 if (F_ISSET(dbinfo, DB_RENUMBER))
158 F_SET(dbp, DB_RE_RENUMBER);
159 if (F_ISSET(dbinfo, DB_SNAPSHOT))
160 F_SET(dbp, DB_RE_SNAPSHOT);
163 /* Set based on the open(2) flags. */
164 if (LF_ISSET(DB_RDONLY))
165 F_SET(dbp, DB_AM_RDONLY);
167 /* Check threading fields. */
168 if (LF_ISSET(DB_THREAD)) {
170 (db_mutex_t *)malloc(sizeof(db_mutex_t))) == NULL) {
171 __db_err(dbenv, "%s", strerror(ENOMEM));
175 __db_mutex_init(dbp->mutex, 0);
177 F_SET(dbp, DB_AM_THREAD);
181 * Always set the master and initialize the queues, so we can
182 * use these fields without checking the thread bit.
185 LIST_INIT(&dbp->handleq);
186 LIST_INSERT_HEAD(&dbp->handleq, dbp, links);
187 TAILQ_INIT(&dbp->curs_queue);
190 * Set based on the dbenv fields, although no logging or transactions
191 * are possible for temporary files.
193 if (dbp->dbenv != NULL) {
194 if (dbenv->lk_info != NULL)
195 F_SET(dbp, DB_AM_LOCKING);
196 if (fname != NULL && dbenv->lg_info != NULL)
197 F_SET(dbp, DB_AM_LOGGING);
200 /* Set the common fields. */
201 if (dbinfo == NULL) {
203 dbp->db_malloc = NULL;
205 dbp->pgsize = dbinfo->db_pagesize;
206 dbp->db_malloc = dbinfo->db_malloc;
209 /* Fill in the default file mode. */
211 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
213 /* Check if the user wants us to swap byte order. */
215 switch (ret = __db_byteorder(dbenv, dbinfo->db_lorder)) {
219 F_SET(dbp, DB_AM_SWAP);
226 * If we have a file name, try and read the first page, figure out
227 * what type of file it is, and initialize everything we can based
228 * on that file's meta-data page.
231 * We don't actually expect zero-length strings as arguments. We
232 * do the check, permitting them, because scripting languages, e.g.,
233 * the Tcl test suite, doesn't know anything about passing NULL's.
235 if (fname != NULL && fname[0] != '\0') {
236 /* Get the real file name. */
237 if ((ret = __db_appname(dbenv,
238 DB_APP_DATA, NULL, fname, NULL, &real_name)) != 0)
242 * Open the backing file. We need to make sure that multiple
243 * processes attempting to create the file at the same time
244 * are properly ordered so that only one of them creates the
245 * "unique" file id, so we open it O_EXCL and O_CREAT so two
246 * simultaneous attempts to create the region will return
247 * failure in one of the attempts. If we're one of the ones
248 * that fail, we simply retry without the O_CREAT flag, which
249 * will require that the meta-data page exist.
252 open_retry: if (LF_ISSET(DB_CREATE)) {
253 if ((ret = __db_fdopen(real_name, flags | DB_EXCL,
254 OKFLAGS | DB_EXCL, mode, &fd)) != 0)
260 "%s: %s", fname, strerror(ret));
264 if ((ret = __db_fdopen(real_name,
265 flags, OKFLAGS, mode, &fd)) != 0) {
266 __db_err(dbenv, "%s: %s", fname, strerror(ret));
271 * Use the optimum I/O size as the pagesize if a pagesize not
272 * specified. Some filesystems have 64K as their optimum I/O
273 * size, but as that results in impossibly large default cache
274 * sizes, we limit the default pagesize to 16K.
276 if (dbp->pgsize == 0) {
277 if ((ret = __db_stat(dbp->dbenv,
278 real_name, fd, NULL, &io)) != 0)
285 F_SET(dbp, DB_AM_PGDEF);
289 * Try and read the first disk sector -- this code assumes
290 * that the meta-data for all access methods fits in 512
291 * bytes, and that no database will be smaller than that.
293 if ((ret = __db_read(fd, mbuf, sizeof(mbuf), &nr)) != 0)
296 /* The fd is no longer needed. */
297 (void)__db_close(fd);
300 if (nr != sizeof(mbuf)) {
303 "%s: unexpected file format", fname);
307 * The only way we can reach here with the DB_CREATE
308 * flag set is if we created the file. If that's not
309 * the case, then a) someone else created the file
310 * but has not yet written out the meta-data page, or
311 * b) we truncated the file (DB_TRUNCATE) leaving it
312 * zero-length. In the case of a), we want to sleep
313 * and give the file creator some time to write the
314 * metadata page. In the case of b), charge forward.
315 * Note, there is a race in the case of two processes
316 * opening the file with the DB_TRUNCATE flag set at
317 * roughly the same time, and they could theoretically
318 * hurt each other, although it's pretty unlikely.
320 if (retry_cnt++ < 3 &&
321 !LF_ISSET(DB_CREATE | DB_TRUNCATE)) {
325 if (type == DB_UNKNOWN) {
327 "%s: DBTYPE of unknown with empty file",
335 * A found file overrides some user information. We'll check
336 * for possible error conditions based on conflicts between
337 * the file and the user's arguments below.
340 F_CLR(dbp, DB_AM_SWAP);
342 retry: switch (((BTMETA *)mbuf)->magic) {
344 if (type != DB_BTREE &&
345 type != DB_RECNO && type != DB_UNKNOWN)
348 btm = (BTMETA *)mbuf;
349 if (swapped && (ret = __bam_mswap((PAGE *)btm)) != 0)
352 if (btm->version < DB_BTREEOLDVER ||
353 btm->version > DB_BTREEVERSION) {
355 "%s: unsupported btree version number %lu",
356 fname, (u_long)btm->version);
359 dbp->pgsize = btm->pagesize;
360 F_CLR(dbp, DB_AM_PGDEF);
362 if ((ret = __db_fchk(dbenv,
363 "db_open", btm->flags, BTM_MASK)) != 0)
365 DBINFO_FCHK(dbp, "DB_DUP",
366 btm->flags, BTM_DUP, DB_AM_DUP);
367 if (F_ISSET(btm, BTM_RECNO)) {
368 DBINFO_FCHK(dbp, "DB_FIXEDLEN",
369 btm->flags, BTM_FIXEDLEN, DB_RE_FIXEDLEN);
370 DBINFO_FCHK(dbp, "DB_RENUMBER",
371 btm->flags, BTM_RENUMBER, DB_RE_RENUMBER);
374 DBINFO_FCHK(dbp, "DB_RECNUM",
375 btm->flags, BTM_RECNUM, DB_BT_RECNUM);
379 /* Copy the file's unique id. */
381 memcpy(dbp->lock.fileid, btm->uid, DB_FILE_ID_LEN);
384 if (type != DB_HASH && type != DB_UNKNOWN)
387 hashm = (HASHHDR *)mbuf;
388 if (swapped && (ret = __ham_mswap((PAGE *)hashm)) != 0)
391 if (hashm->version < DB_HASHOLDVER ||
392 hashm->version > DB_HASHVERSION) {
394 "%s: unsupported hash version number %lu",
395 fname, hashm->version);
398 dbp->pgsize = hashm->pagesize;
399 F_CLR(dbp, DB_AM_PGDEF);
401 if ((ret = __db_fchk(dbenv,
402 "db_open", hashm->flags, DB_HASH_DUP)) != 0)
404 DBINFO_FCHK(dbp, "DB_DUP",
405 hashm->flags, DB_HASH_DUP, DB_AM_DUP);
408 /* Copy the file's unique id. */
410 memcpy(dbp->lock.fileid, hashm->uid, DB_FILE_ID_LEN);
414 __db_err(dbenv, "unrecognized file type");
417 M_32_SWAP(((BTMETA *)mbuf)->magic);
418 F_SET(dbp, DB_AM_SWAP);
424 fname = real_name = NULL;
426 if (type == DB_UNKNOWN) {
428 "DBTYPE of unknown without existing file");
431 F_SET(dbp, DB_AM_INMEM);
435 * By the time we get here we've either set the type or we're taking
441 * Set the page size to the best value for I/O to this file. Don't
442 * overflow the page offset type. The page size must be db_indx_t
443 * aligned and >= MIN_PAGE_SIZE.
446 * Should we be checking for a page size that's not a multiple of 512?
448 if (dbp->pgsize == 0) {
449 F_SET(dbp, DB_AM_PGDEF);
450 dbp->pgsize = 8 * 1024;
452 if (dbp->pgsize < DB_MIN_PGSIZE ||
453 dbp->pgsize > DB_MAX_PGSIZE ||
454 dbp->pgsize & (sizeof(db_indx_t) - 1)) {
455 __db_err(dbenv, "illegal page size");
460 * Set and/or correct the cache size; must be a multiple of the
463 if (dbinfo == NULL || dbinfo->db_cachesize == 0)
464 cachesize = dbp->pgsize * DB_MINCACHE;
466 cachesize = dbinfo->db_cachesize;
467 if (cachesize & (dbp->pgsize - 1))
468 cachesize += (~cachesize & (dbp->pgsize - 1)) + 1;
469 if (cachesize < dbp->pgsize * DB_MINCACHE)
470 cachesize = dbp->pgsize * DB_MINCACHE;
471 if (cachesize < 20 * 1024)
472 cachesize = 20 * 1024;
476 * If no mpool supplied by the application, attach to a local,
477 * created buffer pool.
480 * If the user has a DB_ENV structure, we have to use a temporary
481 * one so that we don't step on their values. If the user doesn't,
482 * we have to create one, and keep it around until the call to the
483 * memp_close() function. This is all so the mpool functions get
484 * the error stuff right.
486 if (dbenv == NULL || dbenv->mp_info == NULL) {
487 F_SET(dbp, DB_AM_MLOCAL);
491 (DB_ENV *)calloc(sizeof(DB_ENV), 1)) == NULL) {
496 envp = dbp->mp_dbenv;
504 envp->mp_size = cachesize;
505 F_SET(envp, DB_MPOOL_PRIVATE);
506 if ((ret = memp_open(NULL,
507 DB_CREATE, S_IRUSR | S_IWUSR, envp, &dbp->mp)) != 0)
512 dbp->mp = dbenv->mp_info;
514 /* Register DB's pgin/pgout functions. */
515 if ((ret = memp_register(dbp->mp,
516 DB_FTYPE_BTREE, __bam_pgin, __bam_pgout)) != 0)
518 if ((ret = memp_register(dbp->mp,
519 DB_FTYPE_HASH, __ham_pgin, __ham_pgout)) != 0)
523 * If we don't already have one, get a unique file ID. If the file
524 * is a temporary file, then we have to create a unique file ID --
525 * no backing file will be created until the mpool cache is filled
526 * forcing it to go to disk. The created ID must never match any
527 * potential real file ID -- we know it won't because real file IDs
528 * contain a time stamp after the dev/ino pair, and we're simply
529 * storing a 4-byte locker ID.
532 * Store the file id in the locker structure -- we can get it from
533 * there as necessary, and it saves having two copies.
537 memset(dbp->lock.fileid, 0, DB_FILE_ID_LEN);
538 if (F_ISSET(dbp, DB_AM_LOCKING) &&
539 (ret = lock_id(dbenv->lk_info,
540 (u_int32_t *)dbp->lock.fileid)) != 0)
543 if ((ret = __db_fileid(dbenv,
544 real_name, 1, dbp->lock.fileid)) != 0)
547 /* No further use for the real name. */
548 if (real_name != NULL)
553 * Open a backing file in the memory pool.
555 * If we need to process the file's pages on I/O, set the file type.
556 * If it's a hash file, always call pgin and pgout routines. This
557 * means that hash files can never be mapped into process memory. If
558 * it's a btree file and requires swapping, we need to page the file
559 * in and out. This has to be right -- we can't mmap files that are
560 * being paged in and out.
563 ftype = DB_FTYPE_HASH;
565 ftype = F_ISSET(dbp, DB_AM_SWAP) ? DB_FTYPE_BTREE : 0;
566 pginfo.db_pagesize = dbp->pgsize;
567 pginfo.needswap = F_ISSET(dbp, DB_AM_SWAP);
568 pgcookie.data = &pginfo;
569 pgcookie.size = sizeof(DB_PGINFO);
571 if ((ret = memp_fopen(dbp->mp, fname, ftype,
572 F_ISSET(dbp, DB_AM_RDONLY) ? DB_RDONLY : 0, 0, dbp->pgsize,
573 0, &pgcookie, dbp->lock.fileid, &dbp->mpf)) != 0)
576 /* Get a log file id. */
577 if (F_ISSET(dbp, DB_AM_LOGGING) &&
578 (ret = log_register(dbenv->lg_info,
579 dbp, fname, type, &dbp->log_fileid)) != 0)
583 * Get a locker id for this DB, and build the lock cookie: the first
584 * db_pgno_t bytes are the page number, the next N bytes are the file
587 if (F_ISSET(dbp, DB_AM_LOCKING)) {
588 if ((ret = lock_id(dbenv->lk_info, &dbp->locker)) != 0)
590 dbp->lock_dbt.size = sizeof(dbp->lock);
591 dbp->lock_dbt.data = &dbp->lock;
594 /* Call the real open function. */
597 if (dbinfo != NULL && (ret = __db_fchk(dbenv,
598 "db_open", dbinfo->flags, DB_RECNUM | DB_DUP)) != 0)
600 if (dbinfo != NULL && (ret = __db_fcchk(dbenv,
601 "db_open", dbinfo->flags, DB_DUP, DB_RECNUM)) != 0)
603 if ((ret = __bam_open(dbp, type, dbinfo)) != 0)
607 if (dbinfo != NULL && (ret = __db_fchk(dbenv,
608 "db_open", dbinfo->flags, DB_DUP)) != 0)
610 if ((ret = __ham_open(dbp, dbinfo)) != 0)
614 #define DB_INFO_FLAGS \
615 (DB_DELIMITER | DB_FIXEDLEN | DB_PAD | DB_RENUMBER | DB_SNAPSHOT)
616 if (dbinfo != NULL && (ret = __db_fchk(dbenv,
617 "db_open", dbinfo->flags, DB_INFO_FLAGS)) != 0)
619 if ((ret = __ram_open(dbp, type, dbinfo)) != 0)
626 /* Call a local close routine. */
627 dbp->close = db_close;
633 einval: ret = EINVAL;
634 err: /* Close the file descriptor. */
636 (void)__db_close(fd);
638 /* Discard the log file id. */
639 if (dbp->log_fileid != 0)
640 (void)log_unregister(dbenv->lg_info, dbp->log_fileid);
642 /* Close the memory pool file. */
643 if (dbp->mpf != NULL)
644 (void)memp_fclose(dbp->mpf);
646 /* If the memory pool was local, close it. */
647 if (F_ISSET(dbp, DB_AM_MLOCAL) && dbp->mp != NULL)
648 (void)memp_close(dbp->mp);
650 /* If we allocated a DB_ENV, discard it. */
651 if (dbp->mp_dbenv != NULL)
652 FREE(dbp->mp_dbenv, sizeof(DB_ENV));
654 if (real_name != NULL)
657 FREE(dbp, sizeof(DB));
677 /* Sync the underlying file. */
678 if (!LF_ISSET(DB_NOSYNC) &&
679 (t_ret = dbp->sync(dbp, 0)) != 0 && ret == 0)
683 * Call the underlying access method close routine for all the
684 * cursors and handles.
686 for (tdbp = LIST_FIRST(&dbp->handleq);
687 tdbp != NULL; tdbp = LIST_NEXT(tdbp, links)) {
689 while ((dbc = TAILQ_FIRST(&tdbp->curs_queue)) != NULL)
690 if ((t_ret = dbc->c_close(dbc)) != 0 && ret == 0)
693 switch (tdbp->type) {
695 if ((t_ret = __bam_close(tdbp)) != 0 && ret == 0)
699 if ((t_ret = __ham_close(tdbp)) != 0 && ret == 0)
703 if ((t_ret = __ram_close(tdbp)) != 0 && ret == 0)
712 /* Sync the memory pool. */
713 if ((t_ret = memp_fsync(dbp->mpf)) != 0 && ret == 0)
716 /* Close the memory pool file. */
717 if ((t_ret = memp_fclose(dbp->mpf)) != 0 && ret == 0)
720 /* If the memory pool was local, close it. */
721 if (F_ISSET(dbp, DB_AM_MLOCAL) &&
722 (t_ret = memp_close(dbp->mp)) != 0 && ret == 0)
725 /* Discard the mutex. */
726 if (dbp->mutex != NULL)
727 FREE(dbp->mutex, sizeof(db_mutex_t));
729 /* Discard the log file id. */
730 if (F_ISSET(dbp, DB_AM_LOGGING))
731 (void)log_unregister(dbp->dbenv->lg_info, dbp->log_fileid);
733 /* Discard the lock cookie for all handles. */
734 for (tdbp = LIST_FIRST(&dbp->handleq);
735 tdbp != NULL; tdbp = LIST_NEXT(tdbp, links))
736 if (F_ISSET(tdbp, DB_AM_LOCKING)) {
741 * If we're running tests, display any locks currently
742 * held. It's possible that some applications may hold
743 * locks for long periods, e.g., conference room locks,
744 * but the DB tests should never close holding locks.
746 request.op = DB_LOCK_DUMP;
747 if ((t_ret = lock_vec(tdbp->dbenv->lk_info,
748 tdbp->locker, 0, &request, 1, NULL)) != 0 &&
754 /* If we allocated a DB_ENV, discard it. */
755 if (dbp->mp_dbenv != NULL)
756 FREE(dbp->mp_dbenv, sizeof(DB_ENV));
758 /* Free all of the DB's. */
759 LIST_REMOVE(dbp, links);
760 while ((tdbp = LIST_FIRST(&dbp->handleq)) != NULL) {
761 LIST_REMOVE(tdbp, links);
762 FREE(tdbp, sizeof(*tdbp));
764 FREE(dbp, sizeof(*dbp));
771 * Return a file descriptor for flock'ing.
778 /* In-memory database can't have a file descriptor. */
779 if (F_ISSET(dbp, DB_AM_INMEM))
784 * Truly spectacular layering violation. As we don't open the
785 * underlying file until we need it, it may not be initialized.
787 if ((*fdp = dbp->mpf->fd) == -1)
794 * Error when unable to retrieve a specified page.
796 * PUBLIC: int __db_pgerr __P((DB *, db_pgno_t));
799 __db_pgerr(dbp, pgno)
804 "unable to create/retrieve page %lu", (u_long)pgno);
805 return (__db_panic(dbp));
810 * Error when a page has the wrong format.
812 * PUBLIC: int __db_pgfmt __P((DB *, db_pgno_t));
815 __db_pgfmt(dbp, pgno)
820 "page %lu: illegal page type or format", (u_long)pgno);
821 return (__db_panic(dbp));