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 MDB_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 MDB_FDATASYNC(fd) fsync(fd)
161 #define MDB_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 static int mdb_debug;
263 static txnid_t mdb_debug_start;
265 /** Print a debug message with printf formatting. */
266 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
267 ((void) ((mdb_debug) && \
268 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
270 # define DPRINTF(fmt, ...) ((void) 0)
272 /** Print a debug string.
273 * The string is printed literally, with no format processing.
275 #define DPUTS(arg) DPRINTF("%s", arg)
278 /** A default memory page size.
279 * The actual size is platform-dependent, but we use this for
280 * boot-strapping. We probably should not be using this any more.
281 * The #GET_PAGESIZE() macro is used to get the actual size.
283 * Note that we don't currently support Huge pages. On Linux,
284 * regular data files cannot use Huge pages, and in general
285 * Huge pages aren't actually pageable. We rely on the OS
286 * demand-pager to read our data and page it out when memory
287 * pressure from other processes is high. So until OSs have
288 * actual paging support for Huge pages, they're not viable.
290 #define MDB_PAGESIZE 4096
292 /** The minimum number of keys required in a database page.
293 * Setting this to a larger value will place a smaller bound on the
294 * maximum size of a data item. Data items larger than this size will
295 * be pushed into overflow pages instead of being stored directly in
296 * the B-tree node. This value used to default to 4. With a page size
297 * of 4096 bytes that meant that any item larger than 1024 bytes would
298 * go into an overflow page. That also meant that on average 2-3KB of
299 * each overflow page was wasted space. The value cannot be lower than
300 * 2 because then there would no longer be a tree structure. With this
301 * value, items larger than 2KB will go into overflow pages, and on
302 * average only 1KB will be wasted.
304 #define MDB_MINKEYS 2
306 /** A stamp that identifies a file as an MDB file.
307 * There's nothing special about this value other than that it is easily
308 * recognizable, and it will reflect any byte order mismatches.
310 #define MDB_MAGIC 0xBEEFC0DE
312 /** The version number for a database's file format. */
313 #define MDB_VERSION 1
315 /** The maximum size of a key in the database.
316 * While data items have essentially unbounded size, we require that
317 * keys all fit onto a regular page. This limit could be raised a bit
318 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
320 #define MAXKEYSIZE 511
325 * This is used for printing a hex dump of a key's contents.
327 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
328 /** Display a key in hex.
330 * Invoke a function to display a key in hex.
332 #define DKEY(x) mdb_dkey(x, kbuf)
334 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
338 /** @defgroup lazylock Lazy Locking
339 * Macros for locks that aren't actually needed.
340 * The DB view is always consistent because all writes are wrapped in
341 * the wmutex. Finer-grained locks aren't necessary.
345 /** Use lazy locking. I.e., don't lock these accesses at all. */
349 /** Grab the reader lock */
350 #define LAZY_MUTEX_LOCK(x)
351 /** Release the reader lock */
352 #define LAZY_MUTEX_UNLOCK(x)
353 /** Release the DB table reader/writer lock */
354 #define LAZY_RWLOCK_UNLOCK(x)
355 /** Grab the DB table write lock */
356 #define LAZY_RWLOCK_WRLOCK(x)
357 /** Grab the DB table read lock */
358 #define LAZY_RWLOCK_RDLOCK(x)
359 /** Declare the DB table rwlock. Should not be followed by ';'. */
360 #define LAZY_RWLOCK_DEF(x)
361 /** Initialize the DB table rwlock */
362 #define LAZY_RWLOCK_INIT(x,y)
363 /** Destroy the DB table rwlock */
364 #define LAZY_RWLOCK_DESTROY(x)
366 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
367 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
368 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
369 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
370 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
371 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
372 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
373 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
377 /** An invalid page number.
378 * Mainly used to denote an empty tree.
380 #define P_INVALID (~0UL)
382 /** Test if a flag \b f is set in a flag word \b w. */
383 #define F_ISSET(w, f) (((w) & (f)) == (f))
385 /** Used for offsets within a single page.
386 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
389 typedef uint16_t indx_t;
391 /** Default size of memory map.
392 * This is certainly too small for any actual applications. Apps should always set
393 * the size explicitly using #mdb_env_set_mapsize().
395 #define DEFAULT_MAPSIZE 1048576
397 /** @defgroup readers Reader Lock Table
398 * Readers don't acquire any locks for their data access. Instead, they
399 * simply record their transaction ID in the reader table. The reader
400 * mutex is needed just to find an empty slot in the reader table. The
401 * slot's address is saved in thread-specific data so that subsequent read
402 * transactions started by the same thread need no further locking to proceed.
404 * Since the database uses multi-version concurrency control, readers don't
405 * actually need any locking. This table is used to keep track of which
406 * readers are using data from which old transactions, so that we'll know
407 * when a particular old transaction is no longer in use. Old transactions
408 * that have discarded any data pages can then have those pages reclaimed
409 * for use by a later write transaction.
411 * The lock table is constructed such that reader slots are aligned with the
412 * processor's cache line size. Any slot is only ever used by one thread.
413 * This alignment guarantees that there will be no contention or cache
414 * thrashing as threads update their own slot info, and also eliminates
415 * any need for locking when accessing a slot.
417 * A writer thread will scan every slot in the table to determine the oldest
418 * outstanding reader transaction. Any freed pages older than this will be
419 * reclaimed by the writer. The writer doesn't use any locks when scanning
420 * this table. This means that there's no guarantee that the writer will
421 * see the most up-to-date reader info, but that's not required for correct
422 * operation - all we need is to know the upper bound on the oldest reader,
423 * we don't care at all about the newest reader. So the only consequence of
424 * reading stale information here is that old pages might hang around a
425 * while longer before being reclaimed. That's actually good anyway, because
426 * the longer we delay reclaiming old pages, the more likely it is that a
427 * string of contiguous pages can be found after coalescing old pages from
428 * many old transactions together.
430 * @todo We don't actually do such coalescing yet, we grab pages from one
431 * old transaction at a time.
434 /** Number of slots in the reader table.
435 * This value was chosen somewhat arbitrarily. 126 readers plus a
436 * couple mutexes fit exactly into 8KB on my development machine.
437 * Applications should set the table size using #mdb_env_set_maxreaders().
439 #define DEFAULT_READERS 126
441 /** The size of a CPU cache line in bytes. We want our lock structures
442 * aligned to this size to avoid false cache line sharing in the
444 * This value works for most CPUs. For Itanium this should be 128.
450 /** The information we store in a single slot of the reader table.
451 * In addition to a transaction ID, we also record the process and
452 * thread ID that owns a slot, so that we can detect stale information,
453 * e.g. threads or processes that went away without cleaning up.
454 * @note We currently don't check for stale records. We simply re-init
455 * the table when we know that we're the only process opening the
458 typedef struct MDB_rxbody {
459 /** The current Transaction ID when this transaction began.
460 * Multiple readers that start at the same time will probably have the
461 * same ID here. Again, it's not important to exclude them from
462 * anything; all we need to know is which version of the DB they
463 * started from so we can avoid overwriting any data used in that
464 * particular version.
467 /** The process ID of the process owning this reader txn. */
469 /** The thread ID of the thread owning this txn. */
473 /** The actual reader record, with cacheline padding. */
474 typedef struct MDB_reader {
477 /** shorthand for mrb_txnid */
478 #define mr_txnid mru.mrx.mrb_txnid
479 #define mr_pid mru.mrx.mrb_pid
480 #define mr_tid mru.mrx.mrb_tid
481 /** cache line alignment */
482 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
486 /** The header for the reader table.
487 * The table resides in a memory-mapped file. (This is a different file
488 * than is used for the main database.)
490 * For POSIX the actual mutexes reside in the shared memory of this
491 * mapped file. On Windows, mutexes are named objects allocated by the
492 * kernel; we store the mutex names in this mapped file so that other
493 * processes can grab them. This same approach is also used on
494 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
495 * process-shared POSIX mutexes. For these cases where a named object
496 * is used, the object name is derived from a 64 bit FNV hash of the
497 * environment pathname. As such, naming collisions are extremely
498 * unlikely. If a collision occurs, the results are unpredictable.
500 typedef struct MDB_txbody {
501 /** Stamp identifying this as an MDB file. It must be set
504 /** Version number of this lock file. Must be set to #MDB_VERSION. */
505 uint32_t mtb_version;
506 #if defined(_WIN32) || defined(__APPLE__)
507 char mtb_rmname[MNAME_LEN];
509 /** Mutex protecting access to this table.
510 * This is the reader lock that #LOCK_MUTEX_R acquires.
512 pthread_mutex_t mtb_mutex;
515 /** The ID of the last transaction committed to the database.
516 * This is recorded here only for convenience; the value can always
517 * be determined by reading the main database meta pages.
519 * Value is unused, but maintained for backwards compatibility.
520 * Drop this or mtb_me_toggle when changing MDB_VERSION.
521 * (Reading both should have been done atomically.)
525 /** The number of slots that have been used in the reader table.
526 * This always records the maximum count, it is not decremented
527 * when readers release their slots.
529 unsigned mtb_numreaders;
530 /** The ID of the most recent meta page in the database.
531 * This is recorded here only for convenience; the value can always
532 * be determined by reading the main database meta pages.
534 uint32_t mtb_me_toggle;
537 /** The actual reader table definition. */
538 typedef struct MDB_txninfo {
541 #define mti_magic mt1.mtb.mtb_magic
542 #define mti_version mt1.mtb.mtb_version
543 #define mti_mutex mt1.mtb.mtb_mutex
544 #define mti_rmname mt1.mtb.mtb_rmname
546 #define mti_txnid mt1.mtb.mtb_txnid
548 #define mti_numreaders mt1.mtb.mtb_numreaders
549 #define mti_me_toggle mt1.mtb.mtb_me_toggle
550 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
553 #if defined(_WIN32) || defined(__APPLE__)
554 char mt2_wmname[MNAME_LEN];
555 #define mti_wmname mt2.mt2_wmname
557 pthread_mutex_t mt2_wmutex;
558 #define mti_wmutex mt2.mt2_wmutex
560 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
562 MDB_reader mti_readers[1];
566 /** Common header for all page types.
567 * Overflow records occupy a number of contiguous pages with no
568 * headers on any page after the first.
570 typedef struct MDB_page {
571 #define mp_pgno mp_p.p_pgno
572 #define mp_next mp_p.p_next
574 pgno_t p_pgno; /**< page number */
575 void * p_next; /**< for in-memory list of freed structs */
578 /** @defgroup mdb_page Page Flags
580 * Flags for the page headers.
583 #define P_BRANCH 0x01 /**< branch page */
584 #define P_LEAF 0x02 /**< leaf page */
585 #define P_OVERFLOW 0x04 /**< overflow page */
586 #define P_META 0x08 /**< meta page */
587 #define P_DIRTY 0x10 /**< dirty page */
588 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
589 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
591 uint16_t mp_flags; /**< @ref mdb_page */
592 #define mp_lower mp_pb.pb.pb_lower
593 #define mp_upper mp_pb.pb.pb_upper
594 #define mp_pages mp_pb.pb_pages
597 indx_t pb_lower; /**< lower bound of free space */
598 indx_t pb_upper; /**< upper bound of free space */
600 uint32_t pb_pages; /**< number of overflow pages */
602 indx_t mp_ptrs[1]; /**< dynamic size */
605 /** Size of the page header, excluding dynamic data at the end */
606 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
608 /** Address of first usable data byte in a page, after the header */
609 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
611 /** Number of nodes on a page */
612 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
614 /** The amount of space remaining in the page */
615 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
617 /** The percentage of space used in the page, in tenths of a percent. */
618 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
619 ((env)->me_psize - PAGEHDRSZ))
620 /** The minimum page fill factor, in tenths of a percent.
621 * Pages emptier than this are candidates for merging.
623 #define FILL_THRESHOLD 250
625 /** Test if a page is a leaf page */
626 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
627 /** Test if a page is a LEAF2 page */
628 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
629 /** Test if a page is a branch page */
630 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
631 /** Test if a page is an overflow page */
632 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
633 /** Test if a page is a sub page */
634 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
636 /** The number of overflow pages needed to store the given size. */
637 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
639 /** Header for a single key/data pair within a page.
640 * We guarantee 2-byte alignment for nodes.
642 typedef struct MDB_node {
643 /** lo and hi are used for data size on leaf nodes and for
644 * child pgno on branch nodes. On 64 bit platforms, flags
645 * is also used for pgno. (Branch nodes have no flags).
646 * They are in host byte order in case that lets some
647 * accesses be optimized into a 32-bit word access.
649 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
650 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
651 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
652 /** @defgroup mdb_node Node Flags
654 * Flags for node headers.
657 #define F_BIGDATA 0x01 /**< data put on overflow page */
658 #define F_SUBDATA 0x02 /**< data is a sub-database */
659 #define F_DUPDATA 0x04 /**< data has duplicates */
661 /** valid flags for #mdb_node_add() */
662 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
665 unsigned short mn_flags; /**< @ref mdb_node */
666 unsigned short mn_ksize; /**< key size */
667 char mn_data[1]; /**< key and data are appended here */
670 /** Size of the node header, excluding dynamic data at the end */
671 #define NODESIZE offsetof(MDB_node, mn_data)
673 /** Bit position of top word in page number, for shifting mn_flags */
674 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
676 /** Size of a node in a branch page with a given key.
677 * This is just the node header plus the key, there is no data.
679 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
681 /** Size of a node in a leaf page with a given key and data.
682 * This is node header plus key plus data size.
684 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
686 /** Address of node \b i in page \b p */
687 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
689 /** Address of the key for the node */
690 #define NODEKEY(node) (void *)((node)->mn_data)
692 /** Address of the data for a node */
693 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
695 /** Get the page number pointed to by a branch node */
696 #define NODEPGNO(node) \
697 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
698 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
699 /** Set the page number in a branch node */
700 #define SETPGNO(node,pgno) do { \
701 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
702 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
704 /** Get the size of the data in a leaf node */
705 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
706 /** Set the size of the data for a leaf node */
707 #define SETDSZ(node,size) do { \
708 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
709 /** The size of a key in a node */
710 #define NODEKSZ(node) ((node)->mn_ksize)
712 /** Copy a page number from src to dst */
714 #define COPY_PGNO(dst,src) dst = src
716 #if SIZE_MAX > 4294967295UL
717 #define COPY_PGNO(dst,src) do { \
718 unsigned short *s, *d; \
719 s = (unsigned short *)&(src); \
720 d = (unsigned short *)&(dst); \
727 #define COPY_PGNO(dst,src) do { \
728 unsigned short *s, *d; \
729 s = (unsigned short *)&(src); \
730 d = (unsigned short *)&(dst); \
736 /** The address of a key in a LEAF2 page.
737 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
738 * There are no node headers, keys are stored contiguously.
740 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
742 /** Set the \b node's key into \b key, if requested. */
743 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
744 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
746 /** Information about a single database in the environment. */
747 typedef struct MDB_db {
748 uint32_t md_pad; /**< also ksize for LEAF2 pages */
749 uint16_t md_flags; /**< @ref mdb_open */
750 uint16_t md_depth; /**< depth of this tree */
751 pgno_t md_branch_pages; /**< number of internal pages */
752 pgno_t md_leaf_pages; /**< number of leaf pages */
753 pgno_t md_overflow_pages; /**< number of overflow pages */
754 size_t md_entries; /**< number of data items */
755 pgno_t md_root; /**< the root page of this tree */
758 /** Handle for the DB used to track free pages. */
760 /** Handle for the default DB. */
763 /** Meta page content. */
764 typedef struct MDB_meta {
765 /** Stamp identifying this as an MDB file. It must be set
768 /** Version number of this lock file. Must be set to #MDB_VERSION. */
770 void *mm_address; /**< address for fixed mapping */
771 size_t mm_mapsize; /**< size of mmap region */
772 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
773 /** The size of pages used in this DB */
774 #define mm_psize mm_dbs[0].md_pad
775 /** Any persistent environment flags. @ref mdb_env */
776 #define mm_flags mm_dbs[0].md_flags
777 pgno_t mm_last_pg; /**< last used page in file */
778 txnid_t mm_txnid; /**< txnid that committed this page */
781 /** Buffer for a stack-allocated dirty page.
782 * The members define size and alignment, and silence type
783 * aliasing warnings. They are not used directly; that could
784 * mean incorrectly using several union members in parallel.
786 typedef union MDB_pagebuf {
787 char mb_raw[MDB_PAGESIZE];
790 char mm_pad[PAGEHDRSZ];
795 /** Auxiliary DB info.
796 * The information here is mostly static/read-only. There is
797 * only a single copy of this record in the environment.
799 typedef struct MDB_dbx {
800 MDB_val md_name; /**< name of the database */
801 MDB_cmp_func *md_cmp; /**< function for comparing keys */
802 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
803 MDB_rel_func *md_rel; /**< user relocate function */
804 void *md_relctx; /**< user-provided context for md_rel */
807 /** A database transaction.
808 * Every operation requires a transaction handle.
811 MDB_txn *mt_parent; /**< parent of a nested txn */
812 MDB_txn *mt_child; /**< nested txn under this txn */
813 pgno_t mt_next_pgno; /**< next unallocated page */
814 /** The ID of this transaction. IDs are integers incrementing from 1.
815 * Only committed write transactions increment the ID. If a transaction
816 * aborts, the ID may be re-used by the next writer.
819 MDB_env *mt_env; /**< the DB environment */
820 /** The list of pages that became unused during this transaction.
824 ID2L dirty_list; /**< modified pages */
825 MDB_reader *reader; /**< this thread's slot in the reader table */
827 /** Array of records for each DB known in the environment. */
829 /** Array of MDB_db records for each known DB */
831 /** @defgroup mt_dbflag Transaction DB Flags
835 #define DB_DIRTY 0x01 /**< DB was written in this txn */
836 #define DB_STALE 0x02 /**< DB record is older than txnID */
838 /** Array of cursors for each DB */
839 MDB_cursor **mt_cursors;
840 /** Array of flags for each DB */
841 unsigned char *mt_dbflags;
842 /** Number of DB records in use. This number only ever increments;
843 * we don't decrement it when individual DB handles are closed.
847 /** @defgroup mdb_txn Transaction Flags
851 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
852 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
854 unsigned int mt_flags; /**< @ref mdb_txn */
855 /** Tracks which of the two meta pages was used at the start
856 * of this transaction.
858 unsigned int mt_toggle;
861 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
862 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
863 * raise this on a 64 bit machine.
865 #define CURSOR_STACK 32
869 /** Cursors are used for all DB operations */
871 /** Next cursor on this DB in this txn */
873 /** Original cursor if this is a shadow */
875 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
876 struct MDB_xcursor *mc_xcursor;
877 /** The transaction that owns this cursor */
879 /** The database handle this cursor operates on */
881 /** The database record for this cursor */
883 /** The database auxiliary record for this cursor */
885 /** The @ref mt_dbflag for this database */
886 unsigned char *mc_dbflag;
887 unsigned short mc_snum; /**< number of pushed pages */
888 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
889 /** @defgroup mdb_cursor Cursor Flags
891 * Cursor state flags.
894 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
895 #define C_EOF 0x02 /**< No more data */
896 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
897 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
898 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
900 unsigned int mc_flags; /**< @ref mdb_cursor */
901 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
902 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
905 /** Context for sorted-dup records.
906 * We could have gone to a fully recursive design, with arbitrarily
907 * deep nesting of sub-databases. But for now we only handle these
908 * levels - main DB, optional sub-DB, sorted-duplicate DB.
910 typedef struct MDB_xcursor {
911 /** A sub-cursor for traversing the Dup DB */
912 MDB_cursor mx_cursor;
913 /** The database record for this Dup DB */
915 /** The auxiliary DB record for this Dup DB */
917 /** The @ref mt_dbflag for this Dup DB */
918 unsigned char mx_dbflag;
921 /** A set of pages freed by an earlier transaction. */
922 typedef struct MDB_oldpages {
923 /** Usually we only read one record from the FREEDB at a time, but
924 * in case we read more, this will chain them together.
926 struct MDB_oldpages *mo_next;
927 /** The ID of the transaction in which these pages were freed. */
929 /** An #IDL of the pages */
930 pgno_t mo_pages[1]; /* dynamic */
933 /** The database environment. */
935 HANDLE me_fd; /**< The main data file */
936 HANDLE me_lfd; /**< The lock file */
937 HANDLE me_mfd; /**< just for writing the meta pages */
938 /** Failed to update the meta page. Probably an I/O error. */
939 #define MDB_FATAL_ERROR 0x80000000U
940 uint32_t me_flags; /**< @ref mdb_env */
941 uint32_t me_extrapad; /**< unused for now */
942 unsigned int me_maxreaders; /**< size of the reader table */
943 MDB_dbi me_numdbs; /**< number of DBs opened */
944 MDB_dbi me_maxdbs; /**< size of the DB table */
945 char *me_path; /**< path to the DB files */
946 char *me_map; /**< the memory map of the data file */
947 MDB_txninfo *me_txns; /**< the memory map of the lock file */
948 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
949 MDB_txn *me_txn; /**< current write transaction */
950 size_t me_mapsize; /**< size of the data memory map */
951 off_t me_size; /**< current file size */
952 pgno_t me_maxpg; /**< me_mapsize / me_psize */
953 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
954 unsigned int me_db_toggle; /**< which DB table is current */
955 txnid_t me_wtxnid; /**< ID of last txn we committed */
956 txnid_t me_pgfirst; /**< ID of first old page record we used */
957 txnid_t me_pglast; /**< ID of last old page record we used */
958 MDB_dbx *me_dbxs; /**< array of static DB info */
959 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
960 MDB_oldpages *me_pghead; /**< list of old page records */
961 pthread_key_t me_txkey; /**< thread-key for readers */
962 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
963 /** IDL of pages that became unused in a write txn */
965 /** ID2L of pages that were written during a write txn */
966 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
967 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
968 LAZY_RWLOCK_DEF(me_dblock)
970 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
974 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
978 /** max number of pages to commit in one writev() call */
979 #define MDB_COMMIT_PAGES 64
980 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
981 #undef MDB_COMMIT_PAGES
982 #define MDB_COMMIT_PAGES IOV_MAX
985 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
986 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
987 static int mdb_page_touch(MDB_cursor *mc);
989 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
990 static int mdb_page_search_root(MDB_cursor *mc,
991 MDB_val *key, int modify);
992 static int mdb_page_search(MDB_cursor *mc,
993 MDB_val *key, int modify);
994 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
995 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
996 pgno_t newpgno, unsigned int nflags);
998 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
999 static int mdb_env_pick_meta(const MDB_env *env);
1000 static int mdb_env_write_meta(MDB_txn *txn);
1002 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1003 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1004 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1005 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1006 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1007 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1008 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1009 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1010 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1012 static int mdb_rebalance(MDB_cursor *mc);
1013 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
1015 static void mdb_cursor_pop(MDB_cursor *mc);
1016 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1018 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1019 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1020 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1021 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1022 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1024 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1025 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1027 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1028 static void mdb_xcursor_init0(MDB_cursor *mc);
1029 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1031 static int mdb_drop0(MDB_cursor *mc, int subs);
1032 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1035 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1039 static SECURITY_DESCRIPTOR mdb_null_sd;
1040 static SECURITY_ATTRIBUTES mdb_all_sa;
1041 static int mdb_sec_inited;
1044 /** Return the library version info. */
1046 mdb_version(int *major, int *minor, int *patch)
1048 if (major) *major = MDB_VERSION_MAJOR;
1049 if (minor) *minor = MDB_VERSION_MINOR;
1050 if (patch) *patch = MDB_VERSION_PATCH;
1051 return MDB_VERSION_STRING;
1054 /** Table of descriptions for MDB @ref errors */
1055 static char *const mdb_errstr[] = {
1056 "MDB_KEYEXIST: Key/data pair already exists",
1057 "MDB_NOTFOUND: No matching key/data pair found",
1058 "MDB_PAGE_NOTFOUND: Requested page not found",
1059 "MDB_CORRUPTED: Located page was wrong type",
1060 "MDB_PANIC: Update of meta page failed",
1061 "MDB_VERSION_MISMATCH: Database environment version mismatch"
1065 mdb_strerror(int err)
1068 return ("Successful return: 0");
1070 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1071 return mdb_errstr[err - MDB_KEYEXIST];
1073 return strerror(err);
1077 /** Display a key in hexadecimal and return the address of the result.
1078 * @param[in] key the key to display
1079 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1080 * @return The key in hexadecimal form.
1083 mdb_dkey(MDB_val *key, char *buf)
1086 unsigned char *c = key->mv_data;
1088 if (key->mv_size > MAXKEYSIZE)
1089 return "MAXKEYSIZE";
1090 /* may want to make this a dynamic check: if the key is mostly
1091 * printable characters, print it as-is instead of converting to hex.
1095 for (i=0; i<key->mv_size; i++)
1096 ptr += sprintf(ptr, "%02x", *c++);
1098 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1103 /** Display all the keys in the page. */
1105 mdb_page_keys(MDB_page *mp)
1108 unsigned int i, nkeys;
1112 nkeys = NUMKEYS(mp);
1113 DPRINTF("numkeys %d", nkeys);
1114 for (i=0; i<nkeys; i++) {
1115 node = NODEPTR(mp, i);
1116 key.mv_size = node->mn_ksize;
1117 key.mv_data = node->mn_data;
1118 DPRINTF("key %d: %s", i, DKEY(&key));
1124 /** Count all the pages in each DB and in the freelist
1125 * and make sure it matches the actual number of pages
1128 static void mdb_audit(MDB_txn *txn)
1134 ID freecount, count;
1137 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1138 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1139 freecount += *(ID *)data.mv_data;
1140 freecount += txn->mt_dbs[0].md_branch_pages + txn->mt_dbs[0].md_leaf_pages +
1141 txn->mt_dbs[0].md_overflow_pages;
1144 for (i = 0; i<txn->mt_numdbs; i++) {
1145 count += txn->mt_dbs[i].md_branch_pages +
1146 txn->mt_dbs[i].md_leaf_pages +
1147 txn->mt_dbs[i].md_overflow_pages;
1148 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1150 mdb_cursor_init(&mc, txn, i, &mx);
1151 mdb_page_search(&mc, NULL, 0);
1155 mp = mc.mc_pg[mc.mc_top];
1156 for (j=0; j<NUMKEYS(mp); j++) {
1157 MDB_node *leaf = NODEPTR(mp, j);
1158 if (leaf->mn_flags & F_SUBDATA) {
1160 memcpy(&db, NODEDATA(leaf), sizeof(db));
1161 count += db.md_branch_pages + db.md_leaf_pages +
1162 db.md_overflow_pages;
1166 while (mdb_cursor_sibling(&mc, 1) == 0);
1169 assert(freecount + count + 2 >= txn->mt_next_pgno - 1);
1174 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1176 return txn->mt_dbxs[dbi].md_cmp(a, b);
1180 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1182 if (txn->mt_dbxs[dbi].md_dcmp)
1183 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1185 return EINVAL; /* too bad you can't distinguish this from a valid result */
1188 /** Allocate a single page.
1189 * Re-use old malloc'd pages first, otherwise just malloc.
1192 mdb_page_malloc(MDB_cursor *mc) {
1194 size_t sz = mc->mc_txn->mt_env->me_psize;
1195 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1196 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1197 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1198 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1199 } else if ((ret = malloc(sz)) != NULL) {
1200 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1205 /** Allocate pages for writing.
1206 * If there are free pages available from older transactions, they
1207 * will be re-used first. Otherwise a new page will be allocated.
1208 * @param[in] mc cursor A cursor handle identifying the transaction and
1209 * database for which we are allocating.
1210 * @param[in] num the number of pages to allocate.
1211 * @return Address of the allocated page(s). Requests for multiple pages
1212 * will always be satisfied by a single contiguous chunk of memory.
1215 mdb_page_alloc(MDB_cursor *mc, int num)
1217 MDB_txn *txn = mc->mc_txn;
1219 pgno_t pgno = P_INVALID;
1222 if (txn->mt_txnid > 2) {
1224 if (!txn->mt_env->me_pghead &&
1225 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1226 /* See if there's anything in the free DB */
1230 txnid_t *kptr, oldest, last;
1232 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1233 if (!txn->mt_env->me_pgfirst) {
1234 mdb_page_search(&m2, NULL, 0);
1235 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1236 kptr = (txnid_t *)NODEKEY(leaf);
1243 last = txn->mt_env->me_pglast + 1;
1245 key.mv_data = &last;
1246 key.mv_size = sizeof(last);
1247 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1250 last = *(txnid_t *)key.mv_data;
1255 oldest = txn->mt_txnid - 1;
1256 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1257 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1258 if (mr && mr < oldest)
1263 if (oldest > last) {
1264 /* It's usable, grab it.
1269 if (!txn->mt_env->me_pgfirst) {
1270 mdb_node_read(txn, leaf, &data);
1272 txn->mt_env->me_pglast = last;
1273 if (!txn->mt_env->me_pgfirst)
1274 txn->mt_env->me_pgfirst = last;
1275 idl = (ID *) data.mv_data;
1276 /* We might have a zero-length IDL due to freelist growth
1277 * during a prior commit
1279 if (!idl[0]) goto again;
1280 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1281 mop->mo_next = txn->mt_env->me_pghead;
1282 mop->mo_txnid = last;
1283 txn->mt_env->me_pghead = mop;
1284 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1289 DPRINTF("IDL read txn %zu root %zu num %zu",
1290 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1291 for (i=0; i<idl[0]; i++) {
1292 DPRINTF("IDL %zu", idl[i+1]);
1299 if (txn->mt_env->me_pghead) {
1300 MDB_oldpages *mop = txn->mt_env->me_pghead;
1302 /* FIXME: For now, always use fresh pages. We
1303 * really ought to search the free list for a
1308 /* peel pages off tail, so we only have to truncate the list */
1309 pgno = MDB_IDL_LAST(mop->mo_pages);
1310 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1312 if (mop->mo_pages[2] > mop->mo_pages[1])
1313 mop->mo_pages[0] = 0;
1317 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1318 txn->mt_env->me_pghead = mop->mo_next;
1325 if (pgno == P_INVALID) {
1326 /* DB size is maxed out */
1327 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1328 DPUTS("DB size maxed out");
1332 if (txn->mt_env->me_dpages && num == 1) {
1333 np = txn->mt_env->me_dpages;
1334 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1335 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1336 txn->mt_env->me_dpages = np->mp_next;
1338 size_t sz = txn->mt_env->me_psize * num;
1339 if ((np = malloc(sz)) == NULL)
1341 VGMEMP_ALLOC(txn->mt_env, np, sz);
1343 if (pgno == P_INVALID) {
1344 np->mp_pgno = txn->mt_next_pgno;
1345 txn->mt_next_pgno += num;
1349 mid.mid = np->mp_pgno;
1351 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1356 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1357 * @param[in] mc cursor pointing to the page to be touched
1358 * @return 0 on success, non-zero on failure.
1361 mdb_page_touch(MDB_cursor *mc)
1363 MDB_page *mp = mc->mc_pg[mc->mc_top];
1366 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1368 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1370 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1371 assert(mp->mp_pgno != np->mp_pgno);
1372 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1374 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1377 mp->mp_flags |= P_DIRTY;
1380 /* Adjust other cursors pointing to mp */
1381 if (mc->mc_flags & C_SUB) {
1382 MDB_cursor *m2, *m3;
1383 MDB_dbi dbi = mc->mc_dbi-1;
1385 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1386 if (m2 == mc) continue;
1387 m3 = &m2->mc_xcursor->mx_cursor;
1388 if (m3->mc_snum < mc->mc_snum) continue;
1389 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1390 m3->mc_pg[mc->mc_top] = mp;
1396 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1397 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1398 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1399 m2->mc_pg[mc->mc_top] = mp;
1403 mc->mc_pg[mc->mc_top] = mp;
1404 /** If this page has a parent, update the parent to point to
1408 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1410 mc->mc_db->md_root = mp->mp_pgno;
1411 } else if (mc->mc_txn->mt_parent) {
1414 /* If txn has a parent, make sure the page is in our
1417 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1418 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1419 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1420 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1421 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1422 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1423 mc->mc_pg[mc->mc_top] = mp;
1429 np = mdb_page_malloc(mc);
1430 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1431 mid.mid = np->mp_pgno;
1433 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1441 mdb_env_sync(MDB_env *env, int force)
1444 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1445 if (MDB_FDATASYNC(env->me_fd))
1451 /** Make shadow copies of all of parent txn's cursors */
1453 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1455 MDB_cursor *mc, *m2;
1456 unsigned int i, j, size;
1458 for (i=0;i<src->mt_numdbs; i++) {
1459 if (src->mt_cursors[i]) {
1460 size = sizeof(MDB_cursor);
1461 if (src->mt_cursors[i]->mc_xcursor)
1462 size += sizeof(MDB_xcursor);
1463 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1470 mc->mc_db = &dst->mt_dbs[i];
1471 mc->mc_dbx = m2->mc_dbx;
1472 mc->mc_dbflag = &dst->mt_dbflags[i];
1473 mc->mc_snum = m2->mc_snum;
1474 mc->mc_top = m2->mc_top;
1475 mc->mc_flags = m2->mc_flags | C_SHADOW;
1476 for (j=0; j<mc->mc_snum; j++) {
1477 mc->mc_pg[j] = m2->mc_pg[j];
1478 mc->mc_ki[j] = m2->mc_ki[j];
1480 if (m2->mc_xcursor) {
1481 MDB_xcursor *mx, *mx2;
1482 mx = (MDB_xcursor *)(mc+1);
1483 mc->mc_xcursor = mx;
1484 mx2 = m2->mc_xcursor;
1485 mx->mx_db = mx2->mx_db;
1486 mx->mx_dbx = mx2->mx_dbx;
1487 mx->mx_dbflag = mx2->mx_dbflag;
1488 mx->mx_cursor.mc_txn = dst;
1489 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1490 mx->mx_cursor.mc_db = &mx->mx_db;
1491 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1492 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1493 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1494 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1495 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1496 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1497 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1498 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1501 mc->mc_xcursor = NULL;
1503 mc->mc_next = dst->mt_cursors[i];
1504 dst->mt_cursors[i] = mc;
1511 /** Merge shadow cursors back into parent's */
1513 mdb_cursor_merge(MDB_txn *txn)
1516 for (i=0; i<txn->mt_numdbs; i++) {
1517 if (txn->mt_cursors[i]) {
1519 while ((mc = txn->mt_cursors[i])) {
1520 txn->mt_cursors[i] = mc->mc_next;
1521 if (mc->mc_flags & C_SHADOW) {
1522 MDB_cursor *m2 = mc->mc_orig;
1524 m2->mc_snum = mc->mc_snum;
1525 m2->mc_top = mc->mc_top;
1526 for (j=0; j<mc->mc_snum; j++) {
1527 m2->mc_pg[j] = mc->mc_pg[j];
1528 m2->mc_ki[j] = mc->mc_ki[j];
1531 if (mc->mc_flags & C_ALLOCD)
1539 mdb_txn_reset0(MDB_txn *txn);
1541 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1542 * @param[in] txn the transaction handle to initialize
1543 * @return 0 on success, non-zero on failure. This can only
1544 * fail for read-only transactions, and then only if the
1545 * reader table is full.
1548 mdb_txn_renew0(MDB_txn *txn)
1550 MDB_env *env = txn->mt_env;
1553 if (txn->mt_flags & MDB_TXN_RDONLY) {
1554 MDB_reader *r = pthread_getspecific(env->me_txkey);
1557 pid_t pid = getpid();
1558 pthread_t tid = pthread_self();
1561 for (i=0; i<env->me_txns->mti_numreaders; i++)
1562 if (env->me_txns->mti_readers[i].mr_pid == 0)
1564 if (i == env->me_maxreaders) {
1565 UNLOCK_MUTEX_R(env);
1568 env->me_txns->mti_readers[i].mr_pid = pid;
1569 env->me_txns->mti_readers[i].mr_tid = tid;
1570 if (i >= env->me_txns->mti_numreaders)
1571 env->me_txns->mti_numreaders = i+1;
1572 UNLOCK_MUTEX_R(env);
1573 r = &env->me_txns->mti_readers[i];
1574 pthread_setspecific(env->me_txkey, r);
1576 txn->mt_toggle = env->me_txns->mti_me_toggle;
1577 txn->mt_txnid = r->mr_txnid = env->me_metas[txn->mt_toggle]->mm_txnid;
1579 /* This happens if a different process was the
1580 * last writer to the DB.
1582 if (env->me_wtxnid < txn->mt_txnid)
1583 mt_dbflag = DB_STALE;
1584 txn->mt_u.reader = r;
1588 txn->mt_toggle = env->me_txns->mti_me_toggle;
1589 txn->mt_txnid = env->me_metas[txn->mt_toggle]->mm_txnid;
1590 if (env->me_wtxnid < txn->mt_txnid)
1591 mt_dbflag = DB_STALE;
1594 if (txn->mt_txnid == mdb_debug_start)
1597 txn->mt_u.dirty_list = env->me_dirty_list;
1598 txn->mt_u.dirty_list[0].mid = 0;
1599 txn->mt_free_pgs = env->me_free_pgs;
1600 txn->mt_free_pgs[0] = 0;
1601 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1605 /* Copy the DB arrays */
1606 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1607 txn->mt_numdbs = env->me_numdbs;
1608 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1609 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1610 if (txn->mt_numdbs > 2)
1611 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1612 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1613 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1615 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1621 mdb_txn_renew(MDB_txn *txn)
1628 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1629 DPUTS("environment had fatal error, must shutdown!");
1633 rc = mdb_txn_renew0(txn);
1634 if (rc == MDB_SUCCESS) {
1635 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1636 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1637 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1643 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1648 if (env->me_flags & MDB_FATAL_ERROR) {
1649 DPUTS("environment had fatal error, must shutdown!");
1653 /* parent already has an active child txn */
1654 if (parent->mt_child) {
1658 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1659 if (!(flags & MDB_RDONLY))
1660 size += env->me_maxdbs * sizeof(MDB_cursor *);
1662 if ((txn = calloc(1, size)) == NULL) {
1663 DPRINTF("calloc: %s", strerror(ErrCode()));
1666 txn->mt_dbs = (MDB_db *)(txn+1);
1667 if (flags & MDB_RDONLY) {
1668 txn->mt_flags |= MDB_TXN_RDONLY;
1669 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1671 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1672 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1677 txn->mt_free_pgs = mdb_midl_alloc();
1678 if (!txn->mt_free_pgs) {
1682 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1683 if (!txn->mt_u.dirty_list) {
1684 free(txn->mt_free_pgs);
1688 txn->mt_txnid = parent->mt_txnid;
1689 txn->mt_toggle = parent->mt_toggle;
1690 txn->mt_u.dirty_list[0].mid = 0;
1691 txn->mt_free_pgs[0] = 0;
1692 txn->mt_next_pgno = parent->mt_next_pgno;
1693 parent->mt_child = txn;
1694 txn->mt_parent = parent;
1695 txn->mt_numdbs = parent->mt_numdbs;
1696 txn->mt_dbxs = parent->mt_dbxs;
1697 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1698 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1699 mdb_cursor_shadow(parent, txn);
1702 rc = mdb_txn_renew0(txn);
1708 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1709 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1710 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1716 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1717 * @param[in] txn the transaction handle to reset
1720 mdb_txn_reset0(MDB_txn *txn)
1722 MDB_env *env = txn->mt_env;
1724 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1725 txn->mt_u.reader->mr_txnid = 0;
1731 /* close(free) all cursors */
1732 for (i=0; i<txn->mt_numdbs; i++) {
1733 if (txn->mt_cursors[i]) {
1735 while ((mc = txn->mt_cursors[i])) {
1736 txn->mt_cursors[i] = mc->mc_next;
1737 if (mc->mc_flags & C_ALLOCD)
1743 /* return all dirty pages to dpage list */
1744 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1745 dp = txn->mt_u.dirty_list[i].mptr;
1746 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1747 dp->mp_next = txn->mt_env->me_dpages;
1748 VGMEMP_FREE(txn->mt_env, dp);
1749 txn->mt_env->me_dpages = dp;
1751 /* large pages just get freed directly */
1752 VGMEMP_FREE(txn->mt_env, dp);
1757 if (txn->mt_parent) {
1758 txn->mt_parent->mt_child = NULL;
1759 free(txn->mt_free_pgs);
1760 free(txn->mt_u.dirty_list);
1763 if (mdb_midl_shrink(&txn->mt_free_pgs))
1764 env->me_free_pgs = txn->mt_free_pgs;
1767 while ((mop = txn->mt_env->me_pghead)) {
1768 txn->mt_env->me_pghead = mop->mo_next;
1771 txn->mt_env->me_pgfirst = 0;
1772 txn->mt_env->me_pglast = 0;
1775 /* The writer mutex was locked in mdb_txn_begin. */
1776 UNLOCK_MUTEX_W(env);
1781 mdb_txn_reset(MDB_txn *txn)
1786 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1787 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1788 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1790 mdb_txn_reset0(txn);
1794 mdb_txn_abort(MDB_txn *txn)
1799 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1800 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1801 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1804 mdb_txn_abort(txn->mt_child);
1806 mdb_txn_reset0(txn);
1811 mdb_txn_commit(MDB_txn *txn)
1819 pgno_t next, freecnt;
1822 assert(txn != NULL);
1823 assert(txn->mt_env != NULL);
1825 if (txn->mt_child) {
1826 mdb_txn_commit(txn->mt_child);
1827 txn->mt_child = NULL;
1832 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1833 if (txn->mt_numdbs > env->me_numdbs) {
1834 /* update the DB tables */
1835 int toggle = !env->me_db_toggle;
1839 ip = &env->me_dbs[toggle][env->me_numdbs];
1840 jp = &txn->mt_dbs[env->me_numdbs];
1841 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1842 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1846 env->me_db_toggle = toggle;
1847 env->me_numdbs = txn->mt_numdbs;
1848 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1854 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1855 DPUTS("error flag is set, can't commit");
1857 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1862 /* Merge (and close) our cursors with parent's */
1863 mdb_cursor_merge(txn);
1865 if (txn->mt_parent) {
1871 /* Update parent's DB table */
1872 ip = &txn->mt_parent->mt_dbs[2];
1873 jp = &txn->mt_dbs[2];
1874 for (i = 2; i < txn->mt_numdbs; i++) {
1875 if (ip->md_root != jp->md_root)
1879 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1881 /* Append our free list to parent's */
1882 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1884 mdb_midl_free(txn->mt_free_pgs);
1886 /* Merge our dirty list with parent's */
1887 dst = txn->mt_parent->mt_u.dirty_list;
1888 src = txn->mt_u.dirty_list;
1889 x = mdb_mid2l_search(dst, src[1].mid);
1890 for (y=1; y<=src[0].mid; y++) {
1891 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1895 dst[x].mptr = src[y].mptr;
1898 for (; y<=src[0].mid; y++) {
1899 if (++x >= MDB_IDL_UM_MAX) {
1906 free(txn->mt_u.dirty_list);
1907 txn->mt_parent->mt_child = NULL;
1912 if (txn != env->me_txn) {
1913 DPUTS("attempt to commit unknown transaction");
1918 if (!txn->mt_u.dirty_list[0].mid)
1921 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1922 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1924 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1926 /* should only be one record now */
1927 if (env->me_pghead) {
1928 /* make sure first page of freeDB is touched and on freelist */
1929 mdb_page_search(&mc, NULL, 1);
1932 /* Delete IDLs we used from the free list */
1933 if (env->me_pgfirst) {
1938 key.mv_size = sizeof(cur);
1939 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1942 mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1943 mdb_cursor_del(&mc, 0);
1945 env->me_pgfirst = 0;
1949 /* save to free list */
1951 freecnt = txn->mt_free_pgs[0];
1952 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1955 /* make sure last page of freeDB is touched and on freelist */
1956 key.mv_size = MAXKEYSIZE+1;
1958 mdb_page_search(&mc, &key, 1);
1960 mdb_midl_sort(txn->mt_free_pgs);
1964 ID *idl = txn->mt_free_pgs;
1965 DPRINTF("IDL write txn %zu root %zu num %zu",
1966 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1967 for (i=0; i<idl[0]; i++) {
1968 DPRINTF("IDL %zu", idl[i+1]);
1972 /* write to last page of freeDB */
1973 key.mv_size = sizeof(pgno_t);
1974 key.mv_data = &txn->mt_txnid;
1975 data.mv_data = txn->mt_free_pgs;
1976 /* The free list can still grow during this call,
1977 * despite the pre-emptive touches above. So check
1978 * and make sure the entire thing got written.
1981 freecnt = txn->mt_free_pgs[0];
1982 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1983 rc = mdb_cursor_put(&mc, &key, &data, 0);
1988 } while (freecnt != txn->mt_free_pgs[0]);
1990 /* should only be one record now */
1992 if (env->me_pghead) {
1998 mop = env->me_pghead;
2000 key.mv_size = sizeof(id);
2002 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2003 data.mv_data = mop->mo_pages;
2004 orig = mop->mo_pages[0];
2005 /* These steps may grow the freelist again
2006 * due to freed overflow pages...
2008 mdb_cursor_put(&mc, &key, &data, 0);
2009 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
2010 /* could have been used again here */
2011 if (mop->mo_pages[0] != orig) {
2012 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2013 data.mv_data = mop->mo_pages;
2015 mdb_cursor_put(&mc, &key, &data, 0);
2017 env->me_pghead = NULL;
2020 /* was completely used up */
2021 mdb_cursor_del(&mc, 0);
2025 env->me_pgfirst = 0;
2028 /* Check for growth of freelist again */
2029 if (freecnt != txn->mt_free_pgs[0])
2032 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2033 if (mdb_midl_shrink(&txn->mt_free_pgs))
2034 env->me_free_pgs = txn->mt_free_pgs;
2037 /* Update DB root pointers. Their pages have already been
2038 * touched so this is all in-place and cannot fail.
2043 data.mv_size = sizeof(MDB_db);
2045 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2046 for (i = 2; i < txn->mt_numdbs; i++) {
2047 if (txn->mt_dbflags[i] & DB_DIRTY) {
2048 data.mv_data = &txn->mt_dbs[i];
2049 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2057 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2063 /* Windows actually supports scatter/gather I/O, but only on
2064 * unbuffered file handles. Since we're relying on the OS page
2065 * cache for all our data, that's self-defeating. So we just
2066 * write pages one at a time. We use the ov structure to set
2067 * the write offset, to at least save the overhead of a Seek
2071 memset(&ov, 0, sizeof(ov));
2072 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2074 dp = txn->mt_u.dirty_list[i].mptr;
2075 DPRINTF("committing page %zu", dp->mp_pgno);
2076 size = dp->mp_pgno * env->me_psize;
2077 ov.Offset = size & 0xffffffff;
2078 ov.OffsetHigh = size >> 16;
2079 ov.OffsetHigh >>= 16;
2080 /* clear dirty flag */
2081 dp->mp_flags &= ~P_DIRTY;
2082 wsize = env->me_psize;
2083 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2084 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2087 DPRINTF("WriteFile: %d", n);
2094 struct iovec iov[MDB_COMMIT_PAGES];
2098 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2099 dp = txn->mt_u.dirty_list[i].mptr;
2100 if (dp->mp_pgno != next) {
2102 rc = writev(env->me_fd, iov, n);
2106 DPUTS("short write, filesystem full?");
2108 DPRINTF("writev: %s", strerror(n));
2115 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2118 DPRINTF("committing page %zu", dp->mp_pgno);
2119 iov[n].iov_len = env->me_psize;
2120 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2121 iov[n].iov_base = (char *)dp;
2122 size += iov[n].iov_len;
2123 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2124 /* clear dirty flag */
2125 dp->mp_flags &= ~P_DIRTY;
2126 if (++n >= MDB_COMMIT_PAGES) {
2136 rc = writev(env->me_fd, iov, n);
2140 DPUTS("short write, filesystem full?");
2142 DPRINTF("writev: %s", strerror(n));
2149 /* Drop the dirty pages.
2151 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2152 dp = txn->mt_u.dirty_list[i].mptr;
2153 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2154 dp->mp_next = txn->mt_env->me_dpages;
2155 VGMEMP_FREE(txn->mt_env, dp);
2156 txn->mt_env->me_dpages = dp;
2158 VGMEMP_FREE(txn->mt_env, dp);
2161 txn->mt_u.dirty_list[i].mid = 0;
2163 txn->mt_u.dirty_list[0].mid = 0;
2165 if ((n = mdb_env_sync(env, 0)) != 0 ||
2166 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2170 env->me_wtxnid = txn->mt_txnid;
2174 /* update the DB tables */
2176 int toggle = !env->me_db_toggle;
2180 ip = &env->me_dbs[toggle][2];
2181 jp = &txn->mt_dbs[2];
2182 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
2183 for (i = 2; i < txn->mt_numdbs; i++) {
2184 if (ip->md_root != jp->md_root)
2189 env->me_db_toggle = toggle;
2190 env->me_numdbs = txn->mt_numdbs;
2191 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
2194 UNLOCK_MUTEX_W(env);
2200 /** Read the environment parameters of a DB environment before
2201 * mapping it into memory.
2202 * @param[in] env the environment handle
2203 * @param[out] meta address of where to store the meta information
2204 * @return 0 on success, non-zero on failure.
2207 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2214 /* We don't know the page size yet, so use a minimum value.
2218 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2220 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2225 else if (rc != MDB_PAGESIZE) {
2229 DPRINTF("read: %s", strerror(err));
2233 p = (MDB_page *)&pbuf;
2235 if (!F_ISSET(p->mp_flags, P_META)) {
2236 DPRINTF("page %zu not a meta page", p->mp_pgno);
2241 if (m->mm_magic != MDB_MAGIC) {
2242 DPUTS("meta has invalid magic");
2246 if (m->mm_version != MDB_VERSION) {
2247 DPRINTF("database is version %u, expected version %u",
2248 m->mm_version, MDB_VERSION);
2249 return MDB_VERSION_MISMATCH;
2252 memcpy(meta, m, sizeof(*m));
2256 /** Write the environment parameters of a freshly created DB environment.
2257 * @param[in] env the environment handle
2258 * @param[out] meta address of where to store the meta information
2259 * @return 0 on success, non-zero on failure.
2262 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2269 DPUTS("writing new meta page");
2271 GET_PAGESIZE(psize);
2273 meta->mm_magic = MDB_MAGIC;
2274 meta->mm_version = MDB_VERSION;
2275 meta->mm_psize = psize;
2276 meta->mm_last_pg = 1;
2277 meta->mm_flags = env->me_flags & 0xffff;
2278 meta->mm_flags |= MDB_INTEGERKEY;
2279 meta->mm_dbs[0].md_root = P_INVALID;
2280 meta->mm_dbs[1].md_root = P_INVALID;
2282 p = calloc(2, psize);
2284 p->mp_flags = P_META;
2287 memcpy(m, meta, sizeof(*meta));
2289 q = (MDB_page *)((char *)p + psize);
2292 q->mp_flags = P_META;
2295 memcpy(m, meta, sizeof(*meta));
2300 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2301 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2304 rc = write(env->me_fd, p, psize * 2);
2305 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2311 /** Update the environment info to commit a transaction.
2312 * @param[in] txn the transaction that's being committed
2313 * @return 0 on success, non-zero on failure.
2316 mdb_env_write_meta(MDB_txn *txn)
2319 MDB_meta meta, metab;
2321 int rc, len, toggle;
2327 assert(txn != NULL);
2328 assert(txn->mt_env != NULL);
2330 toggle = !txn->mt_toggle;
2331 DPRINTF("writing meta page %d for root page %zu",
2332 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2336 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2337 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2339 ptr = (char *)&meta;
2340 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2341 len = sizeof(MDB_meta) - off;
2344 meta.mm_dbs[0] = txn->mt_dbs[0];
2345 meta.mm_dbs[1] = txn->mt_dbs[1];
2346 meta.mm_last_pg = txn->mt_next_pgno - 1;
2347 meta.mm_txnid = txn->mt_txnid;
2350 off += env->me_psize;
2353 /* Write to the SYNC fd */
2356 memset(&ov, 0, sizeof(ov));
2358 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2361 rc = pwrite(env->me_mfd, ptr, len, off);
2366 DPUTS("write failed, disk error?");
2367 /* On a failure, the pagecache still contains the new data.
2368 * Write some old data back, to prevent it from being used.
2369 * Use the non-SYNC fd; we know it will fail anyway.
2371 meta.mm_last_pg = metab.mm_last_pg;
2372 meta.mm_txnid = metab.mm_txnid;
2374 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2376 r2 = pwrite(env->me_fd, ptr, len, off);
2378 env->me_flags |= MDB_FATAL_ERROR;
2381 /* Memory ordering issues are irrelevant; since the entire writer
2382 * is wrapped by wmutex, all of these changes will become visible
2383 * after the wmutex is unlocked. Since the DB is multi-version,
2384 * readers will get consistent data regardless of how fresh or
2385 * how stale their view of these values is.
2387 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2388 txn->mt_env->me_txns->mti_me_toggle = toggle;
2389 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2390 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2395 /** Check both meta pages to see which one is newer.
2396 * @param[in] env the environment handle
2397 * @return meta toggle (0 or 1).
2400 mdb_env_pick_meta(const MDB_env *env)
2402 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2406 mdb_env_create(MDB_env **env)
2410 e = calloc(1, sizeof(MDB_env));
2414 e->me_free_pgs = mdb_midl_alloc();
2415 if (!e->me_free_pgs) {
2419 e->me_maxreaders = DEFAULT_READERS;
2421 e->me_fd = INVALID_HANDLE_VALUE;
2422 e->me_lfd = INVALID_HANDLE_VALUE;
2423 e->me_mfd = INVALID_HANDLE_VALUE;
2424 VGMEMP_CREATE(e,0,0);
2430 mdb_env_set_mapsize(MDB_env *env, size_t size)
2434 env->me_mapsize = size;
2436 env->me_maxpg = env->me_mapsize / env->me_psize;
2441 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2445 env->me_maxdbs = dbs;
2450 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2452 if (env->me_map || readers < 1)
2454 env->me_maxreaders = readers;
2459 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2461 if (!env || !readers)
2463 *readers = env->me_maxreaders;
2467 /** Further setup required for opening an MDB environment
2470 mdb_env_open2(MDB_env *env, unsigned int flags)
2476 env->me_flags = flags;
2478 memset(&meta, 0, sizeof(meta));
2480 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2483 DPUTS("new mdbenv");
2487 if (!env->me_mapsize) {
2488 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2494 LONG sizelo, sizehi;
2495 sizelo = env->me_mapsize & 0xffffffff;
2496 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2498 /* Windows won't create mappings for zero length files.
2499 * Just allocate the maxsize right now.
2502 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2503 if (!SetEndOfFile(env->me_fd))
2505 SetFilePointer(env->me_fd, 0, NULL, 0);
2507 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2508 sizehi, sizelo, NULL);
2511 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2519 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2521 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2523 if (env->me_map == MAP_FAILED) {
2530 meta.mm_mapsize = env->me_mapsize;
2531 if (flags & MDB_FIXEDMAP)
2532 meta.mm_address = env->me_map;
2533 i = mdb_env_init_meta(env, &meta);
2534 if (i != MDB_SUCCESS) {
2535 munmap(env->me_map, env->me_mapsize);
2539 env->me_psize = meta.mm_psize;
2541 env->me_maxpg = env->me_mapsize / env->me_psize;
2543 p = (MDB_page *)env->me_map;
2544 env->me_metas[0] = METADATA(p);
2545 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2549 int toggle = mdb_env_pick_meta(env);
2550 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2552 DPRINTF("opened database version %u, pagesize %u",
2553 env->me_metas[0]->mm_version, env->me_psize);
2554 DPRINTF("using meta page %d", toggle);
2555 DPRINTF("depth: %u", db->md_depth);
2556 DPRINTF("entries: %zu", db->md_entries);
2557 DPRINTF("branch pages: %zu", db->md_branch_pages);
2558 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2559 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2560 DPRINTF("root: %zu", db->md_root);
2569 /** Release a reader thread's slot in the reader lock table.
2570 * This function is called automatically when a thread exits.
2571 * Windows doesn't support destructor callbacks for thread-specific storage,
2572 * so this function is not compiled there.
2573 * @param[in] ptr This points to the slot in the reader lock table.
2576 mdb_env_reader_dest(void *ptr)
2578 MDB_reader *reader = ptr;
2580 reader->mr_txnid = 0;
2586 /** Downgrade the exclusive lock on the region back to shared */
2588 mdb_env_share_locks(MDB_env *env)
2590 int toggle = mdb_env_pick_meta(env);
2592 env->me_txns->mti_me_toggle = toggle;
2593 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2598 /* First acquire a shared lock. The Unlock will
2599 * then release the existing exclusive lock.
2601 memset(&ov, 0, sizeof(ov));
2602 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2603 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2607 struct flock lock_info;
2608 /* The shared lock replaces the existing lock */
2609 memset((void *)&lock_info, 0, sizeof(lock_info));
2610 lock_info.l_type = F_RDLCK;
2611 lock_info.l_whence = SEEK_SET;
2612 lock_info.l_start = 0;
2613 lock_info.l_len = 1;
2614 fcntl(env->me_lfd, F_SETLK, &lock_info);
2618 #if defined(_WIN32) || defined(__APPLE__)
2620 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2622 * @(#) $Revision: 5.1 $
2623 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2624 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2626 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2630 * Please do not copyright this code. This code is in the public domain.
2632 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2633 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2634 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2635 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2636 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2637 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2638 * PERFORMANCE OF THIS SOFTWARE.
2641 * chongo <Landon Curt Noll> /\oo/\
2642 * http://www.isthe.com/chongo/
2644 * Share and Enjoy! :-)
2647 typedef unsigned long long mdb_hash_t;
2648 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2650 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2651 * @param[in] str string to hash
2652 * @param[in] hval initial value for hash
2653 * @return 64 bit hash
2655 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2656 * hval arg on the first call.
2659 mdb_hash_str(char *str, mdb_hash_t hval)
2661 unsigned char *s = (unsigned char *)str; /* unsigned string */
2663 * FNV-1a hash each octet of the string
2666 /* xor the bottom with the current octet */
2667 hval ^= (mdb_hash_t)*s++;
2669 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2670 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2671 (hval << 7) + (hval << 8) + (hval << 40);
2673 /* return our new hash value */
2677 /** Hash the string and output the hash in hex.
2678 * @param[in] str string to hash
2679 * @param[out] hexbuf an array of 17 chars to hold the hash
2682 mdb_hash_hex(char *str, char *hexbuf)
2685 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2686 for (i=0; i<8; i++) {
2687 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2693 /** Open and/or initialize the lock region for the environment.
2694 * @param[in] env The MDB environment.
2695 * @param[in] lpath The pathname of the file used for the lock region.
2696 * @param[in] mode The Unix permissions for the file, if we create it.
2697 * @param[out] excl Set to true if we got an exclusive lock on the region.
2698 * @return 0 on success, non-zero on failure.
2701 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2709 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2710 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2711 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2715 /* Try to get exclusive lock. If we succeed, then
2716 * nobody is using the lock region and we should initialize it.
2719 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2723 memset(&ov, 0, sizeof(ov));
2724 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2730 size = GetFileSize(env->me_lfd, NULL);
2736 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1)
2738 /* Lose record locks when exec*() */
2739 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
2740 fcntl(env->me_lfd, F_SETFD, fdflags);
2742 #else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
2743 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1)
2747 /* Try to get exclusive lock. If we succeed, then
2748 * nobody is using the lock region and we should initialize it.
2751 struct flock lock_info;
2752 memset((void *)&lock_info, 0, sizeof(lock_info));
2753 lock_info.l_type = F_WRLCK;
2754 lock_info.l_whence = SEEK_SET;
2755 lock_info.l_start = 0;
2756 lock_info.l_len = 1;
2757 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2761 lock_info.l_type = F_RDLCK;
2762 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2769 size = lseek(env->me_lfd, 0, SEEK_END);
2771 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2772 if (size < rsize && *excl) {
2774 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2775 if (!SetEndOfFile(env->me_lfd)) {
2780 if (ftruncate(env->me_lfd, rsize) != 0) {
2787 size = rsize - sizeof(MDB_txninfo);
2788 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2793 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2799 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2801 if (!env->me_txns) {
2806 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2808 if (m == MAP_FAILED) {
2809 env->me_txns = NULL;
2819 if (!mdb_sec_inited) {
2820 InitializeSecurityDescriptor(&mdb_null_sd,
2821 SECURITY_DESCRIPTOR_REVISION);
2822 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2823 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2824 mdb_all_sa.bInheritHandle = FALSE;
2825 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2828 mdb_hash_hex(lpath, hexbuf);
2829 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2830 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2831 if (!env->me_rmutex) {
2835 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2836 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2837 if (!env->me_wmutex) {
2844 mdb_hash_hex(lpath, hexbuf);
2845 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2846 if (sem_unlink(env->me_txns->mti_rmname)) {
2848 if (rc != ENOENT && rc != EINVAL)
2851 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2852 if (!env->me_rmutex) {
2856 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2857 if (sem_unlink(env->me_txns->mti_wmname)) {
2859 if (rc != ENOENT && rc != EINVAL)
2862 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2863 if (!env->me_wmutex) {
2867 #else /* __APPLE__ */
2868 pthread_mutexattr_t mattr;
2870 pthread_mutexattr_init(&mattr);
2871 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2875 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2876 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2877 #endif /* __APPLE__ */
2879 env->me_txns->mti_version = MDB_VERSION;
2880 env->me_txns->mti_magic = MDB_MAGIC;
2881 env->me_txns->mti_txnid = 0;
2882 env->me_txns->mti_numreaders = 0;
2883 env->me_txns->mti_me_toggle = 0;
2886 if (env->me_txns->mti_magic != MDB_MAGIC) {
2887 DPUTS("lock region has invalid magic");
2891 if (env->me_txns->mti_version != MDB_VERSION) {
2892 DPRINTF("lock region is version %u, expected version %u",
2893 env->me_txns->mti_version, MDB_VERSION);
2894 rc = MDB_VERSION_MISMATCH;
2898 if (rc != EACCES && rc != EAGAIN) {
2902 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2903 if (!env->me_rmutex) {
2907 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2908 if (!env->me_wmutex) {
2914 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2915 if (!env->me_rmutex) {
2919 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2920 if (!env->me_wmutex) {
2930 env->me_lfd = INVALID_HANDLE_VALUE;
2935 /** The name of the lock file in the DB environment */
2936 #define LOCKNAME "/lock.mdb"
2937 /** The name of the data file in the DB environment */
2938 #define DATANAME "/data.mdb"
2939 /** The suffix of the lock file when no subdir is used */
2940 #define LOCKSUFF "-lock"
2943 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2945 int oflags, rc, len, excl;
2946 char *lpath, *dpath;
2949 if (flags & MDB_NOSUBDIR) {
2950 rc = len + sizeof(LOCKSUFF) + len + 1;
2952 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2957 if (flags & MDB_NOSUBDIR) {
2958 dpath = lpath + len + sizeof(LOCKSUFF);
2959 sprintf(lpath, "%s" LOCKSUFF, path);
2960 strcpy(dpath, path);
2962 dpath = lpath + len + sizeof(LOCKNAME);
2963 sprintf(lpath, "%s" LOCKNAME, path);
2964 sprintf(dpath, "%s" DATANAME, path);
2967 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2972 if (F_ISSET(flags, MDB_RDONLY)) {
2973 oflags = GENERIC_READ;
2974 len = OPEN_EXISTING;
2976 oflags = GENERIC_READ|GENERIC_WRITE;
2979 mode = FILE_ATTRIBUTE_NORMAL;
2980 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2981 NULL, len, mode, NULL);
2983 if (F_ISSET(flags, MDB_RDONLY))
2986 oflags = O_RDWR | O_CREAT;
2988 env->me_fd = open(dpath, oflags, mode);
2990 if (env->me_fd == INVALID_HANDLE_VALUE) {
2995 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2996 if (flags & (MDB_RDONLY|MDB_NOSYNC)) {
2997 env->me_mfd = env->me_fd;
2999 /* synchronous fd for meta writes */
3001 env->me_mfd = CreateFile(dpath, oflags,
3002 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3003 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3005 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3007 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3012 env->me_path = strdup(path);
3013 DPRINTF("opened dbenv %p", (void *) env);
3014 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3015 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
3017 mdb_env_share_locks(env);
3018 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3019 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
3020 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
3026 if (env->me_fd != INVALID_HANDLE_VALUE) {
3028 env->me_fd = INVALID_HANDLE_VALUE;
3030 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3032 env->me_lfd = INVALID_HANDLE_VALUE;
3040 mdb_env_close(MDB_env *env)
3047 VGMEMP_DESTROY(env);
3048 while (env->me_dpages) {
3049 dp = env->me_dpages;
3050 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3051 env->me_dpages = dp->mp_next;
3055 free(env->me_dbs[1]);
3056 free(env->me_dbs[0]);
3060 LAZY_RWLOCK_DESTROY(&env->me_dblock);
3061 pthread_key_delete(env->me_txkey);
3064 munmap(env->me_map, env->me_mapsize);
3066 if (env->me_mfd != env->me_fd)
3070 pid_t pid = getpid();
3072 for (i=0; i<env->me_txns->mti_numreaders; i++)
3073 if (env->me_txns->mti_readers[i].mr_pid == pid)
3074 env->me_txns->mti_readers[i].mr_pid = 0;
3075 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3078 mdb_midl_free(env->me_free_pgs);
3082 /** Compare two items pointing at aligned size_t's */
3084 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3086 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3087 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3090 /** Compare two items pointing at aligned int's */
3092 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3094 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3095 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3098 /** Compare two items pointing at ints of unknown alignment.
3099 * Nodes and keys are guaranteed to be 2-byte aligned.
3102 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3104 #if BYTE_ORDER == LITTLE_ENDIAN
3105 unsigned short *u, *c;
3108 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3109 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3112 } while(!x && u > (unsigned short *)a->mv_data);
3115 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3119 /** Compare two items lexically */
3121 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3128 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3134 diff = memcmp(a->mv_data, b->mv_data, len);
3135 return diff ? diff : len_diff<0 ? -1 : len_diff;
3138 /** Compare two items in reverse byte order */
3140 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3142 const unsigned char *p1, *p2, *p1_lim;
3146 p1_lim = (const unsigned char *)a->mv_data;
3147 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3148 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3150 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3156 while (p1 > p1_lim) {
3157 diff = *--p1 - *--p2;
3161 return len_diff<0 ? -1 : len_diff;
3164 /** Search for key within a page, using binary search.
3165 * Returns the smallest entry larger or equal to the key.
3166 * If exactp is non-null, stores whether the found entry was an exact match
3167 * in *exactp (1 or 0).
3168 * Updates the cursor index with the index of the found entry.
3169 * If no entry larger or equal to the key is found, returns NULL.
3172 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3174 unsigned int i = 0, nkeys;
3177 MDB_page *mp = mc->mc_pg[mc->mc_top];
3178 MDB_node *node = NULL;
3183 nkeys = NUMKEYS(mp);
3188 COPY_PGNO(pgno, mp->mp_pgno);
3189 DPRINTF("searching %u keys in %s %spage %zu",
3190 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3197 low = IS_LEAF(mp) ? 0 : 1;
3199 cmp = mc->mc_dbx->md_cmp;
3201 /* Branch pages have no data, so if using integer keys,
3202 * alignment is guaranteed. Use faster mdb_cmp_int.
3204 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3205 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3212 nodekey.mv_size = mc->mc_db->md_pad;
3213 node = NODEPTR(mp, 0); /* fake */
3214 while (low <= high) {
3215 i = (low + high) >> 1;
3216 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3217 rc = cmp(key, &nodekey);
3218 DPRINTF("found leaf index %u [%s], rc = %i",
3219 i, DKEY(&nodekey), rc);
3228 while (low <= high) {
3229 i = (low + high) >> 1;
3231 node = NODEPTR(mp, i);
3232 nodekey.mv_size = NODEKSZ(node);
3233 nodekey.mv_data = NODEKEY(node);
3235 rc = cmp(key, &nodekey);
3238 DPRINTF("found leaf index %u [%s], rc = %i",
3239 i, DKEY(&nodekey), rc);
3241 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3242 i, DKEY(&nodekey), NODEPGNO(node), rc);
3253 if (rc > 0) { /* Found entry is less than the key. */
3254 i++; /* Skip to get the smallest entry larger than key. */
3256 node = NODEPTR(mp, i);
3259 *exactp = (rc == 0);
3260 /* store the key index */
3261 mc->mc_ki[mc->mc_top] = i;
3263 /* There is no entry larger or equal to the key. */
3266 /* nodeptr is fake for LEAF2 */
3272 mdb_cursor_adjust(MDB_cursor *mc, func)
3276 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3277 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3284 /** Pop a page off the top of the cursor's stack. */
3286 mdb_cursor_pop(MDB_cursor *mc)
3291 top = mc->mc_pg[mc->mc_top];
3296 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3297 mc->mc_dbi, (void *) mc);
3301 /** Push a page onto the top of the cursor's stack. */
3303 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3305 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3306 mc->mc_dbi, (void *) mc);
3308 if (mc->mc_snum >= CURSOR_STACK) {
3309 assert(mc->mc_snum < CURSOR_STACK);
3313 mc->mc_top = mc->mc_snum++;
3314 mc->mc_pg[mc->mc_top] = mp;
3315 mc->mc_ki[mc->mc_top] = 0;
3320 /** Find the address of the page corresponding to a given page number.
3321 * @param[in] txn the transaction for this access.
3322 * @param[in] pgno the page number for the page to retrieve.
3323 * @param[out] ret address of a pointer where the page's address will be stored.
3324 * @return 0 on success, non-zero on failure.
3327 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3331 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3333 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3334 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3335 p = txn->mt_u.dirty_list[x].mptr;
3339 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3340 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3344 DPRINTF("page %zu not found", pgno);
3347 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3350 /** Search for the page a given key should be in.
3351 * Pushes parent pages on the cursor stack. This function continues a
3352 * search on a cursor that has already been initialized. (Usually by
3353 * #mdb_page_search() but also by #mdb_node_move().)
3354 * @param[in,out] mc the cursor for this operation.
3355 * @param[in] key the key to search for. If NULL, search for the lowest
3356 * page. (This is used by #mdb_cursor_first().)
3357 * @param[in] modify If true, visited pages are updated with new page numbers.
3358 * @return 0 on success, non-zero on failure.
3361 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3363 MDB_page *mp = mc->mc_pg[mc->mc_top];
3368 while (IS_BRANCH(mp)) {
3372 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3373 assert(NUMKEYS(mp) > 1);
3374 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3376 if (key == NULL) /* Initialize cursor to first page. */
3378 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3379 /* cursor to last page */
3383 node = mdb_node_search(mc, key, &exact);
3385 i = NUMKEYS(mp) - 1;
3387 i = mc->mc_ki[mc->mc_top];
3396 DPRINTF("following index %u for key [%s]",
3398 assert(i < NUMKEYS(mp));
3399 node = NODEPTR(mp, i);
3401 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3404 mc->mc_ki[mc->mc_top] = i;
3405 if ((rc = mdb_cursor_push(mc, mp)))
3409 if ((rc = mdb_page_touch(mc)) != 0)
3411 mp = mc->mc_pg[mc->mc_top];
3416 DPRINTF("internal error, index points to a %02X page!?",
3418 return MDB_CORRUPTED;
3421 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3422 key ? DKEY(key) : NULL);
3427 /** Search for the page a given key should be in.
3428 * Pushes parent pages on the cursor stack. This function just sets up
3429 * the search; it finds the root page for \b mc's database and sets this
3430 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3431 * called to complete the search.
3432 * @param[in,out] mc the cursor for this operation.
3433 * @param[in] key the key to search for. If NULL, search for the lowest
3434 * page. (This is used by #mdb_cursor_first().)
3435 * @param[in] modify If true, visited pages are updated with new page numbers.
3436 * @return 0 on success, non-zero on failure.
3439 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3444 /* Make sure the txn is still viable, then find the root from
3445 * the txn's db table.
3447 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3448 DPUTS("transaction has failed, must abort");
3451 /* Make sure we're using an up-to-date root */
3452 if (mc->mc_dbi > MAIN_DBI) {
3453 if ((*mc->mc_dbflag & DB_STALE) ||
3454 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3456 unsigned char dbflag = 0;
3457 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3458 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3461 if (*mc->mc_dbflag & DB_STALE) {
3464 MDB_node *leaf = mdb_node_search(&mc2,
3465 &mc->mc_dbx->md_name, &exact);
3467 return MDB_NOTFOUND;
3468 mdb_node_read(mc->mc_txn, leaf, &data);
3469 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3473 *mc->mc_dbflag = dbflag;
3476 root = mc->mc_db->md_root;
3478 if (root == P_INVALID) { /* Tree is empty. */
3479 DPUTS("tree is empty");
3480 return MDB_NOTFOUND;
3485 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3491 DPRINTF("db %u root page %zu has flags 0x%X",
3492 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3495 if ((rc = mdb_page_touch(mc)))
3499 return mdb_page_search_root(mc, key, modify);
3502 /** Return the data associated with a given node.
3503 * @param[in] txn The transaction for this operation.
3504 * @param[in] leaf The node being read.
3505 * @param[out] data Updated to point to the node's data.
3506 * @return 0 on success, non-zero on failure.
3509 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3511 MDB_page *omp; /* overflow page */
3515 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3516 data->mv_size = NODEDSZ(leaf);
3517 data->mv_data = NODEDATA(leaf);
3521 /* Read overflow data.
3523 data->mv_size = NODEDSZ(leaf);
3524 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3525 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3526 DPRINTF("read overflow page %zu failed", pgno);
3529 data->mv_data = METADATA(omp);
3535 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3536 MDB_val *key, MDB_val *data)
3545 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3547 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3550 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3554 mdb_cursor_init(&mc, txn, dbi, &mx);
3555 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3558 /** Find a sibling for a page.
3559 * Replaces the page at the top of the cursor's stack with the
3560 * specified sibling, if one exists.
3561 * @param[in] mc The cursor for this operation.
3562 * @param[in] move_right Non-zero if the right sibling is requested,
3563 * otherwise the left sibling.
3564 * @return 0 on success, non-zero on failure.
3567 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3573 if (mc->mc_snum < 2) {
3574 return MDB_NOTFOUND; /* root has no siblings */
3578 DPRINTF("parent page is page %zu, index %u",
3579 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3581 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3582 : (mc->mc_ki[mc->mc_top] == 0)) {
3583 DPRINTF("no more keys left, moving to %s sibling",
3584 move_right ? "right" : "left");
3585 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3589 mc->mc_ki[mc->mc_top]++;
3591 mc->mc_ki[mc->mc_top]--;
3592 DPRINTF("just moving to %s index key %u",
3593 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3595 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3597 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3598 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3601 mdb_cursor_push(mc, mp);
3606 /** Move the cursor to the next data item. */
3608 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3614 if (mc->mc_flags & C_EOF) {
3615 return MDB_NOTFOUND;
3618 assert(mc->mc_flags & C_INITIALIZED);
3620 mp = mc->mc_pg[mc->mc_top];
3622 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3623 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3624 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3625 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3626 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3627 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3631 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3632 if (op == MDB_NEXT_DUP)
3633 return MDB_NOTFOUND;
3637 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3639 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3640 DPUTS("=====> move to next sibling page");
3641 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3642 mc->mc_flags |= C_EOF;
3643 mc->mc_flags &= ~C_INITIALIZED;
3644 return MDB_NOTFOUND;
3646 mp = mc->mc_pg[mc->mc_top];
3647 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3649 mc->mc_ki[mc->mc_top]++;
3651 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3652 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3655 key->mv_size = mc->mc_db->md_pad;
3656 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3660 assert(IS_LEAF(mp));
3661 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3663 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3664 mdb_xcursor_init1(mc, leaf);
3667 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3670 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3671 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3672 if (rc != MDB_SUCCESS)
3677 MDB_SET_KEY(leaf, key);
3681 /** Move the cursor to the previous data item. */
3683 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3689 assert(mc->mc_flags & C_INITIALIZED);
3691 mp = mc->mc_pg[mc->mc_top];
3693 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3694 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3695 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3696 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3697 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3698 if (op != MDB_PREV || rc == MDB_SUCCESS)
3701 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3702 if (op == MDB_PREV_DUP)
3703 return MDB_NOTFOUND;
3708 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3710 if (mc->mc_ki[mc->mc_top] == 0) {
3711 DPUTS("=====> move to prev sibling page");
3712 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3713 mc->mc_flags &= ~C_INITIALIZED;
3714 return MDB_NOTFOUND;
3716 mp = mc->mc_pg[mc->mc_top];
3717 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3718 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3720 mc->mc_ki[mc->mc_top]--;
3722 mc->mc_flags &= ~C_EOF;
3724 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3725 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3728 key->mv_size = mc->mc_db->md_pad;
3729 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3733 assert(IS_LEAF(mp));
3734 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3736 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3737 mdb_xcursor_init1(mc, leaf);
3740 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3743 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3744 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3745 if (rc != MDB_SUCCESS)
3750 MDB_SET_KEY(leaf, key);
3754 /** Set the cursor on a specific data item. */
3756 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3757 MDB_cursor_op op, int *exactp)
3766 assert(key->mv_size > 0);
3768 /* See if we're already on the right page */
3769 if (mc->mc_flags & C_INITIALIZED) {
3772 mp = mc->mc_pg[mc->mc_top];
3774 mc->mc_ki[mc->mc_top] = 0;
3775 return MDB_NOTFOUND;
3777 if (mp->mp_flags & P_LEAF2) {
3778 nodekey.mv_size = mc->mc_db->md_pad;
3779 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3781 leaf = NODEPTR(mp, 0);
3782 MDB_SET_KEY(leaf, &nodekey);
3784 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3786 /* Probably happens rarely, but first node on the page
3787 * was the one we wanted.
3789 mc->mc_ki[mc->mc_top] = 0;
3790 leaf = NODEPTR(mp, 0);
3797 unsigned int nkeys = NUMKEYS(mp);
3799 if (mp->mp_flags & P_LEAF2) {
3800 nodekey.mv_data = LEAF2KEY(mp,
3801 nkeys-1, nodekey.mv_size);
3803 leaf = NODEPTR(mp, nkeys-1);
3804 MDB_SET_KEY(leaf, &nodekey);
3806 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3808 /* last node was the one we wanted */
3809 mc->mc_ki[mc->mc_top] = nkeys-1;
3810 leaf = NODEPTR(mp, nkeys-1);
3816 /* This is definitely the right page, skip search_page */
3821 /* If any parents have right-sibs, search.
3822 * Otherwise, there's nothing further.
3824 for (i=0; i<mc->mc_top; i++)
3826 NUMKEYS(mc->mc_pg[i])-1)
3828 if (i == mc->mc_top) {
3829 /* There are no other pages */
3830 mc->mc_ki[mc->mc_top] = nkeys;
3831 return MDB_NOTFOUND;
3835 /* There are no other pages */
3836 mc->mc_ki[mc->mc_top] = 0;
3837 return MDB_NOTFOUND;
3841 rc = mdb_page_search(mc, key, 0);
3842 if (rc != MDB_SUCCESS)
3845 mp = mc->mc_pg[mc->mc_top];
3846 assert(IS_LEAF(mp));
3849 leaf = mdb_node_search(mc, key, exactp);
3850 if (exactp != NULL && !*exactp) {
3851 /* MDB_SET specified and not an exact match. */
3852 return MDB_NOTFOUND;
3856 DPUTS("===> inexact leaf not found, goto sibling");
3857 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3858 return rc; /* no entries matched */
3859 mp = mc->mc_pg[mc->mc_top];
3860 assert(IS_LEAF(mp));
3861 leaf = NODEPTR(mp, 0);
3865 mc->mc_flags |= C_INITIALIZED;
3866 mc->mc_flags &= ~C_EOF;
3869 key->mv_size = mc->mc_db->md_pad;
3870 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3874 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3875 mdb_xcursor_init1(mc, leaf);
3878 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3879 if (op == MDB_SET || op == MDB_SET_RANGE) {
3880 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3883 if (op == MDB_GET_BOTH) {
3889 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3890 if (rc != MDB_SUCCESS)
3893 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3895 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3897 rc = mc->mc_dbx->md_dcmp(data, &d2);
3899 if (op == MDB_GET_BOTH || rc > 0)
3900 return MDB_NOTFOUND;
3905 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3906 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3911 /* The key already matches in all other cases */
3912 if (op == MDB_SET_RANGE)
3913 MDB_SET_KEY(leaf, key);
3914 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3919 /** Move the cursor to the first item in the database. */
3921 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3926 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3927 rc = mdb_page_search(mc, NULL, 0);
3928 if (rc != MDB_SUCCESS)
3931 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3933 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3934 mc->mc_flags |= C_INITIALIZED;
3935 mc->mc_flags &= ~C_EOF;
3937 mc->mc_ki[mc->mc_top] = 0;
3939 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3940 key->mv_size = mc->mc_db->md_pad;
3941 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3946 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3947 mdb_xcursor_init1(mc, leaf);
3948 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3953 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3954 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3958 MDB_SET_KEY(leaf, key);
3962 /** Move the cursor to the last item in the database. */
3964 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3970 lkey.mv_size = MAXKEYSIZE+1;
3971 lkey.mv_data = NULL;
3973 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3974 rc = mdb_page_search(mc, &lkey, 0);
3975 if (rc != MDB_SUCCESS)
3978 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3980 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3981 mc->mc_flags |= C_INITIALIZED;
3982 mc->mc_flags &= ~C_EOF;
3984 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3986 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3987 key->mv_size = mc->mc_db->md_pad;
3988 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3993 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3994 mdb_xcursor_init1(mc, leaf);
3995 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4000 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4001 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4006 MDB_SET_KEY(leaf, key);
4011 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4021 case MDB_GET_BOTH_RANGE:
4022 if (data == NULL || mc->mc_xcursor == NULL) {
4029 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4031 } else if (op == MDB_SET_RANGE)
4032 rc = mdb_cursor_set(mc, key, data, op, NULL);
4034 rc = mdb_cursor_set(mc, key, data, op, &exact);
4036 case MDB_GET_MULTIPLE:
4038 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4039 !(mc->mc_flags & C_INITIALIZED)) {
4044 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4045 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4048 case MDB_NEXT_MULTIPLE:
4050 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4054 if (!(mc->mc_flags & C_INITIALIZED))
4055 rc = mdb_cursor_first(mc, key, data);
4057 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4058 if (rc == MDB_SUCCESS) {
4059 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4062 mx = &mc->mc_xcursor->mx_cursor;
4063 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4065 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4066 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4074 case MDB_NEXT_NODUP:
4075 if (!(mc->mc_flags & C_INITIALIZED))
4076 rc = mdb_cursor_first(mc, key, data);
4078 rc = mdb_cursor_next(mc, key, data, op);
4082 case MDB_PREV_NODUP:
4083 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
4084 rc = mdb_cursor_last(mc, key, data);
4086 rc = mdb_cursor_prev(mc, key, data, op);
4089 rc = mdb_cursor_first(mc, key, data);
4093 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4094 !(mc->mc_flags & C_INITIALIZED) ||
4095 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4099 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4102 rc = mdb_cursor_last(mc, key, data);
4106 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4107 !(mc->mc_flags & C_INITIALIZED) ||
4108 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4112 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4115 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4123 /** Touch all the pages in the cursor stack.
4124 * Makes sure all the pages are writable, before attempting a write operation.
4125 * @param[in] mc The cursor to operate on.
4128 mdb_cursor_touch(MDB_cursor *mc)
4132 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4134 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4135 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
4138 *mc->mc_dbflag = DB_DIRTY;
4140 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4141 rc = mdb_page_touch(mc);
4145 mc->mc_top = mc->mc_snum-1;
4150 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4153 MDB_node *leaf = NULL;
4154 MDB_val xdata, *rdata, dkey;
4158 unsigned int mcount = 0;
4162 char dbuf[MAXKEYSIZE+1];
4163 unsigned int nflags;
4166 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4169 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4170 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4174 if (flags == MDB_CURRENT) {
4175 if (!(mc->mc_flags & C_INITIALIZED))
4178 } else if (mc->mc_db->md_root == P_INVALID) {
4180 /* new database, write a root leaf page */
4181 DPUTS("allocating new root leaf page");
4182 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4186 mdb_cursor_push(mc, np);
4187 mc->mc_db->md_root = np->mp_pgno;
4188 mc->mc_db->md_depth++;
4189 *mc->mc_dbflag = DB_DIRTY;
4190 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4192 np->mp_flags |= P_LEAF2;
4193 mc->mc_flags |= C_INITIALIZED;
4199 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4200 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4201 DPRINTF("duplicate key [%s]", DKEY(key));
4203 return MDB_KEYEXIST;
4205 if (rc && rc != MDB_NOTFOUND)
4209 /* Cursor is positioned, now make sure all pages are writable */
4210 rc2 = mdb_cursor_touch(mc);
4215 /* The key already exists */
4216 if (rc == MDB_SUCCESS) {
4217 /* there's only a key anyway, so this is a no-op */
4218 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4219 unsigned int ksize = mc->mc_db->md_pad;
4220 if (key->mv_size != ksize)
4222 if (flags == MDB_CURRENT) {
4223 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4224 memcpy(ptr, key->mv_data, ksize);
4229 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4232 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4233 /* Was a single item before, must convert now */
4235 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4236 /* Just overwrite the current item */
4237 if (flags == MDB_CURRENT)
4240 dkey.mv_size = NODEDSZ(leaf);
4241 dkey.mv_data = NODEDATA(leaf);
4242 #if UINT_MAX < SIZE_MAX
4243 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4244 #ifdef MISALIGNED_OK
4245 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4247 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4250 /* if data matches, ignore it */
4251 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4252 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4254 /* create a fake page for the dup items */
4255 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4256 dkey.mv_data = dbuf;
4257 fp = (MDB_page *)&pbuf;
4258 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4259 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4260 fp->mp_lower = PAGEHDRSZ;
4261 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4262 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4263 fp->mp_flags |= P_LEAF2;
4264 fp->mp_pad = data->mv_size;
4266 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4267 (dkey.mv_size & 1) + (data->mv_size & 1);
4269 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4272 xdata.mv_size = fp->mp_upper;
4277 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4278 /* See if we need to convert from fake page to subDB */
4280 unsigned int offset;
4283 fp = NODEDATA(leaf);
4284 if (flags == MDB_CURRENT) {
4285 fp->mp_flags |= P_DIRTY;
4286 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4287 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4291 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4292 offset = fp->mp_pad;
4294 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4296 offset += offset & 1;
4297 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4298 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4300 /* yes, convert it */
4302 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4303 dummy.md_pad = fp->mp_pad;
4304 dummy.md_flags = MDB_DUPFIXED;
4305 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4306 dummy.md_flags |= MDB_INTEGERKEY;
4309 dummy.md_branch_pages = 0;
4310 dummy.md_leaf_pages = 1;
4311 dummy.md_overflow_pages = 0;
4312 dummy.md_entries = NUMKEYS(fp);
4314 xdata.mv_size = sizeof(MDB_db);
4315 xdata.mv_data = &dummy;
4316 mp = mdb_page_alloc(mc, 1);
4319 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4320 flags |= F_DUPDATA|F_SUBDATA;
4321 dummy.md_root = mp->mp_pgno;
4323 /* no, just grow it */
4325 xdata.mv_size = NODEDSZ(leaf) + offset;
4326 xdata.mv_data = &pbuf;
4327 mp = (MDB_page *)&pbuf;
4328 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4331 mp->mp_flags = fp->mp_flags | P_DIRTY;
4332 mp->mp_pad = fp->mp_pad;
4333 mp->mp_lower = fp->mp_lower;
4334 mp->mp_upper = fp->mp_upper + offset;
4336 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4338 nsize = NODEDSZ(leaf) - fp->mp_upper;
4339 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4340 for (i=0; i<NUMKEYS(fp); i++)
4341 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4343 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4347 /* data is on sub-DB, just store it */
4348 flags |= F_DUPDATA|F_SUBDATA;
4352 /* overflow page overwrites need special handling */
4353 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4356 int ovpages, dpages;
4358 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4359 dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4360 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4361 mdb_page_get(mc->mc_txn, pg, &omp);
4362 /* Is the ov page writable and large enough? */
4363 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
4364 /* yes, overwrite it. Note in this case we don't
4365 * bother to try shrinking the node if the new data
4366 * is smaller than the overflow threshold.
4368 if (F_ISSET(flags, MDB_RESERVE))
4369 data->mv_data = METADATA(omp);
4371 memcpy(METADATA(omp), data->mv_data, data->mv_size);
4374 /* no, free ovpages */
4376 mc->mc_db->md_overflow_pages -= ovpages;
4377 for (i=0; i<ovpages; i++) {
4378 DPRINTF("freed ov page %zu", pg);
4379 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4383 } else if (NODEDSZ(leaf) == data->mv_size) {
4384 /* same size, just replace it. Note that we could
4385 * also reuse this node if the new data is smaller,
4386 * but instead we opt to shrink the node in that case.
4388 if (F_ISSET(flags, MDB_RESERVE))
4389 data->mv_data = NODEDATA(leaf);
4391 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4394 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4395 mc->mc_db->md_entries--;
4397 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4403 nflags = flags & NODE_ADD_FLAGS;
4404 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4405 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4406 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4407 nflags &= ~MDB_APPEND;
4408 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4410 /* There is room already in this leaf page. */
4411 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4412 if (rc == 0 && !do_sub) {
4413 /* Adjust other cursors pointing to mp */
4414 MDB_cursor *m2, *m3;
4415 MDB_dbi dbi = mc->mc_dbi;
4416 unsigned i = mc->mc_top;
4417 MDB_page *mp = mc->mc_pg[i];
4419 if (mc->mc_flags & C_SUB)
4422 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4423 if (mc->mc_flags & C_SUB)
4424 m3 = &m2->mc_xcursor->mx_cursor;
4427 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4428 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4435 if (rc != MDB_SUCCESS)
4436 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4438 /* Now store the actual data in the child DB. Note that we're
4439 * storing the user data in the keys field, so there are strict
4440 * size limits on dupdata. The actual data fields of the child
4441 * DB are all zero size.
4448 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4449 if (flags & MDB_CURRENT) {
4450 xflags = MDB_CURRENT;
4452 mdb_xcursor_init1(mc, leaf);
4453 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4455 /* converted, write the original data first */
4457 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4461 /* Adjust other cursors pointing to mp */
4463 unsigned i = mc->mc_top;
4464 MDB_page *mp = mc->mc_pg[i];
4466 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4467 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4468 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4469 mdb_xcursor_init1(m2, leaf);
4474 xflags |= (flags & MDB_APPEND);
4475 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4476 if (flags & F_SUBDATA) {
4477 void *db = NODEDATA(leaf);
4478 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4481 /* sub-writes might have failed so check rc again.
4482 * Don't increment count if we just replaced an existing item.
4484 if (!rc && !(flags & MDB_CURRENT))
4485 mc->mc_db->md_entries++;
4486 if (flags & MDB_MULTIPLE) {
4488 if (mcount < data[1].mv_size) {
4489 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4490 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4500 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4505 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4508 if (!mc->mc_flags & C_INITIALIZED)
4511 rc = mdb_cursor_touch(mc);
4515 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4517 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4518 if (flags != MDB_NODUPDATA) {
4519 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4520 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4522 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4523 /* If sub-DB still has entries, we're done */
4524 if (mc->mc_xcursor->mx_db.md_entries) {
4525 if (leaf->mn_flags & F_SUBDATA) {
4526 /* update subDB info */
4527 void *db = NODEDATA(leaf);
4528 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4530 /* shrink fake page */
4531 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4533 mc->mc_db->md_entries--;
4536 /* otherwise fall thru and delete the sub-DB */
4539 if (leaf->mn_flags & F_SUBDATA) {
4540 /* add all the child DB's pages to the free list */
4541 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4542 if (rc == MDB_SUCCESS) {
4543 mc->mc_db->md_entries -=
4544 mc->mc_xcursor->mx_db.md_entries;
4549 return mdb_cursor_del0(mc, leaf);
4552 /** Allocate and initialize new pages for a database.
4553 * @param[in] mc a cursor on the database being added to.
4554 * @param[in] flags flags defining what type of page is being allocated.
4555 * @param[in] num the number of pages to allocate. This is usually 1,
4556 * unless allocating overflow pages for a large record.
4557 * @return Address of a page, or NULL on failure.
4560 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4564 if ((np = mdb_page_alloc(mc, num)) == NULL)
4566 DPRINTF("allocated new mpage %zu, page size %u",
4567 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4568 np->mp_flags = flags | P_DIRTY;
4569 np->mp_lower = PAGEHDRSZ;
4570 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4573 mc->mc_db->md_branch_pages++;
4574 else if (IS_LEAF(np))
4575 mc->mc_db->md_leaf_pages++;
4576 else if (IS_OVERFLOW(np)) {
4577 mc->mc_db->md_overflow_pages += num;
4584 /** Calculate the size of a leaf node.
4585 * The size depends on the environment's page size; if a data item
4586 * is too large it will be put onto an overflow page and the node
4587 * size will only include the key and not the data. Sizes are always
4588 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4589 * of the #MDB_node headers.
4590 * @param[in] env The environment handle.
4591 * @param[in] key The key for the node.
4592 * @param[in] data The data for the node.
4593 * @return The number of bytes needed to store the node.
4596 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4600 sz = LEAFSIZE(key, data);
4601 if (sz >= env->me_psize / MDB_MINKEYS) {
4602 /* put on overflow page */
4603 sz -= data->mv_size - sizeof(pgno_t);
4607 return sz + sizeof(indx_t);
4610 /** Calculate the size of a branch node.
4611 * The size should depend on the environment's page size but since
4612 * we currently don't support spilling large keys onto overflow
4613 * pages, it's simply the size of the #MDB_node header plus the
4614 * size of the key. Sizes are always rounded up to an even number
4615 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4616 * @param[in] env The environment handle.
4617 * @param[in] key The key for the node.
4618 * @return The number of bytes needed to store the node.
4621 mdb_branch_size(MDB_env *env, MDB_val *key)
4626 if (sz >= env->me_psize / MDB_MINKEYS) {
4627 /* put on overflow page */
4628 /* not implemented */
4629 /* sz -= key->size - sizeof(pgno_t); */
4632 return sz + sizeof(indx_t);
4635 /** Add a node to the page pointed to by the cursor.
4636 * @param[in] mc The cursor for this operation.
4637 * @param[in] indx The index on the page where the new node should be added.
4638 * @param[in] key The key for the new node.
4639 * @param[in] data The data for the new node, if any.
4640 * @param[in] pgno The page number, if adding a branch node.
4641 * @param[in] flags Flags for the node.
4642 * @return 0 on success, non-zero on failure. Possible errors are:
4644 * <li>ENOMEM - failed to allocate overflow pages for the node.
4645 * <li>ENOSPC - there is insufficient room in the page. This error
4646 * should never happen since all callers already calculate the
4647 * page's free space before calling this function.
4651 mdb_node_add(MDB_cursor *mc, indx_t indx,
4652 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4655 size_t node_size = NODESIZE;
4658 MDB_page *mp = mc->mc_pg[mc->mc_top];
4659 MDB_page *ofp = NULL; /* overflow page */
4662 assert(mp->mp_upper >= mp->mp_lower);
4664 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4665 IS_LEAF(mp) ? "leaf" : "branch",
4666 IS_SUBP(mp) ? "sub-" : "",
4667 mp->mp_pgno, indx, data ? data->mv_size : 0,
4668 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4671 /* Move higher keys up one slot. */
4672 int ksize = mc->mc_db->md_pad, dif;
4673 char *ptr = LEAF2KEY(mp, indx, ksize);
4674 dif = NUMKEYS(mp) - indx;
4676 memmove(ptr+ksize, ptr, dif*ksize);
4677 /* insert new key */
4678 memcpy(ptr, key->mv_data, ksize);
4680 /* Just using these for counting */
4681 mp->mp_lower += sizeof(indx_t);
4682 mp->mp_upper -= ksize - sizeof(indx_t);
4687 node_size += key->mv_size;
4691 if (F_ISSET(flags, F_BIGDATA)) {
4692 /* Data already on overflow page. */
4693 node_size += sizeof(pgno_t);
4694 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4695 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4696 /* Put data on overflow page. */
4697 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4698 data->mv_size, node_size+data->mv_size);
4699 node_size += sizeof(pgno_t);
4700 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4702 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4705 node_size += data->mv_size;
4708 node_size += node_size & 1;
4710 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4711 DPRINTF("not enough room in page %zu, got %u ptrs",
4712 mp->mp_pgno, NUMKEYS(mp));
4713 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4714 mp->mp_upper - mp->mp_lower);
4715 DPRINTF("node size = %zu", node_size);
4719 /* Move higher pointers up one slot. */
4720 for (i = NUMKEYS(mp); i > indx; i--)
4721 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4723 /* Adjust free space offsets. */
4724 ofs = mp->mp_upper - node_size;
4725 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4726 mp->mp_ptrs[indx] = ofs;
4728 mp->mp_lower += sizeof(indx_t);
4730 /* Write the node data. */
4731 node = NODEPTR(mp, indx);
4732 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4733 node->mn_flags = flags;
4735 SETDSZ(node,data->mv_size);
4740 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4745 if (F_ISSET(flags, F_BIGDATA))
4746 memcpy(node->mn_data + key->mv_size, data->mv_data,
4748 else if (F_ISSET(flags, MDB_RESERVE))
4749 data->mv_data = node->mn_data + key->mv_size;
4751 memcpy(node->mn_data + key->mv_size, data->mv_data,
4754 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4756 if (F_ISSET(flags, MDB_RESERVE))
4757 data->mv_data = METADATA(ofp);
4759 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4766 /** Delete the specified node from a page.
4767 * @param[in] mp The page to operate on.
4768 * @param[in] indx The index of the node to delete.
4769 * @param[in] ksize The size of a node. Only used if the page is
4770 * part of a #MDB_DUPFIXED database.
4773 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4776 indx_t i, j, numkeys, ptr;
4783 COPY_PGNO(pgno, mp->mp_pgno);
4784 DPRINTF("delete node %u on %s page %zu", indx,
4785 IS_LEAF(mp) ? "leaf" : "branch", pgno);
4788 assert(indx < NUMKEYS(mp));
4791 int x = NUMKEYS(mp) - 1 - indx;
4792 base = LEAF2KEY(mp, indx, ksize);
4794 memmove(base, base + ksize, x * ksize);
4795 mp->mp_lower -= sizeof(indx_t);
4796 mp->mp_upper += ksize - sizeof(indx_t);
4800 node = NODEPTR(mp, indx);
4801 sz = NODESIZE + node->mn_ksize;
4803 if (F_ISSET(node->mn_flags, F_BIGDATA))
4804 sz += sizeof(pgno_t);
4806 sz += NODEDSZ(node);
4810 ptr = mp->mp_ptrs[indx];
4811 numkeys = NUMKEYS(mp);
4812 for (i = j = 0; i < numkeys; i++) {
4814 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4815 if (mp->mp_ptrs[i] < ptr)
4816 mp->mp_ptrs[j] += sz;
4821 base = (char *)mp + mp->mp_upper;
4822 memmove(base + sz, base, ptr - mp->mp_upper);
4824 mp->mp_lower -= sizeof(indx_t);
4828 /** Compact the main page after deleting a node on a subpage.
4829 * @param[in] mp The main page to operate on.
4830 * @param[in] indx The index of the subpage on the main page.
4833 mdb_node_shrink(MDB_page *mp, indx_t indx)
4840 indx_t i, numkeys, ptr;
4842 node = NODEPTR(mp, indx);
4843 sp = (MDB_page *)NODEDATA(node);
4844 osize = NODEDSZ(node);
4846 delta = sp->mp_upper - sp->mp_lower;
4847 SETDSZ(node, osize - delta);
4848 xp = (MDB_page *)((char *)sp + delta);
4850 /* shift subpage upward */
4852 nsize = NUMKEYS(sp) * sp->mp_pad;
4853 memmove(METADATA(xp), METADATA(sp), nsize);
4856 nsize = osize - sp->mp_upper;
4857 numkeys = NUMKEYS(sp);
4858 for (i=numkeys-1; i>=0; i--)
4859 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4861 xp->mp_upper = sp->mp_lower;
4862 xp->mp_lower = sp->mp_lower;
4863 xp->mp_flags = sp->mp_flags;
4864 xp->mp_pad = sp->mp_pad;
4865 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4867 /* shift lower nodes upward */
4868 ptr = mp->mp_ptrs[indx];
4869 numkeys = NUMKEYS(mp);
4870 for (i = 0; i < numkeys; i++) {
4871 if (mp->mp_ptrs[i] <= ptr)
4872 mp->mp_ptrs[i] += delta;
4875 base = (char *)mp + mp->mp_upper;
4876 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4877 mp->mp_upper += delta;
4880 /** Initial setup of a sorted-dups cursor.
4881 * Sorted duplicates are implemented as a sub-database for the given key.
4882 * The duplicate data items are actually keys of the sub-database.
4883 * Operations on the duplicate data items are performed using a sub-cursor
4884 * initialized when the sub-database is first accessed. This function does
4885 * the preliminary setup of the sub-cursor, filling in the fields that
4886 * depend only on the parent DB.
4887 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4890 mdb_xcursor_init0(MDB_cursor *mc)
4892 MDB_xcursor *mx = mc->mc_xcursor;
4894 mx->mx_cursor.mc_xcursor = NULL;
4895 mx->mx_cursor.mc_txn = mc->mc_txn;
4896 mx->mx_cursor.mc_db = &mx->mx_db;
4897 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4898 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4899 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4900 mx->mx_cursor.mc_snum = 0;
4901 mx->mx_cursor.mc_top = 0;
4902 mx->mx_cursor.mc_flags = C_SUB;
4903 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4904 mx->mx_dbx.md_dcmp = NULL;
4905 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4908 /** Final setup of a sorted-dups cursor.
4909 * Sets up the fields that depend on the data from the main cursor.
4910 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4911 * @param[in] node The data containing the #MDB_db record for the
4912 * sorted-dup database.
4915 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4917 MDB_xcursor *mx = mc->mc_xcursor;
4919 if (node->mn_flags & F_SUBDATA) {
4920 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
4921 mx->mx_cursor.mc_snum = 0;
4922 mx->mx_cursor.mc_flags = C_SUB;
4924 MDB_page *fp = NODEDATA(node);
4925 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4926 mx->mx_db.md_flags = 0;
4927 mx->mx_db.md_depth = 1;
4928 mx->mx_db.md_branch_pages = 0;
4929 mx->mx_db.md_leaf_pages = 1;
4930 mx->mx_db.md_overflow_pages = 0;
4931 mx->mx_db.md_entries = NUMKEYS(fp);
4932 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4933 mx->mx_cursor.mc_snum = 1;
4934 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4935 mx->mx_cursor.mc_top = 0;
4936 mx->mx_cursor.mc_pg[0] = fp;
4937 mx->mx_cursor.mc_ki[0] = 0;
4938 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4939 mx->mx_db.md_flags = MDB_DUPFIXED;
4940 mx->mx_db.md_pad = fp->mp_pad;
4941 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4942 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4945 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4947 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4949 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4950 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4951 #if UINT_MAX < SIZE_MAX
4952 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4953 #ifdef MISALIGNED_OK
4954 mx->mx_dbx.md_cmp = mdb_cmp_long;
4956 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4961 /** Initialize a cursor for a given transaction and database. */
4963 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4968 mc->mc_db = &txn->mt_dbs[dbi];
4969 mc->mc_dbx = &txn->mt_dbxs[dbi];
4970 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4974 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4976 mc->mc_xcursor = mx;
4977 mdb_xcursor_init0(mc);
4979 mc->mc_xcursor = NULL;
4984 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4987 MDB_xcursor *mx = NULL;
4988 size_t size = sizeof(MDB_cursor);
4990 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
4993 /* Allow read access to the freelist */
4994 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
4997 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4998 size += sizeof(MDB_xcursor);
5000 if ((mc = malloc(size)) != NULL) {
5001 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5002 mx = (MDB_xcursor *)(mc + 1);
5004 mdb_cursor_init(mc, txn, dbi, mx);
5005 if (txn->mt_cursors) {
5006 mc->mc_next = txn->mt_cursors[dbi];
5007 txn->mt_cursors[dbi] = mc;
5009 mc->mc_flags |= C_ALLOCD;
5019 /* Return the count of duplicate data items for the current key */
5021 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5025 if (mc == NULL || countp == NULL)
5028 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5031 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5032 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5035 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5038 *countp = mc->mc_xcursor->mx_db.md_entries;
5044 mdb_cursor_close(MDB_cursor *mc)
5047 /* remove from txn, if tracked */
5048 if (mc->mc_txn->mt_cursors) {
5049 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5050 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5052 *prev = mc->mc_next;
5054 if (mc->mc_flags & C_ALLOCD)
5060 mdb_cursor_txn(MDB_cursor *mc)
5062 if (!mc) return NULL;
5067 mdb_cursor_dbi(MDB_cursor *mc)
5073 /** Replace the key for a node with a new key.
5074 * @param[in] mp The page containing the node to operate on.
5075 * @param[in] indx The index of the node to operate on.
5076 * @param[in] key The new key to use.
5077 * @return 0 on success, non-zero on failure.
5080 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5086 indx_t ptr, i, numkeys;
5089 node = NODEPTR(mp, indx);
5090 ptr = mp->mp_ptrs[indx];
5094 char kbuf2[(MAXKEYSIZE*2+1)];
5095 k2.mv_data = NODEKEY(node);
5096 k2.mv_size = node->mn_ksize;
5097 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5099 mdb_dkey(&k2, kbuf2),
5105 delta0 = delta = key->mv_size - node->mn_ksize;
5107 /* Must be 2-byte aligned. If new key is
5108 * shorter by 1, the shift will be skipped.
5110 delta += (delta & 1);
5112 if (delta > 0 && SIZELEFT(mp) < delta) {
5113 DPRINTF("OUCH! Not enough room, delta = %d", delta);
5117 numkeys = NUMKEYS(mp);
5118 for (i = 0; i < numkeys; i++) {
5119 if (mp->mp_ptrs[i] <= ptr)
5120 mp->mp_ptrs[i] -= delta;
5123 base = (char *)mp + mp->mp_upper;
5124 len = ptr - mp->mp_upper + NODESIZE;
5125 memmove(base - delta, base, len);
5126 mp->mp_upper -= delta;
5128 node = NODEPTR(mp, indx);
5131 /* But even if no shift was needed, update ksize */
5133 node->mn_ksize = key->mv_size;
5136 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5141 /** Move a node from csrc to cdst.
5144 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5150 unsigned short flags;
5154 /* Mark src and dst as dirty. */
5155 if ((rc = mdb_page_touch(csrc)) ||
5156 (rc = mdb_page_touch(cdst)))
5159 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5160 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5161 key.mv_size = csrc->mc_db->md_pad;
5162 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5164 data.mv_data = NULL;
5168 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5169 assert(!((long)srcnode&1));
5170 srcpg = NODEPGNO(srcnode);
5171 flags = srcnode->mn_flags;
5172 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5173 unsigned int snum = csrc->mc_snum;
5175 /* must find the lowest key below src */
5176 mdb_page_search_root(csrc, NULL, 0);
5177 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5178 key.mv_size = NODEKSZ(s2);
5179 key.mv_data = NODEKEY(s2);
5180 csrc->mc_snum = snum--;
5181 csrc->mc_top = snum;
5183 key.mv_size = NODEKSZ(srcnode);
5184 key.mv_data = NODEKEY(srcnode);
5186 data.mv_size = NODEDSZ(srcnode);
5187 data.mv_data = NODEDATA(srcnode);
5189 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5190 unsigned int snum = cdst->mc_snum;
5193 /* must find the lowest key below dst */
5194 mdb_page_search_root(cdst, NULL, 0);
5195 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5196 bkey.mv_size = NODEKSZ(s2);
5197 bkey.mv_data = NODEKEY(s2);
5198 cdst->mc_snum = snum--;
5199 cdst->mc_top = snum;
5200 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5203 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5204 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5205 csrc->mc_ki[csrc->mc_top],
5207 csrc->mc_pg[csrc->mc_top]->mp_pgno,
5208 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5210 /* Add the node to the destination page.
5212 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5213 if (rc != MDB_SUCCESS)
5216 /* Delete the node from the source page.
5218 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5221 /* Adjust other cursors pointing to mp */
5222 MDB_cursor *m2, *m3;
5223 MDB_dbi dbi = csrc->mc_dbi;
5224 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5226 if (csrc->mc_flags & C_SUB)
5229 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5230 if (m2 == csrc) continue;
5231 if (csrc->mc_flags & C_SUB)
5232 m3 = &m2->mc_xcursor->mx_cursor;
5235 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5236 csrc->mc_ki[csrc->mc_top]) {
5237 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5238 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5243 /* Update the parent separators.
5245 if (csrc->mc_ki[csrc->mc_top] == 0) {
5246 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5247 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5248 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5250 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5251 key.mv_size = NODEKSZ(srcnode);
5252 key.mv_data = NODEKEY(srcnode);
5254 DPRINTF("update separator for source page %zu to [%s]",
5255 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5256 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5257 &key)) != MDB_SUCCESS)
5260 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5262 nullkey.mv_size = 0;
5263 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5264 assert(rc == MDB_SUCCESS);
5268 if (cdst->mc_ki[cdst->mc_top] == 0) {
5269 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5270 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5271 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5273 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5274 key.mv_size = NODEKSZ(srcnode);
5275 key.mv_data = NODEKEY(srcnode);
5277 DPRINTF("update separator for destination page %zu to [%s]",
5278 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5279 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5280 &key)) != MDB_SUCCESS)
5283 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5285 nullkey.mv_size = 0;
5286 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5287 assert(rc == MDB_SUCCESS);
5294 /** Merge one page into another.
5295 * The nodes from the page pointed to by \b csrc will
5296 * be copied to the page pointed to by \b cdst and then
5297 * the \b csrc page will be freed.
5298 * @param[in] csrc Cursor pointing to the source page.
5299 * @param[in] cdst Cursor pointing to the destination page.
5302 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5310 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5311 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5313 assert(csrc->mc_snum > 1); /* can't merge root page */
5314 assert(cdst->mc_snum > 1);
5316 /* Mark dst as dirty. */
5317 if ((rc = mdb_page_touch(cdst)))
5320 /* Move all nodes from src to dst.
5322 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5323 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5324 key.mv_size = csrc->mc_db->md_pad;
5325 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5326 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5327 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5328 if (rc != MDB_SUCCESS)
5330 key.mv_data = (char *)key.mv_data + key.mv_size;
5333 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5334 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5335 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5336 unsigned int snum = csrc->mc_snum;
5338 /* must find the lowest key below src */
5339 mdb_page_search_root(csrc, NULL, 0);
5340 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5341 key.mv_size = NODEKSZ(s2);
5342 key.mv_data = NODEKEY(s2);
5343 csrc->mc_snum = snum--;
5344 csrc->mc_top = snum;
5346 key.mv_size = srcnode->mn_ksize;
5347 key.mv_data = NODEKEY(srcnode);
5350 data.mv_size = NODEDSZ(srcnode);
5351 data.mv_data = NODEDATA(srcnode);
5352 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5353 if (rc != MDB_SUCCESS)
5358 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5359 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);
5361 /* Unlink the src page from parent and add to free list.
5363 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5364 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5366 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5370 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5371 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5372 csrc->mc_db->md_leaf_pages--;
5374 csrc->mc_db->md_branch_pages--;
5376 /* Adjust other cursors pointing to mp */
5377 MDB_cursor *m2, *m3;
5378 MDB_dbi dbi = csrc->mc_dbi;
5379 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5381 if (csrc->mc_flags & C_SUB)
5384 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5385 if (csrc->mc_flags & C_SUB)
5386 m3 = &m2->mc_xcursor->mx_cursor;
5389 if (m3 == csrc) continue;
5390 if (m3->mc_snum < csrc->mc_snum) continue;
5391 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5392 m3->mc_pg[csrc->mc_top] = mp;
5393 m3->mc_ki[csrc->mc_top] += nkeys;
5397 mdb_cursor_pop(csrc);
5399 return mdb_rebalance(csrc);
5402 /** Copy the contents of a cursor.
5403 * @param[in] csrc The cursor to copy from.
5404 * @param[out] cdst The cursor to copy to.
5407 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5411 cdst->mc_txn = csrc->mc_txn;
5412 cdst->mc_dbi = csrc->mc_dbi;
5413 cdst->mc_db = csrc->mc_db;
5414 cdst->mc_dbx = csrc->mc_dbx;
5415 cdst->mc_snum = csrc->mc_snum;
5416 cdst->mc_top = csrc->mc_top;
5417 cdst->mc_flags = csrc->mc_flags;
5419 for (i=0; i<csrc->mc_snum; i++) {
5420 cdst->mc_pg[i] = csrc->mc_pg[i];
5421 cdst->mc_ki[i] = csrc->mc_ki[i];
5425 /** Rebalance the tree after a delete operation.
5426 * @param[in] mc Cursor pointing to the page where rebalancing
5428 * @return 0 on success, non-zero on failure.
5431 mdb_rebalance(MDB_cursor *mc)
5441 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5442 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5443 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5444 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5448 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5451 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5452 DPRINTF("no need to rebalance page %zu, above fill threshold",
5458 if (mc->mc_snum < 2) {
5459 MDB_page *mp = mc->mc_pg[0];
5460 if (NUMKEYS(mp) == 0) {
5461 DPUTS("tree is completely empty");
5462 mc->mc_db->md_root = P_INVALID;
5463 mc->mc_db->md_depth = 0;
5464 mc->mc_db->md_leaf_pages = 0;
5465 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5469 /* Adjust other cursors pointing to mp */
5470 MDB_cursor *m2, *m3;
5471 MDB_dbi dbi = mc->mc_dbi;
5473 if (mc->mc_flags & C_SUB)
5476 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5477 if (m2 == mc) continue;
5478 if (mc->mc_flags & C_SUB)
5479 m3 = &m2->mc_xcursor->mx_cursor;
5482 if (m3->mc_snum < mc->mc_snum) continue;
5483 if (m3->mc_pg[0] == mp) {
5489 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5490 DPUTS("collapsing root page!");
5491 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5492 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5493 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5496 mc->mc_db->md_depth--;
5497 mc->mc_db->md_branch_pages--;
5499 /* Adjust other cursors pointing to mp */
5500 MDB_cursor *m2, *m3;
5501 MDB_dbi dbi = mc->mc_dbi;
5503 if (mc->mc_flags & C_SUB)
5506 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5507 if (m2 == mc) continue;
5508 if (mc->mc_flags & C_SUB)
5509 m3 = &m2->mc_xcursor->mx_cursor;
5512 if (m3->mc_snum < mc->mc_snum) continue;
5513 if (m3->mc_pg[0] == mp) {
5514 m3->mc_pg[0] = mc->mc_pg[0];
5519 DPUTS("root page doesn't need rebalancing");
5523 /* The parent (branch page) must have at least 2 pointers,
5524 * otherwise the tree is invalid.
5526 ptop = mc->mc_top-1;
5527 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5529 /* Leaf page fill factor is below the threshold.
5530 * Try to move keys from left or right neighbor, or
5531 * merge with a neighbor page.
5536 mdb_cursor_copy(mc, &mn);
5537 mn.mc_xcursor = NULL;
5539 if (mc->mc_ki[ptop] == 0) {
5540 /* We're the leftmost leaf in our parent.
5542 DPUTS("reading right neighbor");
5544 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5545 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5547 mn.mc_ki[mn.mc_top] = 0;
5548 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5550 /* There is at least one neighbor to the left.
5552 DPUTS("reading left neighbor");
5554 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5555 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5557 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5558 mc->mc_ki[mc->mc_top] = 0;
5561 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5562 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);
5564 /* If the neighbor page is above threshold and has at least two
5565 * keys, move one key from it.
5567 * Otherwise we should try to merge them.
5569 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5570 return mdb_node_move(&mn, mc);
5571 else { /* FIXME: if (has_enough_room()) */
5572 mc->mc_flags &= ~C_INITIALIZED;
5573 if (mc->mc_ki[ptop] == 0)
5574 return mdb_page_merge(&mn, mc);
5576 return mdb_page_merge(mc, &mn);
5580 /** Complete a delete operation started by #mdb_cursor_del(). */
5582 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5586 /* add overflow pages to free list */
5587 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5591 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5592 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5593 mc->mc_db->md_overflow_pages -= ovpages;
5594 for (i=0; i<ovpages; i++) {
5595 DPRINTF("freed ov page %zu", pg);
5596 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5600 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5601 mc->mc_db->md_entries--;
5602 rc = mdb_rebalance(mc);
5603 if (rc != MDB_SUCCESS)
5604 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5610 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5611 MDB_val *key, MDB_val *data)
5616 MDB_val rdata, *xdata;
5620 assert(key != NULL);
5622 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5624 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5627 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5631 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5635 mdb_cursor_init(&mc, txn, dbi, &mx);
5646 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5648 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5652 /** Split a page and insert a new node.
5653 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5654 * The cursor will be updated to point to the actual page and index where
5655 * the node got inserted after the split.
5656 * @param[in] newkey The key for the newly inserted node.
5657 * @param[in] newdata The data for the newly inserted node.
5658 * @param[in] newpgno The page number, if the new node is a branch node.
5659 * @return 0 on success, non-zero on failure.
5662 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5663 unsigned int nflags)
5666 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1;
5669 unsigned int i, j, split_indx, nkeys, pmax;
5671 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5673 MDB_page *mp, *rp, *pp;
5678 mp = mc->mc_pg[mc->mc_top];
5679 newindx = mc->mc_ki[mc->mc_top];
5681 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5682 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5683 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5685 /* Create a right sibling. */
5686 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5688 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5690 if (mc->mc_snum < 2) {
5691 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5693 /* shift current top to make room for new parent */
5694 mc->mc_pg[1] = mc->mc_pg[0];
5695 mc->mc_ki[1] = mc->mc_ki[0];
5698 mc->mc_db->md_root = pp->mp_pgno;
5699 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5700 mc->mc_db->md_depth++;
5703 /* Add left (implicit) pointer. */
5704 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5705 /* undo the pre-push */
5706 mc->mc_pg[0] = mc->mc_pg[1];
5707 mc->mc_ki[0] = mc->mc_ki[1];
5708 mc->mc_db->md_root = mp->mp_pgno;
5709 mc->mc_db->md_depth--;
5716 ptop = mc->mc_top-1;
5717 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5720 mdb_cursor_copy(mc, &mn);
5721 mn.mc_pg[mn.mc_top] = rp;
5722 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5724 if (nflags & MDB_APPEND) {
5725 mn.mc_ki[mn.mc_top] = 0;
5732 nkeys = NUMKEYS(mp);
5733 split_indx = (nkeys + 1) / 2;
5738 unsigned int lsize, rsize, ksize;
5739 /* Move half of the keys to the right sibling */
5741 x = mc->mc_ki[mc->mc_top] - split_indx;
5742 ksize = mc->mc_db->md_pad;
5743 split = LEAF2KEY(mp, split_indx, ksize);
5744 rsize = (nkeys - split_indx) * ksize;
5745 lsize = (nkeys - split_indx) * sizeof(indx_t);
5746 mp->mp_lower -= lsize;
5747 rp->mp_lower += lsize;
5748 mp->mp_upper += rsize - lsize;
5749 rp->mp_upper -= rsize - lsize;
5750 sepkey.mv_size = ksize;
5751 if (newindx == split_indx) {
5752 sepkey.mv_data = newkey->mv_data;
5754 sepkey.mv_data = split;
5757 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5758 memcpy(rp->mp_ptrs, split, rsize);
5759 sepkey.mv_data = rp->mp_ptrs;
5760 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5761 memcpy(ins, newkey->mv_data, ksize);
5762 mp->mp_lower += sizeof(indx_t);
5763 mp->mp_upper -= ksize - sizeof(indx_t);
5766 memcpy(rp->mp_ptrs, split, x * ksize);
5767 ins = LEAF2KEY(rp, x, ksize);
5768 memcpy(ins, newkey->mv_data, ksize);
5769 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5770 rp->mp_lower += sizeof(indx_t);
5771 rp->mp_upper -= ksize - sizeof(indx_t);
5772 mc->mc_ki[mc->mc_top] = x;
5773 mc->mc_pg[mc->mc_top] = rp;
5778 /* For leaf pages, check the split point based on what
5779 * fits where, since otherwise mdb_node_add can fail.
5781 * This check is only needed when the data items are
5782 * relatively large, such that being off by one will
5783 * make the difference between success or failure.
5784 * When the size of the data items is much smaller than
5785 * one-half of a page, this check is irrelevant.
5788 unsigned int psize, nsize;
5789 /* Maximum free space in an empty page */
5790 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5791 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5792 if ((nkeys < 20) || (nsize > pmax/4)) {
5793 if (newindx <= split_indx) {
5796 for (i=0; i<split_indx; i++) {
5797 node = NODEPTR(mp, i);
5798 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5799 if (F_ISSET(node->mn_flags, F_BIGDATA))
5800 psize += sizeof(pgno_t);
5802 psize += NODEDSZ(node);
5805 if (i == split_indx - 1 && newindx == split_indx)
5814 for (i=nkeys-1; i>=split_indx; i--) {
5815 node = NODEPTR(mp, i);
5816 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5817 if (F_ISSET(node->mn_flags, F_BIGDATA))
5818 psize += sizeof(pgno_t);
5820 psize += NODEDSZ(node);
5831 /* First find the separating key between the split pages.
5832 * The case where newindx == split_indx is ambiguous; the
5833 * new item could go to the new page or stay on the original
5834 * page. If newpos == 1 it goes to the new page.
5836 if (newindx == split_indx && newpos) {
5837 sepkey.mv_size = newkey->mv_size;
5838 sepkey.mv_data = newkey->mv_data;
5840 node = NODEPTR(mp, split_indx);
5841 sepkey.mv_size = node->mn_ksize;
5842 sepkey.mv_data = NODEKEY(node);
5846 DPRINTF("separator is [%s]", DKEY(&sepkey));
5848 /* Copy separator key to the parent.
5850 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5853 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5855 /* Right page might now have changed parent.
5856 * Check if left page also changed parent.
5858 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5859 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5860 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5861 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5865 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5868 if (rc != MDB_SUCCESS) {
5871 if (nflags & MDB_APPEND) {
5872 mc->mc_pg[mc->mc_top] = rp;
5873 mc->mc_ki[mc->mc_top] = 0;
5874 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5883 /* Move half of the keys to the right sibling. */
5885 /* grab a page to hold a temporary copy */
5886 copy = mdb_page_malloc(mc);
5890 copy->mp_pgno = mp->mp_pgno;
5891 copy->mp_flags = mp->mp_flags;
5892 copy->mp_lower = PAGEHDRSZ;
5893 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5894 mc->mc_pg[mc->mc_top] = copy;
5895 for (i = j = 0; i <= nkeys; j++) {
5896 if (i == split_indx) {
5897 /* Insert in right sibling. */
5898 /* Reset insert index for right sibling. */
5899 if (i != newindx || (newpos ^ ins_new)) {
5901 mc->mc_pg[mc->mc_top] = rp;
5905 if (i == newindx && !ins_new) {
5906 /* Insert the original entry that caused the split. */
5907 rkey.mv_data = newkey->mv_data;
5908 rkey.mv_size = newkey->mv_size;
5917 /* Update index for the new key. */
5918 mc->mc_ki[mc->mc_top] = j;
5919 } else if (i == nkeys) {
5922 node = NODEPTR(mp, i);
5923 rkey.mv_data = NODEKEY(node);
5924 rkey.mv_size = node->mn_ksize;
5926 xdata.mv_data = NODEDATA(node);
5927 xdata.mv_size = NODEDSZ(node);
5930 pgno = NODEPGNO(node);
5931 flags = node->mn_flags;
5936 if (!IS_LEAF(mp) && j == 0) {
5937 /* First branch index doesn't need key data. */
5941 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5945 nkeys = NUMKEYS(copy);
5946 for (i=0; i<nkeys; i++)
5947 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5948 mp->mp_lower = copy->mp_lower;
5949 mp->mp_upper = copy->mp_upper;
5950 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5951 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5953 /* reset back to original page */
5954 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
5955 mc->mc_pg[mc->mc_top] = mp;
5956 if (nflags & MDB_RESERVE) {
5957 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5958 if (!(node->mn_flags & F_BIGDATA))
5959 newdata->mv_data = NODEDATA(node);
5963 /* return tmp page to freelist */
5964 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5965 VGMEMP_FREE(mc->mc_txn->mt_env, copy);
5966 mc->mc_txn->mt_env->me_dpages = copy;
5969 /* Adjust other cursors pointing to mp */
5970 MDB_cursor *m2, *m3;
5971 MDB_dbi dbi = mc->mc_dbi;
5973 if (mc->mc_flags & C_SUB)
5976 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5977 if (m2 == mc) continue;
5978 if (mc->mc_flags & C_SUB)
5979 m3 = &m2->mc_xcursor->mx_cursor;
5982 if (!(m3->mc_flags & C_INITIALIZED))
5987 for (k=m3->mc_top; k>=0; k--) {
5988 m3->mc_ki[k+1] = m3->mc_ki[k];
5989 m3->mc_pg[k+1] = m3->mc_pg[k];
5991 m3->mc_ki[0] = mc->mc_ki[0];
5992 m3->mc_pg[0] = mc->mc_pg[0];
5996 if (m3->mc_pg[mc->mc_top] == mp) {
5997 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5998 m3->mc_pg[m3->mc_top] = rp;
5999 m3->mc_ki[m3->mc_top] -= split_indx;
6008 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6009 MDB_val *key, MDB_val *data, unsigned int flags)
6014 assert(key != NULL);
6015 assert(data != NULL);
6017 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6020 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6024 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
6028 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6031 mdb_cursor_init(&mc, txn, dbi, &mx);
6032 return mdb_cursor_put(&mc, key, data, flags);
6035 /** Only a subset of the @ref mdb_env flags can be changed
6036 * at runtime. Changing other flags requires closing the environment
6037 * and re-opening it with the new flags.
6039 #define CHANGEABLE (MDB_NOSYNC)
6041 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6043 if ((flag & CHANGEABLE) != flag)
6046 env->me_flags |= flag;
6048 env->me_flags &= ~flag;
6053 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6058 *arg = env->me_flags;
6063 mdb_env_get_path(MDB_env *env, const char **arg)
6068 *arg = env->me_path;
6072 /** Common code for #mdb_stat() and #mdb_env_stat().
6073 * @param[in] env the environment to operate in.
6074 * @param[in] db the #MDB_db record containing the stats to return.
6075 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6076 * @return 0, this function always succeeds.
6079 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6081 arg->ms_psize = env->me_psize;
6082 arg->ms_depth = db->md_depth;
6083 arg->ms_branch_pages = db->md_branch_pages;
6084 arg->ms_leaf_pages = db->md_leaf_pages;
6085 arg->ms_overflow_pages = db->md_overflow_pages;
6086 arg->ms_entries = db->md_entries;
6091 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6095 if (env == NULL || arg == NULL)
6098 toggle = mdb_env_pick_meta(env);
6100 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6103 /** Set the default comparison functions for a database.
6104 * Called immediately after a database is opened to set the defaults.
6105 * The user can then override them with #mdb_set_compare() or
6106 * #mdb_set_dupsort().
6107 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6108 * @param[in] dbi A database handle returned by #mdb_open()
6111 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6113 uint16_t f = txn->mt_dbs[dbi].md_flags;
6115 txn->mt_dbxs[dbi].md_cmp =
6116 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
6117 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
6119 txn->mt_dbxs[dbi].md_dcmp =
6120 !(f & MDB_DUPSORT) ? 0 :
6121 ((f & MDB_INTEGERDUP)
6122 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
6123 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
6126 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6131 int rc, dbflag, exact;
6134 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6135 mdb_default_cmp(txn, FREE_DBI);
6141 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6142 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6143 mdb_default_cmp(txn, MAIN_DBI);
6147 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6148 mdb_default_cmp(txn, MAIN_DBI);
6151 /* Is the DB already open? */
6153 for (i=2; i<txn->mt_numdbs; i++) {
6154 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6155 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6161 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6164 /* Find the DB info */
6168 key.mv_data = (void *)name;
6169 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6170 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6171 if (rc == MDB_SUCCESS) {
6172 /* make sure this is actually a DB */
6173 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6174 if (!(node->mn_flags & F_SUBDATA))
6176 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6177 /* Create if requested */
6179 data.mv_size = sizeof(MDB_db);
6180 data.mv_data = &dummy;
6181 memset(&dummy, 0, sizeof(dummy));
6182 dummy.md_root = P_INVALID;
6183 dummy.md_flags = flags & 0xffff;
6184 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6188 /* OK, got info, add to table */
6189 if (rc == MDB_SUCCESS) {
6190 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
6191 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
6192 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
6193 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
6194 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
6195 *dbi = txn->mt_numdbs;
6196 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6197 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6198 mdb_default_cmp(txn, txn->mt_numdbs);
6205 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6207 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6210 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6213 void mdb_close(MDB_env *env, MDB_dbi dbi)
6216 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6218 ptr = env->me_dbxs[dbi].md_name.mv_data;
6219 env->me_dbxs[dbi].md_name.mv_data = NULL;
6220 env->me_dbxs[dbi].md_name.mv_size = 0;
6224 /** Add all the DB's pages to the free list.
6225 * @param[in] mc Cursor on the DB to free.
6226 * @param[in] subs non-Zero to check for sub-DBs in this DB.
6227 * @return 0 on success, non-zero on failure.
6230 mdb_drop0(MDB_cursor *mc, int subs)
6234 rc = mdb_page_search(mc, NULL, 0);
6235 if (rc == MDB_SUCCESS) {
6240 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6241 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6244 mdb_cursor_copy(mc, &mx);
6245 while (mc->mc_snum > 0) {
6246 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6247 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6248 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6249 if (ni->mn_flags & F_SUBDATA) {
6250 mdb_xcursor_init1(mc, ni);
6251 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6257 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6259 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6262 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6267 rc = mdb_cursor_sibling(mc, 1);
6269 /* no more siblings, go back to beginning
6270 * of previous level. (stack was already popped
6271 * by mdb_cursor_sibling)
6273 for (i=1; i<mc->mc_top; i++)
6274 mc->mc_pg[i] = mx.mc_pg[i];
6278 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6279 mc->mc_db->md_root);
6284 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6289 if (!txn || !dbi || dbi >= txn->mt_numdbs)
6292 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6295 rc = mdb_cursor_open(txn, dbi, &mc);
6299 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6303 /* Can't delete the main DB */
6304 if (del && dbi > MAIN_DBI) {
6305 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6307 mdb_close(txn->mt_env, dbi);
6309 txn->mt_dbflags[dbi] |= DB_DIRTY;
6310 txn->mt_dbs[dbi].md_depth = 0;
6311 txn->mt_dbs[dbi].md_branch_pages = 0;
6312 txn->mt_dbs[dbi].md_leaf_pages = 0;
6313 txn->mt_dbs[dbi].md_overflow_pages = 0;
6314 txn->mt_dbs[dbi].md_entries = 0;
6315 txn->mt_dbs[dbi].md_root = P_INVALID;
6318 mdb_cursor_close(mc);
6322 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6324 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6327 txn->mt_dbxs[dbi].md_cmp = cmp;
6331 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6333 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6336 txn->mt_dbxs[dbi].md_dcmp = cmp;
6340 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6342 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6345 txn->mt_dbxs[dbi].md_rel = rel;
6349 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6351 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6354 txn->mt_dbxs[dbi].md_relctx = ctx;