2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2012 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
60 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
61 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
64 #if defined(__APPLE__) || defined (BSD)
65 # define MDB_USE_POSIX_SEM 1
66 # define MDB_FDATASYNC fsync
67 #elif defined(ANDROID)
68 # define MDB_FDATASYNC fsync
73 #ifdef MDB_USE_POSIX_SEM
74 #include <semaphore.h>
79 #include <valgrind/memcheck.h>
80 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
81 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
82 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
83 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
84 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
86 #define VGMEMP_CREATE(h,r,z)
87 #define VGMEMP_ALLOC(h,a,s)
88 #define VGMEMP_FREE(h,a)
89 #define VGMEMP_DESTROY(h)
90 #define VGMEMP_DEFINED(a,s)
94 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
95 /* Solaris just defines one or the other */
96 # define LITTLE_ENDIAN 1234
97 # define BIG_ENDIAN 4321
98 # ifdef _LITTLE_ENDIAN
99 # define BYTE_ORDER LITTLE_ENDIAN
101 # define BYTE_ORDER BIG_ENDIAN
104 # define BYTE_ORDER __BYTE_ORDER
108 #ifndef LITTLE_ENDIAN
109 #define LITTLE_ENDIAN __LITTLE_ENDIAN
112 #define BIG_ENDIAN __BIG_ENDIAN
115 #if defined(__i386) || defined(__x86_64)
116 #define MISALIGNED_OK 1
122 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
123 # error "Unknown or unsupported endianness (BYTE_ORDER)"
124 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
125 # error "Two's complement, reasonably sized integer types, please"
128 /** @defgroup internal MDB Internals
131 /** @defgroup compat Windows Compatibility Macros
132 * A bunch of macros to minimize the amount of platform-specific ifdefs
133 * needed throughout the rest of the code. When the features this library
134 * needs are similar enough to POSIX to be hidden in a one-or-two line
135 * replacement, this macro approach is used.
139 #define pthread_t DWORD
140 #define pthread_mutex_t HANDLE
141 #define pthread_key_t DWORD
142 #define pthread_self() GetCurrentThreadId()
143 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
144 #define pthread_key_delete(x) TlsFree(x)
145 #define pthread_getspecific(x) TlsGetValue(x)
146 #define pthread_setspecific(x,y) TlsSetValue(x,y)
147 #define pthread_mutex_unlock(x) ReleaseMutex(x)
148 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
149 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
150 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
151 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
152 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
153 #define getpid() GetCurrentProcessId()
154 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
155 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
156 #define ErrCode() GetLastError()
157 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
158 #define close(fd) CloseHandle(fd)
159 #define munmap(ptr,len) UnmapViewOfFile(ptr)
162 #ifdef MDB_USE_POSIX_SEM
164 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
165 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
166 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
167 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
170 mdb_sem_wait(sem_t *sem)
173 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
178 /** Lock the reader mutex.
180 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
181 /** Unlock the reader mutex.
183 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
185 /** Lock the writer mutex.
186 * Only a single write transaction is allowed at a time. Other writers
187 * will block waiting for this mutex.
189 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
190 /** Unlock the writer mutex.
192 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
193 #endif /* MDB_USE_POSIX_SEM */
195 /** Get the error code for the last failed system function.
197 #define ErrCode() errno
199 /** An abstraction for a file handle.
200 * On POSIX systems file handles are small integers. On Windows
201 * they're opaque pointers.
205 /** A value for an invalid file handle.
206 * Mainly used to initialize file variables and signify that they are
209 #define INVALID_HANDLE_VALUE (-1)
211 /** Get the size of a memory page for the system.
212 * This is the basic size that the platform's memory manager uses, and is
213 * fundamental to the use of memory-mapped files.
215 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
218 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
221 #define MNAME_LEN (sizeof(pthread_mutex_t))
227 /** A flag for opening a file and requesting synchronous data writes.
228 * This is only used when writing a meta page. It's not strictly needed;
229 * we could just do a normal write and then immediately perform a flush.
230 * But if this flag is available it saves us an extra system call.
232 * @note If O_DSYNC is undefined but exists in /usr/include,
233 * preferably set some compiler flag to get the definition.
234 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
237 # define MDB_DSYNC O_DSYNC
241 /** Function for flushing the data of a file. Define this to fsync
242 * if fdatasync() is not supported.
244 #ifndef MDB_FDATASYNC
245 # define MDB_FDATASYNC fdatasync
249 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
260 /** A page number in the database.
261 * Note that 64 bit page numbers are overkill, since pages themselves
262 * already represent 12-13 bits of addressable memory, and the OS will
263 * always limit applications to a maximum of 63 bits of address space.
265 * @note In the #MDB_node structure, we only store 48 bits of this value,
266 * which thus limits us to only 60 bits of addressable data.
268 typedef MDB_ID pgno_t;
270 /** A transaction ID.
271 * See struct MDB_txn.mt_txnid for details.
273 typedef MDB_ID txnid_t;
275 /** @defgroup debug Debug Macros
279 /** Enable debug output.
280 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
281 * read from and written to the database (used for free space management).
286 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
287 # define DPRINTF (void) /* Vararg macros may be unsupported */
289 static int mdb_debug;
290 static txnid_t mdb_debug_start;
292 /** Print a debug message with printf formatting. */
293 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
294 ((void) ((mdb_debug) && \
295 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
297 # define DPRINTF(fmt, ...) ((void) 0)
299 /** Print a debug string.
300 * The string is printed literally, with no format processing.
302 #define DPUTS(arg) DPRINTF("%s", arg)
305 /** A default memory page size.
306 * The actual size is platform-dependent, but we use this for
307 * boot-strapping. We probably should not be using this any more.
308 * The #GET_PAGESIZE() macro is used to get the actual size.
310 * Note that we don't currently support Huge pages. On Linux,
311 * regular data files cannot use Huge pages, and in general
312 * Huge pages aren't actually pageable. We rely on the OS
313 * demand-pager to read our data and page it out when memory
314 * pressure from other processes is high. So until OSs have
315 * actual paging support for Huge pages, they're not viable.
317 #define MDB_PAGESIZE 4096
319 /** The minimum number of keys required in a database page.
320 * Setting this to a larger value will place a smaller bound on the
321 * maximum size of a data item. Data items larger than this size will
322 * be pushed into overflow pages instead of being stored directly in
323 * the B-tree node. This value used to default to 4. With a page size
324 * of 4096 bytes that meant that any item larger than 1024 bytes would
325 * go into an overflow page. That also meant that on average 2-3KB of
326 * each overflow page was wasted space. The value cannot be lower than
327 * 2 because then there would no longer be a tree structure. With this
328 * value, items larger than 2KB will go into overflow pages, and on
329 * average only 1KB will be wasted.
331 #define MDB_MINKEYS 2
333 /** A stamp that identifies a file as an MDB file.
334 * There's nothing special about this value other than that it is easily
335 * recognizable, and it will reflect any byte order mismatches.
337 #define MDB_MAGIC 0xBEEFC0DE
339 /** The version number for a database's file format. */
340 #define MDB_VERSION 1
342 /** The maximum size of a key in the database.
343 * While data items have essentially unbounded size, we require that
344 * keys all fit onto a regular page. This limit could be raised a bit
345 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
347 #define MAXKEYSIZE 511
352 * This is used for printing a hex dump of a key's contents.
354 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
355 /** Display a key in hex.
357 * Invoke a function to display a key in hex.
359 #define DKEY(x) mdb_dkey(x, kbuf)
361 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
365 /** An invalid page number.
366 * Mainly used to denote an empty tree.
368 #define P_INVALID (~(pgno_t)0)
370 /** Test if a flag \b f is set in a flag word \b w. */
371 #define F_ISSET(w, f) (((w) & (f)) == (f))
373 /** Used for offsets within a single page.
374 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
377 typedef uint16_t indx_t;
379 /** Default size of memory map.
380 * This is certainly too small for any actual applications. Apps should always set
381 * the size explicitly using #mdb_env_set_mapsize().
383 #define DEFAULT_MAPSIZE 1048576
385 /** @defgroup readers Reader Lock Table
386 * Readers don't acquire any locks for their data access. Instead, they
387 * simply record their transaction ID in the reader table. The reader
388 * mutex is needed just to find an empty slot in the reader table. The
389 * slot's address is saved in thread-specific data so that subsequent read
390 * transactions started by the same thread need no further locking to proceed.
392 * Since the database uses multi-version concurrency control, readers don't
393 * actually need any locking. This table is used to keep track of which
394 * readers are using data from which old transactions, so that we'll know
395 * when a particular old transaction is no longer in use. Old transactions
396 * that have discarded any data pages can then have those pages reclaimed
397 * for use by a later write transaction.
399 * The lock table is constructed such that reader slots are aligned with the
400 * processor's cache line size. Any slot is only ever used by one thread.
401 * This alignment guarantees that there will be no contention or cache
402 * thrashing as threads update their own slot info, and also eliminates
403 * any need for locking when accessing a slot.
405 * A writer thread will scan every slot in the table to determine the oldest
406 * outstanding reader transaction. Any freed pages older than this will be
407 * reclaimed by the writer. The writer doesn't use any locks when scanning
408 * this table. This means that there's no guarantee that the writer will
409 * see the most up-to-date reader info, but that's not required for correct
410 * operation - all we need is to know the upper bound on the oldest reader,
411 * we don't care at all about the newest reader. So the only consequence of
412 * reading stale information here is that old pages might hang around a
413 * while longer before being reclaimed. That's actually good anyway, because
414 * the longer we delay reclaiming old pages, the more likely it is that a
415 * string of contiguous pages can be found after coalescing old pages from
416 * many old transactions together.
418 * @todo We don't actually do such coalescing yet, we grab pages from one
419 * old transaction at a time.
422 /** Number of slots in the reader table.
423 * This value was chosen somewhat arbitrarily. 126 readers plus a
424 * couple mutexes fit exactly into 8KB on my development machine.
425 * Applications should set the table size using #mdb_env_set_maxreaders().
427 #define DEFAULT_READERS 126
429 /** The size of a CPU cache line in bytes. We want our lock structures
430 * aligned to this size to avoid false cache line sharing in the
432 * This value works for most CPUs. For Itanium this should be 128.
438 /** The information we store in a single slot of the reader table.
439 * In addition to a transaction ID, we also record the process and
440 * thread ID that owns a slot, so that we can detect stale information,
441 * e.g. threads or processes that went away without cleaning up.
442 * @note We currently don't check for stale records. We simply re-init
443 * the table when we know that we're the only process opening the
446 typedef struct MDB_rxbody {
447 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
448 * Multiple readers that start at the same time will probably have the
449 * same ID here. Again, it's not important to exclude them from
450 * anything; all we need to know is which version of the DB they
451 * started from so we can avoid overwriting any data used in that
452 * particular version.
455 /** The process ID of the process owning this reader txn. */
457 /** The thread ID of the thread owning this txn. */
461 /** The actual reader record, with cacheline padding. */
462 typedef struct MDB_reader {
465 /** shorthand for mrb_txnid */
466 #define mr_txnid mru.mrx.mrb_txnid
467 #define mr_pid mru.mrx.mrb_pid
468 #define mr_tid mru.mrx.mrb_tid
469 /** cache line alignment */
470 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
474 /** The header for the reader table.
475 * The table resides in a memory-mapped file. (This is a different file
476 * than is used for the main database.)
478 * For POSIX the actual mutexes reside in the shared memory of this
479 * mapped file. On Windows, mutexes are named objects allocated by the
480 * kernel; we store the mutex names in this mapped file so that other
481 * processes can grab them. This same approach is also used on
482 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
483 * process-shared POSIX mutexes. For these cases where a named object
484 * is used, the object name is derived from a 64 bit FNV hash of the
485 * environment pathname. As such, naming collisions are extremely
486 * unlikely. If a collision occurs, the results are unpredictable.
488 typedef struct MDB_txbody {
489 /** Stamp identifying this as an MDB file. It must be set
492 /** Version number of this lock file. Must be set to #MDB_VERSION. */
493 uint32_t mtb_version;
494 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
495 char mtb_rmname[MNAME_LEN];
497 /** Mutex protecting access to this table.
498 * This is the reader lock that #LOCK_MUTEX_R acquires.
500 pthread_mutex_t mtb_mutex;
502 /** The ID of the last transaction committed to the database.
503 * This is recorded here only for convenience; the value can always
504 * be determined by reading the main database meta pages.
507 /** The number of slots that have been used in the reader table.
508 * This always records the maximum count, it is not decremented
509 * when readers release their slots.
511 unsigned mtb_numreaders;
514 /** The actual reader table definition. */
515 typedef struct MDB_txninfo {
518 #define mti_magic mt1.mtb.mtb_magic
519 #define mti_version mt1.mtb.mtb_version
520 #define mti_mutex mt1.mtb.mtb_mutex
521 #define mti_rmname mt1.mtb.mtb_rmname
522 #define mti_txnid mt1.mtb.mtb_txnid
523 #define mti_numreaders mt1.mtb.mtb_numreaders
524 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
527 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
528 char mt2_wmname[MNAME_LEN];
529 #define mti_wmname mt2.mt2_wmname
531 pthread_mutex_t mt2_wmutex;
532 #define mti_wmutex mt2.mt2_wmutex
534 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
536 MDB_reader mti_readers[1];
540 /** Common header for all page types.
541 * Overflow records occupy a number of contiguous pages with no
542 * headers on any page after the first.
544 typedef struct MDB_page {
545 #define mp_pgno mp_p.p_pgno
546 #define mp_next mp_p.p_next
548 pgno_t p_pgno; /**< page number */
549 void * p_next; /**< for in-memory list of freed structs */
552 /** @defgroup mdb_page Page Flags
554 * Flags for the page headers.
557 #define P_BRANCH 0x01 /**< branch page */
558 #define P_LEAF 0x02 /**< leaf page */
559 #define P_OVERFLOW 0x04 /**< overflow page */
560 #define P_META 0x08 /**< meta page */
561 #define P_DIRTY 0x10 /**< dirty page */
562 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
563 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
565 uint16_t mp_flags; /**< @ref mdb_page */
566 #define mp_lower mp_pb.pb.pb_lower
567 #define mp_upper mp_pb.pb.pb_upper
568 #define mp_pages mp_pb.pb_pages
571 indx_t pb_lower; /**< lower bound of free space */
572 indx_t pb_upper; /**< upper bound of free space */
574 uint32_t pb_pages; /**< number of overflow pages */
576 indx_t mp_ptrs[1]; /**< dynamic size */
579 /** Size of the page header, excluding dynamic data at the end */
580 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
582 /** Address of first usable data byte in a page, after the header */
583 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
585 /** Number of nodes on a page */
586 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
588 /** The amount of space remaining in the page */
589 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
591 /** The percentage of space used in the page, in tenths of a percent. */
592 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
593 ((env)->me_psize - PAGEHDRSZ))
594 /** The minimum page fill factor, in tenths of a percent.
595 * Pages emptier than this are candidates for merging.
597 #define FILL_THRESHOLD 250
599 /** Test if a page is a leaf page */
600 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
601 /** Test if a page is a LEAF2 page */
602 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
603 /** Test if a page is a branch page */
604 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
605 /** Test if a page is an overflow page */
606 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
607 /** Test if a page is a sub page */
608 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
610 /** The number of overflow pages needed to store the given size. */
611 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
613 /** Header for a single key/data pair within a page.
614 * We guarantee 2-byte alignment for nodes.
616 typedef struct MDB_node {
617 /** lo and hi are used for data size on leaf nodes and for
618 * child pgno on branch nodes. On 64 bit platforms, flags
619 * is also used for pgno. (Branch nodes have no flags).
620 * They are in host byte order in case that lets some
621 * accesses be optimized into a 32-bit word access.
623 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
624 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
625 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
626 /** @defgroup mdb_node Node Flags
628 * Flags for node headers.
631 #define F_BIGDATA 0x01 /**< data put on overflow page */
632 #define F_SUBDATA 0x02 /**< data is a sub-database */
633 #define F_DUPDATA 0x04 /**< data has duplicates */
635 /** valid flags for #mdb_node_add() */
636 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
639 unsigned short mn_flags; /**< @ref mdb_node */
640 unsigned short mn_ksize; /**< key size */
641 char mn_data[1]; /**< key and data are appended here */
644 /** Size of the node header, excluding dynamic data at the end */
645 #define NODESIZE offsetof(MDB_node, mn_data)
647 /** Bit position of top word in page number, for shifting mn_flags */
648 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
650 /** Size of a node in a branch page with a given key.
651 * This is just the node header plus the key, there is no data.
653 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
655 /** Size of a node in a leaf page with a given key and data.
656 * This is node header plus key plus data size.
658 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
660 /** Address of node \b i in page \b p */
661 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
663 /** Address of the key for the node */
664 #define NODEKEY(node) (void *)((node)->mn_data)
666 /** Address of the data for a node */
667 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
669 /** Get the page number pointed to by a branch node */
670 #define NODEPGNO(node) \
671 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
672 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
673 /** Set the page number in a branch node */
674 #define SETPGNO(node,pgno) do { \
675 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
676 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
678 /** Get the size of the data in a leaf node */
679 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
680 /** Set the size of the data for a leaf node */
681 #define SETDSZ(node,size) do { \
682 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
683 /** The size of a key in a node */
684 #define NODEKSZ(node) ((node)->mn_ksize)
686 /** Copy a page number from src to dst */
688 #define COPY_PGNO(dst,src) dst = src
690 #if SIZE_MAX > 4294967295UL
691 #define COPY_PGNO(dst,src) do { \
692 unsigned short *s, *d; \
693 s = (unsigned short *)&(src); \
694 d = (unsigned short *)&(dst); \
701 #define COPY_PGNO(dst,src) do { \
702 unsigned short *s, *d; \
703 s = (unsigned short *)&(src); \
704 d = (unsigned short *)&(dst); \
710 /** The address of a key in a LEAF2 page.
711 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
712 * There are no node headers, keys are stored contiguously.
714 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
716 /** Set the \b node's key into \b key, if requested. */
717 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
718 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
720 /** Information about a single database in the environment. */
721 typedef struct MDB_db {
722 uint32_t md_pad; /**< also ksize for LEAF2 pages */
723 uint16_t md_flags; /**< @ref mdb_open */
724 uint16_t md_depth; /**< depth of this tree */
725 pgno_t md_branch_pages; /**< number of internal pages */
726 pgno_t md_leaf_pages; /**< number of leaf pages */
727 pgno_t md_overflow_pages; /**< number of overflow pages */
728 size_t md_entries; /**< number of data items */
729 pgno_t md_root; /**< the root page of this tree */
732 /** Handle for the DB used to track free pages. */
734 /** Handle for the default DB. */
737 /** Meta page content. */
738 typedef struct MDB_meta {
739 /** Stamp identifying this as an MDB file. It must be set
742 /** Version number of this lock file. Must be set to #MDB_VERSION. */
744 void *mm_address; /**< address for fixed mapping */
745 size_t mm_mapsize; /**< size of mmap region */
746 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
747 /** The size of pages used in this DB */
748 #define mm_psize mm_dbs[0].md_pad
749 /** Any persistent environment flags. @ref mdb_env */
750 #define mm_flags mm_dbs[0].md_flags
751 pgno_t mm_last_pg; /**< last used page in file */
752 txnid_t mm_txnid; /**< txnid that committed this page */
755 /** Buffer for a stack-allocated dirty page.
756 * The members define size and alignment, and silence type
757 * aliasing warnings. They are not used directly; that could
758 * mean incorrectly using several union members in parallel.
760 typedef union MDB_pagebuf {
761 char mb_raw[MDB_PAGESIZE];
764 char mm_pad[PAGEHDRSZ];
769 /** Auxiliary DB info.
770 * The information here is mostly static/read-only. There is
771 * only a single copy of this record in the environment.
773 typedef struct MDB_dbx {
774 MDB_val md_name; /**< name of the database */
775 MDB_cmp_func *md_cmp; /**< function for comparing keys */
776 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
777 MDB_rel_func *md_rel; /**< user relocate function */
778 void *md_relctx; /**< user-provided context for md_rel */
781 /** A database transaction.
782 * Every operation requires a transaction handle.
785 MDB_txn *mt_parent; /**< parent of a nested txn */
786 MDB_txn *mt_child; /**< nested txn under this txn */
787 pgno_t mt_next_pgno; /**< next unallocated page */
788 /** The ID of this transaction. IDs are integers incrementing from 1.
789 * Only committed write transactions increment the ID. If a transaction
790 * aborts, the ID may be re-used by the next writer.
793 MDB_env *mt_env; /**< the DB environment */
794 /** The list of pages that became unused during this transaction.
798 MDB_ID2L dirty_list; /**< modified pages */
799 MDB_reader *reader; /**< this thread's slot in the reader table */
801 /** Array of records for each DB known in the environment. */
803 /** Array of MDB_db records for each known DB */
805 /** @defgroup mt_dbflag Transaction DB Flags
809 #define DB_DIRTY 0x01 /**< DB was written in this txn */
810 #define DB_STALE 0x02 /**< DB record is older than txnID */
812 /** Array of cursors for each DB */
813 MDB_cursor **mt_cursors;
814 /** Array of flags for each DB */
815 unsigned char *mt_dbflags;
816 /** Number of DB records in use. This number only ever increments;
817 * we don't decrement it when individual DB handles are closed.
821 /** @defgroup mdb_txn Transaction Flags
825 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
826 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
828 unsigned int mt_flags; /**< @ref mdb_txn */
829 /** Tracks which of the two meta pages was used at the start
830 * of this transaction.
832 unsigned int mt_toggle;
835 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
836 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
837 * raise this on a 64 bit machine.
839 #define CURSOR_STACK 32
843 /** Cursors are used for all DB operations */
845 /** Next cursor on this DB in this txn */
847 /** Original cursor if this is a shadow */
849 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
850 struct MDB_xcursor *mc_xcursor;
851 /** The transaction that owns this cursor */
853 /** The database handle this cursor operates on */
855 /** The database record for this cursor */
857 /** The database auxiliary record for this cursor */
859 /** The @ref mt_dbflag for this database */
860 unsigned char *mc_dbflag;
861 unsigned short mc_snum; /**< number of pushed pages */
862 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
863 /** @defgroup mdb_cursor Cursor Flags
865 * Cursor state flags.
868 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
869 #define C_EOF 0x02 /**< No more data */
870 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
871 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
872 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
873 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
875 unsigned int mc_flags; /**< @ref mdb_cursor */
876 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
877 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
880 /** Context for sorted-dup records.
881 * We could have gone to a fully recursive design, with arbitrarily
882 * deep nesting of sub-databases. But for now we only handle these
883 * levels - main DB, optional sub-DB, sorted-duplicate DB.
885 typedef struct MDB_xcursor {
886 /** A sub-cursor for traversing the Dup DB */
887 MDB_cursor mx_cursor;
888 /** The database record for this Dup DB */
890 /** The auxiliary DB record for this Dup DB */
892 /** The @ref mt_dbflag for this Dup DB */
893 unsigned char mx_dbflag;
896 /** A set of pages freed by an earlier transaction. */
897 typedef struct MDB_oldpages {
898 /** Usually we only read one record from the FREEDB at a time, but
899 * in case we read more, this will chain them together.
901 struct MDB_oldpages *mo_next;
902 /** The ID of the transaction in which these pages were freed. */
904 /** An #MDB_IDL of the pages */
905 pgno_t mo_pages[1]; /* dynamic */
908 /** The database environment. */
910 HANDLE me_fd; /**< The main data file */
911 HANDLE me_lfd; /**< The lock file */
912 HANDLE me_mfd; /**< just for writing the meta pages */
913 /** Failed to update the meta page. Probably an I/O error. */
914 #define MDB_FATAL_ERROR 0x80000000U
915 uint32_t me_flags; /**< @ref mdb_env */
916 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
917 unsigned int me_maxreaders; /**< size of the reader table */
918 unsigned int me_numreaders; /**< max numreaders set by this env */
919 MDB_dbi me_numdbs; /**< number of DBs opened */
920 MDB_dbi me_maxdbs; /**< size of the DB table */
921 pid_t me_pid; /**< process ID of this env */
922 char *me_path; /**< path to the DB files */
923 char *me_map; /**< the memory map of the data file */
924 MDB_txninfo *me_txns; /**< the memory map of the lock file */
925 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
926 MDB_txn *me_txn; /**< current write transaction */
927 size_t me_mapsize; /**< size of the data memory map */
928 off_t me_size; /**< current file size */
929 pgno_t me_maxpg; /**< me_mapsize / me_psize */
930 txnid_t me_pgfirst; /**< ID of first old page record we used */
931 txnid_t me_pglast; /**< ID of last old page record we used */
932 MDB_dbx *me_dbxs; /**< array of static DB info */
933 uint16_t *me_dbflags; /**< array of DB flags */
934 MDB_oldpages *me_pghead; /**< list of old page records */
935 MDB_oldpages *me_pgfree; /**< list of page records to free */
936 pthread_key_t me_txkey; /**< thread-key for readers */
937 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
938 /** IDL of pages that became unused in a write txn */
940 /** ID2L of pages that were written during a write txn */
941 MDB_ID2 me_dirty_list[MDB_IDL_UM_SIZE];
943 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
945 #elif defined(MDB_USE_POSIX_SEM)
946 sem_t *me_rmutex; /* Shared mutexes are not supported */
950 /** max number of pages to commit in one writev() call */
951 #define MDB_COMMIT_PAGES 64
952 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
953 #undef MDB_COMMIT_PAGES
954 #define MDB_COMMIT_PAGES IOV_MAX
957 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
958 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
959 static int mdb_page_touch(MDB_cursor *mc);
961 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
962 static int mdb_page_search_root(MDB_cursor *mc,
963 MDB_val *key, int modify);
964 #define MDB_PS_MODIFY 1
965 #define MDB_PS_ROOTONLY 2
966 static int mdb_page_search(MDB_cursor *mc,
967 MDB_val *key, int flags);
968 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
970 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
971 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
972 pgno_t newpgno, unsigned int nflags);
974 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
975 static int mdb_env_pick_meta(const MDB_env *env);
976 static int mdb_env_write_meta(MDB_txn *txn);
977 static void mdb_env_close0(MDB_env *env, int excl);
979 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
980 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
981 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
982 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
983 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
984 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
985 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
986 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
987 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
989 static int mdb_rebalance(MDB_cursor *mc);
990 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
992 static void mdb_cursor_pop(MDB_cursor *mc);
993 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
995 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
996 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
997 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
998 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
999 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1001 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1002 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1004 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1005 static void mdb_xcursor_init0(MDB_cursor *mc);
1006 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1008 static int mdb_drop0(MDB_cursor *mc, int subs);
1009 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1012 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1016 static SECURITY_DESCRIPTOR mdb_null_sd;
1017 static SECURITY_ATTRIBUTES mdb_all_sa;
1018 static int mdb_sec_inited;
1021 /** Return the library version info. */
1023 mdb_version(int *major, int *minor, int *patch)
1025 if (major) *major = MDB_VERSION_MAJOR;
1026 if (minor) *minor = MDB_VERSION_MINOR;
1027 if (patch) *patch = MDB_VERSION_PATCH;
1028 return MDB_VERSION_STRING;
1031 /** Table of descriptions for MDB @ref errors */
1032 static char *const mdb_errstr[] = {
1033 "MDB_KEYEXIST: Key/data pair already exists",
1034 "MDB_NOTFOUND: No matching key/data pair found",
1035 "MDB_PAGE_NOTFOUND: Requested page not found",
1036 "MDB_CORRUPTED: Located page was wrong type",
1037 "MDB_PANIC: Update of meta page failed",
1038 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1039 "MDB_INVALID: File is not an MDB file",
1040 "MDB_MAP_FULL: Environment mapsize limit reached",
1041 "MDB_DBS_FULL: Environment maxdbs limit reached",
1042 "MDB_READERS_FULL: Environment maxreaders limit reached",
1043 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1044 "MDB_TXN_FULL: Nested transaction has too many dirty pages - transaction too big",
1045 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1046 "MDB_PAGE_FULL: Internal error - page has no more space"
1050 mdb_strerror(int err)
1054 return ("Successful return: 0");
1056 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1057 i = err - MDB_KEYEXIST;
1058 return mdb_errstr[i];
1061 return strerror(err);
1065 /** Display a key in hexadecimal and return the address of the result.
1066 * @param[in] key the key to display
1067 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1068 * @return The key in hexadecimal form.
1071 mdb_dkey(MDB_val *key, char *buf)
1074 unsigned char *c = key->mv_data;
1076 if (key->mv_size > MAXKEYSIZE)
1077 return "MAXKEYSIZE";
1078 /* may want to make this a dynamic check: if the key is mostly
1079 * printable characters, print it as-is instead of converting to hex.
1083 for (i=0; i<key->mv_size; i++)
1084 ptr += sprintf(ptr, "%02x", *c++);
1086 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1091 /** Display all the keys in the page. */
1093 mdb_page_list(MDB_page *mp)
1096 unsigned int i, nkeys, nsize;
1100 nkeys = NUMKEYS(mp);
1101 fprintf(stderr, "numkeys %d\n", nkeys);
1102 for (i=0; i<nkeys; i++) {
1103 node = NODEPTR(mp, i);
1104 key.mv_size = node->mn_ksize;
1105 key.mv_data = node->mn_data;
1106 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1107 if (F_ISSET(node->mn_flags, F_BIGDATA))
1108 nsize += sizeof(pgno_t);
1110 nsize += NODEDSZ(node);
1111 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1116 mdb_cursor_chk(MDB_cursor *mc)
1122 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1123 for (i=0; i<mc->mc_top; i++) {
1125 node = NODEPTR(mp, mc->mc_ki[i]);
1126 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1129 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1135 /** Count all the pages in each DB and in the freelist
1136 * and make sure it matches the actual number of pages
1139 static void mdb_audit(MDB_txn *txn)
1143 MDB_ID freecount, count;
1148 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1149 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1150 freecount += *(MDB_ID *)data.mv_data;
1153 for (i = 0; i<txn->mt_numdbs; i++) {
1154 MDB_xcursor mx, *mxp;
1155 mxp = (txn->mt_dbs[i].md_flags & MDB_DUPSORT) ? &mx : NULL;
1156 mdb_cursor_init(&mc, txn, i, mxp);
1157 if (txn->mt_dbs[i].md_root == P_INVALID)
1159 count += txn->mt_dbs[i].md_branch_pages +
1160 txn->mt_dbs[i].md_leaf_pages +
1161 txn->mt_dbs[i].md_overflow_pages;
1162 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1163 mdb_page_search(&mc, NULL, 0);
1167 mp = mc.mc_pg[mc.mc_top];
1168 for (j=0; j<NUMKEYS(mp); j++) {
1169 MDB_node *leaf = NODEPTR(mp, j);
1170 if (leaf->mn_flags & F_SUBDATA) {
1172 memcpy(&db, NODEDATA(leaf), sizeof(db));
1173 count += db.md_branch_pages + db.md_leaf_pages +
1174 db.md_overflow_pages;
1178 while (mdb_cursor_sibling(&mc, 1) == 0);
1181 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1182 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1183 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1189 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1191 return txn->mt_dbxs[dbi].md_cmp(a, b);
1195 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1197 if (txn->mt_dbxs[dbi].md_dcmp)
1198 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1200 return EINVAL; /* too bad you can't distinguish this from a valid result */
1203 /** Allocate a single page.
1204 * Re-use old malloc'd pages first, otherwise just malloc.
1207 mdb_page_malloc(MDB_cursor *mc) {
1209 size_t sz = mc->mc_txn->mt_env->me_psize;
1210 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1211 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1212 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1213 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1214 } else if ((ret = malloc(sz)) != NULL) {
1215 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1220 /** Allocate pages for writing.
1221 * If there are free pages available from older transactions, they
1222 * will be re-used first. Otherwise a new page will be allocated.
1223 * @param[in] mc cursor A cursor handle identifying the transaction and
1224 * database for which we are allocating.
1225 * @param[in] num the number of pages to allocate.
1226 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1227 * will always be satisfied by a single contiguous chunk of memory.
1228 * @return 0 on success, non-zero on failure.
1231 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1233 MDB_txn *txn = mc->mc_txn;
1235 pgno_t pgno = P_INVALID;
1240 /* The free list won't have any content at all until txn 2 has
1241 * committed. The pages freed by txn 2 will be unreferenced
1242 * after txn 3 commits, and so will be safe to re-use in txn 4.
1244 if (txn->mt_txnid > 3) {
1246 if (!txn->mt_env->me_pghead &&
1247 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1248 /* See if there's anything in the free DB */
1254 txnid_t *kptr, last;
1256 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1257 if (!txn->mt_env->me_pgfirst) {
1258 mdb_page_search(&m2, NULL, 0);
1259 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1260 kptr = (txnid_t *)NODEKEY(leaf);
1267 last = txn->mt_env->me_pglast + 1;
1269 key.mv_data = &last;
1270 key.mv_size = sizeof(last);
1271 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1274 last = *(txnid_t *)key.mv_data;
1277 /* Unusable if referred by a meta page or reader... */
1279 if (last < txn->mt_txnid-1) {
1280 j = txn->mt_env->me_txns->mti_numreaders;
1281 r = txn->mt_env->me_txns->mti_readers + j;
1282 for (j = -j; j && (last<r[j].mr_txnid || !r[j].mr_pid); j++) ;
1286 /* It's usable, grab it.
1291 if (!txn->mt_env->me_pgfirst) {
1292 mdb_node_read(txn, leaf, &data);
1294 txn->mt_env->me_pglast = last;
1295 if (!txn->mt_env->me_pgfirst)
1296 txn->mt_env->me_pgfirst = last;
1297 idl = (MDB_ID *) data.mv_data;
1298 /* We might have a zero-length IDL due to freelist growth
1299 * during a prior commit
1301 if (!idl[0]) goto again;
1302 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1305 mop->mo_next = txn->mt_env->me_pghead;
1306 mop->mo_txnid = last;
1307 txn->mt_env->me_pghead = mop;
1308 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1313 DPRINTF("IDL read txn %zu root %zu num %zu",
1314 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1315 for (i=0; i<idl[0]; i++) {
1316 DPRINTF("IDL %zu", idl[i+1]);
1323 if (txn->mt_env->me_pghead) {
1324 MDB_oldpages *mop = txn->mt_env->me_pghead;
1326 /* FIXME: For now, always use fresh pages. We
1327 * really ought to search the free list for a
1332 /* peel pages off tail, so we only have to truncate the list */
1333 pgno = MDB_IDL_LAST(mop->mo_pages);
1334 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1336 if (mop->mo_pages[2] > mop->mo_pages[1])
1337 mop->mo_pages[0] = 0;
1341 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1342 txn->mt_env->me_pghead = mop->mo_next;
1343 if (mc->mc_dbi == FREE_DBI) {
1344 mop->mo_next = txn->mt_env->me_pgfree;
1345 txn->mt_env->me_pgfree = mop;
1354 if (pgno == P_INVALID) {
1355 /* DB size is maxed out */
1356 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1357 DPUTS("DB size maxed out");
1358 return MDB_MAP_FULL;
1361 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1362 if (pgno == P_INVALID) {
1363 pgno = txn->mt_next_pgno;
1364 txn->mt_next_pgno += num;
1366 np = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1369 if (txn->mt_env->me_dpages && num == 1) {
1370 np = txn->mt_env->me_dpages;
1371 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1372 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1373 txn->mt_env->me_dpages = np->mp_next;
1375 size_t sz = txn->mt_env->me_psize * num;
1376 if ((np = malloc(sz)) == NULL)
1378 VGMEMP_ALLOC(txn->mt_env, np, sz);
1380 if (pgno == P_INVALID) {
1381 np->mp_pgno = txn->mt_next_pgno;
1382 txn->mt_next_pgno += num;
1387 mid.mid = np->mp_pgno;
1389 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1390 mdb_mid2l_append(txn->mt_u.dirty_list, &mid);
1392 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1399 /** Copy a page: avoid copying unused portions of the page.
1400 * @param[in] dst page to copy into
1401 * @param[in] src page to copy from
1404 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1406 dst->mp_flags = src->mp_flags | P_DIRTY;
1407 dst->mp_pages = src->mp_pages;
1409 if (IS_LEAF2(src)) {
1410 memcpy(dst->mp_ptrs, src->mp_ptrs, psize - PAGEHDRSZ - SIZELEFT(src));
1412 unsigned int i, nkeys = NUMKEYS(src);
1413 for (i=0; i<nkeys; i++)
1414 dst->mp_ptrs[i] = src->mp_ptrs[i];
1415 memcpy((char *)dst+src->mp_upper, (char *)src+src->mp_upper,
1416 psize - src->mp_upper);
1420 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1421 * @param[in] mc cursor pointing to the page to be touched
1422 * @return 0 on success, non-zero on failure.
1425 mdb_page_touch(MDB_cursor *mc)
1427 MDB_page *mp = mc->mc_pg[mc->mc_top];
1431 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1433 if ((rc = mdb_page_alloc(mc, 1, &np)))
1435 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1436 assert(mp->mp_pgno != np->mp_pgno);
1437 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1439 /* If page isn't full, just copy the used portion */
1440 mdb_page_copy(np, mp, mc->mc_txn->mt_env->me_psize);
1443 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1445 np->mp_flags |= P_DIRTY;
1450 /* Adjust other cursors pointing to mp */
1451 if (mc->mc_flags & C_SUB) {
1452 MDB_cursor *m2, *m3;
1453 MDB_dbi dbi = mc->mc_dbi-1;
1455 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1456 if (m2 == mc) continue;
1457 m3 = &m2->mc_xcursor->mx_cursor;
1458 if (m3->mc_snum < mc->mc_snum) continue;
1459 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1460 m3->mc_pg[mc->mc_top] = mp;
1466 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1467 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1468 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1469 m2->mc_pg[mc->mc_top] = mp;
1473 mc->mc_pg[mc->mc_top] = mp;
1474 /** If this page has a parent, update the parent to point to
1478 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1480 mc->mc_db->md_root = mp->mp_pgno;
1481 } else if (mc->mc_txn->mt_parent) {
1484 /* If txn has a parent, make sure the page is in our
1487 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1488 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1489 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1490 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1491 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1492 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1493 mc->mc_pg[mc->mc_top] = mp;
1499 np = mdb_page_malloc(mc);
1502 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1503 mid.mid = np->mp_pgno;
1505 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1513 mdb_env_sync(MDB_env *env, int force)
1516 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1517 if (env->me_flags & MDB_WRITEMAP) {
1518 int flags = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
1519 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1522 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1526 if (MDB_FDATASYNC(env->me_fd))
1533 /** Make shadow copies of all of parent txn's cursors */
1535 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1537 MDB_cursor *mc, *m2;
1538 unsigned int i, j, size;
1540 for (i=0;i<src->mt_numdbs; i++) {
1541 if (src->mt_cursors[i]) {
1542 size = sizeof(MDB_cursor);
1543 if (src->mt_cursors[i]->mc_xcursor)
1544 size += sizeof(MDB_xcursor);
1545 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1552 mc->mc_db = &dst->mt_dbs[i];
1553 mc->mc_dbx = m2->mc_dbx;
1554 mc->mc_dbflag = &dst->mt_dbflags[i];
1555 mc->mc_snum = m2->mc_snum;
1556 mc->mc_top = m2->mc_top;
1557 mc->mc_flags = m2->mc_flags | C_SHADOW;
1558 for (j=0; j<mc->mc_snum; j++) {
1559 mc->mc_pg[j] = m2->mc_pg[j];
1560 mc->mc_ki[j] = m2->mc_ki[j];
1562 if (m2->mc_xcursor) {
1563 MDB_xcursor *mx, *mx2;
1564 mx = (MDB_xcursor *)(mc+1);
1565 mc->mc_xcursor = mx;
1566 mx2 = m2->mc_xcursor;
1567 mx->mx_db = mx2->mx_db;
1568 mx->mx_dbx = mx2->mx_dbx;
1569 mx->mx_dbflag = mx2->mx_dbflag;
1570 mx->mx_cursor.mc_txn = dst;
1571 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1572 mx->mx_cursor.mc_db = &mx->mx_db;
1573 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1574 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1575 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1576 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1577 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1578 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1579 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1580 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1583 mc->mc_xcursor = NULL;
1585 mc->mc_next = dst->mt_cursors[i];
1586 dst->mt_cursors[i] = mc;
1593 /** Merge shadow cursors back into parent's */
1595 mdb_cursor_merge(MDB_txn *txn)
1598 for (i=0; i<txn->mt_numdbs; i++) {
1599 if (txn->mt_cursors[i]) {
1601 while ((mc = txn->mt_cursors[i])) {
1602 txn->mt_cursors[i] = mc->mc_next;
1603 if (mc->mc_flags & C_SHADOW) {
1604 MDB_cursor *m2 = mc->mc_orig;
1606 m2->mc_snum = mc->mc_snum;
1607 m2->mc_top = mc->mc_top;
1608 for (j=0; j<mc->mc_snum; j++) {
1609 m2->mc_pg[j] = mc->mc_pg[j];
1610 m2->mc_ki[j] = mc->mc_ki[j];
1613 if (mc->mc_flags & C_ALLOCD)
1621 mdb_txn_reset0(MDB_txn *txn);
1623 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1624 * @param[in] txn the transaction handle to initialize
1625 * @return 0 on success, non-zero on failure. This can only
1626 * fail for read-only transactions, and then only if the
1627 * reader table is full.
1630 mdb_txn_renew0(MDB_txn *txn)
1632 MDB_env *env = txn->mt_env;
1636 txn->mt_numdbs = env->me_numdbs;
1637 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1639 if (txn->mt_flags & MDB_TXN_RDONLY) {
1640 MDB_reader *r = pthread_getspecific(env->me_txkey);
1642 pid_t pid = env->me_pid;
1643 pthread_t tid = pthread_self();
1646 for (i=0; i<env->me_txns->mti_numreaders; i++)
1647 if (env->me_txns->mti_readers[i].mr_pid == 0)
1649 if (i == env->me_maxreaders) {
1650 UNLOCK_MUTEX_R(env);
1651 return MDB_READERS_FULL;
1653 env->me_txns->mti_readers[i].mr_pid = pid;
1654 env->me_txns->mti_readers[i].mr_tid = tid;
1655 if (i >= env->me_txns->mti_numreaders)
1656 env->me_txns->mti_numreaders = i+1;
1657 /* Save numreaders for un-mutexed mdb_env_close() */
1658 env->me_numreaders = env->me_txns->mti_numreaders;
1659 UNLOCK_MUTEX_R(env);
1660 r = &env->me_txns->mti_readers[i];
1661 pthread_setspecific(env->me_txkey, r);
1663 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1664 txn->mt_toggle = txn->mt_txnid & 1;
1665 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1666 txn->mt_u.reader = r;
1670 txn->mt_txnid = env->me_txns->mti_txnid;
1671 txn->mt_toggle = txn->mt_txnid & 1;
1672 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1675 if (txn->mt_txnid == mdb_debug_start)
1678 txn->mt_u.dirty_list = env->me_dirty_list;
1679 txn->mt_u.dirty_list[0].mid = 0;
1680 txn->mt_free_pgs = env->me_free_pgs;
1681 txn->mt_free_pgs[0] = 0;
1685 /* Copy the DB info and flags */
1686 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1687 for (i=2; i<txn->mt_numdbs; i++)
1688 txn->mt_dbs[i].md_flags = env->me_dbflags[i];
1689 txn->mt_dbflags[0] = txn->mt_dbflags[1] = 0;
1690 if (txn->mt_numdbs > 2)
1691 memset(txn->mt_dbflags+2, DB_STALE, txn->mt_numdbs-2);
1697 mdb_txn_renew(MDB_txn *txn)
1701 if (! (txn && txn->mt_flags & MDB_TXN_RDONLY))
1704 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1705 DPUTS("environment had fatal error, must shutdown!");
1709 rc = mdb_txn_renew0(txn);
1710 if (rc == MDB_SUCCESS) {
1711 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1712 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1713 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1719 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1724 if (env->me_flags & MDB_FATAL_ERROR) {
1725 DPUTS("environment had fatal error, must shutdown!");
1728 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
1731 /* Nested transactions: Max 1 child, write txns only, no writemap */
1732 if (parent->mt_child ||
1733 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
1734 (env->me_flags & MDB_WRITEMAP))
1739 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1740 if (!(flags & MDB_RDONLY))
1741 size += env->me_maxdbs * sizeof(MDB_cursor *);
1743 if ((txn = calloc(1, size)) == NULL) {
1744 DPRINTF("calloc: %s", strerror(ErrCode()));
1747 txn->mt_dbs = (MDB_db *)(txn+1);
1748 if (flags & MDB_RDONLY) {
1749 txn->mt_flags |= MDB_TXN_RDONLY;
1750 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1752 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1753 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1758 txn->mt_free_pgs = mdb_midl_alloc();
1759 if (!txn->mt_free_pgs) {
1763 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1764 if (!txn->mt_u.dirty_list) {
1765 free(txn->mt_free_pgs);
1769 txn->mt_txnid = parent->mt_txnid;
1770 txn->mt_toggle = parent->mt_toggle;
1771 txn->mt_u.dirty_list[0].mid = 0;
1772 txn->mt_free_pgs[0] = 0;
1773 txn->mt_next_pgno = parent->mt_next_pgno;
1774 parent->mt_child = txn;
1775 txn->mt_parent = parent;
1776 txn->mt_numdbs = parent->mt_numdbs;
1777 txn->mt_dbxs = parent->mt_dbxs;
1778 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1779 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1780 mdb_cursor_shadow(parent, txn);
1783 rc = mdb_txn_renew0(txn);
1789 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1790 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1791 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1797 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1798 * @param[in] txn the transaction handle to reset
1801 mdb_txn_reset0(MDB_txn *txn)
1803 MDB_env *env = txn->mt_env;
1805 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1806 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
1812 /* close(free) all cursors */
1813 for (i=0; i<txn->mt_numdbs; i++) {
1814 if (txn->mt_cursors[i]) {
1816 while ((mc = txn->mt_cursors[i])) {
1817 txn->mt_cursors[i] = mc->mc_next;
1818 if (mc->mc_flags & C_ALLOCD)
1824 if (!(env->me_flags & MDB_WRITEMAP)) {
1825 /* return all dirty pages to dpage list */
1826 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1827 dp = txn->mt_u.dirty_list[i].mptr;
1828 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1829 dp->mp_next = txn->mt_env->me_dpages;
1830 VGMEMP_FREE(txn->mt_env, dp);
1831 txn->mt_env->me_dpages = dp;
1833 /* large pages just get freed directly */
1834 VGMEMP_FREE(txn->mt_env, dp);
1840 if (txn->mt_parent) {
1841 txn->mt_parent->mt_child = NULL;
1842 mdb_midl_free(txn->mt_free_pgs);
1843 free(txn->mt_u.dirty_list);
1846 if (mdb_midl_shrink(&txn->mt_free_pgs))
1847 env->me_free_pgs = txn->mt_free_pgs;
1850 while ((mop = txn->mt_env->me_pghead)) {
1851 txn->mt_env->me_pghead = mop->mo_next;
1854 txn->mt_env->me_pgfirst = 0;
1855 txn->mt_env->me_pglast = 0;
1858 /* The writer mutex was locked in mdb_txn_begin. */
1859 UNLOCK_MUTEX_W(env);
1864 mdb_txn_reset(MDB_txn *txn)
1869 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1870 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1871 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1873 mdb_txn_reset0(txn);
1877 mdb_txn_abort(MDB_txn *txn)
1882 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1883 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1884 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1887 mdb_txn_abort(txn->mt_child);
1889 mdb_txn_reset0(txn);
1894 mdb_txn_commit(MDB_txn *txn)
1902 pgno_t next, freecnt;
1905 assert(txn != NULL);
1906 assert(txn->mt_env != NULL);
1908 if (txn->mt_child) {
1909 mdb_txn_commit(txn->mt_child);
1910 txn->mt_child = NULL;
1915 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1916 if (txn->mt_numdbs > env->me_numdbs) {
1917 /* update the DB flags */
1919 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
1920 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
1927 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1928 DPUTS("error flag is set, can't commit");
1930 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1935 /* Merge (and close) our cursors with parent's */
1936 mdb_cursor_merge(txn);
1938 if (txn->mt_parent) {
1944 /* Update parent's DB table */
1945 ip = &txn->mt_parent->mt_dbs[2];
1946 jp = &txn->mt_dbs[2];
1947 for (i = 2; i < txn->mt_numdbs; i++) {
1948 if (ip->md_root != jp->md_root)
1952 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1954 /* Append our free list to parent's */
1955 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1957 mdb_midl_free(txn->mt_free_pgs);
1959 /* Merge our dirty list with parent's */
1960 dst = txn->mt_parent->mt_u.dirty_list;
1961 src = txn->mt_u.dirty_list;
1962 x = mdb_mid2l_search(dst, src[1].mid);
1963 for (y=1; y<=src[0].mid; y++) {
1964 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1968 dst[x].mptr = src[y].mptr;
1971 for (; y<=src[0].mid; y++) {
1972 if (++x >= MDB_IDL_UM_MAX) {
1974 return MDB_TXN_FULL;
1979 free(txn->mt_u.dirty_list);
1980 txn->mt_parent->mt_child = NULL;
1985 if (txn != env->me_txn) {
1986 DPUTS("attempt to commit unknown transaction");
1991 if (!txn->mt_u.dirty_list[0].mid)
1994 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1995 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1997 /* Update DB root pointers. Their pages have already been
1998 * touched so this is all in-place and cannot fail.
2000 if (txn->mt_numdbs > 2) {
2003 data.mv_size = sizeof(MDB_db);
2005 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2006 for (i = 2; i < txn->mt_numdbs; i++) {
2007 if (txn->mt_dbflags[i] & DB_DIRTY) {
2008 data.mv_data = &txn->mt_dbs[i];
2009 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2014 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2016 /* should only be one record now */
2017 if (env->me_pghead) {
2018 /* make sure first page of freeDB is touched and on freelist */
2019 mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2022 /* Delete IDLs we used from the free list */
2023 if (env->me_pgfirst) {
2028 key.mv_size = sizeof(cur);
2029 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
2032 mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
2033 rc = mdb_cursor_del(&mc, 0);
2039 env->me_pgfirst = 0;
2043 /* save to free list */
2045 freecnt = txn->mt_free_pgs[0];
2046 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2049 /* make sure last page of freeDB is touched and on freelist */
2050 key.mv_size = MAXKEYSIZE+1;
2052 mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2054 mdb_midl_sort(txn->mt_free_pgs);
2058 MDB_IDL idl = txn->mt_free_pgs;
2059 DPRINTF("IDL write txn %zu root %zu num %zu",
2060 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
2061 for (i=0; i<idl[0]; i++) {
2062 DPRINTF("IDL %zu", idl[i+1]);
2066 /* write to last page of freeDB */
2067 key.mv_size = sizeof(pgno_t);
2068 key.mv_data = &txn->mt_txnid;
2069 data.mv_data = txn->mt_free_pgs;
2070 /* The free list can still grow during this call,
2071 * despite the pre-emptive touches above. So check
2072 * and make sure the entire thing got written.
2075 freecnt = txn->mt_free_pgs[0];
2076 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
2077 rc = mdb_cursor_put(&mc, &key, &data, 0);
2082 } while (freecnt != txn->mt_free_pgs[0]);
2084 /* should only be one record now */
2086 if (env->me_pghead) {
2092 mop = env->me_pghead;
2094 key.mv_size = sizeof(id);
2096 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2097 data.mv_data = mop->mo_pages;
2098 orig = mop->mo_pages[0];
2099 /* These steps may grow the freelist again
2100 * due to freed overflow pages...
2102 mdb_cursor_put(&mc, &key, &data, 0);
2103 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
2104 /* could have been used again here */
2105 if (mop->mo_pages[0] != orig) {
2106 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2107 data.mv_data = mop->mo_pages;
2109 mdb_cursor_put(&mc, &key, &data, 0);
2111 env->me_pghead = NULL;
2114 /* was completely used up */
2115 mdb_cursor_del(&mc, 0);
2119 env->me_pgfirst = 0;
2123 while (env->me_pgfree) {
2124 MDB_oldpages *mop = env->me_pgfree;
2125 env->me_pgfree = mop->mo_next;
2129 /* Check for growth of freelist again */
2130 if (freecnt != txn->mt_free_pgs[0])
2133 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2134 if (mdb_midl_shrink(&txn->mt_free_pgs))
2135 env->me_free_pgs = txn->mt_free_pgs;
2142 if (env->me_flags & MDB_WRITEMAP) {
2143 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2144 dp = txn->mt_u.dirty_list[i].mptr;
2145 /* clear dirty flag */
2146 dp->mp_flags &= ~P_DIRTY;
2147 txn->mt_u.dirty_list[i].mid = 0;
2149 txn->mt_u.dirty_list[0].mid = 0;
2153 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2159 /* Windows actually supports scatter/gather I/O, but only on
2160 * unbuffered file handles. Since we're relying on the OS page
2161 * cache for all our data, that's self-defeating. So we just
2162 * write pages one at a time. We use the ov structure to set
2163 * the write offset, to at least save the overhead of a Seek
2167 memset(&ov, 0, sizeof(ov));
2168 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2170 dp = txn->mt_u.dirty_list[i].mptr;
2171 DPRINTF("committing page %zu", dp->mp_pgno);
2172 size = dp->mp_pgno * env->me_psize;
2173 ov.Offset = size & 0xffffffff;
2174 ov.OffsetHigh = size >> 16;
2175 ov.OffsetHigh >>= 16;
2176 /* clear dirty flag */
2177 dp->mp_flags &= ~P_DIRTY;
2178 wsize = env->me_psize;
2179 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2180 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2183 DPRINTF("WriteFile: %d", n);
2190 struct iovec iov[MDB_COMMIT_PAGES];
2194 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2195 dp = txn->mt_u.dirty_list[i].mptr;
2196 if (dp->mp_pgno != next) {
2198 rc = writev(env->me_fd, iov, n);
2202 DPUTS("short write, filesystem full?");
2204 DPRINTF("writev: %s", strerror(n));
2211 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2214 DPRINTF("committing page %zu", dp->mp_pgno);
2215 iov[n].iov_len = env->me_psize;
2216 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2217 iov[n].iov_base = (char *)dp;
2218 size += iov[n].iov_len;
2219 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2220 /* clear dirty flag */
2221 dp->mp_flags &= ~P_DIRTY;
2222 if (++n >= MDB_COMMIT_PAGES) {
2232 rc = writev(env->me_fd, iov, n);
2236 DPUTS("short write, filesystem full?");
2238 DPRINTF("writev: %s", strerror(n));
2245 /* Drop the dirty pages.
2247 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2248 dp = txn->mt_u.dirty_list[i].mptr;
2249 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2250 dp->mp_next = txn->mt_env->me_dpages;
2251 VGMEMP_FREE(txn->mt_env, dp);
2252 txn->mt_env->me_dpages = dp;
2254 VGMEMP_FREE(txn->mt_env, dp);
2257 txn->mt_u.dirty_list[i].mid = 0;
2259 txn->mt_u.dirty_list[0].mid = 0;
2262 if ((n = mdb_env_sync(env, 0)) != 0 ||
2263 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2270 if (txn->mt_numdbs > env->me_numdbs) {
2271 /* update the DB flags */
2273 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2274 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2278 UNLOCK_MUTEX_W(env);
2284 /** Read the environment parameters of a DB environment before
2285 * mapping it into memory.
2286 * @param[in] env the environment handle
2287 * @param[out] meta address of where to store the meta information
2288 * @return 0 on success, non-zero on failure.
2291 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2298 /* We don't know the page size yet, so use a minimum value.
2302 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2304 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2309 else if (rc != MDB_PAGESIZE) {
2313 DPRINTF("read: %s", strerror(err));
2317 p = (MDB_page *)&pbuf;
2319 if (!F_ISSET(p->mp_flags, P_META)) {
2320 DPRINTF("page %zu not a meta page", p->mp_pgno);
2325 if (m->mm_magic != MDB_MAGIC) {
2326 DPUTS("meta has invalid magic");
2330 if (m->mm_version != MDB_VERSION) {
2331 DPRINTF("database is version %u, expected version %u",
2332 m->mm_version, MDB_VERSION);
2333 return MDB_VERSION_MISMATCH;
2336 memcpy(meta, m, sizeof(*m));
2340 /** Write the environment parameters of a freshly created DB environment.
2341 * @param[in] env the environment handle
2342 * @param[out] meta address of where to store the meta information
2343 * @return 0 on success, non-zero on failure.
2346 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2353 DPUTS("writing new meta page");
2355 GET_PAGESIZE(psize);
2357 meta->mm_magic = MDB_MAGIC;
2358 meta->mm_version = MDB_VERSION;
2359 meta->mm_psize = psize;
2360 meta->mm_last_pg = 1;
2361 meta->mm_flags = env->me_flags & 0xffff;
2362 meta->mm_flags |= MDB_INTEGERKEY;
2363 meta->mm_dbs[0].md_root = P_INVALID;
2364 meta->mm_dbs[1].md_root = P_INVALID;
2366 p = calloc(2, psize);
2368 p->mp_flags = P_META;
2371 memcpy(m, meta, sizeof(*meta));
2373 q = (MDB_page *)((char *)p + psize);
2376 q->mp_flags = P_META;
2379 memcpy(m, meta, sizeof(*meta));
2384 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2385 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2388 rc = write(env->me_fd, p, psize * 2);
2389 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2395 /** Update the environment info to commit a transaction.
2396 * @param[in] txn the transaction that's being committed
2397 * @return 0 on success, non-zero on failure.
2400 mdb_env_write_meta(MDB_txn *txn)
2403 MDB_meta meta, metab;
2405 int rc, len, toggle;
2411 assert(txn != NULL);
2412 assert(txn->mt_env != NULL);
2414 toggle = !txn->mt_toggle;
2415 DPRINTF("writing meta page %d for root page %zu",
2416 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2420 if (env->me_flags & MDB_WRITEMAP) {
2421 MDB_meta *mp = env->me_metas[toggle];
2422 mp->mm_dbs[0] = txn->mt_dbs[0];
2423 mp->mm_dbs[1] = txn->mt_dbs[1];
2424 mp->mm_last_pg = txn->mt_next_pgno - 1;
2425 mp->mm_txnid = txn->mt_txnid;
2426 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2427 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2430 ptr += env->me_psize;
2431 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2438 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2439 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2441 ptr = (char *)&meta;
2442 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2443 len = sizeof(MDB_meta) - off;
2446 meta.mm_dbs[0] = txn->mt_dbs[0];
2447 meta.mm_dbs[1] = txn->mt_dbs[1];
2448 meta.mm_last_pg = txn->mt_next_pgno - 1;
2449 meta.mm_txnid = txn->mt_txnid;
2452 off += env->me_psize;
2455 /* Write to the SYNC fd */
2458 memset(&ov, 0, sizeof(ov));
2460 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2463 rc = pwrite(env->me_mfd, ptr, len, off);
2468 DPUTS("write failed, disk error?");
2469 /* On a failure, the pagecache still contains the new data.
2470 * Write some old data back, to prevent it from being used.
2471 * Use the non-SYNC fd; we know it will fail anyway.
2473 meta.mm_last_pg = metab.mm_last_pg;
2474 meta.mm_txnid = metab.mm_txnid;
2476 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2478 r2 = pwrite(env->me_fd, ptr, len, off);
2481 env->me_flags |= MDB_FATAL_ERROR;
2485 /* Memory ordering issues are irrelevant; since the entire writer
2486 * is wrapped by wmutex, all of these changes will become visible
2487 * after the wmutex is unlocked. Since the DB is multi-version,
2488 * readers will get consistent data regardless of how fresh or
2489 * how stale their view of these values is.
2491 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2496 /** Check both meta pages to see which one is newer.
2497 * @param[in] env the environment handle
2498 * @return meta toggle (0 or 1).
2501 mdb_env_pick_meta(const MDB_env *env)
2503 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2507 mdb_env_create(MDB_env **env)
2511 e = calloc(1, sizeof(MDB_env));
2515 e->me_free_pgs = mdb_midl_alloc();
2516 if (!e->me_free_pgs) {
2520 e->me_maxreaders = DEFAULT_READERS;
2522 e->me_fd = INVALID_HANDLE_VALUE;
2523 e->me_lfd = INVALID_HANDLE_VALUE;
2524 e->me_mfd = INVALID_HANDLE_VALUE;
2525 #ifdef MDB_USE_POSIX_SEM
2526 e->me_rmutex = SEM_FAILED;
2527 e->me_wmutex = SEM_FAILED;
2529 e->me_pid = getpid();
2530 VGMEMP_CREATE(e,0,0);
2536 mdb_env_set_mapsize(MDB_env *env, size_t size)
2540 env->me_mapsize = size;
2542 env->me_maxpg = env->me_mapsize / env->me_psize;
2547 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2551 env->me_maxdbs = dbs;
2556 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2558 if (env->me_map || readers < 1)
2560 env->me_maxreaders = readers;
2565 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2567 if (!env || !readers)
2569 *readers = env->me_maxreaders;
2573 /** Further setup required for opening an MDB environment
2576 mdb_env_open2(MDB_env *env, unsigned int flags)
2578 int i, newenv = 0, prot;
2582 env->me_flags = flags;
2584 memset(&meta, 0, sizeof(meta));
2586 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2589 DPUTS("new mdbenv");
2593 if (!env->me_mapsize) {
2594 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2600 LONG sizelo, sizehi;
2601 sizelo = env->me_mapsize & 0xffffffff;
2602 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2604 /* Windows won't create mappings for zero length files.
2605 * Just allocate the maxsize right now.
2608 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2609 if (!SetEndOfFile(env->me_fd))
2611 SetFilePointer(env->me_fd, 0, NULL, 0);
2613 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
2614 PAGE_READWRITE : PAGE_READONLY,
2615 sizehi, sizelo, NULL);
2618 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
2619 FILE_MAP_WRITE : FILE_MAP_READ,
2620 0, 0, env->me_mapsize, meta.mm_address);
2627 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2630 if (flags & MDB_WRITEMAP) {
2632 ftruncate(env->me_fd, env->me_mapsize);
2634 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
2636 if (env->me_map == MAP_FAILED) {
2643 meta.mm_mapsize = env->me_mapsize;
2644 if (flags & MDB_FIXEDMAP)
2645 meta.mm_address = env->me_map;
2646 i = mdb_env_init_meta(env, &meta);
2647 if (i != MDB_SUCCESS) {
2651 env->me_psize = meta.mm_psize;
2653 env->me_maxpg = env->me_mapsize / env->me_psize;
2655 p = (MDB_page *)env->me_map;
2656 env->me_metas[0] = METADATA(p);
2657 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2661 int toggle = mdb_env_pick_meta(env);
2662 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2664 DPRINTF("opened database version %u, pagesize %u",
2665 env->me_metas[0]->mm_version, env->me_psize);
2666 DPRINTF("using meta page %d", toggle);
2667 DPRINTF("depth: %u", db->md_depth);
2668 DPRINTF("entries: %zu", db->md_entries);
2669 DPRINTF("branch pages: %zu", db->md_branch_pages);
2670 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2671 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2672 DPRINTF("root: %zu", db->md_root);
2680 /** Release a reader thread's slot in the reader lock table.
2681 * This function is called automatically when a thread exits.
2682 * @param[in] ptr This points to the slot in the reader lock table.
2685 mdb_env_reader_dest(void *ptr)
2687 MDB_reader *reader = ptr;
2693 /** Junk for arranging thread-specific callbacks on Windows. This is
2694 * necessarily platform and compiler-specific. Windows supports up
2695 * to 1088 keys. Let's assume nobody opens more than 64 environments
2696 * in a single process, for now. They can override this if needed.
2698 #ifndef MAX_TLS_KEYS
2699 #define MAX_TLS_KEYS 64
2701 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2702 static int mdb_tls_nkeys;
2704 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2708 case DLL_PROCESS_ATTACH: break;
2709 case DLL_THREAD_ATTACH: break;
2710 case DLL_THREAD_DETACH:
2711 for (i=0; i<mdb_tls_nkeys; i++) {
2712 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
2713 mdb_env_reader_dest(r);
2716 case DLL_PROCESS_DETACH: break;
2721 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2723 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2727 /* Force some symbol references.
2728 * _tls_used forces the linker to create the TLS directory if not already done
2729 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
2731 #pragma comment(linker, "/INCLUDE:_tls_used")
2732 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
2733 #pragma const_seg(".CRT$XLB")
2734 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
2735 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2738 #pragma comment(linker, "/INCLUDE:__tls_used")
2739 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
2740 #pragma data_seg(".CRT$XLB")
2741 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2743 #endif /* WIN 32/64 */
2744 #endif /* !__GNUC__ */
2747 /** Downgrade the exclusive lock on the region back to shared */
2749 mdb_env_share_locks(MDB_env *env, int *excl)
2751 int rc = 0, toggle = mdb_env_pick_meta(env);
2753 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2758 /* First acquire a shared lock. The Unlock will
2759 * then release the existing exclusive lock.
2761 memset(&ov, 0, sizeof(ov));
2762 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2763 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2768 struct flock lock_info;
2769 /* The shared lock replaces the existing lock */
2770 memset((void *)&lock_info, 0, sizeof(lock_info));
2771 lock_info.l_type = F_RDLCK;
2772 lock_info.l_whence = SEEK_SET;
2773 lock_info.l_start = 0;
2774 lock_info.l_len = 1;
2775 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
2776 (rc = ErrCode()) == EINTR) ;
2777 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
2784 /** Try to get exlusive lock, otherwise shared.
2785 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
2788 mdb_env_excl_lock(MDB_env *env, int *excl)
2792 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2796 memset(&ov, 0, sizeof(ov));
2797 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2802 struct flock lock_info;
2803 memset((void *)&lock_info, 0, sizeof(lock_info));
2804 lock_info.l_type = F_WRLCK;
2805 lock_info.l_whence = SEEK_SET;
2806 lock_info.l_start = 0;
2807 lock_info.l_len = 1;
2808 if (!fcntl(env->me_lfd, F_SETLK, &lock_info)) {
2811 # ifdef MDB_USE_POSIX_SEM
2812 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
2815 lock_info.l_type = F_RDLCK;
2816 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
2817 (rc = ErrCode()) == EINTR) ;
2825 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
2827 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2829 * @(#) $Revision: 5.1 $
2830 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2831 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2833 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2837 * Please do not copyright this code. This code is in the public domain.
2839 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2840 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2841 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2842 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2843 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2844 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2845 * PERFORMANCE OF THIS SOFTWARE.
2848 * chongo <Landon Curt Noll> /\oo/\
2849 * http://www.isthe.com/chongo/
2851 * Share and Enjoy! :-)
2854 typedef unsigned long long mdb_hash_t;
2855 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2857 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2858 * @param[in] str string to hash
2859 * @param[in] hval initial value for hash
2860 * @return 64 bit hash
2862 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2863 * hval arg on the first call.
2866 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
2868 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
2869 unsigned char *end = s + val->mv_size;
2871 * FNV-1a hash each octet of the string
2874 /* xor the bottom with the current octet */
2875 hval ^= (mdb_hash_t)*s++;
2877 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2878 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2879 (hval << 7) + (hval << 8) + (hval << 40);
2881 /* return our new hash value */
2885 /** Hash the string and output the hash in hex.
2886 * @param[in] str string to hash
2887 * @param[out] hexbuf an array of 17 chars to hold the hash
2890 mdb_hash_hex(MDB_val *val, char *hexbuf)
2893 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
2894 for (i=0; i<8; i++) {
2895 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2901 /** Open and/or initialize the lock region for the environment.
2902 * @param[in] env The MDB environment.
2903 * @param[in] lpath The pathname of the file used for the lock region.
2904 * @param[in] mode The Unix permissions for the file, if we create it.
2905 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
2906 * @return 0 on success, non-zero on failure.
2909 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2917 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2918 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2919 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2922 /* Try to get exclusive lock. If we succeed, then
2923 * nobody is using the lock region and we should initialize it.
2925 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
2926 size = GetFileSize(env->me_lfd, NULL);
2932 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1)
2934 /* Lose record locks when exec*() */
2935 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
2936 fcntl(env->me_lfd, F_SETFD, fdflags);
2938 #else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
2939 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1)
2943 /* Try to get exclusive lock. If we succeed, then
2944 * nobody is using the lock region and we should initialize it.
2946 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
2948 size = lseek(env->me_lfd, 0, SEEK_END);
2950 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2951 if (size < rsize && *excl > 0) {
2953 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2954 if (!SetEndOfFile(env->me_lfd)) goto fail_errno;
2956 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
2960 size = rsize - sizeof(MDB_txninfo);
2961 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2966 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2968 if (!mh) goto fail_errno;
2969 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2971 if (!env->me_txns) goto fail_errno;
2973 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2975 if (m == MAP_FAILED) goto fail_errno;
2981 BY_HANDLE_FILE_INFORMATION stbuf;
2990 if (!mdb_sec_inited) {
2991 InitializeSecurityDescriptor(&mdb_null_sd,
2992 SECURITY_DESCRIPTOR_REVISION);
2993 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2994 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2995 mdb_all_sa.bInheritHandle = FALSE;
2996 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2999 GetFileInformationByHandle(env->me_lfd, &stbuf);
3000 idbuf.volume = stbuf.dwVolumeSerialNumber;
3001 idbuf.nhigh = stbuf.nFileIndexHigh;
3002 idbuf.nlow = stbuf.nFileIndexLow;
3003 val.mv_data = &idbuf;
3004 val.mv_size = sizeof(idbuf);
3005 mdb_hash_hex(&val, hexbuf);
3006 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3007 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3008 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3009 if (!env->me_rmutex) goto fail_errno;
3010 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3011 if (!env->me_wmutex) goto fail_errno;
3012 #elif defined(MDB_USE_POSIX_SEM)
3021 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3022 idbuf.dev = stbuf.st_dev;
3023 idbuf.ino = stbuf.st_ino;
3024 val.mv_data = &idbuf;
3025 val.mv_size = sizeof(idbuf);
3026 mdb_hash_hex(&val, hexbuf);
3027 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3028 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3029 /* Clean up after a previous run, if needed: Try to
3030 * remove both semaphores before doing anything else.
3032 sem_unlink(env->me_txns->mti_rmname);
3033 sem_unlink(env->me_txns->mti_wmname);
3034 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3035 O_CREAT|O_EXCL, mode, 1);
3036 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3037 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3038 O_CREAT|O_EXCL, mode, 1);
3039 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3040 #else /* MDB_USE_POSIX_SEM */
3041 pthread_mutexattr_t mattr;
3043 if ((rc = pthread_mutexattr_init(&mattr))
3044 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3045 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3046 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3048 pthread_mutexattr_destroy(&mattr);
3049 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3051 env->me_txns->mti_version = MDB_VERSION;
3052 env->me_txns->mti_magic = MDB_MAGIC;
3053 env->me_txns->mti_txnid = 0;
3054 env->me_txns->mti_numreaders = 0;
3057 if (env->me_txns->mti_magic != MDB_MAGIC) {
3058 DPUTS("lock region has invalid magic");
3062 if (env->me_txns->mti_version != MDB_VERSION) {
3063 DPRINTF("lock region is version %u, expected version %u",
3064 env->me_txns->mti_version, MDB_VERSION);
3065 rc = MDB_VERSION_MISMATCH;
3069 if (rc != EACCES && rc != EAGAIN) {
3073 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3074 if (!env->me_rmutex) goto fail_errno;
3075 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3076 if (!env->me_wmutex) goto fail_errno;
3077 #elif defined(MDB_USE_POSIX_SEM)
3078 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3079 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3080 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3081 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3092 /** The name of the lock file in the DB environment */
3093 #define LOCKNAME "/lock.mdb"
3094 /** The name of the data file in the DB environment */
3095 #define DATANAME "/data.mdb"
3096 /** The suffix of the lock file when no subdir is used */
3097 #define LOCKSUFF "-lock"
3100 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
3102 int oflags, rc, len, excl;
3103 char *lpath, *dpath;
3105 if (env->me_fd != INVALID_HANDLE_VALUE)
3109 if (flags & MDB_NOSUBDIR) {
3110 rc = len + sizeof(LOCKSUFF) + len + 1;
3112 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3117 if (flags & MDB_NOSUBDIR) {
3118 dpath = lpath + len + sizeof(LOCKSUFF);
3119 sprintf(lpath, "%s" LOCKSUFF, path);
3120 strcpy(dpath, path);
3122 dpath = lpath + len + sizeof(LOCKNAME);
3123 sprintf(lpath, "%s" LOCKNAME, path);
3124 sprintf(dpath, "%s" DATANAME, path);
3127 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3131 /* silently ignore WRITEMAP if we're only getting read access */
3132 if (F_ISSET(flags, MDB_RDONLY) && F_ISSET(flags, MDB_WRITEMAP))
3133 flags ^= MDB_WRITEMAP;
3136 if (F_ISSET(flags, MDB_RDONLY)) {
3137 oflags = GENERIC_READ;
3138 len = OPEN_EXISTING;
3140 oflags = GENERIC_READ|GENERIC_WRITE;
3143 mode = FILE_ATTRIBUTE_NORMAL;
3144 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3145 NULL, len, mode, NULL);
3147 if (F_ISSET(flags, MDB_RDONLY))
3150 oflags = O_RDWR | O_CREAT;
3152 env->me_fd = open(dpath, oflags, mode);
3154 if (env->me_fd == INVALID_HANDLE_VALUE) {
3159 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
3160 if (flags & (MDB_RDONLY|MDB_NOSYNC|MDB_NOMETASYNC|MDB_WRITEMAP)) {
3161 env->me_mfd = env->me_fd;
3163 /* synchronous fd for meta writes */
3165 env->me_mfd = CreateFile(dpath, oflags,
3166 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3167 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3169 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3171 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3176 DPRINTF("opened dbenv %p", (void *) env);
3177 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3178 env->me_numdbs = 2; /* this notes that me_txkey was set */
3180 /* Windows TLS callbacks need help finding their TLS info. */
3181 if (mdb_tls_nkeys < MAX_TLS_KEYS)
3182 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3189 rc = mdb_env_share_locks(env, &excl);
3193 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3194 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3195 env->me_path = strdup(path);
3196 if (!env->me_dbxs || !env->me_dbflags || !env->me_path)
3202 mdb_env_close0(env, excl);
3208 /** Destroy resources from mdb_env_open() and clear our readers */
3210 mdb_env_close0(MDB_env *env, int excl)
3214 if (env->me_lfd == INVALID_HANDLE_VALUE) /* 1st field to get inited */
3217 free(env->me_dbflags);
3221 if (env->me_numdbs) {
3222 pthread_key_delete(env->me_txkey);
3224 /* Delete our key from the global list */
3225 for (i=0; i<mdb_tls_nkeys; i++)
3226 if (mdb_tls_keys[i] == env->me_txkey) {
3227 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3235 munmap(env->me_map, env->me_mapsize);
3237 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3239 if (env->me_fd != INVALID_HANDLE_VALUE)
3242 pid_t pid = env->me_pid;
3243 /* Clearing readers is done in this function because
3244 * me_txkey with its destructor must be disabled first.
3246 for (i = env->me_numreaders; --i >= 0; )
3247 if (env->me_txns->mti_readers[i].mr_pid == pid)
3248 env->me_txns->mti_readers[i].mr_pid = 0;
3250 if (env->me_rmutex) {
3251 CloseHandle(env->me_rmutex);
3252 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3254 /* Windows automatically destroys the mutexes when
3255 * the last handle closes.
3257 #elif defined(MDB_USE_POSIX_SEM)
3258 if (env->me_rmutex != SEM_FAILED) {
3259 sem_close(env->me_rmutex);
3260 if (env->me_wmutex != SEM_FAILED)
3261 sem_close(env->me_wmutex);
3262 /* If we have the filelock: If we are the
3263 * only remaining user, clean up semaphores.
3266 mdb_env_excl_lock(env, &excl);
3268 sem_unlink(env->me_txns->mti_rmname);
3269 sem_unlink(env->me_txns->mti_wmname);
3273 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3277 env->me_lfd = INVALID_HANDLE_VALUE; /* Mark env as reset */
3281 mdb_env_close(MDB_env *env)
3288 VGMEMP_DESTROY(env);
3289 while ((dp = env->me_dpages) != NULL) {
3290 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3291 env->me_dpages = dp->mp_next;
3295 mdb_env_close0(env, 0);
3296 mdb_midl_free(env->me_free_pgs);
3300 /** Compare two items pointing at aligned size_t's */
3302 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3304 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3305 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3308 /** Compare two items pointing at aligned int's */
3310 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3312 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3313 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3316 /** Compare two items pointing at ints of unknown alignment.
3317 * Nodes and keys are guaranteed to be 2-byte aligned.
3320 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3322 #if BYTE_ORDER == LITTLE_ENDIAN
3323 unsigned short *u, *c;
3326 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3327 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3330 } while(!x && u > (unsigned short *)a->mv_data);
3333 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3337 /** Compare two items lexically */
3339 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3346 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3352 diff = memcmp(a->mv_data, b->mv_data, len);
3353 return diff ? diff : len_diff<0 ? -1 : len_diff;
3356 /** Compare two items in reverse byte order */
3358 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3360 const unsigned char *p1, *p2, *p1_lim;
3364 p1_lim = (const unsigned char *)a->mv_data;
3365 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3366 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3368 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3374 while (p1 > p1_lim) {
3375 diff = *--p1 - *--p2;
3379 return len_diff<0 ? -1 : len_diff;
3382 /** Search for key within a page, using binary search.
3383 * Returns the smallest entry larger or equal to the key.
3384 * If exactp is non-null, stores whether the found entry was an exact match
3385 * in *exactp (1 or 0).
3386 * Updates the cursor index with the index of the found entry.
3387 * If no entry larger or equal to the key is found, returns NULL.
3390 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3392 unsigned int i = 0, nkeys;
3395 MDB_page *mp = mc->mc_pg[mc->mc_top];
3396 MDB_node *node = NULL;
3401 nkeys = NUMKEYS(mp);
3406 COPY_PGNO(pgno, mp->mp_pgno);
3407 DPRINTF("searching %u keys in %s %spage %zu",
3408 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3415 low = IS_LEAF(mp) ? 0 : 1;
3417 cmp = mc->mc_dbx->md_cmp;
3419 /* Branch pages have no data, so if using integer keys,
3420 * alignment is guaranteed. Use faster mdb_cmp_int.
3422 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3423 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3430 nodekey.mv_size = mc->mc_db->md_pad;
3431 node = NODEPTR(mp, 0); /* fake */
3432 while (low <= high) {
3433 i = (low + high) >> 1;
3434 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3435 rc = cmp(key, &nodekey);
3436 DPRINTF("found leaf index %u [%s], rc = %i",
3437 i, DKEY(&nodekey), rc);
3446 while (low <= high) {
3447 i = (low + high) >> 1;
3449 node = NODEPTR(mp, i);
3450 nodekey.mv_size = NODEKSZ(node);
3451 nodekey.mv_data = NODEKEY(node);
3453 rc = cmp(key, &nodekey);
3456 DPRINTF("found leaf index %u [%s], rc = %i",
3457 i, DKEY(&nodekey), rc);
3459 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3460 i, DKEY(&nodekey), NODEPGNO(node), rc);
3471 if (rc > 0) { /* Found entry is less than the key. */
3472 i++; /* Skip to get the smallest entry larger than key. */
3474 node = NODEPTR(mp, i);
3477 *exactp = (rc == 0);
3478 /* store the key index */
3479 mc->mc_ki[mc->mc_top] = i;
3481 /* There is no entry larger or equal to the key. */
3484 /* nodeptr is fake for LEAF2 */
3490 mdb_cursor_adjust(MDB_cursor *mc, func)
3494 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3495 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3502 /** Pop a page off the top of the cursor's stack. */
3504 mdb_cursor_pop(MDB_cursor *mc)
3508 MDB_page *top = mc->mc_pg[mc->mc_top];
3514 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3515 mc->mc_dbi, (void *) mc);
3519 /** Push a page onto the top of the cursor's stack. */
3521 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3523 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3524 mc->mc_dbi, (void *) mc);
3526 if (mc->mc_snum >= CURSOR_STACK) {
3527 assert(mc->mc_snum < CURSOR_STACK);
3528 return MDB_CURSOR_FULL;
3531 mc->mc_top = mc->mc_snum++;
3532 mc->mc_pg[mc->mc_top] = mp;
3533 mc->mc_ki[mc->mc_top] = 0;
3538 /** Find the address of the page corresponding to a given page number.
3539 * @param[in] txn the transaction for this access.
3540 * @param[in] pgno the page number for the page to retrieve.
3541 * @param[out] ret address of a pointer where the page's address will be stored.
3542 * @return 0 on success, non-zero on failure.
3545 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3549 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
3550 if (pgno < txn->mt_next_pgno)
3551 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3554 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3556 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3557 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3558 p = txn->mt_u.dirty_list[x].mptr;
3562 if (pgno < txn->mt_next_pgno)
3563 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3568 DPRINTF("page %zu not found", pgno);
3571 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3574 /** Search for the page a given key should be in.
3575 * Pushes parent pages on the cursor stack. This function continues a
3576 * search on a cursor that has already been initialized. (Usually by
3577 * #mdb_page_search() but also by #mdb_node_move().)
3578 * @param[in,out] mc the cursor for this operation.
3579 * @param[in] key the key to search for. If NULL, search for the lowest
3580 * page. (This is used by #mdb_cursor_first().)
3581 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
3582 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
3583 * @return 0 on success, non-zero on failure.
3586 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3588 MDB_page *mp = mc->mc_pg[mc->mc_top];
3593 while (IS_BRANCH(mp)) {
3597 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3598 assert(NUMKEYS(mp) > 1);
3599 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3601 if (key == NULL) /* Initialize cursor to first page. */
3603 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3604 /* cursor to last page */
3608 node = mdb_node_search(mc, key, &exact);
3610 i = NUMKEYS(mp) - 1;
3612 i = mc->mc_ki[mc->mc_top];
3621 DPRINTF("following index %u for key [%s]",
3623 assert(i < NUMKEYS(mp));
3624 node = NODEPTR(mp, i);
3626 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3629 mc->mc_ki[mc->mc_top] = i;
3630 if ((rc = mdb_cursor_push(mc, mp)))
3634 if ((rc = mdb_page_touch(mc)) != 0)
3636 mp = mc->mc_pg[mc->mc_top];
3641 DPRINTF("internal error, index points to a %02X page!?",
3643 return MDB_CORRUPTED;
3646 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3647 key ? DKEY(key) : NULL);
3652 /** Search for the page a given key should be in.
3653 * Pushes parent pages on the cursor stack. This function just sets up
3654 * the search; it finds the root page for \b mc's database and sets this
3655 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3656 * called to complete the search.
3657 * @param[in,out] mc the cursor for this operation.
3658 * @param[in] key the key to search for. If NULL, search for the lowest
3659 * page. (This is used by #mdb_cursor_first().)
3660 * @param[in] modify If true, visited pages are updated with new page numbers.
3661 * @return 0 on success, non-zero on failure.
3664 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
3669 /* Make sure the txn is still viable, then find the root from
3670 * the txn's db table.
3672 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3673 DPUTS("transaction has failed, must abort");
3676 /* Make sure we're using an up-to-date root */
3677 if (mc->mc_dbi > MAIN_DBI) {
3678 if ((*mc->mc_dbflag & DB_STALE) ||
3679 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
3681 unsigned char dbflag = 0;
3682 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3683 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
3686 if (*mc->mc_dbflag & DB_STALE) {
3689 MDB_node *leaf = mdb_node_search(&mc2,
3690 &mc->mc_dbx->md_name, &exact);
3692 return MDB_NOTFOUND;
3693 mdb_node_read(mc->mc_txn, leaf, &data);
3694 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3696 if (flags & MDB_PS_MODIFY)
3698 *mc->mc_dbflag = dbflag;
3701 root = mc->mc_db->md_root;
3703 if (root == P_INVALID) { /* Tree is empty. */
3704 DPUTS("tree is empty");
3705 return MDB_NOTFOUND;
3710 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
3711 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3717 DPRINTF("db %u root page %zu has flags 0x%X",
3718 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3720 if (flags & MDB_PS_MODIFY) {
3721 if ((rc = mdb_page_touch(mc)))
3725 if (flags & MDB_PS_ROOTONLY)
3728 return mdb_page_search_root(mc, key, flags);
3731 /** Return the data associated with a given node.
3732 * @param[in] txn The transaction for this operation.
3733 * @param[in] leaf The node being read.
3734 * @param[out] data Updated to point to the node's data.
3735 * @return 0 on success, non-zero on failure.
3738 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3740 MDB_page *omp; /* overflow page */
3744 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3745 data->mv_size = NODEDSZ(leaf);
3746 data->mv_data = NODEDATA(leaf);
3750 /* Read overflow data.
3752 data->mv_size = NODEDSZ(leaf);
3753 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3754 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3755 DPRINTF("read overflow page %zu failed", pgno);
3758 data->mv_data = METADATA(omp);
3764 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3765 MDB_val *key, MDB_val *data)
3774 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3776 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3779 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3783 mdb_cursor_init(&mc, txn, dbi, &mx);
3784 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3787 /** Find a sibling for a page.
3788 * Replaces the page at the top of the cursor's stack with the
3789 * specified sibling, if one exists.
3790 * @param[in] mc The cursor for this operation.
3791 * @param[in] move_right Non-zero if the right sibling is requested,
3792 * otherwise the left sibling.
3793 * @return 0 on success, non-zero on failure.
3796 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3802 if (mc->mc_snum < 2) {
3803 return MDB_NOTFOUND; /* root has no siblings */
3807 DPRINTF("parent page is page %zu, index %u",
3808 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3810 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3811 : (mc->mc_ki[mc->mc_top] == 0)) {
3812 DPRINTF("no more keys left, moving to %s sibling",
3813 move_right ? "right" : "left");
3814 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3818 mc->mc_ki[mc->mc_top]++;
3820 mc->mc_ki[mc->mc_top]--;
3821 DPRINTF("just moving to %s index key %u",
3822 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3824 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3826 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3827 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3830 mdb_cursor_push(mc, mp);
3835 /** Move the cursor to the next data item. */
3837 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3843 if (mc->mc_flags & C_EOF) {
3844 return MDB_NOTFOUND;
3847 assert(mc->mc_flags & C_INITIALIZED);
3849 mp = mc->mc_pg[mc->mc_top];
3851 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3852 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3853 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3854 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3855 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3856 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3860 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3861 if (op == MDB_NEXT_DUP)
3862 return MDB_NOTFOUND;
3866 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3868 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3869 DPUTS("=====> move to next sibling page");
3870 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3871 mc->mc_flags |= C_EOF;
3872 mc->mc_flags &= ~C_INITIALIZED;
3873 return MDB_NOTFOUND;
3875 mp = mc->mc_pg[mc->mc_top];
3876 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3878 mc->mc_ki[mc->mc_top]++;
3880 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3881 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3884 key->mv_size = mc->mc_db->md_pad;
3885 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3889 assert(IS_LEAF(mp));
3890 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3892 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3893 mdb_xcursor_init1(mc, leaf);
3896 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3899 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3900 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3901 if (rc != MDB_SUCCESS)
3906 MDB_GET_KEY(leaf, key);
3910 /** Move the cursor to the previous data item. */
3912 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3918 assert(mc->mc_flags & C_INITIALIZED);
3920 mp = mc->mc_pg[mc->mc_top];
3922 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3923 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3924 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3925 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3926 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3927 if (op != MDB_PREV || rc == MDB_SUCCESS)
3930 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3931 if (op == MDB_PREV_DUP)
3932 return MDB_NOTFOUND;
3937 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3939 if (mc->mc_ki[mc->mc_top] == 0) {
3940 DPUTS("=====> move to prev sibling page");
3941 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3942 mc->mc_flags &= ~C_INITIALIZED;
3943 return MDB_NOTFOUND;
3945 mp = mc->mc_pg[mc->mc_top];
3946 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3947 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3949 mc->mc_ki[mc->mc_top]--;
3951 mc->mc_flags &= ~C_EOF;
3953 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3954 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3957 key->mv_size = mc->mc_db->md_pad;
3958 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3962 assert(IS_LEAF(mp));
3963 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3965 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3966 mdb_xcursor_init1(mc, leaf);
3969 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3972 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3973 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3974 if (rc != MDB_SUCCESS)
3979 MDB_GET_KEY(leaf, key);
3983 /** Set the cursor on a specific data item. */
3985 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3986 MDB_cursor_op op, int *exactp)
3990 MDB_node *leaf = NULL;
3995 assert(key->mv_size > 0);
3997 /* See if we're already on the right page */
3998 if (mc->mc_flags & C_INITIALIZED) {
4001 mp = mc->mc_pg[mc->mc_top];
4003 mc->mc_ki[mc->mc_top] = 0;
4004 return MDB_NOTFOUND;
4006 if (mp->mp_flags & P_LEAF2) {
4007 nodekey.mv_size = mc->mc_db->md_pad;
4008 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4010 leaf = NODEPTR(mp, 0);
4011 MDB_GET_KEY(leaf, &nodekey);
4013 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4015 /* Probably happens rarely, but first node on the page
4016 * was the one we wanted.
4018 mc->mc_ki[mc->mc_top] = 0;
4025 unsigned int nkeys = NUMKEYS(mp);
4027 if (mp->mp_flags & P_LEAF2) {
4028 nodekey.mv_data = LEAF2KEY(mp,
4029 nkeys-1, nodekey.mv_size);
4031 leaf = NODEPTR(mp, nkeys-1);
4032 MDB_GET_KEY(leaf, &nodekey);
4034 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4036 /* last node was the one we wanted */
4037 mc->mc_ki[mc->mc_top] = nkeys-1;
4043 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4044 /* This is definitely the right page, skip search_page */
4045 if (mp->mp_flags & P_LEAF2) {
4046 nodekey.mv_data = LEAF2KEY(mp,
4047 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4049 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4050 MDB_GET_KEY(leaf, &nodekey);
4052 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4054 /* current node was the one we wanted */
4064 /* If any parents have right-sibs, search.
4065 * Otherwise, there's nothing further.
4067 for (i=0; i<mc->mc_top; i++)
4069 NUMKEYS(mc->mc_pg[i])-1)
4071 if (i == mc->mc_top) {
4072 /* There are no other pages */
4073 mc->mc_ki[mc->mc_top] = nkeys;
4074 return MDB_NOTFOUND;
4078 /* There are no other pages */
4079 mc->mc_ki[mc->mc_top] = 0;
4080 return MDB_NOTFOUND;
4084 rc = mdb_page_search(mc, key, 0);
4085 if (rc != MDB_SUCCESS)
4088 mp = mc->mc_pg[mc->mc_top];
4089 assert(IS_LEAF(mp));
4092 leaf = mdb_node_search(mc, key, exactp);
4093 if (exactp != NULL && !*exactp) {
4094 /* MDB_SET specified and not an exact match. */
4095 return MDB_NOTFOUND;
4099 DPUTS("===> inexact leaf not found, goto sibling");
4100 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
4101 return rc; /* no entries matched */
4102 mp = mc->mc_pg[mc->mc_top];
4103 assert(IS_LEAF(mp));
4104 leaf = NODEPTR(mp, 0);
4108 mc->mc_flags |= C_INITIALIZED;
4109 mc->mc_flags &= ~C_EOF;
4112 key->mv_size = mc->mc_db->md_pad;
4113 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4117 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4118 mdb_xcursor_init1(mc, leaf);
4121 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4122 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
4123 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4126 if (op == MDB_GET_BOTH) {
4132 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
4133 if (rc != MDB_SUCCESS)
4136 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
4138 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
4140 rc = mc->mc_dbx->md_dcmp(data, &d2);
4142 if (op == MDB_GET_BOTH || rc > 0)
4143 return MDB_NOTFOUND;
4148 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4149 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4154 /* The key already matches in all other cases */
4155 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
4156 MDB_GET_KEY(leaf, key);
4157 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
4162 /** Move the cursor to the first item in the database. */
4164 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4169 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4170 rc = mdb_page_search(mc, NULL, 0);
4171 if (rc != MDB_SUCCESS)
4174 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4176 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
4177 mc->mc_flags |= C_INITIALIZED;
4178 mc->mc_flags &= ~C_EOF;
4180 mc->mc_ki[mc->mc_top] = 0;
4182 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4183 key->mv_size = mc->mc_db->md_pad;
4184 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4189 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4190 mdb_xcursor_init1(mc, leaf);
4191 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4196 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4197 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4201 MDB_GET_KEY(leaf, key);
4205 /** Move the cursor to the last item in the database. */
4207 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4212 if (!(mc->mc_flags & C_EOF)) {
4214 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4217 lkey.mv_size = MAXKEYSIZE+1;
4218 lkey.mv_data = NULL;
4219 rc = mdb_page_search(mc, &lkey, 0);
4220 if (rc != MDB_SUCCESS)
4223 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4225 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4226 mc->mc_flags |= C_INITIALIZED|C_EOF;
4228 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4230 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4231 key->mv_size = mc->mc_db->md_pad;
4232 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4237 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4238 mdb_xcursor_init1(mc, leaf);
4239 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4244 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4245 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4250 MDB_GET_KEY(leaf, key);
4255 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4265 case MDB_GET_BOTH_RANGE:
4266 if (data == NULL || mc->mc_xcursor == NULL) {
4274 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4276 } else if (op == MDB_SET_RANGE)
4277 rc = mdb_cursor_set(mc, key, data, op, NULL);
4279 rc = mdb_cursor_set(mc, key, data, op, &exact);
4281 case MDB_GET_MULTIPLE:
4283 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4284 !(mc->mc_flags & C_INITIALIZED)) {
4289 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4290 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4293 case MDB_NEXT_MULTIPLE:
4295 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4299 if (!(mc->mc_flags & C_INITIALIZED))
4300 rc = mdb_cursor_first(mc, key, data);
4302 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4303 if (rc == MDB_SUCCESS) {
4304 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4307 mx = &mc->mc_xcursor->mx_cursor;
4308 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4310 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4311 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4319 case MDB_NEXT_NODUP:
4320 if (!(mc->mc_flags & C_INITIALIZED))
4321 rc = mdb_cursor_first(mc, key, data);
4323 rc = mdb_cursor_next(mc, key, data, op);
4327 case MDB_PREV_NODUP:
4328 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF)) {
4329 rc = mdb_cursor_last(mc, key, data);
4330 mc->mc_flags &= ~C_EOF;
4332 rc = mdb_cursor_prev(mc, key, data, op);
4335 rc = mdb_cursor_first(mc, key, data);
4339 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4340 !(mc->mc_flags & C_INITIALIZED) ||
4341 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4345 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4348 rc = mdb_cursor_last(mc, key, data);
4352 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4353 !(mc->mc_flags & C_INITIALIZED) ||
4354 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4358 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4361 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4369 /** Touch all the pages in the cursor stack.
4370 * Makes sure all the pages are writable, before attempting a write operation.
4371 * @param[in] mc The cursor to operate on.
4374 mdb_cursor_touch(MDB_cursor *mc)
4378 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4380 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4381 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4384 *mc->mc_dbflag = DB_DIRTY;
4386 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4387 rc = mdb_page_touch(mc);
4391 mc->mc_top = mc->mc_snum-1;
4396 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4399 MDB_node *leaf = NULL;
4400 MDB_val xdata, *rdata, dkey;
4403 int do_sub = 0, insert = 0;
4404 unsigned int mcount = 0;
4408 char dbuf[MAXKEYSIZE+1];
4409 unsigned int nflags;
4412 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4415 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4416 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4420 if (flags == MDB_CURRENT) {
4421 if (!(mc->mc_flags & C_INITIALIZED))
4424 } else if (mc->mc_db->md_root == P_INVALID) {
4426 /* new database, write a root leaf page */
4427 DPUTS("allocating new root leaf page");
4428 if ((rc = mdb_page_new(mc, P_LEAF, 1, &np))) {
4432 mdb_cursor_push(mc, np);
4433 mc->mc_db->md_root = np->mp_pgno;
4434 mc->mc_db->md_depth++;
4435 *mc->mc_dbflag = DB_DIRTY;
4436 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4438 np->mp_flags |= P_LEAF2;
4439 mc->mc_flags |= C_INITIALIZED;
4445 if (flags & MDB_APPEND) {
4447 rc = mdb_cursor_last(mc, &k2, &d2);
4449 rc = mc->mc_dbx->md_cmp(key, &k2);
4452 mc->mc_ki[mc->mc_top]++;
4458 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4460 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4461 DPRINTF("duplicate key [%s]", DKEY(key));
4463 return MDB_KEYEXIST;
4465 if (rc && rc != MDB_NOTFOUND)
4469 /* Cursor is positioned, now make sure all pages are writable */
4470 rc2 = mdb_cursor_touch(mc);
4475 /* The key already exists */
4476 if (rc == MDB_SUCCESS) {
4477 /* there's only a key anyway, so this is a no-op */
4478 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4479 unsigned int ksize = mc->mc_db->md_pad;
4480 if (key->mv_size != ksize)
4482 if (flags == MDB_CURRENT) {
4483 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4484 memcpy(ptr, key->mv_data, ksize);
4489 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4492 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4493 /* Was a single item before, must convert now */
4495 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4496 /* Just overwrite the current item */
4497 if (flags == MDB_CURRENT)
4500 dkey.mv_size = NODEDSZ(leaf);
4501 dkey.mv_data = NODEDATA(leaf);
4502 #if UINT_MAX < SIZE_MAX
4503 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4504 #ifdef MISALIGNED_OK
4505 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4507 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4510 /* if data matches, ignore it */
4511 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4512 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4514 /* create a fake page for the dup items */
4515 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4516 dkey.mv_data = dbuf;
4517 fp = (MDB_page *)&pbuf;
4518 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4519 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4520 fp->mp_lower = PAGEHDRSZ;
4521 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4522 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4523 fp->mp_flags |= P_LEAF2;
4524 fp->mp_pad = data->mv_size;
4525 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
4527 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4528 (dkey.mv_size & 1) + (data->mv_size & 1);
4530 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4533 xdata.mv_size = fp->mp_upper;
4538 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4539 /* See if we need to convert from fake page to subDB */
4541 unsigned int offset;
4544 fp = NODEDATA(leaf);
4545 if (flags == MDB_CURRENT) {
4547 fp->mp_flags |= P_DIRTY;
4548 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4549 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4553 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4554 offset = fp->mp_pad;
4555 if (SIZELEFT(fp) >= offset)
4557 offset *= 4; /* space for 4 more */
4559 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4561 offset += offset & 1;
4562 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4563 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4565 /* yes, convert it */
4567 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4568 dummy.md_pad = fp->mp_pad;
4569 dummy.md_flags = MDB_DUPFIXED;
4570 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4571 dummy.md_flags |= MDB_INTEGERKEY;
4574 dummy.md_branch_pages = 0;
4575 dummy.md_leaf_pages = 1;
4576 dummy.md_overflow_pages = 0;
4577 dummy.md_entries = NUMKEYS(fp);
4579 xdata.mv_size = sizeof(MDB_db);
4580 xdata.mv_data = &dummy;
4581 if ((rc = mdb_page_alloc(mc, 1, &mp)))
4583 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4584 flags |= F_DUPDATA|F_SUBDATA;
4585 dummy.md_root = mp->mp_pgno;
4587 /* no, just grow it */
4589 xdata.mv_size = NODEDSZ(leaf) + offset;
4590 xdata.mv_data = &pbuf;
4591 mp = (MDB_page *)&pbuf;
4592 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4595 mp->mp_flags = fp->mp_flags | P_DIRTY;
4596 mp->mp_pad = fp->mp_pad;
4597 mp->mp_lower = fp->mp_lower;
4598 mp->mp_upper = fp->mp_upper + offset;
4600 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4602 nsize = NODEDSZ(leaf) - fp->mp_upper;
4603 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4604 for (i=0; i<NUMKEYS(fp); i++)
4605 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4607 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4611 /* data is on sub-DB, just store it */
4612 flags |= F_DUPDATA|F_SUBDATA;
4616 /* overflow page overwrites need special handling */
4617 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4620 int ovpages, dpages;
4622 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4623 dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4624 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4625 mdb_page_get(mc->mc_txn, pg, &omp);
4626 /* Is the ov page writable and large enough? */
4627 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
4628 /* yes, overwrite it. Note in this case we don't
4629 * bother to try shrinking the node if the new data
4630 * is smaller than the overflow threshold.
4632 if (F_ISSET(flags, MDB_RESERVE))
4633 data->mv_data = METADATA(omp);
4635 memcpy(METADATA(omp), data->mv_data, data->mv_size);
4638 /* no, free ovpages */
4640 mc->mc_db->md_overflow_pages -= ovpages;
4641 for (i=0; i<ovpages; i++) {
4642 DPRINTF("freed ov page %zu", pg);
4643 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4647 } else if (NODEDSZ(leaf) == data->mv_size) {
4648 /* same size, just replace it. Note that we could
4649 * also reuse this node if the new data is smaller,
4650 * but instead we opt to shrink the node in that case.
4652 if (F_ISSET(flags, MDB_RESERVE))
4653 data->mv_data = NODEDATA(leaf);
4655 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4658 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4659 mc->mc_db->md_entries--;
4661 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4668 nflags = flags & NODE_ADD_FLAGS;
4669 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4670 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4671 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4672 nflags &= ~MDB_APPEND;
4674 nflags |= MDB_SPLIT_REPLACE;
4675 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4677 /* There is room already in this leaf page. */
4678 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4679 if (rc == 0 && !do_sub && insert) {
4680 /* Adjust other cursors pointing to mp */
4681 MDB_cursor *m2, *m3;
4682 MDB_dbi dbi = mc->mc_dbi;
4683 unsigned i = mc->mc_top;
4684 MDB_page *mp = mc->mc_pg[i];
4686 if (mc->mc_flags & C_SUB)
4689 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4690 if (mc->mc_flags & C_SUB)
4691 m3 = &m2->mc_xcursor->mx_cursor;
4694 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4695 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4702 if (rc != MDB_SUCCESS)
4703 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4705 /* Now store the actual data in the child DB. Note that we're
4706 * storing the user data in the keys field, so there are strict
4707 * size limits on dupdata. The actual data fields of the child
4708 * DB are all zero size.
4715 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4716 if (flags & MDB_CURRENT) {
4717 xflags = MDB_CURRENT;
4719 mdb_xcursor_init1(mc, leaf);
4720 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4722 /* converted, write the original data first */
4724 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4728 /* Adjust other cursors pointing to mp */
4730 unsigned i = mc->mc_top;
4731 MDB_page *mp = mc->mc_pg[i];
4733 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4734 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4735 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4736 mdb_xcursor_init1(m2, leaf);
4741 if (flags & MDB_APPENDDUP)
4742 xflags |= MDB_APPEND;
4743 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4744 if (flags & F_SUBDATA) {
4745 void *db = NODEDATA(leaf);
4746 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4749 /* sub-writes might have failed so check rc again.
4750 * Don't increment count if we just replaced an existing item.
4752 if (!rc && !(flags & MDB_CURRENT))
4753 mc->mc_db->md_entries++;
4754 if (flags & MDB_MULTIPLE) {
4756 if (mcount < data[1].mv_size) {
4757 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4758 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4768 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4773 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4776 if (!mc->mc_flags & C_INITIALIZED)
4779 rc = mdb_cursor_touch(mc);
4783 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4785 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4786 if (flags != MDB_NODUPDATA) {
4787 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4788 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4790 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4791 /* If sub-DB still has entries, we're done */
4792 if (mc->mc_xcursor->mx_db.md_entries) {
4793 if (leaf->mn_flags & F_SUBDATA) {
4794 /* update subDB info */
4795 void *db = NODEDATA(leaf);
4796 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4798 /* shrink fake page */
4799 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4801 mc->mc_db->md_entries--;
4804 /* otherwise fall thru and delete the sub-DB */
4807 if (leaf->mn_flags & F_SUBDATA) {
4808 /* add all the child DB's pages to the free list */
4809 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4810 if (rc == MDB_SUCCESS) {
4811 mc->mc_db->md_entries -=
4812 mc->mc_xcursor->mx_db.md_entries;
4817 return mdb_cursor_del0(mc, leaf);
4820 /** Allocate and initialize new pages for a database.
4821 * @param[in] mc a cursor on the database being added to.
4822 * @param[in] flags flags defining what type of page is being allocated.
4823 * @param[in] num the number of pages to allocate. This is usually 1,
4824 * unless allocating overflow pages for a large record.
4825 * @param[out] mp Address of a page, or NULL on failure.
4826 * @return 0 on success, non-zero on failure.
4829 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
4834 if ((rc = mdb_page_alloc(mc, num, &np)))
4836 DPRINTF("allocated new mpage %zu, page size %u",
4837 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4838 np->mp_flags = flags | P_DIRTY;
4839 np->mp_lower = PAGEHDRSZ;
4840 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4843 mc->mc_db->md_branch_pages++;
4844 else if (IS_LEAF(np))
4845 mc->mc_db->md_leaf_pages++;
4846 else if (IS_OVERFLOW(np)) {
4847 mc->mc_db->md_overflow_pages += num;
4855 /** Calculate the size of a leaf node.
4856 * The size depends on the environment's page size; if a data item
4857 * is too large it will be put onto an overflow page and the node
4858 * size will only include the key and not the data. Sizes are always
4859 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4860 * of the #MDB_node headers.
4861 * @param[in] env The environment handle.
4862 * @param[in] key The key for the node.
4863 * @param[in] data The data for the node.
4864 * @return The number of bytes needed to store the node.
4867 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4871 sz = LEAFSIZE(key, data);
4872 if (sz >= env->me_psize / MDB_MINKEYS) {
4873 /* put on overflow page */
4874 sz -= data->mv_size - sizeof(pgno_t);
4878 return sz + sizeof(indx_t);
4881 /** Calculate the size of a branch node.
4882 * The size should depend on the environment's page size but since
4883 * we currently don't support spilling large keys onto overflow
4884 * pages, it's simply the size of the #MDB_node header plus the
4885 * size of the key. Sizes are always rounded up to an even number
4886 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4887 * @param[in] env The environment handle.
4888 * @param[in] key The key for the node.
4889 * @return The number of bytes needed to store the node.
4892 mdb_branch_size(MDB_env *env, MDB_val *key)
4897 if (sz >= env->me_psize / MDB_MINKEYS) {
4898 /* put on overflow page */
4899 /* not implemented */
4900 /* sz -= key->size - sizeof(pgno_t); */
4903 return sz + sizeof(indx_t);
4906 /** Add a node to the page pointed to by the cursor.
4907 * @param[in] mc The cursor for this operation.
4908 * @param[in] indx The index on the page where the new node should be added.
4909 * @param[in] key The key for the new node.
4910 * @param[in] data The data for the new node, if any.
4911 * @param[in] pgno The page number, if adding a branch node.
4912 * @param[in] flags Flags for the node.
4913 * @return 0 on success, non-zero on failure. Possible errors are:
4915 * <li>ENOMEM - failed to allocate overflow pages for the node.
4916 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
4917 * should never happen since all callers already calculate the
4918 * page's free space before calling this function.
4922 mdb_node_add(MDB_cursor *mc, indx_t indx,
4923 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4926 size_t node_size = NODESIZE;
4929 MDB_page *mp = mc->mc_pg[mc->mc_top];
4930 MDB_page *ofp = NULL; /* overflow page */
4933 assert(mp->mp_upper >= mp->mp_lower);
4935 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4936 IS_LEAF(mp) ? "leaf" : "branch",
4937 IS_SUBP(mp) ? "sub-" : "",
4938 mp->mp_pgno, indx, data ? data->mv_size : 0,
4939 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4942 /* Move higher keys up one slot. */
4943 int ksize = mc->mc_db->md_pad, dif;
4944 char *ptr = LEAF2KEY(mp, indx, ksize);
4945 dif = NUMKEYS(mp) - indx;
4947 memmove(ptr+ksize, ptr, dif*ksize);
4948 /* insert new key */
4949 memcpy(ptr, key->mv_data, ksize);
4951 /* Just using these for counting */
4952 mp->mp_lower += sizeof(indx_t);
4953 mp->mp_upper -= ksize - sizeof(indx_t);
4958 node_size += key->mv_size;
4962 if (F_ISSET(flags, F_BIGDATA)) {
4963 /* Data already on overflow page. */
4964 node_size += sizeof(pgno_t);
4965 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4966 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4968 /* Put data on overflow page. */
4969 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4970 data->mv_size, node_size+data->mv_size);
4971 node_size += sizeof(pgno_t);
4972 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
4974 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4977 node_size += data->mv_size;
4980 node_size += node_size & 1;
4982 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4983 DPRINTF("not enough room in page %zu, got %u ptrs",
4984 mp->mp_pgno, NUMKEYS(mp));
4985 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4986 mp->mp_upper - mp->mp_lower);
4987 DPRINTF("node size = %zu", node_size);
4988 return MDB_PAGE_FULL;
4991 /* Move higher pointers up one slot. */
4992 for (i = NUMKEYS(mp); i > indx; i--)
4993 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4995 /* Adjust free space offsets. */
4996 ofs = mp->mp_upper - node_size;
4997 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4998 mp->mp_ptrs[indx] = ofs;
5000 mp->mp_lower += sizeof(indx_t);
5002 /* Write the node data. */
5003 node = NODEPTR(mp, indx);
5004 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
5005 node->mn_flags = flags;
5007 SETDSZ(node,data->mv_size);
5012 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5017 if (F_ISSET(flags, F_BIGDATA))
5018 memcpy(node->mn_data + key->mv_size, data->mv_data,
5020 else if (F_ISSET(flags, MDB_RESERVE))
5021 data->mv_data = node->mn_data + key->mv_size;
5023 memcpy(node->mn_data + key->mv_size, data->mv_data,
5026 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
5028 if (F_ISSET(flags, MDB_RESERVE))
5029 data->mv_data = METADATA(ofp);
5031 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
5038 /** Delete the specified node from a page.
5039 * @param[in] mp The page to operate on.
5040 * @param[in] indx The index of the node to delete.
5041 * @param[in] ksize The size of a node. Only used if the page is
5042 * part of a #MDB_DUPFIXED database.
5045 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
5048 indx_t i, j, numkeys, ptr;
5055 COPY_PGNO(pgno, mp->mp_pgno);
5056 DPRINTF("delete node %u on %s page %zu", indx,
5057 IS_LEAF(mp) ? "leaf" : "branch", pgno);
5060 assert(indx < NUMKEYS(mp));
5063 int x = NUMKEYS(mp) - 1 - indx;
5064 base = LEAF2KEY(mp, indx, ksize);
5066 memmove(base, base + ksize, x * ksize);
5067 mp->mp_lower -= sizeof(indx_t);
5068 mp->mp_upper += ksize - sizeof(indx_t);
5072 node = NODEPTR(mp, indx);
5073 sz = NODESIZE + node->mn_ksize;
5075 if (F_ISSET(node->mn_flags, F_BIGDATA))
5076 sz += sizeof(pgno_t);
5078 sz += NODEDSZ(node);
5082 ptr = mp->mp_ptrs[indx];
5083 numkeys = NUMKEYS(mp);
5084 for (i = j = 0; i < numkeys; i++) {
5086 mp->mp_ptrs[j] = mp->mp_ptrs[i];
5087 if (mp->mp_ptrs[i] < ptr)
5088 mp->mp_ptrs[j] += sz;
5093 base = (char *)mp + mp->mp_upper;
5094 memmove(base + sz, base, ptr - mp->mp_upper);
5096 mp->mp_lower -= sizeof(indx_t);
5100 /** Compact the main page after deleting a node on a subpage.
5101 * @param[in] mp The main page to operate on.
5102 * @param[in] indx The index of the subpage on the main page.
5105 mdb_node_shrink(MDB_page *mp, indx_t indx)
5112 indx_t i, numkeys, ptr;
5114 node = NODEPTR(mp, indx);
5115 sp = (MDB_page *)NODEDATA(node);
5116 osize = NODEDSZ(node);
5118 delta = sp->mp_upper - sp->mp_lower;
5119 SETDSZ(node, osize - delta);
5120 xp = (MDB_page *)((char *)sp + delta);
5122 /* shift subpage upward */
5124 nsize = NUMKEYS(sp) * sp->mp_pad;
5125 memmove(METADATA(xp), METADATA(sp), nsize);
5128 nsize = osize - sp->mp_upper;
5129 numkeys = NUMKEYS(sp);
5130 for (i=numkeys-1; i>=0; i--)
5131 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
5133 xp->mp_upper = sp->mp_lower;
5134 xp->mp_lower = sp->mp_lower;
5135 xp->mp_flags = sp->mp_flags;
5136 xp->mp_pad = sp->mp_pad;
5137 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
5139 /* shift lower nodes upward */
5140 ptr = mp->mp_ptrs[indx];
5141 numkeys = NUMKEYS(mp);
5142 for (i = 0; i < numkeys; i++) {
5143 if (mp->mp_ptrs[i] <= ptr)
5144 mp->mp_ptrs[i] += delta;
5147 base = (char *)mp + mp->mp_upper;
5148 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
5149 mp->mp_upper += delta;
5152 /** Initial setup of a sorted-dups cursor.
5153 * Sorted duplicates are implemented as a sub-database for the given key.
5154 * The duplicate data items are actually keys of the sub-database.
5155 * Operations on the duplicate data items are performed using a sub-cursor
5156 * initialized when the sub-database is first accessed. This function does
5157 * the preliminary setup of the sub-cursor, filling in the fields that
5158 * depend only on the parent DB.
5159 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5162 mdb_xcursor_init0(MDB_cursor *mc)
5164 MDB_xcursor *mx = mc->mc_xcursor;
5166 mx->mx_cursor.mc_xcursor = NULL;
5167 mx->mx_cursor.mc_txn = mc->mc_txn;
5168 mx->mx_cursor.mc_db = &mx->mx_db;
5169 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
5170 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
5171 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
5172 mx->mx_cursor.mc_snum = 0;
5173 mx->mx_cursor.mc_top = 0;
5174 mx->mx_cursor.mc_flags = C_SUB;
5175 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
5176 mx->mx_dbx.md_dcmp = NULL;
5177 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
5180 /** Final setup of a sorted-dups cursor.
5181 * Sets up the fields that depend on the data from the main cursor.
5182 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5183 * @param[in] node The data containing the #MDB_db record for the
5184 * sorted-dup database.
5187 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5189 MDB_xcursor *mx = mc->mc_xcursor;
5191 if (node->mn_flags & F_SUBDATA) {
5192 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5193 mx->mx_cursor.mc_pg[0] = 0;
5194 mx->mx_cursor.mc_snum = 0;
5195 mx->mx_cursor.mc_flags = C_SUB;
5197 MDB_page *fp = NODEDATA(node);
5198 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5199 mx->mx_db.md_flags = 0;
5200 mx->mx_db.md_depth = 1;
5201 mx->mx_db.md_branch_pages = 0;
5202 mx->mx_db.md_leaf_pages = 1;
5203 mx->mx_db.md_overflow_pages = 0;
5204 mx->mx_db.md_entries = NUMKEYS(fp);
5205 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5206 mx->mx_cursor.mc_snum = 1;
5207 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5208 mx->mx_cursor.mc_top = 0;
5209 mx->mx_cursor.mc_pg[0] = fp;
5210 mx->mx_cursor.mc_ki[0] = 0;
5211 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5212 mx->mx_db.md_flags = MDB_DUPFIXED;
5213 mx->mx_db.md_pad = fp->mp_pad;
5214 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5215 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5218 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5220 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
5222 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5223 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5224 #if UINT_MAX < SIZE_MAX
5225 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5226 #ifdef MISALIGNED_OK
5227 mx->mx_dbx.md_cmp = mdb_cmp_long;
5229 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5234 /** Initialize a cursor for a given transaction and database. */
5236 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5241 mc->mc_db = &txn->mt_dbs[dbi];
5242 mc->mc_dbx = &txn->mt_dbxs[dbi];
5243 mc->mc_dbflag = &txn->mt_dbflags[dbi];
5248 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5250 mc->mc_xcursor = mx;
5251 mdb_xcursor_init0(mc);
5253 mc->mc_xcursor = NULL;
5255 if (*mc->mc_dbflag & DB_STALE) {
5256 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5261 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5264 MDB_xcursor *mx = NULL;
5265 size_t size = sizeof(MDB_cursor);
5267 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
5270 /* Allow read access to the freelist */
5271 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5274 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5275 size += sizeof(MDB_xcursor);
5277 if ((mc = malloc(size)) != NULL) {
5278 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5279 mx = (MDB_xcursor *)(mc + 1);
5281 mdb_cursor_init(mc, txn, dbi, mx);
5282 if (txn->mt_cursors) {
5283 mc->mc_next = txn->mt_cursors[dbi];
5284 txn->mt_cursors[dbi] = mc;
5286 mc->mc_flags |= C_ALLOCD;
5297 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
5299 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
5302 if (txn->mt_cursors)
5305 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
5309 /* Return the count of duplicate data items for the current key */
5311 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5315 if (mc == NULL || countp == NULL)
5318 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5321 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5322 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5325 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5328 *countp = mc->mc_xcursor->mx_db.md_entries;
5334 mdb_cursor_close(MDB_cursor *mc)
5337 /* remove from txn, if tracked */
5338 if (mc->mc_txn->mt_cursors) {
5339 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5340 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5342 *prev = mc->mc_next;
5344 if (mc->mc_flags & C_ALLOCD)
5350 mdb_cursor_txn(MDB_cursor *mc)
5352 if (!mc) return NULL;
5357 mdb_cursor_dbi(MDB_cursor *mc)
5363 /** Replace the key for a node with a new key.
5364 * @param[in] mp The page containing the node to operate on.
5365 * @param[in] indx The index of the node to operate on.
5366 * @param[in] key The new key to use.
5367 * @return 0 on success, non-zero on failure.
5370 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5376 indx_t ptr, i, numkeys;
5379 node = NODEPTR(mp, indx);
5380 ptr = mp->mp_ptrs[indx];
5384 char kbuf2[(MAXKEYSIZE*2+1)];
5385 k2.mv_data = NODEKEY(node);
5386 k2.mv_size = node->mn_ksize;
5387 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5389 mdb_dkey(&k2, kbuf2),
5395 delta0 = delta = key->mv_size - node->mn_ksize;
5397 /* Must be 2-byte aligned. If new key is
5398 * shorter by 1, the shift will be skipped.
5400 delta += (delta & 1);
5402 if (delta > 0 && SIZELEFT(mp) < delta) {
5403 DPRINTF("OUCH! Not enough room, delta = %d", delta);
5404 return MDB_PAGE_FULL;
5407 numkeys = NUMKEYS(mp);
5408 for (i = 0; i < numkeys; i++) {
5409 if (mp->mp_ptrs[i] <= ptr)
5410 mp->mp_ptrs[i] -= delta;
5413 base = (char *)mp + mp->mp_upper;
5414 len = ptr - mp->mp_upper + NODESIZE;
5415 memmove(base - delta, base, len);
5416 mp->mp_upper -= delta;
5418 node = NODEPTR(mp, indx);
5421 /* But even if no shift was needed, update ksize */
5423 node->mn_ksize = key->mv_size;
5426 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5431 /** Move a node from csrc to cdst.
5434 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5440 unsigned short flags;
5444 /* Mark src and dst as dirty. */
5445 if ((rc = mdb_page_touch(csrc)) ||
5446 (rc = mdb_page_touch(cdst)))
5449 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5450 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5451 key.mv_size = csrc->mc_db->md_pad;
5452 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5454 data.mv_data = NULL;
5458 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5459 assert(!((long)srcnode&1));
5460 srcpg = NODEPGNO(srcnode);
5461 flags = srcnode->mn_flags;
5462 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5463 unsigned int snum = csrc->mc_snum;
5465 /* must find the lowest key below src */
5466 mdb_page_search_root(csrc, NULL, 0);
5467 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5468 key.mv_size = csrc->mc_db->md_pad;
5469 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5471 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5472 key.mv_size = NODEKSZ(s2);
5473 key.mv_data = NODEKEY(s2);
5475 csrc->mc_snum = snum--;
5476 csrc->mc_top = snum;
5478 key.mv_size = NODEKSZ(srcnode);
5479 key.mv_data = NODEKEY(srcnode);
5481 data.mv_size = NODEDSZ(srcnode);
5482 data.mv_data = NODEDATA(srcnode);
5484 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5485 unsigned int snum = cdst->mc_snum;
5488 /* must find the lowest key below dst */
5489 mdb_page_search_root(cdst, NULL, 0);
5490 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
5491 bkey.mv_size = cdst->mc_db->md_pad;
5492 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
5494 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5495 bkey.mv_size = NODEKSZ(s2);
5496 bkey.mv_data = NODEKEY(s2);
5498 cdst->mc_snum = snum--;
5499 cdst->mc_top = snum;
5500 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5503 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5504 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5505 csrc->mc_ki[csrc->mc_top],
5507 csrc->mc_pg[csrc->mc_top]->mp_pgno,
5508 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5510 /* Add the node to the destination page.
5512 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5513 if (rc != MDB_SUCCESS)
5516 /* Delete the node from the source page.
5518 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5521 /* Adjust other cursors pointing to mp */
5522 MDB_cursor *m2, *m3;
5523 MDB_dbi dbi = csrc->mc_dbi;
5524 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5526 if (csrc->mc_flags & C_SUB)
5529 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5530 if (m2 == csrc) continue;
5531 if (csrc->mc_flags & C_SUB)
5532 m3 = &m2->mc_xcursor->mx_cursor;
5535 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5536 csrc->mc_ki[csrc->mc_top]) {
5537 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5538 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5543 /* Update the parent separators.
5545 if (csrc->mc_ki[csrc->mc_top] == 0) {
5546 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5547 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5548 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5550 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5551 key.mv_size = NODEKSZ(srcnode);
5552 key.mv_data = NODEKEY(srcnode);
5554 DPRINTF("update separator for source page %zu to [%s]",
5555 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5556 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5557 &key)) != MDB_SUCCESS)
5560 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5562 nullkey.mv_size = 0;
5563 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5564 assert(rc == MDB_SUCCESS);
5568 if (cdst->mc_ki[cdst->mc_top] == 0) {
5569 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5570 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5571 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5573 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5574 key.mv_size = NODEKSZ(srcnode);
5575 key.mv_data = NODEKEY(srcnode);
5577 DPRINTF("update separator for destination page %zu to [%s]",
5578 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5579 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5580 &key)) != MDB_SUCCESS)
5583 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5585 nullkey.mv_size = 0;
5586 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5587 assert(rc == MDB_SUCCESS);
5594 /** Merge one page into another.
5595 * The nodes from the page pointed to by \b csrc will
5596 * be copied to the page pointed to by \b cdst and then
5597 * the \b csrc page will be freed.
5598 * @param[in] csrc Cursor pointing to the source page.
5599 * @param[in] cdst Cursor pointing to the destination page.
5602 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5610 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5611 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5613 assert(csrc->mc_snum > 1); /* can't merge root page */
5614 assert(cdst->mc_snum > 1);
5616 /* Mark dst as dirty. */
5617 if ((rc = mdb_page_touch(cdst)))
5620 /* Move all nodes from src to dst.
5622 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5623 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5624 key.mv_size = csrc->mc_db->md_pad;
5625 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5626 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5627 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5628 if (rc != MDB_SUCCESS)
5630 key.mv_data = (char *)key.mv_data + key.mv_size;
5633 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5634 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5635 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5636 unsigned int snum = csrc->mc_snum;
5638 /* must find the lowest key below src */
5639 mdb_page_search_root(csrc, NULL, 0);
5640 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5641 key.mv_size = csrc->mc_db->md_pad;
5642 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5644 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5645 key.mv_size = NODEKSZ(s2);
5646 key.mv_data = NODEKEY(s2);
5648 csrc->mc_snum = snum--;
5649 csrc->mc_top = snum;
5651 key.mv_size = srcnode->mn_ksize;
5652 key.mv_data = NODEKEY(srcnode);
5655 data.mv_size = NODEDSZ(srcnode);
5656 data.mv_data = NODEDATA(srcnode);
5657 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5658 if (rc != MDB_SUCCESS)
5663 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5664 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]), (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10);
5666 /* Unlink the src page from parent and add to free list.
5668 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5669 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5671 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5675 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5676 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5677 csrc->mc_db->md_leaf_pages--;
5679 csrc->mc_db->md_branch_pages--;
5681 /* Adjust other cursors pointing to mp */
5682 MDB_cursor *m2, *m3;
5683 MDB_dbi dbi = csrc->mc_dbi;
5684 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5686 if (csrc->mc_flags & C_SUB)
5689 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5690 if (csrc->mc_flags & C_SUB)
5691 m3 = &m2->mc_xcursor->mx_cursor;
5694 if (m3 == csrc) continue;
5695 if (m3->mc_snum < csrc->mc_snum) continue;
5696 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5697 m3->mc_pg[csrc->mc_top] = mp;
5698 m3->mc_ki[csrc->mc_top] += nkeys;
5702 mdb_cursor_pop(csrc);
5704 return mdb_rebalance(csrc);
5707 /** Copy the contents of a cursor.
5708 * @param[in] csrc The cursor to copy from.
5709 * @param[out] cdst The cursor to copy to.
5712 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5716 cdst->mc_txn = csrc->mc_txn;
5717 cdst->mc_dbi = csrc->mc_dbi;
5718 cdst->mc_db = csrc->mc_db;
5719 cdst->mc_dbx = csrc->mc_dbx;
5720 cdst->mc_snum = csrc->mc_snum;
5721 cdst->mc_top = csrc->mc_top;
5722 cdst->mc_flags = csrc->mc_flags;
5724 for (i=0; i<csrc->mc_snum; i++) {
5725 cdst->mc_pg[i] = csrc->mc_pg[i];
5726 cdst->mc_ki[i] = csrc->mc_ki[i];
5730 /** Rebalance the tree after a delete operation.
5731 * @param[in] mc Cursor pointing to the page where rebalancing
5733 * @return 0 on success, non-zero on failure.
5736 mdb_rebalance(MDB_cursor *mc)
5746 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5747 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5748 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5749 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5753 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5756 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5757 DPRINTF("no need to rebalance page %zu, above fill threshold",
5763 if (mc->mc_snum < 2) {
5764 MDB_page *mp = mc->mc_pg[0];
5765 if (NUMKEYS(mp) == 0) {
5766 DPUTS("tree is completely empty");
5767 mc->mc_db->md_root = P_INVALID;
5768 mc->mc_db->md_depth = 0;
5769 mc->mc_db->md_leaf_pages = 0;
5770 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5774 /* Adjust other cursors pointing to mp */
5775 MDB_cursor *m2, *m3;
5776 MDB_dbi dbi = mc->mc_dbi;
5778 if (mc->mc_flags & C_SUB)
5781 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5782 if (m2 == mc) continue;
5783 if (mc->mc_flags & C_SUB)
5784 m3 = &m2->mc_xcursor->mx_cursor;
5787 if (m3->mc_snum < mc->mc_snum) continue;
5788 if (m3->mc_pg[0] == mp) {
5794 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5795 DPUTS("collapsing root page!");
5796 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5797 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5798 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5801 mc->mc_db->md_depth--;
5802 mc->mc_db->md_branch_pages--;
5804 /* Adjust other cursors pointing to mp */
5805 MDB_cursor *m2, *m3;
5806 MDB_dbi dbi = mc->mc_dbi;
5808 if (mc->mc_flags & C_SUB)
5811 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5812 if (m2 == mc) continue;
5813 if (mc->mc_flags & C_SUB)
5814 m3 = &m2->mc_xcursor->mx_cursor;
5817 if (m3->mc_snum < mc->mc_snum) continue;
5818 if (m3->mc_pg[0] == mp) {
5819 m3->mc_pg[0] = mc->mc_pg[0];
5824 DPUTS("root page doesn't need rebalancing");
5828 /* The parent (branch page) must have at least 2 pointers,
5829 * otherwise the tree is invalid.
5831 ptop = mc->mc_top-1;
5832 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5834 /* Leaf page fill factor is below the threshold.
5835 * Try to move keys from left or right neighbor, or
5836 * merge with a neighbor page.
5841 mdb_cursor_copy(mc, &mn);
5842 mn.mc_xcursor = NULL;
5844 if (mc->mc_ki[ptop] == 0) {
5845 /* We're the leftmost leaf in our parent.
5847 DPUTS("reading right neighbor");
5849 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5850 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5852 mn.mc_ki[mn.mc_top] = 0;
5853 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5855 /* There is at least one neighbor to the left.
5857 DPUTS("reading left neighbor");
5859 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5860 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5862 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5863 mc->mc_ki[mc->mc_top] = 0;
5866 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5867 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10);
5869 /* If the neighbor page is above threshold and has at least two
5870 * keys, move one key from it.
5872 * Otherwise we should try to merge them.
5874 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5875 return mdb_node_move(&mn, mc);
5876 else { /* FIXME: if (has_enough_room()) */
5877 mc->mc_flags &= ~C_INITIALIZED;
5878 if (mc->mc_ki[ptop] == 0)
5879 return mdb_page_merge(&mn, mc);
5881 return mdb_page_merge(mc, &mn);
5885 /** Complete a delete operation started by #mdb_cursor_del(). */
5887 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5891 /* add overflow pages to free list */
5892 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5896 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5897 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5898 mc->mc_db->md_overflow_pages -= ovpages;
5899 for (i=0; i<ovpages; i++) {
5900 DPRINTF("freed ov page %zu", pg);
5901 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5905 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5906 mc->mc_db->md_entries--;
5907 rc = mdb_rebalance(mc);
5908 if (rc != MDB_SUCCESS)
5909 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5915 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5916 MDB_val *key, MDB_val *data)
5921 MDB_val rdata, *xdata;
5925 assert(key != NULL);
5927 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5929 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5932 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5936 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5940 mdb_cursor_init(&mc, txn, dbi, &mx);
5951 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5953 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5957 /** Split a page and insert a new node.
5958 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5959 * The cursor will be updated to point to the actual page and index where
5960 * the node got inserted after the split.
5961 * @param[in] newkey The key for the newly inserted node.
5962 * @param[in] newdata The data for the newly inserted node.
5963 * @param[in] newpgno The page number, if the new node is a branch node.
5964 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
5965 * @return 0 on success, non-zero on failure.
5968 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5969 unsigned int nflags)
5972 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
5975 unsigned int i, j, split_indx, nkeys, pmax;
5977 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5979 MDB_page *mp, *rp, *pp;
5984 mp = mc->mc_pg[mc->mc_top];
5985 newindx = mc->mc_ki[mc->mc_top];
5987 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5988 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5989 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5991 /* Create a right sibling. */
5992 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
5994 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5996 if (mc->mc_snum < 2) {
5997 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
5999 /* shift current top to make room for new parent */
6000 mc->mc_pg[1] = mc->mc_pg[0];
6001 mc->mc_ki[1] = mc->mc_ki[0];
6004 mc->mc_db->md_root = pp->mp_pgno;
6005 DPRINTF("root split! new root = %zu", pp->mp_pgno);
6006 mc->mc_db->md_depth++;
6009 /* Add left (implicit) pointer. */
6010 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
6011 /* undo the pre-push */
6012 mc->mc_pg[0] = mc->mc_pg[1];
6013 mc->mc_ki[0] = mc->mc_ki[1];
6014 mc->mc_db->md_root = mp->mp_pgno;
6015 mc->mc_db->md_depth--;
6022 ptop = mc->mc_top-1;
6023 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
6026 mc->mc_flags |= C_SPLITTING;
6027 mdb_cursor_copy(mc, &mn);
6028 mn.mc_pg[mn.mc_top] = rp;
6029 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
6031 if (nflags & MDB_APPEND) {
6032 mn.mc_ki[mn.mc_top] = 0;
6034 split_indx = newindx;
6039 nkeys = NUMKEYS(mp);
6040 split_indx = nkeys / 2;
6041 if (newindx < split_indx)
6047 unsigned int lsize, rsize, ksize;
6048 /* Move half of the keys to the right sibling */
6050 x = mc->mc_ki[mc->mc_top] - split_indx;
6051 ksize = mc->mc_db->md_pad;
6052 split = LEAF2KEY(mp, split_indx, ksize);
6053 rsize = (nkeys - split_indx) * ksize;
6054 lsize = (nkeys - split_indx) * sizeof(indx_t);
6055 mp->mp_lower -= lsize;
6056 rp->mp_lower += lsize;
6057 mp->mp_upper += rsize - lsize;
6058 rp->mp_upper -= rsize - lsize;
6059 sepkey.mv_size = ksize;
6060 if (newindx == split_indx) {
6061 sepkey.mv_data = newkey->mv_data;
6063 sepkey.mv_data = split;
6066 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
6067 memcpy(rp->mp_ptrs, split, rsize);
6068 sepkey.mv_data = rp->mp_ptrs;
6069 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
6070 memcpy(ins, newkey->mv_data, ksize);
6071 mp->mp_lower += sizeof(indx_t);
6072 mp->mp_upper -= ksize - sizeof(indx_t);
6075 memcpy(rp->mp_ptrs, split, x * ksize);
6076 ins = LEAF2KEY(rp, x, ksize);
6077 memcpy(ins, newkey->mv_data, ksize);
6078 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
6079 rp->mp_lower += sizeof(indx_t);
6080 rp->mp_upper -= ksize - sizeof(indx_t);
6081 mc->mc_ki[mc->mc_top] = x;
6082 mc->mc_pg[mc->mc_top] = rp;
6087 /* For leaf pages, check the split point based on what
6088 * fits where, since otherwise mdb_node_add can fail.
6090 * This check is only needed when the data items are
6091 * relatively large, such that being off by one will
6092 * make the difference between success or failure.
6093 * When the size of the data items is much smaller than
6094 * one-half of a page, this check is irrelevant.
6097 unsigned int psize, nsize;
6098 /* Maximum free space in an empty page */
6099 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
6100 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
6101 if ((nkeys < 20) || (nsize > pmax/4)) {
6102 if (newindx <= split_indx) {
6105 for (i=0; i<split_indx; i++) {
6106 node = NODEPTR(mp, i);
6107 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6108 if (F_ISSET(node->mn_flags, F_BIGDATA))
6109 psize += sizeof(pgno_t);
6111 psize += NODEDSZ(node);
6115 split_indx = newindx;
6126 for (i=nkeys-1; i>=split_indx; i--) {
6127 node = NODEPTR(mp, i);
6128 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6129 if (F_ISSET(node->mn_flags, F_BIGDATA))
6130 psize += sizeof(pgno_t);
6132 psize += NODEDSZ(node);
6136 split_indx = newindx;
6147 /* First find the separating key between the split pages.
6148 * The case where newindx == split_indx is ambiguous; the
6149 * new item could go to the new page or stay on the original
6150 * page. If newpos == 1 it goes to the new page.
6152 if (newindx == split_indx && newpos) {
6153 sepkey.mv_size = newkey->mv_size;
6154 sepkey.mv_data = newkey->mv_data;
6156 node = NODEPTR(mp, split_indx);
6157 sepkey.mv_size = node->mn_ksize;
6158 sepkey.mv_data = NODEKEY(node);
6162 DPRINTF("separator is [%s]", DKEY(&sepkey));
6164 /* Copy separator key to the parent.
6166 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
6170 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
6173 if (mn.mc_snum == mc->mc_snum) {
6174 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
6175 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
6176 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
6177 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
6182 /* Right page might now have changed parent.
6183 * Check if left page also changed parent.
6185 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6186 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6187 for (i=0; i<ptop; i++) {
6188 mc->mc_pg[i] = mn.mc_pg[i];
6189 mc->mc_ki[i] = mn.mc_ki[i];
6191 mc->mc_pg[ptop] = mn.mc_pg[ptop];
6192 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6196 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
6199 mc->mc_flags ^= C_SPLITTING;
6200 if (rc != MDB_SUCCESS) {
6203 if (nflags & MDB_APPEND) {
6204 mc->mc_pg[mc->mc_top] = rp;
6205 mc->mc_ki[mc->mc_top] = 0;
6206 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6209 for (i=0; i<mc->mc_top; i++)
6210 mc->mc_ki[i] = mn.mc_ki[i];
6217 /* Move half of the keys to the right sibling. */
6219 /* grab a page to hold a temporary copy */
6220 copy = mdb_page_malloc(mc);
6224 copy->mp_pgno = mp->mp_pgno;
6225 copy->mp_flags = mp->mp_flags;
6226 copy->mp_lower = PAGEHDRSZ;
6227 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6228 mc->mc_pg[mc->mc_top] = copy;
6229 for (i = j = 0; i <= nkeys; j++) {
6230 if (i == split_indx) {
6231 /* Insert in right sibling. */
6232 /* Reset insert index for right sibling. */
6233 if (i != newindx || (newpos ^ ins_new)) {
6235 mc->mc_pg[mc->mc_top] = rp;
6239 if (i == newindx && !ins_new) {
6240 /* Insert the original entry that caused the split. */
6241 rkey.mv_data = newkey->mv_data;
6242 rkey.mv_size = newkey->mv_size;
6251 /* Update index for the new key. */
6252 mc->mc_ki[mc->mc_top] = j;
6253 } else if (i == nkeys) {
6256 node = NODEPTR(mp, i);
6257 rkey.mv_data = NODEKEY(node);
6258 rkey.mv_size = node->mn_ksize;
6260 xdata.mv_data = NODEDATA(node);
6261 xdata.mv_size = NODEDSZ(node);
6264 pgno = NODEPGNO(node);
6265 flags = node->mn_flags;
6270 if (!IS_LEAF(mp) && j == 0) {
6271 /* First branch index doesn't need key data. */
6275 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6279 nkeys = NUMKEYS(copy);
6280 for (i=0; i<nkeys; i++)
6281 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6282 mp->mp_lower = copy->mp_lower;
6283 mp->mp_upper = copy->mp_upper;
6284 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6285 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6287 /* reset back to original page */
6288 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6289 mc->mc_pg[mc->mc_top] = mp;
6290 if (nflags & MDB_RESERVE) {
6291 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6292 if (!(node->mn_flags & F_BIGDATA))
6293 newdata->mv_data = NODEDATA(node);
6299 /* return tmp page to freelist */
6300 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
6301 VGMEMP_FREE(mc->mc_txn->mt_env, copy);
6302 mc->mc_txn->mt_env->me_dpages = copy;
6305 /* Adjust other cursors pointing to mp */
6306 MDB_cursor *m2, *m3;
6307 MDB_dbi dbi = mc->mc_dbi;
6308 int fixup = NUMKEYS(mp);
6310 if (mc->mc_flags & C_SUB)
6313 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6314 if (m2 == mc) continue;
6315 if (mc->mc_flags & C_SUB)
6316 m3 = &m2->mc_xcursor->mx_cursor;
6319 if (!(m3->mc_flags & C_INITIALIZED))
6321 if (m3->mc_flags & C_SPLITTING)
6326 for (k=m3->mc_top; k>=0; k--) {
6327 m3->mc_ki[k+1] = m3->mc_ki[k];
6328 m3->mc_pg[k+1] = m3->mc_pg[k];
6330 if (m3->mc_ki[0] >= split_indx) {
6335 m3->mc_pg[0] = mc->mc_pg[0];
6339 if (m3->mc_pg[mc->mc_top] == mp) {
6340 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
6341 m3->mc_ki[mc->mc_top]++;
6342 if (m3->mc_ki[mc->mc_top] >= fixup) {
6343 m3->mc_pg[mc->mc_top] = rp;
6344 m3->mc_ki[mc->mc_top] -= fixup;
6345 m3->mc_ki[ptop] = mn.mc_ki[ptop];
6347 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
6348 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
6357 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6358 MDB_val *key, MDB_val *data, unsigned int flags)
6363 assert(key != NULL);
6364 assert(data != NULL);
6366 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6369 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6373 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
6377 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6380 mdb_cursor_init(&mc, txn, dbi, &mx);
6381 return mdb_cursor_put(&mc, key, data, flags);
6384 /** Only a subset of the @ref mdb_env flags can be changed
6385 * at runtime. Changing other flags requires closing the environment
6386 * and re-opening it with the new flags.
6388 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
6390 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6392 if ((flag & CHANGEABLE) != flag)
6395 env->me_flags |= flag;
6397 env->me_flags &= ~flag;
6402 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6407 *arg = env->me_flags;
6412 mdb_env_get_path(MDB_env *env, const char **arg)
6417 *arg = env->me_path;
6421 /** Common code for #mdb_stat() and #mdb_env_stat().
6422 * @param[in] env the environment to operate in.
6423 * @param[in] db the #MDB_db record containing the stats to return.
6424 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6425 * @return 0, this function always succeeds.
6428 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6430 arg->ms_psize = env->me_psize;
6431 arg->ms_depth = db->md_depth;
6432 arg->ms_branch_pages = db->md_branch_pages;
6433 arg->ms_leaf_pages = db->md_leaf_pages;
6434 arg->ms_overflow_pages = db->md_overflow_pages;
6435 arg->ms_entries = db->md_entries;
6440 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6444 if (env == NULL || arg == NULL)
6447 toggle = mdb_env_pick_meta(env);
6449 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6452 /** Set the default comparison functions for a database.
6453 * Called immediately after a database is opened to set the defaults.
6454 * The user can then override them with #mdb_set_compare() or
6455 * #mdb_set_dupsort().
6456 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6457 * @param[in] dbi A database handle returned by #mdb_open()
6460 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6462 uint16_t f = txn->mt_dbs[dbi].md_flags;
6464 txn->mt_dbxs[dbi].md_cmp =
6465 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
6466 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
6468 txn->mt_dbxs[dbi].md_dcmp =
6469 !(f & MDB_DUPSORT) ? 0 :
6470 ((f & MDB_INTEGERDUP)
6471 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
6472 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
6475 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6480 int rc, dbflag, exact;
6481 unsigned int unused = 0;
6484 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6485 mdb_default_cmp(txn, FREE_DBI);
6491 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6492 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6493 mdb_default_cmp(txn, MAIN_DBI);
6497 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6498 mdb_default_cmp(txn, MAIN_DBI);
6501 /* Is the DB already open? */
6503 for (i=2; i<txn->mt_numdbs; i++) {
6504 if (!txn->mt_dbxs[i].md_name.mv_size) {
6505 /* Remember this free slot */
6506 if (!unused) unused = i;
6509 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6510 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6516 /* If no free slot and max hit, fail */
6517 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6518 return MDB_DBS_FULL;
6520 /* Find the DB info */
6524 key.mv_data = (void *)name;
6525 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6526 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6527 if (rc == MDB_SUCCESS) {
6528 /* make sure this is actually a DB */
6529 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6530 if (!(node->mn_flags & F_SUBDATA))
6532 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6533 /* Create if requested */
6535 data.mv_size = sizeof(MDB_db);
6536 data.mv_data = &dummy;
6537 memset(&dummy, 0, sizeof(dummy));
6538 dummy.md_root = P_INVALID;
6539 dummy.md_flags = flags & 0xffff;
6540 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6544 /* OK, got info, add to table */
6545 if (rc == MDB_SUCCESS) {
6546 unsigned int slot = unused ? unused : txn->mt_numdbs;
6547 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
6548 txn->mt_dbxs[slot].md_name.mv_size = len;
6549 txn->mt_dbxs[slot].md_rel = NULL;
6550 txn->mt_dbflags[slot] = dbflag;
6551 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
6553 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
6554 mdb_default_cmp(txn, slot);
6557 txn->mt_env->me_numdbs++;
6564 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6566 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6569 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6572 void mdb_close(MDB_env *env, MDB_dbi dbi)
6575 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6577 ptr = env->me_dbxs[dbi].md_name.mv_data;
6578 env->me_dbxs[dbi].md_name.mv_data = NULL;
6579 env->me_dbxs[dbi].md_name.mv_size = 0;
6583 /** Add all the DB's pages to the free list.
6584 * @param[in] mc Cursor on the DB to free.
6585 * @param[in] subs non-Zero to check for sub-DBs in this DB.
6586 * @return 0 on success, non-zero on failure.
6589 mdb_drop0(MDB_cursor *mc, int subs)
6593 rc = mdb_page_search(mc, NULL, 0);
6594 if (rc == MDB_SUCCESS) {
6599 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6600 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6603 mdb_cursor_copy(mc, &mx);
6604 while (mc->mc_snum > 0) {
6605 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6606 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6607 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6608 if (ni->mn_flags & F_SUBDATA) {
6609 mdb_xcursor_init1(mc, ni);
6610 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6616 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6618 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6621 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6626 rc = mdb_cursor_sibling(mc, 1);
6628 /* no more siblings, go back to beginning
6629 * of previous level. (stack was already popped
6630 * by mdb_cursor_sibling)
6632 for (i=1; i<mc->mc_top; i++)
6633 mc->mc_pg[i] = mx.mc_pg[i];
6637 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6638 mc->mc_db->md_root);
6643 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6648 if (!txn || !dbi || dbi >= txn->mt_numdbs)
6651 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6654 rc = mdb_cursor_open(txn, dbi, &mc);
6658 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6662 /* Can't delete the main DB */
6663 if (del && dbi > MAIN_DBI) {
6664 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6666 mdb_close(txn->mt_env, dbi);
6668 txn->mt_dbflags[dbi] |= DB_DIRTY;
6669 txn->mt_dbs[dbi].md_depth = 0;
6670 txn->mt_dbs[dbi].md_branch_pages = 0;
6671 txn->mt_dbs[dbi].md_leaf_pages = 0;
6672 txn->mt_dbs[dbi].md_overflow_pages = 0;
6673 txn->mt_dbs[dbi].md_entries = 0;
6674 txn->mt_dbs[dbi].md_root = P_INVALID;
6677 mdb_cursor_close(mc);
6681 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6683 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6686 txn->mt_dbxs[dbi].md_cmp = cmp;
6690 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6692 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6695 txn->mt_dbxs[dbi].md_dcmp = cmp;
6699 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6701 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6704 txn->mt_dbxs[dbi].md_rel = rel;
6708 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6710 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6713 txn->mt_dbxs[dbi].md_relctx = ctx;