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
63 #include <semaphore.h>
68 #include <valgrind/memcheck.h>
69 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
70 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
71 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
72 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
73 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
75 #define VGMEMP_CREATE(h,r,z)
76 #define VGMEMP_ALLOC(h,a,s)
77 #define VGMEMP_FREE(h,a)
78 #define VGMEMP_DESTROY(h)
79 #define VGMEMP_DEFINED(a,s)
83 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
84 /* Solaris just defines one or the other */
85 # define LITTLE_ENDIAN 1234
86 # define BIG_ENDIAN 4321
87 # ifdef _LITTLE_ENDIAN
88 # define BYTE_ORDER LITTLE_ENDIAN
90 # define BYTE_ORDER BIG_ENDIAN
93 # define BYTE_ORDER __BYTE_ORDER
98 #define LITTLE_ENDIAN __LITTLE_ENDIAN
101 #define BIG_ENDIAN __BIG_ENDIAN
104 #if defined(__i386) || defined(__x86_64)
105 #define MISALIGNED_OK 1
111 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
112 # error "Unknown or unsupported endianness (BYTE_ORDER)"
113 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
114 # error "Two's complement, reasonably sized integer types, please"
117 /** @defgroup internal MDB Internals
120 /** @defgroup compat Windows Compatibility Macros
121 * A bunch of macros to minimize the amount of platform-specific ifdefs
122 * needed throughout the rest of the code. When the features this library
123 * needs are similar enough to POSIX to be hidden in a one-or-two line
124 * replacement, this macro approach is used.
128 #define pthread_t DWORD
129 #define pthread_mutex_t HANDLE
130 #define pthread_key_t DWORD
131 #define pthread_self() GetCurrentThreadId()
132 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
133 #define pthread_key_delete(x) TlsFree(x)
134 #define pthread_getspecific(x) TlsGetValue(x)
135 #define pthread_setspecific(x,y) TlsSetValue(x,y)
136 #define pthread_mutex_unlock(x) ReleaseMutex(x)
137 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
138 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
139 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
140 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
141 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
142 #define getpid() GetCurrentProcessId()
143 #define fdatasync(fd) (!FlushFileBuffers(fd))
144 #define ErrCode() GetLastError()
145 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
146 #define close(fd) CloseHandle(fd)
147 #define munmap(ptr,len) UnmapViewOfFile(ptr)
150 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
151 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
152 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
153 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
154 #define fdatasync(fd) fsync(fd)
157 #define fdatasync(fd) fsync(fd)
159 /** Lock the reader mutex.
161 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
162 /** Unlock the reader mutex.
164 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
166 /** Lock the writer mutex.
167 * Only a single write transaction is allowed at a time. Other writers
168 * will block waiting for this mutex.
170 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
171 /** Unlock the writer mutex.
173 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
174 #endif /* __APPLE__ */
176 /** Get the error code for the last failed system function.
178 #define ErrCode() errno
180 /** An abstraction for a file handle.
181 * On POSIX systems file handles are small integers. On Windows
182 * they're opaque pointers.
186 /** A value for an invalid file handle.
187 * Mainly used to initialize file variables and signify that they are
190 #define INVALID_HANDLE_VALUE (-1)
192 /** Get the size of a memory page for the system.
193 * This is the basic size that the platform's memory manager uses, and is
194 * fundamental to the use of memory-mapped files.
196 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
199 #if defined(_WIN32) || defined(__APPLE__)
206 /** A flag for opening a file and requesting synchronous data writes.
207 * This is only used when writing a meta page. It's not strictly needed;
208 * we could just do a normal write and then immediately perform a flush.
209 * But if this flag is available it saves us an extra system call.
211 * @note If O_DSYNC is undefined but exists in /usr/include,
212 * preferably set some compiler flag to get the definition.
213 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
216 # define MDB_DSYNC O_DSYNC
220 /** Function for flushing the data of a file. Define this to fsync
221 * if fdatasync() is not supported.
223 #ifndef MDB_FDATASYNC
224 # define MDB_FDATASYNC fdatasync
227 /** A page number in the database.
228 * Note that 64 bit page numbers are overkill, since pages themselves
229 * already represent 12-13 bits of addressable memory, and the OS will
230 * always limit applications to a maximum of 63 bits of address space.
232 * @note In the #MDB_node structure, we only store 48 bits of this value,
233 * which thus limits us to only 60 bits of addressable data.
237 /** A transaction ID.
238 * See struct MDB_txn.mt_txnid for details.
242 /** @defgroup debug Debug Macros
246 /** Enable debug output.
247 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
248 * read from and written to the database (used for free space management).
253 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
254 # define DPRINTF (void) /* Vararg macros may be unsupported */
256 /** Print a debug message with printf formatting. */
257 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
258 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
260 # define DPRINTF(fmt, ...) ((void) 0)
262 /** Print a debug string.
263 * The string is printed literally, with no format processing.
265 #define DPUTS(arg) DPRINTF("%s", arg)
268 /** A default memory page size.
269 * The actual size is platform-dependent, but we use this for
270 * boot-strapping. We probably should not be using this any more.
271 * The #GET_PAGESIZE() macro is used to get the actual size.
273 * Note that we don't currently support Huge pages. On Linux,
274 * regular data files cannot use Huge pages, and in general
275 * Huge pages aren't actually pageable. We rely on the OS
276 * demand-pager to read our data and page it out when memory
277 * pressure from other processes is high. So until OSs have
278 * actual paging support for Huge pages, they're not viable.
280 #define MDB_PAGESIZE 4096
282 /** The minimum number of keys required in a database page.
283 * Setting this to a larger value will place a smaller bound on the
284 * maximum size of a data item. Data items larger than this size will
285 * be pushed into overflow pages instead of being stored directly in
286 * the B-tree node. This value used to default to 4. With a page size
287 * of 4096 bytes that meant that any item larger than 1024 bytes would
288 * go into an overflow page. That also meant that on average 2-3KB of
289 * each overflow page was wasted space. The value cannot be lower than
290 * 2 because then there would no longer be a tree structure. With this
291 * value, items larger than 2KB will go into overflow pages, and on
292 * average only 1KB will be wasted.
294 #define MDB_MINKEYS 2
296 /** A stamp that identifies a file as an MDB file.
297 * There's nothing special about this value other than that it is easily
298 * recognizable, and it will reflect any byte order mismatches.
300 #define MDB_MAGIC 0xBEEFC0DE
302 /** The version number for a database's file format. */
303 #define MDB_VERSION 1
305 /** The maximum size of a key in the database.
306 * While data items have essentially unbounded size, we require that
307 * keys all fit onto a regular page. This limit could be raised a bit
308 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
310 #define MAXKEYSIZE 511
315 * This is used for printing a hex dump of a key's contents.
317 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
318 /** Display a key in hex.
320 * Invoke a function to display a key in hex.
322 #define DKEY(x) mdb_dkey(x, kbuf)
324 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
328 /** @defgroup lazylock Lazy Locking
329 * Macros for locks that are't actually needed.
330 * The DB view is always consistent because all writes are wrapped in
331 * the wmutex. Finer-grained locks aren't necessary.
335 /** Use lazy locking. I.e., don't lock these accesses at all. */
339 /** Grab the reader lock */
340 #define LAZY_MUTEX_LOCK(x)
341 /** Release the reader lock */
342 #define LAZY_MUTEX_UNLOCK(x)
343 /** Release the DB table reader/writer lock */
344 #define LAZY_RWLOCK_UNLOCK(x)
345 /** Grab the DB table write lock */
346 #define LAZY_RWLOCK_WRLOCK(x)
347 /** Grab the DB table read lock */
348 #define LAZY_RWLOCK_RDLOCK(x)
349 /** Declare the DB table rwlock. Should not be followed by ';'. */
350 #define LAZY_RWLOCK_DEF(x)
351 /** Initialize the DB table rwlock */
352 #define LAZY_RWLOCK_INIT(x,y)
353 /** Destroy the DB table rwlock */
354 #define LAZY_RWLOCK_DESTROY(x)
356 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
357 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
358 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
359 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
360 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
361 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
362 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
363 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
367 /** An invalid page number.
368 * Mainly used to denote an empty tree.
370 #define P_INVALID (~0UL)
372 /** Test if a flag \b f is set in a flag word \b w. */
373 #define F_ISSET(w, f) (((w) & (f)) == (f))
375 /** Used for offsets within a single page.
376 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
379 typedef uint16_t indx_t;
381 /** Default size of memory map.
382 * This is certainly too small for any actual applications. Apps should always set
383 * the size explicitly using #mdb_env_set_mapsize().
385 #define DEFAULT_MAPSIZE 1048576
387 /** @defgroup readers Reader Lock Table
388 * Readers don't acquire any locks for their data access. Instead, they
389 * simply record their transaction ID in the reader table. The reader
390 * mutex is needed just to find an empty slot in the reader table. The
391 * slot's address is saved in thread-specific data so that subsequent read
392 * transactions started by the same thread need no further locking to proceed.
394 * Since the database uses multi-version concurrency control, readers don't
395 * actually need any locking. This table is used to keep track of which
396 * readers are using data from which old transactions, so that we'll know
397 * when a particular old transaction is no longer in use. Old transactions
398 * that have discarded any data pages can then have those pages reclaimed
399 * for use by a later write transaction.
401 * The lock table is constructed such that reader slots are aligned with the
402 * processor's cache line size. Any slot is only ever used by one thread.
403 * This alignment guarantees that there will be no contention or cache
404 * thrashing as threads update their own slot info, and also eliminates
405 * any need for locking when accessing a slot.
407 * A writer thread will scan every slot in the table to determine the oldest
408 * outstanding reader transaction. Any freed pages older than this will be
409 * reclaimed by the writer. The writer doesn't use any locks when scanning
410 * this table. This means that there's no guarantee that the writer will
411 * see the most up-to-date reader info, but that's not required for correct
412 * operation - all we need is to know the upper bound on the oldest reader,
413 * we don't care at all about the newest reader. So the only consequence of
414 * reading stale information here is that old pages might hang around a
415 * while longer before being reclaimed. That's actually good anyway, because
416 * the longer we delay reclaiming old pages, the more likely it is that a
417 * string of contiguous pages can be found after coalescing old pages from
418 * many old transactions together.
420 * @todo We don't actually do such coalescing yet, we grab pages from one
421 * old transaction at a time.
424 /** Number of slots in the reader table.
425 * This value was chosen somewhat arbitrarily. 126 readers plus a
426 * couple mutexes fit exactly into 8KB on my development machine.
427 * Applications should set the table size using #mdb_env_set_maxreaders().
429 #define DEFAULT_READERS 126
431 /** The size of a CPU cache line in bytes. We want our lock structures
432 * aligned to this size to avoid false cache line sharing in the
434 * This value works for most CPUs. For Itanium this should be 128.
440 /** The information we store in a single slot of the reader table.
441 * In addition to a transaction ID, we also record the process and
442 * thread ID that owns a slot, so that we can detect stale information,
443 * e.g. threads or processes that went away without cleaning up.
444 * @note We currently don't check for stale records. We simply re-init
445 * the table when we know that we're the only process opening the
448 typedef struct MDB_rxbody {
449 /** The current Transaction ID when this transaction began.
450 * Multiple readers that start at the same time will probably have the
451 * same ID here. Again, it's not important to exclude them from
452 * anything; all we need to know is which version of the DB they
453 * started from so we can avoid overwriting any data used in that
454 * particular version.
457 /** The process ID of the process owning this reader txn. */
459 /** The thread ID of the thread owning this txn. */
463 /** The actual reader record, with cacheline padding. */
464 typedef struct MDB_reader {
467 /** shorthand for mrb_txnid */
468 #define mr_txnid mru.mrx.mrb_txnid
469 #define mr_pid mru.mrx.mrb_pid
470 #define mr_tid mru.mrx.mrb_tid
471 /** cache line alignment */
472 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
476 /** The header for the reader table.
477 * The table resides in a memory-mapped file. (This is a different file
478 * than is used for the main database.)
480 * For POSIX the actual mutexes reside in the shared memory of this
481 * mapped file. On Windows, mutexes are named objects allocated by the
482 * kernel; we store the mutex names in this mapped file so that other
483 * processes can grab them. This same approach is also used on
484 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
485 * process-shared POSIX mutexes. For these cases where a named object
486 * is used, the object name is derived from a 64 bit FNV hash of the
487 * environment pathname. As such, naming collisions are extremely
488 * unlikely. If a collision occurs, the results are unpredictable.
490 typedef struct MDB_txbody {
491 /** Stamp identifying this as an MDB lock file. It must be set
494 /** Version number of this lock file. Must be set to #MDB_VERSION. */
495 uint32_t mtb_version;
496 #if defined(_WIN32) || defined(__APPLE__)
497 char mtb_rmname[MNAME_LEN];
499 /** Mutex protecting access to this table.
500 * This is the reader lock that #LOCK_MUTEX_R acquires.
502 pthread_mutex_t mtb_mutex;
504 /** The ID of the last transaction committed to the database.
505 * This is recorded here only for convenience; the value can always
506 * be determined by reading the main database meta pages.
509 /** The number of slots that have been used in the reader table.
510 * This always records the maximum count, it is not decremented
511 * when readers release their slots.
513 unsigned mtb_numreaders;
514 /** The ID of the most recent meta page in the database.
515 * This is recorded here only for convenience; the value can always
516 * be determined by reading the main database meta pages.
518 uint32_t mtb_me_toggle;
521 /** The actual reader table definition. */
522 typedef struct MDB_txninfo {
525 #define mti_magic mt1.mtb.mtb_magic
526 #define mti_version mt1.mtb.mtb_version
527 #define mti_mutex mt1.mtb.mtb_mutex
528 #define mti_rmname mt1.mtb.mtb_rmname
529 #define mti_txnid mt1.mtb.mtb_txnid
530 #define mti_numreaders mt1.mtb.mtb_numreaders
531 #define mti_me_toggle mt1.mtb.mtb_me_toggle
532 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
535 #if defined(_WIN32) || defined(__APPLE__)
536 char mt2_wmname[MNAME_LEN];
537 #define mti_wmname mt2.mt2_wmname
539 pthread_mutex_t mt2_wmutex;
540 #define mti_wmutex mt2.mt2_wmutex
542 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
544 MDB_reader mti_readers[1];
548 /** Common header for all page types.
549 * Overflow records occupy a number of contiguous pages with no
550 * headers on any page after the first.
552 typedef struct MDB_page {
553 #define mp_pgno mp_p.p_pgno
554 #define mp_next mp_p.p_next
556 pgno_t p_pgno; /**< page number */
557 void * p_next; /**< for in-memory list of freed structs */
560 /** @defgroup mdb_page Page Flags
562 * Flags for the page headers.
565 #define P_BRANCH 0x01 /**< branch page */
566 #define P_LEAF 0x02 /**< leaf page */
567 #define P_OVERFLOW 0x04 /**< overflow page */
568 #define P_META 0x08 /**< meta page */
569 #define P_DIRTY 0x10 /**< dirty page */
570 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
571 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
573 uint16_t mp_flags; /**< @ref mdb_page */
574 #define mp_lower mp_pb.pb.pb_lower
575 #define mp_upper mp_pb.pb.pb_upper
576 #define mp_pages mp_pb.pb_pages
579 indx_t pb_lower; /**< lower bound of free space */
580 indx_t pb_upper; /**< upper bound of free space */
582 uint32_t pb_pages; /**< number of overflow pages */
584 indx_t mp_ptrs[1]; /**< dynamic size */
587 /** Size of the page header, excluding dynamic data at the end */
588 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
590 /** Address of first usable data byte in a page, after the header */
591 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
593 /** Number of nodes on a page */
594 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
596 /** The amount of space remaining in the page */
597 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
599 /** The percentage of space used in the page, in tenths of a percent. */
600 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
601 ((env)->me_psize - PAGEHDRSZ))
602 /** The minimum page fill factor, in tenths of a percent.
603 * Pages emptier than this are candidates for merging.
605 #define FILL_THRESHOLD 250
607 /** Test if a page is a leaf page */
608 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
609 /** Test if a page is a LEAF2 page */
610 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
611 /** Test if a page is a branch page */
612 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
613 /** Test if a page is an overflow page */
614 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
615 /** Test if a page is a sub page */
616 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
618 /** The number of overflow pages needed to store the given size. */
619 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
621 /** Header for a single key/data pair within a page.
622 * We guarantee 2-byte alignment for nodes.
624 typedef struct MDB_node {
625 /** lo and hi are used for data size on leaf nodes and for
626 * child pgno on branch nodes. On 64 bit platforms, flags
627 * is also used for pgno. (Branch nodes have no flags).
628 * They are in host byte order in case that lets some
629 * accesses be optimized into a 32-bit word access.
631 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
632 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
633 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
634 /** @defgroup mdb_node Node Flags
636 * Flags for node headers.
639 #define F_BIGDATA 0x01 /**< data put on overflow page */
640 #define F_SUBDATA 0x02 /**< data is a sub-database */
641 #define F_DUPDATA 0x04 /**< data has duplicates */
643 /** valid flags for #mdb_node_add() */
644 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
647 unsigned short mn_flags; /**< @ref mdb_node */
648 unsigned short mn_ksize; /**< key size */
649 char mn_data[1]; /**< key and data are appended here */
652 /** Size of the node header, excluding dynamic data at the end */
653 #define NODESIZE offsetof(MDB_node, mn_data)
655 /** Bit position of top word in page number, for shifting mn_flags */
656 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
658 /** Size of a node in a branch page with a given key.
659 * This is just the node header plus the key, there is no data.
661 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
663 /** Size of a node in a leaf page with a given key and data.
664 * This is node header plus key plus data size.
666 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
668 /** Address of node \b i in page \b p */
669 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
671 /** Address of the key for the node */
672 #define NODEKEY(node) (void *)((node)->mn_data)
674 /** Address of the data for a node */
675 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
677 /** Get the page number pointed to by a branch node */
678 #define NODEPGNO(node) \
679 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
680 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
681 /** Set the page number in a branch node */
682 #define SETPGNO(node,pgno) do { \
683 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
684 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
686 /** Get the size of the data in a leaf node */
687 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
688 /** Set the size of the data for a leaf node */
689 #define SETDSZ(node,size) do { \
690 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
691 /** The size of a key in a node */
692 #define NODEKSZ(node) ((node)->mn_ksize)
694 /** Copy a page number from src to dst */
696 #define COPY_PGNO(dst,src) dst = src
698 #if SIZE_MAX > 4294967295UL
699 #define COPY_PGNO(dst,src) do { \
700 unsigned short *s, *d; \
701 s = (unsigned short *)&(src); \
702 d = (unsigned short *)&(dst); \
709 #define COPY_PGNO(dst,src) do { \
710 unsigned short *s, *d; \
711 s = (unsigned short *)&(src); \
712 d = (unsigned short *)&(dst); \
718 /** The address of a key in a LEAF2 page.
719 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
720 * There are no node headers, keys are stored contiguously.
722 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
724 /** Set the \b node's key into \b key, if requested. */
725 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
726 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
728 /** Information about a single database in the environment. */
729 typedef struct MDB_db {
730 uint32_t md_pad; /**< also ksize for LEAF2 pages */
731 uint16_t md_flags; /**< @ref mdb_open */
732 uint16_t md_depth; /**< depth of this tree */
733 pgno_t md_branch_pages; /**< number of internal pages */
734 pgno_t md_leaf_pages; /**< number of leaf pages */
735 pgno_t md_overflow_pages; /**< number of overflow pages */
736 size_t md_entries; /**< number of data items */
737 pgno_t md_root; /**< the root page of this tree */
740 /** Handle for the DB used to track free pages. */
742 /** Handle for the default DB. */
745 /** Meta page content. */
746 typedef struct MDB_meta {
747 /** Stamp identifying this as an MDB data file. It must be set
750 /** Version number of this lock file. Must be set to #MDB_VERSION. */
752 void *mm_address; /**< address for fixed mapping */
753 size_t mm_mapsize; /**< size of mmap region */
754 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
755 /** The size of pages used in this DB */
756 #define mm_psize mm_dbs[0].md_pad
757 /** Any persistent environment flags. @ref mdb_env */
758 #define mm_flags mm_dbs[0].md_flags
759 pgno_t mm_last_pg; /**< last used page in file */
760 txnid_t mm_txnid; /**< txnid that committed this page */
763 /** Auxiliary DB info.
764 * The information here is mostly static/read-only. There is
765 * only a single copy of this record in the environment.
767 typedef struct MDB_dbx {
768 MDB_val md_name; /**< name of the database */
769 MDB_cmp_func *md_cmp; /**< function for comparing keys */
770 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
771 MDB_rel_func *md_rel; /**< user relocate function */
772 void *md_relctx; /**< user-provided context for md_rel */
775 /** A database transaction.
776 * Every operation requires a transaction handle.
779 MDB_txn *mt_parent; /**< parent of a nested txn */
780 MDB_txn *mt_child; /**< nested txn under this txn */
781 pgno_t mt_next_pgno; /**< next unallocated page */
782 /** The ID of this transaction. IDs are integers incrementing from 1.
783 * Only committed write transactions increment the ID. If a transaction
784 * aborts, the ID may be re-used by the next writer.
787 MDB_env *mt_env; /**< the DB environment */
788 /** The list of pages that became unused during this transaction.
792 ID2L dirty_list; /**< modified pages */
793 MDB_reader *reader; /**< this thread's slot in the reader table */
795 /** Array of records for each DB known in the environment. */
797 /** Array of MDB_db records for each known DB */
799 /** @defgroup mt_dbflag Transaction DB Flags
803 #define DB_DIRTY 0x01 /**< DB was written in this txn */
804 #define DB_STALE 0x02 /**< DB record is older than txnID */
806 /** Array of cursors for each DB */
807 MDB_cursor **mt_cursors;
808 /** Array of flags for each DB */
809 unsigned char *mt_dbflags;
810 /** Number of DB records in use. This number only ever increments;
811 * we don't decrement it when individual DB handles are closed.
815 /** @defgroup mdb_txn Transaction Flags
819 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
820 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
822 unsigned int mt_flags; /**< @ref mdb_txn */
823 /** Tracks which of the two meta pages was used at the start
824 * of this transaction.
826 unsigned int mt_toggle;
829 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
830 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
831 * raise this on a 64 bit machine.
833 #define CURSOR_STACK 32
837 /** Cursors are used for all DB operations */
839 /** Next cursor on this DB in this txn */
841 /** Original cursor if this is a shadow */
843 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
844 struct MDB_xcursor *mc_xcursor;
845 /** The transaction that owns this cursor */
847 /** The database handle this cursor operates on */
849 /** The database record for this cursor */
851 /** The database auxiliary record for this cursor */
853 /** The @ref mt_dbflag for this database */
854 unsigned char *mc_dbflag;
855 unsigned short mc_snum; /**< number of pushed pages */
856 unsigned short mc_top; /**< index of top page, mc_snum-1 */
857 /** @defgroup mdb_cursor Cursor Flags
859 * Cursor state flags.
862 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
863 #define C_EOF 0x02 /**< No more data */
864 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
865 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
866 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
868 unsigned int mc_flags; /**< @ref mdb_cursor */
869 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
870 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
873 /** Context for sorted-dup records.
874 * We could have gone to a fully recursive design, with arbitrarily
875 * deep nesting of sub-databases. But for now we only handle these
876 * levels - main DB, optional sub-DB, sorted-duplicate DB.
878 typedef struct MDB_xcursor {
879 /** A sub-cursor for traversing the Dup DB */
880 MDB_cursor mx_cursor;
881 /** The database record for this Dup DB */
883 /** The auxiliary DB record for this Dup DB */
885 /** The @ref mt_dbflag for this Dup DB */
886 unsigned char mx_dbflag;
889 /** A set of pages freed by an earlier transaction. */
890 typedef struct MDB_oldpages {
891 /** Usually we only read one record from the FREEDB at a time, but
892 * in case we read more, this will chain them together.
894 struct MDB_oldpages *mo_next;
895 /** The ID of the transaction in which these pages were freed. */
897 /** An #IDL of the pages */
898 pgno_t mo_pages[1]; /* dynamic */
901 /** The database environment. */
903 HANDLE me_fd; /**< The main data file */
904 HANDLE me_lfd; /**< The lock file */
905 HANDLE me_mfd; /**< just for writing the meta pages */
906 /** Failed to update the meta page. Probably an I/O error. */
907 #define MDB_FATAL_ERROR 0x80000000U
908 uint32_t me_flags; /**< @ref mdb_env */
909 uint32_t me_extrapad; /**< unused for now */
910 unsigned int me_maxreaders; /**< size of the reader table */
911 MDB_dbi me_numdbs; /**< number of DBs opened */
912 MDB_dbi me_maxdbs; /**< size of the DB table */
913 char *me_path; /**< path to the DB files */
914 char *me_map; /**< the memory map of the data file */
915 MDB_txninfo *me_txns; /**< the memory map of the lock file */
916 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
917 MDB_txn *me_txn; /**< current write transaction */
918 size_t me_mapsize; /**< size of the data memory map */
919 off_t me_size; /**< current file size */
920 pgno_t me_maxpg; /**< me_mapsize / me_psize */
921 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
922 unsigned int me_db_toggle; /**< which DB table is current */
923 txnid_t me_wtxnid; /**< ID of last txn we committed */
924 MDB_dbx *me_dbxs; /**< array of static DB info */
925 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
926 MDB_oldpages *me_pghead; /**< list of old page records */
927 pthread_key_t me_txkey; /**< thread-key for readers */
928 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
929 /** IDL of pages that became unused in a write txn */
931 /** ID2L of pages that were written during a write txn */
932 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
933 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
934 LAZY_RWLOCK_DEF(me_dblock)
936 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
940 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
944 /** max number of pages to commit in one writev() call */
945 #define MDB_COMMIT_PAGES 64
947 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
948 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
949 static int mdb_page_touch(MDB_cursor *mc);
951 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
952 static int mdb_page_search_root(MDB_cursor *mc,
953 MDB_val *key, int modify);
954 static int mdb_page_search(MDB_cursor *mc,
955 MDB_val *key, int modify);
956 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
957 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
958 pgno_t newpgno, unsigned int nflags);
960 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
961 static int mdb_env_read_meta(MDB_env *env, int *which);
962 static int mdb_env_write_meta(MDB_txn *txn);
964 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
965 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
966 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
967 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
968 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
969 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
970 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
971 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
972 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
974 static int mdb_rebalance(MDB_cursor *mc);
975 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
977 static void mdb_cursor_pop(MDB_cursor *mc);
978 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
980 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
981 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
982 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
983 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
984 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
986 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
987 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
989 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
990 static void mdb_xcursor_init0(MDB_cursor *mc);
991 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
993 static int mdb_drop0(MDB_cursor *mc, int subs);
994 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
997 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1001 static SECURITY_DESCRIPTOR mdb_null_sd;
1002 static SECURITY_ATTRIBUTES mdb_all_sa;
1003 static int mdb_sec_inited;
1006 /** Return the library version info. */
1008 mdb_version(int *major, int *minor, int *patch)
1010 if (major) *major = MDB_VERSION_MAJOR;
1011 if (minor) *minor = MDB_VERSION_MINOR;
1012 if (patch) *patch = MDB_VERSION_PATCH;
1013 return MDB_VERSION_STRING;
1016 /** Table of descriptions for MDB @ref errors */
1017 static char *const mdb_errstr[] = {
1018 "MDB_KEYEXIST: Key/data pair already exists",
1019 "MDB_NOTFOUND: No matching key/data pair found",
1020 "MDB_PAGE_NOTFOUND: Requested page not found",
1021 "MDB_CORRUPTED: Located page was wrong type",
1022 "MDB_PANIC: Update of meta page failed",
1023 "MDB_VERSION_MISMATCH: Database environment version mismatch"
1027 mdb_strerror(int err)
1030 return ("Successful return: 0");
1032 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1033 return mdb_errstr[err - MDB_KEYEXIST];
1035 return strerror(err);
1039 /** Display a key in hexadecimal and return the address of the result.
1040 * @param[in] key the key to display
1041 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1042 * @return The key in hexadecimal form.
1045 mdb_dkey(MDB_val *key, char *buf)
1048 unsigned char *c = key->mv_data;
1050 if (key->mv_size > MAXKEYSIZE)
1051 return "MAXKEYSIZE";
1052 /* may want to make this a dynamic check: if the key is mostly
1053 * printable characters, print it as-is instead of converting to hex.
1056 for (i=0; i<key->mv_size; i++)
1057 ptr += sprintf(ptr, "%02x", *c++);
1059 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1066 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1068 return txn->mt_dbxs[dbi].md_cmp(a, b);
1072 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1074 if (txn->mt_dbxs[dbi].md_dcmp)
1075 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1077 return EINVAL; /* too bad you can't distinguish this from a valid result */
1080 /** Allocate a single page.
1081 * Re-use old malloc'd pages first, otherwise just malloc.
1084 mdb_page_malloc(MDB_cursor *mc) {
1086 size_t sz = mc->mc_txn->mt_env->me_psize;
1087 if (mc->mc_txn->mt_env->me_dpages) {
1088 ret = mc->mc_txn->mt_env->me_dpages;
1089 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1090 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1091 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1094 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1099 /** Allocate pages for writing.
1100 * If there are free pages available from older transactions, they
1101 * will be re-used first. Otherwise a new page will be allocated.
1102 * @param[in] mc cursor A cursor handle identifying the transaction and
1103 * database for which we are allocating.
1104 * @param[in] num the number of pages to allocate.
1105 * @return Address of the allocated page(s). Requests for multiple pages
1106 * will always be satisfied by a single contiguous chunk of memory.
1109 mdb_page_alloc(MDB_cursor *mc, int num)
1111 MDB_txn *txn = mc->mc_txn;
1113 pgno_t pgno = P_INVALID;
1116 if (txn->mt_txnid > 2) {
1118 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1119 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1120 /* See if there's anything in the free DB */
1123 txnid_t *kptr, oldest;
1125 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1126 mdb_page_search(&m2, NULL, 0);
1127 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1128 kptr = (txnid_t *)NODEKEY(leaf);
1132 oldest = txn->mt_txnid - 1;
1133 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1134 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1135 if (mr && mr < oldest)
1140 if (oldest > *kptr) {
1141 /* It's usable, grab it.
1147 mdb_node_read(txn, leaf, &data);
1148 idl = (ID *) data.mv_data;
1149 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1150 mop->mo_next = txn->mt_env->me_pghead;
1151 mop->mo_txnid = *kptr;
1152 txn->mt_env->me_pghead = mop;
1153 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1158 DPRINTF("IDL read txn %zu root %zu num %zu",
1159 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1160 for (i=0; i<idl[0]; i++) {
1161 DPRINTF("IDL %zu", idl[i+1]);
1165 /* drop this IDL from the DB */
1166 m2.mc_ki[m2.mc_top] = 0;
1167 m2.mc_flags = C_INITIALIZED;
1168 mdb_cursor_del(&m2, 0);
1171 if (txn->mt_env->me_pghead) {
1172 MDB_oldpages *mop = txn->mt_env->me_pghead;
1174 /* FIXME: For now, always use fresh pages. We
1175 * really ought to search the free list for a
1180 /* peel pages off tail, so we only have to truncate the list */
1181 pgno = MDB_IDL_LAST(mop->mo_pages);
1182 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1184 if (mop->mo_pages[2] > mop->mo_pages[1])
1185 mop->mo_pages[0] = 0;
1189 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1190 txn->mt_env->me_pghead = mop->mo_next;
1197 if (pgno == P_INVALID) {
1198 /* DB size is maxed out */
1199 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1200 DPUTS("DB size maxed out");
1204 if (txn->mt_env->me_dpages && num == 1) {
1205 np = txn->mt_env->me_dpages;
1206 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1207 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1208 txn->mt_env->me_dpages = np->mp_next;
1210 size_t sz = txn->mt_env->me_psize * num;
1211 if ((np = malloc(sz)) == NULL)
1213 VGMEMP_ALLOC(txn->mt_env, np, sz);
1215 if (pgno == P_INVALID) {
1216 np->mp_pgno = txn->mt_next_pgno;
1217 txn->mt_next_pgno += num;
1221 mid.mid = np->mp_pgno;
1223 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1228 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1229 * @param[in] mc cursor pointing to the page to be touched
1230 * @return 0 on success, non-zero on failure.
1233 mdb_page_touch(MDB_cursor *mc)
1235 MDB_page *mp = mc->mc_pg[mc->mc_top];
1238 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1240 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1242 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1243 assert(mp->mp_pgno != np->mp_pgno);
1244 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1246 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1249 mp->mp_flags |= P_DIRTY;
1252 /* Adjust other cursors pointing to mp */
1253 if (mc->mc_flags & C_SUB) {
1254 MDB_cursor *m2, *m3;
1255 MDB_dbi dbi = mc->mc_dbi-1;
1257 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1258 if (m2 == mc) continue;
1259 m3 = &m2->mc_xcursor->mx_cursor;
1260 if (m3->mc_snum < mc->mc_snum) continue;
1261 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1262 m3->mc_pg[mc->mc_top] = mp;
1268 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1269 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1270 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1271 m2->mc_pg[mc->mc_top] = mp;
1275 mc->mc_pg[mc->mc_top] = mp;
1276 /** If this page has a parent, update the parent to point to
1280 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1282 mc->mc_db->md_root = mp->mp_pgno;
1283 } else if (mc->mc_txn->mt_parent) {
1286 /* If txn has a parent, make sure the page is in our
1289 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1290 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1291 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1292 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1293 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1294 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1295 mc->mc_pg[mc->mc_top] = mp;
1301 np = mdb_page_malloc(mc);
1302 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1303 mid.mid = np->mp_pgno;
1305 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1313 mdb_env_sync(MDB_env *env, int force)
1316 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1317 if (MDB_FDATASYNC(env->me_fd))
1323 /** Make shadow copies of all of parent txn's cursors */
1325 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1327 MDB_cursor *mc, *m2;
1328 unsigned int i, j, size;
1330 for (i=0;i<src->mt_numdbs; i++) {
1331 if (src->mt_cursors[i]) {
1332 size = sizeof(MDB_cursor);
1333 if (src->mt_cursors[i]->mc_xcursor)
1334 size += sizeof(MDB_xcursor);
1335 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1342 mc->mc_db = &dst->mt_dbs[i];
1343 mc->mc_dbx = m2->mc_dbx;
1344 mc->mc_dbflag = &dst->mt_dbflags[i];
1345 mc->mc_snum = m2->mc_snum;
1346 mc->mc_top = m2->mc_top;
1347 mc->mc_flags = m2->mc_flags | C_SHADOW;
1348 for (j=0; j<mc->mc_snum; j++) {
1349 mc->mc_pg[j] = m2->mc_pg[j];
1350 mc->mc_ki[j] = m2->mc_ki[j];
1352 if (m2->mc_xcursor) {
1353 MDB_xcursor *mx, *mx2;
1354 mx = (MDB_xcursor *)(mc+1);
1355 mc->mc_xcursor = mx;
1356 mx2 = m2->mc_xcursor;
1357 mx->mx_db = mx2->mx_db;
1358 mx->mx_dbx = mx2->mx_dbx;
1359 mx->mx_dbflag = mx2->mx_dbflag;
1360 mx->mx_cursor.mc_txn = dst;
1361 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1362 mx->mx_cursor.mc_db = &mx->mx_db;
1363 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1364 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1365 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1366 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1367 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1368 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1369 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1370 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1373 mc->mc_xcursor = NULL;
1375 mc->mc_next = dst->mt_cursors[i];
1376 dst->mt_cursors[i] = mc;
1383 /** Merge shadow cursors back into parent's */
1385 mdb_cursor_merge(MDB_txn *txn)
1388 for (i=0; i<txn->mt_numdbs; i++) {
1389 if (txn->mt_cursors[i]) {
1391 while ((mc = txn->mt_cursors[i])) {
1392 txn->mt_cursors[i] = mc->mc_next;
1393 if (mc->mc_flags & C_SHADOW) {
1394 MDB_cursor *m2 = mc->mc_orig;
1396 m2->mc_snum = mc->mc_snum;
1397 m2->mc_top = mc->mc_top;
1398 for (j=0; j<mc->mc_snum; j++) {
1399 m2->mc_pg[j] = mc->mc_pg[j];
1400 m2->mc_ki[j] = mc->mc_ki[j];
1403 if (mc->mc_flags & C_ALLOCD)
1411 mdb_txn_reset0(MDB_txn *txn);
1413 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1414 * @param[in] txn the transaction handle to initialize
1415 * @return 0 on success, non-zero on failure. This can only
1416 * fail for read-only transactions, and then only if the
1417 * reader table is full.
1420 mdb_txn_renew0(MDB_txn *txn)
1422 MDB_env *env = txn->mt_env;
1425 if (txn->mt_flags & MDB_TXN_RDONLY) {
1426 MDB_reader *r = pthread_getspecific(env->me_txkey);
1429 pid_t pid = getpid();
1430 pthread_t tid = pthread_self();
1433 for (i=0; i<env->me_txns->mti_numreaders; i++)
1434 if (env->me_txns->mti_readers[i].mr_pid == 0)
1436 if (i == env->me_maxreaders) {
1437 UNLOCK_MUTEX_R(env);
1440 env->me_txns->mti_readers[i].mr_pid = pid;
1441 env->me_txns->mti_readers[i].mr_tid = tid;
1442 if (i >= env->me_txns->mti_numreaders)
1443 env->me_txns->mti_numreaders = i+1;
1444 UNLOCK_MUTEX_R(env);
1445 r = &env->me_txns->mti_readers[i];
1446 pthread_setspecific(env->me_txkey, r);
1448 txn->mt_toggle = env->me_txns->mti_me_toggle;
1449 txn->mt_txnid = env->me_txns->mti_txnid;
1450 /* This happens if a different process was the
1451 * last writer to the DB.
1453 if (env->me_wtxnid < txn->mt_txnid)
1454 mt_dbflag = DB_STALE;
1455 r->mr_txnid = txn->mt_txnid;
1456 txn->mt_u.reader = r;
1460 txn->mt_txnid = env->me_txns->mti_txnid;
1461 if (env->me_wtxnid < txn->mt_txnid)
1462 mt_dbflag = DB_STALE;
1464 txn->mt_toggle = env->me_txns->mti_me_toggle;
1465 txn->mt_u.dirty_list = env->me_dirty_list;
1466 txn->mt_u.dirty_list[0].mid = 0;
1467 txn->mt_free_pgs = env->me_free_pgs;
1468 txn->mt_free_pgs[0] = 0;
1469 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1473 /* Copy the DB arrays */
1474 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1475 txn->mt_numdbs = env->me_numdbs;
1476 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1477 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1478 if (txn->mt_numdbs > 2)
1479 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1480 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1481 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1483 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1489 mdb_txn_renew(MDB_txn *txn)
1496 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1497 DPUTS("environment had fatal error, must shutdown!");
1501 rc = mdb_txn_renew0(txn);
1502 if (rc == MDB_SUCCESS) {
1503 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1504 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1505 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1511 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1516 if (env->me_flags & MDB_FATAL_ERROR) {
1517 DPUTS("environment had fatal error, must shutdown!");
1521 /* parent already has an active child txn */
1522 if (parent->mt_child) {
1526 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1527 if (!(flags & MDB_RDONLY))
1528 size += env->me_maxdbs * sizeof(MDB_cursor *);
1530 if ((txn = calloc(1, size)) == NULL) {
1531 DPRINTF("calloc: %s", strerror(ErrCode()));
1534 txn->mt_dbs = (MDB_db *)(txn+1);
1535 if (flags & MDB_RDONLY) {
1536 txn->mt_flags |= MDB_TXN_RDONLY;
1537 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1539 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1540 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1545 txn->mt_free_pgs = mdb_midl_alloc();
1546 if (!txn->mt_free_pgs) {
1550 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1551 if (!txn->mt_u.dirty_list) {
1552 free(txn->mt_free_pgs);
1556 txn->mt_txnid = parent->mt_txnid;
1557 txn->mt_toggle = parent->mt_toggle;
1558 txn->mt_u.dirty_list[0].mid = 0;
1559 txn->mt_free_pgs[0] = 0;
1560 txn->mt_next_pgno = parent->mt_next_pgno;
1561 parent->mt_child = txn;
1562 txn->mt_parent = parent;
1563 txn->mt_numdbs = parent->mt_numdbs;
1564 txn->mt_dbxs = parent->mt_dbxs;
1565 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1566 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1567 mdb_cursor_shadow(parent, txn);
1570 rc = mdb_txn_renew0(txn);
1576 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1577 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1578 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1584 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1585 * @param[in] txn the transaction handle to reset
1588 mdb_txn_reset0(MDB_txn *txn)
1590 MDB_env *env = txn->mt_env;
1592 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1593 txn->mt_u.reader->mr_txnid = 0;
1599 /* close(free) all cursors */
1600 for (i=0; i<txn->mt_numdbs; i++) {
1601 if (txn->mt_cursors[i]) {
1603 while ((mc = txn->mt_cursors[i])) {
1604 txn->mt_cursors[i] = mc->mc_next;
1605 if (mc->mc_flags & C_ALLOCD)
1611 /* return all dirty pages to dpage list */
1612 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1613 dp = txn->mt_u.dirty_list[i].mptr;
1614 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1615 dp->mp_next = txn->mt_env->me_dpages;
1616 VGMEMP_FREE(txn->mt_env, dp);
1617 txn->mt_env->me_dpages = dp;
1619 /* large pages just get freed directly */
1620 VGMEMP_FREE(txn->mt_env, dp);
1625 if (txn->mt_parent) {
1626 txn->mt_parent->mt_child = NULL;
1627 free(txn->mt_free_pgs);
1628 free(txn->mt_u.dirty_list);
1631 if (mdb_midl_shrink(&txn->mt_free_pgs))
1632 env->me_free_pgs = txn->mt_free_pgs;
1635 while ((mop = txn->mt_env->me_pghead)) {
1636 txn->mt_env->me_pghead = mop->mo_next;
1641 /* The writer mutex was locked in mdb_txn_begin. */
1642 UNLOCK_MUTEX_W(env);
1647 mdb_txn_reset(MDB_txn *txn)
1652 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1653 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1654 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1656 mdb_txn_reset0(txn);
1660 mdb_txn_abort(MDB_txn *txn)
1665 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1666 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1667 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1670 mdb_txn_abort(txn->mt_child);
1672 mdb_txn_reset0(txn);
1677 mdb_txn_commit(MDB_txn *txn)
1688 assert(txn != NULL);
1689 assert(txn->mt_env != NULL);
1691 if (txn->mt_child) {
1692 mdb_txn_commit(txn->mt_child);
1693 txn->mt_child = NULL;
1698 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1699 if (txn->mt_numdbs > env->me_numdbs) {
1700 /* update the DB tables */
1701 int toggle = !env->me_db_toggle;
1705 ip = &env->me_dbs[toggle][env->me_numdbs];
1706 jp = &txn->mt_dbs[env->me_numdbs];
1707 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1708 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1712 env->me_db_toggle = toggle;
1713 env->me_numdbs = txn->mt_numdbs;
1714 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1720 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1721 DPUTS("error flag is set, can't commit");
1723 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1728 /* Merge (and close) our cursors with parent's */
1729 mdb_cursor_merge(txn);
1731 if (txn->mt_parent) {
1737 /* Update parent's DB table */
1738 ip = &txn->mt_parent->mt_dbs[2];
1739 jp = &txn->mt_dbs[2];
1740 for (i = 2; i < txn->mt_numdbs; i++) {
1741 if (ip->md_root != jp->md_root)
1745 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1747 /* Append our free list to parent's */
1748 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1750 mdb_midl_free(txn->mt_free_pgs);
1752 /* Merge our dirty list with parent's */
1753 dst = txn->mt_parent->mt_u.dirty_list;
1754 src = txn->mt_u.dirty_list;
1755 x = mdb_mid2l_search(dst, src[1].mid);
1756 for (y=1; y<=src[0].mid; y++) {
1757 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1761 dst[x].mptr = src[y].mptr;
1764 for (; y<=src[0].mid; y++) {
1765 if (++x >= MDB_IDL_UM_MAX) {
1772 free(txn->mt_u.dirty_list);
1773 txn->mt_parent->mt_child = NULL;
1778 if (txn != env->me_txn) {
1779 DPUTS("attempt to commit unknown transaction");
1784 if (!txn->mt_u.dirty_list[0].mid)
1787 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1788 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1790 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1792 /* should only be one record now */
1793 if (env->me_pghead) {
1794 /* make sure first page of freeDB is touched and on freelist */
1795 mdb_page_search(&mc, NULL, 1);
1797 /* save to free list */
1798 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1802 /* make sure last page of freeDB is touched and on freelist */
1803 key.mv_size = MAXKEYSIZE+1;
1805 mdb_page_search(&mc, &key, 1);
1807 mdb_midl_sort(txn->mt_free_pgs);
1811 ID *idl = txn->mt_free_pgs;
1812 DPRINTF("IDL write txn %zu root %zu num %zu",
1813 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1814 for (i=0; i<idl[0]; i++) {
1815 DPRINTF("IDL %zu", idl[i+1]);
1819 /* write to last page of freeDB */
1820 key.mv_size = sizeof(pgno_t);
1821 key.mv_data = &txn->mt_txnid;
1822 data.mv_data = txn->mt_free_pgs;
1823 /* The free list can still grow during this call,
1824 * despite the pre-emptive touches above. So check
1825 * and make sure the entire thing got written.
1828 i = txn->mt_free_pgs[0];
1829 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1830 rc = mdb_cursor_put(&mc, &key, &data, 0);
1835 } while (i != txn->mt_free_pgs[0]);
1836 if (mdb_midl_shrink(&txn->mt_free_pgs))
1837 env->me_free_pgs = txn->mt_free_pgs;
1839 /* should only be one record now */
1840 if (env->me_pghead) {
1844 mop = env->me_pghead;
1845 env->me_pghead = NULL;
1846 key.mv_size = sizeof(pgno_t);
1847 key.mv_data = &mop->mo_txnid;
1848 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1849 data.mv_data = mop->mo_pages;
1850 mdb_cursor_put(&mc, &key, &data, 0);
1854 /* Update DB root pointers. Their pages have already been
1855 * touched so this is all in-place and cannot fail.
1860 data.mv_size = sizeof(MDB_db);
1862 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1863 for (i = 2; i < txn->mt_numdbs; i++) {
1864 if (txn->mt_dbflags[i] & DB_DIRTY) {
1865 data.mv_data = &txn->mt_dbs[i];
1866 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1871 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1877 /* Windows actually supports scatter/gather I/O, but only on
1878 * unbuffered file handles. Since we're relying on the OS page
1879 * cache for all our data, that's self-defeating. So we just
1880 * write pages one at a time. We use the ov structure to set
1881 * the write offset, to at least save the overhead of a Seek
1885 memset(&ov, 0, sizeof(ov));
1886 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1888 dp = txn->mt_u.dirty_list[i].mptr;
1889 DPRINTF("committing page %zu", dp->mp_pgno);
1890 size = dp->mp_pgno * env->me_psize;
1891 ov.Offset = size & 0xffffffff;
1892 ov.OffsetHigh = size >> 16;
1893 ov.OffsetHigh >>= 16;
1894 /* clear dirty flag */
1895 dp->mp_flags &= ~P_DIRTY;
1896 wsize = env->me_psize;
1897 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1898 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1901 DPRINTF("WriteFile: %d", n);
1908 struct iovec iov[MDB_COMMIT_PAGES];
1912 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1913 dp = txn->mt_u.dirty_list[i].mptr;
1914 if (dp->mp_pgno != next) {
1916 DPRINTF("committing %u dirty pages", n);
1917 rc = writev(env->me_fd, iov, n);
1921 DPUTS("short write, filesystem full?");
1923 DPRINTF("writev: %s", strerror(n));
1930 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1933 DPRINTF("committing page %zu", dp->mp_pgno);
1934 iov[n].iov_len = env->me_psize;
1935 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1936 iov[n].iov_base = (char *)dp;
1937 size += iov[n].iov_len;
1938 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1939 /* clear dirty flag */
1940 dp->mp_flags &= ~P_DIRTY;
1941 if (++n >= MDB_COMMIT_PAGES) {
1951 DPRINTF("committing %u dirty pages", n);
1952 rc = writev(env->me_fd, iov, n);
1956 DPUTS("short write, filesystem full?");
1958 DPRINTF("writev: %s", strerror(n));
1965 /* Drop the dirty pages.
1967 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1968 dp = txn->mt_u.dirty_list[i].mptr;
1969 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1970 dp->mp_next = txn->mt_env->me_dpages;
1971 VGMEMP_FREE(txn->mt_env, dp);
1972 txn->mt_env->me_dpages = dp;
1974 VGMEMP_FREE(txn->mt_env, dp);
1977 txn->mt_u.dirty_list[i].mid = 0;
1979 txn->mt_u.dirty_list[0].mid = 0;
1981 if ((n = mdb_env_sync(env, 0)) != 0 ||
1982 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1986 env->me_wtxnid = txn->mt_txnid;
1990 /* update the DB tables */
1992 int toggle = !env->me_db_toggle;
1996 ip = &env->me_dbs[toggle][2];
1997 jp = &txn->mt_dbs[2];
1998 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1999 for (i = 2; i < txn->mt_numdbs; i++) {
2000 if (ip->md_root != jp->md_root)
2005 env->me_db_toggle = toggle;
2006 env->me_numdbs = txn->mt_numdbs;
2007 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
2010 UNLOCK_MUTEX_W(env);
2016 /** Read the environment parameters of a DB environment before
2017 * mapping it into memory.
2018 * @param[in] env the environment handle
2019 * @param[out] meta address of where to store the meta information
2020 * @return 0 on success, non-zero on failure.
2023 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2025 char page[MDB_PAGESIZE];
2030 /* We don't know the page size yet, so use a minimum value.
2034 if (!ReadFile(env->me_fd, page, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2036 if ((rc = read(env->me_fd, page, MDB_PAGESIZE)) == 0)
2041 else if (rc != MDB_PAGESIZE) {
2045 DPRINTF("read: %s", strerror(err));
2049 p = (MDB_page *)page;
2051 if (!F_ISSET(p->mp_flags, P_META)) {
2052 DPRINTF("page %zu not a meta page", p->mp_pgno);
2057 if (m->mm_magic != MDB_MAGIC) {
2058 DPUTS("meta has invalid magic");
2062 if (m->mm_version != MDB_VERSION) {
2063 DPRINTF("database is version %u, expected version %u",
2064 m->mm_version, MDB_VERSION);
2065 return MDB_VERSION_MISMATCH;
2068 memcpy(meta, m, sizeof(*m));
2072 /** Write the environment parameters of a freshly created DB environment.
2073 * @param[in] env the environment handle
2074 * @param[out] meta address of where to store the meta information
2075 * @return 0 on success, non-zero on failure.
2078 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2085 DPUTS("writing new meta page");
2087 GET_PAGESIZE(psize);
2089 meta->mm_magic = MDB_MAGIC;
2090 meta->mm_version = MDB_VERSION;
2091 meta->mm_psize = psize;
2092 meta->mm_last_pg = 1;
2093 meta->mm_flags = env->me_flags & 0xffff;
2094 meta->mm_flags |= MDB_INTEGERKEY;
2095 meta->mm_dbs[0].md_root = P_INVALID;
2096 meta->mm_dbs[1].md_root = P_INVALID;
2098 p = calloc(2, psize);
2100 p->mp_flags = P_META;
2103 memcpy(m, meta, sizeof(*meta));
2105 q = (MDB_page *)((char *)p + psize);
2108 q->mp_flags = P_META;
2111 memcpy(m, meta, sizeof(*meta));
2116 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2117 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2120 rc = write(env->me_fd, p, psize * 2);
2121 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2127 /** Update the environment info to commit a transaction.
2128 * @param[in] txn the transaction that's being committed
2129 * @return 0 on success, non-zero on failure.
2132 mdb_env_write_meta(MDB_txn *txn)
2135 MDB_meta meta, metab;
2137 int rc, len, toggle;
2143 assert(txn != NULL);
2144 assert(txn->mt_env != NULL);
2146 toggle = !txn->mt_toggle;
2147 DPRINTF("writing meta page %d for root page %zu",
2148 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2152 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2153 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2155 ptr = (char *)&meta;
2156 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2157 len = sizeof(MDB_meta) - off;
2160 meta.mm_dbs[0] = txn->mt_dbs[0];
2161 meta.mm_dbs[1] = txn->mt_dbs[1];
2162 meta.mm_last_pg = txn->mt_next_pgno - 1;
2163 meta.mm_txnid = txn->mt_txnid;
2166 off += env->me_psize;
2169 /* Write to the SYNC fd */
2172 memset(&ov, 0, sizeof(ov));
2174 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2177 rc = pwrite(env->me_mfd, ptr, len, off);
2182 DPUTS("write failed, disk error?");
2183 /* On a failure, the pagecache still contains the new data.
2184 * Write some old data back, to prevent it from being used.
2185 * Use the non-SYNC fd; we know it will fail anyway.
2187 meta.mm_last_pg = metab.mm_last_pg;
2188 meta.mm_txnid = metab.mm_txnid;
2190 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2192 r2 = pwrite(env->me_fd, ptr, len, off);
2194 env->me_flags |= MDB_FATAL_ERROR;
2197 /* Memory ordering issues are irrelevant; since the entire writer
2198 * is wrapped by wmutex, all of these changes will become visible
2199 * after the wmutex is unlocked. Since the DB is multi-version,
2200 * readers will get consistent data regardless of how fresh or
2201 * how stale their view of these values is.
2203 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2204 txn->mt_env->me_txns->mti_me_toggle = toggle;
2205 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2206 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2211 /** Check both meta pages to see which one is newer.
2212 * @param[in] env the environment handle
2213 * @param[out] which address of where to store the meta toggle ID
2214 * @return 0 on success, non-zero on failure.
2217 mdb_env_read_meta(MDB_env *env, int *which)
2221 assert(env != NULL);
2223 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2226 DPRINTF("Using meta page %d", toggle);
2233 mdb_env_create(MDB_env **env)
2237 e = calloc(1, sizeof(MDB_env));
2241 e->me_free_pgs = mdb_midl_alloc();
2242 if (!e->me_free_pgs) {
2246 e->me_maxreaders = DEFAULT_READERS;
2248 e->me_fd = INVALID_HANDLE_VALUE;
2249 e->me_lfd = INVALID_HANDLE_VALUE;
2250 e->me_mfd = INVALID_HANDLE_VALUE;
2251 VGMEMP_CREATE(e,0,0);
2257 mdb_env_set_mapsize(MDB_env *env, size_t size)
2261 env->me_mapsize = size;
2263 env->me_maxpg = env->me_mapsize / env->me_psize;
2268 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2272 env->me_maxdbs = dbs;
2277 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2279 if (env->me_map || readers < 1)
2281 env->me_maxreaders = readers;
2286 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2288 if (!env || !readers)
2290 *readers = env->me_maxreaders;
2294 /** Further setup required for opening an MDB environment
2297 mdb_env_open2(MDB_env *env, unsigned int flags)
2299 int i, newenv = 0, toggle;
2303 env->me_flags = flags;
2305 memset(&meta, 0, sizeof(meta));
2307 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2310 DPUTS("new mdbenv");
2314 if (!env->me_mapsize) {
2315 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2321 LONG sizelo, sizehi;
2322 sizelo = env->me_mapsize & 0xffffffff;
2323 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2325 /* Windows won't create mappings for zero length files.
2326 * Just allocate the maxsize right now.
2329 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2330 if (!SetEndOfFile(env->me_fd))
2332 SetFilePointer(env->me_fd, 0, NULL, 0);
2334 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2335 sizehi, sizelo, NULL);
2338 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2346 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2348 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2350 if (env->me_map == MAP_FAILED)
2355 meta.mm_mapsize = env->me_mapsize;
2356 if (flags & MDB_FIXEDMAP)
2357 meta.mm_address = env->me_map;
2358 i = mdb_env_init_meta(env, &meta);
2359 if (i != MDB_SUCCESS) {
2360 munmap(env->me_map, env->me_mapsize);
2364 env->me_psize = meta.mm_psize;
2366 env->me_maxpg = env->me_mapsize / env->me_psize;
2368 p = (MDB_page *)env->me_map;
2369 env->me_metas[0] = METADATA(p);
2370 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2372 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2375 DPRINTF("opened database version %u, pagesize %u",
2376 env->me_metas[toggle]->mm_version, env->me_psize);
2377 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2378 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2379 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2380 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2381 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2382 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2388 /** Release a reader thread's slot in the reader lock table.
2389 * This function is called automatically when a thread exits.
2390 * Windows doesn't support destructor callbacks for thread-specific storage,
2391 * so this function is not compiled there.
2392 * @param[in] ptr This points to the slot in the reader lock table.
2395 mdb_env_reader_dest(void *ptr)
2397 MDB_reader *reader = ptr;
2399 reader->mr_txnid = 0;
2405 /** Downgrade the exclusive lock on the region back to shared */
2407 mdb_env_share_locks(MDB_env *env)
2411 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2413 env->me_txns->mti_me_toggle = toggle;
2414 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2419 /* First acquire a shared lock. The Unlock will
2420 * then release the existing exclusive lock.
2422 memset(&ov, 0, sizeof(ov));
2423 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2424 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2428 struct flock lock_info;
2429 /* The shared lock replaces the existing lock */
2430 memset((void *)&lock_info, 0, sizeof(lock_info));
2431 lock_info.l_type = F_RDLCK;
2432 lock_info.l_whence = SEEK_SET;
2433 lock_info.l_start = 0;
2434 lock_info.l_len = 1;
2435 fcntl(env->me_lfd, F_SETLK, &lock_info);
2439 #if defined(_WIN32) || defined(__APPLE__)
2441 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2443 * @(#) $Revision: 5.1 $
2444 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2445 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2447 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2451 * Please do not copyright this code. This code is in the public domain.
2453 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2454 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2455 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2456 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2457 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2458 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2459 * PERFORMANCE OF THIS SOFTWARE.
2462 * chongo <Landon Curt Noll> /\oo/\
2463 * http://www.isthe.com/chongo/
2465 * Share and Enjoy! :-)
2468 typedef unsigned long long mdb_hash_t;
2469 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2471 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2472 * @param[in] str string to hash
2473 * @param[in] hval initial value for hash
2474 * @return 64 bit hash
2476 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2477 * hval arg on the first call.
2480 mdb_hash_str(char *str, mdb_hash_t hval)
2482 unsigned char *s = (unsigned char *)str; /* unsigned string */
2484 * FNV-1a hash each octet of the string
2487 /* xor the bottom with the current octet */
2488 hval ^= (mdb_hash_t)*s++;
2490 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2491 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2492 (hval << 7) + (hval << 8) + (hval << 40);
2494 /* return our new hash value */
2498 /** Hash the string and output the hash in hex.
2499 * @param[in] str string to hash
2500 * @param[out] hexbuf an array of 17 chars to hold the hash
2503 mdb_hash_hex(char *str, char *hexbuf)
2506 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2507 for (i=0; i<8; i++) {
2508 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2514 /** Open and/or initialize the lock region for the environment.
2515 * @param[in] env The MDB environment.
2516 * @param[in] lpath The pathname of the file used for the lock region.
2517 * @param[in] mode The Unix permissions for the file, if we create it.
2518 * @param[out] excl Set to true if we got an exclusive lock on the region.
2519 * @return 0 on success, non-zero on failure.
2522 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2530 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2531 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2532 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2536 /* Try to get exclusive lock. If we succeed, then
2537 * nobody is using the lock region and we should initialize it.
2540 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2544 memset(&ov, 0, sizeof(ov));
2545 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2551 size = GetFileSize(env->me_lfd, NULL);
2553 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2557 /* Try to get exclusive lock. If we succeed, then
2558 * nobody is using the lock region and we should initialize it.
2561 struct flock lock_info;
2562 memset((void *)&lock_info, 0, sizeof(lock_info));
2563 lock_info.l_type = F_WRLCK;
2564 lock_info.l_whence = SEEK_SET;
2565 lock_info.l_start = 0;
2566 lock_info.l_len = 1;
2567 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2571 lock_info.l_type = F_RDLCK;
2572 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2579 size = lseek(env->me_lfd, 0, SEEK_END);
2581 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2582 if (size < rsize && *excl) {
2584 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2585 if (!SetEndOfFile(env->me_lfd)) {
2590 if (ftruncate(env->me_lfd, rsize) != 0) {
2597 size = rsize - sizeof(MDB_txninfo);
2598 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2603 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2609 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2611 if (!env->me_txns) {
2617 env->me_txns = (MDB_txninfo *)mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2619 if (env->me_txns == MAP_FAILED) {
2627 if (!mdb_sec_inited) {
2628 InitializeSecurityDescriptor(&mdb_null_sd,
2629 SECURITY_DESCRIPTOR_REVISION);
2630 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2631 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2632 mdb_all_sa.bInheritHandle = FALSE;
2633 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2636 mdb_hash_hex(lpath, hexbuf);
2637 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2638 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2639 if (!env->me_rmutex) {
2643 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2644 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2645 if (!env->me_wmutex) {
2652 mdb_hash_hex(lpath, hexbuf);
2653 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2654 if (sem_unlink(env->me_txns->mti_rmname)) {
2656 if (rc != ENOENT && rc != EINVAL)
2659 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2660 if (!env->me_rmutex) {
2664 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2665 if (sem_unlink(env->me_txns->mti_wmname)) {
2667 if (rc != ENOENT && rc != EINVAL)
2670 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2671 if (!env->me_wmutex) {
2675 #else /* __APPLE__ */
2676 pthread_mutexattr_t mattr;
2678 pthread_mutexattr_init(&mattr);
2679 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2683 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2684 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2685 #endif /* __APPLE__ */
2687 env->me_txns->mti_version = MDB_VERSION;
2688 env->me_txns->mti_magic = MDB_MAGIC;
2689 env->me_txns->mti_txnid = 0;
2690 env->me_txns->mti_numreaders = 0;
2691 env->me_txns->mti_me_toggle = 0;
2694 if (env->me_txns->mti_magic != MDB_MAGIC) {
2695 DPUTS("lock region has invalid magic");
2699 if (env->me_txns->mti_version != MDB_VERSION) {
2700 DPRINTF("lock region is version %u, expected version %u",
2701 env->me_txns->mti_version, MDB_VERSION);
2702 rc = MDB_VERSION_MISMATCH;
2706 if (rc != EACCES && rc != EAGAIN) {
2710 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2711 if (!env->me_rmutex) {
2715 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2716 if (!env->me_wmutex) {
2722 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2723 if (!env->me_rmutex) {
2727 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2728 if (!env->me_wmutex) {
2738 env->me_lfd = INVALID_HANDLE_VALUE;
2743 /** The name of the lock file in the DB environment */
2744 #define LOCKNAME "/lock.mdb"
2745 /** The name of the data file in the DB environment */
2746 #define DATANAME "/data.mdb"
2747 /** The suffix of the lock file when no subdir is used */
2748 #define LOCKSUFF "-lock"
2751 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2753 int oflags, rc, len, excl;
2754 char *lpath, *dpath;
2757 if (flags & MDB_NOSUBDIR) {
2758 rc = len + sizeof(LOCKSUFF) + len + 1;
2760 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2765 if (flags & MDB_NOSUBDIR) {
2766 dpath = lpath + len + sizeof(LOCKSUFF);
2767 sprintf(lpath, "%s" LOCKSUFF, path);
2768 strcpy(dpath, path);
2770 dpath = lpath + len + sizeof(LOCKNAME);
2771 sprintf(lpath, "%s" LOCKNAME, path);
2772 sprintf(dpath, "%s" DATANAME, path);
2775 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2780 if (F_ISSET(flags, MDB_RDONLY)) {
2781 oflags = GENERIC_READ;
2782 len = OPEN_EXISTING;
2784 oflags = GENERIC_READ|GENERIC_WRITE;
2787 mode = FILE_ATTRIBUTE_NORMAL;
2788 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2789 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2794 if (F_ISSET(flags, MDB_RDONLY))
2797 oflags = O_RDWR | O_CREAT;
2799 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2805 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2806 /* synchronous fd for meta writes */
2808 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2809 mode |= FILE_FLAG_WRITE_THROUGH;
2810 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2811 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2816 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2817 oflags |= MDB_DSYNC;
2818 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2823 env->me_path = strdup(path);
2824 DPRINTF("opened dbenv %p", (void *) env);
2825 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2826 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2828 mdb_env_share_locks(env);
2829 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2830 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2831 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2837 if (env->me_fd != INVALID_HANDLE_VALUE) {
2839 env->me_fd = INVALID_HANDLE_VALUE;
2841 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2843 env->me_lfd = INVALID_HANDLE_VALUE;
2851 mdb_env_close(MDB_env *env)
2858 VGMEMP_DESTROY(env);
2859 while (env->me_dpages) {
2860 dp = env->me_dpages;
2861 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
2862 env->me_dpages = dp->mp_next;
2866 free(env->me_dbs[1]);
2867 free(env->me_dbs[0]);
2871 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2872 pthread_key_delete(env->me_txkey);
2875 munmap(env->me_map, env->me_mapsize);
2880 pid_t pid = getpid();
2882 for (i=0; i<env->me_txns->mti_numreaders; i++)
2883 if (env->me_txns->mti_readers[i].mr_pid == pid)
2884 env->me_txns->mti_readers[i].mr_pid = 0;
2885 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2888 mdb_midl_free(env->me_free_pgs);
2892 /** Compare two items pointing at aligned size_t's */
2894 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2896 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2897 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2900 /** Compare two items pointing at aligned int's */
2902 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2904 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2905 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2908 /** Compare two items pointing at ints of unknown alignment.
2909 * Nodes and keys are guaranteed to be 2-byte aligned.
2912 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2914 #if BYTE_ORDER == LITTLE_ENDIAN
2915 unsigned short *u, *c;
2918 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2919 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2922 } while(!x && u > (unsigned short *)a->mv_data);
2925 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2929 /** Compare two items lexically */
2931 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2938 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2944 diff = memcmp(a->mv_data, b->mv_data, len);
2945 return diff ? diff : len_diff<0 ? -1 : len_diff;
2948 /** Compare two items in reverse byte order */
2950 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2952 const unsigned char *p1, *p2, *p1_lim;
2956 p1_lim = (const unsigned char *)a->mv_data;
2957 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2958 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2960 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2966 while (p1 > p1_lim) {
2967 diff = *--p1 - *--p2;
2971 return len_diff<0 ? -1 : len_diff;
2974 /** Search for key within a page, using binary search.
2975 * Returns the smallest entry larger or equal to the key.
2976 * If exactp is non-null, stores whether the found entry was an exact match
2977 * in *exactp (1 or 0).
2978 * Updates the cursor index with the index of the found entry.
2979 * If no entry larger or equal to the key is found, returns NULL.
2982 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2984 unsigned int i = 0, nkeys;
2987 MDB_page *mp = mc->mc_pg[mc->mc_top];
2988 MDB_node *node = NULL;
2993 nkeys = NUMKEYS(mp);
2998 COPY_PGNO(pgno, mp->mp_pgno);
2999 DPRINTF("searching %u keys in %s %spage %zu",
3000 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3007 low = IS_LEAF(mp) ? 0 : 1;
3009 cmp = mc->mc_dbx->md_cmp;
3011 /* Branch pages have no data, so if using integer keys,
3012 * alignment is guaranteed. Use faster mdb_cmp_int.
3014 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3015 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3022 nodekey.mv_size = mc->mc_db->md_pad;
3023 node = NODEPTR(mp, 0); /* fake */
3024 while (low <= high) {
3025 i = (low + high) >> 1;
3026 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3027 rc = cmp(key, &nodekey);
3028 DPRINTF("found leaf index %u [%s], rc = %i",
3029 i, DKEY(&nodekey), rc);
3038 while (low <= high) {
3039 i = (low + high) >> 1;
3041 node = NODEPTR(mp, i);
3042 nodekey.mv_size = NODEKSZ(node);
3043 nodekey.mv_data = NODEKEY(node);
3045 rc = cmp(key, &nodekey);
3048 DPRINTF("found leaf index %u [%s], rc = %i",
3049 i, DKEY(&nodekey), rc);
3051 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3052 i, DKEY(&nodekey), NODEPGNO(node), rc);
3063 if (rc > 0) { /* Found entry is less than the key. */
3064 i++; /* Skip to get the smallest entry larger than key. */
3066 node = NODEPTR(mp, i);
3069 *exactp = (rc == 0);
3070 /* store the key index */
3071 mc->mc_ki[mc->mc_top] = i;
3073 /* There is no entry larger or equal to the key. */
3076 /* nodeptr is fake for LEAF2 */
3082 mdb_cursor_adjust(MDB_cursor *mc, func)
3086 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3087 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3094 /** Pop a page off the top of the cursor's stack. */
3096 mdb_cursor_pop(MDB_cursor *mc)
3101 top = mc->mc_pg[mc->mc_top];
3106 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3107 mc->mc_dbi, (void *) mc);
3111 /** Push a page onto the top of the cursor's stack. */
3113 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3115 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3116 mc->mc_dbi, (void *) mc);
3118 if (mc->mc_snum >= CURSOR_STACK) {
3119 assert(mc->mc_snum < CURSOR_STACK);
3123 mc->mc_top = mc->mc_snum++;
3124 mc->mc_pg[mc->mc_top] = mp;
3125 mc->mc_ki[mc->mc_top] = 0;
3130 /** Find the address of the page corresponding to a given page number.
3131 * @param[in] txn the transaction for this access.
3132 * @param[in] pgno the page number for the page to retrieve.
3133 * @param[out] ret address of a pointer where the page's address will be stored.
3134 * @return 0 on success, non-zero on failure.
3137 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3141 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3143 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3144 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3145 p = txn->mt_u.dirty_list[x].mptr;
3149 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3150 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3154 DPRINTF("page %zu not found", pgno);
3157 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3160 /** Search for the page a given key should be in.
3161 * Pushes parent pages on the cursor stack. This function continues a
3162 * search on a cursor that has already been initialized. (Usually by
3163 * #mdb_page_search() but also by #mdb_node_move().)
3164 * @param[in,out] mc the cursor for this operation.
3165 * @param[in] key the key to search for. If NULL, search for the lowest
3166 * page. (This is used by #mdb_cursor_first().)
3167 * @param[in] modify If true, visited pages are updated with new page numbers.
3168 * @return 0 on success, non-zero on failure.
3171 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3173 MDB_page *mp = mc->mc_pg[mc->mc_top];
3178 while (IS_BRANCH(mp)) {
3182 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3183 assert(NUMKEYS(mp) > 1);
3184 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3186 if (key == NULL) /* Initialize cursor to first page. */
3188 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3189 /* cursor to last page */
3193 node = mdb_node_search(mc, key, &exact);
3195 i = NUMKEYS(mp) - 1;
3197 i = mc->mc_ki[mc->mc_top];
3206 DPRINTF("following index %u for key [%s]",
3208 assert(i < NUMKEYS(mp));
3209 node = NODEPTR(mp, i);
3211 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3214 mc->mc_ki[mc->mc_top] = i;
3215 if ((rc = mdb_cursor_push(mc, mp)))
3219 if ((rc = mdb_page_touch(mc)) != 0)
3221 mp = mc->mc_pg[mc->mc_top];
3226 DPRINTF("internal error, index points to a %02X page!?",
3228 return MDB_CORRUPTED;
3231 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3232 key ? DKEY(key) : NULL);
3237 /** Search for the page a given key should be in.
3238 * Pushes parent pages on the cursor stack. This function just sets up
3239 * the search; it finds the root page for \b mc's database and sets this
3240 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3241 * called to complete the search.
3242 * @param[in,out] mc the cursor for this operation.
3243 * @param[in] key the key to search for. If NULL, search for the lowest
3244 * page. (This is used by #mdb_cursor_first().)
3245 * @param[in] modify If true, visited pages are updated with new page numbers.
3246 * @return 0 on success, non-zero on failure.
3249 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3254 /* Make sure the txn is still viable, then find the root from
3255 * the txn's db table.
3257 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3258 DPUTS("transaction has failed, must abort");
3261 /* Make sure we're using an up-to-date root */
3262 if (mc->mc_dbi > MAIN_DBI) {
3263 if ((*mc->mc_dbflag & DB_STALE) ||
3264 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3266 unsigned char dbflag = 0;
3267 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3268 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3271 if (*mc->mc_dbflag & DB_STALE) {
3274 MDB_node *leaf = mdb_node_search(&mc2,
3275 &mc->mc_dbx->md_name, &exact);
3277 return MDB_NOTFOUND;
3278 mdb_node_read(mc->mc_txn, leaf, &data);
3279 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3283 *mc->mc_dbflag = dbflag;
3286 root = mc->mc_db->md_root;
3288 if (root == P_INVALID) { /* Tree is empty. */
3289 DPUTS("tree is empty");
3290 return MDB_NOTFOUND;
3295 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3301 DPRINTF("db %u root page %zu has flags 0x%X",
3302 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3305 if ((rc = mdb_page_touch(mc)))
3309 return mdb_page_search_root(mc, key, modify);
3312 /** Return the data associated with a given node.
3313 * @param[in] txn The transaction for this operation.
3314 * @param[in] leaf The node being read.
3315 * @param[out] data Updated to point to the node's data.
3316 * @return 0 on success, non-zero on failure.
3319 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3321 MDB_page *omp; /* overflow page */
3325 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3326 data->mv_size = NODEDSZ(leaf);
3327 data->mv_data = NODEDATA(leaf);
3331 /* Read overflow data.
3333 data->mv_size = NODEDSZ(leaf);
3334 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3335 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3336 DPRINTF("read overflow page %zu failed", pgno);
3339 data->mv_data = METADATA(omp);
3345 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3346 MDB_val *key, MDB_val *data)
3355 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3357 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3360 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3364 mdb_cursor_init(&mc, txn, dbi, &mx);
3365 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3368 /** Find a sibling for a page.
3369 * Replaces the page at the top of the cursor's stack with the
3370 * specified sibling, if one exists.
3371 * @param[in] mc The cursor for this operation.
3372 * @param[in] move_right Non-zero if the right sibling is requested,
3373 * otherwise the left sibling.
3374 * @return 0 on success, non-zero on failure.
3377 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3383 if (mc->mc_snum < 2) {
3384 return MDB_NOTFOUND; /* root has no siblings */
3388 DPRINTF("parent page is page %zu, index %u",
3389 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3391 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3392 : (mc->mc_ki[mc->mc_top] == 0)) {
3393 DPRINTF("no more keys left, moving to %s sibling",
3394 move_right ? "right" : "left");
3395 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3399 mc->mc_ki[mc->mc_top]++;
3401 mc->mc_ki[mc->mc_top]--;
3402 DPRINTF("just moving to %s index key %u",
3403 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3405 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3407 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3408 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3411 mdb_cursor_push(mc, mp);
3416 /** Move the cursor to the next data item. */
3418 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3424 if (mc->mc_flags & C_EOF) {
3425 return MDB_NOTFOUND;
3428 assert(mc->mc_flags & C_INITIALIZED);
3430 mp = mc->mc_pg[mc->mc_top];
3432 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3433 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3434 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3435 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3436 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3437 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3441 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3442 if (op == MDB_NEXT_DUP)
3443 return MDB_NOTFOUND;
3447 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3449 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3450 DPUTS("=====> move to next sibling page");
3451 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3452 mc->mc_flags |= C_EOF;
3453 mc->mc_flags &= ~C_INITIALIZED;
3454 return MDB_NOTFOUND;
3456 mp = mc->mc_pg[mc->mc_top];
3457 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3459 mc->mc_ki[mc->mc_top]++;
3461 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3462 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3465 key->mv_size = mc->mc_db->md_pad;
3466 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3470 assert(IS_LEAF(mp));
3471 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3473 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3474 mdb_xcursor_init1(mc, leaf);
3477 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3480 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3481 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3482 if (rc != MDB_SUCCESS)
3487 MDB_SET_KEY(leaf, key);
3491 /** Move the cursor to the previous data item. */
3493 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3499 assert(mc->mc_flags & C_INITIALIZED);
3501 mp = mc->mc_pg[mc->mc_top];
3503 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3504 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3505 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3507 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3508 if (op != MDB_PREV || rc == MDB_SUCCESS)
3511 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3512 if (op == MDB_PREV_DUP)
3513 return MDB_NOTFOUND;
3518 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3520 if (mc->mc_ki[mc->mc_top] == 0) {
3521 DPUTS("=====> move to prev sibling page");
3522 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3523 mc->mc_flags &= ~C_INITIALIZED;
3524 return MDB_NOTFOUND;
3526 mp = mc->mc_pg[mc->mc_top];
3527 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3528 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3530 mc->mc_ki[mc->mc_top]--;
3532 mc->mc_flags &= ~C_EOF;
3534 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3535 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3538 key->mv_size = mc->mc_db->md_pad;
3539 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3543 assert(IS_LEAF(mp));
3544 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3546 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3547 mdb_xcursor_init1(mc, leaf);
3550 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3553 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3554 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3555 if (rc != MDB_SUCCESS)
3560 MDB_SET_KEY(leaf, key);
3564 /** Set the cursor on a specific data item. */
3566 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3567 MDB_cursor_op op, int *exactp)
3576 assert(key->mv_size > 0);
3578 /* See if we're already on the right page */
3579 if (mc->mc_flags & C_INITIALIZED) {
3582 mp = mc->mc_pg[mc->mc_top];
3584 mc->mc_ki[mc->mc_top] = 0;
3585 return MDB_NOTFOUND;
3587 if (mp->mp_flags & P_LEAF2) {
3588 nodekey.mv_size = mc->mc_db->md_pad;
3589 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3591 leaf = NODEPTR(mp, 0);
3592 MDB_SET_KEY(leaf, &nodekey);
3594 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3596 /* Probably happens rarely, but first node on the page
3597 * was the one we wanted.
3599 mc->mc_ki[mc->mc_top] = 0;
3600 leaf = NODEPTR(mp, 0);
3607 unsigned int nkeys = NUMKEYS(mp);
3609 if (mp->mp_flags & P_LEAF2) {
3610 nodekey.mv_data = LEAF2KEY(mp,
3611 nkeys-1, nodekey.mv_size);
3613 leaf = NODEPTR(mp, nkeys-1);
3614 MDB_SET_KEY(leaf, &nodekey);
3616 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3618 /* last node was the one we wanted */
3619 mc->mc_ki[mc->mc_top] = nkeys-1;
3620 leaf = NODEPTR(mp, nkeys-1);
3626 /* This is definitely the right page, skip search_page */
3631 /* If any parents have right-sibs, search.
3632 * Otherwise, there's nothing further.
3634 for (i=0; i<mc->mc_top; i++)
3636 NUMKEYS(mc->mc_pg[i])-1)
3638 if (i == mc->mc_top) {
3639 /* There are no other pages */
3640 mc->mc_ki[mc->mc_top] = nkeys;
3641 return MDB_NOTFOUND;
3645 /* There are no other pages */
3646 mc->mc_ki[mc->mc_top] = 0;
3647 return MDB_NOTFOUND;
3651 rc = mdb_page_search(mc, key, 0);
3652 if (rc != MDB_SUCCESS)
3655 mp = mc->mc_pg[mc->mc_top];
3656 assert(IS_LEAF(mp));
3659 leaf = mdb_node_search(mc, key, exactp);
3660 if (exactp != NULL && !*exactp) {
3661 /* MDB_SET specified and not an exact match. */
3662 return MDB_NOTFOUND;
3666 DPUTS("===> inexact leaf not found, goto sibling");
3667 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3668 return rc; /* no entries matched */
3669 mp = mc->mc_pg[mc->mc_top];
3670 assert(IS_LEAF(mp));
3671 leaf = NODEPTR(mp, 0);
3675 mc->mc_flags |= C_INITIALIZED;
3676 mc->mc_flags &= ~C_EOF;
3679 key->mv_size = mc->mc_db->md_pad;
3680 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3684 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3685 mdb_xcursor_init1(mc, leaf);
3688 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3689 if (op == MDB_SET || op == MDB_SET_RANGE) {
3690 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3693 if (op == MDB_GET_BOTH) {
3699 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3700 if (rc != MDB_SUCCESS)
3703 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3705 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3707 rc = mc->mc_dbx->md_dcmp(data, &d2);
3709 if (op == MDB_GET_BOTH || rc > 0)
3710 return MDB_NOTFOUND;
3715 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3716 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3721 /* The key already matches in all other cases */
3722 if (op == MDB_SET_RANGE)
3723 MDB_SET_KEY(leaf, key);
3724 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3729 /** Move the cursor to the first item in the database. */
3731 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3736 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3737 rc = mdb_page_search(mc, NULL, 0);
3738 if (rc != MDB_SUCCESS)
3741 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3743 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3744 mc->mc_flags |= C_INITIALIZED;
3745 mc->mc_flags &= ~C_EOF;
3747 mc->mc_ki[mc->mc_top] = 0;
3749 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3750 key->mv_size = mc->mc_db->md_pad;
3751 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3756 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3757 mdb_xcursor_init1(mc, leaf);
3758 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3763 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3764 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3768 MDB_SET_KEY(leaf, key);
3772 /** Move the cursor to the last item in the database. */
3774 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3780 lkey.mv_size = MAXKEYSIZE+1;
3781 lkey.mv_data = NULL;
3783 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3784 rc = mdb_page_search(mc, &lkey, 0);
3785 if (rc != MDB_SUCCESS)
3788 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3790 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3791 mc->mc_flags |= C_INITIALIZED;
3792 mc->mc_flags &= ~C_EOF;
3794 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3796 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3797 key->mv_size = mc->mc_db->md_pad;
3798 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3803 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3804 mdb_xcursor_init1(mc, leaf);
3805 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3810 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3811 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3816 MDB_SET_KEY(leaf, key);
3821 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3831 case MDB_GET_BOTH_RANGE:
3832 if (data == NULL || mc->mc_xcursor == NULL) {
3839 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3841 } else if (op == MDB_SET_RANGE)
3842 rc = mdb_cursor_set(mc, key, data, op, NULL);
3844 rc = mdb_cursor_set(mc, key, data, op, &exact);
3846 case MDB_GET_MULTIPLE:
3848 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3849 !(mc->mc_flags & C_INITIALIZED)) {
3854 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3855 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3858 case MDB_NEXT_MULTIPLE:
3860 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3864 if (!(mc->mc_flags & C_INITIALIZED))
3865 rc = mdb_cursor_first(mc, key, data);
3867 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3868 if (rc == MDB_SUCCESS) {
3869 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3872 mx = &mc->mc_xcursor->mx_cursor;
3873 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3875 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3876 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3884 case MDB_NEXT_NODUP:
3885 if (!(mc->mc_flags & C_INITIALIZED))
3886 rc = mdb_cursor_first(mc, key, data);
3888 rc = mdb_cursor_next(mc, key, data, op);
3892 case MDB_PREV_NODUP:
3893 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3894 rc = mdb_cursor_last(mc, key, data);
3896 rc = mdb_cursor_prev(mc, key, data, op);
3899 rc = mdb_cursor_first(mc, key, data);
3903 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3904 !(mc->mc_flags & C_INITIALIZED) ||
3905 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3909 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3912 rc = mdb_cursor_last(mc, key, data);
3916 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3917 !(mc->mc_flags & C_INITIALIZED) ||
3918 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3922 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3925 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3933 /** Touch all the pages in the cursor stack.
3934 * Makes sure all the pages are writable, before attempting a write operation.
3935 * @param[in] mc The cursor to operate on.
3938 mdb_cursor_touch(MDB_cursor *mc)
3942 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3944 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3945 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3948 *mc->mc_dbflag = DB_DIRTY;
3950 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3951 rc = mdb_page_touch(mc);
3955 mc->mc_top = mc->mc_snum-1;
3960 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3963 MDB_node *leaf = NULL;
3964 MDB_val xdata, *rdata, dkey;
3968 unsigned int mcount = 0;
3971 char pbuf[MDB_PAGESIZE];
3972 char dbuf[MAXKEYSIZE+1];
3973 unsigned int nflags;
3976 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3979 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3980 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3984 if (flags == MDB_CURRENT) {
3985 if (!(mc->mc_flags & C_INITIALIZED))
3988 } else if (mc->mc_db->md_root == P_INVALID) {
3990 /* new database, write a root leaf page */
3991 DPUTS("allocating new root leaf page");
3992 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3996 mdb_cursor_push(mc, np);
3997 mc->mc_db->md_root = np->mp_pgno;
3998 mc->mc_db->md_depth++;
3999 *mc->mc_dbflag = DB_DIRTY;
4000 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4002 np->mp_flags |= P_LEAF2;
4003 mc->mc_flags |= C_INITIALIZED;
4009 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4010 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4011 DPRINTF("duplicate key [%s]", DKEY(key));
4013 return MDB_KEYEXIST;
4015 if (rc && rc != MDB_NOTFOUND)
4019 /* Cursor is positioned, now make sure all pages are writable */
4020 rc2 = mdb_cursor_touch(mc);
4025 /* The key already exists */
4026 if (rc == MDB_SUCCESS) {
4027 /* there's only a key anyway, so this is a no-op */
4028 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4029 unsigned int ksize = mc->mc_db->md_pad;
4030 if (key->mv_size != ksize)
4032 if (flags == MDB_CURRENT) {
4033 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4034 memcpy(ptr, key->mv_data, ksize);
4039 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4042 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4043 /* Was a single item before, must convert now */
4045 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4046 /* Just overwrite the current item */
4047 if (flags == MDB_CURRENT)
4050 dkey.mv_size = NODEDSZ(leaf);
4051 dkey.mv_data = NODEDATA(leaf);
4052 #if UINT_MAX < SIZE_MAX
4053 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4054 #ifdef MISALIGNED_OK
4055 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4057 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4060 /* if data matches, ignore it */
4061 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4062 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4064 /* create a fake page for the dup items */
4065 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4066 dkey.mv_data = dbuf;
4067 fp = (MDB_page *)pbuf;
4068 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4069 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4070 fp->mp_lower = PAGEHDRSZ;
4071 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4072 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4073 fp->mp_flags |= P_LEAF2;
4074 fp->mp_pad = data->mv_size;
4076 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4077 (dkey.mv_size & 1) + (data->mv_size & 1);
4079 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4082 xdata.mv_size = fp->mp_upper;
4083 xdata.mv_data = pbuf;
4087 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4088 /* See if we need to convert from fake page to subDB */
4090 unsigned int offset;
4093 fp = NODEDATA(leaf);
4094 if (flags == MDB_CURRENT) {
4095 fp->mp_flags |= P_DIRTY;
4096 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4097 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4101 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4102 offset = fp->mp_pad;
4104 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4106 offset += offset & 1;
4107 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4108 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4110 /* yes, convert it */
4112 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4113 dummy.md_pad = fp->mp_pad;
4114 dummy.md_flags = MDB_DUPFIXED;
4115 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4116 dummy.md_flags |= MDB_INTEGERKEY;
4119 dummy.md_branch_pages = 0;
4120 dummy.md_leaf_pages = 1;
4121 dummy.md_overflow_pages = 0;
4122 dummy.md_entries = NUMKEYS(fp);
4124 xdata.mv_size = sizeof(MDB_db);
4125 xdata.mv_data = &dummy;
4126 mp = mdb_page_alloc(mc, 1);
4129 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4130 flags |= F_DUPDATA|F_SUBDATA;
4131 dummy.md_root = mp->mp_pgno;
4133 /* no, just grow it */
4135 xdata.mv_size = NODEDSZ(leaf) + offset;
4136 xdata.mv_data = pbuf;
4137 mp = (MDB_page *)pbuf;
4138 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4141 mp->mp_flags = fp->mp_flags | P_DIRTY;
4142 mp->mp_pad = fp->mp_pad;
4143 mp->mp_lower = fp->mp_lower;
4144 mp->mp_upper = fp->mp_upper + offset;
4146 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4148 nsize = NODEDSZ(leaf) - fp->mp_upper;
4149 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4150 for (i=0; i<NUMKEYS(fp); i++)
4151 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4153 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4157 /* data is on sub-DB, just store it */
4158 flags |= F_DUPDATA|F_SUBDATA;
4162 /* same size, just replace it */
4163 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4164 NODEDSZ(leaf) == data->mv_size) {
4165 if (F_ISSET(flags, MDB_RESERVE))
4166 data->mv_data = NODEDATA(leaf);
4168 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4171 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4173 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4179 nflags = flags & NODE_ADD_FLAGS;
4180 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4181 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4182 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4183 nflags &= ~MDB_APPEND;
4184 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4186 /* There is room already in this leaf page. */
4187 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4188 if (rc == 0 && !do_sub) {
4189 /* Adjust other cursors pointing to mp */
4190 MDB_cursor *m2, *m3;
4191 MDB_dbi dbi = mc->mc_dbi;
4192 unsigned i = mc->mc_top;
4193 MDB_page *mp = mc->mc_pg[i];
4195 if (mc->mc_flags & C_SUB)
4198 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4199 if (mc->mc_flags & C_SUB)
4200 m3 = &m2->mc_xcursor->mx_cursor;
4203 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4204 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4211 if (rc != MDB_SUCCESS)
4212 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4214 /* Now store the actual data in the child DB. Note that we're
4215 * storing the user data in the keys field, so there are strict
4216 * size limits on dupdata. The actual data fields of the child
4217 * DB are all zero size.
4225 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4226 if (flags & MDB_CURRENT) {
4227 xflags = MDB_CURRENT;
4229 mdb_xcursor_init1(mc, leaf);
4230 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4232 /* converted, write the original data first */
4234 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4238 /* Adjust other cursors pointing to mp */
4240 unsigned i = mc->mc_top;
4241 MDB_page *mp = mc->mc_pg[i];
4243 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4244 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4245 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4246 mdb_xcursor_init1(m2, leaf);
4251 xflags |= (flags & MDB_APPEND);
4252 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4253 if (flags & F_SUBDATA) {
4254 db = NODEDATA(leaf);
4255 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4258 /* sub-writes might have failed so check rc again.
4259 * Don't increment count if we just replaced an existing item.
4261 if (!rc && !(flags & MDB_CURRENT))
4262 mc->mc_db->md_entries++;
4263 if (flags & MDB_MULTIPLE) {
4265 if (mcount < data[1].mv_size) {
4266 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4267 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4277 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4282 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4285 if (!mc->mc_flags & C_INITIALIZED)
4288 rc = mdb_cursor_touch(mc);
4292 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4294 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4295 if (flags != MDB_NODUPDATA) {
4296 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4297 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4299 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4300 /* If sub-DB still has entries, we're done */
4301 if (mc->mc_xcursor->mx_db.md_entries) {
4302 if (leaf->mn_flags & F_SUBDATA) {
4303 /* update subDB info */
4304 MDB_db *db = NODEDATA(leaf);
4305 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4307 /* shrink fake page */
4308 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4310 mc->mc_db->md_entries--;
4313 /* otherwise fall thru and delete the sub-DB */
4316 if (leaf->mn_flags & F_SUBDATA) {
4317 /* add all the child DB's pages to the free list */
4318 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4319 if (rc == MDB_SUCCESS) {
4320 mc->mc_db->md_entries -=
4321 mc->mc_xcursor->mx_db.md_entries;
4326 return mdb_cursor_del0(mc, leaf);
4329 /** Allocate and initialize new pages for a database.
4330 * @param[in] mc a cursor on the database being added to.
4331 * @param[in] flags flags defining what type of page is being allocated.
4332 * @param[in] num the number of pages to allocate. This is usually 1,
4333 * unless allocating overflow pages for a large record.
4334 * @return Address of a page, or NULL on failure.
4337 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4341 if ((np = mdb_page_alloc(mc, num)) == NULL)
4343 DPRINTF("allocated new mpage %zu, page size %u",
4344 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4345 np->mp_flags = flags | P_DIRTY;
4346 np->mp_lower = PAGEHDRSZ;
4347 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4350 mc->mc_db->md_branch_pages++;
4351 else if (IS_LEAF(np))
4352 mc->mc_db->md_leaf_pages++;
4353 else if (IS_OVERFLOW(np)) {
4354 mc->mc_db->md_overflow_pages += num;
4361 /** Calculate the size of a leaf node.
4362 * The size depends on the environment's page size; if a data item
4363 * is too large it will be put onto an overflow page and the node
4364 * size will only include the key and not the data. Sizes are always
4365 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4366 * of the #MDB_node headers.
4367 * @param[in] env The environment handle.
4368 * @param[in] key The key for the node.
4369 * @param[in] data The data for the node.
4370 * @return The number of bytes needed to store the node.
4373 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4377 sz = LEAFSIZE(key, data);
4378 if (sz >= env->me_psize / MDB_MINKEYS) {
4379 /* put on overflow page */
4380 sz -= data->mv_size - sizeof(pgno_t);
4384 return sz + sizeof(indx_t);
4387 /** Calculate the size of a branch node.
4388 * The size should depend on the environment's page size but since
4389 * we currently don't support spilling large keys onto overflow
4390 * pages, it's simply the size of the #MDB_node header plus the
4391 * size of the key. Sizes are always rounded up to an even number
4392 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4393 * @param[in] env The environment handle.
4394 * @param[in] key The key for the node.
4395 * @return The number of bytes needed to store the node.
4398 mdb_branch_size(MDB_env *env, MDB_val *key)
4403 if (sz >= env->me_psize / MDB_MINKEYS) {
4404 /* put on overflow page */
4405 /* not implemented */
4406 /* sz -= key->size - sizeof(pgno_t); */
4409 return sz + sizeof(indx_t);
4412 /** Add a node to the page pointed to by the cursor.
4413 * @param[in] mc The cursor for this operation.
4414 * @param[in] indx The index on the page where the new node should be added.
4415 * @param[in] key The key for the new node.
4416 * @param[in] data The data for the new node, if any.
4417 * @param[in] pgno The page number, if adding a branch node.
4418 * @param[in] flags Flags for the node.
4419 * @return 0 on success, non-zero on failure. Possible errors are:
4421 * <li>ENOMEM - failed to allocate overflow pages for the node.
4422 * <li>ENOSPC - there is insufficient room in the page. This error
4423 * should never happen since all callers already calculate the
4424 * page's free space before calling this function.
4428 mdb_node_add(MDB_cursor *mc, indx_t indx,
4429 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4432 size_t node_size = NODESIZE;
4435 MDB_page *mp = mc->mc_pg[mc->mc_top];
4436 MDB_page *ofp = NULL; /* overflow page */
4439 assert(mp->mp_upper >= mp->mp_lower);
4441 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4442 IS_LEAF(mp) ? "leaf" : "branch",
4443 IS_SUBP(mp) ? "sub-" : "",
4444 mp->mp_pgno, indx, data ? data->mv_size : 0,
4445 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4448 /* Move higher keys up one slot. */
4449 int ksize = mc->mc_db->md_pad, dif;
4450 char *ptr = LEAF2KEY(mp, indx, ksize);
4451 dif = NUMKEYS(mp) - indx;
4453 memmove(ptr+ksize, ptr, dif*ksize);
4454 /* insert new key */
4455 memcpy(ptr, key->mv_data, ksize);
4457 /* Just using these for counting */
4458 mp->mp_lower += sizeof(indx_t);
4459 mp->mp_upper -= ksize - sizeof(indx_t);
4464 node_size += key->mv_size;
4468 if (F_ISSET(flags, F_BIGDATA)) {
4469 /* Data already on overflow page. */
4470 node_size += sizeof(pgno_t);
4471 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4472 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4473 /* Put data on overflow page. */
4474 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4475 data->mv_size, node_size+data->mv_size);
4476 node_size += sizeof(pgno_t);
4477 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4479 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4482 node_size += data->mv_size;
4485 node_size += node_size & 1;
4487 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4488 DPRINTF("not enough room in page %zu, got %u ptrs",
4489 mp->mp_pgno, NUMKEYS(mp));
4490 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4491 mp->mp_upper - mp->mp_lower);
4492 DPRINTF("node size = %zu", node_size);
4496 /* Move higher pointers up one slot. */
4497 for (i = NUMKEYS(mp); i > indx; i--)
4498 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4500 /* Adjust free space offsets. */
4501 ofs = mp->mp_upper - node_size;
4502 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4503 mp->mp_ptrs[indx] = ofs;
4505 mp->mp_lower += sizeof(indx_t);
4507 /* Write the node data. */
4508 node = NODEPTR(mp, indx);
4509 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4510 node->mn_flags = flags;
4512 SETDSZ(node,data->mv_size);
4517 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4522 if (F_ISSET(flags, F_BIGDATA))
4523 memcpy(node->mn_data + key->mv_size, data->mv_data,
4525 else if (F_ISSET(flags, MDB_RESERVE))
4526 data->mv_data = node->mn_data + key->mv_size;
4528 memcpy(node->mn_data + key->mv_size, data->mv_data,
4531 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4533 if (F_ISSET(flags, MDB_RESERVE))
4534 data->mv_data = METADATA(ofp);
4536 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4543 /** Delete the specified node from a page.
4544 * @param[in] mp The page to operate on.
4545 * @param[in] indx The index of the node to delete.
4546 * @param[in] ksize The size of a node. Only used if the page is
4547 * part of a #MDB_DUPFIXED database.
4550 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4553 indx_t i, j, numkeys, ptr;
4560 COPY_PGNO(pgno, mp->mp_pgno);
4561 DPRINTF("delete node %u on %s page %zu", indx,
4562 IS_LEAF(mp) ? "leaf" : "branch", pgno);
4565 assert(indx < NUMKEYS(mp));
4568 int x = NUMKEYS(mp) - 1 - indx;
4569 base = LEAF2KEY(mp, indx, ksize);
4571 memmove(base, base + ksize, x * ksize);
4572 mp->mp_lower -= sizeof(indx_t);
4573 mp->mp_upper += ksize - sizeof(indx_t);
4577 node = NODEPTR(mp, indx);
4578 sz = NODESIZE + node->mn_ksize;
4580 if (F_ISSET(node->mn_flags, F_BIGDATA))
4581 sz += sizeof(pgno_t);
4583 sz += NODEDSZ(node);
4587 ptr = mp->mp_ptrs[indx];
4588 numkeys = NUMKEYS(mp);
4589 for (i = j = 0; i < numkeys; i++) {
4591 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4592 if (mp->mp_ptrs[i] < ptr)
4593 mp->mp_ptrs[j] += sz;
4598 base = (char *)mp + mp->mp_upper;
4599 memmove(base + sz, base, ptr - mp->mp_upper);
4601 mp->mp_lower -= sizeof(indx_t);
4605 /** Compact the main page after deleting a node on a subpage.
4606 * @param[in] mp The main page to operate on.
4607 * @param[in] indx The index of the subpage on the main page.
4610 mdb_node_shrink(MDB_page *mp, indx_t indx)
4617 indx_t i, numkeys, ptr;
4619 node = NODEPTR(mp, indx);
4620 sp = (MDB_page *)NODEDATA(node);
4621 osize = NODEDSZ(node);
4623 delta = sp->mp_upper - sp->mp_lower;
4624 SETDSZ(node, osize - delta);
4625 xp = (MDB_page *)((char *)sp + delta);
4627 /* shift subpage upward */
4629 nsize = NUMKEYS(sp) * sp->mp_pad;
4630 memmove(METADATA(xp), METADATA(sp), nsize);
4633 nsize = osize - sp->mp_upper;
4634 numkeys = NUMKEYS(sp);
4635 for (i=numkeys-1; i>=0; i--)
4636 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4638 xp->mp_upper = sp->mp_lower;
4639 xp->mp_lower = sp->mp_lower;
4640 xp->mp_flags = sp->mp_flags;
4641 xp->mp_pad = sp->mp_pad;
4642 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4644 /* shift lower nodes upward */
4645 ptr = mp->mp_ptrs[indx];
4646 numkeys = NUMKEYS(mp);
4647 for (i = 0; i < numkeys; i++) {
4648 if (mp->mp_ptrs[i] <= ptr)
4649 mp->mp_ptrs[i] += delta;
4652 base = (char *)mp + mp->mp_upper;
4653 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4654 mp->mp_upper += delta;
4657 /** Initial setup of a sorted-dups cursor.
4658 * Sorted duplicates are implemented as a sub-database for the given key.
4659 * The duplicate data items are actually keys of the sub-database.
4660 * Operations on the duplicate data items are performed using a sub-cursor
4661 * initialized when the sub-database is first accessed. This function does
4662 * the preliminary setup of the sub-cursor, filling in the fields that
4663 * depend only on the parent DB.
4664 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4667 mdb_xcursor_init0(MDB_cursor *mc)
4669 MDB_xcursor *mx = mc->mc_xcursor;
4671 mx->mx_cursor.mc_xcursor = NULL;
4672 mx->mx_cursor.mc_txn = mc->mc_txn;
4673 mx->mx_cursor.mc_db = &mx->mx_db;
4674 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4675 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4676 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4677 mx->mx_cursor.mc_snum = 0;
4678 mx->mx_cursor.mc_flags = C_SUB;
4679 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4680 mx->mx_dbx.md_dcmp = NULL;
4681 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4684 /** Final setup of a sorted-dups cursor.
4685 * Sets up the fields that depend on the data from the main cursor.
4686 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4687 * @param[in] node The data containing the #MDB_db record for the
4688 * sorted-dup database.
4691 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4693 MDB_xcursor *mx = mc->mc_xcursor;
4695 if (node->mn_flags & F_SUBDATA) {
4696 MDB_db *db = NODEDATA(node);
4698 mx->mx_cursor.mc_snum = 0;
4699 mx->mx_cursor.mc_flags = C_SUB;
4701 MDB_page *fp = NODEDATA(node);
4702 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4703 mx->mx_db.md_flags = 0;
4704 mx->mx_db.md_depth = 1;
4705 mx->mx_db.md_branch_pages = 0;
4706 mx->mx_db.md_leaf_pages = 1;
4707 mx->mx_db.md_overflow_pages = 0;
4708 mx->mx_db.md_entries = NUMKEYS(fp);
4709 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4710 mx->mx_cursor.mc_snum = 1;
4711 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4712 mx->mx_cursor.mc_top = 0;
4713 mx->mx_cursor.mc_pg[0] = fp;
4714 mx->mx_cursor.mc_ki[0] = 0;
4715 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4716 mx->mx_db.md_flags = MDB_DUPFIXED;
4717 mx->mx_db.md_pad = fp->mp_pad;
4718 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4719 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4722 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4724 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4726 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4727 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4728 #if UINT_MAX < SIZE_MAX
4729 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4730 #ifdef MISALIGNED_OK
4731 mx->mx_dbx.md_cmp = mdb_cmp_long;
4733 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4738 /** Initialize a cursor for a given transaction and database. */
4740 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4745 mc->mc_db = &txn->mt_dbs[dbi];
4746 mc->mc_dbx = &txn->mt_dbxs[dbi];
4747 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4751 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4753 mc->mc_xcursor = mx;
4754 mdb_xcursor_init0(mc);
4756 mc->mc_xcursor = NULL;
4761 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4764 MDB_xcursor *mx = NULL;
4765 size_t size = sizeof(MDB_cursor);
4767 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4770 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4771 size += sizeof(MDB_xcursor);
4773 if ((mc = malloc(size)) != NULL) {
4774 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4775 mx = (MDB_xcursor *)(mc + 1);
4777 mdb_cursor_init(mc, txn, dbi, mx);
4778 if (txn->mt_cursors) {
4779 mc->mc_next = txn->mt_cursors[dbi];
4780 txn->mt_cursors[dbi] = mc;
4782 mc->mc_flags |= C_ALLOCD;
4792 /* Return the count of duplicate data items for the current key */
4794 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4798 if (mc == NULL || countp == NULL)
4801 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4804 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4805 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4808 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4811 *countp = mc->mc_xcursor->mx_db.md_entries;
4817 mdb_cursor_close(MDB_cursor *mc)
4820 /* remove from txn, if tracked */
4821 if (mc->mc_txn->mt_cursors) {
4822 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4823 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4825 *prev = mc->mc_next;
4827 if (mc->mc_flags & C_ALLOCD)
4833 mdb_cursor_txn(MDB_cursor *mc)
4835 if (!mc) return NULL;
4840 mdb_cursor_dbi(MDB_cursor *mc)
4846 /** Replace the key for a node with a new key.
4847 * @param[in] mp The page containing the node to operate on.
4848 * @param[in] indx The index of the node to operate on.
4849 * @param[in] key The new key to use.
4850 * @return 0 on success, non-zero on failure.
4853 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4855 indx_t ptr, i, numkeys;
4862 node = NODEPTR(mp, indx);
4863 ptr = mp->mp_ptrs[indx];
4864 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4866 (int)node->mn_ksize, (char *)NODEKEY(node),
4870 delta = key->mv_size - node->mn_ksize;
4872 if (delta > 0 && SIZELEFT(mp) < delta) {
4873 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4877 numkeys = NUMKEYS(mp);
4878 for (i = 0; i < numkeys; i++) {
4879 if (mp->mp_ptrs[i] <= ptr)
4880 mp->mp_ptrs[i] -= delta;
4883 base = (char *)mp + mp->mp_upper;
4884 len = ptr - mp->mp_upper + NODESIZE;
4885 memmove(base - delta, base, len);
4886 mp->mp_upper -= delta;
4888 node = NODEPTR(mp, indx);
4889 node->mn_ksize = key->mv_size;
4892 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4897 /** Move a node from csrc to cdst.
4900 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4907 /* Mark src and dst as dirty. */
4908 if ((rc = mdb_page_touch(csrc)) ||
4909 (rc = mdb_page_touch(cdst)))
4912 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4913 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4914 key.mv_size = csrc->mc_db->md_pad;
4915 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4917 data.mv_data = NULL;
4919 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4920 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4921 unsigned int snum = csrc->mc_snum;
4923 /* must find the lowest key below src */
4924 mdb_page_search_root(csrc, NULL, 0);
4925 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4926 key.mv_size = NODEKSZ(s2);
4927 key.mv_data = NODEKEY(s2);
4928 csrc->mc_snum = snum--;
4929 csrc->mc_top = snum;
4931 key.mv_size = NODEKSZ(srcnode);
4932 key.mv_data = NODEKEY(srcnode);
4934 data.mv_size = NODEDSZ(srcnode);
4935 data.mv_data = NODEDATA(srcnode);
4937 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4938 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4939 csrc->mc_ki[csrc->mc_top],
4941 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4942 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4944 /* Add the node to the destination page.
4946 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4948 if (rc != MDB_SUCCESS)
4951 /* Delete the node from the source page.
4953 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4956 /* Adjust other cursors pointing to mp */
4957 MDB_cursor *m2, *m3;
4958 MDB_dbi dbi = csrc->mc_dbi;
4959 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4961 if (csrc->mc_flags & C_SUB)
4964 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4965 if (m2 == csrc) continue;
4966 if (csrc->mc_flags & C_SUB)
4967 m3 = &m2->mc_xcursor->mx_cursor;
4970 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4971 csrc->mc_ki[csrc->mc_top]) {
4972 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4973 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4978 /* Update the parent separators.
4980 if (csrc->mc_ki[csrc->mc_top] == 0) {
4981 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4982 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4983 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4985 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4986 key.mv_size = NODEKSZ(srcnode);
4987 key.mv_data = NODEKEY(srcnode);
4989 DPRINTF("update separator for source page %zu to [%s]",
4990 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4991 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4992 &key)) != MDB_SUCCESS)
4995 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4997 nullkey.mv_size = 0;
4998 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4999 assert(rc == MDB_SUCCESS);
5003 if (cdst->mc_ki[cdst->mc_top] == 0) {
5004 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5005 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5006 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5008 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5009 key.mv_size = NODEKSZ(srcnode);
5010 key.mv_data = NODEKEY(srcnode);
5012 DPRINTF("update separator for destination page %zu to [%s]",
5013 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5014 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5015 &key)) != MDB_SUCCESS)
5018 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5020 nullkey.mv_size = 0;
5021 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5022 assert(rc == MDB_SUCCESS);
5029 /** Merge one page into another.
5030 * The nodes from the page pointed to by \b csrc will
5031 * be copied to the page pointed to by \b cdst and then
5032 * the \b csrc page will be freed.
5033 * @param[in] csrc Cursor pointing to the source page.
5034 * @param[in] cdst Cursor pointing to the destination page.
5037 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5045 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5046 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5048 assert(csrc->mc_snum > 1); /* can't merge root page */
5049 assert(cdst->mc_snum > 1);
5051 /* Mark dst as dirty. */
5052 if ((rc = mdb_page_touch(cdst)))
5055 /* Move all nodes from src to dst.
5057 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5058 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5059 key.mv_size = csrc->mc_db->md_pad;
5060 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5061 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5062 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5063 if (rc != MDB_SUCCESS)
5065 key.mv_data = (char *)key.mv_data + key.mv_size;
5068 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5069 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5071 key.mv_size = srcnode->mn_ksize;
5072 key.mv_data = NODEKEY(srcnode);
5073 data.mv_size = NODEDSZ(srcnode);
5074 data.mv_data = NODEDATA(srcnode);
5075 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5076 if (rc != MDB_SUCCESS)
5081 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5082 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);
5084 /* Unlink the src page from parent and add to free list.
5086 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5087 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5089 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5093 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5094 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5095 csrc->mc_db->md_leaf_pages--;
5097 csrc->mc_db->md_branch_pages--;
5099 /* Adjust other cursors pointing to mp */
5100 MDB_cursor *m2, *m3;
5101 MDB_dbi dbi = csrc->mc_dbi;
5102 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5104 if (csrc->mc_flags & C_SUB)
5107 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5108 if (m2 == csrc) continue;
5109 if (csrc->mc_flags & C_SUB)
5110 m3 = &m2->mc_xcursor->mx_cursor;
5113 if (m3->mc_snum < csrc->mc_snum) continue;
5114 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5115 m3->mc_pg[csrc->mc_top] = mp;
5116 m3->mc_ki[csrc->mc_top] += nkeys;
5120 mdb_cursor_pop(csrc);
5122 return mdb_rebalance(csrc);
5125 /** Copy the contents of a cursor.
5126 * @param[in] csrc The cursor to copy from.
5127 * @param[out] cdst The cursor to copy to.
5130 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5134 cdst->mc_txn = csrc->mc_txn;
5135 cdst->mc_dbi = csrc->mc_dbi;
5136 cdst->mc_db = csrc->mc_db;
5137 cdst->mc_dbx = csrc->mc_dbx;
5138 cdst->mc_snum = csrc->mc_snum;
5139 cdst->mc_top = csrc->mc_top;
5140 cdst->mc_flags = csrc->mc_flags;
5142 for (i=0; i<csrc->mc_snum; i++) {
5143 cdst->mc_pg[i] = csrc->mc_pg[i];
5144 cdst->mc_ki[i] = csrc->mc_ki[i];
5148 /** Rebalance the tree after a delete operation.
5149 * @param[in] mc Cursor pointing to the page where rebalancing
5151 * @return 0 on success, non-zero on failure.
5154 mdb_rebalance(MDB_cursor *mc)
5164 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5165 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5166 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5167 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5171 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5174 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5175 DPRINTF("no need to rebalance page %zu, above fill threshold",
5181 if (mc->mc_snum < 2) {
5182 MDB_page *mp = mc->mc_pg[0];
5183 if (NUMKEYS(mp) == 0) {
5184 DPUTS("tree is completely empty");
5185 mc->mc_db->md_root = P_INVALID;
5186 mc->mc_db->md_depth = 0;
5187 mc->mc_db->md_leaf_pages = 0;
5188 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5192 /* Adjust other cursors pointing to mp */
5193 MDB_cursor *m2, *m3;
5194 MDB_dbi dbi = mc->mc_dbi;
5196 if (mc->mc_flags & C_SUB)
5199 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5200 if (m2 == mc) continue;
5201 if (mc->mc_flags & C_SUB)
5202 m3 = &m2->mc_xcursor->mx_cursor;
5205 if (m3->mc_snum < mc->mc_snum) continue;
5206 if (m3->mc_pg[0] == mp) {
5212 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5213 DPUTS("collapsing root page!");
5214 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5215 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5216 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5219 mc->mc_db->md_depth--;
5220 mc->mc_db->md_branch_pages--;
5222 /* Adjust other cursors pointing to mp */
5223 MDB_cursor *m2, *m3;
5224 MDB_dbi dbi = mc->mc_dbi;
5226 if (mc->mc_flags & C_SUB)
5229 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5230 if (m2 == mc) continue;
5231 if (mc->mc_flags & C_SUB)
5232 m3 = &m2->mc_xcursor->mx_cursor;
5235 if (m3->mc_snum < mc->mc_snum) continue;
5236 if (m3->mc_pg[0] == mp) {
5237 m3->mc_pg[0] = mc->mc_pg[0];
5242 DPUTS("root page doesn't need rebalancing");
5246 /* The parent (branch page) must have at least 2 pointers,
5247 * otherwise the tree is invalid.
5249 ptop = mc->mc_top-1;
5250 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5252 /* Leaf page fill factor is below the threshold.
5253 * Try to move keys from left or right neighbor, or
5254 * merge with a neighbor page.
5259 mdb_cursor_copy(mc, &mn);
5260 mn.mc_xcursor = NULL;
5262 if (mc->mc_ki[ptop] == 0) {
5263 /* We're the leftmost leaf in our parent.
5265 DPUTS("reading right neighbor");
5267 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5268 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5270 mn.mc_ki[mn.mc_top] = 0;
5271 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5273 /* There is at least one neighbor to the left.
5275 DPUTS("reading left neighbor");
5277 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5278 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5280 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5281 mc->mc_ki[mc->mc_top] = 0;
5284 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5285 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);
5287 /* If the neighbor page is above threshold and has at least two
5288 * keys, move one key from it.
5290 * Otherwise we should try to merge them.
5292 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5293 return mdb_node_move(&mn, mc);
5294 else { /* FIXME: if (has_enough_room()) */
5295 mc->mc_flags &= ~C_INITIALIZED;
5296 if (mc->mc_ki[ptop] == 0)
5297 return mdb_page_merge(&mn, mc);
5299 return mdb_page_merge(mc, &mn);
5303 /** Complete a delete operation started by #mdb_cursor_del(). */
5305 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5309 /* add overflow pages to free list */
5310 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5314 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5315 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5316 for (i=0; i<ovpages; i++) {
5317 DPRINTF("freed ov page %zu", pg);
5318 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5322 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5323 mc->mc_db->md_entries--;
5324 rc = mdb_rebalance(mc);
5325 if (rc != MDB_SUCCESS)
5326 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5332 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5333 MDB_val *key, MDB_val *data)
5338 MDB_val rdata, *xdata;
5342 assert(key != NULL);
5344 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5346 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5349 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5353 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5357 mdb_cursor_init(&mc, txn, dbi, &mx);
5368 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5370 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5374 /** Split a page and insert a new node.
5375 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5376 * The cursor will be updated to point to the actual page and index where
5377 * the node got inserted after the split.
5378 * @param[in] newkey The key for the newly inserted node.
5379 * @param[in] newdata The data for the newly inserted node.
5380 * @param[in] newpgno The page number, if the new node is a branch node.
5381 * @return 0 on success, non-zero on failure.
5384 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5385 unsigned int nflags)
5388 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5391 unsigned int i, j, split_indx, nkeys, pmax;
5393 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5395 MDB_page *mp, *rp, *pp;
5400 mp = mc->mc_pg[mc->mc_top];
5401 newindx = mc->mc_ki[mc->mc_top];
5403 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5404 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5405 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5407 if (mc->mc_snum < 2) {
5408 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5410 /* shift current top to make room for new parent */
5411 mc->mc_pg[1] = mc->mc_pg[0];
5412 mc->mc_ki[1] = mc->mc_ki[0];
5415 mc->mc_db->md_root = pp->mp_pgno;
5416 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5417 mc->mc_db->md_depth++;
5420 /* Add left (implicit) pointer. */
5421 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5422 /* undo the pre-push */
5423 mc->mc_pg[0] = mc->mc_pg[1];
5424 mc->mc_ki[0] = mc->mc_ki[1];
5425 mc->mc_db->md_root = mp->mp_pgno;
5426 mc->mc_db->md_depth--;
5433 ptop = mc->mc_top-1;
5434 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5437 /* Create a right sibling. */
5438 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5440 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5442 mdb_cursor_copy(mc, &mn);
5443 mn.mc_pg[mn.mc_top] = rp;
5444 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5446 if (nflags & MDB_APPEND) {
5447 mn.mc_ki[mn.mc_top] = 0;
5454 nkeys = NUMKEYS(mp);
5455 split_indx = nkeys / 2 + 1;
5460 unsigned int lsize, rsize, ksize;
5461 /* Move half of the keys to the right sibling */
5463 x = mc->mc_ki[mc->mc_top] - split_indx;
5464 ksize = mc->mc_db->md_pad;
5465 split = LEAF2KEY(mp, split_indx, ksize);
5466 rsize = (nkeys - split_indx) * ksize;
5467 lsize = (nkeys - split_indx) * sizeof(indx_t);
5468 mp->mp_lower -= lsize;
5469 rp->mp_lower += lsize;
5470 mp->mp_upper += rsize - lsize;
5471 rp->mp_upper -= rsize - lsize;
5472 sepkey.mv_size = ksize;
5473 if (newindx == split_indx) {
5474 sepkey.mv_data = newkey->mv_data;
5476 sepkey.mv_data = split;
5479 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5480 memcpy(rp->mp_ptrs, split, rsize);
5481 sepkey.mv_data = rp->mp_ptrs;
5482 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5483 memcpy(ins, newkey->mv_data, ksize);
5484 mp->mp_lower += sizeof(indx_t);
5485 mp->mp_upper -= ksize - sizeof(indx_t);
5488 memcpy(rp->mp_ptrs, split, x * ksize);
5489 ins = LEAF2KEY(rp, x, ksize);
5490 memcpy(ins, newkey->mv_data, ksize);
5491 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5492 rp->mp_lower += sizeof(indx_t);
5493 rp->mp_upper -= ksize - sizeof(indx_t);
5494 mc->mc_ki[mc->mc_top] = x;
5495 mc->mc_pg[mc->mc_top] = rp;
5500 /* For leaf pages, check the split point based on what
5501 * fits where, since otherwise add_node can fail.
5504 unsigned int psize, nsize;
5505 /* Maximum free space in an empty page */
5506 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5507 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5508 if (newindx < split_indx) {
5510 for (i=0; i<split_indx; i++) {
5511 node = NODEPTR(mp, i);
5512 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5513 if (F_ISSET(node->mn_flags, F_BIGDATA))
5514 psize += sizeof(pgno_t);
5516 psize += NODEDSZ(node);
5525 for (i=nkeys-1; i>=split_indx; i--) {
5526 node = NODEPTR(mp, i);
5527 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5528 if (F_ISSET(node->mn_flags, F_BIGDATA))
5529 psize += sizeof(pgno_t);
5531 psize += NODEDSZ(node);
5541 /* First find the separating key between the split pages.
5543 if (newindx == split_indx) {
5544 sepkey.mv_size = newkey->mv_size;
5545 sepkey.mv_data = newkey->mv_data;
5547 node = NODEPTR(mp, split_indx);
5548 sepkey.mv_size = node->mn_ksize;
5549 sepkey.mv_data = NODEKEY(node);
5553 DPRINTF("separator is [%s]", DKEY(&sepkey));
5555 /* Copy separator key to the parent.
5557 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5560 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5562 /* Right page might now have changed parent.
5563 * Check if left page also changed parent.
5565 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5566 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5567 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5568 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5572 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5575 if (rc != MDB_SUCCESS) {
5578 if (nflags & MDB_APPEND) {
5579 mc->mc_pg[mc->mc_top] = rp;
5580 mc->mc_ki[mc->mc_top] = 0;
5581 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5587 /* Move half of the keys to the right sibling. */
5589 /* grab a page to hold a temporary copy */
5590 copy = mdb_page_malloc(mc);
5594 copy->mp_pgno = mp->mp_pgno;
5595 copy->mp_flags = mp->mp_flags;
5596 copy->mp_lower = PAGEHDRSZ;
5597 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5598 mc->mc_pg[mc->mc_top] = copy;
5599 for (i = j = 0; i <= nkeys; j++) {
5600 if (i == split_indx) {
5601 /* Insert in right sibling. */
5602 /* Reset insert index for right sibling. */
5603 j = (i == newindx && ins_new);
5604 mc->mc_pg[mc->mc_top] = rp;
5607 if (i == newindx && !ins_new) {
5608 /* Insert the original entry that caused the split. */
5609 rkey.mv_data = newkey->mv_data;
5610 rkey.mv_size = newkey->mv_size;
5619 /* Update page and index for the new key. */
5621 mc->mc_pg[mc->mc_top] = copy;
5622 mc->mc_ki[mc->mc_top] = j;
5623 } else if (i == nkeys) {
5626 node = NODEPTR(mp, i);
5627 rkey.mv_data = NODEKEY(node);
5628 rkey.mv_size = node->mn_ksize;
5630 xdata.mv_data = NODEDATA(node);
5631 xdata.mv_size = NODEDSZ(node);
5634 pgno = NODEPGNO(node);
5635 flags = node->mn_flags;
5640 if (!IS_LEAF(mp) && j == 0) {
5641 /* First branch index doesn't need key data. */
5645 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5648 nkeys = NUMKEYS(copy);
5649 for (i=0; i<nkeys; i++)
5650 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5651 mp->mp_lower = copy->mp_lower;
5652 mp->mp_upper = copy->mp_upper;
5653 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5654 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5656 /* reset back to original page */
5657 if (!newindx || (newindx < split_indx)) {
5658 mc->mc_pg[mc->mc_top] = mp;
5659 if (nflags & MDB_RESERVE) {
5660 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5661 if (!(node->mn_flags & F_BIGDATA))
5662 newdata->mv_data = NODEDATA(node);
5666 /* return tmp page to freelist */
5667 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5668 VGMEMP_FREE(mc->mc_txn->mt_env, copy);
5669 mc->mc_txn->mt_env->me_dpages = copy;
5672 /* Adjust other cursors pointing to mp */
5673 MDB_cursor *m2, *m3;
5674 MDB_dbi dbi = mc->mc_dbi;
5676 if (mc->mc_flags & C_SUB)
5679 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5680 if (m2 == mc) continue;
5681 if (mc->mc_flags & C_SUB)
5682 m3 = &m2->mc_xcursor->mx_cursor;
5685 if (!(m3->mc_flags & C_INITIALIZED))
5689 for (i=m3->mc_top; i>0; i--) {
5690 m3->mc_ki[i+1] = m3->mc_ki[i];
5691 m3->mc_pg[i+1] = m3->mc_pg[i];
5693 m3->mc_ki[0] = mc->mc_ki[0];
5694 m3->mc_pg[0] = mc->mc_pg[0];
5698 if (m3->mc_pg[mc->mc_top] == mp) {
5699 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5700 m3->mc_pg[m3->mc_top] = rp;
5701 m3->mc_ki[m3->mc_top] -= split_indx;
5710 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5711 MDB_val *key, MDB_val *data, unsigned int flags)
5716 assert(key != NULL);
5717 assert(data != NULL);
5719 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5722 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5726 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5730 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5733 mdb_cursor_init(&mc, txn, dbi, &mx);
5734 return mdb_cursor_put(&mc, key, data, flags);
5737 /** Only a subset of the @ref mdb_env flags can be changed
5738 * at runtime. Changing other flags requires closing the environment
5739 * and re-opening it with the new flags.
5741 #define CHANGEABLE (MDB_NOSYNC)
5743 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5745 if ((flag & CHANGEABLE) != flag)
5748 env->me_flags |= flag;
5750 env->me_flags &= ~flag;
5755 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5760 *arg = env->me_flags;
5765 mdb_env_get_path(MDB_env *env, const char **arg)
5770 *arg = env->me_path;
5774 /** Common code for #mdb_stat() and #mdb_env_stat().
5775 * @param[in] env the environment to operate in.
5776 * @param[in] db the #MDB_db record containing the stats to return.
5777 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5778 * @return 0, this function always succeeds.
5781 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5783 arg->ms_psize = env->me_psize;
5784 arg->ms_depth = db->md_depth;
5785 arg->ms_branch_pages = db->md_branch_pages;
5786 arg->ms_leaf_pages = db->md_leaf_pages;
5787 arg->ms_overflow_pages = db->md_overflow_pages;
5788 arg->ms_entries = db->md_entries;
5793 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5797 if (env == NULL || arg == NULL)
5800 mdb_env_read_meta(env, &toggle);
5802 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5805 /** Set the default comparison functions for a database.
5806 * Called immediately after a database is opened to set the defaults.
5807 * The user can then override them with #mdb_set_compare() or
5808 * #mdb_set_dupsort().
5809 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5810 * @param[in] dbi A database handle returned by #mdb_open()
5813 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5815 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5816 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5817 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5818 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5820 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5822 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5823 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5824 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5825 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5827 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5828 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5829 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5831 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5834 txn->mt_dbxs[dbi].md_dcmp = NULL;
5838 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5843 int rc, dbflag, exact;
5846 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5847 mdb_default_cmp(txn, FREE_DBI);
5853 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5854 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5855 mdb_default_cmp(txn, MAIN_DBI);
5859 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5860 mdb_default_cmp(txn, MAIN_DBI);
5863 /* Is the DB already open? */
5865 for (i=2; i<txn->mt_numdbs; i++) {
5866 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5867 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5873 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5876 /* Find the DB info */
5880 key.mv_data = (void *)name;
5881 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5882 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5883 if (rc == MDB_SUCCESS) {
5884 /* make sure this is actually a DB */
5885 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5886 if (!(node->mn_flags & F_SUBDATA))
5888 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5889 /* Create if requested */
5891 data.mv_size = sizeof(MDB_db);
5892 data.mv_data = &dummy;
5893 memset(&dummy, 0, sizeof(dummy));
5894 dummy.md_root = P_INVALID;
5895 dummy.md_flags = flags & 0xffff;
5896 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5900 /* OK, got info, add to table */
5901 if (rc == MDB_SUCCESS) {
5902 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5903 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5904 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5905 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5906 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5907 *dbi = txn->mt_numdbs;
5908 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5909 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5910 mdb_default_cmp(txn, txn->mt_numdbs);
5917 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5919 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5922 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5925 void mdb_close(MDB_env *env, MDB_dbi dbi)
5928 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5930 ptr = env->me_dbxs[dbi].md_name.mv_data;
5931 env->me_dbxs[dbi].md_name.mv_data = NULL;
5932 env->me_dbxs[dbi].md_name.mv_size = 0;
5936 /** Add all the DB's pages to the free list.
5937 * @param[in] mc Cursor on the DB to free.
5938 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5939 * @return 0 on success, non-zero on failure.
5942 mdb_drop0(MDB_cursor *mc, int subs)
5946 rc = mdb_page_search(mc, NULL, 0);
5947 if (rc == MDB_SUCCESS) {
5952 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5953 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5956 mdb_cursor_copy(mc, &mx);
5957 while (mc->mc_snum > 0) {
5958 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5959 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5960 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5961 if (ni->mn_flags & F_SUBDATA) {
5962 mdb_xcursor_init1(mc, ni);
5963 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5969 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5971 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5974 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5979 rc = mdb_cursor_sibling(mc, 1);
5981 /* no more siblings, go back to beginning
5982 * of previous level. (stack was already popped
5983 * by mdb_cursor_sibling)
5985 for (i=1; i<mc->mc_top; i++)
5986 mc->mc_pg[i] = mx.mc_pg[i];
5990 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5991 mc->mc_db->md_root);
5996 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6001 if (!txn || !dbi || dbi >= txn->mt_numdbs)
6004 rc = mdb_cursor_open(txn, dbi, &mc);
6008 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6012 /* Can't delete the main DB */
6013 if (del && dbi > MAIN_DBI) {
6014 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6016 mdb_close(txn->mt_env, dbi);
6018 txn->mt_dbflags[dbi] |= DB_DIRTY;
6019 txn->mt_dbs[dbi].md_depth = 0;
6020 txn->mt_dbs[dbi].md_branch_pages = 0;
6021 txn->mt_dbs[dbi].md_leaf_pages = 0;
6022 txn->mt_dbs[dbi].md_overflow_pages = 0;
6023 txn->mt_dbs[dbi].md_entries = 0;
6024 txn->mt_dbs[dbi].md_root = P_INVALID;
6027 mdb_cursor_close(mc);
6031 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6033 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6036 txn->mt_dbxs[dbi].md_cmp = cmp;
6040 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6042 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6045 txn->mt_dbxs[dbi].md_dcmp = cmp;
6049 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6051 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6054 txn->mt_dbxs[dbi].md_rel = rel;
6058 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6060 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6063 txn->mt_dbxs[dbi].md_relctx = ctx;