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 /** Count all the pages in each DB and in the freelist
1113 * and make sure it matches the actual number of pages
1116 static void mdb_audit(MDB_txn *txn)
1121 ID freecount, count;
1124 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1125 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1126 freecount += *(ID *)data.mv_data;
1127 freecount += txn->mt_dbs[0].md_branch_pages + txn->mt_dbs[0].md_leaf_pages +
1128 txn->mt_dbs[0].md_overflow_pages;
1131 for (i = 0; i<txn->mt_numdbs; i++) {
1132 count += txn->mt_dbs[i].md_branch_pages +
1133 txn->mt_dbs[i].md_leaf_pages +
1134 txn->mt_dbs[i].md_overflow_pages;
1135 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1137 mdb_cursor_init(&mc, txn, i, &mx);
1138 mdb_page_search(&mc, NULL, 0);
1142 mp = mc.mc_pg[mc.mc_top];
1143 for (j=0; j<NUMKEYS(mp); j++) {
1144 MDB_node *leaf = NODEPTR(mp, j);
1145 if (leaf->mn_flags & F_SUBDATA) {
1147 memcpy(&db, NODEDATA(leaf), sizeof(db));
1148 count += db.md_branch_pages + db.md_leaf_pages +
1149 db.md_overflow_pages;
1153 while (mdb_cursor_sibling(&mc, 1) == 0);
1156 assert(freecount + count + 2 >= txn->mt_next_pgno - 1);
1161 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1163 return txn->mt_dbxs[dbi].md_cmp(a, b);
1167 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1169 if (txn->mt_dbxs[dbi].md_dcmp)
1170 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1172 return EINVAL; /* too bad you can't distinguish this from a valid result */
1175 /** Allocate a single page.
1176 * Re-use old malloc'd pages first, otherwise just malloc.
1179 mdb_page_malloc(MDB_cursor *mc) {
1181 size_t sz = mc->mc_txn->mt_env->me_psize;
1182 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1183 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1184 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1185 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1186 } else if ((ret = malloc(sz)) != NULL) {
1187 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1192 /** Allocate pages for writing.
1193 * If there are free pages available from older transactions, they
1194 * will be re-used first. Otherwise a new page will be allocated.
1195 * @param[in] mc cursor A cursor handle identifying the transaction and
1196 * database for which we are allocating.
1197 * @param[in] num the number of pages to allocate.
1198 * @return Address of the allocated page(s). Requests for multiple pages
1199 * will always be satisfied by a single contiguous chunk of memory.
1202 mdb_page_alloc(MDB_cursor *mc, int num)
1204 MDB_txn *txn = mc->mc_txn;
1206 pgno_t pgno = P_INVALID;
1209 if (txn->mt_txnid > 2) {
1211 if (!txn->mt_env->me_pghead &&
1212 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1213 /* See if there's anything in the free DB */
1217 txnid_t *kptr, oldest, last;
1219 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1220 if (!txn->mt_env->me_pgfirst) {
1221 mdb_page_search(&m2, NULL, 0);
1222 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1223 kptr = (txnid_t *)NODEKEY(leaf);
1228 last = txn->mt_env->me_pglast + 1;
1230 key.mv_data = &last;
1231 key.mv_size = sizeof(last);
1232 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1235 last = *(txnid_t *)key.mv_data;
1240 oldest = txn->mt_txnid - 1;
1241 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1242 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1243 if (mr && mr < oldest)
1248 if (oldest > last) {
1249 /* It's usable, grab it.
1254 if (!txn->mt_env->me_pgfirst) {
1255 mdb_node_read(txn, leaf, &data);
1257 idl = (ID *) data.mv_data;
1258 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1259 mop->mo_next = txn->mt_env->me_pghead;
1260 mop->mo_txnid = last;
1261 txn->mt_env->me_pglast = last;
1262 if (!txn->mt_env->me_pgfirst)
1263 txn->mt_env->me_pgfirst = last;
1264 txn->mt_env->me_pghead = mop;
1265 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1270 DPRINTF("IDL read txn %zu root %zu num %zu",
1271 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1272 for (i=0; i<idl[0]; i++) {
1273 DPRINTF("IDL %zu", idl[i+1]);
1280 if (txn->mt_env->me_pghead) {
1281 MDB_oldpages *mop = txn->mt_env->me_pghead;
1283 /* FIXME: For now, always use fresh pages. We
1284 * really ought to search the free list for a
1289 /* peel pages off tail, so we only have to truncate the list */
1290 pgno = MDB_IDL_LAST(mop->mo_pages);
1291 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1293 if (mop->mo_pages[2] > mop->mo_pages[1])
1294 mop->mo_pages[0] = 0;
1298 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1299 txn->mt_env->me_pghead = mop->mo_next;
1306 if (pgno == P_INVALID) {
1307 /* DB size is maxed out */
1308 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1309 DPUTS("DB size maxed out");
1313 if (txn->mt_env->me_dpages && num == 1) {
1314 np = txn->mt_env->me_dpages;
1315 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1316 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1317 txn->mt_env->me_dpages = np->mp_next;
1319 size_t sz = txn->mt_env->me_psize * num;
1320 if ((np = malloc(sz)) == NULL)
1322 VGMEMP_ALLOC(txn->mt_env, np, sz);
1324 if (pgno == P_INVALID) {
1325 np->mp_pgno = txn->mt_next_pgno;
1326 txn->mt_next_pgno += num;
1330 mid.mid = np->mp_pgno;
1332 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1337 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1338 * @param[in] mc cursor pointing to the page to be touched
1339 * @return 0 on success, non-zero on failure.
1342 mdb_page_touch(MDB_cursor *mc)
1344 MDB_page *mp = mc->mc_pg[mc->mc_top];
1347 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1349 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1351 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1352 assert(mp->mp_pgno != np->mp_pgno);
1353 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1355 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1358 mp->mp_flags |= P_DIRTY;
1361 /* Adjust other cursors pointing to mp */
1362 if (mc->mc_flags & C_SUB) {
1363 MDB_cursor *m2, *m3;
1364 MDB_dbi dbi = mc->mc_dbi-1;
1366 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1367 if (m2 == mc) continue;
1368 m3 = &m2->mc_xcursor->mx_cursor;
1369 if (m3->mc_snum < mc->mc_snum) continue;
1370 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1371 m3->mc_pg[mc->mc_top] = mp;
1377 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1378 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1379 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1380 m2->mc_pg[mc->mc_top] = mp;
1384 mc->mc_pg[mc->mc_top] = mp;
1385 /** If this page has a parent, update the parent to point to
1389 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1391 mc->mc_db->md_root = mp->mp_pgno;
1392 } else if (mc->mc_txn->mt_parent) {
1395 /* If txn has a parent, make sure the page is in our
1398 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1399 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1400 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1401 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1402 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1403 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1404 mc->mc_pg[mc->mc_top] = mp;
1410 np = mdb_page_malloc(mc);
1411 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1412 mid.mid = np->mp_pgno;
1414 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1422 mdb_env_sync(MDB_env *env, int force)
1425 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1426 if (MDB_FDATASYNC(env->me_fd))
1432 /** Make shadow copies of all of parent txn's cursors */
1434 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1436 MDB_cursor *mc, *m2;
1437 unsigned int i, j, size;
1439 for (i=0;i<src->mt_numdbs; i++) {
1440 if (src->mt_cursors[i]) {
1441 size = sizeof(MDB_cursor);
1442 if (src->mt_cursors[i]->mc_xcursor)
1443 size += sizeof(MDB_xcursor);
1444 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1451 mc->mc_db = &dst->mt_dbs[i];
1452 mc->mc_dbx = m2->mc_dbx;
1453 mc->mc_dbflag = &dst->mt_dbflags[i];
1454 mc->mc_snum = m2->mc_snum;
1455 mc->mc_top = m2->mc_top;
1456 mc->mc_flags = m2->mc_flags | C_SHADOW;
1457 for (j=0; j<mc->mc_snum; j++) {
1458 mc->mc_pg[j] = m2->mc_pg[j];
1459 mc->mc_ki[j] = m2->mc_ki[j];
1461 if (m2->mc_xcursor) {
1462 MDB_xcursor *mx, *mx2;
1463 mx = (MDB_xcursor *)(mc+1);
1464 mc->mc_xcursor = mx;
1465 mx2 = m2->mc_xcursor;
1466 mx->mx_db = mx2->mx_db;
1467 mx->mx_dbx = mx2->mx_dbx;
1468 mx->mx_dbflag = mx2->mx_dbflag;
1469 mx->mx_cursor.mc_txn = dst;
1470 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1471 mx->mx_cursor.mc_db = &mx->mx_db;
1472 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1473 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1474 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1475 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1476 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1477 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1478 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1479 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1482 mc->mc_xcursor = NULL;
1484 mc->mc_next = dst->mt_cursors[i];
1485 dst->mt_cursors[i] = mc;
1492 /** Merge shadow cursors back into parent's */
1494 mdb_cursor_merge(MDB_txn *txn)
1497 for (i=0; i<txn->mt_numdbs; i++) {
1498 if (txn->mt_cursors[i]) {
1500 while ((mc = txn->mt_cursors[i])) {
1501 txn->mt_cursors[i] = mc->mc_next;
1502 if (mc->mc_flags & C_SHADOW) {
1503 MDB_cursor *m2 = mc->mc_orig;
1505 m2->mc_snum = mc->mc_snum;
1506 m2->mc_top = mc->mc_top;
1507 for (j=0; j<mc->mc_snum; j++) {
1508 m2->mc_pg[j] = mc->mc_pg[j];
1509 m2->mc_ki[j] = mc->mc_ki[j];
1512 if (mc->mc_flags & C_ALLOCD)
1520 mdb_txn_reset0(MDB_txn *txn);
1522 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1523 * @param[in] txn the transaction handle to initialize
1524 * @return 0 on success, non-zero on failure. This can only
1525 * fail for read-only transactions, and then only if the
1526 * reader table is full.
1529 mdb_txn_renew0(MDB_txn *txn)
1531 MDB_env *env = txn->mt_env;
1534 if (txn->mt_flags & MDB_TXN_RDONLY) {
1535 MDB_reader *r = pthread_getspecific(env->me_txkey);
1538 pid_t pid = getpid();
1539 pthread_t tid = pthread_self();
1542 for (i=0; i<env->me_txns->mti_numreaders; i++)
1543 if (env->me_txns->mti_readers[i].mr_pid == 0)
1545 if (i == env->me_maxreaders) {
1546 UNLOCK_MUTEX_R(env);
1549 env->me_txns->mti_readers[i].mr_pid = pid;
1550 env->me_txns->mti_readers[i].mr_tid = tid;
1551 if (i >= env->me_txns->mti_numreaders)
1552 env->me_txns->mti_numreaders = i+1;
1553 UNLOCK_MUTEX_R(env);
1554 r = &env->me_txns->mti_readers[i];
1555 pthread_setspecific(env->me_txkey, r);
1557 txn->mt_toggle = env->me_txns->mti_me_toggle;
1558 txn->mt_txnid = env->me_txns->mti_txnid;
1559 /* This happens if a different process was the
1560 * last writer to the DB.
1562 if (env->me_wtxnid < txn->mt_txnid)
1563 mt_dbflag = DB_STALE;
1564 r->mr_txnid = txn->mt_txnid;
1565 txn->mt_u.reader = r;
1569 txn->mt_txnid = env->me_txns->mti_txnid;
1570 if (env->me_wtxnid < txn->mt_txnid)
1571 mt_dbflag = DB_STALE;
1573 txn->mt_toggle = env->me_txns->mti_me_toggle;
1574 txn->mt_u.dirty_list = env->me_dirty_list;
1575 txn->mt_u.dirty_list[0].mid = 0;
1576 txn->mt_free_pgs = env->me_free_pgs;
1577 txn->mt_free_pgs[0] = 0;
1578 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1582 /* Copy the DB arrays */
1583 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1584 txn->mt_numdbs = env->me_numdbs;
1585 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1586 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1587 if (txn->mt_numdbs > 2)
1588 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1589 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1590 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1592 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1598 mdb_txn_renew(MDB_txn *txn)
1605 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1606 DPUTS("environment had fatal error, must shutdown!");
1610 rc = mdb_txn_renew0(txn);
1611 if (rc == MDB_SUCCESS) {
1612 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1613 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1614 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1620 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1625 if (env->me_flags & MDB_FATAL_ERROR) {
1626 DPUTS("environment had fatal error, must shutdown!");
1630 /* parent already has an active child txn */
1631 if (parent->mt_child) {
1635 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1636 if (!(flags & MDB_RDONLY))
1637 size += env->me_maxdbs * sizeof(MDB_cursor *);
1639 if ((txn = calloc(1, size)) == NULL) {
1640 DPRINTF("calloc: %s", strerror(ErrCode()));
1643 txn->mt_dbs = (MDB_db *)(txn+1);
1644 if (flags & MDB_RDONLY) {
1645 txn->mt_flags |= MDB_TXN_RDONLY;
1646 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1648 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1649 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1654 txn->mt_free_pgs = mdb_midl_alloc();
1655 if (!txn->mt_free_pgs) {
1659 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1660 if (!txn->mt_u.dirty_list) {
1661 free(txn->mt_free_pgs);
1665 txn->mt_txnid = parent->mt_txnid;
1666 txn->mt_toggle = parent->mt_toggle;
1667 txn->mt_u.dirty_list[0].mid = 0;
1668 txn->mt_free_pgs[0] = 0;
1669 txn->mt_next_pgno = parent->mt_next_pgno;
1670 parent->mt_child = txn;
1671 txn->mt_parent = parent;
1672 txn->mt_numdbs = parent->mt_numdbs;
1673 txn->mt_dbxs = parent->mt_dbxs;
1674 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1675 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1676 mdb_cursor_shadow(parent, txn);
1679 rc = mdb_txn_renew0(txn);
1685 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1686 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1687 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1693 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1694 * @param[in] txn the transaction handle to reset
1697 mdb_txn_reset0(MDB_txn *txn)
1699 MDB_env *env = txn->mt_env;
1701 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1702 txn->mt_u.reader->mr_txnid = 0;
1708 /* close(free) all cursors */
1709 for (i=0; i<txn->mt_numdbs; i++) {
1710 if (txn->mt_cursors[i]) {
1712 while ((mc = txn->mt_cursors[i])) {
1713 txn->mt_cursors[i] = mc->mc_next;
1714 if (mc->mc_flags & C_ALLOCD)
1720 /* return all dirty pages to dpage list */
1721 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1722 dp = txn->mt_u.dirty_list[i].mptr;
1723 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1724 dp->mp_next = txn->mt_env->me_dpages;
1725 VGMEMP_FREE(txn->mt_env, dp);
1726 txn->mt_env->me_dpages = dp;
1728 /* large pages just get freed directly */
1729 VGMEMP_FREE(txn->mt_env, dp);
1734 if (txn->mt_parent) {
1735 txn->mt_parent->mt_child = NULL;
1736 free(txn->mt_free_pgs);
1737 free(txn->mt_u.dirty_list);
1740 if (mdb_midl_shrink(&txn->mt_free_pgs))
1741 env->me_free_pgs = txn->mt_free_pgs;
1744 while ((mop = txn->mt_env->me_pghead)) {
1745 txn->mt_env->me_pghead = mop->mo_next;
1748 txn->mt_env->me_pgfirst = 0;
1749 txn->mt_env->me_pglast = 0;
1752 /* The writer mutex was locked in mdb_txn_begin. */
1753 UNLOCK_MUTEX_W(env);
1758 mdb_txn_reset(MDB_txn *txn)
1763 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1764 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1765 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1767 mdb_txn_reset0(txn);
1771 mdb_txn_abort(MDB_txn *txn)
1776 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1777 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1778 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1781 mdb_txn_abort(txn->mt_child);
1783 mdb_txn_reset0(txn);
1788 mdb_txn_commit(MDB_txn *txn)
1796 pgno_t next, freecnt;
1799 assert(txn != NULL);
1800 assert(txn->mt_env != NULL);
1802 if (txn->mt_child) {
1803 mdb_txn_commit(txn->mt_child);
1804 txn->mt_child = NULL;
1809 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1810 if (txn->mt_numdbs > env->me_numdbs) {
1811 /* update the DB tables */
1812 int toggle = !env->me_db_toggle;
1816 ip = &env->me_dbs[toggle][env->me_numdbs];
1817 jp = &txn->mt_dbs[env->me_numdbs];
1818 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1819 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1823 env->me_db_toggle = toggle;
1824 env->me_numdbs = txn->mt_numdbs;
1825 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1831 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1832 DPUTS("error flag is set, can't commit");
1834 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1839 /* Merge (and close) our cursors with parent's */
1840 mdb_cursor_merge(txn);
1842 if (txn->mt_parent) {
1848 /* Update parent's DB table */
1849 ip = &txn->mt_parent->mt_dbs[2];
1850 jp = &txn->mt_dbs[2];
1851 for (i = 2; i < txn->mt_numdbs; i++) {
1852 if (ip->md_root != jp->md_root)
1856 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1858 /* Append our free list to parent's */
1859 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1861 mdb_midl_free(txn->mt_free_pgs);
1863 /* Merge our dirty list with parent's */
1864 dst = txn->mt_parent->mt_u.dirty_list;
1865 src = txn->mt_u.dirty_list;
1866 x = mdb_mid2l_search(dst, src[1].mid);
1867 for (y=1; y<=src[0].mid; y++) {
1868 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1872 dst[x].mptr = src[y].mptr;
1875 for (; y<=src[0].mid; y++) {
1876 if (++x >= MDB_IDL_UM_MAX) {
1883 free(txn->mt_u.dirty_list);
1884 txn->mt_parent->mt_child = NULL;
1889 if (txn != env->me_txn) {
1890 DPUTS("attempt to commit unknown transaction");
1895 if (!txn->mt_u.dirty_list[0].mid)
1898 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1899 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1901 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1903 /* should only be one record now */
1904 if (env->me_pghead) {
1905 /* make sure first page of freeDB is touched and on freelist */
1906 mdb_page_search(&mc, NULL, 1);
1909 /* Delete IDLs we used from the free list */
1910 if (env->me_pgfirst) {
1915 key.mv_size = sizeof(cur);
1916 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1919 mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1920 mdb_cursor_del(&mc, 0);
1922 env->me_pgfirst = 0;
1926 /* save to free list */
1927 freecnt = txn->mt_free_pgs[0];
1928 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1931 /* make sure last page of freeDB is touched and on freelist */
1932 key.mv_size = MAXKEYSIZE+1;
1934 mdb_page_search(&mc, &key, 1);
1936 mdb_midl_sort(txn->mt_free_pgs);
1940 ID *idl = txn->mt_free_pgs;
1941 DPRINTF("IDL write txn %zu root %zu num %zu",
1942 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1943 for (i=0; i<idl[0]; i++) {
1944 DPRINTF("IDL %zu", idl[i+1]);
1948 /* write to last page of freeDB */
1949 key.mv_size = sizeof(pgno_t);
1950 key.mv_data = &txn->mt_txnid;
1951 data.mv_data = txn->mt_free_pgs;
1952 /* The free list can still grow during this call,
1953 * despite the pre-emptive touches above. So check
1954 * and make sure the entire thing got written.
1957 freecnt = txn->mt_free_pgs[0];
1958 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1959 rc = mdb_cursor_put(&mc, &key, &data, 0);
1964 } while (freecnt != txn->mt_free_pgs[0]);
1965 if (mdb_midl_shrink(&txn->mt_free_pgs))
1966 env->me_free_pgs = txn->mt_free_pgs;
1968 /* should only be one record now */
1970 if (env->me_pghead) {
1976 mop = env->me_pghead;
1978 key.mv_size = sizeof(id);
1980 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1981 data.mv_data = mop->mo_pages;
1982 orig = mop->mo_pages[0];
1983 mdb_cursor_put(&mc, &key, &data, 0);
1984 if (mop == env->me_pghead) {
1985 /* could have been used again here */
1986 if (mop->mo_pages[0] != orig) {
1987 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1988 data.mv_data = mop->mo_pages;
1990 mdb_cursor_put(&mc, &key, &data, 0);
1992 env->me_pghead = NULL;
1995 /* was completely used up */
1996 mdb_cursor_del(&mc, 0);
2000 env->me_pgfirst = 0;
2004 /* Update DB root pointers. Their pages have already been
2005 * touched so this is all in-place and cannot fail.
2010 data.mv_size = sizeof(MDB_db);
2012 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2013 for (i = 2; i < txn->mt_numdbs; i++) {
2014 if (txn->mt_dbflags[i] & DB_DIRTY) {
2015 data.mv_data = &txn->mt_dbs[i];
2016 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2024 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2030 /* Windows actually supports scatter/gather I/O, but only on
2031 * unbuffered file handles. Since we're relying on the OS page
2032 * cache for all our data, that's self-defeating. So we just
2033 * write pages one at a time. We use the ov structure to set
2034 * the write offset, to at least save the overhead of a Seek
2038 memset(&ov, 0, sizeof(ov));
2039 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2041 dp = txn->mt_u.dirty_list[i].mptr;
2042 DPRINTF("committing page %zu", dp->mp_pgno);
2043 size = dp->mp_pgno * env->me_psize;
2044 ov.Offset = size & 0xffffffff;
2045 ov.OffsetHigh = size >> 16;
2046 ov.OffsetHigh >>= 16;
2047 /* clear dirty flag */
2048 dp->mp_flags &= ~P_DIRTY;
2049 wsize = env->me_psize;
2050 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2051 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2054 DPRINTF("WriteFile: %d", n);
2061 struct iovec iov[MDB_COMMIT_PAGES];
2065 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2066 dp = txn->mt_u.dirty_list[i].mptr;
2067 if (dp->mp_pgno != next) {
2069 rc = writev(env->me_fd, iov, n);
2073 DPUTS("short write, filesystem full?");
2075 DPRINTF("writev: %s", strerror(n));
2082 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2085 DPRINTF("committing page %zu", dp->mp_pgno);
2086 iov[n].iov_len = env->me_psize;
2087 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2088 iov[n].iov_base = (char *)dp;
2089 size += iov[n].iov_len;
2090 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2091 /* clear dirty flag */
2092 dp->mp_flags &= ~P_DIRTY;
2093 if (++n >= MDB_COMMIT_PAGES) {
2103 rc = writev(env->me_fd, iov, n);
2107 DPUTS("short write, filesystem full?");
2109 DPRINTF("writev: %s", strerror(n));
2116 /* Drop the dirty pages.
2118 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2119 dp = txn->mt_u.dirty_list[i].mptr;
2120 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2121 dp->mp_next = txn->mt_env->me_dpages;
2122 VGMEMP_FREE(txn->mt_env, dp);
2123 txn->mt_env->me_dpages = dp;
2125 VGMEMP_FREE(txn->mt_env, dp);
2128 txn->mt_u.dirty_list[i].mid = 0;
2130 txn->mt_u.dirty_list[0].mid = 0;
2132 if ((n = mdb_env_sync(env, 0)) != 0 ||
2133 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2137 env->me_wtxnid = txn->mt_txnid;
2141 /* update the DB tables */
2143 int toggle = !env->me_db_toggle;
2147 ip = &env->me_dbs[toggle][2];
2148 jp = &txn->mt_dbs[2];
2149 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
2150 for (i = 2; i < txn->mt_numdbs; i++) {
2151 if (ip->md_root != jp->md_root)
2156 env->me_db_toggle = toggle;
2157 env->me_numdbs = txn->mt_numdbs;
2158 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
2161 UNLOCK_MUTEX_W(env);
2167 /** Read the environment parameters of a DB environment before
2168 * mapping it into memory.
2169 * @param[in] env the environment handle
2170 * @param[out] meta address of where to store the meta information
2171 * @return 0 on success, non-zero on failure.
2174 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2181 /* We don't know the page size yet, so use a minimum value.
2185 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2187 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2192 else if (rc != MDB_PAGESIZE) {
2196 DPRINTF("read: %s", strerror(err));
2200 p = (MDB_page *)&pbuf;
2202 if (!F_ISSET(p->mp_flags, P_META)) {
2203 DPRINTF("page %zu not a meta page", p->mp_pgno);
2208 if (m->mm_magic != MDB_MAGIC) {
2209 DPUTS("meta has invalid magic");
2213 if (m->mm_version != MDB_VERSION) {
2214 DPRINTF("database is version %u, expected version %u",
2215 m->mm_version, MDB_VERSION);
2216 return MDB_VERSION_MISMATCH;
2219 memcpy(meta, m, sizeof(*m));
2223 /** Write the environment parameters of a freshly created DB environment.
2224 * @param[in] env the environment handle
2225 * @param[out] meta address of where to store the meta information
2226 * @return 0 on success, non-zero on failure.
2229 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2236 DPUTS("writing new meta page");
2238 GET_PAGESIZE(psize);
2240 meta->mm_magic = MDB_MAGIC;
2241 meta->mm_version = MDB_VERSION;
2242 meta->mm_psize = psize;
2243 meta->mm_last_pg = 1;
2244 meta->mm_flags = env->me_flags & 0xffff;
2245 meta->mm_flags |= MDB_INTEGERKEY;
2246 meta->mm_dbs[0].md_root = P_INVALID;
2247 meta->mm_dbs[1].md_root = P_INVALID;
2249 p = calloc(2, psize);
2251 p->mp_flags = P_META;
2254 memcpy(m, meta, sizeof(*meta));
2256 q = (MDB_page *)((char *)p + psize);
2259 q->mp_flags = P_META;
2262 memcpy(m, meta, sizeof(*meta));
2267 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2268 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2271 rc = write(env->me_fd, p, psize * 2);
2272 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2278 /** Update the environment info to commit a transaction.
2279 * @param[in] txn the transaction that's being committed
2280 * @return 0 on success, non-zero on failure.
2283 mdb_env_write_meta(MDB_txn *txn)
2286 MDB_meta meta, metab;
2288 int rc, len, toggle;
2294 assert(txn != NULL);
2295 assert(txn->mt_env != NULL);
2297 toggle = !txn->mt_toggle;
2298 DPRINTF("writing meta page %d for root page %zu",
2299 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2303 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2304 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2306 ptr = (char *)&meta;
2307 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2308 len = sizeof(MDB_meta) - off;
2311 meta.mm_dbs[0] = txn->mt_dbs[0];
2312 meta.mm_dbs[1] = txn->mt_dbs[1];
2313 meta.mm_last_pg = txn->mt_next_pgno - 1;
2314 meta.mm_txnid = txn->mt_txnid;
2317 off += env->me_psize;
2320 /* Write to the SYNC fd */
2323 memset(&ov, 0, sizeof(ov));
2325 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2328 rc = pwrite(env->me_mfd, ptr, len, off);
2333 DPUTS("write failed, disk error?");
2334 /* On a failure, the pagecache still contains the new data.
2335 * Write some old data back, to prevent it from being used.
2336 * Use the non-SYNC fd; we know it will fail anyway.
2338 meta.mm_last_pg = metab.mm_last_pg;
2339 meta.mm_txnid = metab.mm_txnid;
2341 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2343 r2 = pwrite(env->me_fd, ptr, len, off);
2345 env->me_flags |= MDB_FATAL_ERROR;
2348 /* Memory ordering issues are irrelevant; since the entire writer
2349 * is wrapped by wmutex, all of these changes will become visible
2350 * after the wmutex is unlocked. Since the DB is multi-version,
2351 * readers will get consistent data regardless of how fresh or
2352 * how stale their view of these values is.
2354 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2355 txn->mt_env->me_txns->mti_me_toggle = toggle;
2356 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2357 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2362 /** Check both meta pages to see which one is newer.
2363 * @param[in] env the environment handle
2364 * @param[out] which address of where to store the meta toggle ID
2365 * @return 0 on success, non-zero on failure.
2368 mdb_env_read_meta(MDB_env *env, int *which)
2372 assert(env != NULL);
2374 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2377 DPRINTF("Using meta page %d", toggle);
2384 mdb_env_create(MDB_env **env)
2388 e = calloc(1, sizeof(MDB_env));
2392 e->me_free_pgs = mdb_midl_alloc();
2393 if (!e->me_free_pgs) {
2397 e->me_maxreaders = DEFAULT_READERS;
2399 e->me_fd = INVALID_HANDLE_VALUE;
2400 e->me_lfd = INVALID_HANDLE_VALUE;
2401 e->me_mfd = INVALID_HANDLE_VALUE;
2402 VGMEMP_CREATE(e,0,0);
2408 mdb_env_set_mapsize(MDB_env *env, size_t size)
2412 env->me_mapsize = size;
2414 env->me_maxpg = env->me_mapsize / env->me_psize;
2419 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2423 env->me_maxdbs = dbs;
2428 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2430 if (env->me_map || readers < 1)
2432 env->me_maxreaders = readers;
2437 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2439 if (!env || !readers)
2441 *readers = env->me_maxreaders;
2445 /** Further setup required for opening an MDB environment
2448 mdb_env_open2(MDB_env *env, unsigned int flags)
2450 int i, newenv = 0, toggle;
2454 env->me_flags = flags;
2456 memset(&meta, 0, sizeof(meta));
2458 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2461 DPUTS("new mdbenv");
2465 if (!env->me_mapsize) {
2466 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2472 LONG sizelo, sizehi;
2473 sizelo = env->me_mapsize & 0xffffffff;
2474 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2476 /* Windows won't create mappings for zero length files.
2477 * Just allocate the maxsize right now.
2480 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2481 if (!SetEndOfFile(env->me_fd))
2483 SetFilePointer(env->me_fd, 0, NULL, 0);
2485 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2486 sizehi, sizelo, NULL);
2489 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2497 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2499 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2501 if (env->me_map == MAP_FAILED) {
2508 meta.mm_mapsize = env->me_mapsize;
2509 if (flags & MDB_FIXEDMAP)
2510 meta.mm_address = env->me_map;
2511 i = mdb_env_init_meta(env, &meta);
2512 if (i != MDB_SUCCESS) {
2513 munmap(env->me_map, env->me_mapsize);
2517 env->me_psize = meta.mm_psize;
2519 env->me_maxpg = env->me_mapsize / env->me_psize;
2521 p = (MDB_page *)env->me_map;
2522 env->me_metas[0] = METADATA(p);
2523 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2525 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2528 DPRINTF("opened database version %u, pagesize %u",
2529 env->me_metas[toggle]->mm_version, env->me_psize);
2530 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2531 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2532 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2533 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2534 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2535 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2541 /** Release a reader thread's slot in the reader lock table.
2542 * This function is called automatically when a thread exits.
2543 * Windows doesn't support destructor callbacks for thread-specific storage,
2544 * so this function is not compiled there.
2545 * @param[in] ptr This points to the slot in the reader lock table.
2548 mdb_env_reader_dest(void *ptr)
2550 MDB_reader *reader = ptr;
2552 reader->mr_txnid = 0;
2558 /** Downgrade the exclusive lock on the region back to shared */
2560 mdb_env_share_locks(MDB_env *env)
2564 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2566 env->me_txns->mti_me_toggle = toggle;
2567 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2572 /* First acquire a shared lock. The Unlock will
2573 * then release the existing exclusive lock.
2575 memset(&ov, 0, sizeof(ov));
2576 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2577 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2581 struct flock lock_info;
2582 /* The shared lock replaces the existing lock */
2583 memset((void *)&lock_info, 0, sizeof(lock_info));
2584 lock_info.l_type = F_RDLCK;
2585 lock_info.l_whence = SEEK_SET;
2586 lock_info.l_start = 0;
2587 lock_info.l_len = 1;
2588 fcntl(env->me_lfd, F_SETLK, &lock_info);
2592 #if defined(_WIN32) || defined(__APPLE__)
2594 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2596 * @(#) $Revision: 5.1 $
2597 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2598 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2600 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2604 * Please do not copyright this code. This code is in the public domain.
2606 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2607 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2608 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2609 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2610 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2611 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2612 * PERFORMANCE OF THIS SOFTWARE.
2615 * chongo <Landon Curt Noll> /\oo/\
2616 * http://www.isthe.com/chongo/
2618 * Share and Enjoy! :-)
2621 typedef unsigned long long mdb_hash_t;
2622 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2624 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2625 * @param[in] str string to hash
2626 * @param[in] hval initial value for hash
2627 * @return 64 bit hash
2629 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2630 * hval arg on the first call.
2633 mdb_hash_str(char *str, mdb_hash_t hval)
2635 unsigned char *s = (unsigned char *)str; /* unsigned string */
2637 * FNV-1a hash each octet of the string
2640 /* xor the bottom with the current octet */
2641 hval ^= (mdb_hash_t)*s++;
2643 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2644 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2645 (hval << 7) + (hval << 8) + (hval << 40);
2647 /* return our new hash value */
2651 /** Hash the string and output the hash in hex.
2652 * @param[in] str string to hash
2653 * @param[out] hexbuf an array of 17 chars to hold the hash
2656 mdb_hash_hex(char *str, char *hexbuf)
2659 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2660 for (i=0; i<8; i++) {
2661 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2667 /** Open and/or initialize the lock region for the environment.
2668 * @param[in] env The MDB environment.
2669 * @param[in] lpath The pathname of the file used for the lock region.
2670 * @param[in] mode The Unix permissions for the file, if we create it.
2671 * @param[out] excl Set to true if we got an exclusive lock on the region.
2672 * @return 0 on success, non-zero on failure.
2675 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2683 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2684 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2685 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2689 /* Try to get exclusive lock. If we succeed, then
2690 * nobody is using the lock region and we should initialize it.
2693 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2697 memset(&ov, 0, sizeof(ov));
2698 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2704 size = GetFileSize(env->me_lfd, NULL);
2706 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2710 /* Try to get exclusive lock. If we succeed, then
2711 * nobody is using the lock region and we should initialize it.
2714 struct flock lock_info;
2715 memset((void *)&lock_info, 0, sizeof(lock_info));
2716 lock_info.l_type = F_WRLCK;
2717 lock_info.l_whence = SEEK_SET;
2718 lock_info.l_start = 0;
2719 lock_info.l_len = 1;
2720 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2724 lock_info.l_type = F_RDLCK;
2725 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2732 size = lseek(env->me_lfd, 0, SEEK_END);
2734 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2735 if (size < rsize && *excl) {
2737 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2738 if (!SetEndOfFile(env->me_lfd)) {
2743 if (ftruncate(env->me_lfd, rsize) != 0) {
2750 size = rsize - sizeof(MDB_txninfo);
2751 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2756 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2762 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2764 if (!env->me_txns) {
2769 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2771 if (m == MAP_FAILED) {
2772 env->me_txns = NULL;
2782 if (!mdb_sec_inited) {
2783 InitializeSecurityDescriptor(&mdb_null_sd,
2784 SECURITY_DESCRIPTOR_REVISION);
2785 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2786 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2787 mdb_all_sa.bInheritHandle = FALSE;
2788 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2791 mdb_hash_hex(lpath, hexbuf);
2792 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2793 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2794 if (!env->me_rmutex) {
2798 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2799 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2800 if (!env->me_wmutex) {
2807 mdb_hash_hex(lpath, hexbuf);
2808 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2809 if (sem_unlink(env->me_txns->mti_rmname)) {
2811 if (rc != ENOENT && rc != EINVAL)
2814 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2815 if (!env->me_rmutex) {
2819 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2820 if (sem_unlink(env->me_txns->mti_wmname)) {
2822 if (rc != ENOENT && rc != EINVAL)
2825 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2826 if (!env->me_wmutex) {
2830 #else /* __APPLE__ */
2831 pthread_mutexattr_t mattr;
2833 pthread_mutexattr_init(&mattr);
2834 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2838 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2839 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2840 #endif /* __APPLE__ */
2842 env->me_txns->mti_version = MDB_VERSION;
2843 env->me_txns->mti_magic = MDB_MAGIC;
2844 env->me_txns->mti_txnid = 0;
2845 env->me_txns->mti_numreaders = 0;
2846 env->me_txns->mti_me_toggle = 0;
2849 if (env->me_txns->mti_magic != MDB_MAGIC) {
2850 DPUTS("lock region has invalid magic");
2854 if (env->me_txns->mti_version != MDB_VERSION) {
2855 DPRINTF("lock region is version %u, expected version %u",
2856 env->me_txns->mti_version, MDB_VERSION);
2857 rc = MDB_VERSION_MISMATCH;
2861 if (rc != EACCES && rc != EAGAIN) {
2865 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2866 if (!env->me_rmutex) {
2870 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2871 if (!env->me_wmutex) {
2877 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2878 if (!env->me_rmutex) {
2882 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2883 if (!env->me_wmutex) {
2893 env->me_lfd = INVALID_HANDLE_VALUE;
2898 /** The name of the lock file in the DB environment */
2899 #define LOCKNAME "/lock.mdb"
2900 /** The name of the data file in the DB environment */
2901 #define DATANAME "/data.mdb"
2902 /** The suffix of the lock file when no subdir is used */
2903 #define LOCKSUFF "-lock"
2906 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2908 int oflags, rc, len, excl;
2909 char *lpath, *dpath;
2912 if (flags & MDB_NOSUBDIR) {
2913 rc = len + sizeof(LOCKSUFF) + len + 1;
2915 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2920 if (flags & MDB_NOSUBDIR) {
2921 dpath = lpath + len + sizeof(LOCKSUFF);
2922 sprintf(lpath, "%s" LOCKSUFF, path);
2923 strcpy(dpath, path);
2925 dpath = lpath + len + sizeof(LOCKNAME);
2926 sprintf(lpath, "%s" LOCKNAME, path);
2927 sprintf(dpath, "%s" DATANAME, path);
2930 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2935 if (F_ISSET(flags, MDB_RDONLY)) {
2936 oflags = GENERIC_READ;
2937 len = OPEN_EXISTING;
2939 oflags = GENERIC_READ|GENERIC_WRITE;
2942 mode = FILE_ATTRIBUTE_NORMAL;
2943 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2944 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2949 if (F_ISSET(flags, MDB_RDONLY))
2952 oflags = O_RDWR | O_CREAT;
2954 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2960 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2961 /* synchronous fd for meta writes */
2963 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2964 mode |= FILE_FLAG_WRITE_THROUGH;
2965 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2966 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2971 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2972 oflags |= MDB_DSYNC;
2973 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2978 env->me_path = strdup(path);
2979 DPRINTF("opened dbenv %p", (void *) env);
2980 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2981 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2983 mdb_env_share_locks(env);
2984 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2985 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2986 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2992 if (env->me_fd != INVALID_HANDLE_VALUE) {
2994 env->me_fd = INVALID_HANDLE_VALUE;
2996 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2998 env->me_lfd = INVALID_HANDLE_VALUE;
3006 mdb_env_close(MDB_env *env)
3013 VGMEMP_DESTROY(env);
3014 while (env->me_dpages) {
3015 dp = env->me_dpages;
3016 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3017 env->me_dpages = dp->mp_next;
3021 free(env->me_dbs[1]);
3022 free(env->me_dbs[0]);
3026 LAZY_RWLOCK_DESTROY(&env->me_dblock);
3027 pthread_key_delete(env->me_txkey);
3030 munmap(env->me_map, env->me_mapsize);
3035 pid_t pid = getpid();
3037 for (i=0; i<env->me_txns->mti_numreaders; i++)
3038 if (env->me_txns->mti_readers[i].mr_pid == pid)
3039 env->me_txns->mti_readers[i].mr_pid = 0;
3040 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3043 mdb_midl_free(env->me_free_pgs);
3047 /** Compare two items pointing at aligned size_t's */
3049 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3051 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3052 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3055 /** Compare two items pointing at aligned int's */
3057 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3059 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3060 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3063 /** Compare two items pointing at ints of unknown alignment.
3064 * Nodes and keys are guaranteed to be 2-byte aligned.
3067 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3069 #if BYTE_ORDER == LITTLE_ENDIAN
3070 unsigned short *u, *c;
3073 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3074 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3077 } while(!x && u > (unsigned short *)a->mv_data);
3080 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3084 /** Compare two items lexically */
3086 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3093 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3099 diff = memcmp(a->mv_data, b->mv_data, len);
3100 return diff ? diff : len_diff<0 ? -1 : len_diff;
3103 /** Compare two items in reverse byte order */
3105 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3107 const unsigned char *p1, *p2, *p1_lim;
3111 p1_lim = (const unsigned char *)a->mv_data;
3112 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3113 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3115 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3121 while (p1 > p1_lim) {
3122 diff = *--p1 - *--p2;
3126 return len_diff<0 ? -1 : len_diff;
3129 /** Search for key within a page, using binary search.
3130 * Returns the smallest entry larger or equal to the key.
3131 * If exactp is non-null, stores whether the found entry was an exact match
3132 * in *exactp (1 or 0).
3133 * Updates the cursor index with the index of the found entry.
3134 * If no entry larger or equal to the key is found, returns NULL.
3137 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3139 unsigned int i = 0, nkeys;
3142 MDB_page *mp = mc->mc_pg[mc->mc_top];
3143 MDB_node *node = NULL;
3148 nkeys = NUMKEYS(mp);
3153 COPY_PGNO(pgno, mp->mp_pgno);
3154 DPRINTF("searching %u keys in %s %spage %zu",
3155 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3162 low = IS_LEAF(mp) ? 0 : 1;
3164 cmp = mc->mc_dbx->md_cmp;
3166 /* Branch pages have no data, so if using integer keys,
3167 * alignment is guaranteed. Use faster mdb_cmp_int.
3169 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3170 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3177 nodekey.mv_size = mc->mc_db->md_pad;
3178 node = NODEPTR(mp, 0); /* fake */
3179 while (low <= high) {
3180 i = (low + high) >> 1;
3181 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3182 rc = cmp(key, &nodekey);
3183 DPRINTF("found leaf index %u [%s], rc = %i",
3184 i, DKEY(&nodekey), rc);
3193 while (low <= high) {
3194 i = (low + high) >> 1;
3196 node = NODEPTR(mp, i);
3197 nodekey.mv_size = NODEKSZ(node);
3198 nodekey.mv_data = NODEKEY(node);
3200 rc = cmp(key, &nodekey);
3203 DPRINTF("found leaf index %u [%s], rc = %i",
3204 i, DKEY(&nodekey), rc);
3206 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3207 i, DKEY(&nodekey), NODEPGNO(node), rc);
3218 if (rc > 0) { /* Found entry is less than the key. */
3219 i++; /* Skip to get the smallest entry larger than key. */
3221 node = NODEPTR(mp, i);
3224 *exactp = (rc == 0);
3225 /* store the key index */
3226 mc->mc_ki[mc->mc_top] = i;
3228 /* There is no entry larger or equal to the key. */
3231 /* nodeptr is fake for LEAF2 */
3237 mdb_cursor_adjust(MDB_cursor *mc, func)
3241 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3242 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3249 /** Pop a page off the top of the cursor's stack. */
3251 mdb_cursor_pop(MDB_cursor *mc)
3256 top = mc->mc_pg[mc->mc_top];
3261 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3262 mc->mc_dbi, (void *) mc);
3266 /** Push a page onto the top of the cursor's stack. */
3268 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3270 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3271 mc->mc_dbi, (void *) mc);
3273 if (mc->mc_snum >= CURSOR_STACK) {
3274 assert(mc->mc_snum < CURSOR_STACK);
3278 mc->mc_top = mc->mc_snum++;
3279 mc->mc_pg[mc->mc_top] = mp;
3280 mc->mc_ki[mc->mc_top] = 0;
3285 /** Find the address of the page corresponding to a given page number.
3286 * @param[in] txn the transaction for this access.
3287 * @param[in] pgno the page number for the page to retrieve.
3288 * @param[out] ret address of a pointer where the page's address will be stored.
3289 * @return 0 on success, non-zero on failure.
3292 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3296 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3298 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3299 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3300 p = txn->mt_u.dirty_list[x].mptr;
3304 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3305 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3309 DPRINTF("page %zu not found", pgno);
3312 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3315 /** Search for the page a given key should be in.
3316 * Pushes parent pages on the cursor stack. This function continues a
3317 * search on a cursor that has already been initialized. (Usually by
3318 * #mdb_page_search() but also by #mdb_node_move().)
3319 * @param[in,out] mc the cursor for this operation.
3320 * @param[in] key the key to search for. If NULL, search for the lowest
3321 * page. (This is used by #mdb_cursor_first().)
3322 * @param[in] modify If true, visited pages are updated with new page numbers.
3323 * @return 0 on success, non-zero on failure.
3326 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3328 MDB_page *mp = mc->mc_pg[mc->mc_top];
3333 while (IS_BRANCH(mp)) {
3337 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3338 assert(NUMKEYS(mp) > 1);
3339 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3341 if (key == NULL) /* Initialize cursor to first page. */
3343 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3344 /* cursor to last page */
3348 node = mdb_node_search(mc, key, &exact);
3350 i = NUMKEYS(mp) - 1;
3352 i = mc->mc_ki[mc->mc_top];
3361 DPRINTF("following index %u for key [%s]",
3363 assert(i < NUMKEYS(mp));
3364 node = NODEPTR(mp, i);
3366 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3369 mc->mc_ki[mc->mc_top] = i;
3370 if ((rc = mdb_cursor_push(mc, mp)))
3374 if ((rc = mdb_page_touch(mc)) != 0)
3376 mp = mc->mc_pg[mc->mc_top];
3381 DPRINTF("internal error, index points to a %02X page!?",
3383 return MDB_CORRUPTED;
3386 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3387 key ? DKEY(key) : NULL);
3392 /** Search for the page a given key should be in.
3393 * Pushes parent pages on the cursor stack. This function just sets up
3394 * the search; it finds the root page for \b mc's database and sets this
3395 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3396 * called to complete the search.
3397 * @param[in,out] mc the cursor for this operation.
3398 * @param[in] key the key to search for. If NULL, search for the lowest
3399 * page. (This is used by #mdb_cursor_first().)
3400 * @param[in] modify If true, visited pages are updated with new page numbers.
3401 * @return 0 on success, non-zero on failure.
3404 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3409 /* Make sure the txn is still viable, then find the root from
3410 * the txn's db table.
3412 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3413 DPUTS("transaction has failed, must abort");
3416 /* Make sure we're using an up-to-date root */
3417 if (mc->mc_dbi > MAIN_DBI) {
3418 if ((*mc->mc_dbflag & DB_STALE) ||
3419 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3421 unsigned char dbflag = 0;
3422 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3423 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3426 if (*mc->mc_dbflag & DB_STALE) {
3429 MDB_node *leaf = mdb_node_search(&mc2,
3430 &mc->mc_dbx->md_name, &exact);
3432 return MDB_NOTFOUND;
3433 mdb_node_read(mc->mc_txn, leaf, &data);
3434 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3438 *mc->mc_dbflag = dbflag;
3441 root = mc->mc_db->md_root;
3443 if (root == P_INVALID) { /* Tree is empty. */
3444 DPUTS("tree is empty");
3445 return MDB_NOTFOUND;
3450 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3456 DPRINTF("db %u root page %zu has flags 0x%X",
3457 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3460 if ((rc = mdb_page_touch(mc)))
3464 return mdb_page_search_root(mc, key, modify);
3467 /** Return the data associated with a given node.
3468 * @param[in] txn The transaction for this operation.
3469 * @param[in] leaf The node being read.
3470 * @param[out] data Updated to point to the node's data.
3471 * @return 0 on success, non-zero on failure.
3474 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3476 MDB_page *omp; /* overflow page */
3480 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3481 data->mv_size = NODEDSZ(leaf);
3482 data->mv_data = NODEDATA(leaf);
3486 /* Read overflow data.
3488 data->mv_size = NODEDSZ(leaf);
3489 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3490 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3491 DPRINTF("read overflow page %zu failed", pgno);
3494 data->mv_data = METADATA(omp);
3500 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3501 MDB_val *key, MDB_val *data)
3510 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3512 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3515 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3519 mdb_cursor_init(&mc, txn, dbi, &mx);
3520 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3523 /** Find a sibling for a page.
3524 * Replaces the page at the top of the cursor's stack with the
3525 * specified sibling, if one exists.
3526 * @param[in] mc The cursor for this operation.
3527 * @param[in] move_right Non-zero if the right sibling is requested,
3528 * otherwise the left sibling.
3529 * @return 0 on success, non-zero on failure.
3532 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3538 if (mc->mc_snum < 2) {
3539 return MDB_NOTFOUND; /* root has no siblings */
3543 DPRINTF("parent page is page %zu, index %u",
3544 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3546 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3547 : (mc->mc_ki[mc->mc_top] == 0)) {
3548 DPRINTF("no more keys left, moving to %s sibling",
3549 move_right ? "right" : "left");
3550 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3554 mc->mc_ki[mc->mc_top]++;
3556 mc->mc_ki[mc->mc_top]--;
3557 DPRINTF("just moving to %s index key %u",
3558 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3560 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3562 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3563 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3566 mdb_cursor_push(mc, mp);
3571 /** Move the cursor to the next data item. */
3573 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3579 if (mc->mc_flags & C_EOF) {
3580 return MDB_NOTFOUND;
3583 assert(mc->mc_flags & C_INITIALIZED);
3585 mp = mc->mc_pg[mc->mc_top];
3587 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3588 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3589 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3590 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3591 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3592 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3596 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3597 if (op == MDB_NEXT_DUP)
3598 return MDB_NOTFOUND;
3602 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3604 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3605 DPUTS("=====> move to next sibling page");
3606 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3607 mc->mc_flags |= C_EOF;
3608 mc->mc_flags &= ~C_INITIALIZED;
3609 return MDB_NOTFOUND;
3611 mp = mc->mc_pg[mc->mc_top];
3612 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3614 mc->mc_ki[mc->mc_top]++;
3616 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3617 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3620 key->mv_size = mc->mc_db->md_pad;
3621 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3625 assert(IS_LEAF(mp));
3626 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3628 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3629 mdb_xcursor_init1(mc, leaf);
3632 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3635 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3636 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3637 if (rc != MDB_SUCCESS)
3642 MDB_SET_KEY(leaf, key);
3646 /** Move the cursor to the previous data item. */
3648 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3654 assert(mc->mc_flags & C_INITIALIZED);
3656 mp = mc->mc_pg[mc->mc_top];
3658 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3659 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3660 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3661 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3662 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3663 if (op != MDB_PREV || rc == MDB_SUCCESS)
3666 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3667 if (op == MDB_PREV_DUP)
3668 return MDB_NOTFOUND;
3673 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3675 if (mc->mc_ki[mc->mc_top] == 0) {
3676 DPUTS("=====> move to prev sibling page");
3677 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3678 mc->mc_flags &= ~C_INITIALIZED;
3679 return MDB_NOTFOUND;
3681 mp = mc->mc_pg[mc->mc_top];
3682 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3683 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3685 mc->mc_ki[mc->mc_top]--;
3687 mc->mc_flags &= ~C_EOF;
3689 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3690 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3693 key->mv_size = mc->mc_db->md_pad;
3694 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3698 assert(IS_LEAF(mp));
3699 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3701 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3702 mdb_xcursor_init1(mc, leaf);
3705 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3708 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3709 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3710 if (rc != MDB_SUCCESS)
3715 MDB_SET_KEY(leaf, key);
3719 /** Set the cursor on a specific data item. */
3721 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3722 MDB_cursor_op op, int *exactp)
3731 assert(key->mv_size > 0);
3733 /* See if we're already on the right page */
3734 if (mc->mc_flags & C_INITIALIZED) {
3737 mp = mc->mc_pg[mc->mc_top];
3739 mc->mc_ki[mc->mc_top] = 0;
3740 return MDB_NOTFOUND;
3742 if (mp->mp_flags & P_LEAF2) {
3743 nodekey.mv_size = mc->mc_db->md_pad;
3744 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3746 leaf = NODEPTR(mp, 0);
3747 MDB_SET_KEY(leaf, &nodekey);
3749 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3751 /* Probably happens rarely, but first node on the page
3752 * was the one we wanted.
3754 mc->mc_ki[mc->mc_top] = 0;
3755 leaf = NODEPTR(mp, 0);
3762 unsigned int nkeys = NUMKEYS(mp);
3764 if (mp->mp_flags & P_LEAF2) {
3765 nodekey.mv_data = LEAF2KEY(mp,
3766 nkeys-1, nodekey.mv_size);
3768 leaf = NODEPTR(mp, nkeys-1);
3769 MDB_SET_KEY(leaf, &nodekey);
3771 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3773 /* last node was the one we wanted */
3774 mc->mc_ki[mc->mc_top] = nkeys-1;
3775 leaf = NODEPTR(mp, nkeys-1);
3781 /* This is definitely the right page, skip search_page */
3786 /* If any parents have right-sibs, search.
3787 * Otherwise, there's nothing further.
3789 for (i=0; i<mc->mc_top; i++)
3791 NUMKEYS(mc->mc_pg[i])-1)
3793 if (i == mc->mc_top) {
3794 /* There are no other pages */
3795 mc->mc_ki[mc->mc_top] = nkeys;
3796 return MDB_NOTFOUND;
3800 /* There are no other pages */
3801 mc->mc_ki[mc->mc_top] = 0;
3802 return MDB_NOTFOUND;
3806 rc = mdb_page_search(mc, key, 0);
3807 if (rc != MDB_SUCCESS)
3810 mp = mc->mc_pg[mc->mc_top];
3811 assert(IS_LEAF(mp));
3814 leaf = mdb_node_search(mc, key, exactp);
3815 if (exactp != NULL && !*exactp) {
3816 /* MDB_SET specified and not an exact match. */
3817 return MDB_NOTFOUND;
3821 DPUTS("===> inexact leaf not found, goto sibling");
3822 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3823 return rc; /* no entries matched */
3824 mp = mc->mc_pg[mc->mc_top];
3825 assert(IS_LEAF(mp));
3826 leaf = NODEPTR(mp, 0);
3830 mc->mc_flags |= C_INITIALIZED;
3831 mc->mc_flags &= ~C_EOF;
3834 key->mv_size = mc->mc_db->md_pad;
3835 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3839 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3840 mdb_xcursor_init1(mc, leaf);
3843 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3844 if (op == MDB_SET || op == MDB_SET_RANGE) {
3845 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3848 if (op == MDB_GET_BOTH) {
3854 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3855 if (rc != MDB_SUCCESS)
3858 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3860 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3862 rc = mc->mc_dbx->md_dcmp(data, &d2);
3864 if (op == MDB_GET_BOTH || rc > 0)
3865 return MDB_NOTFOUND;
3870 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3871 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3876 /* The key already matches in all other cases */
3877 if (op == MDB_SET_RANGE)
3878 MDB_SET_KEY(leaf, key);
3879 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3884 /** Move the cursor to the first item in the database. */
3886 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3891 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3892 rc = mdb_page_search(mc, NULL, 0);
3893 if (rc != MDB_SUCCESS)
3896 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3898 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3899 mc->mc_flags |= C_INITIALIZED;
3900 mc->mc_flags &= ~C_EOF;
3902 mc->mc_ki[mc->mc_top] = 0;
3904 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3905 key->mv_size = mc->mc_db->md_pad;
3906 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3911 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3912 mdb_xcursor_init1(mc, leaf);
3913 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3918 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3919 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3923 MDB_SET_KEY(leaf, key);
3927 /** Move the cursor to the last item in the database. */
3929 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3935 lkey.mv_size = MAXKEYSIZE+1;
3936 lkey.mv_data = NULL;
3938 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3939 rc = mdb_page_search(mc, &lkey, 0);
3940 if (rc != MDB_SUCCESS)
3943 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3945 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3946 mc->mc_flags |= C_INITIALIZED;
3947 mc->mc_flags &= ~C_EOF;
3949 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3951 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3952 key->mv_size = mc->mc_db->md_pad;
3953 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3958 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3959 mdb_xcursor_init1(mc, leaf);
3960 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3965 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3966 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3971 MDB_SET_KEY(leaf, key);
3976 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3986 case MDB_GET_BOTH_RANGE:
3987 if (data == NULL || mc->mc_xcursor == NULL) {
3994 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3996 } else if (op == MDB_SET_RANGE)
3997 rc = mdb_cursor_set(mc, key, data, op, NULL);
3999 rc = mdb_cursor_set(mc, key, data, op, &exact);
4001 case MDB_GET_MULTIPLE:
4003 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4004 !(mc->mc_flags & C_INITIALIZED)) {
4009 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4010 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4013 case MDB_NEXT_MULTIPLE:
4015 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4019 if (!(mc->mc_flags & C_INITIALIZED))
4020 rc = mdb_cursor_first(mc, key, data);
4022 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4023 if (rc == MDB_SUCCESS) {
4024 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4027 mx = &mc->mc_xcursor->mx_cursor;
4028 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4030 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4031 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4039 case MDB_NEXT_NODUP:
4040 if (!(mc->mc_flags & C_INITIALIZED))
4041 rc = mdb_cursor_first(mc, key, data);
4043 rc = mdb_cursor_next(mc, key, data, op);
4047 case MDB_PREV_NODUP:
4048 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
4049 rc = mdb_cursor_last(mc, key, data);
4051 rc = mdb_cursor_prev(mc, key, data, op);
4054 rc = mdb_cursor_first(mc, key, data);
4058 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4059 !(mc->mc_flags & C_INITIALIZED) ||
4060 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4064 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4067 rc = mdb_cursor_last(mc, key, data);
4071 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4072 !(mc->mc_flags & C_INITIALIZED) ||
4073 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4077 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4080 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4088 /** Touch all the pages in the cursor stack.
4089 * Makes sure all the pages are writable, before attempting a write operation.
4090 * @param[in] mc The cursor to operate on.
4093 mdb_cursor_touch(MDB_cursor *mc)
4097 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4099 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4100 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
4103 *mc->mc_dbflag = DB_DIRTY;
4105 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4106 rc = mdb_page_touch(mc);
4110 mc->mc_top = mc->mc_snum-1;
4115 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4118 MDB_node *leaf = NULL;
4119 MDB_val xdata, *rdata, dkey;
4123 unsigned int mcount = 0;
4127 char dbuf[MAXKEYSIZE+1];
4128 unsigned int nflags;
4131 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4134 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4135 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4139 if (flags == MDB_CURRENT) {
4140 if (!(mc->mc_flags & C_INITIALIZED))
4143 } else if (mc->mc_db->md_root == P_INVALID) {
4145 /* new database, write a root leaf page */
4146 DPUTS("allocating new root leaf page");
4147 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4151 mdb_cursor_push(mc, np);
4152 mc->mc_db->md_root = np->mp_pgno;
4153 mc->mc_db->md_depth++;
4154 *mc->mc_dbflag = DB_DIRTY;
4155 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4157 np->mp_flags |= P_LEAF2;
4158 mc->mc_flags |= C_INITIALIZED;
4164 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4165 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4166 DPRINTF("duplicate key [%s]", DKEY(key));
4168 return MDB_KEYEXIST;
4170 if (rc && rc != MDB_NOTFOUND)
4174 /* Cursor is positioned, now make sure all pages are writable */
4175 rc2 = mdb_cursor_touch(mc);
4180 /* The key already exists */
4181 if (rc == MDB_SUCCESS) {
4182 /* there's only a key anyway, so this is a no-op */
4183 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4184 unsigned int ksize = mc->mc_db->md_pad;
4185 if (key->mv_size != ksize)
4187 if (flags == MDB_CURRENT) {
4188 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4189 memcpy(ptr, key->mv_data, ksize);
4194 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4197 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4198 /* Was a single item before, must convert now */
4200 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4201 /* Just overwrite the current item */
4202 if (flags == MDB_CURRENT)
4205 dkey.mv_size = NODEDSZ(leaf);
4206 dkey.mv_data = NODEDATA(leaf);
4207 #if UINT_MAX < SIZE_MAX
4208 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4209 #ifdef MISALIGNED_OK
4210 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4212 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4215 /* if data matches, ignore it */
4216 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4217 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4219 /* create a fake page for the dup items */
4220 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4221 dkey.mv_data = dbuf;
4222 fp = (MDB_page *)&pbuf;
4223 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4224 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4225 fp->mp_lower = PAGEHDRSZ;
4226 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4227 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4228 fp->mp_flags |= P_LEAF2;
4229 fp->mp_pad = data->mv_size;
4231 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4232 (dkey.mv_size & 1) + (data->mv_size & 1);
4234 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4235 mc->mc_db->md_entries--;
4238 xdata.mv_size = fp->mp_upper;
4243 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4244 /* See if we need to convert from fake page to subDB */
4246 unsigned int offset;
4249 fp = NODEDATA(leaf);
4250 if (flags == MDB_CURRENT) {
4251 fp->mp_flags |= P_DIRTY;
4252 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4253 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4257 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4258 offset = fp->mp_pad;
4260 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4262 offset += offset & 1;
4263 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4264 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4266 /* yes, convert it */
4268 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4269 dummy.md_pad = fp->mp_pad;
4270 dummy.md_flags = MDB_DUPFIXED;
4271 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4272 dummy.md_flags |= MDB_INTEGERKEY;
4275 dummy.md_branch_pages = 0;
4276 dummy.md_leaf_pages = 1;
4277 dummy.md_overflow_pages = 0;
4278 dummy.md_entries = NUMKEYS(fp);
4280 xdata.mv_size = sizeof(MDB_db);
4281 xdata.mv_data = &dummy;
4282 mp = mdb_page_alloc(mc, 1);
4285 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4286 flags |= F_DUPDATA|F_SUBDATA;
4287 dummy.md_root = mp->mp_pgno;
4289 /* no, just grow it */
4291 xdata.mv_size = NODEDSZ(leaf) + offset;
4292 xdata.mv_data = &pbuf;
4293 mp = (MDB_page *)&pbuf;
4294 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4297 mp->mp_flags = fp->mp_flags | P_DIRTY;
4298 mp->mp_pad = fp->mp_pad;
4299 mp->mp_lower = fp->mp_lower;
4300 mp->mp_upper = fp->mp_upper + offset;
4302 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4304 nsize = NODEDSZ(leaf) - fp->mp_upper;
4305 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4306 for (i=0; i<NUMKEYS(fp); i++)
4307 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4309 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4310 mc->mc_db->md_entries--;
4314 /* data is on sub-DB, just store it */
4315 flags |= F_DUPDATA|F_SUBDATA;
4319 /* same size, just replace it */
4320 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4321 NODEDSZ(leaf) == data->mv_size) {
4322 if (F_ISSET(flags, MDB_RESERVE))
4323 data->mv_data = NODEDATA(leaf);
4325 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4328 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4329 mc->mc_db->md_entries--;
4331 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4337 nflags = flags & NODE_ADD_FLAGS;
4338 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4339 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4340 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4341 nflags &= ~MDB_APPEND;
4342 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4344 /* There is room already in this leaf page. */
4345 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4346 if (rc == 0 && !do_sub) {
4347 /* Adjust other cursors pointing to mp */
4348 MDB_cursor *m2, *m3;
4349 MDB_dbi dbi = mc->mc_dbi;
4350 unsigned i = mc->mc_top;
4351 MDB_page *mp = mc->mc_pg[i];
4353 if (mc->mc_flags & C_SUB)
4356 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4357 if (mc->mc_flags & C_SUB)
4358 m3 = &m2->mc_xcursor->mx_cursor;
4361 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4362 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4369 if (rc != MDB_SUCCESS)
4370 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4372 /* Now store the actual data in the child DB. Note that we're
4373 * storing the user data in the keys field, so there are strict
4374 * size limits on dupdata. The actual data fields of the child
4375 * DB are all zero size.
4382 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4383 if (flags & MDB_CURRENT) {
4384 xflags = MDB_CURRENT;
4386 mdb_xcursor_init1(mc, leaf);
4387 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4389 /* converted, write the original data first */
4391 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4395 /* Adjust other cursors pointing to mp */
4397 unsigned i = mc->mc_top;
4398 MDB_page *mp = mc->mc_pg[i];
4400 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4401 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4402 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4403 mdb_xcursor_init1(m2, leaf);
4408 xflags |= (flags & MDB_APPEND);
4409 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4410 if (flags & F_SUBDATA) {
4411 void *db = NODEDATA(leaf);
4412 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4415 /* sub-writes might have failed so check rc again.
4416 * Don't increment count if we just replaced an existing item.
4418 if (!rc && !(flags & MDB_CURRENT))
4419 mc->mc_db->md_entries++;
4420 if (flags & MDB_MULTIPLE) {
4422 if (mcount < data[1].mv_size) {
4423 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4424 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4434 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4439 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4442 if (!mc->mc_flags & C_INITIALIZED)
4445 rc = mdb_cursor_touch(mc);
4449 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4451 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4452 if (flags != MDB_NODUPDATA) {
4453 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4454 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4456 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4457 /* If sub-DB still has entries, we're done */
4458 if (mc->mc_xcursor->mx_db.md_entries) {
4459 if (leaf->mn_flags & F_SUBDATA) {
4460 /* update subDB info */
4461 void *db = NODEDATA(leaf);
4462 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4464 /* shrink fake page */
4465 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4467 mc->mc_db->md_entries--;
4470 /* otherwise fall thru and delete the sub-DB */
4473 if (leaf->mn_flags & F_SUBDATA) {
4474 /* add all the child DB's pages to the free list */
4475 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4476 if (rc == MDB_SUCCESS) {
4477 mc->mc_db->md_entries -=
4478 mc->mc_xcursor->mx_db.md_entries;
4483 return mdb_cursor_del0(mc, leaf);
4486 /** Allocate and initialize new pages for a database.
4487 * @param[in] mc a cursor on the database being added to.
4488 * @param[in] flags flags defining what type of page is being allocated.
4489 * @param[in] num the number of pages to allocate. This is usually 1,
4490 * unless allocating overflow pages for a large record.
4491 * @return Address of a page, or NULL on failure.
4494 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4498 if ((np = mdb_page_alloc(mc, num)) == NULL)
4500 DPRINTF("allocated new mpage %zu, page size %u",
4501 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4502 np->mp_flags = flags | P_DIRTY;
4503 np->mp_lower = PAGEHDRSZ;
4504 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4507 mc->mc_db->md_branch_pages++;
4508 else if (IS_LEAF(np))
4509 mc->mc_db->md_leaf_pages++;
4510 else if (IS_OVERFLOW(np)) {
4511 mc->mc_db->md_overflow_pages += num;
4518 /** Calculate the size of a leaf node.
4519 * The size depends on the environment's page size; if a data item
4520 * is too large it will be put onto an overflow page and the node
4521 * size will only include the key and not the data. Sizes are always
4522 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4523 * of the #MDB_node headers.
4524 * @param[in] env The environment handle.
4525 * @param[in] key The key for the node.
4526 * @param[in] data The data for the node.
4527 * @return The number of bytes needed to store the node.
4530 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4534 sz = LEAFSIZE(key, data);
4535 if (sz >= env->me_psize / MDB_MINKEYS) {
4536 /* put on overflow page */
4537 sz -= data->mv_size - sizeof(pgno_t);
4541 return sz + sizeof(indx_t);
4544 /** Calculate the size of a branch node.
4545 * The size should depend on the environment's page size but since
4546 * we currently don't support spilling large keys onto overflow
4547 * pages, it's simply the size of the #MDB_node header plus the
4548 * size of the key. Sizes are always rounded up to an even number
4549 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4550 * @param[in] env The environment handle.
4551 * @param[in] key The key for the node.
4552 * @return The number of bytes needed to store the node.
4555 mdb_branch_size(MDB_env *env, MDB_val *key)
4560 if (sz >= env->me_psize / MDB_MINKEYS) {
4561 /* put on overflow page */
4562 /* not implemented */
4563 /* sz -= key->size - sizeof(pgno_t); */
4566 return sz + sizeof(indx_t);
4569 /** Add a node to the page pointed to by the cursor.
4570 * @param[in] mc The cursor for this operation.
4571 * @param[in] indx The index on the page where the new node should be added.
4572 * @param[in] key The key for the new node.
4573 * @param[in] data The data for the new node, if any.
4574 * @param[in] pgno The page number, if adding a branch node.
4575 * @param[in] flags Flags for the node.
4576 * @return 0 on success, non-zero on failure. Possible errors are:
4578 * <li>ENOMEM - failed to allocate overflow pages for the node.
4579 * <li>ENOSPC - there is insufficient room in the page. This error
4580 * should never happen since all callers already calculate the
4581 * page's free space before calling this function.
4585 mdb_node_add(MDB_cursor *mc, indx_t indx,
4586 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4589 size_t node_size = NODESIZE;
4592 MDB_page *mp = mc->mc_pg[mc->mc_top];
4593 MDB_page *ofp = NULL; /* overflow page */
4596 assert(mp->mp_upper >= mp->mp_lower);
4598 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4599 IS_LEAF(mp) ? "leaf" : "branch",
4600 IS_SUBP(mp) ? "sub-" : "",
4601 mp->mp_pgno, indx, data ? data->mv_size : 0,
4602 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4605 /* Move higher keys up one slot. */
4606 int ksize = mc->mc_db->md_pad, dif;
4607 char *ptr = LEAF2KEY(mp, indx, ksize);
4608 dif = NUMKEYS(mp) - indx;
4610 memmove(ptr+ksize, ptr, dif*ksize);
4611 /* insert new key */
4612 memcpy(ptr, key->mv_data, ksize);
4614 /* Just using these for counting */
4615 mp->mp_lower += sizeof(indx_t);
4616 mp->mp_upper -= ksize - sizeof(indx_t);
4621 node_size += key->mv_size;
4625 if (F_ISSET(flags, F_BIGDATA)) {
4626 /* Data already on overflow page. */
4627 node_size += sizeof(pgno_t);
4628 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4629 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4630 /* Put data on overflow page. */
4631 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4632 data->mv_size, node_size+data->mv_size);
4633 node_size += sizeof(pgno_t);
4634 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4636 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4639 node_size += data->mv_size;
4642 node_size += node_size & 1;
4644 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4645 DPRINTF("not enough room in page %zu, got %u ptrs",
4646 mp->mp_pgno, NUMKEYS(mp));
4647 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4648 mp->mp_upper - mp->mp_lower);
4649 DPRINTF("node size = %zu", node_size);
4653 /* Move higher pointers up one slot. */
4654 for (i = NUMKEYS(mp); i > indx; i--)
4655 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4657 /* Adjust free space offsets. */
4658 ofs = mp->mp_upper - node_size;
4659 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4660 mp->mp_ptrs[indx] = ofs;
4662 mp->mp_lower += sizeof(indx_t);
4664 /* Write the node data. */
4665 node = NODEPTR(mp, indx);
4666 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4667 node->mn_flags = flags;
4669 SETDSZ(node,data->mv_size);
4674 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4679 if (F_ISSET(flags, F_BIGDATA))
4680 memcpy(node->mn_data + key->mv_size, data->mv_data,
4682 else if (F_ISSET(flags, MDB_RESERVE))
4683 data->mv_data = node->mn_data + key->mv_size;
4685 memcpy(node->mn_data + key->mv_size, data->mv_data,
4688 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4690 if (F_ISSET(flags, MDB_RESERVE))
4691 data->mv_data = METADATA(ofp);
4693 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4700 /** Delete the specified node from a page.
4701 * @param[in] mp The page to operate on.
4702 * @param[in] indx The index of the node to delete.
4703 * @param[in] ksize The size of a node. Only used if the page is
4704 * part of a #MDB_DUPFIXED database.
4707 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4710 indx_t i, j, numkeys, ptr;
4717 COPY_PGNO(pgno, mp->mp_pgno);
4718 DPRINTF("delete node %u on %s page %zu", indx,
4719 IS_LEAF(mp) ? "leaf" : "branch", pgno);
4722 assert(indx < NUMKEYS(mp));
4725 int x = NUMKEYS(mp) - 1 - indx;
4726 base = LEAF2KEY(mp, indx, ksize);
4728 memmove(base, base + ksize, x * ksize);
4729 mp->mp_lower -= sizeof(indx_t);
4730 mp->mp_upper += ksize - sizeof(indx_t);
4734 node = NODEPTR(mp, indx);
4735 sz = NODESIZE + node->mn_ksize;
4737 if (F_ISSET(node->mn_flags, F_BIGDATA))
4738 sz += sizeof(pgno_t);
4740 sz += NODEDSZ(node);
4744 ptr = mp->mp_ptrs[indx];
4745 numkeys = NUMKEYS(mp);
4746 for (i = j = 0; i < numkeys; i++) {
4748 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4749 if (mp->mp_ptrs[i] < ptr)
4750 mp->mp_ptrs[j] += sz;
4755 base = (char *)mp + mp->mp_upper;
4756 memmove(base + sz, base, ptr - mp->mp_upper);
4758 mp->mp_lower -= sizeof(indx_t);
4762 /** Compact the main page after deleting a node on a subpage.
4763 * @param[in] mp The main page to operate on.
4764 * @param[in] indx The index of the subpage on the main page.
4767 mdb_node_shrink(MDB_page *mp, indx_t indx)
4774 indx_t i, numkeys, ptr;
4776 node = NODEPTR(mp, indx);
4777 sp = (MDB_page *)NODEDATA(node);
4778 osize = NODEDSZ(node);
4780 delta = sp->mp_upper - sp->mp_lower;
4781 SETDSZ(node, osize - delta);
4782 xp = (MDB_page *)((char *)sp + delta);
4784 /* shift subpage upward */
4786 nsize = NUMKEYS(sp) * sp->mp_pad;
4787 memmove(METADATA(xp), METADATA(sp), nsize);
4790 nsize = osize - sp->mp_upper;
4791 numkeys = NUMKEYS(sp);
4792 for (i=numkeys-1; i>=0; i--)
4793 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4795 xp->mp_upper = sp->mp_lower;
4796 xp->mp_lower = sp->mp_lower;
4797 xp->mp_flags = sp->mp_flags;
4798 xp->mp_pad = sp->mp_pad;
4799 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4801 /* shift lower nodes upward */
4802 ptr = mp->mp_ptrs[indx];
4803 numkeys = NUMKEYS(mp);
4804 for (i = 0; i < numkeys; i++) {
4805 if (mp->mp_ptrs[i] <= ptr)
4806 mp->mp_ptrs[i] += delta;
4809 base = (char *)mp + mp->mp_upper;
4810 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4811 mp->mp_upper += delta;
4814 /** Initial setup of a sorted-dups cursor.
4815 * Sorted duplicates are implemented as a sub-database for the given key.
4816 * The duplicate data items are actually keys of the sub-database.
4817 * Operations on the duplicate data items are performed using a sub-cursor
4818 * initialized when the sub-database is first accessed. This function does
4819 * the preliminary setup of the sub-cursor, filling in the fields that
4820 * depend only on the parent DB.
4821 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4824 mdb_xcursor_init0(MDB_cursor *mc)
4826 MDB_xcursor *mx = mc->mc_xcursor;
4828 mx->mx_cursor.mc_xcursor = NULL;
4829 mx->mx_cursor.mc_txn = mc->mc_txn;
4830 mx->mx_cursor.mc_db = &mx->mx_db;
4831 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4832 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4833 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4834 mx->mx_cursor.mc_snum = 0;
4835 mx->mx_cursor.mc_top = 0;
4836 mx->mx_cursor.mc_flags = C_SUB;
4837 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4838 mx->mx_dbx.md_dcmp = NULL;
4839 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4842 /** Final setup of a sorted-dups cursor.
4843 * Sets up the fields that depend on the data from the main cursor.
4844 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4845 * @param[in] node The data containing the #MDB_db record for the
4846 * sorted-dup database.
4849 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4851 MDB_xcursor *mx = mc->mc_xcursor;
4853 if (node->mn_flags & F_SUBDATA) {
4854 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
4855 mx->mx_cursor.mc_snum = 0;
4856 mx->mx_cursor.mc_flags = C_SUB;
4858 MDB_page *fp = NODEDATA(node);
4859 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4860 mx->mx_db.md_flags = 0;
4861 mx->mx_db.md_depth = 1;
4862 mx->mx_db.md_branch_pages = 0;
4863 mx->mx_db.md_leaf_pages = 1;
4864 mx->mx_db.md_overflow_pages = 0;
4865 mx->mx_db.md_entries = NUMKEYS(fp);
4866 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4867 mx->mx_cursor.mc_snum = 1;
4868 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4869 mx->mx_cursor.mc_top = 0;
4870 mx->mx_cursor.mc_pg[0] = fp;
4871 mx->mx_cursor.mc_ki[0] = 0;
4872 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4873 mx->mx_db.md_flags = MDB_DUPFIXED;
4874 mx->mx_db.md_pad = fp->mp_pad;
4875 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4876 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4879 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4881 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4883 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4884 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4885 #if UINT_MAX < SIZE_MAX
4886 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4887 #ifdef MISALIGNED_OK
4888 mx->mx_dbx.md_cmp = mdb_cmp_long;
4890 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4895 /** Initialize a cursor for a given transaction and database. */
4897 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4902 mc->mc_db = &txn->mt_dbs[dbi];
4903 mc->mc_dbx = &txn->mt_dbxs[dbi];
4904 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4908 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4910 mc->mc_xcursor = mx;
4911 mdb_xcursor_init0(mc);
4913 mc->mc_xcursor = NULL;
4918 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4921 MDB_xcursor *mx = NULL;
4922 size_t size = sizeof(MDB_cursor);
4924 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
4927 /* Allow read access to the freelist */
4928 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
4931 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4932 size += sizeof(MDB_xcursor);
4934 if ((mc = malloc(size)) != NULL) {
4935 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4936 mx = (MDB_xcursor *)(mc + 1);
4938 mdb_cursor_init(mc, txn, dbi, mx);
4939 if (txn->mt_cursors) {
4940 mc->mc_next = txn->mt_cursors[dbi];
4941 txn->mt_cursors[dbi] = mc;
4943 mc->mc_flags |= C_ALLOCD;
4953 /* Return the count of duplicate data items for the current key */
4955 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4959 if (mc == NULL || countp == NULL)
4962 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4965 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4966 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4969 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4972 *countp = mc->mc_xcursor->mx_db.md_entries;
4978 mdb_cursor_close(MDB_cursor *mc)
4981 /* remove from txn, if tracked */
4982 if (mc->mc_txn->mt_cursors) {
4983 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4984 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4986 *prev = mc->mc_next;
4988 if (mc->mc_flags & C_ALLOCD)
4994 mdb_cursor_txn(MDB_cursor *mc)
4996 if (!mc) return NULL;
5001 mdb_cursor_dbi(MDB_cursor *mc)
5007 /** Replace the key for a node with a new key.
5008 * @param[in] mp The page containing the node to operate on.
5009 * @param[in] indx The index of the node to operate on.
5010 * @param[in] key The new key to use.
5011 * @return 0 on success, non-zero on failure.
5014 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5016 indx_t ptr, i, numkeys;
5023 node = NODEPTR(mp, indx);
5024 ptr = mp->mp_ptrs[indx];
5028 char kbuf2[(MAXKEYSIZE*2+1)];
5029 k2.mv_data = NODEKEY(node);
5030 k2.mv_size = node->mn_ksize;
5031 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5033 mdb_dkey(&k2, kbuf2),
5039 delta = key->mv_size - node->mn_ksize;
5041 if (delta > 0 && SIZELEFT(mp) < delta) {
5042 DPRINTF("OUCH! Not enough room, delta = %d", delta);
5046 numkeys = NUMKEYS(mp);
5047 for (i = 0; i < numkeys; i++) {
5048 if (mp->mp_ptrs[i] <= ptr)
5049 mp->mp_ptrs[i] -= delta;
5052 base = (char *)mp + mp->mp_upper;
5053 len = ptr - mp->mp_upper + NODESIZE;
5054 memmove(base - delta, base, len);
5055 mp->mp_upper -= delta;
5057 node = NODEPTR(mp, indx);
5058 node->mn_ksize = key->mv_size;
5062 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5067 /** Move a node from csrc to cdst.
5070 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5076 unsigned short flags;
5080 /* Mark src and dst as dirty. */
5081 if ((rc = mdb_page_touch(csrc)) ||
5082 (rc = mdb_page_touch(cdst)))
5085 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5086 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5087 key.mv_size = csrc->mc_db->md_pad;
5088 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5090 data.mv_data = NULL;
5094 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5095 assert(!((long)srcnode&1));
5096 srcpg = NODEPGNO(srcnode);
5097 flags = srcnode->mn_flags;
5098 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5099 unsigned int snum = csrc->mc_snum;
5101 /* must find the lowest key below src */
5102 mdb_page_search_root(csrc, NULL, 0);
5103 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5104 key.mv_size = NODEKSZ(s2);
5105 key.mv_data = NODEKEY(s2);
5106 csrc->mc_snum = snum--;
5107 csrc->mc_top = snum;
5109 key.mv_size = NODEKSZ(srcnode);
5110 key.mv_data = NODEKEY(srcnode);
5112 data.mv_size = NODEDSZ(srcnode);
5113 data.mv_data = NODEDATA(srcnode);
5115 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5116 unsigned int snum = cdst->mc_snum;
5119 /* must find the lowest key below dst */
5120 mdb_page_search_root(cdst, NULL, 0);
5121 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5122 bkey.mv_size = NODEKSZ(s2);
5123 bkey.mv_data = NODEKEY(s2);
5124 cdst->mc_snum = snum--;
5125 cdst->mc_top = snum;
5126 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5129 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5130 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5131 csrc->mc_ki[csrc->mc_top],
5133 csrc->mc_pg[csrc->mc_top]->mp_pgno,
5134 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5136 /* Add the node to the destination page.
5138 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5139 if (rc != MDB_SUCCESS)
5142 /* Delete the node from the source page.
5144 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5147 /* Adjust other cursors pointing to mp */
5148 MDB_cursor *m2, *m3;
5149 MDB_dbi dbi = csrc->mc_dbi;
5150 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5152 if (csrc->mc_flags & C_SUB)
5155 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5156 if (m2 == csrc) continue;
5157 if (csrc->mc_flags & C_SUB)
5158 m3 = &m2->mc_xcursor->mx_cursor;
5161 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5162 csrc->mc_ki[csrc->mc_top]) {
5163 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5164 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5169 /* Update the parent separators.
5171 if (csrc->mc_ki[csrc->mc_top] == 0) {
5172 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5173 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5174 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5176 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5177 key.mv_size = NODEKSZ(srcnode);
5178 key.mv_data = NODEKEY(srcnode);
5180 DPRINTF("update separator for source page %zu to [%s]",
5181 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5182 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5183 &key)) != MDB_SUCCESS)
5186 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5188 nullkey.mv_size = 0;
5189 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5190 assert(rc == MDB_SUCCESS);
5194 if (cdst->mc_ki[cdst->mc_top] == 0) {
5195 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5196 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5197 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5199 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5200 key.mv_size = NODEKSZ(srcnode);
5201 key.mv_data = NODEKEY(srcnode);
5203 DPRINTF("update separator for destination page %zu to [%s]",
5204 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5205 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5206 &key)) != MDB_SUCCESS)
5209 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5211 nullkey.mv_size = 0;
5212 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5213 assert(rc == MDB_SUCCESS);
5220 /** Merge one page into another.
5221 * The nodes from the page pointed to by \b csrc will
5222 * be copied to the page pointed to by \b cdst and then
5223 * the \b csrc page will be freed.
5224 * @param[in] csrc Cursor pointing to the source page.
5225 * @param[in] cdst Cursor pointing to the destination page.
5228 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5236 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5237 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5239 assert(csrc->mc_snum > 1); /* can't merge root page */
5240 assert(cdst->mc_snum > 1);
5242 /* Mark dst as dirty. */
5243 if ((rc = mdb_page_touch(cdst)))
5246 /* Move all nodes from src to dst.
5248 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5249 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5250 key.mv_size = csrc->mc_db->md_pad;
5251 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5252 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5253 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5254 if (rc != MDB_SUCCESS)
5256 key.mv_data = (char *)key.mv_data + key.mv_size;
5259 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5260 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5261 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5262 unsigned int snum = csrc->mc_snum;
5264 /* must find the lowest key below src */
5265 mdb_page_search_root(csrc, NULL, 0);
5266 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5267 key.mv_size = NODEKSZ(s2);
5268 key.mv_data = NODEKEY(s2);
5269 csrc->mc_snum = snum--;
5270 csrc->mc_top = snum;
5272 key.mv_size = srcnode->mn_ksize;
5273 key.mv_data = NODEKEY(srcnode);
5276 data.mv_size = NODEDSZ(srcnode);
5277 data.mv_data = NODEDATA(srcnode);
5278 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5279 if (rc != MDB_SUCCESS)
5284 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5285 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);
5287 /* Unlink the src page from parent and add to free list.
5289 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5290 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5292 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5296 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5297 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5298 csrc->mc_db->md_leaf_pages--;
5300 csrc->mc_db->md_branch_pages--;
5302 /* Adjust other cursors pointing to mp */
5303 MDB_cursor *m2, *m3;
5304 MDB_dbi dbi = csrc->mc_dbi;
5305 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5307 if (csrc->mc_flags & C_SUB)
5310 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5311 if (csrc->mc_flags & C_SUB)
5312 m3 = &m2->mc_xcursor->mx_cursor;
5315 if (m3 == csrc) continue;
5316 if (m3->mc_snum < csrc->mc_snum) continue;
5317 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5318 m3->mc_pg[csrc->mc_top] = mp;
5319 m3->mc_ki[csrc->mc_top] += nkeys;
5323 mdb_cursor_pop(csrc);
5325 return mdb_rebalance(csrc);
5328 /** Copy the contents of a cursor.
5329 * @param[in] csrc The cursor to copy from.
5330 * @param[out] cdst The cursor to copy to.
5333 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5337 cdst->mc_txn = csrc->mc_txn;
5338 cdst->mc_dbi = csrc->mc_dbi;
5339 cdst->mc_db = csrc->mc_db;
5340 cdst->mc_dbx = csrc->mc_dbx;
5341 cdst->mc_snum = csrc->mc_snum;
5342 cdst->mc_top = csrc->mc_top;
5343 cdst->mc_flags = csrc->mc_flags;
5345 for (i=0; i<csrc->mc_snum; i++) {
5346 cdst->mc_pg[i] = csrc->mc_pg[i];
5347 cdst->mc_ki[i] = csrc->mc_ki[i];
5351 /** Rebalance the tree after a delete operation.
5352 * @param[in] mc Cursor pointing to the page where rebalancing
5354 * @return 0 on success, non-zero on failure.
5357 mdb_rebalance(MDB_cursor *mc)
5367 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5368 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5369 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5370 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5374 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5377 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5378 DPRINTF("no need to rebalance page %zu, above fill threshold",
5384 if (mc->mc_snum < 2) {
5385 MDB_page *mp = mc->mc_pg[0];
5386 if (NUMKEYS(mp) == 0) {
5387 DPUTS("tree is completely empty");
5388 mc->mc_db->md_root = P_INVALID;
5389 mc->mc_db->md_depth = 0;
5390 mc->mc_db->md_leaf_pages = 0;
5391 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5395 /* Adjust other cursors pointing to mp */
5396 MDB_cursor *m2, *m3;
5397 MDB_dbi dbi = mc->mc_dbi;
5399 if (mc->mc_flags & C_SUB)
5402 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5403 if (m2 == mc) continue;
5404 if (mc->mc_flags & C_SUB)
5405 m3 = &m2->mc_xcursor->mx_cursor;
5408 if (m3->mc_snum < mc->mc_snum) continue;
5409 if (m3->mc_pg[0] == mp) {
5415 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5416 DPUTS("collapsing root page!");
5417 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5418 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5419 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5422 mc->mc_db->md_depth--;
5423 mc->mc_db->md_branch_pages--;
5425 /* Adjust other cursors pointing to mp */
5426 MDB_cursor *m2, *m3;
5427 MDB_dbi dbi = mc->mc_dbi;
5429 if (mc->mc_flags & C_SUB)
5432 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5433 if (m2 == mc) continue;
5434 if (mc->mc_flags & C_SUB)
5435 m3 = &m2->mc_xcursor->mx_cursor;
5438 if (m3->mc_snum < mc->mc_snum) continue;
5439 if (m3->mc_pg[0] == mp) {
5440 m3->mc_pg[0] = mc->mc_pg[0];
5445 DPUTS("root page doesn't need rebalancing");
5449 /* The parent (branch page) must have at least 2 pointers,
5450 * otherwise the tree is invalid.
5452 ptop = mc->mc_top-1;
5453 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5455 /* Leaf page fill factor is below the threshold.
5456 * Try to move keys from left or right neighbor, or
5457 * merge with a neighbor page.
5462 mdb_cursor_copy(mc, &mn);
5463 mn.mc_xcursor = NULL;
5465 if (mc->mc_ki[ptop] == 0) {
5466 /* We're the leftmost leaf in our parent.
5468 DPUTS("reading right neighbor");
5470 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5471 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5473 mn.mc_ki[mn.mc_top] = 0;
5474 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5476 /* There is at least one neighbor to the left.
5478 DPUTS("reading left neighbor");
5480 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5481 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5483 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5484 mc->mc_ki[mc->mc_top] = 0;
5487 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5488 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);
5490 /* If the neighbor page is above threshold and has at least two
5491 * keys, move one key from it.
5493 * Otherwise we should try to merge them.
5495 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5496 return mdb_node_move(&mn, mc);
5497 else { /* FIXME: if (has_enough_room()) */
5498 mc->mc_flags &= ~C_INITIALIZED;
5499 if (mc->mc_ki[ptop] == 0)
5500 return mdb_page_merge(&mn, mc);
5502 return mdb_page_merge(mc, &mn);
5506 /** Complete a delete operation started by #mdb_cursor_del(). */
5508 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5512 /* add overflow pages to free list */
5513 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5517 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5518 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5519 mc->mc_db->md_overflow_pages -= ovpages;
5520 for (i=0; i<ovpages; i++) {
5521 DPRINTF("freed ov page %zu", pg);
5522 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5526 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5527 mc->mc_db->md_entries--;
5528 rc = mdb_rebalance(mc);
5529 if (rc != MDB_SUCCESS)
5530 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5536 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5537 MDB_val *key, MDB_val *data)
5542 MDB_val rdata, *xdata;
5546 assert(key != NULL);
5548 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5550 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5553 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5557 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5561 mdb_cursor_init(&mc, txn, dbi, &mx);
5572 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5574 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5578 /** Split a page and insert a new node.
5579 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5580 * The cursor will be updated to point to the actual page and index where
5581 * the node got inserted after the split.
5582 * @param[in] newkey The key for the newly inserted node.
5583 * @param[in] newdata The data for the newly inserted node.
5584 * @param[in] newpgno The page number, if the new node is a branch node.
5585 * @return 0 on success, non-zero on failure.
5588 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5589 unsigned int nflags)
5592 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5595 unsigned int i, j, split_indx, nkeys, pmax;
5597 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5599 MDB_page *mp, *rp, *pp;
5604 mp = mc->mc_pg[mc->mc_top];
5605 newindx = mc->mc_ki[mc->mc_top];
5607 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5608 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5609 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5611 /* Create a right sibling. */
5612 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5614 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5616 if (mc->mc_snum < 2) {
5617 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5619 /* shift current top to make room for new parent */
5620 mc->mc_pg[1] = mc->mc_pg[0];
5621 mc->mc_ki[1] = mc->mc_ki[0];
5624 mc->mc_db->md_root = pp->mp_pgno;
5625 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5626 mc->mc_db->md_depth++;
5629 /* Add left (implicit) pointer. */
5630 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5631 /* undo the pre-push */
5632 mc->mc_pg[0] = mc->mc_pg[1];
5633 mc->mc_ki[0] = mc->mc_ki[1];
5634 mc->mc_db->md_root = mp->mp_pgno;
5635 mc->mc_db->md_depth--;
5642 ptop = mc->mc_top-1;
5643 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5646 mdb_cursor_copy(mc, &mn);
5647 mn.mc_pg[mn.mc_top] = rp;
5648 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5650 if (nflags & MDB_APPEND) {
5651 mn.mc_ki[mn.mc_top] = 0;
5658 nkeys = NUMKEYS(mp);
5659 split_indx = nkeys / 2 + 1;
5664 unsigned int lsize, rsize, ksize;
5665 /* Move half of the keys to the right sibling */
5667 x = mc->mc_ki[mc->mc_top] - split_indx;
5668 ksize = mc->mc_db->md_pad;
5669 split = LEAF2KEY(mp, split_indx, ksize);
5670 rsize = (nkeys - split_indx) * ksize;
5671 lsize = (nkeys - split_indx) * sizeof(indx_t);
5672 mp->mp_lower -= lsize;
5673 rp->mp_lower += lsize;
5674 mp->mp_upper += rsize - lsize;
5675 rp->mp_upper -= rsize - lsize;
5676 sepkey.mv_size = ksize;
5677 if (newindx == split_indx) {
5678 sepkey.mv_data = newkey->mv_data;
5680 sepkey.mv_data = split;
5683 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5684 memcpy(rp->mp_ptrs, split, rsize);
5685 sepkey.mv_data = rp->mp_ptrs;
5686 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5687 memcpy(ins, newkey->mv_data, ksize);
5688 mp->mp_lower += sizeof(indx_t);
5689 mp->mp_upper -= ksize - sizeof(indx_t);
5692 memcpy(rp->mp_ptrs, split, x * ksize);
5693 ins = LEAF2KEY(rp, x, ksize);
5694 memcpy(ins, newkey->mv_data, ksize);
5695 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5696 rp->mp_lower += sizeof(indx_t);
5697 rp->mp_upper -= ksize - sizeof(indx_t);
5698 mc->mc_ki[mc->mc_top] = x;
5699 mc->mc_pg[mc->mc_top] = rp;
5704 /* For leaf pages, check the split point based on what
5705 * fits where, since otherwise add_node can fail.
5708 unsigned int psize, nsize;
5709 /* Maximum free space in an empty page */
5710 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5711 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5712 if (newindx < split_indx) {
5714 for (i=0; i<split_indx; i++) {
5715 node = NODEPTR(mp, i);
5716 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5717 if (F_ISSET(node->mn_flags, F_BIGDATA))
5718 psize += sizeof(pgno_t);
5720 psize += NODEDSZ(node);
5729 for (i=nkeys-1; i>=split_indx; i--) {
5730 node = NODEPTR(mp, i);
5731 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5732 if (F_ISSET(node->mn_flags, F_BIGDATA))
5733 psize += sizeof(pgno_t);
5735 psize += NODEDSZ(node);
5745 /* First find the separating key between the split pages.
5747 if (newindx == split_indx) {
5748 sepkey.mv_size = newkey->mv_size;
5749 sepkey.mv_data = newkey->mv_data;
5751 node = NODEPTR(mp, split_indx);
5752 sepkey.mv_size = node->mn_ksize;
5753 sepkey.mv_data = NODEKEY(node);
5757 DPRINTF("separator is [%s]", DKEY(&sepkey));
5759 /* Copy separator key to the parent.
5761 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5764 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5766 /* Right page might now have changed parent.
5767 * Check if left page also changed parent.
5769 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5770 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5771 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5772 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5776 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5779 if (rc != MDB_SUCCESS) {
5782 if (nflags & MDB_APPEND) {
5783 mc->mc_pg[mc->mc_top] = rp;
5784 mc->mc_ki[mc->mc_top] = 0;
5785 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5794 /* Move half of the keys to the right sibling. */
5796 /* grab a page to hold a temporary copy */
5797 copy = mdb_page_malloc(mc);
5801 copy->mp_pgno = mp->mp_pgno;
5802 copy->mp_flags = mp->mp_flags;
5803 copy->mp_lower = PAGEHDRSZ;
5804 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5805 mc->mc_pg[mc->mc_top] = copy;
5806 for (i = j = 0; i <= nkeys; j++) {
5807 if (i == split_indx) {
5808 /* Insert in right sibling. */
5809 /* Reset insert index for right sibling. */
5810 j = (i == newindx && ins_new);
5811 mc->mc_pg[mc->mc_top] = rp;
5814 if (i == newindx && !ins_new) {
5815 /* Insert the original entry that caused the split. */
5816 rkey.mv_data = newkey->mv_data;
5817 rkey.mv_size = newkey->mv_size;
5826 /* Update page and index for the new key. */
5828 mc->mc_pg[mc->mc_top] = copy;
5829 mc->mc_ki[mc->mc_top] = j;
5830 } else if (i == nkeys) {
5833 node = NODEPTR(mp, i);
5834 rkey.mv_data = NODEKEY(node);
5835 rkey.mv_size = node->mn_ksize;
5837 xdata.mv_data = NODEDATA(node);
5838 xdata.mv_size = NODEDSZ(node);
5841 pgno = NODEPGNO(node);
5842 flags = node->mn_flags;
5847 if (!IS_LEAF(mp) && j == 0) {
5848 /* First branch index doesn't need key data. */
5852 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5855 nkeys = NUMKEYS(copy);
5856 for (i=0; i<nkeys; i++)
5857 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5858 mp->mp_lower = copy->mp_lower;
5859 mp->mp_upper = copy->mp_upper;
5860 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5861 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5863 /* reset back to original page */
5864 if (!newindx || (newindx < split_indx)) {
5865 mc->mc_pg[mc->mc_top] = mp;
5866 if (nflags & MDB_RESERVE) {
5867 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5868 if (!(node->mn_flags & F_BIGDATA))
5869 newdata->mv_data = NODEDATA(node);
5873 /* return tmp page to freelist */
5874 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5875 VGMEMP_FREE(mc->mc_txn->mt_env, copy);
5876 mc->mc_txn->mt_env->me_dpages = copy;
5879 /* Adjust other cursors pointing to mp */
5880 MDB_cursor *m2, *m3;
5881 MDB_dbi dbi = mc->mc_dbi;
5883 if (mc->mc_flags & C_SUB)
5886 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5887 if (m2 == mc) continue;
5888 if (mc->mc_flags & C_SUB)
5889 m3 = &m2->mc_xcursor->mx_cursor;
5892 if (!(m3->mc_flags & C_INITIALIZED))
5897 for (k=m3->mc_top; k>=0; k--) {
5898 m3->mc_ki[k+1] = m3->mc_ki[k];
5899 m3->mc_pg[k+1] = m3->mc_pg[k];
5901 m3->mc_ki[0] = mc->mc_ki[0];
5902 m3->mc_pg[0] = mc->mc_pg[0];
5906 if (m3->mc_pg[mc->mc_top] == mp) {
5907 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5908 m3->mc_pg[m3->mc_top] = rp;
5909 m3->mc_ki[m3->mc_top] -= split_indx;
5918 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5919 MDB_val *key, MDB_val *data, unsigned int flags)
5924 assert(key != NULL);
5925 assert(data != NULL);
5927 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5930 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5934 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5938 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5941 mdb_cursor_init(&mc, txn, dbi, &mx);
5942 return mdb_cursor_put(&mc, key, data, flags);
5945 /** Only a subset of the @ref mdb_env flags can be changed
5946 * at runtime. Changing other flags requires closing the environment
5947 * and re-opening it with the new flags.
5949 #define CHANGEABLE (MDB_NOSYNC)
5951 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5953 if ((flag & CHANGEABLE) != flag)
5956 env->me_flags |= flag;
5958 env->me_flags &= ~flag;
5963 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5968 *arg = env->me_flags;
5973 mdb_env_get_path(MDB_env *env, const char **arg)
5978 *arg = env->me_path;
5982 /** Common code for #mdb_stat() and #mdb_env_stat().
5983 * @param[in] env the environment to operate in.
5984 * @param[in] db the #MDB_db record containing the stats to return.
5985 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5986 * @return 0, this function always succeeds.
5989 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5991 arg->ms_psize = env->me_psize;
5992 arg->ms_depth = db->md_depth;
5993 arg->ms_branch_pages = db->md_branch_pages;
5994 arg->ms_leaf_pages = db->md_leaf_pages;
5995 arg->ms_overflow_pages = db->md_overflow_pages;
5996 arg->ms_entries = db->md_entries;
6001 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6005 if (env == NULL || arg == NULL)
6008 mdb_env_read_meta(env, &toggle);
6010 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6013 /** Set the default comparison functions for a database.
6014 * Called immediately after a database is opened to set the defaults.
6015 * The user can then override them with #mdb_set_compare() or
6016 * #mdb_set_dupsort().
6017 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6018 * @param[in] dbi A database handle returned by #mdb_open()
6021 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6023 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
6024 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
6025 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
6026 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
6028 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
6030 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6031 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
6032 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
6033 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
6035 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
6036 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
6037 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
6039 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
6042 txn->mt_dbxs[dbi].md_dcmp = NULL;
6046 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6051 int rc, dbflag, exact;
6054 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6055 mdb_default_cmp(txn, FREE_DBI);
6061 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6062 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6063 mdb_default_cmp(txn, MAIN_DBI);
6067 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6068 mdb_default_cmp(txn, MAIN_DBI);
6071 /* Is the DB already open? */
6073 for (i=2; i<txn->mt_numdbs; i++) {
6074 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6075 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6081 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6084 /* Find the DB info */
6088 key.mv_data = (void *)name;
6089 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6090 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6091 if (rc == MDB_SUCCESS) {
6092 /* make sure this is actually a DB */
6093 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6094 if (!(node->mn_flags & F_SUBDATA))
6096 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6097 /* Create if requested */
6099 data.mv_size = sizeof(MDB_db);
6100 data.mv_data = &dummy;
6101 memset(&dummy, 0, sizeof(dummy));
6102 dummy.md_root = P_INVALID;
6103 dummy.md_flags = flags & 0xffff;
6104 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6108 /* OK, got info, add to table */
6109 if (rc == MDB_SUCCESS) {
6110 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
6111 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
6112 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
6113 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
6114 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
6115 *dbi = txn->mt_numdbs;
6116 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6117 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6118 mdb_default_cmp(txn, txn->mt_numdbs);
6125 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6127 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6130 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6133 void mdb_close(MDB_env *env, MDB_dbi dbi)
6136 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6138 ptr = env->me_dbxs[dbi].md_name.mv_data;
6139 env->me_dbxs[dbi].md_name.mv_data = NULL;
6140 env->me_dbxs[dbi].md_name.mv_size = 0;
6144 /** Add all the DB's pages to the free list.
6145 * @param[in] mc Cursor on the DB to free.
6146 * @param[in] subs non-Zero to check for sub-DBs in this DB.
6147 * @return 0 on success, non-zero on failure.
6150 mdb_drop0(MDB_cursor *mc, int subs)
6154 rc = mdb_page_search(mc, NULL, 0);
6155 if (rc == MDB_SUCCESS) {
6160 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6161 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6164 mdb_cursor_copy(mc, &mx);
6165 while (mc->mc_snum > 0) {
6166 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6167 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6168 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6169 if (ni->mn_flags & F_SUBDATA) {
6170 mdb_xcursor_init1(mc, ni);
6171 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6177 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6179 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6182 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6187 rc = mdb_cursor_sibling(mc, 1);
6189 /* no more siblings, go back to beginning
6190 * of previous level. (stack was already popped
6191 * by mdb_cursor_sibling)
6193 for (i=1; i<mc->mc_top; i++)
6194 mc->mc_pg[i] = mx.mc_pg[i];
6198 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6199 mc->mc_db->md_root);
6204 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6209 if (!txn || !dbi || dbi >= txn->mt_numdbs)
6212 rc = mdb_cursor_open(txn, dbi, &mc);
6216 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6220 /* Can't delete the main DB */
6221 if (del && dbi > MAIN_DBI) {
6222 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6224 mdb_close(txn->mt_env, dbi);
6226 txn->mt_dbflags[dbi] |= DB_DIRTY;
6227 txn->mt_dbs[dbi].md_depth = 0;
6228 txn->mt_dbs[dbi].md_branch_pages = 0;
6229 txn->mt_dbs[dbi].md_leaf_pages = 0;
6230 txn->mt_dbs[dbi].md_overflow_pages = 0;
6231 txn->mt_dbs[dbi].md_entries = 0;
6232 txn->mt_dbs[dbi].md_root = P_INVALID;
6235 mdb_cursor_close(mc);
6239 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6241 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6244 txn->mt_dbxs[dbi].md_cmp = cmp;
6248 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6250 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6253 txn->mt_dbxs[dbi].md_dcmp = cmp;
6257 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6259 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6262 txn->mt_dbxs[dbi].md_rel = rel;
6266 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6268 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6271 txn->mt_dbxs[dbi].md_relctx = ctx;