2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2012 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
60 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
61 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
67 #include <semaphore.h>
72 #include <valgrind/memcheck.h>
73 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
74 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
75 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
76 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
77 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
79 #define VGMEMP_CREATE(h,r,z)
80 #define VGMEMP_ALLOC(h,a,s)
81 #define VGMEMP_FREE(h,a)
82 #define VGMEMP_DESTROY(h)
83 #define VGMEMP_DEFINED(a,s)
87 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
88 /* Solaris just defines one or the other */
89 # define LITTLE_ENDIAN 1234
90 # define BIG_ENDIAN 4321
91 # ifdef _LITTLE_ENDIAN
92 # define BYTE_ORDER LITTLE_ENDIAN
94 # define BYTE_ORDER BIG_ENDIAN
97 # define BYTE_ORDER __BYTE_ORDER
101 #ifndef LITTLE_ENDIAN
102 #define LITTLE_ENDIAN __LITTLE_ENDIAN
105 #define BIG_ENDIAN __BIG_ENDIAN
108 #if defined(__i386) || defined(__x86_64)
109 #define MISALIGNED_OK 1
115 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
116 # error "Unknown or unsupported endianness (BYTE_ORDER)"
117 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
118 # error "Two's complement, reasonably sized integer types, please"
121 /** @defgroup internal MDB Internals
124 /** @defgroup compat Windows Compatibility Macros
125 * A bunch of macros to minimize the amount of platform-specific ifdefs
126 * needed throughout the rest of the code. When the features this library
127 * needs are similar enough to POSIX to be hidden in a one-or-two line
128 * replacement, this macro approach is used.
132 #define pthread_t DWORD
133 #define pthread_mutex_t HANDLE
134 #define pthread_key_t DWORD
135 #define pthread_self() GetCurrentThreadId()
136 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
137 #define pthread_key_delete(x) TlsFree(x)
138 #define pthread_getspecific(x) TlsGetValue(x)
139 #define pthread_setspecific(x,y) TlsSetValue(x,y)
140 #define pthread_mutex_unlock(x) ReleaseMutex(x)
141 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
142 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
143 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
144 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
145 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
146 #define getpid() GetCurrentProcessId()
147 #define fdatasync(fd) (!FlushFileBuffers(fd))
148 #define ErrCode() GetLastError()
149 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
150 #define close(fd) CloseHandle(fd)
151 #define munmap(ptr,len) UnmapViewOfFile(ptr)
154 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
158 #define fdatasync(fd) fsync(fd)
161 #define fdatasync(fd) fsync(fd)
163 /** Lock the reader mutex.
165 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
166 /** Unlock the reader mutex.
168 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
170 /** Lock the writer mutex.
171 * Only a single write transaction is allowed at a time. Other writers
172 * will block waiting for this mutex.
174 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
175 /** Unlock the writer mutex.
177 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
178 #endif /* __APPLE__ */
180 /** Get the error code for the last failed system function.
182 #define ErrCode() errno
184 /** An abstraction for a file handle.
185 * On POSIX systems file handles are small integers. On Windows
186 * they're opaque pointers.
190 /** A value for an invalid file handle.
191 * Mainly used to initialize file variables and signify that they are
194 #define INVALID_HANDLE_VALUE (-1)
196 /** Get the size of a memory page for the system.
197 * This is the basic size that the platform's memory manager uses, and is
198 * fundamental to the use of memory-mapped files.
200 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
203 #if defined(_WIN32) || defined(__APPLE__)
206 #define MNAME_LEN (sizeof(pthread_mutex_t))
212 /** A flag for opening a file and requesting synchronous data writes.
213 * This is only used when writing a meta page. It's not strictly needed;
214 * we could just do a normal write and then immediately perform a flush.
215 * But if this flag is available it saves us an extra system call.
217 * @note If O_DSYNC is undefined but exists in /usr/include,
218 * preferably set some compiler flag to get the definition.
219 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
222 # define MDB_DSYNC O_DSYNC
226 /** Function for flushing the data of a file. Define this to fsync
227 * if fdatasync() is not supported.
229 #ifndef MDB_FDATASYNC
230 # define MDB_FDATASYNC fdatasync
233 /** A page number in the database.
234 * Note that 64 bit page numbers are overkill, since pages themselves
235 * already represent 12-13 bits of addressable memory, and the OS will
236 * always limit applications to a maximum of 63 bits of address space.
238 * @note In the #MDB_node structure, we only store 48 bits of this value,
239 * which thus limits us to only 60 bits of addressable data.
243 /** A transaction ID.
244 * See struct MDB_txn.mt_txnid for details.
248 /** @defgroup debug Debug Macros
252 /** Enable debug output.
253 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
254 * read from and written to the database (used for free space management).
259 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
260 # define DPRINTF (void) /* Vararg macros may be unsupported */
262 /** Print a debug message with printf formatting. */
263 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
264 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
266 # define DPRINTF(fmt, ...) ((void) 0)
268 /** Print a debug string.
269 * The string is printed literally, with no format processing.
271 #define DPUTS(arg) DPRINTF("%s", arg)
274 /** A default memory page size.
275 * The actual size is platform-dependent, but we use this for
276 * boot-strapping. We probably should not be using this any more.
277 * The #GET_PAGESIZE() macro is used to get the actual size.
279 * Note that we don't currently support Huge pages. On Linux,
280 * regular data files cannot use Huge pages, and in general
281 * Huge pages aren't actually pageable. We rely on the OS
282 * demand-pager to read our data and page it out when memory
283 * pressure from other processes is high. So until OSs have
284 * actual paging support for Huge pages, they're not viable.
286 #define MDB_PAGESIZE 4096
288 /** The minimum number of keys required in a database page.
289 * Setting this to a larger value will place a smaller bound on the
290 * maximum size of a data item. Data items larger than this size will
291 * be pushed into overflow pages instead of being stored directly in
292 * the B-tree node. This value used to default to 4. With a page size
293 * of 4096 bytes that meant that any item larger than 1024 bytes would
294 * go into an overflow page. That also meant that on average 2-3KB of
295 * each overflow page was wasted space. The value cannot be lower than
296 * 2 because then there would no longer be a tree structure. With this
297 * value, items larger than 2KB will go into overflow pages, and on
298 * average only 1KB will be wasted.
300 #define MDB_MINKEYS 2
302 /** A stamp that identifies a file as an MDB file.
303 * There's nothing special about this value other than that it is easily
304 * recognizable, and it will reflect any byte order mismatches.
306 #define MDB_MAGIC 0xBEEFC0DE
308 /** The version number for a database's file format. */
309 #define MDB_VERSION 1
311 /** The maximum size of a key in the database.
312 * While data items have essentially unbounded size, we require that
313 * keys all fit onto a regular page. This limit could be raised a bit
314 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
316 #define MAXKEYSIZE 511
321 * This is used for printing a hex dump of a key's contents.
323 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
324 /** Display a key in hex.
326 * Invoke a function to display a key in hex.
328 #define DKEY(x) mdb_dkey(x, kbuf)
330 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
334 /** @defgroup lazylock Lazy Locking
335 * Macros for locks that aren't actually needed.
336 * The DB view is always consistent because all writes are wrapped in
337 * the wmutex. Finer-grained locks aren't necessary.
341 /** Use lazy locking. I.e., don't lock these accesses at all. */
345 /** Grab the reader lock */
346 #define LAZY_MUTEX_LOCK(x)
347 /** Release the reader lock */
348 #define LAZY_MUTEX_UNLOCK(x)
349 /** Release the DB table reader/writer lock */
350 #define LAZY_RWLOCK_UNLOCK(x)
351 /** Grab the DB table write lock */
352 #define LAZY_RWLOCK_WRLOCK(x)
353 /** Grab the DB table read lock */
354 #define LAZY_RWLOCK_RDLOCK(x)
355 /** Declare the DB table rwlock. Should not be followed by ';'. */
356 #define LAZY_RWLOCK_DEF(x)
357 /** Initialize the DB table rwlock */
358 #define LAZY_RWLOCK_INIT(x,y)
359 /** Destroy the DB table rwlock */
360 #define LAZY_RWLOCK_DESTROY(x)
362 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
363 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
364 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
365 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
366 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
367 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
368 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
369 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
373 /** An invalid page number.
374 * Mainly used to denote an empty tree.
376 #define P_INVALID (~0UL)
378 /** Test if a flag \b f is set in a flag word \b w. */
379 #define F_ISSET(w, f) (((w) & (f)) == (f))
381 /** Used for offsets within a single page.
382 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
385 typedef uint16_t indx_t;
387 /** Default size of memory map.
388 * This is certainly too small for any actual applications. Apps should always set
389 * the size explicitly using #mdb_env_set_mapsize().
391 #define DEFAULT_MAPSIZE 1048576
393 /** @defgroup readers Reader Lock Table
394 * Readers don't acquire any locks for their data access. Instead, they
395 * simply record their transaction ID in the reader table. The reader
396 * mutex is needed just to find an empty slot in the reader table. The
397 * slot's address is saved in thread-specific data so that subsequent read
398 * transactions started by the same thread need no further locking to proceed.
400 * Since the database uses multi-version concurrency control, readers don't
401 * actually need any locking. This table is used to keep track of which
402 * readers are using data from which old transactions, so that we'll know
403 * when a particular old transaction is no longer in use. Old transactions
404 * that have discarded any data pages can then have those pages reclaimed
405 * for use by a later write transaction.
407 * The lock table is constructed such that reader slots are aligned with the
408 * processor's cache line size. Any slot is only ever used by one thread.
409 * This alignment guarantees that there will be no contention or cache
410 * thrashing as threads update their own slot info, and also eliminates
411 * any need for locking when accessing a slot.
413 * A writer thread will scan every slot in the table to determine the oldest
414 * outstanding reader transaction. Any freed pages older than this will be
415 * reclaimed by the writer. The writer doesn't use any locks when scanning
416 * this table. This means that there's no guarantee that the writer will
417 * see the most up-to-date reader info, but that's not required for correct
418 * operation - all we need is to know the upper bound on the oldest reader,
419 * we don't care at all about the newest reader. So the only consequence of
420 * reading stale information here is that old pages might hang around a
421 * while longer before being reclaimed. That's actually good anyway, because
422 * the longer we delay reclaiming old pages, the more likely it is that a
423 * string of contiguous pages can be found after coalescing old pages from
424 * many old transactions together.
426 * @todo We don't actually do such coalescing yet, we grab pages from one
427 * old transaction at a time.
430 /** Number of slots in the reader table.
431 * This value was chosen somewhat arbitrarily. 126 readers plus a
432 * couple mutexes fit exactly into 8KB on my development machine.
433 * Applications should set the table size using #mdb_env_set_maxreaders().
435 #define DEFAULT_READERS 126
437 /** The size of a CPU cache line in bytes. We want our lock structures
438 * aligned to this size to avoid false cache line sharing in the
440 * This value works for most CPUs. For Itanium this should be 128.
446 /** The information we store in a single slot of the reader table.
447 * In addition to a transaction ID, we also record the process and
448 * thread ID that owns a slot, so that we can detect stale information,
449 * e.g. threads or processes that went away without cleaning up.
450 * @note We currently don't check for stale records. We simply re-init
451 * the table when we know that we're the only process opening the
454 typedef struct MDB_rxbody {
455 /** The current Transaction ID when this transaction began.
456 * Multiple readers that start at the same time will probably have the
457 * same ID here. Again, it's not important to exclude them from
458 * anything; all we need to know is which version of the DB they
459 * started from so we can avoid overwriting any data used in that
460 * particular version.
463 /** The process ID of the process owning this reader txn. */
465 /** The thread ID of the thread owning this txn. */
469 /** The actual reader record, with cacheline padding. */
470 typedef struct MDB_reader {
473 /** shorthand for mrb_txnid */
474 #define mr_txnid mru.mrx.mrb_txnid
475 #define mr_pid mru.mrx.mrb_pid
476 #define mr_tid mru.mrx.mrb_tid
477 /** cache line alignment */
478 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
482 /** The header for the reader table.
483 * The table resides in a memory-mapped file. (This is a different file
484 * than is used for the main database.)
486 * For POSIX the actual mutexes reside in the shared memory of this
487 * mapped file. On Windows, mutexes are named objects allocated by the
488 * kernel; we store the mutex names in this mapped file so that other
489 * processes can grab them. This same approach is also used on
490 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
491 * process-shared POSIX mutexes. For these cases where a named object
492 * is used, the object name is derived from a 64 bit FNV hash of the
493 * environment pathname. As such, naming collisions are extremely
494 * unlikely. If a collision occurs, the results are unpredictable.
496 typedef struct MDB_txbody {
497 /** Stamp identifying this as an MDB file. It must be set
500 /** Version number of this lock file. Must be set to #MDB_VERSION. */
501 uint32_t mtb_version;
502 #if defined(_WIN32) || defined(__APPLE__)
503 char mtb_rmname[MNAME_LEN];
505 /** Mutex protecting access to this table.
506 * This is the reader lock that #LOCK_MUTEX_R acquires.
508 pthread_mutex_t mtb_mutex;
510 /** The ID of the last transaction committed to the database.
511 * This is recorded here only for convenience; the value can always
512 * be determined by reading the main database meta pages.
515 /** The number of slots that have been used in the reader table.
516 * This always records the maximum count, it is not decremented
517 * when readers release their slots.
519 unsigned mtb_numreaders;
520 /** The ID of the most recent meta page in the database.
521 * This is recorded here only for convenience; the value can always
522 * be determined by reading the main database meta pages.
524 uint32_t mtb_me_toggle;
527 /** The actual reader table definition. */
528 typedef struct MDB_txninfo {
531 #define mti_magic mt1.mtb.mtb_magic
532 #define mti_version mt1.mtb.mtb_version
533 #define mti_mutex mt1.mtb.mtb_mutex
534 #define mti_rmname mt1.mtb.mtb_rmname
535 #define mti_txnid mt1.mtb.mtb_txnid
536 #define mti_numreaders mt1.mtb.mtb_numreaders
537 #define mti_me_toggle mt1.mtb.mtb_me_toggle
538 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
541 #if defined(_WIN32) || defined(__APPLE__)
542 char mt2_wmname[MNAME_LEN];
543 #define mti_wmname mt2.mt2_wmname
545 pthread_mutex_t mt2_wmutex;
546 #define mti_wmutex mt2.mt2_wmutex
548 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
550 MDB_reader mti_readers[1];
554 /** Common header for all page types.
555 * Overflow records occupy a number of contiguous pages with no
556 * headers on any page after the first.
558 typedef struct MDB_page {
559 #define mp_pgno mp_p.p_pgno
560 #define mp_next mp_p.p_next
562 pgno_t p_pgno; /**< page number */
563 void * p_next; /**< for in-memory list of freed structs */
566 /** @defgroup mdb_page Page Flags
568 * Flags for the page headers.
571 #define P_BRANCH 0x01 /**< branch page */
572 #define P_LEAF 0x02 /**< leaf page */
573 #define P_OVERFLOW 0x04 /**< overflow page */
574 #define P_META 0x08 /**< meta page */
575 #define P_DIRTY 0x10 /**< dirty page */
576 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
577 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
579 uint16_t mp_flags; /**< @ref mdb_page */
580 #define mp_lower mp_pb.pb.pb_lower
581 #define mp_upper mp_pb.pb.pb_upper
582 #define mp_pages mp_pb.pb_pages
585 indx_t pb_lower; /**< lower bound of free space */
586 indx_t pb_upper; /**< upper bound of free space */
588 uint32_t pb_pages; /**< number of overflow pages */
590 indx_t mp_ptrs[1]; /**< dynamic size */
593 /** Size of the page header, excluding dynamic data at the end */
594 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
596 /** Address of first usable data byte in a page, after the header */
597 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
599 /** Number of nodes on a page */
600 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
602 /** The amount of space remaining in the page */
603 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
605 /** The percentage of space used in the page, in tenths of a percent. */
606 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
607 ((env)->me_psize - PAGEHDRSZ))
608 /** The minimum page fill factor, in tenths of a percent.
609 * Pages emptier than this are candidates for merging.
611 #define FILL_THRESHOLD 250
613 /** Test if a page is a leaf page */
614 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
615 /** Test if a page is a LEAF2 page */
616 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
617 /** Test if a page is a branch page */
618 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
619 /** Test if a page is an overflow page */
620 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
621 /** Test if a page is a sub page */
622 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
624 /** The number of overflow pages needed to store the given size. */
625 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
627 /** Header for a single key/data pair within a page.
628 * We guarantee 2-byte alignment for nodes.
630 typedef struct MDB_node {
631 /** lo and hi are used for data size on leaf nodes and for
632 * child pgno on branch nodes. On 64 bit platforms, flags
633 * is also used for pgno. (Branch nodes have no flags).
634 * They are in host byte order in case that lets some
635 * accesses be optimized into a 32-bit word access.
637 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
638 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
639 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
640 /** @defgroup mdb_node Node Flags
642 * Flags for node headers.
645 #define F_BIGDATA 0x01 /**< data put on overflow page */
646 #define F_SUBDATA 0x02 /**< data is a sub-database */
647 #define F_DUPDATA 0x04 /**< data has duplicates */
649 /** valid flags for #mdb_node_add() */
650 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
653 unsigned short mn_flags; /**< @ref mdb_node */
654 unsigned short mn_ksize; /**< key size */
655 char mn_data[1]; /**< key and data are appended here */
658 /** Size of the node header, excluding dynamic data at the end */
659 #define NODESIZE offsetof(MDB_node, mn_data)
661 /** Bit position of top word in page number, for shifting mn_flags */
662 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
664 /** Size of a node in a branch page with a given key.
665 * This is just the node header plus the key, there is no data.
667 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
669 /** Size of a node in a leaf page with a given key and data.
670 * This is node header plus key plus data size.
672 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
674 /** Address of node \b i in page \b p */
675 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
677 /** Address of the key for the node */
678 #define NODEKEY(node) (void *)((node)->mn_data)
680 /** Address of the data for a node */
681 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
683 /** Get the page number pointed to by a branch node */
684 #define NODEPGNO(node) \
685 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
686 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
687 /** Set the page number in a branch node */
688 #define SETPGNO(node,pgno) do { \
689 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
690 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
692 /** Get the size of the data in a leaf node */
693 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
694 /** Set the size of the data for a leaf node */
695 #define SETDSZ(node,size) do { \
696 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
697 /** The size of a key in a node */
698 #define NODEKSZ(node) ((node)->mn_ksize)
700 /** Copy a page number from src to dst */
702 #define COPY_PGNO(dst,src) dst = src
704 #if SIZE_MAX > 4294967295UL
705 #define COPY_PGNO(dst,src) do { \
706 unsigned short *s, *d; \
707 s = (unsigned short *)&(src); \
708 d = (unsigned short *)&(dst); \
715 #define COPY_PGNO(dst,src) do { \
716 unsigned short *s, *d; \
717 s = (unsigned short *)&(src); \
718 d = (unsigned short *)&(dst); \
724 /** The address of a key in a LEAF2 page.
725 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
726 * There are no node headers, keys are stored contiguously.
728 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
730 /** Set the \b node's key into \b key, if requested. */
731 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
732 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
734 /** Information about a single database in the environment. */
735 typedef struct MDB_db {
736 uint32_t md_pad; /**< also ksize for LEAF2 pages */
737 uint16_t md_flags; /**< @ref mdb_open */
738 uint16_t md_depth; /**< depth of this tree */
739 pgno_t md_branch_pages; /**< number of internal pages */
740 pgno_t md_leaf_pages; /**< number of leaf pages */
741 pgno_t md_overflow_pages; /**< number of overflow pages */
742 size_t md_entries; /**< number of data items */
743 pgno_t md_root; /**< the root page of this tree */
746 /** Handle for the DB used to track free pages. */
748 /** Handle for the default DB. */
751 /** Meta page content. */
752 typedef struct MDB_meta {
753 /** Stamp identifying this as an MDB file. It must be set
756 /** Version number of this lock file. Must be set to #MDB_VERSION. */
758 void *mm_address; /**< address for fixed mapping */
759 size_t mm_mapsize; /**< size of mmap region */
760 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
761 /** The size of pages used in this DB */
762 #define mm_psize mm_dbs[0].md_pad
763 /** Any persistent environment flags. @ref mdb_env */
764 #define mm_flags mm_dbs[0].md_flags
765 pgno_t mm_last_pg; /**< last used page in file */
766 txnid_t mm_txnid; /**< txnid that committed this page */
769 /** Buffer for a stack-allocated dirty page.
770 * The members define size and alignment, and silence type
771 * aliasing warnings. They are not used directly; that could
772 * mean incorrectly using several union members in parallel.
774 typedef union MDB_pagebuf {
775 char mb_raw[MDB_PAGESIZE];
778 char mm_pad[PAGEHDRSZ];
783 /** Auxiliary DB info.
784 * The information here is mostly static/read-only. There is
785 * only a single copy of this record in the environment.
787 typedef struct MDB_dbx {
788 MDB_val md_name; /**< name of the database */
789 MDB_cmp_func *md_cmp; /**< function for comparing keys */
790 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
791 MDB_rel_func *md_rel; /**< user relocate function */
792 void *md_relctx; /**< user-provided context for md_rel */
795 /** A database transaction.
796 * Every operation requires a transaction handle.
799 MDB_txn *mt_parent; /**< parent of a nested txn */
800 MDB_txn *mt_child; /**< nested txn under this txn */
801 pgno_t mt_next_pgno; /**< next unallocated page */
802 /** The ID of this transaction. IDs are integers incrementing from 1.
803 * Only committed write transactions increment the ID. If a transaction
804 * aborts, the ID may be re-used by the next writer.
807 MDB_env *mt_env; /**< the DB environment */
808 /** The list of pages that became unused during this transaction.
812 ID2L dirty_list; /**< modified pages */
813 MDB_reader *reader; /**< this thread's slot in the reader table */
815 /** Array of records for each DB known in the environment. */
817 /** Array of MDB_db records for each known DB */
819 /** @defgroup mt_dbflag Transaction DB Flags
823 #define DB_DIRTY 0x01 /**< DB was written in this txn */
824 #define DB_STALE 0x02 /**< DB record is older than txnID */
826 /** Array of cursors for each DB */
827 MDB_cursor **mt_cursors;
828 /** Array of flags for each DB */
829 unsigned char *mt_dbflags;
830 /** Number of DB records in use. This number only ever increments;
831 * we don't decrement it when individual DB handles are closed.
835 /** @defgroup mdb_txn Transaction Flags
839 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
840 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
842 unsigned int mt_flags; /**< @ref mdb_txn */
843 /** Tracks which of the two meta pages was used at the start
844 * of this transaction.
846 unsigned int mt_toggle;
849 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
850 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
851 * raise this on a 64 bit machine.
853 #define CURSOR_STACK 32
857 /** Cursors are used for all DB operations */
859 /** Next cursor on this DB in this txn */
861 /** Original cursor if this is a shadow */
863 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
864 struct MDB_xcursor *mc_xcursor;
865 /** The transaction that owns this cursor */
867 /** The database handle this cursor operates on */
869 /** The database record for this cursor */
871 /** The database auxiliary record for this cursor */
873 /** The @ref mt_dbflag for this database */
874 unsigned char *mc_dbflag;
875 unsigned short mc_snum; /**< number of pushed pages */
876 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
877 /** @defgroup mdb_cursor Cursor Flags
879 * Cursor state flags.
882 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
883 #define C_EOF 0x02 /**< No more data */
884 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
885 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
886 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
888 unsigned int mc_flags; /**< @ref mdb_cursor */
889 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
890 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
893 /** Context for sorted-dup records.
894 * We could have gone to a fully recursive design, with arbitrarily
895 * deep nesting of sub-databases. But for now we only handle these
896 * levels - main DB, optional sub-DB, sorted-duplicate DB.
898 typedef struct MDB_xcursor {
899 /** A sub-cursor for traversing the Dup DB */
900 MDB_cursor mx_cursor;
901 /** The database record for this Dup DB */
903 /** The auxiliary DB record for this Dup DB */
905 /** The @ref mt_dbflag for this Dup DB */
906 unsigned char mx_dbflag;
909 /** A set of pages freed by an earlier transaction. */
910 typedef struct MDB_oldpages {
911 /** Usually we only read one record from the FREEDB at a time, but
912 * in case we read more, this will chain them together.
914 struct MDB_oldpages *mo_next;
915 /** The ID of the transaction in which these pages were freed. */
917 /** An #IDL of the pages */
918 pgno_t mo_pages[1]; /* dynamic */
921 /** The database environment. */
923 HANDLE me_fd; /**< The main data file */
924 HANDLE me_lfd; /**< The lock file */
925 HANDLE me_mfd; /**< just for writing the meta pages */
926 /** Failed to update the meta page. Probably an I/O error. */
927 #define MDB_FATAL_ERROR 0x80000000U
928 uint32_t me_flags; /**< @ref mdb_env */
929 uint32_t me_extrapad; /**< unused for now */
930 unsigned int me_maxreaders; /**< size of the reader table */
931 MDB_dbi me_numdbs; /**< number of DBs opened */
932 MDB_dbi me_maxdbs; /**< size of the DB table */
933 char *me_path; /**< path to the DB files */
934 char *me_map; /**< the memory map of the data file */
935 MDB_txninfo *me_txns; /**< the memory map of the lock file */
936 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
937 MDB_txn *me_txn; /**< current write transaction */
938 size_t me_mapsize; /**< size of the data memory map */
939 off_t me_size; /**< current file size */
940 pgno_t me_maxpg; /**< me_mapsize / me_psize */
941 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
942 unsigned int me_db_toggle; /**< which DB table is current */
943 txnid_t me_wtxnid; /**< ID of last txn we committed */
944 txnid_t me_pgfirst; /**< ID of first old page record we used */
945 txnid_t me_pglast; /**< ID of last old page record we used */
946 MDB_dbx *me_dbxs; /**< array of static DB info */
947 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
948 MDB_oldpages *me_pghead; /**< list of old page records */
949 pthread_key_t me_txkey; /**< thread-key for readers */
950 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
951 /** IDL of pages that became unused in a write txn */
953 /** ID2L of pages that were written during a write txn */
954 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
955 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
956 LAZY_RWLOCK_DEF(me_dblock)
958 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
962 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
966 /** max number of pages to commit in one writev() call */
967 #define MDB_COMMIT_PAGES 64
968 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
969 #undef MDB_COMMIT_PAGES
970 #define MDB_COMMIT_PAGES IOV_MAX
973 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
974 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
975 static int mdb_page_touch(MDB_cursor *mc);
977 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
978 static int mdb_page_search_root(MDB_cursor *mc,
979 MDB_val *key, int modify);
980 static int mdb_page_search(MDB_cursor *mc,
981 MDB_val *key, int modify);
982 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
983 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
984 pgno_t newpgno, unsigned int nflags);
986 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
987 static int mdb_env_read_meta(MDB_env *env, int *which);
988 static int mdb_env_write_meta(MDB_txn *txn);
990 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
991 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
992 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
993 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
994 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
995 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
996 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
997 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
998 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1000 static int mdb_rebalance(MDB_cursor *mc);
1001 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
1003 static void mdb_cursor_pop(MDB_cursor *mc);
1004 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1006 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1007 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1008 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1009 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1010 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1012 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1013 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1015 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1016 static void mdb_xcursor_init0(MDB_cursor *mc);
1017 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1019 static int mdb_drop0(MDB_cursor *mc, int subs);
1020 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1023 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1027 static SECURITY_DESCRIPTOR mdb_null_sd;
1028 static SECURITY_ATTRIBUTES mdb_all_sa;
1029 static int mdb_sec_inited;
1032 /** Return the library version info. */
1034 mdb_version(int *major, int *minor, int *patch)
1036 if (major) *major = MDB_VERSION_MAJOR;
1037 if (minor) *minor = MDB_VERSION_MINOR;
1038 if (patch) *patch = MDB_VERSION_PATCH;
1039 return MDB_VERSION_STRING;
1042 /** Table of descriptions for MDB @ref errors */
1043 static char *const mdb_errstr[] = {
1044 "MDB_KEYEXIST: Key/data pair already exists",
1045 "MDB_NOTFOUND: No matching key/data pair found",
1046 "MDB_PAGE_NOTFOUND: Requested page not found",
1047 "MDB_CORRUPTED: Located page was wrong type",
1048 "MDB_PANIC: Update of meta page failed",
1049 "MDB_VERSION_MISMATCH: Database environment version mismatch"
1053 mdb_strerror(int err)
1056 return ("Successful return: 0");
1058 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1059 return mdb_errstr[err - MDB_KEYEXIST];
1061 return strerror(err);
1065 /** Display a key in hexadecimal and return the address of the result.
1066 * @param[in] key the key to display
1067 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1068 * @return The key in hexadecimal form.
1071 mdb_dkey(MDB_val *key, char *buf)
1074 unsigned char *c = key->mv_data;
1076 if (key->mv_size > MAXKEYSIZE)
1077 return "MAXKEYSIZE";
1078 /* may want to make this a dynamic check: if the key is mostly
1079 * printable characters, print it as-is instead of converting to hex.
1083 for (i=0; i<key->mv_size; i++)
1084 ptr += sprintf(ptr, "%02x", *c++);
1086 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1091 /** Display all the keys in the page. */
1093 mdb_page_keys(MDB_page *mp)
1096 unsigned int i, nkeys;
1100 nkeys = NUMKEYS(mp);
1101 DPRINTF("numkeys %d", nkeys);
1102 for (i=0; i<nkeys; i++) {
1103 node = NODEPTR(mp, i);
1104 key.mv_size = node->mn_ksize;
1105 key.mv_data = node->mn_data;
1106 DPRINTF("key %d: %s", i, DKEY(&key));
1112 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1114 return txn->mt_dbxs[dbi].md_cmp(a, b);
1118 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1120 if (txn->mt_dbxs[dbi].md_dcmp)
1121 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1123 return EINVAL; /* too bad you can't distinguish this from a valid result */
1126 /** Allocate a single page.
1127 * Re-use old malloc'd pages first, otherwise just malloc.
1130 mdb_page_malloc(MDB_cursor *mc) {
1132 size_t sz = mc->mc_txn->mt_env->me_psize;
1133 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1134 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1135 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1136 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1137 } else if ((ret = malloc(sz)) != NULL) {
1138 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1143 /** Allocate pages for writing.
1144 * If there are free pages available from older transactions, they
1145 * will be re-used first. Otherwise a new page will be allocated.
1146 * @param[in] mc cursor A cursor handle identifying the transaction and
1147 * database for which we are allocating.
1148 * @param[in] num the number of pages to allocate.
1149 * @return Address of the allocated page(s). Requests for multiple pages
1150 * will always be satisfied by a single contiguous chunk of memory.
1153 mdb_page_alloc(MDB_cursor *mc, int num)
1155 MDB_txn *txn = mc->mc_txn;
1157 pgno_t pgno = P_INVALID;
1160 if (txn->mt_txnid > 2) {
1162 if (!txn->mt_env->me_pghead &&
1163 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1164 /* See if there's anything in the free DB */
1168 txnid_t *kptr, oldest, last;
1170 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1171 if (!txn->mt_env->me_pgfirst) {
1172 mdb_page_search(&m2, NULL, 0);
1173 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1174 kptr = (txnid_t *)NODEKEY(leaf);
1179 last = txn->mt_env->me_pglast + 1;
1181 key.mv_data = &last;
1182 key.mv_size = sizeof(last);
1183 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1186 last = *(txnid_t *)key.mv_data;
1191 oldest = txn->mt_txnid - 1;
1192 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1193 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1194 if (mr && mr < oldest)
1199 if (oldest > last) {
1200 /* It's usable, grab it.
1205 if (!txn->mt_env->me_pgfirst) {
1206 mdb_node_read(txn, leaf, &data);
1208 idl = (ID *) data.mv_data;
1209 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1210 mop->mo_next = txn->mt_env->me_pghead;
1211 mop->mo_txnid = last;
1212 txn->mt_env->me_pglast = last;
1213 if (!txn->mt_env->me_pgfirst)
1214 txn->mt_env->me_pgfirst = last;
1215 txn->mt_env->me_pghead = mop;
1216 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1221 DPRINTF("IDL read txn %zu root %zu num %zu",
1222 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1223 for (i=0; i<idl[0]; i++) {
1224 DPRINTF("IDL %zu", idl[i+1]);
1228 if (mop->mo_txnid == 87869 && txn->mt_txnid == 87879) {
1234 if (txn->mt_env->me_pghead) {
1235 MDB_oldpages *mop = txn->mt_env->me_pghead;
1237 /* FIXME: For now, always use fresh pages. We
1238 * really ought to search the free list for a
1243 /* peel pages off tail, so we only have to truncate the list */
1244 pgno = MDB_IDL_LAST(mop->mo_pages);
1245 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1247 if (mop->mo_pages[2] > mop->mo_pages[1])
1248 mop->mo_pages[0] = 0;
1252 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1253 txn->mt_env->me_pghead = mop->mo_next;
1260 if (pgno == P_INVALID) {
1261 /* DB size is maxed out */
1262 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1263 DPUTS("DB size maxed out");
1267 if (txn->mt_env->me_dpages && num == 1) {
1268 np = txn->mt_env->me_dpages;
1269 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1270 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1271 txn->mt_env->me_dpages = np->mp_next;
1273 size_t sz = txn->mt_env->me_psize * num;
1274 if ((np = malloc(sz)) == NULL)
1276 VGMEMP_ALLOC(txn->mt_env, np, sz);
1278 if (pgno == P_INVALID) {
1279 np->mp_pgno = txn->mt_next_pgno;
1280 txn->mt_next_pgno += num;
1284 mid.mid = np->mp_pgno;
1286 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1291 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1292 * @param[in] mc cursor pointing to the page to be touched
1293 * @return 0 on success, non-zero on failure.
1296 mdb_page_touch(MDB_cursor *mc)
1298 MDB_page *mp = mc->mc_pg[mc->mc_top];
1301 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1303 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1305 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1306 assert(mp->mp_pgno != np->mp_pgno);
1307 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1309 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1312 mp->mp_flags |= P_DIRTY;
1315 /* Adjust other cursors pointing to mp */
1316 if (mc->mc_flags & C_SUB) {
1317 MDB_cursor *m2, *m3;
1318 MDB_dbi dbi = mc->mc_dbi-1;
1320 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1321 if (m2 == mc) continue;
1322 m3 = &m2->mc_xcursor->mx_cursor;
1323 if (m3->mc_snum < mc->mc_snum) continue;
1324 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1325 m3->mc_pg[mc->mc_top] = mp;
1331 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1332 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1333 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1334 m2->mc_pg[mc->mc_top] = mp;
1338 mc->mc_pg[mc->mc_top] = mp;
1339 /** If this page has a parent, update the parent to point to
1343 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1345 mc->mc_db->md_root = mp->mp_pgno;
1346 } else if (mc->mc_txn->mt_parent) {
1349 /* If txn has a parent, make sure the page is in our
1352 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1353 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1354 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1355 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1356 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1357 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1358 mc->mc_pg[mc->mc_top] = mp;
1364 np = mdb_page_malloc(mc);
1365 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1366 mid.mid = np->mp_pgno;
1368 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1376 mdb_env_sync(MDB_env *env, int force)
1379 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1380 if (MDB_FDATASYNC(env->me_fd))
1386 /** Make shadow copies of all of parent txn's cursors */
1388 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1390 MDB_cursor *mc, *m2;
1391 unsigned int i, j, size;
1393 for (i=0;i<src->mt_numdbs; i++) {
1394 if (src->mt_cursors[i]) {
1395 size = sizeof(MDB_cursor);
1396 if (src->mt_cursors[i]->mc_xcursor)
1397 size += sizeof(MDB_xcursor);
1398 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1405 mc->mc_db = &dst->mt_dbs[i];
1406 mc->mc_dbx = m2->mc_dbx;
1407 mc->mc_dbflag = &dst->mt_dbflags[i];
1408 mc->mc_snum = m2->mc_snum;
1409 mc->mc_top = m2->mc_top;
1410 mc->mc_flags = m2->mc_flags | C_SHADOW;
1411 for (j=0; j<mc->mc_snum; j++) {
1412 mc->mc_pg[j] = m2->mc_pg[j];
1413 mc->mc_ki[j] = m2->mc_ki[j];
1415 if (m2->mc_xcursor) {
1416 MDB_xcursor *mx, *mx2;
1417 mx = (MDB_xcursor *)(mc+1);
1418 mc->mc_xcursor = mx;
1419 mx2 = m2->mc_xcursor;
1420 mx->mx_db = mx2->mx_db;
1421 mx->mx_dbx = mx2->mx_dbx;
1422 mx->mx_dbflag = mx2->mx_dbflag;
1423 mx->mx_cursor.mc_txn = dst;
1424 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1425 mx->mx_cursor.mc_db = &mx->mx_db;
1426 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1427 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1428 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1429 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1430 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1431 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1432 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1433 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1436 mc->mc_xcursor = NULL;
1438 mc->mc_next = dst->mt_cursors[i];
1439 dst->mt_cursors[i] = mc;
1446 /** Merge shadow cursors back into parent's */
1448 mdb_cursor_merge(MDB_txn *txn)
1451 for (i=0; i<txn->mt_numdbs; i++) {
1452 if (txn->mt_cursors[i]) {
1454 while ((mc = txn->mt_cursors[i])) {
1455 txn->mt_cursors[i] = mc->mc_next;
1456 if (mc->mc_flags & C_SHADOW) {
1457 MDB_cursor *m2 = mc->mc_orig;
1459 m2->mc_snum = mc->mc_snum;
1460 m2->mc_top = mc->mc_top;
1461 for (j=0; j<mc->mc_snum; j++) {
1462 m2->mc_pg[j] = mc->mc_pg[j];
1463 m2->mc_ki[j] = mc->mc_ki[j];
1466 if (mc->mc_flags & C_ALLOCD)
1474 mdb_txn_reset0(MDB_txn *txn);
1476 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1477 * @param[in] txn the transaction handle to initialize
1478 * @return 0 on success, non-zero on failure. This can only
1479 * fail for read-only transactions, and then only if the
1480 * reader table is full.
1483 mdb_txn_renew0(MDB_txn *txn)
1485 MDB_env *env = txn->mt_env;
1488 if (txn->mt_flags & MDB_TXN_RDONLY) {
1489 MDB_reader *r = pthread_getspecific(env->me_txkey);
1492 pid_t pid = getpid();
1493 pthread_t tid = pthread_self();
1496 for (i=0; i<env->me_txns->mti_numreaders; i++)
1497 if (env->me_txns->mti_readers[i].mr_pid == 0)
1499 if (i == env->me_maxreaders) {
1500 UNLOCK_MUTEX_R(env);
1503 env->me_txns->mti_readers[i].mr_pid = pid;
1504 env->me_txns->mti_readers[i].mr_tid = tid;
1505 if (i >= env->me_txns->mti_numreaders)
1506 env->me_txns->mti_numreaders = i+1;
1507 UNLOCK_MUTEX_R(env);
1508 r = &env->me_txns->mti_readers[i];
1509 pthread_setspecific(env->me_txkey, r);
1511 txn->mt_toggle = env->me_txns->mti_me_toggle;
1512 txn->mt_txnid = env->me_txns->mti_txnid;
1513 /* This happens if a different process was the
1514 * last writer to the DB.
1516 if (env->me_wtxnid < txn->mt_txnid)
1517 mt_dbflag = DB_STALE;
1518 r->mr_txnid = txn->mt_txnid;
1519 txn->mt_u.reader = r;
1523 txn->mt_txnid = env->me_txns->mti_txnid;
1524 if (env->me_wtxnid < txn->mt_txnid)
1525 mt_dbflag = DB_STALE;
1527 txn->mt_toggle = env->me_txns->mti_me_toggle;
1528 txn->mt_u.dirty_list = env->me_dirty_list;
1529 txn->mt_u.dirty_list[0].mid = 0;
1530 txn->mt_free_pgs = env->me_free_pgs;
1531 txn->mt_free_pgs[0] = 0;
1532 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1536 /* Copy the DB arrays */
1537 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1538 txn->mt_numdbs = env->me_numdbs;
1539 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1540 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1541 if (txn->mt_numdbs > 2)
1542 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1543 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1544 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1546 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1552 mdb_txn_renew(MDB_txn *txn)
1559 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1560 DPUTS("environment had fatal error, must shutdown!");
1564 rc = mdb_txn_renew0(txn);
1565 if (rc == MDB_SUCCESS) {
1566 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1567 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1568 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1574 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1579 if (env->me_flags & MDB_FATAL_ERROR) {
1580 DPUTS("environment had fatal error, must shutdown!");
1584 /* parent already has an active child txn */
1585 if (parent->mt_child) {
1589 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1590 if (!(flags & MDB_RDONLY))
1591 size += env->me_maxdbs * sizeof(MDB_cursor *);
1593 if ((txn = calloc(1, size)) == NULL) {
1594 DPRINTF("calloc: %s", strerror(ErrCode()));
1597 txn->mt_dbs = (MDB_db *)(txn+1);
1598 if (flags & MDB_RDONLY) {
1599 txn->mt_flags |= MDB_TXN_RDONLY;
1600 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1602 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1603 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1608 txn->mt_free_pgs = mdb_midl_alloc();
1609 if (!txn->mt_free_pgs) {
1613 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1614 if (!txn->mt_u.dirty_list) {
1615 free(txn->mt_free_pgs);
1619 txn->mt_txnid = parent->mt_txnid;
1620 txn->mt_toggle = parent->mt_toggle;
1621 txn->mt_u.dirty_list[0].mid = 0;
1622 txn->mt_free_pgs[0] = 0;
1623 txn->mt_next_pgno = parent->mt_next_pgno;
1624 parent->mt_child = txn;
1625 txn->mt_parent = parent;
1626 txn->mt_numdbs = parent->mt_numdbs;
1627 txn->mt_dbxs = parent->mt_dbxs;
1628 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1629 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1630 mdb_cursor_shadow(parent, txn);
1633 rc = mdb_txn_renew0(txn);
1639 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1640 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1641 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1647 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1648 * @param[in] txn the transaction handle to reset
1651 mdb_txn_reset0(MDB_txn *txn)
1653 MDB_env *env = txn->mt_env;
1655 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1656 txn->mt_u.reader->mr_txnid = 0;
1662 /* close(free) all cursors */
1663 for (i=0; i<txn->mt_numdbs; i++) {
1664 if (txn->mt_cursors[i]) {
1666 while ((mc = txn->mt_cursors[i])) {
1667 txn->mt_cursors[i] = mc->mc_next;
1668 if (mc->mc_flags & C_ALLOCD)
1674 /* return all dirty pages to dpage list */
1675 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1676 dp = txn->mt_u.dirty_list[i].mptr;
1677 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1678 dp->mp_next = txn->mt_env->me_dpages;
1679 VGMEMP_FREE(txn->mt_env, dp);
1680 txn->mt_env->me_dpages = dp;
1682 /* large pages just get freed directly */
1683 VGMEMP_FREE(txn->mt_env, dp);
1688 if (txn->mt_parent) {
1689 txn->mt_parent->mt_child = NULL;
1690 free(txn->mt_free_pgs);
1691 free(txn->mt_u.dirty_list);
1694 if (mdb_midl_shrink(&txn->mt_free_pgs))
1695 env->me_free_pgs = txn->mt_free_pgs;
1698 while ((mop = txn->mt_env->me_pghead)) {
1699 txn->mt_env->me_pghead = mop->mo_next;
1702 txn->mt_env->me_pgfirst = 0;
1703 txn->mt_env->me_pglast = 0;
1706 /* The writer mutex was locked in mdb_txn_begin. */
1707 UNLOCK_MUTEX_W(env);
1712 mdb_txn_reset(MDB_txn *txn)
1717 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1718 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1719 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1721 mdb_txn_reset0(txn);
1725 mdb_txn_abort(MDB_txn *txn)
1730 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1731 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1732 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1735 mdb_txn_abort(txn->mt_child);
1737 mdb_txn_reset0(txn);
1742 mdb_txn_commit(MDB_txn *txn)
1753 assert(txn != NULL);
1754 assert(txn->mt_env != NULL);
1756 if (txn->mt_child) {
1757 mdb_txn_commit(txn->mt_child);
1758 txn->mt_child = NULL;
1763 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1764 if (txn->mt_numdbs > env->me_numdbs) {
1765 /* update the DB tables */
1766 int toggle = !env->me_db_toggle;
1770 ip = &env->me_dbs[toggle][env->me_numdbs];
1771 jp = &txn->mt_dbs[env->me_numdbs];
1772 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1773 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1777 env->me_db_toggle = toggle;
1778 env->me_numdbs = txn->mt_numdbs;
1779 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1785 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1786 DPUTS("error flag is set, can't commit");
1788 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1793 /* Merge (and close) our cursors with parent's */
1794 mdb_cursor_merge(txn);
1796 if (txn->mt_parent) {
1802 /* Update parent's DB table */
1803 ip = &txn->mt_parent->mt_dbs[2];
1804 jp = &txn->mt_dbs[2];
1805 for (i = 2; i < txn->mt_numdbs; i++) {
1806 if (ip->md_root != jp->md_root)
1810 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1812 /* Append our free list to parent's */
1813 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1815 mdb_midl_free(txn->mt_free_pgs);
1817 /* Merge our dirty list with parent's */
1818 dst = txn->mt_parent->mt_u.dirty_list;
1819 src = txn->mt_u.dirty_list;
1820 x = mdb_mid2l_search(dst, src[1].mid);
1821 for (y=1; y<=src[0].mid; y++) {
1822 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1826 dst[x].mptr = src[y].mptr;
1829 for (; y<=src[0].mid; y++) {
1830 if (++x >= MDB_IDL_UM_MAX) {
1837 free(txn->mt_u.dirty_list);
1838 txn->mt_parent->mt_child = NULL;
1843 if (txn != env->me_txn) {
1844 DPUTS("attempt to commit unknown transaction");
1849 if (!txn->mt_u.dirty_list[0].mid)
1852 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1853 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1855 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1857 /* should only be one record now */
1858 if (env->me_pghead) {
1859 /* make sure first page of freeDB is touched and on freelist */
1860 mdb_page_search(&mc, NULL, 1);
1863 /* Delete IDLs we used from the free list */
1864 if (env->me_pgfirst) {
1869 key.mv_size = sizeof(cur);
1870 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1873 mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1874 mdb_cursor_del(&mc, 0);
1876 env->me_pgfirst = 0;
1880 /* save to free list */
1881 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1885 /* make sure last page of freeDB is touched and on freelist */
1886 key.mv_size = MAXKEYSIZE+1;
1888 mdb_page_search(&mc, &key, 1);
1890 mdb_midl_sort(txn->mt_free_pgs);
1894 ID *idl = txn->mt_free_pgs;
1895 DPRINTF("IDL write txn %zu root %zu num %zu",
1896 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1897 for (i=0; i<idl[0]; i++) {
1898 DPRINTF("IDL %zu", idl[i+1]);
1902 /* write to last page of freeDB */
1903 key.mv_size = sizeof(pgno_t);
1904 key.mv_data = &txn->mt_txnid;
1905 data.mv_data = txn->mt_free_pgs;
1906 /* The free list can still grow during this call,
1907 * despite the pre-emptive touches above. So check
1908 * and make sure the entire thing got written.
1911 i = txn->mt_free_pgs[0];
1912 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1913 rc = mdb_cursor_put(&mc, &key, &data, 0);
1918 } while (i != txn->mt_free_pgs[0]);
1919 if (mdb_midl_shrink(&txn->mt_free_pgs))
1920 env->me_free_pgs = txn->mt_free_pgs;
1922 /* should only be one record now */
1923 if (env->me_pghead) {
1928 mop = env->me_pghead;
1929 key.mv_size = sizeof(pgno_t);
1930 key.mv_data = &mop->mo_txnid;
1931 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1932 data.mv_data = mop->mo_pages;
1933 orig = mop->mo_pages[0];
1934 mdb_cursor_put(&mc, &key, &data, 0);
1935 /* could have been used again here */
1936 if (mop->mo_pages[0] != orig) {
1937 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1938 data.mv_data = mop->mo_pages;
1939 mdb_cursor_put(&mc, &key, &data, 0);
1940 env->me_pgfirst = 0;
1943 env->me_pghead = NULL;
1947 /* Update DB root pointers. Their pages have already been
1948 * touched so this is all in-place and cannot fail.
1953 data.mv_size = sizeof(MDB_db);
1955 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1956 for (i = 2; i < txn->mt_numdbs; i++) {
1957 if (txn->mt_dbflags[i] & DB_DIRTY) {
1958 data.mv_data = &txn->mt_dbs[i];
1959 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1964 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1970 /* Windows actually supports scatter/gather I/O, but only on
1971 * unbuffered file handles. Since we're relying on the OS page
1972 * cache for all our data, that's self-defeating. So we just
1973 * write pages one at a time. We use the ov structure to set
1974 * the write offset, to at least save the overhead of a Seek
1978 memset(&ov, 0, sizeof(ov));
1979 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1981 dp = txn->mt_u.dirty_list[i].mptr;
1982 DPRINTF("committing page %zu", dp->mp_pgno);
1983 size = dp->mp_pgno * env->me_psize;
1984 ov.Offset = size & 0xffffffff;
1985 ov.OffsetHigh = size >> 16;
1986 ov.OffsetHigh >>= 16;
1987 /* clear dirty flag */
1988 dp->mp_flags &= ~P_DIRTY;
1989 wsize = env->me_psize;
1990 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1991 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1994 DPRINTF("WriteFile: %d", n);
2001 struct iovec iov[MDB_COMMIT_PAGES];
2005 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2006 dp = txn->mt_u.dirty_list[i].mptr;
2007 if (dp->mp_pgno != next) {
2009 DPRINTF("committing %u dirty pages", n);
2010 rc = writev(env->me_fd, iov, n);
2014 DPUTS("short write, filesystem full?");
2016 DPRINTF("writev: %s", strerror(n));
2023 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2026 DPRINTF("committing page %zu", dp->mp_pgno);
2027 iov[n].iov_len = env->me_psize;
2028 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2029 iov[n].iov_base = (char *)dp;
2030 size += iov[n].iov_len;
2031 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2032 /* clear dirty flag */
2033 dp->mp_flags &= ~P_DIRTY;
2034 if (++n >= MDB_COMMIT_PAGES) {
2044 DPRINTF("committing %u dirty pages", n);
2045 rc = writev(env->me_fd, iov, n);
2049 DPUTS("short write, filesystem full?");
2051 DPRINTF("writev: %s", strerror(n));
2058 /* Drop the dirty pages.
2060 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2061 dp = txn->mt_u.dirty_list[i].mptr;
2062 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2063 dp->mp_next = txn->mt_env->me_dpages;
2064 VGMEMP_FREE(txn->mt_env, dp);
2065 txn->mt_env->me_dpages = dp;
2067 VGMEMP_FREE(txn->mt_env, dp);
2070 txn->mt_u.dirty_list[i].mid = 0;
2072 txn->mt_u.dirty_list[0].mid = 0;
2074 if ((n = mdb_env_sync(env, 0)) != 0 ||
2075 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2079 env->me_wtxnid = txn->mt_txnid;
2083 /* update the DB tables */
2085 int toggle = !env->me_db_toggle;
2089 ip = &env->me_dbs[toggle][2];
2090 jp = &txn->mt_dbs[2];
2091 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
2092 for (i = 2; i < txn->mt_numdbs; i++) {
2093 if (ip->md_root != jp->md_root)
2098 env->me_db_toggle = toggle;
2099 env->me_numdbs = txn->mt_numdbs;
2100 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
2103 UNLOCK_MUTEX_W(env);
2109 /** Read the environment parameters of a DB environment before
2110 * mapping it into memory.
2111 * @param[in] env the environment handle
2112 * @param[out] meta address of where to store the meta information
2113 * @return 0 on success, non-zero on failure.
2116 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2123 /* We don't know the page size yet, so use a minimum value.
2127 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2129 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2134 else if (rc != MDB_PAGESIZE) {
2138 DPRINTF("read: %s", strerror(err));
2142 p = (MDB_page *)&pbuf;
2144 if (!F_ISSET(p->mp_flags, P_META)) {
2145 DPRINTF("page %zu not a meta page", p->mp_pgno);
2150 if (m->mm_magic != MDB_MAGIC) {
2151 DPUTS("meta has invalid magic");
2155 if (m->mm_version != MDB_VERSION) {
2156 DPRINTF("database is version %u, expected version %u",
2157 m->mm_version, MDB_VERSION);
2158 return MDB_VERSION_MISMATCH;
2161 memcpy(meta, m, sizeof(*m));
2165 /** Write the environment parameters of a freshly created DB environment.
2166 * @param[in] env the environment handle
2167 * @param[out] meta address of where to store the meta information
2168 * @return 0 on success, non-zero on failure.
2171 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2178 DPUTS("writing new meta page");
2180 GET_PAGESIZE(psize);
2182 meta->mm_magic = MDB_MAGIC;
2183 meta->mm_version = MDB_VERSION;
2184 meta->mm_psize = psize;
2185 meta->mm_last_pg = 1;
2186 meta->mm_flags = env->me_flags & 0xffff;
2187 meta->mm_flags |= MDB_INTEGERKEY;
2188 meta->mm_dbs[0].md_root = P_INVALID;
2189 meta->mm_dbs[1].md_root = P_INVALID;
2191 p = calloc(2, psize);
2193 p->mp_flags = P_META;
2196 memcpy(m, meta, sizeof(*meta));
2198 q = (MDB_page *)((char *)p + psize);
2201 q->mp_flags = P_META;
2204 memcpy(m, meta, sizeof(*meta));
2209 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2210 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2213 rc = write(env->me_fd, p, psize * 2);
2214 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2220 /** Update the environment info to commit a transaction.
2221 * @param[in] txn the transaction that's being committed
2222 * @return 0 on success, non-zero on failure.
2225 mdb_env_write_meta(MDB_txn *txn)
2228 MDB_meta meta, metab;
2230 int rc, len, toggle;
2236 assert(txn != NULL);
2237 assert(txn->mt_env != NULL);
2239 toggle = !txn->mt_toggle;
2240 DPRINTF("writing meta page %d for root page %zu",
2241 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2245 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2246 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2248 ptr = (char *)&meta;
2249 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2250 len = sizeof(MDB_meta) - off;
2253 meta.mm_dbs[0] = txn->mt_dbs[0];
2254 meta.mm_dbs[1] = txn->mt_dbs[1];
2255 meta.mm_last_pg = txn->mt_next_pgno - 1;
2256 meta.mm_txnid = txn->mt_txnid;
2259 off += env->me_psize;
2262 /* Write to the SYNC fd */
2265 memset(&ov, 0, sizeof(ov));
2267 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2270 rc = pwrite(env->me_mfd, ptr, len, off);
2275 DPUTS("write failed, disk error?");
2276 /* On a failure, the pagecache still contains the new data.
2277 * Write some old data back, to prevent it from being used.
2278 * Use the non-SYNC fd; we know it will fail anyway.
2280 meta.mm_last_pg = metab.mm_last_pg;
2281 meta.mm_txnid = metab.mm_txnid;
2283 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2285 r2 = pwrite(env->me_fd, ptr, len, off);
2287 env->me_flags |= MDB_FATAL_ERROR;
2290 /* Memory ordering issues are irrelevant; since the entire writer
2291 * is wrapped by wmutex, all of these changes will become visible
2292 * after the wmutex is unlocked. Since the DB is multi-version,
2293 * readers will get consistent data regardless of how fresh or
2294 * how stale their view of these values is.
2296 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2297 txn->mt_env->me_txns->mti_me_toggle = toggle;
2298 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2299 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2304 /** Check both meta pages to see which one is newer.
2305 * @param[in] env the environment handle
2306 * @param[out] which address of where to store the meta toggle ID
2307 * @return 0 on success, non-zero on failure.
2310 mdb_env_read_meta(MDB_env *env, int *which)
2314 assert(env != NULL);
2316 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2319 DPRINTF("Using meta page %d", toggle);
2326 mdb_env_create(MDB_env **env)
2330 e = calloc(1, sizeof(MDB_env));
2334 e->me_free_pgs = mdb_midl_alloc();
2335 if (!e->me_free_pgs) {
2339 e->me_maxreaders = DEFAULT_READERS;
2341 e->me_fd = INVALID_HANDLE_VALUE;
2342 e->me_lfd = INVALID_HANDLE_VALUE;
2343 e->me_mfd = INVALID_HANDLE_VALUE;
2344 VGMEMP_CREATE(e,0,0);
2350 mdb_env_set_mapsize(MDB_env *env, size_t size)
2354 env->me_mapsize = size;
2356 env->me_maxpg = env->me_mapsize / env->me_psize;
2361 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2365 env->me_maxdbs = dbs;
2370 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2372 if (env->me_map || readers < 1)
2374 env->me_maxreaders = readers;
2379 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2381 if (!env || !readers)
2383 *readers = env->me_maxreaders;
2387 /** Further setup required for opening an MDB environment
2390 mdb_env_open2(MDB_env *env, unsigned int flags)
2392 int i, newenv = 0, toggle;
2396 env->me_flags = flags;
2398 memset(&meta, 0, sizeof(meta));
2400 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2403 DPUTS("new mdbenv");
2407 if (!env->me_mapsize) {
2408 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2414 LONG sizelo, sizehi;
2415 sizelo = env->me_mapsize & 0xffffffff;
2416 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2418 /* Windows won't create mappings for zero length files.
2419 * Just allocate the maxsize right now.
2422 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2423 if (!SetEndOfFile(env->me_fd))
2425 SetFilePointer(env->me_fd, 0, NULL, 0);
2427 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2428 sizehi, sizelo, NULL);
2431 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2439 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2441 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2443 if (env->me_map == MAP_FAILED) {
2450 meta.mm_mapsize = env->me_mapsize;
2451 if (flags & MDB_FIXEDMAP)
2452 meta.mm_address = env->me_map;
2453 i = mdb_env_init_meta(env, &meta);
2454 if (i != MDB_SUCCESS) {
2455 munmap(env->me_map, env->me_mapsize);
2459 env->me_psize = meta.mm_psize;
2461 env->me_maxpg = env->me_mapsize / env->me_psize;
2463 p = (MDB_page *)env->me_map;
2464 env->me_metas[0] = METADATA(p);
2465 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2467 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2470 DPRINTF("opened database version %u, pagesize %u",
2471 env->me_metas[toggle]->mm_version, env->me_psize);
2472 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2473 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2474 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2475 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2476 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2477 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2483 /** Release a reader thread's slot in the reader lock table.
2484 * This function is called automatically when a thread exits.
2485 * Windows doesn't support destructor callbacks for thread-specific storage,
2486 * so this function is not compiled there.
2487 * @param[in] ptr This points to the slot in the reader lock table.
2490 mdb_env_reader_dest(void *ptr)
2492 MDB_reader *reader = ptr;
2494 reader->mr_txnid = 0;
2500 /** Downgrade the exclusive lock on the region back to shared */
2502 mdb_env_share_locks(MDB_env *env)
2506 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2508 env->me_txns->mti_me_toggle = toggle;
2509 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2514 /* First acquire a shared lock. The Unlock will
2515 * then release the existing exclusive lock.
2517 memset(&ov, 0, sizeof(ov));
2518 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2519 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2523 struct flock lock_info;
2524 /* The shared lock replaces the existing lock */
2525 memset((void *)&lock_info, 0, sizeof(lock_info));
2526 lock_info.l_type = F_RDLCK;
2527 lock_info.l_whence = SEEK_SET;
2528 lock_info.l_start = 0;
2529 lock_info.l_len = 1;
2530 fcntl(env->me_lfd, F_SETLK, &lock_info);
2534 #if defined(_WIN32) || defined(__APPLE__)
2536 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2538 * @(#) $Revision: 5.1 $
2539 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2540 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2542 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2546 * Please do not copyright this code. This code is in the public domain.
2548 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2549 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2550 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2551 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2552 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2553 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2554 * PERFORMANCE OF THIS SOFTWARE.
2557 * chongo <Landon Curt Noll> /\oo/\
2558 * http://www.isthe.com/chongo/
2560 * Share and Enjoy! :-)
2563 typedef unsigned long long mdb_hash_t;
2564 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2566 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2567 * @param[in] str string to hash
2568 * @param[in] hval initial value for hash
2569 * @return 64 bit hash
2571 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2572 * hval arg on the first call.
2575 mdb_hash_str(char *str, mdb_hash_t hval)
2577 unsigned char *s = (unsigned char *)str; /* unsigned string */
2579 * FNV-1a hash each octet of the string
2582 /* xor the bottom with the current octet */
2583 hval ^= (mdb_hash_t)*s++;
2585 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2586 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2587 (hval << 7) + (hval << 8) + (hval << 40);
2589 /* return our new hash value */
2593 /** Hash the string and output the hash in hex.
2594 * @param[in] str string to hash
2595 * @param[out] hexbuf an array of 17 chars to hold the hash
2598 mdb_hash_hex(char *str, char *hexbuf)
2601 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2602 for (i=0; i<8; i++) {
2603 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2609 /** Open and/or initialize the lock region for the environment.
2610 * @param[in] env The MDB environment.
2611 * @param[in] lpath The pathname of the file used for the lock region.
2612 * @param[in] mode The Unix permissions for the file, if we create it.
2613 * @param[out] excl Set to true if we got an exclusive lock on the region.
2614 * @return 0 on success, non-zero on failure.
2617 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2625 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2626 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2627 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2631 /* Try to get exclusive lock. If we succeed, then
2632 * nobody is using the lock region and we should initialize it.
2635 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2639 memset(&ov, 0, sizeof(ov));
2640 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2646 size = GetFileSize(env->me_lfd, NULL);
2648 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2652 /* Try to get exclusive lock. If we succeed, then
2653 * nobody is using the lock region and we should initialize it.
2656 struct flock lock_info;
2657 memset((void *)&lock_info, 0, sizeof(lock_info));
2658 lock_info.l_type = F_WRLCK;
2659 lock_info.l_whence = SEEK_SET;
2660 lock_info.l_start = 0;
2661 lock_info.l_len = 1;
2662 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2666 lock_info.l_type = F_RDLCK;
2667 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2674 size = lseek(env->me_lfd, 0, SEEK_END);
2676 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2677 if (size < rsize && *excl) {
2679 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2680 if (!SetEndOfFile(env->me_lfd)) {
2685 if (ftruncate(env->me_lfd, rsize) != 0) {
2692 size = rsize - sizeof(MDB_txninfo);
2693 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2698 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2704 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2706 if (!env->me_txns) {
2711 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2713 if (m == MAP_FAILED) {
2714 env->me_txns = NULL;
2724 if (!mdb_sec_inited) {
2725 InitializeSecurityDescriptor(&mdb_null_sd,
2726 SECURITY_DESCRIPTOR_REVISION);
2727 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2728 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2729 mdb_all_sa.bInheritHandle = FALSE;
2730 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2733 mdb_hash_hex(lpath, hexbuf);
2734 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2735 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2736 if (!env->me_rmutex) {
2740 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2741 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2742 if (!env->me_wmutex) {
2749 mdb_hash_hex(lpath, hexbuf);
2750 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2751 if (sem_unlink(env->me_txns->mti_rmname)) {
2753 if (rc != ENOENT && rc != EINVAL)
2756 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2757 if (!env->me_rmutex) {
2761 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2762 if (sem_unlink(env->me_txns->mti_wmname)) {
2764 if (rc != ENOENT && rc != EINVAL)
2767 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2768 if (!env->me_wmutex) {
2772 #else /* __APPLE__ */
2773 pthread_mutexattr_t mattr;
2775 pthread_mutexattr_init(&mattr);
2776 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2780 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2781 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2782 #endif /* __APPLE__ */
2784 env->me_txns->mti_version = MDB_VERSION;
2785 env->me_txns->mti_magic = MDB_MAGIC;
2786 env->me_txns->mti_txnid = 0;
2787 env->me_txns->mti_numreaders = 0;
2788 env->me_txns->mti_me_toggle = 0;
2791 if (env->me_txns->mti_magic != MDB_MAGIC) {
2792 DPUTS("lock region has invalid magic");
2796 if (env->me_txns->mti_version != MDB_VERSION) {
2797 DPRINTF("lock region is version %u, expected version %u",
2798 env->me_txns->mti_version, MDB_VERSION);
2799 rc = MDB_VERSION_MISMATCH;
2803 if (rc != EACCES && rc != EAGAIN) {
2807 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2808 if (!env->me_rmutex) {
2812 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2813 if (!env->me_wmutex) {
2819 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2820 if (!env->me_rmutex) {
2824 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2825 if (!env->me_wmutex) {
2835 env->me_lfd = INVALID_HANDLE_VALUE;
2840 /** The name of the lock file in the DB environment */
2841 #define LOCKNAME "/lock.mdb"
2842 /** The name of the data file in the DB environment */
2843 #define DATANAME "/data.mdb"
2844 /** The suffix of the lock file when no subdir is used */
2845 #define LOCKSUFF "-lock"
2848 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2850 int oflags, rc, len, excl;
2851 char *lpath, *dpath;
2854 if (flags & MDB_NOSUBDIR) {
2855 rc = len + sizeof(LOCKSUFF) + len + 1;
2857 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2862 if (flags & MDB_NOSUBDIR) {
2863 dpath = lpath + len + sizeof(LOCKSUFF);
2864 sprintf(lpath, "%s" LOCKSUFF, path);
2865 strcpy(dpath, path);
2867 dpath = lpath + len + sizeof(LOCKNAME);
2868 sprintf(lpath, "%s" LOCKNAME, path);
2869 sprintf(dpath, "%s" DATANAME, path);
2872 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2877 if (F_ISSET(flags, MDB_RDONLY)) {
2878 oflags = GENERIC_READ;
2879 len = OPEN_EXISTING;
2881 oflags = GENERIC_READ|GENERIC_WRITE;
2884 mode = FILE_ATTRIBUTE_NORMAL;
2885 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2886 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2891 if (F_ISSET(flags, MDB_RDONLY))
2894 oflags = O_RDWR | O_CREAT;
2896 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2902 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2903 /* synchronous fd for meta writes */
2905 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2906 mode |= FILE_FLAG_WRITE_THROUGH;
2907 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2908 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2913 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2914 oflags |= MDB_DSYNC;
2915 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2920 env->me_path = strdup(path);
2921 DPRINTF("opened dbenv %p", (void *) env);
2922 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2923 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2925 mdb_env_share_locks(env);
2926 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2927 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2928 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2934 if (env->me_fd != INVALID_HANDLE_VALUE) {
2936 env->me_fd = INVALID_HANDLE_VALUE;
2938 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2940 env->me_lfd = INVALID_HANDLE_VALUE;
2948 mdb_env_close(MDB_env *env)
2955 VGMEMP_DESTROY(env);
2956 while (env->me_dpages) {
2957 dp = env->me_dpages;
2958 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
2959 env->me_dpages = dp->mp_next;
2963 free(env->me_dbs[1]);
2964 free(env->me_dbs[0]);
2968 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2969 pthread_key_delete(env->me_txkey);
2972 munmap(env->me_map, env->me_mapsize);
2977 pid_t pid = getpid();
2979 for (i=0; i<env->me_txns->mti_numreaders; i++)
2980 if (env->me_txns->mti_readers[i].mr_pid == pid)
2981 env->me_txns->mti_readers[i].mr_pid = 0;
2982 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2985 mdb_midl_free(env->me_free_pgs);
2989 /** Compare two items pointing at aligned size_t's */
2991 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2993 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2994 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2997 /** Compare two items pointing at aligned int's */
2999 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3001 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3002 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3005 /** Compare two items pointing at ints of unknown alignment.
3006 * Nodes and keys are guaranteed to be 2-byte aligned.
3009 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3011 #if BYTE_ORDER == LITTLE_ENDIAN
3012 unsigned short *u, *c;
3015 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3016 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3019 } while(!x && u > (unsigned short *)a->mv_data);
3022 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3026 /** Compare two items lexically */
3028 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3035 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3041 diff = memcmp(a->mv_data, b->mv_data, len);
3042 return diff ? diff : len_diff<0 ? -1 : len_diff;
3045 /** Compare two items in reverse byte order */
3047 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3049 const unsigned char *p1, *p2, *p1_lim;
3053 p1_lim = (const unsigned char *)a->mv_data;
3054 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3055 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3057 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3063 while (p1 > p1_lim) {
3064 diff = *--p1 - *--p2;
3068 return len_diff<0 ? -1 : len_diff;
3071 /** Search for key within a page, using binary search.
3072 * Returns the smallest entry larger or equal to the key.
3073 * If exactp is non-null, stores whether the found entry was an exact match
3074 * in *exactp (1 or 0).
3075 * Updates the cursor index with the index of the found entry.
3076 * If no entry larger or equal to the key is found, returns NULL.
3079 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3081 unsigned int i = 0, nkeys;
3084 MDB_page *mp = mc->mc_pg[mc->mc_top];
3085 MDB_node *node = NULL;
3090 nkeys = NUMKEYS(mp);
3095 COPY_PGNO(pgno, mp->mp_pgno);
3096 DPRINTF("searching %u keys in %s %spage %zu",
3097 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3104 low = IS_LEAF(mp) ? 0 : 1;
3106 cmp = mc->mc_dbx->md_cmp;
3108 /* Branch pages have no data, so if using integer keys,
3109 * alignment is guaranteed. Use faster mdb_cmp_int.
3111 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3112 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3119 nodekey.mv_size = mc->mc_db->md_pad;
3120 node = NODEPTR(mp, 0); /* fake */
3121 while (low <= high) {
3122 i = (low + high) >> 1;
3123 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3124 rc = cmp(key, &nodekey);
3125 DPRINTF("found leaf index %u [%s], rc = %i",
3126 i, DKEY(&nodekey), rc);
3135 while (low <= high) {
3136 i = (low + high) >> 1;
3138 node = NODEPTR(mp, i);
3139 nodekey.mv_size = NODEKSZ(node);
3140 nodekey.mv_data = NODEKEY(node);
3142 rc = cmp(key, &nodekey);
3145 DPRINTF("found leaf index %u [%s], rc = %i",
3146 i, DKEY(&nodekey), rc);
3148 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3149 i, DKEY(&nodekey), NODEPGNO(node), rc);
3160 if (rc > 0) { /* Found entry is less than the key. */
3161 i++; /* Skip to get the smallest entry larger than key. */
3163 node = NODEPTR(mp, i);
3166 *exactp = (rc == 0);
3167 /* store the key index */
3168 mc->mc_ki[mc->mc_top] = i;
3170 /* There is no entry larger or equal to the key. */
3173 /* nodeptr is fake for LEAF2 */
3179 mdb_cursor_adjust(MDB_cursor *mc, func)
3183 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3184 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3191 /** Pop a page off the top of the cursor's stack. */
3193 mdb_cursor_pop(MDB_cursor *mc)
3198 top = mc->mc_pg[mc->mc_top];
3203 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3204 mc->mc_dbi, (void *) mc);
3208 /** Push a page onto the top of the cursor's stack. */
3210 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3212 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3213 mc->mc_dbi, (void *) mc);
3215 if (mc->mc_snum >= CURSOR_STACK) {
3216 assert(mc->mc_snum < CURSOR_STACK);
3220 mc->mc_top = mc->mc_snum++;
3221 mc->mc_pg[mc->mc_top] = mp;
3222 mc->mc_ki[mc->mc_top] = 0;
3227 /** Find the address of the page corresponding to a given page number.
3228 * @param[in] txn the transaction for this access.
3229 * @param[in] pgno the page number for the page to retrieve.
3230 * @param[out] ret address of a pointer where the page's address will be stored.
3231 * @return 0 on success, non-zero on failure.
3234 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3238 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3240 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3241 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3242 p = txn->mt_u.dirty_list[x].mptr;
3246 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3247 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3251 DPRINTF("page %zu not found", pgno);
3254 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3257 /** Search for the page a given key should be in.
3258 * Pushes parent pages on the cursor stack. This function continues a
3259 * search on a cursor that has already been initialized. (Usually by
3260 * #mdb_page_search() but also by #mdb_node_move().)
3261 * @param[in,out] mc the cursor for this operation.
3262 * @param[in] key the key to search for. If NULL, search for the lowest
3263 * page. (This is used by #mdb_cursor_first().)
3264 * @param[in] modify If true, visited pages are updated with new page numbers.
3265 * @return 0 on success, non-zero on failure.
3268 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3270 MDB_page *mp = mc->mc_pg[mc->mc_top];
3275 while (IS_BRANCH(mp)) {
3279 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3280 assert(NUMKEYS(mp) > 1);
3281 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3283 if (key == NULL) /* Initialize cursor to first page. */
3285 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3286 /* cursor to last page */
3290 node = mdb_node_search(mc, key, &exact);
3292 i = NUMKEYS(mp) - 1;
3294 i = mc->mc_ki[mc->mc_top];
3303 DPRINTF("following index %u for key [%s]",
3305 assert(i < NUMKEYS(mp));
3306 node = NODEPTR(mp, i);
3308 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3311 mc->mc_ki[mc->mc_top] = i;
3312 if ((rc = mdb_cursor_push(mc, mp)))
3316 if ((rc = mdb_page_touch(mc)) != 0)
3318 mp = mc->mc_pg[mc->mc_top];
3323 DPRINTF("internal error, index points to a %02X page!?",
3325 return MDB_CORRUPTED;
3328 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3329 key ? DKEY(key) : NULL);
3334 /** Search for the page a given key should be in.
3335 * Pushes parent pages on the cursor stack. This function just sets up
3336 * the search; it finds the root page for \b mc's database and sets this
3337 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3338 * called to complete the search.
3339 * @param[in,out] mc the cursor for this operation.
3340 * @param[in] key the key to search for. If NULL, search for the lowest
3341 * page. (This is used by #mdb_cursor_first().)
3342 * @param[in] modify If true, visited pages are updated with new page numbers.
3343 * @return 0 on success, non-zero on failure.
3346 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3351 /* Make sure the txn is still viable, then find the root from
3352 * the txn's db table.
3354 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3355 DPUTS("transaction has failed, must abort");
3358 /* Make sure we're using an up-to-date root */
3359 if (mc->mc_dbi > MAIN_DBI) {
3360 if ((*mc->mc_dbflag & DB_STALE) ||
3361 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3363 unsigned char dbflag = 0;
3364 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3365 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3368 if (*mc->mc_dbflag & DB_STALE) {
3371 MDB_node *leaf = mdb_node_search(&mc2,
3372 &mc->mc_dbx->md_name, &exact);
3374 return MDB_NOTFOUND;
3375 mdb_node_read(mc->mc_txn, leaf, &data);
3376 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3380 *mc->mc_dbflag = dbflag;
3383 root = mc->mc_db->md_root;
3385 if (root == P_INVALID) { /* Tree is empty. */
3386 DPUTS("tree is empty");
3387 return MDB_NOTFOUND;
3392 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3398 DPRINTF("db %u root page %zu has flags 0x%X",
3399 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3402 if ((rc = mdb_page_touch(mc)))
3406 return mdb_page_search_root(mc, key, modify);
3409 /** Return the data associated with a given node.
3410 * @param[in] txn The transaction for this operation.
3411 * @param[in] leaf The node being read.
3412 * @param[out] data Updated to point to the node's data.
3413 * @return 0 on success, non-zero on failure.
3416 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3418 MDB_page *omp; /* overflow page */
3422 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3423 data->mv_size = NODEDSZ(leaf);
3424 data->mv_data = NODEDATA(leaf);
3428 /* Read overflow data.
3430 data->mv_size = NODEDSZ(leaf);
3431 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3432 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3433 DPRINTF("read overflow page %zu failed", pgno);
3436 data->mv_data = METADATA(omp);
3442 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3443 MDB_val *key, MDB_val *data)
3452 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3454 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3457 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3461 mdb_cursor_init(&mc, txn, dbi, &mx);
3462 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3465 /** Find a sibling for a page.
3466 * Replaces the page at the top of the cursor's stack with the
3467 * specified sibling, if one exists.
3468 * @param[in] mc The cursor for this operation.
3469 * @param[in] move_right Non-zero if the right sibling is requested,
3470 * otherwise the left sibling.
3471 * @return 0 on success, non-zero on failure.
3474 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3480 if (mc->mc_snum < 2) {
3481 return MDB_NOTFOUND; /* root has no siblings */
3485 DPRINTF("parent page is page %zu, index %u",
3486 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3488 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3489 : (mc->mc_ki[mc->mc_top] == 0)) {
3490 DPRINTF("no more keys left, moving to %s sibling",
3491 move_right ? "right" : "left");
3492 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3496 mc->mc_ki[mc->mc_top]++;
3498 mc->mc_ki[mc->mc_top]--;
3499 DPRINTF("just moving to %s index key %u",
3500 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3502 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3504 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3505 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3508 mdb_cursor_push(mc, mp);
3513 /** Move the cursor to the next data item. */
3515 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3521 if (mc->mc_flags & C_EOF) {
3522 return MDB_NOTFOUND;
3525 assert(mc->mc_flags & C_INITIALIZED);
3527 mp = mc->mc_pg[mc->mc_top];
3529 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3530 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3531 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3532 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3533 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3534 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3538 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3539 if (op == MDB_NEXT_DUP)
3540 return MDB_NOTFOUND;
3544 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3546 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3547 DPUTS("=====> move to next sibling page");
3548 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3549 mc->mc_flags |= C_EOF;
3550 mc->mc_flags &= ~C_INITIALIZED;
3551 return MDB_NOTFOUND;
3553 mp = mc->mc_pg[mc->mc_top];
3554 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3556 mc->mc_ki[mc->mc_top]++;
3558 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3559 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3562 key->mv_size = mc->mc_db->md_pad;
3563 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3567 assert(IS_LEAF(mp));
3568 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3570 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3571 mdb_xcursor_init1(mc, leaf);
3574 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3577 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3578 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3579 if (rc != MDB_SUCCESS)
3584 MDB_SET_KEY(leaf, key);
3588 /** Move the cursor to the previous data item. */
3590 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3596 assert(mc->mc_flags & C_INITIALIZED);
3598 mp = mc->mc_pg[mc->mc_top];
3600 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3601 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3602 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3603 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3604 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3605 if (op != MDB_PREV || rc == MDB_SUCCESS)
3608 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3609 if (op == MDB_PREV_DUP)
3610 return MDB_NOTFOUND;
3615 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3617 if (mc->mc_ki[mc->mc_top] == 0) {
3618 DPUTS("=====> move to prev sibling page");
3619 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3620 mc->mc_flags &= ~C_INITIALIZED;
3621 return MDB_NOTFOUND;
3623 mp = mc->mc_pg[mc->mc_top];
3624 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3625 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3627 mc->mc_ki[mc->mc_top]--;
3629 mc->mc_flags &= ~C_EOF;
3631 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3632 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3635 key->mv_size = mc->mc_db->md_pad;
3636 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3640 assert(IS_LEAF(mp));
3641 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3643 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3644 mdb_xcursor_init1(mc, leaf);
3647 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3650 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3651 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3652 if (rc != MDB_SUCCESS)
3657 MDB_SET_KEY(leaf, key);
3661 /** Set the cursor on a specific data item. */
3663 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3664 MDB_cursor_op op, int *exactp)
3673 assert(key->mv_size > 0);
3675 /* See if we're already on the right page */
3676 if (mc->mc_flags & C_INITIALIZED) {
3679 mp = mc->mc_pg[mc->mc_top];
3681 mc->mc_ki[mc->mc_top] = 0;
3682 return MDB_NOTFOUND;
3684 if (mp->mp_flags & P_LEAF2) {
3685 nodekey.mv_size = mc->mc_db->md_pad;
3686 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3688 leaf = NODEPTR(mp, 0);
3689 MDB_SET_KEY(leaf, &nodekey);
3691 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3693 /* Probably happens rarely, but first node on the page
3694 * was the one we wanted.
3696 mc->mc_ki[mc->mc_top] = 0;
3697 leaf = NODEPTR(mp, 0);
3704 unsigned int nkeys = NUMKEYS(mp);
3706 if (mp->mp_flags & P_LEAF2) {
3707 nodekey.mv_data = LEAF2KEY(mp,
3708 nkeys-1, nodekey.mv_size);
3710 leaf = NODEPTR(mp, nkeys-1);
3711 MDB_SET_KEY(leaf, &nodekey);
3713 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3715 /* last node was the one we wanted */
3716 mc->mc_ki[mc->mc_top] = nkeys-1;
3717 leaf = NODEPTR(mp, nkeys-1);
3723 /* This is definitely the right page, skip search_page */
3728 /* If any parents have right-sibs, search.
3729 * Otherwise, there's nothing further.
3731 for (i=0; i<mc->mc_top; i++)
3733 NUMKEYS(mc->mc_pg[i])-1)
3735 if (i == mc->mc_top) {
3736 /* There are no other pages */
3737 mc->mc_ki[mc->mc_top] = nkeys;
3738 return MDB_NOTFOUND;
3742 /* There are no other pages */
3743 mc->mc_ki[mc->mc_top] = 0;
3744 return MDB_NOTFOUND;
3748 rc = mdb_page_search(mc, key, 0);
3749 if (rc != MDB_SUCCESS)
3752 mp = mc->mc_pg[mc->mc_top];
3753 assert(IS_LEAF(mp));
3756 leaf = mdb_node_search(mc, key, exactp);
3757 if (exactp != NULL && !*exactp) {
3758 /* MDB_SET specified and not an exact match. */
3759 return MDB_NOTFOUND;
3763 DPUTS("===> inexact leaf not found, goto sibling");
3764 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3765 return rc; /* no entries matched */
3766 mp = mc->mc_pg[mc->mc_top];
3767 assert(IS_LEAF(mp));
3768 leaf = NODEPTR(mp, 0);
3772 mc->mc_flags |= C_INITIALIZED;
3773 mc->mc_flags &= ~C_EOF;
3776 key->mv_size = mc->mc_db->md_pad;
3777 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3781 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3782 mdb_xcursor_init1(mc, leaf);
3785 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3786 if (op == MDB_SET || op == MDB_SET_RANGE) {
3787 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3790 if (op == MDB_GET_BOTH) {
3796 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3797 if (rc != MDB_SUCCESS)
3800 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3802 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3804 rc = mc->mc_dbx->md_dcmp(data, &d2);
3806 if (op == MDB_GET_BOTH || rc > 0)
3807 return MDB_NOTFOUND;
3812 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3813 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3818 /* The key already matches in all other cases */
3819 if (op == MDB_SET_RANGE)
3820 MDB_SET_KEY(leaf, key);
3821 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3826 /** Move the cursor to the first item in the database. */
3828 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3833 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3834 rc = mdb_page_search(mc, NULL, 0);
3835 if (rc != MDB_SUCCESS)
3838 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3840 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3841 mc->mc_flags |= C_INITIALIZED;
3842 mc->mc_flags &= ~C_EOF;
3844 mc->mc_ki[mc->mc_top] = 0;
3846 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3847 key->mv_size = mc->mc_db->md_pad;
3848 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3853 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3854 mdb_xcursor_init1(mc, leaf);
3855 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3860 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3861 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3865 MDB_SET_KEY(leaf, key);
3869 /** Move the cursor to the last item in the database. */
3871 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3877 lkey.mv_size = MAXKEYSIZE+1;
3878 lkey.mv_data = NULL;
3880 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3881 rc = mdb_page_search(mc, &lkey, 0);
3882 if (rc != MDB_SUCCESS)
3885 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3887 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3888 mc->mc_flags |= C_INITIALIZED;
3889 mc->mc_flags &= ~C_EOF;
3891 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3893 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3894 key->mv_size = mc->mc_db->md_pad;
3895 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3900 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3901 mdb_xcursor_init1(mc, leaf);
3902 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3907 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3908 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3913 MDB_SET_KEY(leaf, key);
3918 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3928 case MDB_GET_BOTH_RANGE:
3929 if (data == NULL || mc->mc_xcursor == NULL) {
3936 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3938 } else if (op == MDB_SET_RANGE)
3939 rc = mdb_cursor_set(mc, key, data, op, NULL);
3941 rc = mdb_cursor_set(mc, key, data, op, &exact);
3943 case MDB_GET_MULTIPLE:
3945 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3946 !(mc->mc_flags & C_INITIALIZED)) {
3951 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3952 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3955 case MDB_NEXT_MULTIPLE:
3957 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3961 if (!(mc->mc_flags & C_INITIALIZED))
3962 rc = mdb_cursor_first(mc, key, data);
3964 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3965 if (rc == MDB_SUCCESS) {
3966 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3969 mx = &mc->mc_xcursor->mx_cursor;
3970 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3972 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3973 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3981 case MDB_NEXT_NODUP:
3982 if (!(mc->mc_flags & C_INITIALIZED))
3983 rc = mdb_cursor_first(mc, key, data);
3985 rc = mdb_cursor_next(mc, key, data, op);
3989 case MDB_PREV_NODUP:
3990 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3991 rc = mdb_cursor_last(mc, key, data);
3993 rc = mdb_cursor_prev(mc, key, data, op);
3996 rc = mdb_cursor_first(mc, key, data);
4000 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4001 !(mc->mc_flags & C_INITIALIZED) ||
4002 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4006 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4009 rc = mdb_cursor_last(mc, key, data);
4013 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4014 !(mc->mc_flags & C_INITIALIZED) ||
4015 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4019 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4022 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4030 /** Touch all the pages in the cursor stack.
4031 * Makes sure all the pages are writable, before attempting a write operation.
4032 * @param[in] mc The cursor to operate on.
4035 mdb_cursor_touch(MDB_cursor *mc)
4039 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4041 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4042 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
4045 *mc->mc_dbflag = DB_DIRTY;
4047 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4048 rc = mdb_page_touch(mc);
4052 mc->mc_top = mc->mc_snum-1;
4057 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4060 MDB_node *leaf = NULL;
4061 MDB_val xdata, *rdata, dkey;
4065 unsigned int mcount = 0;
4069 char dbuf[MAXKEYSIZE+1];
4070 unsigned int nflags;
4073 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4076 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4077 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4081 if (flags == MDB_CURRENT) {
4082 if (!(mc->mc_flags & C_INITIALIZED))
4085 } else if (mc->mc_db->md_root == P_INVALID) {
4087 /* new database, write a root leaf page */
4088 DPUTS("allocating new root leaf page");
4089 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4093 mdb_cursor_push(mc, np);
4094 mc->mc_db->md_root = np->mp_pgno;
4095 mc->mc_db->md_depth++;
4096 *mc->mc_dbflag = DB_DIRTY;
4097 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4099 np->mp_flags |= P_LEAF2;
4100 mc->mc_flags |= C_INITIALIZED;
4106 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4107 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4108 DPRINTF("duplicate key [%s]", DKEY(key));
4110 return MDB_KEYEXIST;
4112 if (rc && rc != MDB_NOTFOUND)
4116 /* Cursor is positioned, now make sure all pages are writable */
4117 rc2 = mdb_cursor_touch(mc);
4122 /* The key already exists */
4123 if (rc == MDB_SUCCESS) {
4124 /* there's only a key anyway, so this is a no-op */
4125 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4126 unsigned int ksize = mc->mc_db->md_pad;
4127 if (key->mv_size != ksize)
4129 if (flags == MDB_CURRENT) {
4130 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4131 memcpy(ptr, key->mv_data, ksize);
4136 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4139 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4140 /* Was a single item before, must convert now */
4142 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4143 /* Just overwrite the current item */
4144 if (flags == MDB_CURRENT)
4147 dkey.mv_size = NODEDSZ(leaf);
4148 dkey.mv_data = NODEDATA(leaf);
4149 #if UINT_MAX < SIZE_MAX
4150 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4151 #ifdef MISALIGNED_OK
4152 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4154 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4157 /* if data matches, ignore it */
4158 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4159 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4161 /* create a fake page for the dup items */
4162 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4163 dkey.mv_data = dbuf;
4164 fp = (MDB_page *)&pbuf;
4165 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4166 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4167 fp->mp_lower = PAGEHDRSZ;
4168 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4169 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4170 fp->mp_flags |= P_LEAF2;
4171 fp->mp_pad = data->mv_size;
4173 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4174 (dkey.mv_size & 1) + (data->mv_size & 1);
4176 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4179 xdata.mv_size = fp->mp_upper;
4184 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4185 /* See if we need to convert from fake page to subDB */
4187 unsigned int offset;
4190 fp = NODEDATA(leaf);
4191 if (flags == MDB_CURRENT) {
4192 fp->mp_flags |= P_DIRTY;
4193 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4194 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4198 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4199 offset = fp->mp_pad;
4201 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4203 offset += offset & 1;
4204 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4205 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4207 /* yes, convert it */
4209 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4210 dummy.md_pad = fp->mp_pad;
4211 dummy.md_flags = MDB_DUPFIXED;
4212 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4213 dummy.md_flags |= MDB_INTEGERKEY;
4216 dummy.md_branch_pages = 0;
4217 dummy.md_leaf_pages = 1;
4218 dummy.md_overflow_pages = 0;
4219 dummy.md_entries = NUMKEYS(fp);
4221 xdata.mv_size = sizeof(MDB_db);
4222 xdata.mv_data = &dummy;
4223 mp = mdb_page_alloc(mc, 1);
4226 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4227 flags |= F_DUPDATA|F_SUBDATA;
4228 dummy.md_root = mp->mp_pgno;
4230 /* no, just grow it */
4232 xdata.mv_size = NODEDSZ(leaf) + offset;
4233 xdata.mv_data = &pbuf;
4234 mp = (MDB_page *)&pbuf;
4235 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4238 mp->mp_flags = fp->mp_flags | P_DIRTY;
4239 mp->mp_pad = fp->mp_pad;
4240 mp->mp_lower = fp->mp_lower;
4241 mp->mp_upper = fp->mp_upper + offset;
4243 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4245 nsize = NODEDSZ(leaf) - fp->mp_upper;
4246 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4247 for (i=0; i<NUMKEYS(fp); i++)
4248 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4250 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4254 /* data is on sub-DB, just store it */
4255 flags |= F_DUPDATA|F_SUBDATA;
4259 /* same size, just replace it */
4260 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4261 NODEDSZ(leaf) == data->mv_size) {
4262 if (F_ISSET(flags, MDB_RESERVE))
4263 data->mv_data = NODEDATA(leaf);
4265 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4268 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4270 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4276 nflags = flags & NODE_ADD_FLAGS;
4277 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4278 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4279 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4280 nflags &= ~MDB_APPEND;
4281 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4283 /* There is room already in this leaf page. */
4284 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4285 if (rc == 0 && !do_sub) {
4286 /* Adjust other cursors pointing to mp */
4287 MDB_cursor *m2, *m3;
4288 MDB_dbi dbi = mc->mc_dbi;
4289 unsigned i = mc->mc_top;
4290 MDB_page *mp = mc->mc_pg[i];
4292 if (mc->mc_flags & C_SUB)
4295 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4296 if (mc->mc_flags & C_SUB)
4297 m3 = &m2->mc_xcursor->mx_cursor;
4300 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4301 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4308 if (rc != MDB_SUCCESS)
4309 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4311 /* Now store the actual data in the child DB. Note that we're
4312 * storing the user data in the keys field, so there are strict
4313 * size limits on dupdata. The actual data fields of the child
4314 * DB are all zero size.
4321 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4322 if (flags & MDB_CURRENT) {
4323 xflags = MDB_CURRENT;
4325 mdb_xcursor_init1(mc, leaf);
4326 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4328 /* converted, write the original data first */
4330 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4334 /* Adjust other cursors pointing to mp */
4336 unsigned i = mc->mc_top;
4337 MDB_page *mp = mc->mc_pg[i];
4339 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4340 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4341 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4342 mdb_xcursor_init1(m2, leaf);
4347 xflags |= (flags & MDB_APPEND);
4348 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4349 if (flags & F_SUBDATA) {
4350 void *db = NODEDATA(leaf);
4351 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4354 /* sub-writes might have failed so check rc again.
4355 * Don't increment count if we just replaced an existing item.
4357 if (!rc && !(flags & MDB_CURRENT))
4358 mc->mc_db->md_entries++;
4359 if (flags & MDB_MULTIPLE) {
4361 if (mcount < data[1].mv_size) {
4362 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4363 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4373 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4378 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4381 if (!mc->mc_flags & C_INITIALIZED)
4384 rc = mdb_cursor_touch(mc);
4388 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4390 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4391 if (flags != MDB_NODUPDATA) {
4392 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4393 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4395 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4396 /* If sub-DB still has entries, we're done */
4397 if (mc->mc_xcursor->mx_db.md_entries) {
4398 if (leaf->mn_flags & F_SUBDATA) {
4399 /* update subDB info */
4400 void *db = NODEDATA(leaf);
4401 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4403 /* shrink fake page */
4404 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4406 mc->mc_db->md_entries--;
4409 /* otherwise fall thru and delete the sub-DB */
4412 if (leaf->mn_flags & F_SUBDATA) {
4413 /* add all the child DB's pages to the free list */
4414 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4415 if (rc == MDB_SUCCESS) {
4416 mc->mc_db->md_entries -=
4417 mc->mc_xcursor->mx_db.md_entries;
4422 return mdb_cursor_del0(mc, leaf);
4425 /** Allocate and initialize new pages for a database.
4426 * @param[in] mc a cursor on the database being added to.
4427 * @param[in] flags flags defining what type of page is being allocated.
4428 * @param[in] num the number of pages to allocate. This is usually 1,
4429 * unless allocating overflow pages for a large record.
4430 * @return Address of a page, or NULL on failure.
4433 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4437 if ((np = mdb_page_alloc(mc, num)) == NULL)
4439 DPRINTF("allocated new mpage %zu, page size %u",
4440 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4441 np->mp_flags = flags | P_DIRTY;
4442 np->mp_lower = PAGEHDRSZ;
4443 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4446 mc->mc_db->md_branch_pages++;
4447 else if (IS_LEAF(np))
4448 mc->mc_db->md_leaf_pages++;
4449 else if (IS_OVERFLOW(np)) {
4450 mc->mc_db->md_overflow_pages += num;
4457 /** Calculate the size of a leaf node.
4458 * The size depends on the environment's page size; if a data item
4459 * is too large it will be put onto an overflow page and the node
4460 * size will only include the key and not the data. Sizes are always
4461 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4462 * of the #MDB_node headers.
4463 * @param[in] env The environment handle.
4464 * @param[in] key The key for the node.
4465 * @param[in] data The data for the node.
4466 * @return The number of bytes needed to store the node.
4469 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4473 sz = LEAFSIZE(key, data);
4474 if (sz >= env->me_psize / MDB_MINKEYS) {
4475 /* put on overflow page */
4476 sz -= data->mv_size - sizeof(pgno_t);
4480 return sz + sizeof(indx_t);
4483 /** Calculate the size of a branch node.
4484 * The size should depend on the environment's page size but since
4485 * we currently don't support spilling large keys onto overflow
4486 * pages, it's simply the size of the #MDB_node header plus the
4487 * size of the key. Sizes are always rounded up to an even number
4488 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4489 * @param[in] env The environment handle.
4490 * @param[in] key The key for the node.
4491 * @return The number of bytes needed to store the node.
4494 mdb_branch_size(MDB_env *env, MDB_val *key)
4499 if (sz >= env->me_psize / MDB_MINKEYS) {
4500 /* put on overflow page */
4501 /* not implemented */
4502 /* sz -= key->size - sizeof(pgno_t); */
4505 return sz + sizeof(indx_t);
4508 /** Add a node to the page pointed to by the cursor.
4509 * @param[in] mc The cursor for this operation.
4510 * @param[in] indx The index on the page where the new node should be added.
4511 * @param[in] key The key for the new node.
4512 * @param[in] data The data for the new node, if any.
4513 * @param[in] pgno The page number, if adding a branch node.
4514 * @param[in] flags Flags for the node.
4515 * @return 0 on success, non-zero on failure. Possible errors are:
4517 * <li>ENOMEM - failed to allocate overflow pages for the node.
4518 * <li>ENOSPC - there is insufficient room in the page. This error
4519 * should never happen since all callers already calculate the
4520 * page's free space before calling this function.
4524 mdb_node_add(MDB_cursor *mc, indx_t indx,
4525 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4528 size_t node_size = NODESIZE;
4531 MDB_page *mp = mc->mc_pg[mc->mc_top];
4532 MDB_page *ofp = NULL; /* overflow page */
4535 assert(mp->mp_upper >= mp->mp_lower);
4537 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4538 IS_LEAF(mp) ? "leaf" : "branch",
4539 IS_SUBP(mp) ? "sub-" : "",
4540 mp->mp_pgno, indx, data ? data->mv_size : 0,
4541 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4544 /* Move higher keys up one slot. */
4545 int ksize = mc->mc_db->md_pad, dif;
4546 char *ptr = LEAF2KEY(mp, indx, ksize);
4547 dif = NUMKEYS(mp) - indx;
4549 memmove(ptr+ksize, ptr, dif*ksize);
4550 /* insert new key */
4551 memcpy(ptr, key->mv_data, ksize);
4553 /* Just using these for counting */
4554 mp->mp_lower += sizeof(indx_t);
4555 mp->mp_upper -= ksize - sizeof(indx_t);
4560 node_size += key->mv_size;
4564 if (F_ISSET(flags, F_BIGDATA)) {
4565 /* Data already on overflow page. */
4566 node_size += sizeof(pgno_t);
4567 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4568 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4569 /* Put data on overflow page. */
4570 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4571 data->mv_size, node_size+data->mv_size);
4572 node_size += sizeof(pgno_t);
4573 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4575 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4578 node_size += data->mv_size;
4581 node_size += node_size & 1;
4583 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4584 DPRINTF("not enough room in page %zu, got %u ptrs",
4585 mp->mp_pgno, NUMKEYS(mp));
4586 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4587 mp->mp_upper - mp->mp_lower);
4588 DPRINTF("node size = %zu", node_size);
4592 /* Move higher pointers up one slot. */
4593 for (i = NUMKEYS(mp); i > indx; i--)
4594 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4596 /* Adjust free space offsets. */
4597 ofs = mp->mp_upper - node_size;
4598 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4599 mp->mp_ptrs[indx] = ofs;
4601 mp->mp_lower += sizeof(indx_t);
4603 /* Write the node data. */
4604 node = NODEPTR(mp, indx);
4605 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4606 node->mn_flags = flags;
4608 SETDSZ(node,data->mv_size);
4613 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4618 if (F_ISSET(flags, F_BIGDATA))
4619 memcpy(node->mn_data + key->mv_size, data->mv_data,
4621 else if (F_ISSET(flags, MDB_RESERVE))
4622 data->mv_data = node->mn_data + key->mv_size;
4624 memcpy(node->mn_data + key->mv_size, data->mv_data,
4627 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4629 if (F_ISSET(flags, MDB_RESERVE))
4630 data->mv_data = METADATA(ofp);
4632 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4639 /** Delete the specified node from a page.
4640 * @param[in] mp The page to operate on.
4641 * @param[in] indx The index of the node to delete.
4642 * @param[in] ksize The size of a node. Only used if the page is
4643 * part of a #MDB_DUPFIXED database.
4646 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4649 indx_t i, j, numkeys, ptr;
4656 COPY_PGNO(pgno, mp->mp_pgno);
4657 DPRINTF("delete node %u on %s page %zu", indx,
4658 IS_LEAF(mp) ? "leaf" : "branch", pgno);
4661 assert(indx < NUMKEYS(mp));
4664 int x = NUMKEYS(mp) - 1 - indx;
4665 base = LEAF2KEY(mp, indx, ksize);
4667 memmove(base, base + ksize, x * ksize);
4668 mp->mp_lower -= sizeof(indx_t);
4669 mp->mp_upper += ksize - sizeof(indx_t);
4673 node = NODEPTR(mp, indx);
4674 sz = NODESIZE + node->mn_ksize;
4676 if (F_ISSET(node->mn_flags, F_BIGDATA))
4677 sz += sizeof(pgno_t);
4679 sz += NODEDSZ(node);
4683 ptr = mp->mp_ptrs[indx];
4684 numkeys = NUMKEYS(mp);
4685 for (i = j = 0; i < numkeys; i++) {
4687 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4688 if (mp->mp_ptrs[i] < ptr)
4689 mp->mp_ptrs[j] += sz;
4694 base = (char *)mp + mp->mp_upper;
4695 memmove(base + sz, base, ptr - mp->mp_upper);
4697 mp->mp_lower -= sizeof(indx_t);
4701 /** Compact the main page after deleting a node on a subpage.
4702 * @param[in] mp The main page to operate on.
4703 * @param[in] indx The index of the subpage on the main page.
4706 mdb_node_shrink(MDB_page *mp, indx_t indx)
4713 indx_t i, numkeys, ptr;
4715 node = NODEPTR(mp, indx);
4716 sp = (MDB_page *)NODEDATA(node);
4717 osize = NODEDSZ(node);
4719 delta = sp->mp_upper - sp->mp_lower;
4720 SETDSZ(node, osize - delta);
4721 xp = (MDB_page *)((char *)sp + delta);
4723 /* shift subpage upward */
4725 nsize = NUMKEYS(sp) * sp->mp_pad;
4726 memmove(METADATA(xp), METADATA(sp), nsize);
4729 nsize = osize - sp->mp_upper;
4730 numkeys = NUMKEYS(sp);
4731 for (i=numkeys-1; i>=0; i--)
4732 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4734 xp->mp_upper = sp->mp_lower;
4735 xp->mp_lower = sp->mp_lower;
4736 xp->mp_flags = sp->mp_flags;
4737 xp->mp_pad = sp->mp_pad;
4738 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4740 /* shift lower nodes upward */
4741 ptr = mp->mp_ptrs[indx];
4742 numkeys = NUMKEYS(mp);
4743 for (i = 0; i < numkeys; i++) {
4744 if (mp->mp_ptrs[i] <= ptr)
4745 mp->mp_ptrs[i] += delta;
4748 base = (char *)mp + mp->mp_upper;
4749 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4750 mp->mp_upper += delta;
4753 /** Initial setup of a sorted-dups cursor.
4754 * Sorted duplicates are implemented as a sub-database for the given key.
4755 * The duplicate data items are actually keys of the sub-database.
4756 * Operations on the duplicate data items are performed using a sub-cursor
4757 * initialized when the sub-database is first accessed. This function does
4758 * the preliminary setup of the sub-cursor, filling in the fields that
4759 * depend only on the parent DB.
4760 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4763 mdb_xcursor_init0(MDB_cursor *mc)
4765 MDB_xcursor *mx = mc->mc_xcursor;
4767 mx->mx_cursor.mc_xcursor = NULL;
4768 mx->mx_cursor.mc_txn = mc->mc_txn;
4769 mx->mx_cursor.mc_db = &mx->mx_db;
4770 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4771 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4772 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4773 mx->mx_cursor.mc_snum = 0;
4774 mx->mx_cursor.mc_flags = C_SUB;
4775 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4776 mx->mx_dbx.md_dcmp = NULL;
4777 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4780 /** Final setup of a sorted-dups cursor.
4781 * Sets up the fields that depend on the data from the main cursor.
4782 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4783 * @param[in] node The data containing the #MDB_db record for the
4784 * sorted-dup database.
4787 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4789 MDB_xcursor *mx = mc->mc_xcursor;
4791 if (node->mn_flags & F_SUBDATA) {
4792 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
4793 mx->mx_cursor.mc_snum = 0;
4794 mx->mx_cursor.mc_flags = C_SUB;
4796 MDB_page *fp = NODEDATA(node);
4797 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4798 mx->mx_db.md_flags = 0;
4799 mx->mx_db.md_depth = 1;
4800 mx->mx_db.md_branch_pages = 0;
4801 mx->mx_db.md_leaf_pages = 1;
4802 mx->mx_db.md_overflow_pages = 0;
4803 mx->mx_db.md_entries = NUMKEYS(fp);
4804 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4805 mx->mx_cursor.mc_snum = 1;
4806 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4807 mx->mx_cursor.mc_top = 0;
4808 mx->mx_cursor.mc_pg[0] = fp;
4809 mx->mx_cursor.mc_ki[0] = 0;
4810 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4811 mx->mx_db.md_flags = MDB_DUPFIXED;
4812 mx->mx_db.md_pad = fp->mp_pad;
4813 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4814 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4817 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4819 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4821 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4822 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4823 #if UINT_MAX < SIZE_MAX
4824 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4825 #ifdef MISALIGNED_OK
4826 mx->mx_dbx.md_cmp = mdb_cmp_long;
4828 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4833 /** Initialize a cursor for a given transaction and database. */
4835 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4840 mc->mc_db = &txn->mt_dbs[dbi];
4841 mc->mc_dbx = &txn->mt_dbxs[dbi];
4842 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4846 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4848 mc->mc_xcursor = mx;
4849 mdb_xcursor_init0(mc);
4851 mc->mc_xcursor = NULL;
4856 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4859 MDB_xcursor *mx = NULL;
4860 size_t size = sizeof(MDB_cursor);
4862 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4865 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4866 size += sizeof(MDB_xcursor);
4868 if ((mc = malloc(size)) != NULL) {
4869 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4870 mx = (MDB_xcursor *)(mc + 1);
4872 mdb_cursor_init(mc, txn, dbi, mx);
4873 if (txn->mt_cursors) {
4874 mc->mc_next = txn->mt_cursors[dbi];
4875 txn->mt_cursors[dbi] = mc;
4877 mc->mc_flags |= C_ALLOCD;
4887 /* Return the count of duplicate data items for the current key */
4889 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4893 if (mc == NULL || countp == NULL)
4896 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4899 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4900 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4903 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4906 *countp = mc->mc_xcursor->mx_db.md_entries;
4912 mdb_cursor_close(MDB_cursor *mc)
4915 /* remove from txn, if tracked */
4916 if (mc->mc_txn->mt_cursors) {
4917 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4918 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4920 *prev = mc->mc_next;
4922 if (mc->mc_flags & C_ALLOCD)
4928 mdb_cursor_txn(MDB_cursor *mc)
4930 if (!mc) return NULL;
4935 mdb_cursor_dbi(MDB_cursor *mc)
4941 /** Replace the key for a node with a new key.
4942 * @param[in] mp The page containing the node to operate on.
4943 * @param[in] indx The index of the node to operate on.
4944 * @param[in] key The new key to use.
4945 * @return 0 on success, non-zero on failure.
4948 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4950 indx_t ptr, i, numkeys;
4957 node = NODEPTR(mp, indx);
4958 ptr = mp->mp_ptrs[indx];
4962 char kbuf2[(MAXKEYSIZE*2+1)];
4963 k2.mv_data = NODEKEY(node);
4964 k2.mv_size = node->mn_ksize;
4965 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
4967 mdb_dkey(&k2, kbuf2),
4973 delta = key->mv_size - node->mn_ksize;
4975 if (delta > 0 && SIZELEFT(mp) < delta) {
4976 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4980 numkeys = NUMKEYS(mp);
4981 for (i = 0; i < numkeys; i++) {
4982 if (mp->mp_ptrs[i] <= ptr)
4983 mp->mp_ptrs[i] -= delta;
4986 base = (char *)mp + mp->mp_upper;
4987 len = ptr - mp->mp_upper + NODESIZE;
4988 memmove(base - delta, base, len);
4989 mp->mp_upper -= delta;
4991 node = NODEPTR(mp, indx);
4992 node->mn_ksize = key->mv_size;
4996 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5001 /** Move a node from csrc to cdst.
5004 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5010 unsigned short flags;
5014 /* Mark src and dst as dirty. */
5015 if ((rc = mdb_page_touch(csrc)) ||
5016 (rc = mdb_page_touch(cdst)))
5019 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5020 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5021 key.mv_size = csrc->mc_db->md_pad;
5022 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5024 data.mv_data = NULL;
5028 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5029 assert(!((long)srcnode&1));
5030 srcpg = NODEPGNO(srcnode);
5031 flags = srcnode->mn_flags;
5032 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5033 unsigned int snum = csrc->mc_snum;
5035 /* must find the lowest key below src */
5036 mdb_page_search_root(csrc, NULL, 0);
5037 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5038 key.mv_size = NODEKSZ(s2);
5039 key.mv_data = NODEKEY(s2);
5040 csrc->mc_snum = snum--;
5041 csrc->mc_top = snum;
5043 key.mv_size = NODEKSZ(srcnode);
5044 key.mv_data = NODEKEY(srcnode);
5046 data.mv_size = NODEDSZ(srcnode);
5047 data.mv_data = NODEDATA(srcnode);
5049 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5050 unsigned int snum = cdst->mc_snum;
5053 /* must find the lowest key below dst */
5054 mdb_page_search_root(cdst, NULL, 0);
5055 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5056 bkey.mv_size = NODEKSZ(s2);
5057 bkey.mv_data = NODEKEY(s2);
5058 cdst->mc_snum = snum--;
5059 cdst->mc_top = snum;
5060 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5063 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5064 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5065 csrc->mc_ki[csrc->mc_top],
5067 csrc->mc_pg[csrc->mc_top]->mp_pgno,
5068 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5070 /* Add the node to the destination page.
5072 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5073 if (rc != MDB_SUCCESS)
5076 /* Delete the node from the source page.
5078 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5081 /* Adjust other cursors pointing to mp */
5082 MDB_cursor *m2, *m3;
5083 MDB_dbi dbi = csrc->mc_dbi;
5084 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5086 if (csrc->mc_flags & C_SUB)
5089 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5090 if (m2 == csrc) continue;
5091 if (csrc->mc_flags & C_SUB)
5092 m3 = &m2->mc_xcursor->mx_cursor;
5095 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5096 csrc->mc_ki[csrc->mc_top]) {
5097 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5098 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5103 /* Update the parent separators.
5105 if (csrc->mc_ki[csrc->mc_top] == 0) {
5106 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5107 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5108 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5110 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5111 key.mv_size = NODEKSZ(srcnode);
5112 key.mv_data = NODEKEY(srcnode);
5114 DPRINTF("update separator for source page %zu to [%s]",
5115 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5116 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5117 &key)) != MDB_SUCCESS)
5120 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5122 nullkey.mv_size = 0;
5123 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5124 assert(rc == MDB_SUCCESS);
5128 if (cdst->mc_ki[cdst->mc_top] == 0) {
5129 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5130 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5131 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5133 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5134 key.mv_size = NODEKSZ(srcnode);
5135 key.mv_data = NODEKEY(srcnode);
5137 DPRINTF("update separator for destination page %zu to [%s]",
5138 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5139 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5140 &key)) != MDB_SUCCESS)
5143 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5145 nullkey.mv_size = 0;
5146 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5147 assert(rc == MDB_SUCCESS);
5154 /** Merge one page into another.
5155 * The nodes from the page pointed to by \b csrc will
5156 * be copied to the page pointed to by \b cdst and then
5157 * the \b csrc page will be freed.
5158 * @param[in] csrc Cursor pointing to the source page.
5159 * @param[in] cdst Cursor pointing to the destination page.
5162 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5170 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5171 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5173 assert(csrc->mc_snum > 1); /* can't merge root page */
5174 assert(cdst->mc_snum > 1);
5176 /* Mark dst as dirty. */
5177 if ((rc = mdb_page_touch(cdst)))
5180 /* Move all nodes from src to dst.
5182 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5183 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5184 key.mv_size = csrc->mc_db->md_pad;
5185 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5186 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5187 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5188 if (rc != MDB_SUCCESS)
5190 key.mv_data = (char *)key.mv_data + key.mv_size;
5193 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5194 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5195 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5196 unsigned int snum = csrc->mc_snum;
5198 /* must find the lowest key below src */
5199 mdb_page_search_root(csrc, NULL, 0);
5200 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5201 key.mv_size = NODEKSZ(s2);
5202 key.mv_data = NODEKEY(s2);
5203 csrc->mc_snum = snum--;
5204 csrc->mc_top = snum;
5206 key.mv_size = srcnode->mn_ksize;
5207 key.mv_data = NODEKEY(srcnode);
5210 data.mv_size = NODEDSZ(srcnode);
5211 data.mv_data = NODEDATA(srcnode);
5212 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5213 if (rc != MDB_SUCCESS)
5218 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5219 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);
5221 /* Unlink the src page from parent and add to free list.
5223 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5224 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5226 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5230 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5231 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5232 csrc->mc_db->md_leaf_pages--;
5234 csrc->mc_db->md_branch_pages--;
5236 /* Adjust other cursors pointing to mp */
5237 MDB_cursor *m2, *m3;
5238 MDB_dbi dbi = csrc->mc_dbi;
5239 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5241 if (csrc->mc_flags & C_SUB)
5244 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5245 if (csrc->mc_flags & C_SUB)
5246 m3 = &m2->mc_xcursor->mx_cursor;
5249 if (m3 == csrc) continue;
5250 if (m3->mc_snum < csrc->mc_snum) continue;
5251 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5252 m3->mc_pg[csrc->mc_top] = mp;
5253 m3->mc_ki[csrc->mc_top] += nkeys;
5257 mdb_cursor_pop(csrc);
5259 return mdb_rebalance(csrc);
5262 /** Copy the contents of a cursor.
5263 * @param[in] csrc The cursor to copy from.
5264 * @param[out] cdst The cursor to copy to.
5267 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5271 cdst->mc_txn = csrc->mc_txn;
5272 cdst->mc_dbi = csrc->mc_dbi;
5273 cdst->mc_db = csrc->mc_db;
5274 cdst->mc_dbx = csrc->mc_dbx;
5275 cdst->mc_snum = csrc->mc_snum;
5276 cdst->mc_top = csrc->mc_top;
5277 cdst->mc_flags = csrc->mc_flags;
5279 for (i=0; i<csrc->mc_snum; i++) {
5280 cdst->mc_pg[i] = csrc->mc_pg[i];
5281 cdst->mc_ki[i] = csrc->mc_ki[i];
5285 /** Rebalance the tree after a delete operation.
5286 * @param[in] mc Cursor pointing to the page where rebalancing
5288 * @return 0 on success, non-zero on failure.
5291 mdb_rebalance(MDB_cursor *mc)
5301 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5302 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5303 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5304 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5308 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5311 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5312 DPRINTF("no need to rebalance page %zu, above fill threshold",
5318 if (mc->mc_snum < 2) {
5319 MDB_page *mp = mc->mc_pg[0];
5320 if (NUMKEYS(mp) == 0) {
5321 DPUTS("tree is completely empty");
5322 mc->mc_db->md_root = P_INVALID;
5323 mc->mc_db->md_depth = 0;
5324 mc->mc_db->md_leaf_pages = 0;
5325 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5329 /* Adjust other cursors pointing to mp */
5330 MDB_cursor *m2, *m3;
5331 MDB_dbi dbi = mc->mc_dbi;
5333 if (mc->mc_flags & C_SUB)
5336 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5337 if (m2 == mc) continue;
5338 if (mc->mc_flags & C_SUB)
5339 m3 = &m2->mc_xcursor->mx_cursor;
5342 if (m3->mc_snum < mc->mc_snum) continue;
5343 if (m3->mc_pg[0] == mp) {
5349 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5350 DPUTS("collapsing root page!");
5351 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5352 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5353 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5356 mc->mc_db->md_depth--;
5357 mc->mc_db->md_branch_pages--;
5359 /* Adjust other cursors pointing to mp */
5360 MDB_cursor *m2, *m3;
5361 MDB_dbi dbi = mc->mc_dbi;
5363 if (mc->mc_flags & C_SUB)
5366 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5367 if (m2 == mc) continue;
5368 if (mc->mc_flags & C_SUB)
5369 m3 = &m2->mc_xcursor->mx_cursor;
5372 if (m3->mc_snum < mc->mc_snum) continue;
5373 if (m3->mc_pg[0] == mp) {
5374 m3->mc_pg[0] = mc->mc_pg[0];
5379 DPUTS("root page doesn't need rebalancing");
5383 /* The parent (branch page) must have at least 2 pointers,
5384 * otherwise the tree is invalid.
5386 ptop = mc->mc_top-1;
5387 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5389 /* Leaf page fill factor is below the threshold.
5390 * Try to move keys from left or right neighbor, or
5391 * merge with a neighbor page.
5396 mdb_cursor_copy(mc, &mn);
5397 mn.mc_xcursor = NULL;
5399 if (mc->mc_ki[ptop] == 0) {
5400 /* We're the leftmost leaf in our parent.
5402 DPUTS("reading right neighbor");
5404 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5405 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5407 mn.mc_ki[mn.mc_top] = 0;
5408 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5410 /* There is at least one neighbor to the left.
5412 DPUTS("reading left neighbor");
5414 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5415 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5417 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5418 mc->mc_ki[mc->mc_top] = 0;
5421 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5422 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);
5424 /* If the neighbor page is above threshold and has at least two
5425 * keys, move one key from it.
5427 * Otherwise we should try to merge them.
5429 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5430 return mdb_node_move(&mn, mc);
5431 else { /* FIXME: if (has_enough_room()) */
5432 mc->mc_flags &= ~C_INITIALIZED;
5433 if (mc->mc_ki[ptop] == 0)
5434 return mdb_page_merge(&mn, mc);
5436 return mdb_page_merge(mc, &mn);
5440 /** Complete a delete operation started by #mdb_cursor_del(). */
5442 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5446 /* add overflow pages to free list */
5447 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5451 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5452 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5453 mc->mc_db->md_overflow_pages -= ovpages;
5454 for (i=0; i<ovpages; i++) {
5455 DPRINTF("freed ov page %zu", pg);
5456 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5460 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5461 mc->mc_db->md_entries--;
5462 rc = mdb_rebalance(mc);
5463 if (rc != MDB_SUCCESS)
5464 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5470 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5471 MDB_val *key, MDB_val *data)
5476 MDB_val rdata, *xdata;
5480 assert(key != NULL);
5482 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5484 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5487 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5491 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5495 mdb_cursor_init(&mc, txn, dbi, &mx);
5506 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5508 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5512 /** Split a page and insert a new node.
5513 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5514 * The cursor will be updated to point to the actual page and index where
5515 * the node got inserted after the split.
5516 * @param[in] newkey The key for the newly inserted node.
5517 * @param[in] newdata The data for the newly inserted node.
5518 * @param[in] newpgno The page number, if the new node is a branch node.
5519 * @return 0 on success, non-zero on failure.
5522 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5523 unsigned int nflags)
5526 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5529 unsigned int i, j, split_indx, nkeys, pmax;
5531 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5533 MDB_page *mp, *rp, *pp;
5538 mp = mc->mc_pg[mc->mc_top];
5539 newindx = mc->mc_ki[mc->mc_top];
5541 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5542 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5543 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5545 if (mc->mc_snum < 2) {
5546 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5548 /* shift current top to make room for new parent */
5549 mc->mc_pg[1] = mc->mc_pg[0];
5550 mc->mc_ki[1] = mc->mc_ki[0];
5553 mc->mc_db->md_root = pp->mp_pgno;
5554 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5555 mc->mc_db->md_depth++;
5558 /* Add left (implicit) pointer. */
5559 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5560 /* undo the pre-push */
5561 mc->mc_pg[0] = mc->mc_pg[1];
5562 mc->mc_ki[0] = mc->mc_ki[1];
5563 mc->mc_db->md_root = mp->mp_pgno;
5564 mc->mc_db->md_depth--;
5571 ptop = mc->mc_top-1;
5572 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5575 /* Create a right sibling. */
5576 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5578 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5580 mdb_cursor_copy(mc, &mn);
5581 mn.mc_pg[mn.mc_top] = rp;
5582 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5584 if (nflags & MDB_APPEND) {
5585 mn.mc_ki[mn.mc_top] = 0;
5592 nkeys = NUMKEYS(mp);
5593 split_indx = nkeys / 2 + 1;
5598 unsigned int lsize, rsize, ksize;
5599 /* Move half of the keys to the right sibling */
5601 x = mc->mc_ki[mc->mc_top] - split_indx;
5602 ksize = mc->mc_db->md_pad;
5603 split = LEAF2KEY(mp, split_indx, ksize);
5604 rsize = (nkeys - split_indx) * ksize;
5605 lsize = (nkeys - split_indx) * sizeof(indx_t);
5606 mp->mp_lower -= lsize;
5607 rp->mp_lower += lsize;
5608 mp->mp_upper += rsize - lsize;
5609 rp->mp_upper -= rsize - lsize;
5610 sepkey.mv_size = ksize;
5611 if (newindx == split_indx) {
5612 sepkey.mv_data = newkey->mv_data;
5614 sepkey.mv_data = split;
5617 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5618 memcpy(rp->mp_ptrs, split, rsize);
5619 sepkey.mv_data = rp->mp_ptrs;
5620 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5621 memcpy(ins, newkey->mv_data, ksize);
5622 mp->mp_lower += sizeof(indx_t);
5623 mp->mp_upper -= ksize - sizeof(indx_t);
5626 memcpy(rp->mp_ptrs, split, x * ksize);
5627 ins = LEAF2KEY(rp, x, ksize);
5628 memcpy(ins, newkey->mv_data, ksize);
5629 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5630 rp->mp_lower += sizeof(indx_t);
5631 rp->mp_upper -= ksize - sizeof(indx_t);
5632 mc->mc_ki[mc->mc_top] = x;
5633 mc->mc_pg[mc->mc_top] = rp;
5638 /* For leaf pages, check the split point based on what
5639 * fits where, since otherwise add_node can fail.
5642 unsigned int psize, nsize;
5643 /* Maximum free space in an empty page */
5644 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5645 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5646 if (newindx < split_indx) {
5648 for (i=0; i<split_indx; i++) {
5649 node = NODEPTR(mp, i);
5650 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5651 if (F_ISSET(node->mn_flags, F_BIGDATA))
5652 psize += sizeof(pgno_t);
5654 psize += NODEDSZ(node);
5663 for (i=nkeys-1; i>=split_indx; i--) {
5664 node = NODEPTR(mp, i);
5665 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5666 if (F_ISSET(node->mn_flags, F_BIGDATA))
5667 psize += sizeof(pgno_t);
5669 psize += NODEDSZ(node);
5679 /* First find the separating key between the split pages.
5681 if (newindx == split_indx) {
5682 sepkey.mv_size = newkey->mv_size;
5683 sepkey.mv_data = newkey->mv_data;
5685 node = NODEPTR(mp, split_indx);
5686 sepkey.mv_size = node->mn_ksize;
5687 sepkey.mv_data = NODEKEY(node);
5691 DPRINTF("separator is [%s]", DKEY(&sepkey));
5693 /* Copy separator key to the parent.
5695 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5698 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5700 /* Right page might now have changed parent.
5701 * Check if left page also changed parent.
5703 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5704 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5705 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5706 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5710 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5713 if (rc != MDB_SUCCESS) {
5716 if (nflags & MDB_APPEND) {
5717 mc->mc_pg[mc->mc_top] = rp;
5718 mc->mc_ki[mc->mc_top] = 0;
5719 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5728 /* Move half of the keys to the right sibling. */
5730 /* grab a page to hold a temporary copy */
5731 copy = mdb_page_malloc(mc);
5735 copy->mp_pgno = mp->mp_pgno;
5736 copy->mp_flags = mp->mp_flags;
5737 copy->mp_lower = PAGEHDRSZ;
5738 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5739 mc->mc_pg[mc->mc_top] = copy;
5740 for (i = j = 0; i <= nkeys; j++) {
5741 if (i == split_indx) {
5742 /* Insert in right sibling. */
5743 /* Reset insert index for right sibling. */
5744 j = (i == newindx && ins_new);
5745 mc->mc_pg[mc->mc_top] = rp;
5748 if (i == newindx && !ins_new) {
5749 /* Insert the original entry that caused the split. */
5750 rkey.mv_data = newkey->mv_data;
5751 rkey.mv_size = newkey->mv_size;
5760 /* Update page and index for the new key. */
5762 mc->mc_pg[mc->mc_top] = copy;
5763 mc->mc_ki[mc->mc_top] = j;
5764 } else if (i == nkeys) {
5767 node = NODEPTR(mp, i);
5768 rkey.mv_data = NODEKEY(node);
5769 rkey.mv_size = node->mn_ksize;
5771 xdata.mv_data = NODEDATA(node);
5772 xdata.mv_size = NODEDSZ(node);
5775 pgno = NODEPGNO(node);
5776 flags = node->mn_flags;
5781 if (!IS_LEAF(mp) && j == 0) {
5782 /* First branch index doesn't need key data. */
5786 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5789 nkeys = NUMKEYS(copy);
5790 for (i=0; i<nkeys; i++)
5791 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5792 mp->mp_lower = copy->mp_lower;
5793 mp->mp_upper = copy->mp_upper;
5794 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5795 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5797 /* reset back to original page */
5798 if (!newindx || (newindx < split_indx)) {
5799 mc->mc_pg[mc->mc_top] = mp;
5800 if (nflags & MDB_RESERVE) {
5801 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5802 if (!(node->mn_flags & F_BIGDATA))
5803 newdata->mv_data = NODEDATA(node);
5807 /* return tmp page to freelist */
5808 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5809 VGMEMP_FREE(mc->mc_txn->mt_env, copy);
5810 mc->mc_txn->mt_env->me_dpages = copy;
5813 /* Adjust other cursors pointing to mp */
5814 MDB_cursor *m2, *m3;
5815 MDB_dbi dbi = mc->mc_dbi;
5817 if (mc->mc_flags & C_SUB)
5820 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5821 if (m2 == mc) continue;
5822 if (mc->mc_flags & C_SUB)
5823 m3 = &m2->mc_xcursor->mx_cursor;
5826 if (!(m3->mc_flags & C_INITIALIZED))
5831 for (k=m3->mc_top; k>=0; k--) {
5832 m3->mc_ki[k+1] = m3->mc_ki[k];
5833 m3->mc_pg[k+1] = m3->mc_pg[k];
5835 m3->mc_ki[0] = mc->mc_ki[0];
5836 m3->mc_pg[0] = mc->mc_pg[0];
5840 if (m3->mc_pg[mc->mc_top] == mp) {
5841 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5842 m3->mc_pg[m3->mc_top] = rp;
5843 m3->mc_ki[m3->mc_top] -= split_indx;
5852 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5853 MDB_val *key, MDB_val *data, unsigned int flags)
5858 assert(key != NULL);
5859 assert(data != NULL);
5861 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5864 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5868 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5872 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5875 mdb_cursor_init(&mc, txn, dbi, &mx);
5876 return mdb_cursor_put(&mc, key, data, flags);
5879 /** Only a subset of the @ref mdb_env flags can be changed
5880 * at runtime. Changing other flags requires closing the environment
5881 * and re-opening it with the new flags.
5883 #define CHANGEABLE (MDB_NOSYNC)
5885 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5887 if ((flag & CHANGEABLE) != flag)
5890 env->me_flags |= flag;
5892 env->me_flags &= ~flag;
5897 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5902 *arg = env->me_flags;
5907 mdb_env_get_path(MDB_env *env, const char **arg)
5912 *arg = env->me_path;
5916 /** Common code for #mdb_stat() and #mdb_env_stat().
5917 * @param[in] env the environment to operate in.
5918 * @param[in] db the #MDB_db record containing the stats to return.
5919 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5920 * @return 0, this function always succeeds.
5923 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5925 arg->ms_psize = env->me_psize;
5926 arg->ms_depth = db->md_depth;
5927 arg->ms_branch_pages = db->md_branch_pages;
5928 arg->ms_leaf_pages = db->md_leaf_pages;
5929 arg->ms_overflow_pages = db->md_overflow_pages;
5930 arg->ms_entries = db->md_entries;
5935 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5939 if (env == NULL || arg == NULL)
5942 mdb_env_read_meta(env, &toggle);
5944 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5947 /** Set the default comparison functions for a database.
5948 * Called immediately after a database is opened to set the defaults.
5949 * The user can then override them with #mdb_set_compare() or
5950 * #mdb_set_dupsort().
5951 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5952 * @param[in] dbi A database handle returned by #mdb_open()
5955 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5957 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5958 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5959 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5960 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5962 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5964 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5965 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5966 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5967 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5969 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5970 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5971 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5973 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5976 txn->mt_dbxs[dbi].md_dcmp = NULL;
5980 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5985 int rc, dbflag, exact;
5988 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5989 mdb_default_cmp(txn, FREE_DBI);
5995 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5996 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5997 mdb_default_cmp(txn, MAIN_DBI);
6001 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6002 mdb_default_cmp(txn, MAIN_DBI);
6005 /* Is the DB already open? */
6007 for (i=2; i<txn->mt_numdbs; i++) {
6008 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6009 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6015 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6018 /* Find the DB info */
6022 key.mv_data = (void *)name;
6023 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6024 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6025 if (rc == MDB_SUCCESS) {
6026 /* make sure this is actually a DB */
6027 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6028 if (!(node->mn_flags & F_SUBDATA))
6030 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6031 /* Create if requested */
6033 data.mv_size = sizeof(MDB_db);
6034 data.mv_data = &dummy;
6035 memset(&dummy, 0, sizeof(dummy));
6036 dummy.md_root = P_INVALID;
6037 dummy.md_flags = flags & 0xffff;
6038 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6042 /* OK, got info, add to table */
6043 if (rc == MDB_SUCCESS) {
6044 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
6045 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
6046 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
6047 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
6048 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
6049 *dbi = txn->mt_numdbs;
6050 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6051 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6052 mdb_default_cmp(txn, txn->mt_numdbs);
6059 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6061 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6064 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6067 void mdb_close(MDB_env *env, MDB_dbi dbi)
6070 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6072 ptr = env->me_dbxs[dbi].md_name.mv_data;
6073 env->me_dbxs[dbi].md_name.mv_data = NULL;
6074 env->me_dbxs[dbi].md_name.mv_size = 0;
6078 /** Add all the DB's pages to the free list.
6079 * @param[in] mc Cursor on the DB to free.
6080 * @param[in] subs non-Zero to check for sub-DBs in this DB.
6081 * @return 0 on success, non-zero on failure.
6084 mdb_drop0(MDB_cursor *mc, int subs)
6088 rc = mdb_page_search(mc, NULL, 0);
6089 if (rc == MDB_SUCCESS) {
6094 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6095 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6098 mdb_cursor_copy(mc, &mx);
6099 while (mc->mc_snum > 0) {
6100 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6101 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6102 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6103 if (ni->mn_flags & F_SUBDATA) {
6104 mdb_xcursor_init1(mc, ni);
6105 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6111 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6113 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6116 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6121 rc = mdb_cursor_sibling(mc, 1);
6123 /* no more siblings, go back to beginning
6124 * of previous level. (stack was already popped
6125 * by mdb_cursor_sibling)
6127 for (i=1; i<mc->mc_top; i++)
6128 mc->mc_pg[i] = mx.mc_pg[i];
6132 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6133 mc->mc_db->md_root);
6138 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6143 if (!txn || !dbi || dbi >= txn->mt_numdbs)
6146 rc = mdb_cursor_open(txn, dbi, &mc);
6150 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6154 /* Can't delete the main DB */
6155 if (del && dbi > MAIN_DBI) {
6156 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6158 mdb_close(txn->mt_env, dbi);
6160 txn->mt_dbflags[dbi] |= DB_DIRTY;
6161 txn->mt_dbs[dbi].md_depth = 0;
6162 txn->mt_dbs[dbi].md_branch_pages = 0;
6163 txn->mt_dbs[dbi].md_leaf_pages = 0;
6164 txn->mt_dbs[dbi].md_overflow_pages = 0;
6165 txn->mt_dbs[dbi].md_entries = 0;
6166 txn->mt_dbs[dbi].md_root = P_INVALID;
6169 mdb_cursor_close(mc);
6173 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6175 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6178 txn->mt_dbxs[dbi].md_cmp = cmp;
6182 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6184 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6187 txn->mt_dbxs[dbi].md_dcmp = cmp;
6191 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6193 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6196 txn->mt_dbxs[dbi].md_rel = rel;
6200 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6202 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6205 txn->mt_dbxs[dbi].md_relctx = ctx;