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.44 (Sleepycat) 10/25/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)
129 LF_ISSET(DB_THREAD) && !F_ISSET(dbenv, DB_ENV_THREAD)) {
130 __db_err(dbenv, "environment not created using DB_THREAD");
134 /* Initialize for error return. */
139 /* Allocate the DB structure, reference the DB_ENV structure. */
140 if ((dbp = (DB *)__db_calloc(1, sizeof(DB))) == NULL) {
141 __db_err(dbenv, "%s", strerror(ENOMEM));
146 /* Convert the db_open(3) flags. */
147 if (LF_ISSET(DB_RDONLY))
148 F_SET(dbp, DB_AM_RDONLY);
149 if (LF_ISSET(DB_THREAD))
150 F_SET(dbp, DB_AM_THREAD);
152 /* Convert the dbinfo structure flags. */
153 if (dbinfo != NULL) {
156 * We can't check for illegal flags until we know what type
157 * of open we're doing.
159 if (F_ISSET(dbinfo, DB_DELIMITER))
160 F_SET(dbp, DB_RE_DELIMITER);
161 if (F_ISSET(dbinfo, DB_DUP))
162 F_SET(dbp, DB_AM_DUP);
163 if (F_ISSET(dbinfo, DB_FIXEDLEN))
164 F_SET(dbp, DB_RE_FIXEDLEN);
165 if (F_ISSET(dbinfo, DB_PAD))
166 F_SET(dbp, DB_RE_PAD);
167 if (F_ISSET(dbinfo, DB_RECNUM))
168 F_SET(dbp, DB_BT_RECNUM);
169 if (F_ISSET(dbinfo, DB_RENUMBER))
170 F_SET(dbp, DB_RE_RENUMBER);
171 if (F_ISSET(dbinfo, DB_SNAPSHOT))
172 F_SET(dbp, DB_RE_SNAPSHOT);
176 * Always set the master and initialize the queues, so we can
177 * use these fields without checking the thread bit.
180 LIST_INIT(&dbp->handleq);
181 LIST_INSERT_HEAD(&dbp->handleq, dbp, links);
182 TAILQ_INIT(&dbp->curs_queue);
185 * Set based on the dbenv fields, although no logging or transactions
186 * are possible for temporary files.
189 if (dbenv->lk_info != NULL)
190 F_SET(dbp, DB_AM_LOCKING);
191 if (fname != NULL && dbenv->lg_info != NULL)
192 F_SET(dbp, DB_AM_LOGGING);
195 /* Set the common fields. */
196 if (dbinfo == NULL) {
198 dbp->db_malloc = NULL;
200 dbp->pgsize = dbinfo->db_pagesize;
201 dbp->db_malloc = dbinfo->db_malloc;
204 /* Fill in the default file mode. */
206 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
208 /* Check if the user wants us to swap byte order. */
210 switch (ret = __db_byteorder(dbenv, dbinfo->db_lorder)) {
214 F_SET(dbp, DB_AM_SWAP);
221 * If we have a file name, try and read the first page, figure out
222 * what type of file it is, and initialize everything we can based
223 * on that file's meta-data page.
226 * We don't actually expect zero-length strings as arguments. We
227 * do the check, permitting them, because scripting languages, e.g.,
228 * the Tcl test suite, doesn't know anything about passing NULL's.
230 if (fname != NULL && fname[0] != '\0') {
231 /* Get the real file name. */
232 if ((ret = __db_appname(dbenv,
233 DB_APP_DATA, NULL, fname, NULL, &real_name)) != 0)
237 * Open the backing file. We need to make sure that multiple
238 * processes attempting to create the file at the same time
239 * are properly ordered so that only one of them creates the
240 * "unique" file id, so we open it O_EXCL and O_CREAT so two
241 * simultaneous attempts to create the region will return
242 * failure in one of the attempts. If we're one of the ones
243 * that fail, we simply retry without the O_CREAT flag, which
244 * will require that the meta-data page exist.
247 open_retry: if (LF_ISSET(DB_CREATE)) {
248 if ((ret = __db_open(real_name, flags | DB_EXCL,
249 OKFLAGS | DB_EXCL, mode, &fd)) != 0)
255 "%s: %s", fname, strerror(ret));
259 if ((ret = __db_open(real_name,
260 flags, OKFLAGS, mode, &fd)) != 0) {
261 __db_err(dbenv, "%s: %s", fname, strerror(ret));
266 * Use the optimum I/O size as the pagesize if a pagesize not
267 * specified. Some filesystems have 64K as their optimum I/O
268 * size, but as that results in impossibly large default cache
269 * sizes, we limit the default pagesize to 16K.
271 if (dbp->pgsize == 0) {
273 __db_ioinfo(real_name, fd, NULL, &io)) != 0) {
275 "%s: %s", real_name, strerror(ret));
283 F_SET(dbp, DB_AM_PGDEF);
287 * Try and read the first disk sector -- this code assumes
288 * that the meta-data for all access methods fits in 512
289 * bytes, and that no database will be smaller than that.
291 if ((ret = __db_read(fd, mbuf, sizeof(mbuf), &nr)) != 0)
294 /* The fd is no longer needed. */
295 (void)__db_close(fd);
298 if (nr != sizeof(mbuf)) {
301 "%s: unexpected file format", fname);
305 * The only way we can reach here with the DB_CREATE
306 * flag set is if we created the file. If that's not
307 * the case, then a) someone else created the file
308 * but has not yet written out the meta-data page, or
309 * b) we truncated the file (DB_TRUNCATE) leaving it
310 * zero-length. In the case of a), we want to sleep
311 * and give the file creator some time to write the
312 * metadata page. In the case of b), charge forward.
313 * Note, there is a race in the case of two processes
314 * opening the file with the DB_TRUNCATE flag set at
315 * roughly the same time, and they could theoretically
316 * hurt each other, although it's pretty unlikely.
318 if (retry_cnt++ < 3 &&
319 !LF_ISSET(DB_CREATE | DB_TRUNCATE)) {
323 if (type == DB_UNKNOWN) {
325 "%s: DBTYPE of unknown with empty file",
333 * A found file overrides some user information. We'll check
334 * for possible error conditions based on conflicts between
335 * the file and the user's arguments below.
338 F_CLR(dbp, DB_AM_SWAP);
340 retry: switch (((BTMETA *)mbuf)->magic) {
342 if (type != DB_BTREE &&
343 type != DB_RECNO && type != DB_UNKNOWN)
346 btm = (BTMETA *)mbuf;
347 if (swapped && (ret = __bam_mswap((PAGE *)btm)) != 0)
350 if (btm->version < DB_BTREEOLDVER ||
351 btm->version > DB_BTREEVERSION) {
353 "%s: unsupported btree version number %lu",
354 fname, (u_long)btm->version);
357 dbp->pgsize = btm->pagesize;
358 F_CLR(dbp, DB_AM_PGDEF);
360 if ((ret = __db_fchk(dbenv,
361 "db_open", btm->flags, BTM_MASK)) != 0)
363 DBINFO_FCHK(dbp, "DB_DUP",
364 btm->flags, BTM_DUP, DB_AM_DUP);
365 if (F_ISSET(btm, BTM_RECNO)) {
366 DBINFO_FCHK(dbp, "DB_FIXEDLEN",
367 btm->flags, BTM_FIXEDLEN, DB_RE_FIXEDLEN);
368 DBINFO_FCHK(dbp, "DB_RENUMBER",
369 btm->flags, BTM_RENUMBER, DB_RE_RENUMBER);
372 DBINFO_FCHK(dbp, "DB_RECNUM",
373 btm->flags, BTM_RECNUM, DB_BT_RECNUM);
377 /* Copy the file's unique id. */
379 memcpy(dbp->lock.fileid, btm->uid, DB_FILE_ID_LEN);
382 if (type != DB_HASH && type != DB_UNKNOWN)
385 hashm = (HASHHDR *)mbuf;
386 if (swapped && (ret = __ham_mswap((PAGE *)hashm)) != 0)
389 if (hashm->version < DB_HASHOLDVER ||
390 hashm->version > DB_HASHVERSION) {
392 "%s: unsupported hash version number %lu",
393 fname, hashm->version);
396 dbp->pgsize = hashm->pagesize;
397 F_CLR(dbp, DB_AM_PGDEF);
399 if ((ret = __db_fchk(dbenv,
400 "db_open", hashm->flags, DB_HASH_DUP)) != 0)
402 DBINFO_FCHK(dbp, "DB_DUP",
403 hashm->flags, DB_HASH_DUP, DB_AM_DUP);
406 /* Copy the file's unique id. */
408 memcpy(dbp->lock.fileid, hashm->uid, DB_FILE_ID_LEN);
412 __db_err(dbenv, "unrecognized file type");
415 M_32_SWAP(((BTMETA *)mbuf)->magic);
416 F_SET(dbp, DB_AM_SWAP);
422 fname = real_name = NULL;
424 if (type == DB_UNKNOWN) {
426 "DBTYPE of unknown without existing file");
429 F_SET(dbp, DB_AM_INMEM);
433 * By the time we get here we've either set the type or we're taking
439 * Set the page size to the best value for I/O to this file. Don't
440 * overflow the page offset type. The page size must be db_indx_t
441 * aligned and >= MIN_PAGE_SIZE.
444 * Should we be checking for a page size that's not a multiple of 512?
446 if (dbp->pgsize == 0) {
447 F_SET(dbp, DB_AM_PGDEF);
448 dbp->pgsize = 8 * 1024;
450 if (dbp->pgsize < DB_MIN_PGSIZE ||
451 dbp->pgsize > DB_MAX_PGSIZE ||
452 dbp->pgsize & (sizeof(db_indx_t) - 1)) {
453 __db_err(dbenv, "illegal page size");
458 * Set and/or correct the cache size; must be a multiple of the
461 if (dbinfo == NULL || dbinfo->db_cachesize == 0)
462 cachesize = dbp->pgsize * DB_MINCACHE;
464 cachesize = dbinfo->db_cachesize;
465 if (cachesize & (dbp->pgsize - 1))
466 cachesize += (~cachesize & (dbp->pgsize - 1)) + 1;
467 if (cachesize < dbp->pgsize * DB_MINCACHE)
468 cachesize = dbp->pgsize * DB_MINCACHE;
469 if (cachesize < 20 * 1024)
470 cachesize = 20 * 1024;
474 * If no mpool supplied by the application, attach to a local,
475 * created buffer pool.
478 * If the user has a DB_ENV structure, we have to use a temporary
479 * one so that we don't step on their values. If the user doesn't,
480 * we have to create one, and keep it around until the call to the
481 * memp_close() function. This is all so the mpool functions get
482 * the error stuff right.
484 if (dbenv == NULL || dbenv->mp_info == NULL) {
485 F_SET(dbp, DB_AM_MLOCAL);
489 (DB_ENV *)__db_calloc(sizeof(DB_ENV), 1)) == NULL) {
494 envp = dbp->mp_dbenv;
502 envp->mp_size = cachesize;
503 if ((ret = memp_open(NULL, DB_CREATE | DB_MPOOL_PRIVATE |
504 (F_ISSET(dbp, DB_AM_THREAD) ? DB_THREAD : 0),
505 S_IRUSR | S_IWUSR, envp, &dbp->mp)) != 0)
510 dbp->mp = dbenv->mp_info;
512 /* Register DB's pgin/pgout functions. */
513 if ((ret = memp_register(dbp->mp,
514 DB_FTYPE_BTREE, __bam_pgin, __bam_pgout)) != 0)
516 if ((ret = memp_register(dbp->mp,
517 DB_FTYPE_HASH, __ham_pgin, __ham_pgout)) != 0)
521 * If we don't already have one, get a unique file ID. If the file
522 * is a temporary file, then we have to create a unique file ID --
523 * no backing file will be created until the mpool cache is filled
524 * forcing it to go to disk. The created ID must never match any
525 * potential real file ID -- we know it won't because real file IDs
526 * contain a time stamp after the dev/ino pair, and we're simply
527 * storing a 4-byte locker ID.
530 * Store the file id in the locker structure -- we can get it from
531 * there as necessary, and it saves having two copies.
535 memset(dbp->lock.fileid, 0, DB_FILE_ID_LEN);
536 if (F_ISSET(dbp, DB_AM_LOCKING) &&
537 (ret = lock_id(dbenv->lk_info,
538 (u_int32_t *)dbp->lock.fileid)) != 0)
541 if ((ret = __db_fileid(dbenv,
542 real_name, 1, dbp->lock.fileid)) != 0)
545 /* No further use for the real name. */
546 if (real_name != NULL)
551 * Open a backing file in the memory pool.
553 * If we need to process the file's pages on I/O, set the file type.
554 * If it's a hash file, always call pgin and pgout routines. This
555 * means that hash files can never be mapped into process memory. If
556 * it's a btree file and requires swapping, we need to page the file
557 * in and out. This has to be right -- we can't mmap files that are
558 * being paged in and out.
561 ftype = DB_FTYPE_HASH;
563 ftype = F_ISSET(dbp, DB_AM_SWAP) ? DB_FTYPE_BTREE : 0;
564 pginfo.db_pagesize = dbp->pgsize;
565 pginfo.needswap = F_ISSET(dbp, DB_AM_SWAP);
566 pgcookie.data = &pginfo;
567 pgcookie.size = sizeof(DB_PGINFO);
569 if ((ret = memp_fopen(dbp->mp, fname, ftype,
570 F_ISSET(dbp, DB_AM_RDONLY) ? DB_RDONLY : 0, 0, dbp->pgsize,
571 0, &pgcookie, dbp->lock.fileid, &dbp->mpf)) != 0)
576 * Truly spectacular layering violation. We need a per-thread mutex
577 * that lives in shared memory (thanks, HP-UX!) and so we acquire a
578 * pointer to the mpool one.
580 if (F_ISSET(dbp, DB_AM_THREAD))
581 dbp->mutexp = dbp->mpf->mutexp;
583 /* Get a log file id. */
584 if (F_ISSET(dbp, DB_AM_LOGGING) &&
585 (ret = log_register(dbenv->lg_info,
586 dbp, fname, type, &dbp->log_fileid)) != 0)
590 * Get a locker id for this DB, and build the lock cookie: the first
591 * db_pgno_t bytes are the page number, the next N bytes are the file
594 if (F_ISSET(dbp, DB_AM_LOCKING)) {
595 if ((ret = lock_id(dbenv->lk_info, &dbp->locker)) != 0)
597 dbp->lock_dbt.size = sizeof(dbp->lock);
598 dbp->lock_dbt.data = &dbp->lock;
601 /* Call the real open function. */
604 if (dbinfo != NULL && (ret = __db_fchk(dbenv,
605 "db_open", dbinfo->flags, DB_RECNUM | DB_DUP)) != 0)
607 if (dbinfo != NULL && (ret = __db_fcchk(dbenv,
608 "db_open", dbinfo->flags, DB_DUP, DB_RECNUM)) != 0)
610 if ((ret = __bam_open(dbp, type, dbinfo)) != 0)
614 if (dbinfo != NULL && (ret = __db_fchk(dbenv,
615 "db_open", dbinfo->flags, DB_DUP)) != 0)
617 if ((ret = __ham_open(dbp, dbinfo)) != 0)
621 #define DB_INFO_FLAGS \
622 (DB_DELIMITER | DB_FIXEDLEN | DB_PAD | DB_RENUMBER | DB_SNAPSHOT)
623 if (dbinfo != NULL && (ret = __db_fchk(dbenv,
624 "db_open", dbinfo->flags, DB_INFO_FLAGS)) != 0)
626 if ((ret = __ram_open(dbp, type, dbinfo)) != 0)
633 /* Call a local close routine. */
634 dbp->close = db_close;
640 einval: ret = EINVAL;
641 err: /* Close the file descriptor. */
643 (void)__db_close(fd);
645 /* Discard the log file id. */
646 if (dbp->log_fileid != 0)
647 (void)log_unregister(dbenv->lg_info, dbp->log_fileid);
649 /* Close the memory pool file. */
650 if (dbp->mpf != NULL)
651 (void)memp_fclose(dbp->mpf);
653 /* If the memory pool was local, close it. */
654 if (F_ISSET(dbp, DB_AM_MLOCAL) && dbp->mp != NULL)
655 (void)memp_close(dbp->mp);
657 /* If we allocated a DB_ENV, discard it. */
658 if (dbp->mp_dbenv != NULL)
659 FREE(dbp->mp_dbenv, sizeof(DB_ENV));
661 if (real_name != NULL)
664 FREE(dbp, sizeof(DB));
682 /* Validate arguments. */
683 if ((ret = __db_fchk(dbp->dbenv, "db_close", flags, DB_NOSYNC)) != 0)
686 /* Sync the underlying file. */
687 if (!LF_ISSET(DB_NOSYNC) &&
688 (t_ret = dbp->sync(dbp, 0)) != 0 && ret == 0)
692 * Call the underlying access method close routine for all the
693 * cursors and handles.
695 for (tdbp = LIST_FIRST(&dbp->handleq);
696 tdbp != NULL; tdbp = LIST_NEXT(tdbp, links)) {
697 while ((dbc = TAILQ_FIRST(&tdbp->curs_queue)) != NULL)
698 switch (tdbp->type) {
701 __bam_c_iclose(tdbp, dbc)) != 0 && ret == 0)
706 __ham_c_iclose(tdbp, dbc)) != 0 && ret == 0)
711 __ram_c_iclose(tdbp, dbc)) != 0 && ret == 0)
718 switch (tdbp->type) {
720 if ((t_ret = __bam_close(tdbp)) != 0 && ret == 0)
724 if ((t_ret = __ham_close(tdbp)) != 0 && ret == 0)
728 if ((t_ret = __ram_close(tdbp)) != 0 && ret == 0)
736 /* Sync the memory pool. */
737 if ((t_ret = memp_fsync(dbp->mpf)) != 0 &&
738 t_ret != DB_INCOMPLETE && ret == 0)
741 /* Close the memory pool file. */
742 if ((t_ret = memp_fclose(dbp->mpf)) != 0 && ret == 0)
745 /* If the memory pool was local, close it. */
746 if (F_ISSET(dbp, DB_AM_MLOCAL) &&
747 (t_ret = memp_close(dbp->mp)) != 0 && ret == 0)
750 /* Discard the log file id. */
751 if (F_ISSET(dbp, DB_AM_LOGGING))
752 (void)log_unregister(dbp->dbenv->lg_info, dbp->log_fileid);
754 /* Discard the lock cookie for all handles. */
755 for (tdbp = LIST_FIRST(&dbp->handleq);
756 tdbp != NULL; tdbp = LIST_NEXT(tdbp, links))
757 if (F_ISSET(tdbp, DB_AM_LOCKING)) {
762 * If we're running tests, display any locks currently
763 * held. It's possible that some applications may hold
764 * locks for long periods, e.g., conference room locks,
765 * but the DB tests should never close holding locks.
767 request.op = DB_LOCK_DUMP;
768 if ((t_ret = lock_vec(tdbp->dbenv->lk_info,
769 tdbp->locker, 0, &request, 1, NULL)) != 0 &&
775 /* If we allocated a DB_ENV, discard it. */
776 if (dbp->mp_dbenv != NULL)
777 FREE(dbp->mp_dbenv, sizeof(DB_ENV));
779 /* Free all of the DB's. */
780 LIST_REMOVE(dbp, links);
781 while ((tdbp = LIST_FIRST(&dbp->handleq)) != NULL) {
782 LIST_REMOVE(tdbp, links);
783 FREE(tdbp, sizeof(*tdbp));
785 FREE(dbp, sizeof(*dbp));
792 * Return a file descriptor for flock'ing.
799 /* In-memory database can't have a file descriptor. */
800 if (F_ISSET(dbp, DB_AM_INMEM))
805 * Truly spectacular layering violation. As we don't open the
806 * underlying file until we need it, it may not be initialized.
808 if ((*fdp = dbp->mpf->fd) == -1)
815 * Error when unable to retrieve a specified page.
817 * PUBLIC: int __db_pgerr __P((DB *, db_pgno_t));
820 __db_pgerr(dbp, pgno)
825 "unable to create/retrieve page %lu", (u_long)pgno);
826 return (__db_panic(dbp));
831 * Error when a page has the wrong format.
833 * PUBLIC: int __db_pgfmt __P((DB *, db_pgno_t));
836 __db_pgfmt(dbp, pgno)
841 "page %lu: illegal page type or format", (u_long)pgno);
842 return (__db_panic(dbp));