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-2013 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.
36 #include <sys/types.h>
38 #include <sys/param.h>
44 #ifdef HAVE_SYS_FILE_H
61 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
62 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
65 #if defined(__APPLE__) || defined (BSD)
66 # define MDB_USE_POSIX_SEM 1
67 # define MDB_FDATASYNC fsync
68 #elif defined(ANDROID)
69 # define MDB_FDATASYNC fsync
74 #ifdef MDB_USE_POSIX_SEM
75 #include <semaphore.h>
80 #include <valgrind/memcheck.h>
81 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
82 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
83 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
84 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
85 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
87 #define VGMEMP_CREATE(h,r,z)
88 #define VGMEMP_ALLOC(h,a,s)
89 #define VGMEMP_FREE(h,a)
90 #define VGMEMP_DESTROY(h)
91 #define VGMEMP_DEFINED(a,s)
95 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
96 /* Solaris just defines one or the other */
97 # define LITTLE_ENDIAN 1234
98 # define BIG_ENDIAN 4321
99 # ifdef _LITTLE_ENDIAN
100 # define BYTE_ORDER LITTLE_ENDIAN
102 # define BYTE_ORDER BIG_ENDIAN
105 # define BYTE_ORDER __BYTE_ORDER
109 #ifndef LITTLE_ENDIAN
110 #define LITTLE_ENDIAN __LITTLE_ENDIAN
113 #define BIG_ENDIAN __BIG_ENDIAN
116 #if defined(__i386) || defined(__x86_64)
117 #define MISALIGNED_OK 1
123 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
124 # error "Unknown or unsupported endianness (BYTE_ORDER)"
125 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
126 # error "Two's complement, reasonably sized integer types, please"
129 /** @defgroup internal MDB Internals
132 /** @defgroup compat Windows Compatibility Macros
133 * A bunch of macros to minimize the amount of platform-specific ifdefs
134 * needed throughout the rest of the code. When the features this library
135 * needs are similar enough to POSIX to be hidden in a one-or-two line
136 * replacement, this macro approach is used.
140 #define pthread_t DWORD
141 #define pthread_mutex_t HANDLE
142 #define pthread_key_t DWORD
143 #define pthread_self() GetCurrentThreadId()
144 #define pthread_key_create(x,y) \
145 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
146 #define pthread_key_delete(x) TlsFree(x)
147 #define pthread_getspecific(x) TlsGetValue(x)
148 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
149 #define pthread_mutex_unlock(x) ReleaseMutex(x)
150 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
151 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
152 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
153 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
154 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
155 #define getpid() GetCurrentProcessId()
156 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
157 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
158 #define ErrCode() GetLastError()
159 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
160 #define close(fd) CloseHandle(fd)
161 #define munmap(ptr,len) UnmapViewOfFile(ptr)
164 #ifdef MDB_USE_POSIX_SEM
166 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
167 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
168 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
169 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
172 mdb_sem_wait(sem_t *sem)
175 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
180 /** Lock the reader mutex.
182 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
183 /** Unlock the reader mutex.
185 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
187 /** Lock the writer mutex.
188 * Only a single write transaction is allowed at a time. Other writers
189 * will block waiting for this mutex.
191 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
192 /** Unlock the writer mutex.
194 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
195 #endif /* MDB_USE_POSIX_SEM */
197 /** Get the error code for the last failed system function.
199 #define ErrCode() errno
201 /** An abstraction for a file handle.
202 * On POSIX systems file handles are small integers. On Windows
203 * they're opaque pointers.
207 /** A value for an invalid file handle.
208 * Mainly used to initialize file variables and signify that they are
211 #define INVALID_HANDLE_VALUE (-1)
213 /** Get the size of a memory page for the system.
214 * This is the basic size that the platform's memory manager uses, and is
215 * fundamental to the use of memory-mapped files.
217 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
220 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
223 #define MNAME_LEN (sizeof(pthread_mutex_t))
229 /** A flag for opening a file and requesting synchronous data writes.
230 * This is only used when writing a meta page. It's not strictly needed;
231 * we could just do a normal write and then immediately perform a flush.
232 * But if this flag is available it saves us an extra system call.
234 * @note If O_DSYNC is undefined but exists in /usr/include,
235 * preferably set some compiler flag to get the definition.
236 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
239 # define MDB_DSYNC O_DSYNC
243 /** Function for flushing the data of a file. Define this to fsync
244 * if fdatasync() is not supported.
246 #ifndef MDB_FDATASYNC
247 # define MDB_FDATASYNC fdatasync
251 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
262 /** A page number in the database.
263 * Note that 64 bit page numbers are overkill, since pages themselves
264 * already represent 12-13 bits of addressable memory, and the OS will
265 * always limit applications to a maximum of 63 bits of address space.
267 * @note In the #MDB_node structure, we only store 48 bits of this value,
268 * which thus limits us to only 60 bits of addressable data.
270 typedef MDB_ID pgno_t;
272 /** A transaction ID.
273 * See struct MDB_txn.mt_txnid for details.
275 typedef MDB_ID txnid_t;
277 /** @defgroup debug Debug Macros
281 /** Enable debug output.
282 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
283 * read from and written to the database (used for free space management).
288 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
289 # define DPRINTF (void) /* Vararg macros may be unsupported */
291 static int mdb_debug;
292 static txnid_t mdb_debug_start;
294 /** Print a debug message with printf formatting. */
295 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
296 ((void) ((mdb_debug) && \
297 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
299 # define DPRINTF(fmt, ...) ((void) 0)
300 # define MDB_DEBUG_SKIP
302 /** Print a debug string.
303 * The string is printed literally, with no format processing.
305 #define DPUTS(arg) DPRINTF("%s", arg)
308 /** A default memory page size.
309 * The actual size is platform-dependent, but we use this for
310 * boot-strapping. We probably should not be using this any more.
311 * The #GET_PAGESIZE() macro is used to get the actual size.
313 * Note that we don't currently support Huge pages. On Linux,
314 * regular data files cannot use Huge pages, and in general
315 * Huge pages aren't actually pageable. We rely on the OS
316 * demand-pager to read our data and page it out when memory
317 * pressure from other processes is high. So until OSs have
318 * actual paging support for Huge pages, they're not viable.
320 #define MDB_PAGESIZE 4096
322 /** The minimum number of keys required in a database page.
323 * Setting this to a larger value will place a smaller bound on the
324 * maximum size of a data item. Data items larger than this size will
325 * be pushed into overflow pages instead of being stored directly in
326 * the B-tree node. This value used to default to 4. With a page size
327 * of 4096 bytes that meant that any item larger than 1024 bytes would
328 * go into an overflow page. That also meant that on average 2-3KB of
329 * each overflow page was wasted space. The value cannot be lower than
330 * 2 because then there would no longer be a tree structure. With this
331 * value, items larger than 2KB will go into overflow pages, and on
332 * average only 1KB will be wasted.
334 #define MDB_MINKEYS 2
336 /** A stamp that identifies a file as an MDB file.
337 * There's nothing special about this value other than that it is easily
338 * recognizable, and it will reflect any byte order mismatches.
340 #define MDB_MAGIC 0xBEEFC0DE
342 /** The version number for a database's file format. */
343 #define MDB_VERSION 1
345 /** @brief The maximum size of a key in the database.
347 * While data items have essentially unbounded size, we require that
348 * keys all fit onto a regular page. This limit could be raised a bit
349 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
351 * Note that data items in an #MDB_DUPSORT database are actually keys
352 * of a subDB, so they're also limited to this size.
354 #ifndef MDB_MAXKEYSIZE
355 #define MDB_MAXKEYSIZE 511
361 * This is used for printing a hex dump of a key's contents.
363 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
364 /** Display a key in hex.
366 * Invoke a function to display a key in hex.
368 #define DKEY(x) mdb_dkey(x, kbuf)
370 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
374 /** An invalid page number.
375 * Mainly used to denote an empty tree.
377 #define P_INVALID (~(pgno_t)0)
379 /** Test if a flag \b f is set in a flag word \b w. */
380 #define F_ISSET(w, f) (((w) & (f)) == (f))
382 /** Used for offsets within a single page.
383 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
386 typedef uint16_t indx_t;
388 /** Default size of memory map.
389 * This is certainly too small for any actual applications. Apps should always set
390 * the size explicitly using #mdb_env_set_mapsize().
392 #define DEFAULT_MAPSIZE 1048576
394 /** @defgroup readers Reader Lock Table
395 * Readers don't acquire any locks for their data access. Instead, they
396 * simply record their transaction ID in the reader table. The reader
397 * mutex is needed just to find an empty slot in the reader table. The
398 * slot's address is saved in thread-specific data so that subsequent read
399 * transactions started by the same thread need no further locking to proceed.
401 * Since the database uses multi-version concurrency control, readers don't
402 * actually need any locking. This table is used to keep track of which
403 * readers are using data from which old transactions, so that we'll know
404 * when a particular old transaction is no longer in use. Old transactions
405 * that have discarded any data pages can then have those pages reclaimed
406 * for use by a later write transaction.
408 * The lock table is constructed such that reader slots are aligned with the
409 * processor's cache line size. Any slot is only ever used by one thread.
410 * This alignment guarantees that there will be no contention or cache
411 * thrashing as threads update their own slot info, and also eliminates
412 * any need for locking when accessing a slot.
414 * A writer thread will scan every slot in the table to determine the oldest
415 * outstanding reader transaction. Any freed pages older than this will be
416 * reclaimed by the writer. The writer doesn't use any locks when scanning
417 * this table. This means that there's no guarantee that the writer will
418 * see the most up-to-date reader info, but that's not required for correct
419 * operation - all we need is to know the upper bound on the oldest reader,
420 * we don't care at all about the newest reader. So the only consequence of
421 * reading stale information here is that old pages might hang around a
422 * while longer before being reclaimed. That's actually good anyway, because
423 * the longer we delay reclaiming old pages, the more likely it is that a
424 * string of contiguous pages can be found after coalescing old pages from
425 * many old transactions together.
427 * @todo We don't actually do such coalescing yet, we grab pages from one
428 * old transaction at a time.
431 /** Number of slots in the reader table.
432 * This value was chosen somewhat arbitrarily. 126 readers plus a
433 * couple mutexes fit exactly into 8KB on my development machine.
434 * Applications should set the table size using #mdb_env_set_maxreaders().
436 #define DEFAULT_READERS 126
438 /** The size of a CPU cache line in bytes. We want our lock structures
439 * aligned to this size to avoid false cache line sharing in the
441 * This value works for most CPUs. For Itanium this should be 128.
447 /** The information we store in a single slot of the reader table.
448 * In addition to a transaction ID, we also record the process and
449 * thread ID that owns a slot, so that we can detect stale information,
450 * e.g. threads or processes that went away without cleaning up.
451 * @note We currently don't check for stale records. We simply re-init
452 * the table when we know that we're the only process opening the
455 typedef struct MDB_rxbody {
456 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
457 * Multiple readers that start at the same time will probably have the
458 * same ID here. Again, it's not important to exclude them from
459 * anything; all we need to know is which version of the DB they
460 * started from so we can avoid overwriting any data used in that
461 * particular version.
464 /** The process ID of the process owning this reader txn. */
466 /** The thread ID of the thread owning this txn. */
470 /** The actual reader record, with cacheline padding. */
471 typedef struct MDB_reader {
474 /** shorthand for mrb_txnid */
475 #define mr_txnid mru.mrx.mrb_txnid
476 #define mr_pid mru.mrx.mrb_pid
477 #define mr_tid mru.mrx.mrb_tid
478 /** cache line alignment */
479 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
483 /** The header for the reader table.
484 * The table resides in a memory-mapped file. (This is a different file
485 * than is used for the main database.)
487 * For POSIX the actual mutexes reside in the shared memory of this
488 * mapped file. On Windows, mutexes are named objects allocated by the
489 * kernel; we store the mutex names in this mapped file so that other
490 * processes can grab them. This same approach is also used on
491 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
492 * process-shared POSIX mutexes. For these cases where a named object
493 * is used, the object name is derived from a 64 bit FNV hash of the
494 * environment pathname. As such, naming collisions are extremely
495 * unlikely. If a collision occurs, the results are unpredictable.
497 typedef struct MDB_txbody {
498 /** Stamp identifying this as an MDB file. It must be set
501 /** Version number of this lock file. Must be set to #MDB_VERSION. */
502 uint32_t mtb_version;
503 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
504 char mtb_rmname[MNAME_LEN];
506 /** Mutex protecting access to this table.
507 * This is the reader lock that #LOCK_MUTEX_R acquires.
509 pthread_mutex_t mtb_mutex;
511 /** The ID of the last transaction committed to the database.
512 * This is recorded here only for convenience; the value can always
513 * be determined by reading the main database meta pages.
516 /** The number of slots that have been used in the reader table.
517 * This always records the maximum count, it is not decremented
518 * when readers release their slots.
520 unsigned mtb_numreaders;
523 /** The actual reader table definition. */
524 typedef struct MDB_txninfo {
527 #define mti_magic mt1.mtb.mtb_magic
528 #define mti_version mt1.mtb.mtb_version
529 #define mti_mutex mt1.mtb.mtb_mutex
530 #define mti_rmname mt1.mtb.mtb_rmname
531 #define mti_txnid mt1.mtb.mtb_txnid
532 #define mti_numreaders mt1.mtb.mtb_numreaders
533 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
536 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
537 char mt2_wmname[MNAME_LEN];
538 #define mti_wmname mt2.mt2_wmname
540 pthread_mutex_t mt2_wmutex;
541 #define mti_wmutex mt2.mt2_wmutex
543 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
545 MDB_reader mti_readers[1];
549 /** Common header for all page types.
550 * Overflow records occupy a number of contiguous pages with no
551 * headers on any page after the first.
553 typedef struct MDB_page {
554 #define mp_pgno mp_p.p_pgno
555 #define mp_next mp_p.p_next
557 pgno_t p_pgno; /**< page number */
558 void * p_next; /**< for in-memory list of freed structs */
561 /** @defgroup mdb_page Page Flags
563 * Flags for the page headers.
566 #define P_BRANCH 0x01 /**< branch page */
567 #define P_LEAF 0x02 /**< leaf page */
568 #define P_OVERFLOW 0x04 /**< overflow page */
569 #define P_META 0x08 /**< meta page */
570 #define P_DIRTY 0x10 /**< dirty page */
571 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
572 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
574 uint16_t mp_flags; /**< @ref mdb_page */
575 #define mp_lower mp_pb.pb.pb_lower
576 #define mp_upper mp_pb.pb.pb_upper
577 #define mp_pages mp_pb.pb_pages
580 indx_t pb_lower; /**< lower bound of free space */
581 indx_t pb_upper; /**< upper bound of free space */
583 uint32_t pb_pages; /**< number of overflow pages */
585 indx_t mp_ptrs[1]; /**< dynamic size */
588 /** Size of the page header, excluding dynamic data at the end */
589 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
591 /** Address of first usable data byte in a page, after the header */
592 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
594 /** Number of nodes on a page */
595 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
597 /** The amount of space remaining in the page */
598 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
600 /** The percentage of space used in the page, in tenths of a percent. */
601 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
602 ((env)->me_psize - PAGEHDRSZ))
603 /** The minimum page fill factor, in tenths of a percent.
604 * Pages emptier than this are candidates for merging.
606 #define FILL_THRESHOLD 250
608 /** Test if a page is a leaf page */
609 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
610 /** Test if a page is a LEAF2 page */
611 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
612 /** Test if a page is a branch page */
613 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
614 /** Test if a page is an overflow page */
615 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
616 /** Test if a page is a sub page */
617 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
619 /** The number of overflow pages needed to store the given size. */
620 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
622 /** Header for a single key/data pair within a page.
623 * We guarantee 2-byte alignment for nodes.
625 typedef struct MDB_node {
626 /** lo and hi are used for data size on leaf nodes and for
627 * child pgno on branch nodes. On 64 bit platforms, flags
628 * is also used for pgno. (Branch nodes have no flags).
629 * They are in host byte order in case that lets some
630 * accesses be optimized into a 32-bit word access.
632 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
633 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
634 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
635 /** @defgroup mdb_node Node Flags
637 * Flags for node headers.
640 #define F_BIGDATA 0x01 /**< data put on overflow page */
641 #define F_SUBDATA 0x02 /**< data is a sub-database */
642 #define F_DUPDATA 0x04 /**< data has duplicates */
644 /** valid flags for #mdb_node_add() */
645 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
648 unsigned short mn_flags; /**< @ref mdb_node */
649 unsigned short mn_ksize; /**< key size */
650 char mn_data[1]; /**< key and data are appended here */
653 /** Size of the node header, excluding dynamic data at the end */
654 #define NODESIZE offsetof(MDB_node, mn_data)
656 /** Bit position of top word in page number, for shifting mn_flags */
657 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
659 /** Size of a node in a branch page with a given key.
660 * This is just the node header plus the key, there is no data.
662 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
664 /** Size of a node in a leaf page with a given key and data.
665 * This is node header plus key plus data size.
667 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
669 /** Address of node \b i in page \b p */
670 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
672 /** Address of the key for the node */
673 #define NODEKEY(node) (void *)((node)->mn_data)
675 /** Address of the data for a node */
676 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
678 /** Get the page number pointed to by a branch node */
679 #define NODEPGNO(node) \
680 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
681 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
682 /** Set the page number in a branch node */
683 #define SETPGNO(node,pgno) do { \
684 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
685 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
687 /** Get the size of the data in a leaf node */
688 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
689 /** Set the size of the data for a leaf node */
690 #define SETDSZ(node,size) do { \
691 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
692 /** The size of a key in a node */
693 #define NODEKSZ(node) ((node)->mn_ksize)
695 /** Copy a page number from src to dst */
697 #define COPY_PGNO(dst,src) dst = src
699 #if SIZE_MAX > 4294967295UL
700 #define COPY_PGNO(dst,src) do { \
701 unsigned short *s, *d; \
702 s = (unsigned short *)&(src); \
703 d = (unsigned short *)&(dst); \
710 #define COPY_PGNO(dst,src) do { \
711 unsigned short *s, *d; \
712 s = (unsigned short *)&(src); \
713 d = (unsigned short *)&(dst); \
719 /** The address of a key in a LEAF2 page.
720 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
721 * There are no node headers, keys are stored contiguously.
723 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
725 /** Set the \b node's key into \b key, if requested. */
726 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
727 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
729 /** Information about a single database in the environment. */
730 typedef struct MDB_db {
731 uint32_t md_pad; /**< also ksize for LEAF2 pages */
732 uint16_t md_flags; /**< @ref mdb_dbi_open */
733 uint16_t md_depth; /**< depth of this tree */
734 pgno_t md_branch_pages; /**< number of internal pages */
735 pgno_t md_leaf_pages; /**< number of leaf pages */
736 pgno_t md_overflow_pages; /**< number of overflow pages */
737 size_t md_entries; /**< number of data items */
738 pgno_t md_root; /**< the root page of this tree */
741 /** Handle for the DB used to track free pages. */
743 /** Handle for the default DB. */
746 /** Meta page content. */
747 typedef struct MDB_meta {
748 /** Stamp identifying this as an MDB file. It must be set
751 /** Version number of this lock file. Must be set to #MDB_VERSION. */
753 void *mm_address; /**< address for fixed mapping */
754 size_t mm_mapsize; /**< size of mmap region */
755 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
756 /** The size of pages used in this DB */
757 #define mm_psize mm_dbs[0].md_pad
758 /** Any persistent environment flags. @ref mdb_env */
759 #define mm_flags mm_dbs[0].md_flags
760 pgno_t mm_last_pg; /**< last used page in file */
761 txnid_t mm_txnid; /**< txnid that committed this page */
764 /** Buffer for a stack-allocated dirty page.
765 * The members define size and alignment, and silence type
766 * aliasing warnings. They are not used directly; that could
767 * mean incorrectly using several union members in parallel.
769 typedef union MDB_pagebuf {
770 char mb_raw[MDB_PAGESIZE];
773 char mm_pad[PAGEHDRSZ];
778 /** Auxiliary DB info.
779 * The information here is mostly static/read-only. There is
780 * only a single copy of this record in the environment.
782 typedef struct MDB_dbx {
783 MDB_val md_name; /**< name of the database */
784 MDB_cmp_func *md_cmp; /**< function for comparing keys */
785 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
786 MDB_rel_func *md_rel; /**< user relocate function */
787 void *md_relctx; /**< user-provided context for md_rel */
790 /** A database transaction.
791 * Every operation requires a transaction handle.
794 MDB_txn *mt_parent; /**< parent of a nested txn */
795 MDB_txn *mt_child; /**< nested txn under this txn */
796 pgno_t mt_next_pgno; /**< next unallocated page */
797 /** The ID of this transaction. IDs are integers incrementing from 1.
798 * Only committed write transactions increment the ID. If a transaction
799 * aborts, the ID may be re-used by the next writer.
802 MDB_env *mt_env; /**< the DB environment */
803 /** The list of pages that became unused during this transaction.
807 MDB_ID2L dirty_list; /**< modified pages */
808 MDB_reader *reader; /**< this thread's slot in the reader table */
810 /** Array of records for each DB known in the environment. */
812 /** Array of MDB_db records for each known DB */
814 /** @defgroup mt_dbflag Transaction DB Flags
818 #define DB_DIRTY 0x01 /**< DB was written in this txn */
819 #define DB_STALE 0x02 /**< DB record is older than txnID */
821 /** Array of cursors for each DB */
822 MDB_cursor **mt_cursors;
823 /** Array of flags for each DB */
824 unsigned char *mt_dbflags;
825 /** Number of DB records in use. This number only ever increments;
826 * we don't decrement it when individual DB handles are closed.
830 /** @defgroup mdb_txn Transaction Flags
834 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
835 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
836 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
838 unsigned int mt_flags; /**< @ref mdb_txn */
839 /** Tracks which of the two meta pages was used at the start
840 * of this transaction.
842 unsigned int mt_toggle;
845 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
846 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
847 * raise this on a 64 bit machine.
849 #define CURSOR_STACK 32
853 /** Cursors are used for all DB operations */
855 /** Next cursor on this DB in this txn */
857 /** Original cursor if this is a shadow */
859 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
860 struct MDB_xcursor *mc_xcursor;
861 /** The transaction that owns this cursor */
863 /** The database handle this cursor operates on */
865 /** The database record for this cursor */
867 /** The database auxiliary record for this cursor */
869 /** The @ref mt_dbflag for this database */
870 unsigned char *mc_dbflag;
871 unsigned short mc_snum; /**< number of pushed pages */
872 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
873 /** @defgroup mdb_cursor Cursor Flags
875 * Cursor state flags.
878 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
879 #define C_EOF 0x02 /**< No more data */
880 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
881 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
882 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
883 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
885 unsigned int mc_flags; /**< @ref mdb_cursor */
886 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
887 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
890 /** Context for sorted-dup records.
891 * We could have gone to a fully recursive design, with arbitrarily
892 * deep nesting of sub-databases. But for now we only handle these
893 * levels - main DB, optional sub-DB, sorted-duplicate DB.
895 typedef struct MDB_xcursor {
896 /** A sub-cursor for traversing the Dup DB */
897 MDB_cursor mx_cursor;
898 /** The database record for this Dup DB */
900 /** The auxiliary DB record for this Dup DB */
902 /** The @ref mt_dbflag for this Dup DB */
903 unsigned char mx_dbflag;
906 /** A set of pages freed by an earlier transaction. */
907 typedef struct MDB_oldpages {
908 /** Usually we only read one record from the FREEDB at a time, but
909 * in case we read more, this will chain them together.
911 struct MDB_oldpages *mo_next;
912 /** The ID of the transaction in which these pages were freed. */
914 /** An #MDB_IDL of the pages */
915 pgno_t mo_pages[1]; /* dynamic */
918 /** The database environment. */
920 HANDLE me_fd; /**< The main data file */
921 HANDLE me_lfd; /**< The lock file */
922 HANDLE me_mfd; /**< just for writing the meta pages */
923 /** Failed to update the meta page. Probably an I/O error. */
924 #define MDB_FATAL_ERROR 0x80000000U
925 /** Read-only Filesystem. Allow read access, no locking. */
926 #define MDB_ROFS 0x40000000U
927 /** Some fields are initialized. */
928 #define MDB_ENV_ACTIVE 0x20000000U
929 uint32_t me_flags; /**< @ref mdb_env */
930 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
931 unsigned int me_maxreaders; /**< size of the reader table */
932 unsigned int me_numreaders; /**< max numreaders set by this env */
933 MDB_dbi me_numdbs; /**< number of DBs opened */
934 MDB_dbi me_maxdbs; /**< size of the DB table */
935 pid_t me_pid; /**< process ID of this env */
936 char *me_path; /**< path to the DB files */
937 char *me_map; /**< the memory map of the data file */
938 MDB_txninfo *me_txns; /**< the memory map of the lock file */
939 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
940 MDB_txn *me_txn; /**< current write transaction */
941 size_t me_mapsize; /**< size of the data memory map */
942 off_t me_size; /**< current file size */
943 pgno_t me_maxpg; /**< me_mapsize / me_psize */
944 txnid_t me_pgfirst; /**< ID of first old page record we used */
945 txnid_t me_pglast; /**< ID of last old page record we used */
946 MDB_dbx *me_dbxs; /**< array of static DB info */
947 uint16_t *me_dbflags; /**< array of DB flags */
948 MDB_oldpages *me_pghead; /**< list of old page records */
949 MDB_oldpages *me_pgfree; /**< list of page records to free */
950 pthread_key_t me_txkey; /**< thread-key for readers */
951 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
952 /** IDL of pages that became unused in a write txn */
954 /** ID2L of pages that were written during a write txn */
955 MDB_ID2 me_dirty_list[MDB_IDL_UM_SIZE];
957 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
959 #elif defined(MDB_USE_POSIX_SEM)
960 sem_t *me_rmutex; /* Shared mutexes are not supported */
964 /** max number of pages to commit in one writev() call */
965 #define MDB_COMMIT_PAGES 64
966 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
967 #undef MDB_COMMIT_PAGES
968 #define MDB_COMMIT_PAGES IOV_MAX
971 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
972 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
973 static int mdb_page_touch(MDB_cursor *mc);
975 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
976 static int mdb_page_search_root(MDB_cursor *mc,
977 MDB_val *key, int modify);
978 #define MDB_PS_MODIFY 1
979 #define MDB_PS_ROOTONLY 2
980 static int mdb_page_search(MDB_cursor *mc,
981 MDB_val *key, int flags);
982 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
984 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
985 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
986 pgno_t newpgno, unsigned int nflags);
988 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
989 static int mdb_env_pick_meta(const MDB_env *env);
990 static int mdb_env_write_meta(MDB_txn *txn);
991 static void mdb_env_close0(MDB_env *env, int excl);
993 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
994 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
995 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
996 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
997 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
998 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
999 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1000 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1001 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1003 static int mdb_rebalance(MDB_cursor *mc);
1004 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
1006 static void mdb_cursor_pop(MDB_cursor *mc);
1007 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1009 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1010 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1011 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1012 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1013 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1015 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1016 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1018 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1019 static void mdb_xcursor_init0(MDB_cursor *mc);
1020 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1022 static int mdb_drop0(MDB_cursor *mc, int subs);
1023 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1026 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1030 static SECURITY_DESCRIPTOR mdb_null_sd;
1031 static SECURITY_ATTRIBUTES mdb_all_sa;
1032 static int mdb_sec_inited;
1035 /** Return the library version info. */
1037 mdb_version(int *major, int *minor, int *patch)
1039 if (major) *major = MDB_VERSION_MAJOR;
1040 if (minor) *minor = MDB_VERSION_MINOR;
1041 if (patch) *patch = MDB_VERSION_PATCH;
1042 return MDB_VERSION_STRING;
1045 /** Table of descriptions for MDB @ref errors */
1046 static char *const mdb_errstr[] = {
1047 "MDB_KEYEXIST: Key/data pair already exists",
1048 "MDB_NOTFOUND: No matching key/data pair found",
1049 "MDB_PAGE_NOTFOUND: Requested page not found",
1050 "MDB_CORRUPTED: Located page was wrong type",
1051 "MDB_PANIC: Update of meta page failed",
1052 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1053 "MDB_INVALID: File is not an MDB file",
1054 "MDB_MAP_FULL: Environment mapsize limit reached",
1055 "MDB_DBS_FULL: Environment maxdbs limit reached",
1056 "MDB_READERS_FULL: Environment maxreaders limit reached",
1057 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1058 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1059 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1060 "MDB_PAGE_FULL: Internal error - page has no more space"
1064 mdb_strerror(int err)
1068 return ("Successful return: 0");
1070 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1071 i = err - MDB_KEYEXIST;
1072 return mdb_errstr[i];
1075 return strerror(err);
1079 /** Display a key in hexadecimal and return the address of the result.
1080 * @param[in] key the key to display
1081 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1082 * @return The key in hexadecimal form.
1085 mdb_dkey(MDB_val *key, char *buf)
1088 unsigned char *c = key->mv_data;
1090 if (key->mv_size > MDB_MAXKEYSIZE)
1091 return "MDB_MAXKEYSIZE";
1092 /* may want to make this a dynamic check: if the key is mostly
1093 * printable characters, print it as-is instead of converting to hex.
1097 for (i=0; i<key->mv_size; i++)
1098 ptr += sprintf(ptr, "%02x", *c++);
1100 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1105 /** Display all the keys in the page. */
1107 mdb_page_list(MDB_page *mp)
1110 unsigned int i, nkeys, nsize;
1114 nkeys = NUMKEYS(mp);
1115 fprintf(stderr, "numkeys %d\n", nkeys);
1116 for (i=0; i<nkeys; i++) {
1117 node = NODEPTR(mp, i);
1118 key.mv_size = node->mn_ksize;
1119 key.mv_data = node->mn_data;
1120 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1121 if (F_ISSET(node->mn_flags, F_BIGDATA))
1122 nsize += sizeof(pgno_t);
1124 nsize += NODEDSZ(node);
1125 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1130 mdb_cursor_chk(MDB_cursor *mc)
1136 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1137 for (i=0; i<mc->mc_top; i++) {
1139 node = NODEPTR(mp, mc->mc_ki[i]);
1140 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1143 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1149 /** Count all the pages in each DB and in the freelist
1150 * and make sure it matches the actual number of pages
1153 static void mdb_audit(MDB_txn *txn)
1157 MDB_ID freecount, count;
1162 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1163 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1164 freecount += *(MDB_ID *)data.mv_data;
1167 for (i = 0; i<txn->mt_numdbs; i++) {
1168 MDB_xcursor mx, *mxp;
1169 mxp = (txn->mt_dbs[i].md_flags & MDB_DUPSORT) ? &mx : NULL;
1170 mdb_cursor_init(&mc, txn, i, mxp);
1171 if (txn->mt_dbs[i].md_root == P_INVALID)
1173 count += txn->mt_dbs[i].md_branch_pages +
1174 txn->mt_dbs[i].md_leaf_pages +
1175 txn->mt_dbs[i].md_overflow_pages;
1176 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1177 mdb_page_search(&mc, NULL, 0);
1181 mp = mc.mc_pg[mc.mc_top];
1182 for (j=0; j<NUMKEYS(mp); j++) {
1183 MDB_node *leaf = NODEPTR(mp, j);
1184 if (leaf->mn_flags & F_SUBDATA) {
1186 memcpy(&db, NODEDATA(leaf), sizeof(db));
1187 count += db.md_branch_pages + db.md_leaf_pages +
1188 db.md_overflow_pages;
1192 while (mdb_cursor_sibling(&mc, 1) == 0);
1195 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1196 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1197 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1203 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1205 return txn->mt_dbxs[dbi].md_cmp(a, b);
1209 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1211 if (txn->mt_dbxs[dbi].md_dcmp)
1212 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1214 return EINVAL; /* too bad you can't distinguish this from a valid result */
1217 /** Allocate a single page.
1218 * Re-use old malloc'd pages first, otherwise just malloc.
1221 mdb_page_malloc(MDB_cursor *mc) {
1223 size_t sz = mc->mc_txn->mt_env->me_psize;
1224 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1225 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1226 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1227 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1228 } else if ((ret = malloc(sz)) != NULL) {
1229 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1235 mdb_page_free(MDB_env *env, MDB_page *mp)
1237 mp->mp_next = env->me_dpages;
1238 VGMEMP_FREE(env, mp);
1239 env->me_dpages = mp;
1242 /** Allocate pages for writing.
1243 * If there are free pages available from older transactions, they
1244 * will be re-used first. Otherwise a new page will be allocated.
1245 * @param[in] mc cursor A cursor handle identifying the transaction and
1246 * database for which we are allocating.
1247 * @param[in] num the number of pages to allocate.
1248 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1249 * will always be satisfied by a single contiguous chunk of memory.
1250 * @return 0 on success, non-zero on failure.
1253 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1255 MDB_txn *txn = mc->mc_txn;
1257 pgno_t pgno = P_INVALID;
1259 txnid_t oldest = 0, last;
1264 /* If our dirty list is already full, we can't do anything */
1265 if (txn->mt_u.dirty_list[0].mid >= MDB_IDL_UM_MAX)
1266 return MDB_TXN_FULL;
1268 /* The free list won't have any content at all until txn 2 has
1269 * committed. The pages freed by txn 2 will be unreferenced
1270 * after txn 3 commits, and so will be safe to re-use in txn 4.
1272 if (txn->mt_txnid > 3) {
1274 if (!txn->mt_env->me_pghead &&
1275 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1276 /* See if there's anything in the free DB */
1283 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1284 if (!txn->mt_env->me_pgfirst) {
1285 mdb_page_search(&m2, NULL, 0);
1286 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1287 kptr = (txnid_t *)NODEKEY(leaf);
1294 last = txn->mt_env->me_pglast + 1;
1296 key.mv_data = &last;
1297 key.mv_size = sizeof(last);
1298 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1301 last = *(txnid_t *)key.mv_data;
1307 oldest = txn->mt_txnid - 1;
1308 nr = txn->mt_env->me_txns->mti_numreaders;
1309 r = txn->mt_env->me_txns->mti_readers;
1310 for (i=0; i<nr; i++) {
1311 if (!r[i].mr_pid) continue;
1318 if (oldest > last) {
1319 /* It's usable, grab it.
1324 if (!txn->mt_env->me_pgfirst) {
1325 mdb_node_read(txn, leaf, &data);
1327 txn->mt_env->me_pglast = last;
1328 if (!txn->mt_env->me_pgfirst)
1329 txn->mt_env->me_pgfirst = last;
1330 idl = (MDB_ID *) data.mv_data;
1331 /* We might have a zero-length IDL due to freelist growth
1332 * during a prior commit
1334 if (!idl[0]) goto again;
1335 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1338 mop->mo_next = txn->mt_env->me_pghead;
1339 mop->mo_txnid = last;
1340 txn->mt_env->me_pghead = mop;
1341 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1346 DPRINTF("IDL read txn %zu root %zu num %zu",
1347 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1348 for (i=0; i<idl[0]; i++) {
1349 DPRINTF("IDL %zu", idl[i+1]);
1356 if (txn->mt_env->me_pghead) {
1357 MDB_oldpages *mop = txn->mt_env->me_pghead;
1360 int retry = 500, readit = 0, n2 = num-1;
1361 unsigned int i, j, k;
1363 /* If current list is too short, must fetch more and coalesce */
1364 if (mop->mo_pages[0] < (unsigned)num)
1367 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1369 /* If on freelist, don't try to read more. If what we have
1370 * right now isn't enough just use new pages.
1371 * TODO: get all of this working. Many circular dependencies...
1373 if (mc->mc_dbi == FREE_DBI) {
1383 last = mop->mo_txnid + 1;
1385 /* We haven't hit the readers list yet? */
1391 oldest = txn->mt_txnid - 1;
1392 nr = txn->mt_env->me_txns->mti_numreaders;
1393 r = txn->mt_env->me_txns->mti_readers;
1394 for (i=0; i<nr; i++) {
1395 if (!r[i].mr_pid) continue;
1402 /* There's nothing we can use on the freelist */
1403 if (oldest - last < 1)
1407 key.mv_data = &last;
1408 key.mv_size = sizeof(last);
1409 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1412 idl = (MDB_ID *) data.mv_data;
1413 mop2 = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - 2*sizeof(pgno_t) + MDB_IDL_SIZEOF(mop->mo_pages));
1416 /* merge in sorted order */
1417 i = idl[0]; j = mop->mo_pages[0]; mop2->mo_pages[0] = k = i+j;
1418 mop->mo_pages[0] = P_INVALID;
1419 while (i>0 || j>0) {
1420 if (i && idl[i] < mop->mo_pages[j])
1421 mop2->mo_pages[k--] = idl[i--];
1423 mop2->mo_pages[k--] = mop->mo_pages[j--];
1425 txn->mt_env->me_pglast = last;
1426 mop2->mo_txnid = last;
1427 mop2->mo_next = mop->mo_next;
1428 txn->mt_env->me_pghead = mop2;
1431 /* Keep trying to read until we have enough */
1432 if (mop->mo_pages[0] < (unsigned)num) {
1437 /* current list has enough pages, but are they contiguous? */
1438 for (i=mop->mo_pages[0]; i>=(unsigned)num; i--) {
1439 if (mop->mo_pages[i-n2] == mop->mo_pages[i] + n2) {
1440 pgno = mop->mo_pages[i];
1442 /* move any stragglers down */
1443 for (j=i+num; j<=mop->mo_pages[0]; j++)
1444 mop->mo_pages[i++] = mop->mo_pages[j];
1445 mop->mo_pages[0] -= num;
1450 /* Stop if we succeeded, or no more retries */
1451 if (!retry || pgno != P_INVALID)
1458 /* peel pages off tail, so we only have to truncate the list */
1459 pgno = MDB_IDL_LAST(mop->mo_pages);
1462 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1463 txn->mt_env->me_pghead = mop->mo_next;
1464 if (mc->mc_dbi == FREE_DBI) {
1465 mop->mo_next = txn->mt_env->me_pgfree;
1466 txn->mt_env->me_pgfree = mop;
1474 if (pgno == P_INVALID) {
1475 /* DB size is maxed out */
1476 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1477 DPUTS("DB size maxed out");
1478 return MDB_MAP_FULL;
1481 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1482 if (pgno == P_INVALID) {
1483 pgno = txn->mt_next_pgno;
1484 txn->mt_next_pgno += num;
1486 np = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1489 if (txn->mt_env->me_dpages && num == 1) {
1490 np = txn->mt_env->me_dpages;
1491 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1492 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1493 txn->mt_env->me_dpages = np->mp_next;
1495 size_t sz = txn->mt_env->me_psize * num;
1496 if ((np = malloc(sz)) == NULL)
1498 VGMEMP_ALLOC(txn->mt_env, np, sz);
1500 if (pgno == P_INVALID) {
1501 np->mp_pgno = txn->mt_next_pgno;
1502 txn->mt_next_pgno += num;
1507 mid.mid = np->mp_pgno;
1509 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1510 mdb_mid2l_append(txn->mt_u.dirty_list, &mid);
1512 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1519 /** Copy a page: avoid copying unused portions of the page.
1520 * @param[in] dst page to copy into
1521 * @param[in] src page to copy from
1524 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1526 dst->mp_flags = src->mp_flags | P_DIRTY;
1527 dst->mp_pages = src->mp_pages;
1529 if (IS_LEAF2(src)) {
1530 memcpy(dst->mp_ptrs, src->mp_ptrs, psize - PAGEHDRSZ - SIZELEFT(src));
1532 unsigned int i, nkeys = NUMKEYS(src);
1533 for (i=0; i<nkeys; i++)
1534 dst->mp_ptrs[i] = src->mp_ptrs[i];
1535 memcpy((char *)dst+src->mp_upper, (char *)src+src->mp_upper,
1536 psize - src->mp_upper);
1540 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1541 * @param[in] mc cursor pointing to the page to be touched
1542 * @return 0 on success, non-zero on failure.
1545 mdb_page_touch(MDB_cursor *mc)
1547 MDB_page *mp = mc->mc_pg[mc->mc_top];
1551 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1553 if ((rc = mdb_page_alloc(mc, 1, &np)))
1555 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1556 assert(mp->mp_pgno != np->mp_pgno);
1557 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1559 /* If page isn't full, just copy the used portion */
1560 mdb_page_copy(np, mp, mc->mc_txn->mt_env->me_psize);
1563 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1565 np->mp_flags |= P_DIRTY;
1570 /* Adjust other cursors pointing to mp */
1571 if (mc->mc_flags & C_SUB) {
1572 MDB_cursor *m2, *m3;
1573 MDB_dbi dbi = mc->mc_dbi-1;
1575 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1576 if (m2 == mc) continue;
1577 m3 = &m2->mc_xcursor->mx_cursor;
1578 if (m3->mc_snum < mc->mc_snum) continue;
1579 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1580 m3->mc_pg[mc->mc_top] = mp;
1586 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1587 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1588 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1589 m2->mc_pg[mc->mc_top] = mp;
1593 mc->mc_pg[mc->mc_top] = mp;
1594 /** If this page has a parent, update the parent to point to
1598 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1600 mc->mc_db->md_root = mp->mp_pgno;
1601 } else if (mc->mc_txn->mt_parent) {
1604 /* If txn has a parent, make sure the page is in our
1607 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1608 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1609 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1610 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1611 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1612 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1613 mc->mc_pg[mc->mc_top] = mp;
1618 if (mc->mc_txn->mt_u.dirty_list[0].mid >= MDB_IDL_UM_MAX)
1619 return MDB_TXN_FULL;
1621 np = mdb_page_malloc(mc);
1624 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1625 mid.mid = np->mp_pgno;
1627 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1635 mdb_env_sync(MDB_env *env, int force)
1638 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1639 if (env->me_flags & MDB_WRITEMAP) {
1640 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1641 ? MS_ASYNC : MS_SYNC;
1642 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1645 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1649 if (MDB_FDATASYNC(env->me_fd))
1656 /** Make shadow copies of all of parent txn's cursors */
1658 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1660 MDB_cursor *mc, *m2;
1661 unsigned int i, j, size;
1663 for (i=0;i<src->mt_numdbs; i++) {
1664 if (src->mt_cursors[i]) {
1665 size = sizeof(MDB_cursor);
1666 if (src->mt_cursors[i]->mc_xcursor)
1667 size += sizeof(MDB_xcursor);
1668 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1675 mc->mc_db = &dst->mt_dbs[i];
1676 mc->mc_dbx = m2->mc_dbx;
1677 mc->mc_dbflag = &dst->mt_dbflags[i];
1678 mc->mc_snum = m2->mc_snum;
1679 mc->mc_top = m2->mc_top;
1680 mc->mc_flags = m2->mc_flags | C_SHADOW;
1681 for (j=0; j<mc->mc_snum; j++) {
1682 mc->mc_pg[j] = m2->mc_pg[j];
1683 mc->mc_ki[j] = m2->mc_ki[j];
1685 if (m2->mc_xcursor) {
1686 MDB_xcursor *mx, *mx2;
1687 mx = (MDB_xcursor *)(mc+1);
1688 mc->mc_xcursor = mx;
1689 mx2 = m2->mc_xcursor;
1690 mx->mx_db = mx2->mx_db;
1691 mx->mx_dbx = mx2->mx_dbx;
1692 mx->mx_dbflag = mx2->mx_dbflag;
1693 mx->mx_cursor.mc_txn = dst;
1694 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1695 mx->mx_cursor.mc_db = &mx->mx_db;
1696 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1697 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1698 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1699 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1700 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1701 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1702 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1703 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1706 mc->mc_xcursor = NULL;
1708 mc->mc_next = dst->mt_cursors[i];
1709 dst->mt_cursors[i] = mc;
1716 /** Merge shadow cursors back into parent's */
1718 mdb_cursor_merge(MDB_txn *txn)
1721 for (i=0; i<txn->mt_numdbs; i++) {
1722 if (txn->mt_cursors[i]) {
1724 while ((mc = txn->mt_cursors[i])) {
1725 txn->mt_cursors[i] = mc->mc_next;
1726 if (mc->mc_flags & C_SHADOW) {
1727 MDB_cursor *m2 = mc->mc_orig;
1729 m2->mc_snum = mc->mc_snum;
1730 m2->mc_top = mc->mc_top;
1731 for (j=0; j<mc->mc_snum; j++) {
1732 m2->mc_pg[j] = mc->mc_pg[j];
1733 m2->mc_ki[j] = mc->mc_ki[j];
1736 if (mc->mc_flags & C_ALLOCD)
1744 mdb_txn_reset0(MDB_txn *txn);
1746 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1747 * @param[in] txn the transaction handle to initialize
1748 * @return 0 on success, non-zero on failure. This can only
1749 * fail for read-only transactions, and then only if the
1750 * reader table is full.
1753 mdb_txn_renew0(MDB_txn *txn)
1755 MDB_env *env = txn->mt_env;
1760 txn->mt_numdbs = env->me_numdbs;
1761 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1763 if (txn->mt_flags & MDB_TXN_RDONLY) {
1764 if (env->me_flags & MDB_ROFS) {
1765 i = mdb_env_pick_meta(env);
1766 txn->mt_txnid = env->me_metas[i]->mm_txnid;
1767 txn->mt_u.reader = NULL;
1769 MDB_reader *r = pthread_getspecific(env->me_txkey);
1771 pid_t pid = env->me_pid;
1772 pthread_t tid = pthread_self();
1775 for (i=0; i<env->me_txns->mti_numreaders; i++)
1776 if (env->me_txns->mti_readers[i].mr_pid == 0)
1778 if (i == env->me_maxreaders) {
1779 UNLOCK_MUTEX_R(env);
1780 return MDB_READERS_FULL;
1782 env->me_txns->mti_readers[i].mr_pid = pid;
1783 env->me_txns->mti_readers[i].mr_tid = tid;
1784 if (i >= env->me_txns->mti_numreaders)
1785 env->me_txns->mti_numreaders = i+1;
1786 /* Save numreaders for un-mutexed mdb_env_close() */
1787 env->me_numreaders = env->me_txns->mti_numreaders;
1788 UNLOCK_MUTEX_R(env);
1789 r = &env->me_txns->mti_readers[i];
1790 if ((rc = pthread_setspecific(env->me_txkey, r)) != 0) {
1791 env->me_txns->mti_readers[i].mr_pid = 0;
1795 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1796 txn->mt_u.reader = r;
1798 txn->mt_toggle = txn->mt_txnid & 1;
1799 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1803 txn->mt_txnid = env->me_txns->mti_txnid;
1804 txn->mt_toggle = txn->mt_txnid & 1;
1805 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1808 if (txn->mt_txnid == mdb_debug_start)
1811 txn->mt_u.dirty_list = env->me_dirty_list;
1812 txn->mt_u.dirty_list[0].mid = 0;
1813 txn->mt_free_pgs = env->me_free_pgs;
1814 txn->mt_free_pgs[0] = 0;
1818 /* Copy the DB info and flags */
1819 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1820 for (i=2; i<txn->mt_numdbs; i++)
1821 txn->mt_dbs[i].md_flags = env->me_dbflags[i];
1822 txn->mt_dbflags[0] = txn->mt_dbflags[1] = 0;
1823 if (txn->mt_numdbs > 2)
1824 memset(txn->mt_dbflags+2, DB_STALE, txn->mt_numdbs-2);
1830 mdb_txn_renew(MDB_txn *txn)
1834 if (! (txn && txn->mt_flags & MDB_TXN_RDONLY))
1837 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1838 DPUTS("environment had fatal error, must shutdown!");
1842 rc = mdb_txn_renew0(txn);
1843 if (rc == MDB_SUCCESS) {
1844 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1845 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1846 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1852 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1857 if (env->me_flags & MDB_FATAL_ERROR) {
1858 DPUTS("environment had fatal error, must shutdown!");
1861 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
1864 /* Nested transactions: Max 1 child, write txns only, no writemap */
1865 if (parent->mt_child ||
1866 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
1867 (env->me_flags & MDB_WRITEMAP))
1872 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1873 if (!(flags & MDB_RDONLY))
1874 size += env->me_maxdbs * sizeof(MDB_cursor *);
1876 if ((txn = calloc(1, size)) == NULL) {
1877 DPRINTF("calloc: %s", strerror(ErrCode()));
1880 txn->mt_dbs = (MDB_db *)(txn+1);
1881 if (flags & MDB_RDONLY) {
1882 txn->mt_flags |= MDB_TXN_RDONLY;
1883 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1885 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1886 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1891 txn->mt_free_pgs = mdb_midl_alloc();
1892 if (!txn->mt_free_pgs) {
1896 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1897 if (!txn->mt_u.dirty_list) {
1898 free(txn->mt_free_pgs);
1902 txn->mt_txnid = parent->mt_txnid;
1903 txn->mt_toggle = parent->mt_toggle;
1904 txn->mt_u.dirty_list[0].mid = 0;
1905 txn->mt_free_pgs[0] = 0;
1906 txn->mt_next_pgno = parent->mt_next_pgno;
1907 parent->mt_child = txn;
1908 txn->mt_parent = parent;
1909 txn->mt_numdbs = parent->mt_numdbs;
1910 txn->mt_dbxs = parent->mt_dbxs;
1911 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1912 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1913 mdb_cursor_shadow(parent, txn);
1916 rc = mdb_txn_renew0(txn);
1922 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1923 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1924 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1930 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1931 * @param[in] txn the transaction handle to reset
1934 mdb_txn_reset0(MDB_txn *txn)
1936 MDB_env *env = txn->mt_env;
1938 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1939 if (!(env->me_flags & MDB_ROFS))
1940 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
1946 /* close(free) all cursors */
1947 for (i=0; i<txn->mt_numdbs; i++) {
1948 if (txn->mt_cursors[i]) {
1950 while ((mc = txn->mt_cursors[i])) {
1951 txn->mt_cursors[i] = mc->mc_next;
1952 if (mc->mc_flags & C_ALLOCD)
1958 if (!(env->me_flags & MDB_WRITEMAP)) {
1959 /* return all dirty pages to dpage list */
1960 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1961 dp = txn->mt_u.dirty_list[i].mptr;
1962 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1963 mdb_page_free(txn->mt_env, dp);
1965 /* large pages just get freed directly */
1966 VGMEMP_FREE(txn->mt_env, dp);
1972 if (txn->mt_parent) {
1973 txn->mt_parent->mt_child = NULL;
1974 mdb_midl_free(txn->mt_free_pgs);
1975 free(txn->mt_u.dirty_list);
1978 if (mdb_midl_shrink(&txn->mt_free_pgs))
1979 env->me_free_pgs = txn->mt_free_pgs;
1982 while ((mop = txn->mt_env->me_pghead)) {
1983 txn->mt_env->me_pghead = mop->mo_next;
1986 txn->mt_env->me_pgfirst = 0;
1987 txn->mt_env->me_pglast = 0;
1990 /* The writer mutex was locked in mdb_txn_begin. */
1991 UNLOCK_MUTEX_W(env);
1996 mdb_txn_reset(MDB_txn *txn)
2001 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
2002 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2003 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2005 mdb_txn_reset0(txn);
2009 mdb_txn_abort(MDB_txn *txn)
2014 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
2015 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2016 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2019 mdb_txn_abort(txn->mt_child);
2021 mdb_txn_reset0(txn);
2026 mdb_txn_commit(MDB_txn *txn)
2034 pgno_t next, freecnt;
2037 assert(txn != NULL);
2038 assert(txn->mt_env != NULL);
2040 if (txn->mt_child) {
2041 mdb_txn_commit(txn->mt_child);
2042 txn->mt_child = NULL;
2047 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2048 if (txn->mt_numdbs > env->me_numdbs) {
2049 /* update the DB flags */
2051 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2052 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2059 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2060 DPUTS("error flag is set, can't commit");
2062 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2067 if (txn->mt_parent) {
2073 /* Merge (and close) our cursors with parent's */
2074 mdb_cursor_merge(txn);
2076 /* Update parent's DB table */
2077 ip = &txn->mt_parent->mt_dbs[2];
2078 jp = &txn->mt_dbs[2];
2079 for (i = 2; i < txn->mt_numdbs; i++) {
2080 if (ip->md_root != jp->md_root)
2084 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
2086 /* Append our free list to parent's */
2087 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
2089 mdb_midl_free(txn->mt_free_pgs);
2091 /* Merge our dirty list with parent's */
2092 dst = txn->mt_parent->mt_u.dirty_list;
2093 src = txn->mt_u.dirty_list;
2094 x = mdb_mid2l_search(dst, src[1].mid);
2095 for (y=1; y<=src[0].mid; y++) {
2096 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
2100 dst[x].mptr = src[y].mptr;
2103 for (; y<=src[0].mid; y++) {
2104 if (++x >= MDB_IDL_UM_MAX) {
2106 return MDB_TXN_FULL;
2111 free(txn->mt_u.dirty_list);
2112 txn->mt_parent->mt_child = NULL;
2117 if (txn != env->me_txn) {
2118 DPUTS("attempt to commit unknown transaction");
2123 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2126 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2127 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2129 /* Update DB root pointers. Their pages have already been
2130 * touched so this is all in-place and cannot fail.
2132 if (txn->mt_numdbs > 2) {
2135 data.mv_size = sizeof(MDB_db);
2137 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2138 for (i = 2; i < txn->mt_numdbs; i++) {
2139 if (txn->mt_dbflags[i] & DB_DIRTY) {
2140 data.mv_data = &txn->mt_dbs[i];
2141 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2146 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2148 /* should only be one record now */
2149 if (env->me_pghead || env->me_pgfirst) {
2150 /* make sure first page of freeDB is touched and on freelist */
2151 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2152 if (rc && rc != MDB_NOTFOUND) {
2159 /* Delete IDLs we used from the free list */
2160 if (env->me_pgfirst) {
2165 key.mv_size = sizeof(cur);
2166 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
2169 mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
2170 rc = mdb_cursor_del(&mc, 0);
2174 env->me_pgfirst = 0;
2178 /* save to free list */
2180 freecnt = txn->mt_free_pgs[0];
2181 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2184 /* make sure last page of freeDB is touched and on freelist */
2185 key.mv_size = MDB_MAXKEYSIZE+1;
2187 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2188 if (rc && rc != MDB_NOTFOUND)
2194 MDB_IDL idl = txn->mt_free_pgs;
2195 mdb_midl_sort(txn->mt_free_pgs);
2196 DPRINTF("IDL write txn %zu root %zu num %zu",
2197 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
2198 for (i=1; i<=idl[0]; i++) {
2199 DPRINTF("IDL %zu", idl[i]);
2203 /* write to last page of freeDB */
2204 key.mv_size = sizeof(pgno_t);
2205 key.mv_data = &txn->mt_txnid;
2206 data.mv_data = txn->mt_free_pgs;
2207 /* The free list can still grow during this call,
2208 * despite the pre-emptive touches above. So check
2209 * and make sure the entire thing got written.
2212 freecnt = txn->mt_free_pgs[0];
2213 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
2214 mdb_midl_sort(txn->mt_free_pgs);
2215 rc = mdb_cursor_put(&mc, &key, &data, 0);
2218 } while (freecnt != txn->mt_free_pgs[0]);
2220 /* should only be one record now */
2222 if (env->me_pghead) {
2228 mop = env->me_pghead;
2230 key.mv_size = sizeof(id);
2232 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2233 data.mv_data = mop->mo_pages;
2234 orig = mop->mo_pages[0];
2235 /* These steps may grow the freelist again
2236 * due to freed overflow pages...
2238 rc = mdb_cursor_put(&mc, &key, &data, 0);
2241 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
2242 /* could have been used again here */
2243 if (mop->mo_pages[0] != orig) {
2244 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2245 data.mv_data = mop->mo_pages;
2247 rc = mdb_cursor_put(&mc, &key, &data, 0);
2252 /* was completely used up */
2253 rc = mdb_cursor_del(&mc, 0);
2259 env->me_pgfirst = 0;
2263 /* Check for growth of freelist again */
2264 if (freecnt != txn->mt_free_pgs[0])
2267 if (env->me_pghead) {
2268 free(env->me_pghead);
2269 env->me_pghead = NULL;
2272 while (env->me_pgfree) {
2273 MDB_oldpages *mop = env->me_pgfree;
2274 env->me_pgfree = mop->mo_next;
2278 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2279 if (mdb_midl_shrink(&txn->mt_free_pgs))
2280 env->me_free_pgs = txn->mt_free_pgs;
2287 if (env->me_flags & MDB_WRITEMAP) {
2288 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2289 dp = txn->mt_u.dirty_list[i].mptr;
2290 /* clear dirty flag */
2291 dp->mp_flags &= ~P_DIRTY;
2292 txn->mt_u.dirty_list[i].mid = 0;
2294 txn->mt_u.dirty_list[0].mid = 0;
2298 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2304 /* Windows actually supports scatter/gather I/O, but only on
2305 * unbuffered file handles. Since we're relying on the OS page
2306 * cache for all our data, that's self-defeating. So we just
2307 * write pages one at a time. We use the ov structure to set
2308 * the write offset, to at least save the overhead of a Seek
2312 memset(&ov, 0, sizeof(ov));
2313 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2315 dp = txn->mt_u.dirty_list[i].mptr;
2316 DPRINTF("committing page %zu", dp->mp_pgno);
2317 size = dp->mp_pgno * env->me_psize;
2318 ov.Offset = size & 0xffffffff;
2319 ov.OffsetHigh = size >> 16;
2320 ov.OffsetHigh >>= 16;
2321 /* clear dirty flag */
2322 dp->mp_flags &= ~P_DIRTY;
2323 wsize = env->me_psize;
2324 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2325 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2328 DPRINTF("WriteFile: %d", n);
2335 struct iovec iov[MDB_COMMIT_PAGES];
2339 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2340 dp = txn->mt_u.dirty_list[i].mptr;
2341 if (dp->mp_pgno != next) {
2343 rc = writev(env->me_fd, iov, n);
2347 DPUTS("short write, filesystem full?");
2349 DPRINTF("writev: %s", strerror(n));
2356 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2359 DPRINTF("committing page %zu", dp->mp_pgno);
2360 iov[n].iov_len = env->me_psize;
2361 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2362 iov[n].iov_base = (char *)dp;
2363 size += iov[n].iov_len;
2364 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2365 /* clear dirty flag */
2366 dp->mp_flags &= ~P_DIRTY;
2367 if (++n >= MDB_COMMIT_PAGES) {
2377 rc = writev(env->me_fd, iov, n);
2381 DPUTS("short write, filesystem full?");
2383 DPRINTF("writev: %s", strerror(n));
2390 /* Drop the dirty pages.
2392 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2393 dp = txn->mt_u.dirty_list[i].mptr;
2394 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2395 mdb_page_free(txn->mt_env, dp);
2397 VGMEMP_FREE(txn->mt_env, dp);
2400 txn->mt_u.dirty_list[i].mid = 0;
2402 txn->mt_u.dirty_list[0].mid = 0;
2405 if ((n = mdb_env_sync(env, 0)) != 0 ||
2406 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2413 if (txn->mt_numdbs > env->me_numdbs) {
2414 /* update the DB flags */
2416 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2417 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2421 UNLOCK_MUTEX_W(env);
2427 /** Read the environment parameters of a DB environment before
2428 * mapping it into memory.
2429 * @param[in] env the environment handle
2430 * @param[out] meta address of where to store the meta information
2431 * @return 0 on success, non-zero on failure.
2434 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2441 /* We don't know the page size yet, so use a minimum value.
2442 * Read both meta pages so we can use the latest one.
2445 for (i=0; i<2; i++) {
2447 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2449 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2454 else if (rc != MDB_PAGESIZE) {
2458 DPRINTF("read: %s", strerror(err));
2462 p = (MDB_page *)&pbuf;
2464 if (!F_ISSET(p->mp_flags, P_META)) {
2465 DPRINTF("page %zu not a meta page", p->mp_pgno);
2470 if (m->mm_magic != MDB_MAGIC) {
2471 DPUTS("meta has invalid magic");
2475 if (m->mm_version != MDB_VERSION) {
2476 DPRINTF("database is version %u, expected version %u",
2477 m->mm_version, MDB_VERSION);
2478 return MDB_VERSION_MISMATCH;
2482 if (m->mm_txnid > meta->mm_txnid)
2483 memcpy(meta, m, sizeof(*m));
2485 memcpy(meta, m, sizeof(*m));
2487 if (SetFilePointer(env->me_fd, meta->mm_psize, NULL, FILE_BEGIN) != meta->mm_psize)
2489 if (lseek(env->me_fd, meta->mm_psize, SEEK_SET) != meta->mm_psize)
2497 /** Write the environment parameters of a freshly created DB environment.
2498 * @param[in] env the environment handle
2499 * @param[out] meta address of where to store the meta information
2500 * @return 0 on success, non-zero on failure.
2503 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2510 DPUTS("writing new meta page");
2512 GET_PAGESIZE(psize);
2514 meta->mm_magic = MDB_MAGIC;
2515 meta->mm_version = MDB_VERSION;
2516 meta->mm_mapsize = env->me_mapsize;
2517 meta->mm_psize = psize;
2518 meta->mm_last_pg = 1;
2519 meta->mm_flags = env->me_flags & 0xffff;
2520 meta->mm_flags |= MDB_INTEGERKEY;
2521 meta->mm_dbs[0].md_root = P_INVALID;
2522 meta->mm_dbs[1].md_root = P_INVALID;
2524 p = calloc(2, psize);
2526 p->mp_flags = P_META;
2529 memcpy(m, meta, sizeof(*meta));
2531 q = (MDB_page *)((char *)p + psize);
2534 q->mp_flags = P_META;
2537 memcpy(m, meta, sizeof(*meta));
2542 SetFilePointer(env->me_fd, 0, NULL, FILE_BEGIN);
2543 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2544 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2547 lseek(env->me_fd, 0, SEEK_SET);
2548 rc = write(env->me_fd, p, psize * 2);
2549 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2555 /** Update the environment info to commit a transaction.
2556 * @param[in] txn the transaction that's being committed
2557 * @return 0 on success, non-zero on failure.
2560 mdb_env_write_meta(MDB_txn *txn)
2563 MDB_meta meta, metab, *mp;
2565 int rc, len, toggle;
2572 assert(txn != NULL);
2573 assert(txn->mt_env != NULL);
2575 toggle = !txn->mt_toggle;
2576 DPRINTF("writing meta page %d for root page %zu",
2577 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2580 mp = env->me_metas[toggle];
2582 if (env->me_flags & MDB_WRITEMAP) {
2583 /* Persist any increases of mapsize config */
2584 if (env->me_mapsize > mp->mm_mapsize)
2585 mp->mm_mapsize = env->me_mapsize;
2586 mp->mm_dbs[0] = txn->mt_dbs[0];
2587 mp->mm_dbs[1] = txn->mt_dbs[1];
2588 mp->mm_last_pg = txn->mt_next_pgno - 1;
2589 mp->mm_txnid = txn->mt_txnid;
2590 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2591 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2594 ptr += env->me_psize;
2595 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2602 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2603 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2605 ptr = (char *)&meta;
2606 if (env->me_mapsize > mp->mm_mapsize) {
2607 /* Persist any increases of mapsize config */
2608 meta.mm_mapsize = env->me_mapsize;
2609 off = offsetof(MDB_meta, mm_mapsize);
2611 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2613 len = sizeof(MDB_meta) - off;
2616 meta.mm_dbs[0] = txn->mt_dbs[0];
2617 meta.mm_dbs[1] = txn->mt_dbs[1];
2618 meta.mm_last_pg = txn->mt_next_pgno - 1;
2619 meta.mm_txnid = txn->mt_txnid;
2622 off += env->me_psize;
2625 /* Write to the SYNC fd */
2626 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
2627 env->me_fd : env->me_mfd;
2630 memset(&ov, 0, sizeof(ov));
2632 WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov);
2635 rc = pwrite(mfd, ptr, len, off);
2640 DPUTS("write failed, disk error?");
2641 /* On a failure, the pagecache still contains the new data.
2642 * Write some old data back, to prevent it from being used.
2643 * Use the non-SYNC fd; we know it will fail anyway.
2645 meta.mm_last_pg = metab.mm_last_pg;
2646 meta.mm_txnid = metab.mm_txnid;
2648 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2650 r2 = pwrite(env->me_fd, ptr, len, off);
2653 env->me_flags |= MDB_FATAL_ERROR;
2657 /* Memory ordering issues are irrelevant; since the entire writer
2658 * is wrapped by wmutex, all of these changes will become visible
2659 * after the wmutex is unlocked. Since the DB is multi-version,
2660 * readers will get consistent data regardless of how fresh or
2661 * how stale their view of these values is.
2663 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2668 /** Check both meta pages to see which one is newer.
2669 * @param[in] env the environment handle
2670 * @return meta toggle (0 or 1).
2673 mdb_env_pick_meta(const MDB_env *env)
2675 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2679 mdb_env_create(MDB_env **env)
2683 e = calloc(1, sizeof(MDB_env));
2687 e->me_free_pgs = mdb_midl_alloc();
2688 if (!e->me_free_pgs) {
2692 e->me_maxreaders = DEFAULT_READERS;
2694 e->me_fd = INVALID_HANDLE_VALUE;
2695 e->me_lfd = INVALID_HANDLE_VALUE;
2696 e->me_mfd = INVALID_HANDLE_VALUE;
2697 #ifdef MDB_USE_POSIX_SEM
2698 e->me_rmutex = SEM_FAILED;
2699 e->me_wmutex = SEM_FAILED;
2701 e->me_pid = getpid();
2702 VGMEMP_CREATE(e,0,0);
2708 mdb_env_set_mapsize(MDB_env *env, size_t size)
2712 env->me_mapsize = size;
2714 env->me_maxpg = env->me_mapsize / env->me_psize;
2719 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2723 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
2728 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2730 if (env->me_map || readers < 1)
2732 env->me_maxreaders = readers;
2737 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2739 if (!env || !readers)
2741 *readers = env->me_maxreaders;
2745 /** Further setup required for opening an MDB environment
2748 mdb_env_open2(MDB_env *env)
2750 unsigned int flags = env->me_flags;
2751 int i, newenv = 0, prot;
2755 memset(&meta, 0, sizeof(meta));
2757 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2760 DPUTS("new mdbenv");
2764 /* Was a mapsize configured? */
2765 if (!env->me_mapsize) {
2766 /* If this is a new environment, take the default,
2767 * else use the size recorded in the existing env.
2769 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2770 } else if (env->me_mapsize < meta.mm_mapsize) {
2771 /* If the configured size is smaller, make sure it's
2772 * still big enough. Silently round up to minimum if not.
2774 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
2775 if (env->me_mapsize < minsize)
2776 env->me_mapsize = minsize;
2782 LONG sizelo, sizehi;
2783 sizelo = env->me_mapsize & 0xffffffff;
2784 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2786 /* Windows won't create mappings for zero length files.
2787 * Just allocate the maxsize right now.
2790 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2791 if (!SetEndOfFile(env->me_fd))
2793 SetFilePointer(env->me_fd, 0, NULL, 0);
2795 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
2796 PAGE_READWRITE : PAGE_READONLY,
2797 sizehi, sizelo, NULL);
2800 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
2801 FILE_MAP_WRITE : FILE_MAP_READ,
2802 0, 0, env->me_mapsize, meta.mm_address);
2810 if (flags & MDB_WRITEMAP) {
2812 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
2815 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
2817 if (env->me_map == MAP_FAILED) {
2824 if (flags & MDB_FIXEDMAP)
2825 meta.mm_address = env->me_map;
2826 i = mdb_env_init_meta(env, &meta);
2827 if (i != MDB_SUCCESS) {
2830 } else if (meta.mm_address && env->me_map != meta.mm_address) {
2831 /* Can happen because the address argument to mmap() is just a
2832 * hint. mmap() can pick another, e.g. if the range is in use.
2833 * The MAP_FIXED flag would prevent that, but then mmap could
2834 * instead unmap existing pages to make room for the new map.
2836 return EBUSY; /* TODO: Make a new MDB_* error code? */
2838 env->me_psize = meta.mm_psize;
2840 env->me_maxpg = env->me_mapsize / env->me_psize;
2842 p = (MDB_page *)env->me_map;
2843 env->me_metas[0] = METADATA(p);
2844 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2848 int toggle = mdb_env_pick_meta(env);
2849 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2851 DPRINTF("opened database version %u, pagesize %u",
2852 env->me_metas[0]->mm_version, env->me_psize);
2853 DPRINTF("using meta page %d", toggle);
2854 DPRINTF("depth: %u", db->md_depth);
2855 DPRINTF("entries: %zu", db->md_entries);
2856 DPRINTF("branch pages: %zu", db->md_branch_pages);
2857 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2858 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2859 DPRINTF("root: %zu", db->md_root);
2867 /** Release a reader thread's slot in the reader lock table.
2868 * This function is called automatically when a thread exits.
2869 * @param[in] ptr This points to the slot in the reader lock table.
2872 mdb_env_reader_dest(void *ptr)
2874 MDB_reader *reader = ptr;
2880 /** Junk for arranging thread-specific callbacks on Windows. This is
2881 * necessarily platform and compiler-specific. Windows supports up
2882 * to 1088 keys. Let's assume nobody opens more than 64 environments
2883 * in a single process, for now. They can override this if needed.
2885 #ifndef MAX_TLS_KEYS
2886 #define MAX_TLS_KEYS 64
2888 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2889 static int mdb_tls_nkeys;
2891 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2895 case DLL_PROCESS_ATTACH: break;
2896 case DLL_THREAD_ATTACH: break;
2897 case DLL_THREAD_DETACH:
2898 for (i=0; i<mdb_tls_nkeys; i++) {
2899 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
2900 mdb_env_reader_dest(r);
2903 case DLL_PROCESS_DETACH: break;
2908 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2910 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2914 /* Force some symbol references.
2915 * _tls_used forces the linker to create the TLS directory if not already done
2916 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
2918 #pragma comment(linker, "/INCLUDE:_tls_used")
2919 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
2920 #pragma const_seg(".CRT$XLB")
2921 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
2922 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2925 #pragma comment(linker, "/INCLUDE:__tls_used")
2926 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
2927 #pragma data_seg(".CRT$XLB")
2928 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2930 #endif /* WIN 32/64 */
2931 #endif /* !__GNUC__ */
2934 /** Downgrade the exclusive lock on the region back to shared */
2936 mdb_env_share_locks(MDB_env *env, int *excl)
2938 int rc = 0, toggle = mdb_env_pick_meta(env);
2940 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2945 /* First acquire a shared lock. The Unlock will
2946 * then release the existing exclusive lock.
2948 memset(&ov, 0, sizeof(ov));
2949 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2952 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2958 struct flock lock_info;
2959 /* The shared lock replaces the existing lock */
2960 memset((void *)&lock_info, 0, sizeof(lock_info));
2961 lock_info.l_type = F_RDLCK;
2962 lock_info.l_whence = SEEK_SET;
2963 lock_info.l_start = 0;
2964 lock_info.l_len = 1;
2965 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
2966 (rc = ErrCode()) == EINTR) ;
2967 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
2974 /** Try to get exlusive lock, otherwise shared.
2975 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
2978 mdb_env_excl_lock(MDB_env *env, int *excl)
2982 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2986 memset(&ov, 0, sizeof(ov));
2987 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2994 struct flock lock_info;
2995 memset((void *)&lock_info, 0, sizeof(lock_info));
2996 lock_info.l_type = F_WRLCK;
2997 lock_info.l_whence = SEEK_SET;
2998 lock_info.l_start = 0;
2999 lock_info.l_len = 1;
3000 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3001 (rc = ErrCode()) == EINTR) ;
3005 # ifdef MDB_USE_POSIX_SEM
3006 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3009 lock_info.l_type = F_RDLCK;
3010 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3011 (rc = ErrCode()) == EINTR) ;
3019 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3021 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3023 * @(#) $Revision: 5.1 $
3024 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3025 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3027 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3031 * Please do not copyright this code. This code is in the public domain.
3033 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3034 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3035 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3036 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3037 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3038 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3039 * PERFORMANCE OF THIS SOFTWARE.
3042 * chongo <Landon Curt Noll> /\oo/\
3043 * http://www.isthe.com/chongo/
3045 * Share and Enjoy! :-)
3048 typedef unsigned long long mdb_hash_t;
3049 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3051 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3052 * @param[in] str string to hash
3053 * @param[in] hval initial value for hash
3054 * @return 64 bit hash
3056 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3057 * hval arg on the first call.
3060 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3062 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3063 unsigned char *end = s + val->mv_size;
3065 * FNV-1a hash each octet of the string
3068 /* xor the bottom with the current octet */
3069 hval ^= (mdb_hash_t)*s++;
3071 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3072 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3073 (hval << 7) + (hval << 8) + (hval << 40);
3075 /* return our new hash value */
3079 /** Hash the string and output the hash in hex.
3080 * @param[in] str string to hash
3081 * @param[out] hexbuf an array of 17 chars to hold the hash
3084 mdb_hash_hex(MDB_val *val, char *hexbuf)
3087 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3088 for (i=0; i<8; i++) {
3089 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3095 /** Open and/or initialize the lock region for the environment.
3096 * @param[in] env The MDB environment.
3097 * @param[in] lpath The pathname of the file used for the lock region.
3098 * @param[in] mode The Unix permissions for the file, if we create it.
3099 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3100 * @return 0 on success, non-zero on failure.
3103 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3111 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3112 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3113 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
3115 if (rc == ERROR_WRITE_PROTECT && (env->me_flags & MDB_RDONLY)) {
3116 env->me_flags |= MDB_ROFS;
3121 /* Try to get exclusive lock. If we succeed, then
3122 * nobody is using the lock region and we should initialize it.
3124 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3125 size = GetFileSize(env->me_lfd, NULL);
3131 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
3133 if (rc == EROFS && (env->me_flags & MDB_RDONLY)) {
3134 env->me_flags |= MDB_ROFS;
3139 /* Lose record locks when exec*() */
3140 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3141 fcntl(env->me_lfd, F_SETFD, fdflags);
3143 #else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
3144 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1) {
3146 if (rc == EROFS && (env->me_flags & MDB_RDONLY)) {
3147 env->me_flags |= MDB_ROFS;
3154 /* Try to get exclusive lock. If we succeed, then
3155 * nobody is using the lock region and we should initialize it.
3157 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3159 size = lseek(env->me_lfd, 0, SEEK_END);
3161 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3162 if (size < rsize && *excl > 0) {
3164 SetFilePointer(env->me_lfd, rsize, NULL, 0);
3165 if (!SetEndOfFile(env->me_lfd)) goto fail_errno;
3167 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3171 size = rsize - sizeof(MDB_txninfo);
3172 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3177 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3179 if (!mh) goto fail_errno;
3180 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3182 if (!env->me_txns) goto fail_errno;
3184 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3186 if (m == MAP_FAILED) goto fail_errno;
3192 BY_HANDLE_FILE_INFORMATION stbuf;
3201 if (!mdb_sec_inited) {
3202 InitializeSecurityDescriptor(&mdb_null_sd,
3203 SECURITY_DESCRIPTOR_REVISION);
3204 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3205 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3206 mdb_all_sa.bInheritHandle = FALSE;
3207 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3210 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3211 idbuf.volume = stbuf.dwVolumeSerialNumber;
3212 idbuf.nhigh = stbuf.nFileIndexHigh;
3213 idbuf.nlow = stbuf.nFileIndexLow;
3214 val.mv_data = &idbuf;
3215 val.mv_size = sizeof(idbuf);
3216 mdb_hash_hex(&val, hexbuf);
3217 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3218 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3219 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3220 if (!env->me_rmutex) goto fail_errno;
3221 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3222 if (!env->me_wmutex) goto fail_errno;
3223 #elif defined(MDB_USE_POSIX_SEM)
3232 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3233 idbuf.dev = stbuf.st_dev;
3234 idbuf.ino = stbuf.st_ino;
3235 val.mv_data = &idbuf;
3236 val.mv_size = sizeof(idbuf);
3237 mdb_hash_hex(&val, hexbuf);
3238 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3239 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3240 /* Clean up after a previous run, if needed: Try to
3241 * remove both semaphores before doing anything else.
3243 sem_unlink(env->me_txns->mti_rmname);
3244 sem_unlink(env->me_txns->mti_wmname);
3245 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3246 O_CREAT|O_EXCL, mode, 1);
3247 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3248 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3249 O_CREAT|O_EXCL, mode, 1);
3250 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3251 #else /* MDB_USE_POSIX_SEM */
3252 pthread_mutexattr_t mattr;
3254 if ((rc = pthread_mutexattr_init(&mattr))
3255 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3256 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3257 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3259 pthread_mutexattr_destroy(&mattr);
3260 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3262 env->me_txns->mti_version = MDB_VERSION;
3263 env->me_txns->mti_magic = MDB_MAGIC;
3264 env->me_txns->mti_txnid = 0;
3265 env->me_txns->mti_numreaders = 0;
3268 if (env->me_txns->mti_magic != MDB_MAGIC) {
3269 DPUTS("lock region has invalid magic");
3273 if (env->me_txns->mti_version != MDB_VERSION) {
3274 DPRINTF("lock region is version %u, expected version %u",
3275 env->me_txns->mti_version, MDB_VERSION);
3276 rc = MDB_VERSION_MISMATCH;
3280 if (rc != EACCES && rc != EAGAIN) {
3284 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3285 if (!env->me_rmutex) goto fail_errno;
3286 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3287 if (!env->me_wmutex) goto fail_errno;
3288 #elif defined(MDB_USE_POSIX_SEM)
3289 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3290 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3291 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3292 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3303 /** The name of the lock file in the DB environment */
3304 #define LOCKNAME "/lock.mdb"
3305 /** The name of the data file in the DB environment */
3306 #define DATANAME "/data.mdb"
3307 /** The suffix of the lock file when no subdir is used */
3308 #define LOCKSUFF "-lock"
3309 /** Only a subset of the @ref mdb_env flags can be changed
3310 * at runtime. Changing other flags requires closing the
3311 * environment and re-opening it with the new flags.
3313 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3314 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP)
3317 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
3319 int oflags, rc, len, excl;
3320 char *lpath, *dpath;
3322 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3326 if (flags & MDB_NOSUBDIR) {
3327 rc = len + sizeof(LOCKSUFF) + len + 1;
3329 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3334 if (flags & MDB_NOSUBDIR) {
3335 dpath = lpath + len + sizeof(LOCKSUFF);
3336 sprintf(lpath, "%s" LOCKSUFF, path);
3337 strcpy(dpath, path);
3339 dpath = lpath + len + sizeof(LOCKNAME);
3340 sprintf(lpath, "%s" LOCKNAME, path);
3341 sprintf(dpath, "%s" DATANAME, path);
3344 flags |= env->me_flags;
3345 /* silently ignore WRITEMAP if we're only getting read access */
3346 if (F_ISSET(flags, MDB_RDONLY|MDB_WRITEMAP))
3347 flags ^= MDB_WRITEMAP;
3348 env->me_flags = flags |= MDB_ENV_ACTIVE;
3350 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3355 if (F_ISSET(flags, MDB_RDONLY)) {
3356 oflags = GENERIC_READ;
3357 len = OPEN_EXISTING;
3359 oflags = GENERIC_READ|GENERIC_WRITE;
3362 mode = FILE_ATTRIBUTE_NORMAL;
3363 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3364 NULL, len, mode, NULL);
3366 if (F_ISSET(flags, MDB_RDONLY))
3369 oflags = O_RDWR | O_CREAT;
3371 env->me_fd = open(dpath, oflags, mode);
3373 if (env->me_fd == INVALID_HANDLE_VALUE) {
3378 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3379 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3380 env->me_mfd = env->me_fd;
3382 /* Synchronous fd for meta writes. Needed even with
3383 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3386 env->me_mfd = CreateFile(dpath, oflags,
3387 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3388 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3390 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3392 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3397 DPRINTF("opened dbenv %p", (void *) env);
3398 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3401 env->me_numdbs = 2; /* this notes that me_txkey was set */
3403 /* Windows TLS callbacks need help finding their TLS info. */
3404 if (mdb_tls_nkeys < MAX_TLS_KEYS)
3405 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3412 rc = mdb_env_share_locks(env, &excl);
3416 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3417 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3418 env->me_path = strdup(path);
3419 if (!env->me_dbxs || !env->me_dbflags || !env->me_path)
3425 mdb_env_close0(env, excl);
3431 /** Destroy resources from mdb_env_open() and clear our readers */
3433 mdb_env_close0(MDB_env *env, int excl)
3437 if (!(env->me_flags & MDB_ENV_ACTIVE))
3440 free(env->me_dbflags);
3444 if (env->me_numdbs) {
3445 pthread_key_delete(env->me_txkey);
3447 /* Delete our key from the global list */
3448 for (i=0; i<mdb_tls_nkeys; i++)
3449 if (mdb_tls_keys[i] == env->me_txkey) {
3450 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3458 munmap(env->me_map, env->me_mapsize);
3460 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3462 if (env->me_fd != INVALID_HANDLE_VALUE)
3465 pid_t pid = env->me_pid;
3466 /* Clearing readers is done in this function because
3467 * me_txkey with its destructor must be disabled first.
3469 for (i = env->me_numreaders; --i >= 0; )
3470 if (env->me_txns->mti_readers[i].mr_pid == pid)
3471 env->me_txns->mti_readers[i].mr_pid = 0;
3473 if (env->me_rmutex) {
3474 CloseHandle(env->me_rmutex);
3475 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3477 /* Windows automatically destroys the mutexes when
3478 * the last handle closes.
3480 #elif defined(MDB_USE_POSIX_SEM)
3481 if (env->me_rmutex != SEM_FAILED) {
3482 sem_close(env->me_rmutex);
3483 if (env->me_wmutex != SEM_FAILED)
3484 sem_close(env->me_wmutex);
3485 /* If we have the filelock: If we are the
3486 * only remaining user, clean up semaphores.
3489 mdb_env_excl_lock(env, &excl);
3491 sem_unlink(env->me_txns->mti_rmname);
3492 sem_unlink(env->me_txns->mti_wmname);
3496 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3498 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3501 /* Unlock the lockfile. Windows would have unlocked it
3502 * after closing anyway, but not necessarily at once.
3504 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3510 env->me_flags &= ~MDB_ENV_ACTIVE;
3514 mdb_env_copy(MDB_env *env, const char *path)
3516 MDB_txn *txn = NULL;
3520 HANDLE newfd = INVALID_HANDLE_VALUE;
3522 if (env->me_flags & MDB_NOSUBDIR) {
3523 lpath = (char *)path;
3526 len += sizeof(DATANAME);
3527 lpath = malloc(len);
3530 sprintf(lpath, "%s" DATANAME, path);
3533 /* The destination path must exist, but the destination file must not.
3534 * We don't want the OS to cache the writes, since the source data is
3535 * already in the OS cache.
3538 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
3539 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
3541 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
3547 if (!(env->me_flags & MDB_NOSUBDIR))
3549 if (newfd == INVALID_HANDLE_VALUE) {
3554 #ifdef F_NOCACHE /* __APPLE__ */
3555 rc = fcntl(newfd, F_NOCACHE, 1);
3562 /* Do the lock/unlock of the reader mutex before starting the
3563 * write txn. Otherwise other read txns could block writers.
3565 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3569 if (!(env->me_flags & MDB_ROFS)) {
3570 /* We must start the actual read txn after blocking writers */
3571 mdb_txn_reset0(txn);
3573 /* Temporarily block writers until we snapshot the meta pages */
3576 rc = mdb_txn_renew0(txn);
3578 UNLOCK_MUTEX_W(env);
3583 wsize = env->me_psize * 2;
3587 rc = WriteFile(newfd, env->me_map, wsize, &len, NULL);
3588 rc = (len == wsize) ? MDB_SUCCESS : ErrCode();
3591 rc = write(newfd, env->me_map, wsize);
3592 rc = (rc == (int)wsize) ? MDB_SUCCESS : ErrCode();
3594 if (! (env->me_flags & MDB_ROFS))
3595 UNLOCK_MUTEX_W(env);
3600 ptr = env->me_map + wsize;
3601 wsize = txn->mt_next_pgno * env->me_psize - wsize;
3602 #define MAX_WRITE 2147483648U
3606 if (wsize > MAX_WRITE)
3610 rc = WriteFile(newfd, ptr, w2, &len, NULL);
3611 rc = (len == w2) ? MDB_SUCCESS : ErrCode();
3620 if (wsize > MAX_WRITE)
3624 wres = write(newfd, ptr, w2);
3625 rc = (wres > 0) ? MDB_SUCCESS : ErrCode();
3634 if (newfd != INVALID_HANDLE_VALUE)
3641 mdb_env_close(MDB_env *env)
3648 VGMEMP_DESTROY(env);
3649 while ((dp = env->me_dpages) != NULL) {
3650 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3651 env->me_dpages = dp->mp_next;
3655 mdb_env_close0(env, 0);
3656 mdb_midl_free(env->me_free_pgs);
3660 /** Compare two items pointing at aligned size_t's */
3662 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3664 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3665 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3668 /** Compare two items pointing at aligned int's */
3670 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3672 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3673 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3676 /** Compare two items pointing at ints of unknown alignment.
3677 * Nodes and keys are guaranteed to be 2-byte aligned.
3680 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3682 #if BYTE_ORDER == LITTLE_ENDIAN
3683 unsigned short *u, *c;
3686 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3687 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3690 } while(!x && u > (unsigned short *)a->mv_data);
3693 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3697 /** Compare two items lexically */
3699 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3706 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3712 diff = memcmp(a->mv_data, b->mv_data, len);
3713 return diff ? diff : len_diff<0 ? -1 : len_diff;
3716 /** Compare two items in reverse byte order */
3718 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3720 const unsigned char *p1, *p2, *p1_lim;
3724 p1_lim = (const unsigned char *)a->mv_data;
3725 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3726 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3728 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3734 while (p1 > p1_lim) {
3735 diff = *--p1 - *--p2;
3739 return len_diff<0 ? -1 : len_diff;
3742 /** Search for key within a page, using binary search.
3743 * Returns the smallest entry larger or equal to the key.
3744 * If exactp is non-null, stores whether the found entry was an exact match
3745 * in *exactp (1 or 0).
3746 * Updates the cursor index with the index of the found entry.
3747 * If no entry larger or equal to the key is found, returns NULL.
3750 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3752 unsigned int i = 0, nkeys;
3755 MDB_page *mp = mc->mc_pg[mc->mc_top];
3756 MDB_node *node = NULL;
3761 nkeys = NUMKEYS(mp);
3766 COPY_PGNO(pgno, mp->mp_pgno);
3767 DPRINTF("searching %u keys in %s %spage %zu",
3768 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3775 low = IS_LEAF(mp) ? 0 : 1;
3777 cmp = mc->mc_dbx->md_cmp;
3779 /* Branch pages have no data, so if using integer keys,
3780 * alignment is guaranteed. Use faster mdb_cmp_int.
3782 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3783 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3790 nodekey.mv_size = mc->mc_db->md_pad;
3791 node = NODEPTR(mp, 0); /* fake */
3792 while (low <= high) {
3793 i = (low + high) >> 1;
3794 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3795 rc = cmp(key, &nodekey);
3796 DPRINTF("found leaf index %u [%s], rc = %i",
3797 i, DKEY(&nodekey), rc);
3806 while (low <= high) {
3807 i = (low + high) >> 1;
3809 node = NODEPTR(mp, i);
3810 nodekey.mv_size = NODEKSZ(node);
3811 nodekey.mv_data = NODEKEY(node);
3813 rc = cmp(key, &nodekey);
3816 DPRINTF("found leaf index %u [%s], rc = %i",
3817 i, DKEY(&nodekey), rc);
3819 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3820 i, DKEY(&nodekey), NODEPGNO(node), rc);
3831 if (rc > 0) { /* Found entry is less than the key. */
3832 i++; /* Skip to get the smallest entry larger than key. */
3834 node = NODEPTR(mp, i);
3837 *exactp = (rc == 0);
3838 /* store the key index */
3839 mc->mc_ki[mc->mc_top] = i;
3841 /* There is no entry larger or equal to the key. */
3844 /* nodeptr is fake for LEAF2 */
3850 mdb_cursor_adjust(MDB_cursor *mc, func)
3854 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3855 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3862 /** Pop a page off the top of the cursor's stack. */
3864 mdb_cursor_pop(MDB_cursor *mc)
3867 #ifndef MDB_DEBUG_SKIP
3868 MDB_page *top = mc->mc_pg[mc->mc_top];
3874 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3875 mc->mc_dbi, (void *) mc);
3879 /** Push a page onto the top of the cursor's stack. */
3881 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3883 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3884 mc->mc_dbi, (void *) mc);
3886 if (mc->mc_snum >= CURSOR_STACK) {
3887 assert(mc->mc_snum < CURSOR_STACK);
3888 return MDB_CURSOR_FULL;
3891 mc->mc_top = mc->mc_snum++;
3892 mc->mc_pg[mc->mc_top] = mp;
3893 mc->mc_ki[mc->mc_top] = 0;
3898 /** Find the address of the page corresponding to a given page number.
3899 * @param[in] txn the transaction for this access.
3900 * @param[in] pgno the page number for the page to retrieve.
3901 * @param[out] ret address of a pointer where the page's address will be stored.
3902 * @return 0 on success, non-zero on failure.
3905 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3909 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
3910 if (pgno < txn->mt_next_pgno)
3911 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3914 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3916 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3917 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3918 p = txn->mt_u.dirty_list[x].mptr;
3922 if (pgno < txn->mt_next_pgno)
3923 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3928 DPRINTF("page %zu not found", pgno);
3931 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3934 /** Search for the page a given key should be in.
3935 * Pushes parent pages on the cursor stack. This function continues a
3936 * search on a cursor that has already been initialized. (Usually by
3937 * #mdb_page_search() but also by #mdb_node_move().)
3938 * @param[in,out] mc the cursor for this operation.
3939 * @param[in] key the key to search for. If NULL, search for the lowest
3940 * page. (This is used by #mdb_cursor_first().)
3941 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
3942 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
3943 * @return 0 on success, non-zero on failure.
3946 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3948 MDB_page *mp = mc->mc_pg[mc->mc_top];
3953 while (IS_BRANCH(mp)) {
3957 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3958 assert(NUMKEYS(mp) > 1);
3959 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3961 if (key == NULL) /* Initialize cursor to first page. */
3963 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
3964 /* cursor to last page */
3968 node = mdb_node_search(mc, key, &exact);
3970 i = NUMKEYS(mp) - 1;
3972 i = mc->mc_ki[mc->mc_top];
3981 DPRINTF("following index %u for key [%s]",
3983 assert(i < NUMKEYS(mp));
3984 node = NODEPTR(mp, i);
3986 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3989 mc->mc_ki[mc->mc_top] = i;
3990 if ((rc = mdb_cursor_push(mc, mp)))
3994 if ((rc = mdb_page_touch(mc)) != 0)
3996 mp = mc->mc_pg[mc->mc_top];
4001 DPRINTF("internal error, index points to a %02X page!?",
4003 return MDB_CORRUPTED;
4006 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4007 key ? DKEY(key) : NULL);
4012 /** Search for the page a given key should be in.
4013 * Pushes parent pages on the cursor stack. This function just sets up
4014 * the search; it finds the root page for \b mc's database and sets this
4015 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4016 * called to complete the search.
4017 * @param[in,out] mc the cursor for this operation.
4018 * @param[in] key the key to search for. If NULL, search for the lowest
4019 * page. (This is used by #mdb_cursor_first().)
4020 * @param[in] modify If true, visited pages are updated with new page numbers.
4021 * @return 0 on success, non-zero on failure.
4024 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4029 /* Make sure the txn is still viable, then find the root from
4030 * the txn's db table.
4032 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4033 DPUTS("transaction has failed, must abort");
4036 /* Make sure we're using an up-to-date root */
4037 if (mc->mc_dbi > MAIN_DBI) {
4038 if ((*mc->mc_dbflag & DB_STALE) ||
4039 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4041 unsigned char dbflag = 0;
4042 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4043 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4046 if (*mc->mc_dbflag & DB_STALE) {
4049 MDB_node *leaf = mdb_node_search(&mc2,
4050 &mc->mc_dbx->md_name, &exact);
4052 return MDB_NOTFOUND;
4053 mdb_node_read(mc->mc_txn, leaf, &data);
4054 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4056 if (flags & MDB_PS_MODIFY)
4058 *mc->mc_dbflag = dbflag;
4061 root = mc->mc_db->md_root;
4063 if (root == P_INVALID) { /* Tree is empty. */
4064 DPUTS("tree is empty");
4065 return MDB_NOTFOUND;
4070 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4071 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
4077 DPRINTF("db %u root page %zu has flags 0x%X",
4078 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4080 if (flags & MDB_PS_MODIFY) {
4081 if ((rc = mdb_page_touch(mc)))
4085 if (flags & MDB_PS_ROOTONLY)
4088 return mdb_page_search_root(mc, key, flags);
4091 /** Return the data associated with a given node.
4092 * @param[in] txn The transaction for this operation.
4093 * @param[in] leaf The node being read.
4094 * @param[out] data Updated to point to the node's data.
4095 * @return 0 on success, non-zero on failure.
4098 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4100 MDB_page *omp; /* overflow page */
4104 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4105 data->mv_size = NODEDSZ(leaf);
4106 data->mv_data = NODEDATA(leaf);
4110 /* Read overflow data.
4112 data->mv_size = NODEDSZ(leaf);
4113 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4114 if ((rc = mdb_page_get(txn, pgno, &omp))) {
4115 DPRINTF("read overflow page %zu failed", pgno);
4118 data->mv_data = METADATA(omp);
4124 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4125 MDB_val *key, MDB_val *data)
4134 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4136 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4139 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4143 mdb_cursor_init(&mc, txn, dbi, &mx);
4144 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4147 /** Find a sibling for a page.
4148 * Replaces the page at the top of the cursor's stack with the
4149 * specified sibling, if one exists.
4150 * @param[in] mc The cursor for this operation.
4151 * @param[in] move_right Non-zero if the right sibling is requested,
4152 * otherwise the left sibling.
4153 * @return 0 on success, non-zero on failure.
4156 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4162 if (mc->mc_snum < 2) {
4163 return MDB_NOTFOUND; /* root has no siblings */
4167 DPRINTF("parent page is page %zu, index %u",
4168 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4170 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4171 : (mc->mc_ki[mc->mc_top] == 0)) {
4172 DPRINTF("no more keys left, moving to %s sibling",
4173 move_right ? "right" : "left");
4174 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4175 /* undo cursor_pop before returning */
4182 mc->mc_ki[mc->mc_top]++;
4184 mc->mc_ki[mc->mc_top]--;
4185 DPRINTF("just moving to %s index key %u",
4186 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4188 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4190 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4191 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
4194 mdb_cursor_push(mc, mp);
4199 /** Move the cursor to the next data item. */
4201 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4207 if (mc->mc_flags & C_EOF) {
4208 return MDB_NOTFOUND;
4211 assert(mc->mc_flags & C_INITIALIZED);
4213 mp = mc->mc_pg[mc->mc_top];
4215 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4216 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4217 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4218 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4219 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4220 if (op != MDB_NEXT || rc == MDB_SUCCESS)
4224 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4225 if (op == MDB_NEXT_DUP)
4226 return MDB_NOTFOUND;
4230 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4232 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4233 DPUTS("=====> move to next sibling page");
4234 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
4235 mc->mc_flags |= C_EOF;
4236 mc->mc_flags &= ~C_INITIALIZED;
4237 return MDB_NOTFOUND;
4239 mp = mc->mc_pg[mc->mc_top];
4240 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4242 mc->mc_ki[mc->mc_top]++;
4244 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4245 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4248 key->mv_size = mc->mc_db->md_pad;
4249 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4253 assert(IS_LEAF(mp));
4254 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4256 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4257 mdb_xcursor_init1(mc, leaf);
4260 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
4263 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4264 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4265 if (rc != MDB_SUCCESS)
4270 MDB_GET_KEY(leaf, key);
4274 /** Move the cursor to the previous data item. */
4276 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4282 assert(mc->mc_flags & C_INITIALIZED);
4284 mp = mc->mc_pg[mc->mc_top];
4286 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4287 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4288 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4289 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4290 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4291 if (op != MDB_PREV || rc == MDB_SUCCESS)
4294 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4295 if (op == MDB_PREV_DUP)
4296 return MDB_NOTFOUND;
4301 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4303 if (mc->mc_ki[mc->mc_top] == 0) {
4304 DPUTS("=====> move to prev sibling page");
4305 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
4306 mc->mc_flags &= ~C_INITIALIZED;
4307 return MDB_NOTFOUND;
4309 mp = mc->mc_pg[mc->mc_top];
4310 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4311 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4313 mc->mc_ki[mc->mc_top]--;
4315 mc->mc_flags &= ~C_EOF;
4317 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4318 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4321 key->mv_size = mc->mc_db->md_pad;
4322 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4326 assert(IS_LEAF(mp));
4327 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4329 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4330 mdb_xcursor_init1(mc, leaf);
4333 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
4336 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4337 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4338 if (rc != MDB_SUCCESS)
4343 MDB_GET_KEY(leaf, key);
4347 /** Set the cursor on a specific data item. */
4349 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4350 MDB_cursor_op op, int *exactp)
4354 MDB_node *leaf = NULL;
4359 assert(key->mv_size > 0);
4361 /* See if we're already on the right page */
4362 if (mc->mc_flags & C_INITIALIZED) {
4365 mp = mc->mc_pg[mc->mc_top];
4367 mc->mc_ki[mc->mc_top] = 0;
4368 return MDB_NOTFOUND;
4370 if (mp->mp_flags & P_LEAF2) {
4371 nodekey.mv_size = mc->mc_db->md_pad;
4372 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4374 leaf = NODEPTR(mp, 0);
4375 MDB_GET_KEY(leaf, &nodekey);
4377 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4379 /* Probably happens rarely, but first node on the page
4380 * was the one we wanted.
4382 mc->mc_ki[mc->mc_top] = 0;
4389 unsigned int nkeys = NUMKEYS(mp);
4391 if (mp->mp_flags & P_LEAF2) {
4392 nodekey.mv_data = LEAF2KEY(mp,
4393 nkeys-1, nodekey.mv_size);
4395 leaf = NODEPTR(mp, nkeys-1);
4396 MDB_GET_KEY(leaf, &nodekey);
4398 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4400 /* last node was the one we wanted */
4401 mc->mc_ki[mc->mc_top] = nkeys-1;
4407 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4408 /* This is definitely the right page, skip search_page */
4409 if (mp->mp_flags & P_LEAF2) {
4410 nodekey.mv_data = LEAF2KEY(mp,
4411 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4413 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4414 MDB_GET_KEY(leaf, &nodekey);
4416 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4418 /* current node was the one we wanted */
4428 /* If any parents have right-sibs, search.
4429 * Otherwise, there's nothing further.
4431 for (i=0; i<mc->mc_top; i++)
4433 NUMKEYS(mc->mc_pg[i])-1)
4435 if (i == mc->mc_top) {
4436 /* There are no other pages */
4437 mc->mc_ki[mc->mc_top] = nkeys;
4438 return MDB_NOTFOUND;
4442 /* There are no other pages */
4443 mc->mc_ki[mc->mc_top] = 0;
4444 return MDB_NOTFOUND;
4448 rc = mdb_page_search(mc, key, 0);
4449 if (rc != MDB_SUCCESS)
4452 mp = mc->mc_pg[mc->mc_top];
4453 assert(IS_LEAF(mp));
4456 leaf = mdb_node_search(mc, key, exactp);
4457 if (exactp != NULL && !*exactp) {
4458 /* MDB_SET specified and not an exact match. */
4459 return MDB_NOTFOUND;
4463 DPUTS("===> inexact leaf not found, goto sibling");
4464 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
4465 return rc; /* no entries matched */
4466 mp = mc->mc_pg[mc->mc_top];
4467 assert(IS_LEAF(mp));
4468 leaf = NODEPTR(mp, 0);
4472 mc->mc_flags |= C_INITIALIZED;
4473 mc->mc_flags &= ~C_EOF;
4476 key->mv_size = mc->mc_db->md_pad;
4477 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4481 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4482 mdb_xcursor_init1(mc, leaf);
4485 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4486 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
4487 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4490 if (op == MDB_GET_BOTH) {
4496 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
4497 if (rc != MDB_SUCCESS)
4500 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
4502 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
4504 rc = mc->mc_dbx->md_dcmp(data, &d2);
4506 if (op == MDB_GET_BOTH || rc > 0)
4507 return MDB_NOTFOUND;
4512 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4513 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4518 /* The key already matches in all other cases */
4519 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
4520 MDB_GET_KEY(leaf, key);
4521 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
4526 /** Move the cursor to the first item in the database. */
4528 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4533 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4534 rc = mdb_page_search(mc, NULL, 0);
4535 if (rc != MDB_SUCCESS)
4538 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4540 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
4541 mc->mc_flags |= C_INITIALIZED;
4542 mc->mc_flags &= ~C_EOF;
4544 mc->mc_ki[mc->mc_top] = 0;
4546 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4547 key->mv_size = mc->mc_db->md_pad;
4548 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4553 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4554 mdb_xcursor_init1(mc, leaf);
4555 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4560 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4561 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4565 MDB_GET_KEY(leaf, key);
4569 /** Move the cursor to the last item in the database. */
4571 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4576 if (!(mc->mc_flags & C_EOF)) {
4578 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4581 lkey.mv_size = MDB_MAXKEYSIZE+1;
4582 lkey.mv_data = NULL;
4583 rc = mdb_page_search(mc, &lkey, 0);
4584 if (rc != MDB_SUCCESS)
4587 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4589 mc->mc_flags |= C_INITIALIZED|C_EOF;
4590 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4592 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4594 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4595 key->mv_size = mc->mc_db->md_pad;
4596 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4601 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4602 mdb_xcursor_init1(mc, leaf);
4603 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4608 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4609 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4614 MDB_GET_KEY(leaf, key);
4619 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4628 case MDB_GET_CURRENT:
4629 if (!mc->mc_flags & C_INITIALIZED) {
4632 MDB_page *mp = mc->mc_pg[mc->mc_top];
4634 mc->mc_ki[mc->mc_top] = 0;
4640 key->mv_size = mc->mc_db->md_pad;
4641 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4643 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4644 MDB_GET_KEY(leaf, key);
4646 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4647 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
4649 rc = mdb_node_read(mc->mc_txn, leaf, data);
4656 case MDB_GET_BOTH_RANGE:
4657 if (data == NULL || mc->mc_xcursor == NULL) {
4665 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4667 } else if (op == MDB_SET_RANGE)
4668 rc = mdb_cursor_set(mc, key, data, op, NULL);
4670 rc = mdb_cursor_set(mc, key, data, op, &exact);
4672 case MDB_GET_MULTIPLE:
4674 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4675 !(mc->mc_flags & C_INITIALIZED)) {
4680 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4681 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4684 case MDB_NEXT_MULTIPLE:
4686 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4690 if (!(mc->mc_flags & C_INITIALIZED))
4691 rc = mdb_cursor_first(mc, key, data);
4693 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4694 if (rc == MDB_SUCCESS) {
4695 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4698 mx = &mc->mc_xcursor->mx_cursor;
4699 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4701 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4702 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4710 case MDB_NEXT_NODUP:
4711 if (!(mc->mc_flags & C_INITIALIZED))
4712 rc = mdb_cursor_first(mc, key, data);
4714 rc = mdb_cursor_next(mc, key, data, op);
4718 case MDB_PREV_NODUP:
4719 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF)) {
4720 rc = mdb_cursor_last(mc, key, data);
4721 mc->mc_flags |= C_INITIALIZED;
4722 mc->mc_ki[mc->mc_top]++;
4724 rc = mdb_cursor_prev(mc, key, data, op);
4727 rc = mdb_cursor_first(mc, key, data);
4731 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4732 !(mc->mc_flags & C_INITIALIZED) ||
4733 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4737 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4740 rc = mdb_cursor_last(mc, key, data);
4744 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4745 !(mc->mc_flags & C_INITIALIZED) ||
4746 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4750 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4753 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4761 /** Touch all the pages in the cursor stack.
4762 * Makes sure all the pages are writable, before attempting a write operation.
4763 * @param[in] mc The cursor to operate on.
4766 mdb_cursor_touch(MDB_cursor *mc)
4770 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4773 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI,
4774 mc->mc_txn->mt_dbs[MAIN_DBI].md_flags & MDB_DUPSORT ? &mcx : NULL);
4775 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4778 *mc->mc_dbflag = DB_DIRTY;
4780 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4781 rc = mdb_page_touch(mc);
4785 mc->mc_top = mc->mc_snum-1;
4790 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4793 MDB_node *leaf = NULL;
4794 MDB_val xdata, *rdata, dkey;
4797 int do_sub = 0, insert = 0;
4798 unsigned int mcount = 0;
4802 char dbuf[MDB_MAXKEYSIZE+1];
4803 unsigned int nflags;
4806 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4809 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE)
4812 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4813 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4817 if (flags == MDB_CURRENT) {
4818 if (!(mc->mc_flags & C_INITIALIZED))
4821 } else if (mc->mc_db->md_root == P_INVALID) {
4823 /* new database, write a root leaf page */
4824 DPUTS("allocating new root leaf page");
4825 if ((rc = mdb_page_new(mc, P_LEAF, 1, &np))) {
4829 mdb_cursor_push(mc, np);
4830 mc->mc_db->md_root = np->mp_pgno;
4831 mc->mc_db->md_depth++;
4832 *mc->mc_dbflag = DB_DIRTY;
4833 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4835 np->mp_flags |= P_LEAF2;
4836 mc->mc_flags |= C_INITIALIZED;
4842 if (flags & MDB_APPEND) {
4844 rc = mdb_cursor_last(mc, &k2, &d2);
4846 rc = mc->mc_dbx->md_cmp(key, &k2);
4849 mc->mc_ki[mc->mc_top]++;
4855 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4857 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4858 DPRINTF("duplicate key [%s]", DKEY(key));
4860 return MDB_KEYEXIST;
4862 if (rc && rc != MDB_NOTFOUND)
4866 /* Cursor is positioned, now make sure all pages are writable */
4867 rc2 = mdb_cursor_touch(mc);
4872 /* The key already exists */
4873 if (rc == MDB_SUCCESS) {
4874 /* there's only a key anyway, so this is a no-op */
4875 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4876 unsigned int ksize = mc->mc_db->md_pad;
4877 if (key->mv_size != ksize)
4879 if (flags == MDB_CURRENT) {
4880 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4881 memcpy(ptr, key->mv_data, ksize);
4886 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4889 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4890 /* Was a single item before, must convert now */
4892 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4893 /* Just overwrite the current item */
4894 if (flags == MDB_CURRENT)
4897 dkey.mv_size = NODEDSZ(leaf);
4898 dkey.mv_data = NODEDATA(leaf);
4899 #if UINT_MAX < SIZE_MAX
4900 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4901 #ifdef MISALIGNED_OK
4902 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4904 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4907 /* if data matches, ignore it */
4908 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4909 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4911 /* create a fake page for the dup items */
4912 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4913 dkey.mv_data = dbuf;
4914 fp = (MDB_page *)&pbuf;
4915 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4916 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4917 fp->mp_lower = PAGEHDRSZ;
4918 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4919 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4920 fp->mp_flags |= P_LEAF2;
4921 fp->mp_pad = data->mv_size;
4922 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
4924 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4925 (dkey.mv_size & 1) + (data->mv_size & 1);
4927 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4930 xdata.mv_size = fp->mp_upper;
4935 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4936 /* See if we need to convert from fake page to subDB */
4938 unsigned int offset;
4941 fp = NODEDATA(leaf);
4942 if (flags == MDB_CURRENT) {
4944 fp->mp_flags |= P_DIRTY;
4945 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4946 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4950 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4951 offset = fp->mp_pad;
4952 if (SIZELEFT(fp) >= offset)
4954 offset *= 4; /* space for 4 more */
4956 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4958 offset += offset & 1;
4959 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4960 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4962 /* yes, convert it */
4964 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4965 dummy.md_pad = fp->mp_pad;
4966 dummy.md_flags = MDB_DUPFIXED;
4967 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4968 dummy.md_flags |= MDB_INTEGERKEY;
4971 dummy.md_branch_pages = 0;
4972 dummy.md_leaf_pages = 1;
4973 dummy.md_overflow_pages = 0;
4974 dummy.md_entries = NUMKEYS(fp);
4976 xdata.mv_size = sizeof(MDB_db);
4977 xdata.mv_data = &dummy;
4978 if ((rc = mdb_page_alloc(mc, 1, &mp)))
4980 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4981 flags |= F_DUPDATA|F_SUBDATA;
4982 dummy.md_root = mp->mp_pgno;
4984 /* no, just grow it */
4986 xdata.mv_size = NODEDSZ(leaf) + offset;
4987 xdata.mv_data = &pbuf;
4988 mp = (MDB_page *)&pbuf;
4989 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4992 mp->mp_flags = fp->mp_flags | P_DIRTY;
4993 mp->mp_pad = fp->mp_pad;
4994 mp->mp_lower = fp->mp_lower;
4995 mp->mp_upper = fp->mp_upper + offset;
4997 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4999 nsize = NODEDSZ(leaf) - fp->mp_upper;
5000 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5001 for (i=0; i<NUMKEYS(fp); i++)
5002 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5004 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5008 /* data is on sub-DB, just store it */
5009 flags |= F_DUPDATA|F_SUBDATA;
5013 /* overflow page overwrites need special handling */
5014 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5017 int ovpages, dpages;
5019 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5020 dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5021 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5022 mdb_page_get(mc->mc_txn, pg, &omp);
5023 /* Is the ov page writable and large enough? */
5024 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
5025 /* yes, overwrite it. Note in this case we don't
5026 * bother to try shrinking the node if the new data
5027 * is smaller than the overflow threshold.
5029 if (F_ISSET(flags, MDB_RESERVE))
5030 data->mv_data = METADATA(omp);
5032 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5035 /* no, free ovpages */
5037 mc->mc_db->md_overflow_pages -= ovpages;
5038 for (i=0; i<ovpages; i++) {
5039 DPRINTF("freed ov page %zu", pg);
5040 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5044 } else if (NODEDSZ(leaf) == data->mv_size) {
5045 /* same size, just replace it. Note that we could
5046 * also reuse this node if the new data is smaller,
5047 * but instead we opt to shrink the node in that case.
5049 if (F_ISSET(flags, MDB_RESERVE))
5050 data->mv_data = NODEDATA(leaf);
5052 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5055 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5056 mc->mc_db->md_entries--;
5058 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5065 nflags = flags & NODE_ADD_FLAGS;
5066 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5067 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5068 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5069 nflags &= ~MDB_APPEND;
5071 nflags |= MDB_SPLIT_REPLACE;
5072 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5074 /* There is room already in this leaf page. */
5075 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5076 if (rc == 0 && !do_sub && insert) {
5077 /* Adjust other cursors pointing to mp */
5078 MDB_cursor *m2, *m3;
5079 MDB_dbi dbi = mc->mc_dbi;
5080 unsigned i = mc->mc_top;
5081 MDB_page *mp = mc->mc_pg[i];
5083 if (mc->mc_flags & C_SUB)
5086 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5087 if (mc->mc_flags & C_SUB)
5088 m3 = &m2->mc_xcursor->mx_cursor;
5091 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5092 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5099 if (rc != MDB_SUCCESS)
5100 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5102 /* Now store the actual data in the child DB. Note that we're
5103 * storing the user data in the keys field, so there are strict
5104 * size limits on dupdata. The actual data fields of the child
5105 * DB are all zero size.
5112 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5113 if (flags & MDB_CURRENT) {
5114 xflags = MDB_CURRENT;
5116 mdb_xcursor_init1(mc, leaf);
5117 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
5119 /* converted, write the original data first */
5121 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5125 /* Adjust other cursors pointing to mp */
5127 unsigned i = mc->mc_top;
5128 MDB_page *mp = mc->mc_pg[i];
5130 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5131 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5132 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5133 mdb_xcursor_init1(m2, leaf);
5138 if (flags & MDB_APPENDDUP)
5139 xflags |= MDB_APPEND;
5140 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5141 if (flags & F_SUBDATA) {
5142 void *db = NODEDATA(leaf);
5143 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5146 /* sub-writes might have failed so check rc again.
5147 * Don't increment count if we just replaced an existing item.
5149 if (!rc && !(flags & MDB_CURRENT))
5150 mc->mc_db->md_entries++;
5151 if (flags & MDB_MULTIPLE) {
5153 if (mcount < data[1].mv_size) {
5154 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5155 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5165 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5170 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5173 if (!mc->mc_flags & C_INITIALIZED)
5176 rc = mdb_cursor_touch(mc);
5180 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5182 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5183 if (flags != MDB_NODUPDATA) {
5184 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5185 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5187 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
5188 /* If sub-DB still has entries, we're done */
5189 if (mc->mc_xcursor->mx_db.md_entries) {
5190 if (leaf->mn_flags & F_SUBDATA) {
5191 /* update subDB info */
5192 void *db = NODEDATA(leaf);
5193 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5195 /* shrink fake page */
5196 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5198 mc->mc_db->md_entries--;
5201 /* otherwise fall thru and delete the sub-DB */
5204 if (leaf->mn_flags & F_SUBDATA) {
5205 /* add all the child DB's pages to the free list */
5206 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5207 if (rc == MDB_SUCCESS) {
5208 mc->mc_db->md_entries -=
5209 mc->mc_xcursor->mx_db.md_entries;
5214 return mdb_cursor_del0(mc, leaf);
5217 /** Allocate and initialize new pages for a database.
5218 * @param[in] mc a cursor on the database being added to.
5219 * @param[in] flags flags defining what type of page is being allocated.
5220 * @param[in] num the number of pages to allocate. This is usually 1,
5221 * unless allocating overflow pages for a large record.
5222 * @param[out] mp Address of a page, or NULL on failure.
5223 * @return 0 on success, non-zero on failure.
5226 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5231 if ((rc = mdb_page_alloc(mc, num, &np)))
5233 DPRINTF("allocated new mpage %zu, page size %u",
5234 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5235 np->mp_flags = flags | P_DIRTY;
5236 np->mp_lower = PAGEHDRSZ;
5237 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5240 mc->mc_db->md_branch_pages++;
5241 else if (IS_LEAF(np))
5242 mc->mc_db->md_leaf_pages++;
5243 else if (IS_OVERFLOW(np)) {
5244 mc->mc_db->md_overflow_pages += num;
5252 /** Calculate the size of a leaf node.
5253 * The size depends on the environment's page size; if a data item
5254 * is too large it will be put onto an overflow page and the node
5255 * size will only include the key and not the data. Sizes are always
5256 * rounded up to an even number of bytes, to guarantee 2-byte alignment
5257 * of the #MDB_node headers.
5258 * @param[in] env The environment handle.
5259 * @param[in] key The key for the node.
5260 * @param[in] data The data for the node.
5261 * @return The number of bytes needed to store the node.
5264 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5268 sz = LEAFSIZE(key, data);
5269 if (sz >= env->me_psize / MDB_MINKEYS) {
5270 /* put on overflow page */
5271 sz -= data->mv_size - sizeof(pgno_t);
5275 return sz + sizeof(indx_t);
5278 /** Calculate the size of a branch node.
5279 * The size should depend on the environment's page size but since
5280 * we currently don't support spilling large keys onto overflow
5281 * pages, it's simply the size of the #MDB_node header plus the
5282 * size of the key. Sizes are always rounded up to an even number
5283 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5284 * @param[in] env The environment handle.
5285 * @param[in] key The key for the node.
5286 * @return The number of bytes needed to store the node.
5289 mdb_branch_size(MDB_env *env, MDB_val *key)
5294 if (sz >= env->me_psize / MDB_MINKEYS) {
5295 /* put on overflow page */
5296 /* not implemented */
5297 /* sz -= key->size - sizeof(pgno_t); */
5300 return sz + sizeof(indx_t);
5303 /** Add a node to the page pointed to by the cursor.
5304 * @param[in] mc The cursor for this operation.
5305 * @param[in] indx The index on the page where the new node should be added.
5306 * @param[in] key The key for the new node.
5307 * @param[in] data The data for the new node, if any.
5308 * @param[in] pgno The page number, if adding a branch node.
5309 * @param[in] flags Flags for the node.
5310 * @return 0 on success, non-zero on failure. Possible errors are:
5312 * <li>ENOMEM - failed to allocate overflow pages for the node.
5313 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5314 * should never happen since all callers already calculate the
5315 * page's free space before calling this function.
5319 mdb_node_add(MDB_cursor *mc, indx_t indx,
5320 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5323 size_t node_size = NODESIZE;
5326 MDB_page *mp = mc->mc_pg[mc->mc_top];
5327 MDB_page *ofp = NULL; /* overflow page */
5330 assert(mp->mp_upper >= mp->mp_lower);
5332 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5333 IS_LEAF(mp) ? "leaf" : "branch",
5334 IS_SUBP(mp) ? "sub-" : "",
5335 mp->mp_pgno, indx, data ? data->mv_size : 0,
5336 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5339 /* Move higher keys up one slot. */
5340 int ksize = mc->mc_db->md_pad, dif;
5341 char *ptr = LEAF2KEY(mp, indx, ksize);
5342 dif = NUMKEYS(mp) - indx;
5344 memmove(ptr+ksize, ptr, dif*ksize);
5345 /* insert new key */
5346 memcpy(ptr, key->mv_data, ksize);
5348 /* Just using these for counting */
5349 mp->mp_lower += sizeof(indx_t);
5350 mp->mp_upper -= ksize - sizeof(indx_t);
5355 node_size += key->mv_size;
5359 if (F_ISSET(flags, F_BIGDATA)) {
5360 /* Data already on overflow page. */
5361 node_size += sizeof(pgno_t);
5362 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
5363 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5365 /* Put data on overflow page. */
5366 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
5367 data->mv_size, node_size+data->mv_size);
5368 node_size += sizeof(pgno_t);
5369 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
5371 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
5374 node_size += data->mv_size;
5377 node_size += node_size & 1;
5379 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
5380 DPRINTF("not enough room in page %zu, got %u ptrs",
5381 mp->mp_pgno, NUMKEYS(mp));
5382 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
5383 mp->mp_upper - mp->mp_lower);
5384 DPRINTF("node size = %zu", node_size);
5385 return MDB_PAGE_FULL;
5388 /* Move higher pointers up one slot. */
5389 for (i = NUMKEYS(mp); i > indx; i--)
5390 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
5392 /* Adjust free space offsets. */
5393 ofs = mp->mp_upper - node_size;
5394 assert(ofs >= mp->mp_lower + sizeof(indx_t));
5395 mp->mp_ptrs[indx] = ofs;
5397 mp->mp_lower += sizeof(indx_t);
5399 /* Write the node data. */
5400 node = NODEPTR(mp, indx);
5401 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
5402 node->mn_flags = flags;
5404 SETDSZ(node,data->mv_size);
5409 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5414 if (F_ISSET(flags, F_BIGDATA))
5415 memcpy(node->mn_data + key->mv_size, data->mv_data,
5417 else if (F_ISSET(flags, MDB_RESERVE))
5418 data->mv_data = node->mn_data + key->mv_size;
5420 memcpy(node->mn_data + key->mv_size, data->mv_data,
5423 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
5425 if (F_ISSET(flags, MDB_RESERVE))
5426 data->mv_data = METADATA(ofp);
5428 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
5435 /** Delete the specified node from a page.
5436 * @param[in] mp The page to operate on.
5437 * @param[in] indx The index of the node to delete.
5438 * @param[in] ksize The size of a node. Only used if the page is
5439 * part of a #MDB_DUPFIXED database.
5442 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
5445 indx_t i, j, numkeys, ptr;
5452 COPY_PGNO(pgno, mp->mp_pgno);
5453 DPRINTF("delete node %u on %s page %zu", indx,
5454 IS_LEAF(mp) ? "leaf" : "branch", pgno);
5457 assert(indx < NUMKEYS(mp));
5460 int x = NUMKEYS(mp) - 1 - indx;
5461 base = LEAF2KEY(mp, indx, ksize);
5463 memmove(base, base + ksize, x * ksize);
5464 mp->mp_lower -= sizeof(indx_t);
5465 mp->mp_upper += ksize - sizeof(indx_t);
5469 node = NODEPTR(mp, indx);
5470 sz = NODESIZE + node->mn_ksize;
5472 if (F_ISSET(node->mn_flags, F_BIGDATA))
5473 sz += sizeof(pgno_t);
5475 sz += NODEDSZ(node);
5479 ptr = mp->mp_ptrs[indx];
5480 numkeys = NUMKEYS(mp);
5481 for (i = j = 0; i < numkeys; i++) {
5483 mp->mp_ptrs[j] = mp->mp_ptrs[i];
5484 if (mp->mp_ptrs[i] < ptr)
5485 mp->mp_ptrs[j] += sz;
5490 base = (char *)mp + mp->mp_upper;
5491 memmove(base + sz, base, ptr - mp->mp_upper);
5493 mp->mp_lower -= sizeof(indx_t);
5497 /** Compact the main page after deleting a node on a subpage.
5498 * @param[in] mp The main page to operate on.
5499 * @param[in] indx The index of the subpage on the main page.
5502 mdb_node_shrink(MDB_page *mp, indx_t indx)
5509 indx_t i, numkeys, ptr;
5511 node = NODEPTR(mp, indx);
5512 sp = (MDB_page *)NODEDATA(node);
5513 osize = NODEDSZ(node);
5515 delta = sp->mp_upper - sp->mp_lower;
5516 SETDSZ(node, osize - delta);
5517 xp = (MDB_page *)((char *)sp + delta);
5519 /* shift subpage upward */
5521 nsize = NUMKEYS(sp) * sp->mp_pad;
5522 memmove(METADATA(xp), METADATA(sp), nsize);
5525 nsize = osize - sp->mp_upper;
5526 numkeys = NUMKEYS(sp);
5527 for (i=numkeys-1; i>=0; i--)
5528 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
5530 xp->mp_upper = sp->mp_lower;
5531 xp->mp_lower = sp->mp_lower;
5532 xp->mp_flags = sp->mp_flags;
5533 xp->mp_pad = sp->mp_pad;
5534 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
5536 /* shift lower nodes upward */
5537 ptr = mp->mp_ptrs[indx];
5538 numkeys = NUMKEYS(mp);
5539 for (i = 0; i < numkeys; i++) {
5540 if (mp->mp_ptrs[i] <= ptr)
5541 mp->mp_ptrs[i] += delta;
5544 base = (char *)mp + mp->mp_upper;
5545 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
5546 mp->mp_upper += delta;
5549 /** Initial setup of a sorted-dups cursor.
5550 * Sorted duplicates are implemented as a sub-database for the given key.
5551 * The duplicate data items are actually keys of the sub-database.
5552 * Operations on the duplicate data items are performed using a sub-cursor
5553 * initialized when the sub-database is first accessed. This function does
5554 * the preliminary setup of the sub-cursor, filling in the fields that
5555 * depend only on the parent DB.
5556 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5559 mdb_xcursor_init0(MDB_cursor *mc)
5561 MDB_xcursor *mx = mc->mc_xcursor;
5563 mx->mx_cursor.mc_xcursor = NULL;
5564 mx->mx_cursor.mc_txn = mc->mc_txn;
5565 mx->mx_cursor.mc_db = &mx->mx_db;
5566 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
5567 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
5568 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
5569 mx->mx_cursor.mc_snum = 0;
5570 mx->mx_cursor.mc_top = 0;
5571 mx->mx_cursor.mc_flags = C_SUB;
5572 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
5573 mx->mx_dbx.md_dcmp = NULL;
5574 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
5577 /** Final setup of a sorted-dups cursor.
5578 * Sets up the fields that depend on the data from the main cursor.
5579 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5580 * @param[in] node The data containing the #MDB_db record for the
5581 * sorted-dup database.
5584 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5586 MDB_xcursor *mx = mc->mc_xcursor;
5588 if (node->mn_flags & F_SUBDATA) {
5589 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5590 mx->mx_cursor.mc_pg[0] = 0;
5591 mx->mx_cursor.mc_snum = 0;
5592 mx->mx_cursor.mc_flags = C_SUB;
5594 MDB_page *fp = NODEDATA(node);
5595 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5596 mx->mx_db.md_flags = 0;
5597 mx->mx_db.md_depth = 1;
5598 mx->mx_db.md_branch_pages = 0;
5599 mx->mx_db.md_leaf_pages = 1;
5600 mx->mx_db.md_overflow_pages = 0;
5601 mx->mx_db.md_entries = NUMKEYS(fp);
5602 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5603 mx->mx_cursor.mc_snum = 1;
5604 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5605 mx->mx_cursor.mc_top = 0;
5606 mx->mx_cursor.mc_pg[0] = fp;
5607 mx->mx_cursor.mc_ki[0] = 0;
5608 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5609 mx->mx_db.md_flags = MDB_DUPFIXED;
5610 mx->mx_db.md_pad = fp->mp_pad;
5611 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5612 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5615 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5617 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
5619 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5620 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5621 #if UINT_MAX < SIZE_MAX
5622 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5623 #ifdef MISALIGNED_OK
5624 mx->mx_dbx.md_cmp = mdb_cmp_long;
5626 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5631 /** Initialize a cursor for a given transaction and database. */
5633 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5638 mc->mc_db = &txn->mt_dbs[dbi];
5639 mc->mc_dbx = &txn->mt_dbxs[dbi];
5640 mc->mc_dbflag = &txn->mt_dbflags[dbi];
5645 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5647 mc->mc_xcursor = mx;
5648 mdb_xcursor_init0(mc);
5650 mc->mc_xcursor = NULL;
5652 if (*mc->mc_dbflag & DB_STALE) {
5653 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5658 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5661 MDB_xcursor *mx = NULL;
5662 size_t size = sizeof(MDB_cursor);
5664 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
5667 /* Allow read access to the freelist */
5668 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5671 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5672 size += sizeof(MDB_xcursor);
5674 if ((mc = malloc(size)) != NULL) {
5675 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5676 mx = (MDB_xcursor *)(mc + 1);
5678 mdb_cursor_init(mc, txn, dbi, mx);
5679 if (txn->mt_cursors) {
5680 mc->mc_next = txn->mt_cursors[dbi];
5681 txn->mt_cursors[dbi] = mc;
5683 mc->mc_flags |= C_ALLOCD;
5694 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
5696 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
5699 if (txn->mt_cursors)
5702 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
5706 /* Return the count of duplicate data items for the current key */
5708 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5712 if (mc == NULL || countp == NULL)
5715 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5718 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5719 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5722 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5725 *countp = mc->mc_xcursor->mx_db.md_entries;
5731 mdb_cursor_close(MDB_cursor *mc)
5734 /* remove from txn, if tracked */
5735 if (mc->mc_txn->mt_cursors) {
5736 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5737 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5739 *prev = mc->mc_next;
5741 if (mc->mc_flags & C_ALLOCD)
5747 mdb_cursor_txn(MDB_cursor *mc)
5749 if (!mc) return NULL;
5754 mdb_cursor_dbi(MDB_cursor *mc)
5760 /** Replace the key for a node with a new key.
5761 * @param[in] mp The page containing the node to operate on.
5762 * @param[in] indx The index of the node to operate on.
5763 * @param[in] key The new key to use.
5764 * @return 0 on success, non-zero on failure.
5767 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5773 indx_t ptr, i, numkeys;
5776 node = NODEPTR(mp, indx);
5777 ptr = mp->mp_ptrs[indx];
5781 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
5782 k2.mv_data = NODEKEY(node);
5783 k2.mv_size = node->mn_ksize;
5784 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5786 mdb_dkey(&k2, kbuf2),
5792 delta0 = delta = key->mv_size - node->mn_ksize;
5794 /* Must be 2-byte aligned. If new key is
5795 * shorter by 1, the shift will be skipped.
5797 delta += (delta & 1);
5799 if (delta > 0 && SIZELEFT(mp) < delta) {
5800 DPRINTF("OUCH! Not enough room, delta = %d", delta);
5801 return MDB_PAGE_FULL;
5804 numkeys = NUMKEYS(mp);
5805 for (i = 0; i < numkeys; i++) {
5806 if (mp->mp_ptrs[i] <= ptr)
5807 mp->mp_ptrs[i] -= delta;
5810 base = (char *)mp + mp->mp_upper;
5811 len = ptr - mp->mp_upper + NODESIZE;
5812 memmove(base - delta, base, len);
5813 mp->mp_upper -= delta;
5815 node = NODEPTR(mp, indx);
5818 /* But even if no shift was needed, update ksize */
5820 node->mn_ksize = key->mv_size;
5823 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5828 /** Move a node from csrc to cdst.
5831 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5837 unsigned short flags;
5841 /* Mark src and dst as dirty. */
5842 if ((rc = mdb_page_touch(csrc)) ||
5843 (rc = mdb_page_touch(cdst)))
5846 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5847 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5848 key.mv_size = csrc->mc_db->md_pad;
5849 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5851 data.mv_data = NULL;
5855 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5856 assert(!((long)srcnode&1));
5857 srcpg = NODEPGNO(srcnode);
5858 flags = srcnode->mn_flags;
5859 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5860 unsigned int snum = csrc->mc_snum;
5862 /* must find the lowest key below src */
5863 mdb_page_search_root(csrc, NULL, 0);
5864 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5865 key.mv_size = csrc->mc_db->md_pad;
5866 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5868 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5869 key.mv_size = NODEKSZ(s2);
5870 key.mv_data = NODEKEY(s2);
5872 csrc->mc_snum = snum--;
5873 csrc->mc_top = snum;
5875 key.mv_size = NODEKSZ(srcnode);
5876 key.mv_data = NODEKEY(srcnode);
5878 data.mv_size = NODEDSZ(srcnode);
5879 data.mv_data = NODEDATA(srcnode);
5881 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5882 unsigned int snum = cdst->mc_snum;
5885 /* must find the lowest key below dst */
5886 mdb_page_search_root(cdst, NULL, 0);
5887 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
5888 bkey.mv_size = cdst->mc_db->md_pad;
5889 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
5891 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5892 bkey.mv_size = NODEKSZ(s2);
5893 bkey.mv_data = NODEKEY(s2);
5895 cdst->mc_snum = snum--;
5896 cdst->mc_top = snum;
5897 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5900 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5901 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5902 csrc->mc_ki[csrc->mc_top],
5904 csrc->mc_pg[csrc->mc_top]->mp_pgno,
5905 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5907 /* Add the node to the destination page.
5909 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5910 if (rc != MDB_SUCCESS)
5913 /* Delete the node from the source page.
5915 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5918 /* Adjust other cursors pointing to mp */
5919 MDB_cursor *m2, *m3;
5920 MDB_dbi dbi = csrc->mc_dbi;
5921 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5923 if (csrc->mc_flags & C_SUB)
5926 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5927 if (m2 == csrc) continue;
5928 if (csrc->mc_flags & C_SUB)
5929 m3 = &m2->mc_xcursor->mx_cursor;
5932 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5933 csrc->mc_ki[csrc->mc_top]) {
5934 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5935 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5940 /* Update the parent separators.
5942 if (csrc->mc_ki[csrc->mc_top] == 0) {
5943 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5944 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5945 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5947 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5948 key.mv_size = NODEKSZ(srcnode);
5949 key.mv_data = NODEKEY(srcnode);
5951 DPRINTF("update separator for source page %zu to [%s]",
5952 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5953 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5954 &key)) != MDB_SUCCESS)
5957 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5959 nullkey.mv_size = 0;
5960 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5961 assert(rc == MDB_SUCCESS);
5965 if (cdst->mc_ki[cdst->mc_top] == 0) {
5966 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5967 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5968 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5970 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5971 key.mv_size = NODEKSZ(srcnode);
5972 key.mv_data = NODEKEY(srcnode);
5974 DPRINTF("update separator for destination page %zu to [%s]",
5975 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5976 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5977 &key)) != MDB_SUCCESS)
5980 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5982 nullkey.mv_size = 0;
5983 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5984 assert(rc == MDB_SUCCESS);
5991 /** Merge one page into another.
5992 * The nodes from the page pointed to by \b csrc will
5993 * be copied to the page pointed to by \b cdst and then
5994 * the \b csrc page will be freed.
5995 * @param[in] csrc Cursor pointing to the source page.
5996 * @param[in] cdst Cursor pointing to the destination page.
5999 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6007 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6008 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6010 assert(csrc->mc_snum > 1); /* can't merge root page */
6011 assert(cdst->mc_snum > 1);
6013 /* Mark dst as dirty. */
6014 if ((rc = mdb_page_touch(cdst)))
6017 /* Move all nodes from src to dst.
6019 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6020 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6021 key.mv_size = csrc->mc_db->md_pad;
6022 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6023 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6024 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6025 if (rc != MDB_SUCCESS)
6027 key.mv_data = (char *)key.mv_data + key.mv_size;
6030 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6031 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6032 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6033 unsigned int snum = csrc->mc_snum;
6035 /* must find the lowest key below src */
6036 mdb_page_search_root(csrc, NULL, 0);
6037 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6038 key.mv_size = csrc->mc_db->md_pad;
6039 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6041 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6042 key.mv_size = NODEKSZ(s2);
6043 key.mv_data = NODEKEY(s2);
6045 csrc->mc_snum = snum--;
6046 csrc->mc_top = snum;
6048 key.mv_size = srcnode->mn_ksize;
6049 key.mv_data = NODEKEY(srcnode);
6052 data.mv_size = NODEDSZ(srcnode);
6053 data.mv_data = NODEDATA(srcnode);
6054 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6055 if (rc != MDB_SUCCESS)
6060 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6061 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);
6063 /* Unlink the src page from parent and add to free list.
6065 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6066 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6068 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
6072 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
6073 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6074 csrc->mc_db->md_leaf_pages--;
6076 csrc->mc_db->md_branch_pages--;
6078 /* Adjust other cursors pointing to mp */
6079 MDB_cursor *m2, *m3;
6080 MDB_dbi dbi = csrc->mc_dbi;
6081 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6083 if (csrc->mc_flags & C_SUB)
6086 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6087 if (csrc->mc_flags & C_SUB)
6088 m3 = &m2->mc_xcursor->mx_cursor;
6091 if (m3 == csrc) continue;
6092 if (m3->mc_snum < csrc->mc_snum) continue;
6093 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6094 m3->mc_pg[csrc->mc_top] = mp;
6095 m3->mc_ki[csrc->mc_top] += nkeys;
6099 mdb_cursor_pop(csrc);
6101 return mdb_rebalance(csrc);
6104 /** Copy the contents of a cursor.
6105 * @param[in] csrc The cursor to copy from.
6106 * @param[out] cdst The cursor to copy to.
6109 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6113 cdst->mc_txn = csrc->mc_txn;
6114 cdst->mc_dbi = csrc->mc_dbi;
6115 cdst->mc_db = csrc->mc_db;
6116 cdst->mc_dbx = csrc->mc_dbx;
6117 cdst->mc_snum = csrc->mc_snum;
6118 cdst->mc_top = csrc->mc_top;
6119 cdst->mc_flags = csrc->mc_flags;
6121 for (i=0; i<csrc->mc_snum; i++) {
6122 cdst->mc_pg[i] = csrc->mc_pg[i];
6123 cdst->mc_ki[i] = csrc->mc_ki[i];
6127 /** Rebalance the tree after a delete operation.
6128 * @param[in] mc Cursor pointing to the page where rebalancing
6130 * @return 0 on success, non-zero on failure.
6133 mdb_rebalance(MDB_cursor *mc)
6143 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6144 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6145 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6146 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6150 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
6153 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6154 DPRINTF("no need to rebalance page %zu, above fill threshold",
6160 if (mc->mc_snum < 2) {
6161 MDB_page *mp = mc->mc_pg[0];
6162 if (NUMKEYS(mp) == 0) {
6163 DPUTS("tree is completely empty");
6164 mc->mc_db->md_root = P_INVALID;
6165 mc->mc_db->md_depth = 0;
6166 mc->mc_db->md_leaf_pages = 0;
6167 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6171 /* Adjust other cursors pointing to mp */
6172 MDB_cursor *m2, *m3;
6173 MDB_dbi dbi = mc->mc_dbi;
6175 if (mc->mc_flags & C_SUB)
6178 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6179 if (m2 == mc) continue;
6180 if (mc->mc_flags & C_SUB)
6181 m3 = &m2->mc_xcursor->mx_cursor;
6184 if (m3->mc_snum < mc->mc_snum) continue;
6185 if (m3->mc_pg[0] == mp) {
6191 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6192 DPUTS("collapsing root page!");
6193 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6194 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6195 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
6198 mc->mc_db->md_depth--;
6199 mc->mc_db->md_branch_pages--;
6201 /* Adjust other cursors pointing to mp */
6202 MDB_cursor *m2, *m3;
6203 MDB_dbi dbi = mc->mc_dbi;
6205 if (mc->mc_flags & C_SUB)
6208 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6209 if (m2 == mc) continue;
6210 if (mc->mc_flags & C_SUB)
6211 m3 = &m2->mc_xcursor->mx_cursor;
6214 if (m3->mc_snum < mc->mc_snum) continue;
6215 if (m3->mc_pg[0] == mp) {
6216 m3->mc_pg[0] = mc->mc_pg[0];
6221 DPUTS("root page doesn't need rebalancing");
6225 /* The parent (branch page) must have at least 2 pointers,
6226 * otherwise the tree is invalid.
6228 ptop = mc->mc_top-1;
6229 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6231 /* Leaf page fill factor is below the threshold.
6232 * Try to move keys from left or right neighbor, or
6233 * merge with a neighbor page.
6238 mdb_cursor_copy(mc, &mn);
6239 mn.mc_xcursor = NULL;
6241 if (mc->mc_ki[ptop] == 0) {
6242 /* We're the leftmost leaf in our parent.
6244 DPUTS("reading right neighbor");
6246 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6247 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
6249 mn.mc_ki[mn.mc_top] = 0;
6250 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6252 /* There is at least one neighbor to the left.
6254 DPUTS("reading left neighbor");
6256 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6257 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
6259 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6260 mc->mc_ki[mc->mc_top] = 0;
6263 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6264 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);
6266 /* If the neighbor page is above threshold and has at least two
6267 * keys, move one key from it.
6269 * Otherwise we should try to merge them.
6271 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
6272 return mdb_node_move(&mn, mc);
6273 else { /* FIXME: if (has_enough_room()) */
6274 mc->mc_flags &= ~C_INITIALIZED;
6275 if (mc->mc_ki[ptop] == 0)
6276 return mdb_page_merge(&mn, mc);
6278 return mdb_page_merge(mc, &mn);
6282 /** Complete a delete operation started by #mdb_cursor_del(). */
6284 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6288 /* add overflow pages to free list */
6289 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6293 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6294 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
6295 mc->mc_db->md_overflow_pages -= ovpages;
6296 for (i=0; i<ovpages; i++) {
6297 DPRINTF("freed ov page %zu", pg);
6298 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6302 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
6303 mc->mc_db->md_entries--;
6304 rc = mdb_rebalance(mc);
6305 if (rc != MDB_SUCCESS)
6306 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6312 mdb_del(MDB_txn *txn, MDB_dbi dbi,
6313 MDB_val *key, MDB_val *data)
6318 MDB_val rdata, *xdata;
6322 assert(key != NULL);
6324 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
6326 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6329 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6333 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6337 mdb_cursor_init(&mc, txn, dbi, &mx);
6348 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
6350 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
6354 /** Split a page and insert a new node.
6355 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
6356 * The cursor will be updated to point to the actual page and index where
6357 * the node got inserted after the split.
6358 * @param[in] newkey The key for the newly inserted node.
6359 * @param[in] newdata The data for the newly inserted node.
6360 * @param[in] newpgno The page number, if the new node is a branch node.
6361 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
6362 * @return 0 on success, non-zero on failure.
6365 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
6366 unsigned int nflags)
6369 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
6372 unsigned int i, j, split_indx, nkeys, pmax;
6374 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
6376 MDB_page *mp, *rp, *pp;
6381 mp = mc->mc_pg[mc->mc_top];
6382 newindx = mc->mc_ki[mc->mc_top];
6384 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
6385 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
6386 DKEY(newkey), mc->mc_ki[mc->mc_top]);
6388 /* Create a right sibling. */
6389 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
6391 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
6393 if (mc->mc_snum < 2) {
6394 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
6396 /* shift current top to make room for new parent */
6397 mc->mc_pg[1] = mc->mc_pg[0];
6398 mc->mc_ki[1] = mc->mc_ki[0];
6401 mc->mc_db->md_root = pp->mp_pgno;
6402 DPRINTF("root split! new root = %zu", pp->mp_pgno);
6403 mc->mc_db->md_depth++;
6406 /* Add left (implicit) pointer. */
6407 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
6408 /* undo the pre-push */
6409 mc->mc_pg[0] = mc->mc_pg[1];
6410 mc->mc_ki[0] = mc->mc_ki[1];
6411 mc->mc_db->md_root = mp->mp_pgno;
6412 mc->mc_db->md_depth--;
6419 ptop = mc->mc_top-1;
6420 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
6423 mc->mc_flags |= C_SPLITTING;
6424 mdb_cursor_copy(mc, &mn);
6425 mn.mc_pg[mn.mc_top] = rp;
6426 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
6428 if (nflags & MDB_APPEND) {
6429 mn.mc_ki[mn.mc_top] = 0;
6431 split_indx = newindx;
6436 nkeys = NUMKEYS(mp);
6437 split_indx = nkeys / 2;
6438 if (newindx < split_indx)
6444 unsigned int lsize, rsize, ksize;
6445 /* Move half of the keys to the right sibling */
6447 x = mc->mc_ki[mc->mc_top] - split_indx;
6448 ksize = mc->mc_db->md_pad;
6449 split = LEAF2KEY(mp, split_indx, ksize);
6450 rsize = (nkeys - split_indx) * ksize;
6451 lsize = (nkeys - split_indx) * sizeof(indx_t);
6452 mp->mp_lower -= lsize;
6453 rp->mp_lower += lsize;
6454 mp->mp_upper += rsize - lsize;
6455 rp->mp_upper -= rsize - lsize;
6456 sepkey.mv_size = ksize;
6457 if (newindx == split_indx) {
6458 sepkey.mv_data = newkey->mv_data;
6460 sepkey.mv_data = split;
6463 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
6464 memcpy(rp->mp_ptrs, split, rsize);
6465 sepkey.mv_data = rp->mp_ptrs;
6466 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
6467 memcpy(ins, newkey->mv_data, ksize);
6468 mp->mp_lower += sizeof(indx_t);
6469 mp->mp_upper -= ksize - sizeof(indx_t);
6472 memcpy(rp->mp_ptrs, split, x * ksize);
6473 ins = LEAF2KEY(rp, x, ksize);
6474 memcpy(ins, newkey->mv_data, ksize);
6475 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
6476 rp->mp_lower += sizeof(indx_t);
6477 rp->mp_upper -= ksize - sizeof(indx_t);
6478 mc->mc_ki[mc->mc_top] = x;
6479 mc->mc_pg[mc->mc_top] = rp;
6484 /* For leaf pages, check the split point based on what
6485 * fits where, since otherwise mdb_node_add can fail.
6487 * This check is only needed when the data items are
6488 * relatively large, such that being off by one will
6489 * make the difference between success or failure.
6491 * It's also relevant if a page happens to be laid out
6492 * such that one half of its nodes are all "small" and
6493 * the other half of its nodes are "large." If the new
6494 * item is also "large" and falls on the half with
6495 * "large" nodes, it also may not fit.
6498 unsigned int psize, nsize;
6499 /* Maximum free space in an empty page */
6500 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
6501 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
6502 if ((nkeys < 20) || (nsize > pmax/16)) {
6503 if (newindx <= split_indx) {
6506 for (i=0; i<split_indx; i++) {
6507 node = NODEPTR(mp, i);
6508 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6509 if (F_ISSET(node->mn_flags, F_BIGDATA))
6510 psize += sizeof(pgno_t);
6512 psize += NODEDSZ(node);
6516 split_indx = newindx;
6527 for (i=nkeys-1; i>=split_indx; i--) {
6528 node = NODEPTR(mp, i);
6529 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6530 if (F_ISSET(node->mn_flags, F_BIGDATA))
6531 psize += sizeof(pgno_t);
6533 psize += NODEDSZ(node);
6537 split_indx = newindx;
6548 /* First find the separating key between the split pages.
6549 * The case where newindx == split_indx is ambiguous; the
6550 * new item could go to the new page or stay on the original
6551 * page. If newpos == 1 it goes to the new page.
6553 if (newindx == split_indx && newpos) {
6554 sepkey.mv_size = newkey->mv_size;
6555 sepkey.mv_data = newkey->mv_data;
6557 node = NODEPTR(mp, split_indx);
6558 sepkey.mv_size = node->mn_ksize;
6559 sepkey.mv_data = NODEKEY(node);
6563 DPRINTF("separator is [%s]", DKEY(&sepkey));
6565 /* Copy separator key to the parent.
6567 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
6571 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
6574 if (mn.mc_snum == mc->mc_snum) {
6575 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
6576 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
6577 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
6578 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
6583 /* Right page might now have changed parent.
6584 * Check if left page also changed parent.
6586 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6587 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6588 for (i=0; i<ptop; i++) {
6589 mc->mc_pg[i] = mn.mc_pg[i];
6590 mc->mc_ki[i] = mn.mc_ki[i];
6592 mc->mc_pg[ptop] = mn.mc_pg[ptop];
6593 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6597 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
6600 mc->mc_flags ^= C_SPLITTING;
6601 if (rc != MDB_SUCCESS) {
6604 if (nflags & MDB_APPEND) {
6605 mc->mc_pg[mc->mc_top] = rp;
6606 mc->mc_ki[mc->mc_top] = 0;
6607 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6610 for (i=0; i<mc->mc_top; i++)
6611 mc->mc_ki[i] = mn.mc_ki[i];
6618 /* Move half of the keys to the right sibling. */
6620 /* grab a page to hold a temporary copy */
6621 copy = mdb_page_malloc(mc);
6625 copy->mp_pgno = mp->mp_pgno;
6626 copy->mp_flags = mp->mp_flags;
6627 copy->mp_lower = PAGEHDRSZ;
6628 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6629 mc->mc_pg[mc->mc_top] = copy;
6630 for (i = j = 0; i <= nkeys; j++) {
6631 if (i == split_indx) {
6632 /* Insert in right sibling. */
6633 /* Reset insert index for right sibling. */
6634 if (i != newindx || (newpos ^ ins_new)) {
6636 mc->mc_pg[mc->mc_top] = rp;
6640 if (i == newindx && !ins_new) {
6641 /* Insert the original entry that caused the split. */
6642 rkey.mv_data = newkey->mv_data;
6643 rkey.mv_size = newkey->mv_size;
6652 /* Update index for the new key. */
6653 mc->mc_ki[mc->mc_top] = j;
6654 } else if (i == nkeys) {
6657 node = NODEPTR(mp, i);
6658 rkey.mv_data = NODEKEY(node);
6659 rkey.mv_size = node->mn_ksize;
6661 xdata.mv_data = NODEDATA(node);
6662 xdata.mv_size = NODEDSZ(node);
6665 pgno = NODEPGNO(node);
6666 flags = node->mn_flags;
6671 if (!IS_LEAF(mp) && j == 0) {
6672 /* First branch index doesn't need key data. */
6676 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6680 nkeys = NUMKEYS(copy);
6681 for (i=0; i<nkeys; i++)
6682 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6683 mp->mp_lower = copy->mp_lower;
6684 mp->mp_upper = copy->mp_upper;
6685 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6686 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6688 /* reset back to original page */
6689 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6690 mc->mc_pg[mc->mc_top] = mp;
6691 if (nflags & MDB_RESERVE) {
6692 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6693 if (!(node->mn_flags & F_BIGDATA))
6694 newdata->mv_data = NODEDATA(node);
6700 /* return tmp page to freelist */
6701 mdb_page_free(mc->mc_txn->mt_env, copy);
6704 /* Adjust other cursors pointing to mp */
6705 MDB_cursor *m2, *m3;
6706 MDB_dbi dbi = mc->mc_dbi;
6707 int fixup = NUMKEYS(mp);
6709 if (mc->mc_flags & C_SUB)
6712 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6713 if (m2 == mc) continue;
6714 if (mc->mc_flags & C_SUB)
6715 m3 = &m2->mc_xcursor->mx_cursor;
6718 if (!(m3->mc_flags & C_INITIALIZED))
6720 if (m3->mc_flags & C_SPLITTING)
6725 for (k=m3->mc_top; k>=0; k--) {
6726 m3->mc_ki[k+1] = m3->mc_ki[k];
6727 m3->mc_pg[k+1] = m3->mc_pg[k];
6729 if (m3->mc_ki[0] >= split_indx) {
6734 m3->mc_pg[0] = mc->mc_pg[0];
6738 if (m3->mc_pg[mc->mc_top] == mp) {
6739 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
6740 m3->mc_ki[mc->mc_top]++;
6741 if (m3->mc_ki[mc->mc_top] >= fixup) {
6742 m3->mc_pg[mc->mc_top] = rp;
6743 m3->mc_ki[mc->mc_top] -= fixup;
6744 m3->mc_ki[ptop] = mn.mc_ki[ptop];
6746 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
6747 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
6756 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6757 MDB_val *key, MDB_val *data, unsigned int flags)
6762 assert(key != NULL);
6763 assert(data != NULL);
6765 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6768 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6772 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6776 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6779 mdb_cursor_init(&mc, txn, dbi, &mx);
6780 return mdb_cursor_put(&mc, key, data, flags);
6784 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6786 if ((flag & CHANGEABLE) != flag)
6789 env->me_flags |= flag;
6791 env->me_flags &= ~flag;
6796 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6801 *arg = env->me_flags;
6806 mdb_env_get_path(MDB_env *env, const char **arg)
6811 *arg = env->me_path;
6815 /** Common code for #mdb_stat() and #mdb_env_stat().
6816 * @param[in] env the environment to operate in.
6817 * @param[in] db the #MDB_db record containing the stats to return.
6818 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6819 * @return 0, this function always succeeds.
6822 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6824 arg->ms_psize = env->me_psize;
6825 arg->ms_depth = db->md_depth;
6826 arg->ms_branch_pages = db->md_branch_pages;
6827 arg->ms_leaf_pages = db->md_leaf_pages;
6828 arg->ms_overflow_pages = db->md_overflow_pages;
6829 arg->ms_entries = db->md_entries;
6834 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6838 if (env == NULL || arg == NULL)
6841 toggle = mdb_env_pick_meta(env);
6843 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6847 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
6851 if (env == NULL || arg == NULL)
6854 toggle = mdb_env_pick_meta(env);
6855 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
6856 arg->me_mapsize = env->me_mapsize;
6857 arg->me_maxreaders = env->me_maxreaders;
6858 arg->me_numreaders = env->me_numreaders;
6859 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
6860 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
6864 /** Set the default comparison functions for a database.
6865 * Called immediately after a database is opened to set the defaults.
6866 * The user can then override them with #mdb_set_compare() or
6867 * #mdb_set_dupsort().
6868 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6869 * @param[in] dbi A database handle returned by #mdb_dbi_open()
6872 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6874 uint16_t f = txn->mt_dbs[dbi].md_flags;
6876 txn->mt_dbxs[dbi].md_cmp =
6877 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
6878 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
6880 txn->mt_dbxs[dbi].md_dcmp =
6881 !(f & MDB_DUPSORT) ? 0 :
6882 ((f & MDB_INTEGERDUP)
6883 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
6884 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
6887 #define PERSISTENT_FLAGS 0xffff
6888 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
6889 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
6890 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6895 int rc, dbflag, exact;
6896 unsigned int unused = 0;
6899 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6900 mdb_default_cmp(txn, FREE_DBI);
6903 if ((flags & VALID_FLAGS) != flags)
6909 if (flags & PERSISTENT_FLAGS) {
6910 uint16_t f2 = flags & PERSISTENT_FLAGS;
6911 /* make sure flag changes get committed */
6912 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
6913 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
6914 txn->mt_flags |= MDB_TXN_DIRTY;
6917 mdb_default_cmp(txn, MAIN_DBI);
6921 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6922 mdb_default_cmp(txn, MAIN_DBI);
6925 /* Is the DB already open? */
6927 for (i=2; i<txn->mt_numdbs; i++) {
6928 if (!txn->mt_dbxs[i].md_name.mv_size) {
6929 /* Remember this free slot */
6930 if (!unused) unused = i;
6933 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6934 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6940 /* If no free slot and max hit, fail */
6941 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
6942 return MDB_DBS_FULL;
6944 /* Find the DB info */
6948 key.mv_data = (void *)name;
6949 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6950 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6951 if (rc == MDB_SUCCESS) {
6952 /* make sure this is actually a DB */
6953 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6954 if (!(node->mn_flags & F_SUBDATA))
6956 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6957 /* Create if requested */
6959 data.mv_size = sizeof(MDB_db);
6960 data.mv_data = &dummy;
6961 memset(&dummy, 0, sizeof(dummy));
6962 dummy.md_root = P_INVALID;
6963 dummy.md_flags = flags & PERSISTENT_FLAGS;
6964 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6968 /* OK, got info, add to table */
6969 if (rc == MDB_SUCCESS) {
6970 unsigned int slot = unused ? unused : txn->mt_numdbs;
6971 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
6972 txn->mt_dbxs[slot].md_name.mv_size = len;
6973 txn->mt_dbxs[slot].md_rel = NULL;
6974 txn->mt_dbflags[slot] = dbflag;
6975 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
6977 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
6978 mdb_default_cmp(txn, slot);
6981 txn->mt_env->me_numdbs++;
6988 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6990 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6993 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6996 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
6999 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
7001 ptr = env->me_dbxs[dbi].md_name.mv_data;
7002 env->me_dbxs[dbi].md_name.mv_data = NULL;
7003 env->me_dbxs[dbi].md_name.mv_size = 0;
7007 /** Add all the DB's pages to the free list.
7008 * @param[in] mc Cursor on the DB to free.
7009 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7010 * @return 0 on success, non-zero on failure.
7013 mdb_drop0(MDB_cursor *mc, int subs)
7017 rc = mdb_page_search(mc, NULL, 0);
7018 if (rc == MDB_SUCCESS) {
7023 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7024 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
7027 mdb_cursor_copy(mc, &mx);
7028 while (mc->mc_snum > 0) {
7029 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
7030 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7031 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7032 if (ni->mn_flags & F_SUBDATA) {
7033 mdb_xcursor_init1(mc, ni);
7034 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7040 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7042 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7045 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
7050 rc = mdb_cursor_sibling(mc, 1);
7052 /* no more siblings, go back to beginning
7053 * of previous level.
7056 for (i=1; i<mc->mc_top; i++)
7057 mc->mc_pg[i] = mx.mc_pg[i];
7061 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
7062 mc->mc_db->md_root);
7067 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7072 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1)
7075 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7078 rc = mdb_cursor_open(txn, dbi, &mc);
7082 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7086 /* Can't delete the main DB */
7087 if (del && dbi > MAIN_DBI) {
7088 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7090 mdb_dbi_close(txn->mt_env, dbi);
7092 /* reset the DB record, mark it dirty */
7093 txn->mt_dbflags[dbi] |= DB_DIRTY;
7094 txn->mt_dbs[dbi].md_depth = 0;
7095 txn->mt_dbs[dbi].md_branch_pages = 0;
7096 txn->mt_dbs[dbi].md_leaf_pages = 0;
7097 txn->mt_dbs[dbi].md_overflow_pages = 0;
7098 txn->mt_dbs[dbi].md_entries = 0;
7099 txn->mt_dbs[dbi].md_root = P_INVALID;
7101 if (!txn->mt_u.dirty_list[0].mid) {
7104 /* make sure we have at least one dirty page in this txn
7105 * otherwise these changes will be ignored.
7107 key.mv_size = sizeof(txnid_t);
7108 key.mv_data = &txn->mt_txnid;
7109 data.mv_size = sizeof(MDB_ID);
7110 data.mv_data = txn->mt_free_pgs;
7111 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
7112 rc = mdb_cursor_put(&m2, &key, &data, 0);
7116 mdb_cursor_close(mc);
7120 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7122 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7125 txn->mt_dbxs[dbi].md_cmp = cmp;
7129 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7131 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7134 txn->mt_dbxs[dbi].md_dcmp = cmp;
7138 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7140 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7143 txn->mt_dbxs[dbi].md_rel = rel;
7147 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7149 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7152 txn->mt_dbxs[dbi].md_relctx = ctx;