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.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 #include <semaphore.h>
83 #include <valgrind/memcheck.h>
84 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
85 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
86 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
87 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
88 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
90 #define VGMEMP_CREATE(h,r,z)
91 #define VGMEMP_ALLOC(h,a,s)
92 #define VGMEMP_FREE(h,a)
93 #define VGMEMP_DESTROY(h)
94 #define VGMEMP_DEFINED(a,s)
98 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
99 /* Solaris just defines one or the other */
100 # define LITTLE_ENDIAN 1234
101 # define BIG_ENDIAN 4321
102 # ifdef _LITTLE_ENDIAN
103 # define BYTE_ORDER LITTLE_ENDIAN
105 # define BYTE_ORDER BIG_ENDIAN
108 # define BYTE_ORDER __BYTE_ORDER
112 #ifndef LITTLE_ENDIAN
113 #define LITTLE_ENDIAN __LITTLE_ENDIAN
116 #define BIG_ENDIAN __BIG_ENDIAN
119 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
120 #define MISALIGNED_OK 1
126 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
127 # error "Unknown or unsupported endianness (BYTE_ORDER)"
128 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
129 # error "Two's complement, reasonably sized integer types, please"
132 /** @defgroup internal MDB Internals
135 /** @defgroup compat Windows Compatibility Macros
136 * A bunch of macros to minimize the amount of platform-specific ifdefs
137 * needed throughout the rest of the code. When the features this library
138 * needs are similar enough to POSIX to be hidden in a one-or-two line
139 * replacement, this macro approach is used.
143 #define pthread_t DWORD
144 #define pthread_mutex_t HANDLE
145 #define pthread_key_t DWORD
146 #define pthread_self() GetCurrentThreadId()
147 #define pthread_key_create(x,y) \
148 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
149 #define pthread_key_delete(x) TlsFree(x)
150 #define pthread_getspecific(x) TlsGetValue(x)
151 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
152 #define pthread_mutex_unlock(x) ReleaseMutex(x)
153 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
154 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
158 #define getpid() GetCurrentProcessId()
159 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
160 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
161 #define ErrCode() GetLastError()
162 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
163 #define close(fd) (CloseHandle(fd) ? 0 : -1)
164 #define munmap(ptr,len) UnmapViewOfFile(ptr)
170 #ifdef MDB_USE_POSIX_SEM
172 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
173 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
174 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
175 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
178 mdb_sem_wait(sem_t *sem)
181 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
186 /** Lock the reader mutex.
188 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
189 /** Unlock the reader mutex.
191 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
193 /** Lock the writer mutex.
194 * Only a single write transaction is allowed at a time. Other writers
195 * will block waiting for this mutex.
197 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
198 /** Unlock the writer mutex.
200 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
201 #endif /* MDB_USE_POSIX_SEM */
203 /** Get the error code for the last failed system function.
205 #define ErrCode() errno
207 /** An abstraction for a file handle.
208 * On POSIX systems file handles are small integers. On Windows
209 * they're opaque pointers.
213 /** A value for an invalid file handle.
214 * Mainly used to initialize file variables and signify that they are
217 #define INVALID_HANDLE_VALUE (-1)
219 /** Get the size of a memory page for the system.
220 * This is the basic size that the platform's memory manager uses, and is
221 * fundamental to the use of memory-mapped files.
223 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
226 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
229 #define MNAME_LEN (sizeof(pthread_mutex_t))
235 /** A flag for opening a file and requesting synchronous data writes.
236 * This is only used when writing a meta page. It's not strictly needed;
237 * we could just do a normal write and then immediately perform a flush.
238 * But if this flag is available it saves us an extra system call.
240 * @note If O_DSYNC is undefined but exists in /usr/include,
241 * preferably set some compiler flag to get the definition.
242 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
245 # define MDB_DSYNC O_DSYNC
249 /** Function for flushing the data of a file. Define this to fsync
250 * if fdatasync() is not supported.
252 #ifndef MDB_FDATASYNC
253 # define MDB_FDATASYNC fdatasync
257 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
268 /** A page number in the database.
269 * Note that 64 bit page numbers are overkill, since pages themselves
270 * already represent 12-13 bits of addressable memory, and the OS will
271 * always limit applications to a maximum of 63 bits of address space.
273 * @note In the #MDB_node structure, we only store 48 bits of this value,
274 * which thus limits us to only 60 bits of addressable data.
276 typedef MDB_ID pgno_t;
278 /** A transaction ID.
279 * See struct MDB_txn.mt_txnid for details.
281 typedef MDB_ID txnid_t;
283 /** @defgroup debug Debug Macros
287 /** Enable debug output.
288 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
289 * read from and written to the database (used for free space management).
294 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
297 # define DPRINTF (void) /* Vararg macros may be unsupported */
299 static int mdb_debug;
300 static txnid_t mdb_debug_start;
302 /** Print a debug message with printf formatting. */
303 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
304 ((void) ((mdb_debug) && \
305 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
307 # define DPRINTF(fmt, ...) ((void) 0)
308 # define MDB_DEBUG_SKIP
310 /** Print a debug string.
311 * The string is printed literally, with no format processing.
313 #define DPUTS(arg) DPRINTF("%s", arg)
316 /** A default memory page size.
317 * The actual size is platform-dependent, but we use this for
318 * boot-strapping. We probably should not be using this any more.
319 * The #GET_PAGESIZE() macro is used to get the actual size.
321 * Note that we don't currently support Huge pages. On Linux,
322 * regular data files cannot use Huge pages, and in general
323 * Huge pages aren't actually pageable. We rely on the OS
324 * demand-pager to read our data and page it out when memory
325 * pressure from other processes is high. So until OSs have
326 * actual paging support for Huge pages, they're not viable.
328 #define MDB_PAGESIZE 4096
330 /** The minimum number of keys required in a database page.
331 * Setting this to a larger value will place a smaller bound on the
332 * maximum size of a data item. Data items larger than this size will
333 * be pushed into overflow pages instead of being stored directly in
334 * the B-tree node. This value used to default to 4. With a page size
335 * of 4096 bytes that meant that any item larger than 1024 bytes would
336 * go into an overflow page. That also meant that on average 2-3KB of
337 * each overflow page was wasted space. The value cannot be lower than
338 * 2 because then there would no longer be a tree structure. With this
339 * value, items larger than 2KB will go into overflow pages, and on
340 * average only 1KB will be wasted.
342 #define MDB_MINKEYS 2
344 /** A stamp that identifies a file as an MDB file.
345 * There's nothing special about this value other than that it is easily
346 * recognizable, and it will reflect any byte order mismatches.
348 #define MDB_MAGIC 0xBEEFC0DE
350 /** The version number for a database's datafile format. */
351 #define MDB_DATA_VERSION 1
352 /** The version number for a database's lockfile format. */
353 #define MDB_LOCK_VERSION 1
355 /** @brief The maximum size of a key in the database.
357 * The library rejects bigger keys, and cannot deal with records
358 * with bigger keys stored by a library with bigger max keysize.
360 * We require that keys all fit onto a regular page. This limit
361 * could be raised a bit further if needed; to something just
362 * under #MDB_PAGESIZE / #MDB_MINKEYS.
364 * Note that data items in an #MDB_DUPSORT database are actually keys
365 * of a subDB, so they're also limited to this size.
367 #ifndef MDB_MAXKEYSIZE
368 #define MDB_MAXKEYSIZE 511
371 /** @brief The maximum size of a data item.
373 * We only store a 32 bit value for node sizes.
375 #define MAXDATASIZE 0xffffffffUL
380 * This is used for printing a hex dump of a key's contents.
382 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
383 /** Display a key in hex.
385 * Invoke a function to display a key in hex.
387 #define DKEY(x) mdb_dkey(x, kbuf)
389 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
393 /** An invalid page number.
394 * Mainly used to denote an empty tree.
396 #define P_INVALID (~(pgno_t)0)
398 /** Test if the flags \b f are set in a flag word \b w. */
399 #define F_ISSET(w, f) (((w) & (f)) == (f))
401 /** Used for offsets within a single page.
402 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
405 typedef uint16_t indx_t;
407 /** Default size of memory map.
408 * This is certainly too small for any actual applications. Apps should always set
409 * the size explicitly using #mdb_env_set_mapsize().
411 #define DEFAULT_MAPSIZE 1048576
413 /** @defgroup readers Reader Lock Table
414 * Readers don't acquire any locks for their data access. Instead, they
415 * simply record their transaction ID in the reader table. The reader
416 * mutex is needed just to find an empty slot in the reader table. The
417 * slot's address is saved in thread-specific data so that subsequent read
418 * transactions started by the same thread need no further locking to proceed.
420 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
422 * No reader table is used if the database is on a read-only filesystem.
424 * Since the database uses multi-version concurrency control, readers don't
425 * actually need any locking. This table is used to keep track of which
426 * readers are using data from which old transactions, so that we'll know
427 * when a particular old transaction is no longer in use. Old transactions
428 * that have discarded any data pages can then have those pages reclaimed
429 * for use by a later write transaction.
431 * The lock table is constructed such that reader slots are aligned with the
432 * processor's cache line size. Any slot is only ever used by one thread.
433 * This alignment guarantees that there will be no contention or cache
434 * thrashing as threads update their own slot info, and also eliminates
435 * any need for locking when accessing a slot.
437 * A writer thread will scan every slot in the table to determine the oldest
438 * outstanding reader transaction. Any freed pages older than this will be
439 * reclaimed by the writer. The writer doesn't use any locks when scanning
440 * this table. This means that there's no guarantee that the writer will
441 * see the most up-to-date reader info, but that's not required for correct
442 * operation - all we need is to know the upper bound on the oldest reader,
443 * we don't care at all about the newest reader. So the only consequence of
444 * reading stale information here is that old pages might hang around a
445 * while longer before being reclaimed. That's actually good anyway, because
446 * the longer we delay reclaiming old pages, the more likely it is that a
447 * string of contiguous pages can be found after coalescing old pages from
448 * many old transactions together.
451 /** Number of slots in the reader table.
452 * This value was chosen somewhat arbitrarily. 126 readers plus a
453 * couple mutexes fit exactly into 8KB on my development machine.
454 * Applications should set the table size using #mdb_env_set_maxreaders().
456 #define DEFAULT_READERS 126
458 /** The size of a CPU cache line in bytes. We want our lock structures
459 * aligned to this size to avoid false cache line sharing in the
461 * This value works for most CPUs. For Itanium this should be 128.
467 /** The information we store in a single slot of the reader table.
468 * In addition to a transaction ID, we also record the process and
469 * thread ID that owns a slot, so that we can detect stale information,
470 * e.g. threads or processes that went away without cleaning up.
471 * @note We currently don't check for stale records. We simply re-init
472 * the table when we know that we're the only process opening the
475 typedef struct MDB_rxbody {
476 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
477 * Multiple readers that start at the same time will probably have the
478 * same ID here. Again, it's not important to exclude them from
479 * anything; all we need to know is which version of the DB they
480 * started from so we can avoid overwriting any data used in that
481 * particular version.
484 /** The process ID of the process owning this reader txn. */
486 /** The thread ID of the thread owning this txn. */
490 /** The actual reader record, with cacheline padding. */
491 typedef struct MDB_reader {
494 /** shorthand for mrb_txnid */
495 #define mr_txnid mru.mrx.mrb_txnid
496 #define mr_pid mru.mrx.mrb_pid
497 #define mr_tid mru.mrx.mrb_tid
498 /** cache line alignment */
499 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
503 /** The header for the reader table.
504 * The table resides in a memory-mapped file. (This is a different file
505 * than is used for the main database.)
507 * For POSIX the actual mutexes reside in the shared memory of this
508 * mapped file. On Windows, mutexes are named objects allocated by the
509 * kernel; we store the mutex names in this mapped file so that other
510 * processes can grab them. This same approach is also used on
511 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
512 * process-shared POSIX mutexes. For these cases where a named object
513 * is used, the object name is derived from a 64 bit FNV hash of the
514 * environment pathname. As such, naming collisions are extremely
515 * unlikely. If a collision occurs, the results are unpredictable.
517 typedef struct MDB_txbody {
518 /** Stamp identifying this as an MDB file. It must be set
521 /** Version number of this lock file. Must be set to #MDB_LOCK_VERSION. */
522 uint32_t mtb_version;
523 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
524 char mtb_rmname[MNAME_LEN];
526 /** Mutex protecting access to this table.
527 * This is the reader lock that #LOCK_MUTEX_R acquires.
529 pthread_mutex_t mtb_mutex;
531 /** The ID of the last transaction committed to the database.
532 * This is recorded here only for convenience; the value can always
533 * be determined by reading the main database meta pages.
536 /** The number of slots that have been used in the reader table.
537 * This always records the maximum count, it is not decremented
538 * when readers release their slots.
540 unsigned mtb_numreaders;
543 /** The actual reader table definition. */
544 typedef struct MDB_txninfo {
547 #define mti_magic mt1.mtb.mtb_magic
548 #define mti_version mt1.mtb.mtb_version
549 #define mti_mutex mt1.mtb.mtb_mutex
550 #define mti_rmname mt1.mtb.mtb_rmname
551 #define mti_txnid mt1.mtb.mtb_txnid
552 #define mti_numreaders mt1.mtb.mtb_numreaders
553 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
556 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
557 char mt2_wmname[MNAME_LEN];
558 #define mti_wmname mt2.mt2_wmname
560 pthread_mutex_t mt2_wmutex;
561 #define mti_wmutex mt2.mt2_wmutex
563 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
565 MDB_reader mti_readers[1];
569 /** Common header for all page types.
570 * Overflow records occupy a number of contiguous pages with no
571 * headers on any page after the first.
573 typedef struct MDB_page {
574 #define mp_pgno mp_p.p_pgno
575 #define mp_next mp_p.p_next
577 pgno_t p_pgno; /**< page number */
578 void * p_next; /**< for in-memory list of freed structs */
581 /** @defgroup mdb_page Page Flags
583 * Flags for the page headers.
586 #define P_BRANCH 0x01 /**< branch page */
587 #define P_LEAF 0x02 /**< leaf page */
588 #define P_OVERFLOW 0x04 /**< overflow page */
589 #define P_META 0x08 /**< meta page */
590 #define P_DIRTY 0x10 /**< dirty page */
591 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
592 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
593 #define P_KEEP 0x8000 /**< leave this page alone during spill */
595 uint16_t mp_flags; /**< @ref mdb_page */
596 #define mp_lower mp_pb.pb.pb_lower
597 #define mp_upper mp_pb.pb.pb_upper
598 #define mp_pages mp_pb.pb_pages
601 indx_t pb_lower; /**< lower bound of free space */
602 indx_t pb_upper; /**< upper bound of free space */
604 uint32_t pb_pages; /**< number of overflow pages */
606 indx_t mp_ptrs[1]; /**< dynamic size */
609 /** Size of the page header, excluding dynamic data at the end */
610 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
612 /** Address of first usable data byte in a page, after the header */
613 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
615 /** Number of nodes on a page */
616 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
618 /** The amount of space remaining in the page */
619 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
621 /** The percentage of space used in the page, in tenths of a percent. */
622 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
623 ((env)->me_psize - PAGEHDRSZ))
624 /** The minimum page fill factor, in tenths of a percent.
625 * Pages emptier than this are candidates for merging.
627 #define FILL_THRESHOLD 250
629 /** Test if a page is a leaf page */
630 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
631 /** Test if a page is a LEAF2 page */
632 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
633 /** Test if a page is a branch page */
634 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
635 /** Test if a page is an overflow page */
636 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
637 /** Test if a page is a sub page */
638 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
640 /** The number of overflow pages needed to store the given size. */
641 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
643 /** Header for a single key/data pair within a page.
644 * We guarantee 2-byte alignment for nodes.
646 typedef struct MDB_node {
647 /** lo and hi are used for data size on leaf nodes and for
648 * child pgno on branch nodes. On 64 bit platforms, flags
649 * is also used for pgno. (Branch nodes have no flags).
650 * They are in host byte order in case that lets some
651 * accesses be optimized into a 32-bit word access.
653 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
654 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
655 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
656 /** @defgroup mdb_node Node Flags
658 * Flags for node headers.
661 #define F_BIGDATA 0x01 /**< data put on overflow page */
662 #define F_SUBDATA 0x02 /**< data is a sub-database */
663 #define F_DUPDATA 0x04 /**< data has duplicates */
665 /** valid flags for #mdb_node_add() */
666 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
669 unsigned short mn_flags; /**< @ref mdb_node */
670 unsigned short mn_ksize; /**< key size */
671 char mn_data[1]; /**< key and data are appended here */
674 /** Size of the node header, excluding dynamic data at the end */
675 #define NODESIZE offsetof(MDB_node, mn_data)
677 /** Bit position of top word in page number, for shifting mn_flags */
678 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
680 /** Size of a node in a branch page with a given key.
681 * This is just the node header plus the key, there is no data.
683 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
685 /** Size of a node in a leaf page with a given key and data.
686 * This is node header plus key plus data size.
688 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
690 /** Address of node \b i in page \b p */
691 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
693 /** Address of the key for the node */
694 #define NODEKEY(node) (void *)((node)->mn_data)
696 /** Address of the data for a node */
697 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
699 /** Get the page number pointed to by a branch node */
700 #define NODEPGNO(node) \
701 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
702 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
703 /** Set the page number in a branch node */
704 #define SETPGNO(node,pgno) do { \
705 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
706 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
708 /** Get the size of the data in a leaf node */
709 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
710 /** Set the size of the data for a leaf node */
711 #define SETDSZ(node,size) do { \
712 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
713 /** The size of a key in a node */
714 #define NODEKSZ(node) ((node)->mn_ksize)
716 /** Copy a page number from src to dst */
718 #define COPY_PGNO(dst,src) dst = src
720 #if SIZE_MAX > 4294967295UL
721 #define COPY_PGNO(dst,src) do { \
722 unsigned short *s, *d; \
723 s = (unsigned short *)&(src); \
724 d = (unsigned short *)&(dst); \
731 #define COPY_PGNO(dst,src) do { \
732 unsigned short *s, *d; \
733 s = (unsigned short *)&(src); \
734 d = (unsigned short *)&(dst); \
740 /** The address of a key in a LEAF2 page.
741 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
742 * There are no node headers, keys are stored contiguously.
744 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
746 /** Set the \b node's key into \b key, if requested. */
747 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
748 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
750 /** Information about a single database in the environment. */
751 typedef struct MDB_db {
752 uint32_t md_pad; /**< also ksize for LEAF2 pages */
753 uint16_t md_flags; /**< @ref mdb_dbi_open */
754 uint16_t md_depth; /**< depth of this tree */
755 pgno_t md_branch_pages; /**< number of internal pages */
756 pgno_t md_leaf_pages; /**< number of leaf pages */
757 pgno_t md_overflow_pages; /**< number of overflow pages */
758 size_t md_entries; /**< number of data items */
759 pgno_t md_root; /**< the root page of this tree */
762 /** mdb_dbi_open flags */
763 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
764 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
765 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
766 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
768 /** Handle for the DB used to track free pages. */
770 /** Handle for the default DB. */
773 /** Meta page content. */
774 typedef struct MDB_meta {
775 /** Stamp identifying this as an MDB file. It must be set
778 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
780 void *mm_address; /**< address for fixed mapping */
781 size_t mm_mapsize; /**< size of mmap region */
782 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
783 /** The size of pages used in this DB */
784 #define mm_psize mm_dbs[0].md_pad
785 /** Any persistent environment flags. @ref mdb_env */
786 #define mm_flags mm_dbs[0].md_flags
787 pgno_t mm_last_pg; /**< last used page in file */
788 txnid_t mm_txnid; /**< txnid that committed this page */
791 /** Buffer for a stack-allocated dirty page.
792 * The members define size and alignment, and silence type
793 * aliasing warnings. They are not used directly; that could
794 * mean incorrectly using several union members in parallel.
796 typedef union MDB_pagebuf {
797 char mb_raw[MDB_PAGESIZE];
800 char mm_pad[PAGEHDRSZ];
805 /** Auxiliary DB info.
806 * The information here is mostly static/read-only. There is
807 * only a single copy of this record in the environment.
809 typedef struct MDB_dbx {
810 MDB_val md_name; /**< name of the database */
811 MDB_cmp_func *md_cmp; /**< function for comparing keys */
812 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
813 MDB_rel_func *md_rel; /**< user relocate function */
814 void *md_relctx; /**< user-provided context for md_rel */
817 /** A database transaction.
818 * Every operation requires a transaction handle.
821 MDB_txn *mt_parent; /**< parent of a nested txn */
822 MDB_txn *mt_child; /**< nested txn under this txn */
823 pgno_t mt_next_pgno; /**< next unallocated page */
824 /** The ID of this transaction. IDs are integers incrementing from 1.
825 * Only committed write transactions increment the ID. If a transaction
826 * aborts, the ID may be re-used by the next writer.
829 MDB_env *mt_env; /**< the DB environment */
830 /** The list of pages that became unused during this transaction.
833 /** The sorted list of dirty pages we temporarily wrote to disk
834 * because the dirty list was full.
836 MDB_IDL mt_spill_pgs;
838 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
840 /** For read txns: This thread/txn's reader table slot, or NULL. */
843 /** Array of records for each DB known in the environment. */
845 /** Array of MDB_db records for each known DB */
847 /** @defgroup mt_dbflag Transaction DB Flags
851 #define DB_DIRTY 0x01 /**< DB was written in this txn */
852 #define DB_STALE 0x02 /**< DB record is older than txnID */
853 #define DB_NEW 0x04 /**< DB handle opened in this txn */
854 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
856 /** In write txns, array of cursors for each DB */
857 MDB_cursor **mt_cursors;
858 /** Array of flags for each DB */
859 unsigned char *mt_dbflags;
860 /** Number of DB records in use. This number only ever increments;
861 * we don't decrement it when individual DB handles are closed.
865 /** @defgroup mdb_txn Transaction Flags
869 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
870 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
871 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
872 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
874 unsigned int mt_flags; /**< @ref mdb_txn */
875 /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
876 unsigned int mt_dirty_room;
877 /** Tracks which of the two meta pages was used at the start
878 * of this transaction.
880 unsigned int mt_toggle;
883 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
884 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
885 * raise this on a 64 bit machine.
887 #define CURSOR_STACK 32
891 /** Cursors are used for all DB operations */
893 /** Next cursor on this DB in this txn */
895 /** Backup of the original cursor if this cursor is a shadow */
896 MDB_cursor *mc_backup;
897 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
898 struct MDB_xcursor *mc_xcursor;
899 /** The transaction that owns this cursor */
901 /** The database handle this cursor operates on */
903 /** The database record for this cursor */
905 /** The database auxiliary record for this cursor */
907 /** The @ref mt_dbflag for this database */
908 unsigned char *mc_dbflag;
909 unsigned short mc_snum; /**< number of pushed pages */
910 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
911 /** @defgroup mdb_cursor Cursor Flags
913 * Cursor state flags.
916 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
917 #define C_EOF 0x02 /**< No more data */
918 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
919 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
920 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
922 unsigned int mc_flags; /**< @ref mdb_cursor */
923 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
924 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
927 /** Context for sorted-dup records.
928 * We could have gone to a fully recursive design, with arbitrarily
929 * deep nesting of sub-databases. But for now we only handle these
930 * levels - main DB, optional sub-DB, sorted-duplicate DB.
932 typedef struct MDB_xcursor {
933 /** A sub-cursor for traversing the Dup DB */
934 MDB_cursor mx_cursor;
935 /** The database record for this Dup DB */
937 /** The auxiliary DB record for this Dup DB */
939 /** The @ref mt_dbflag for this Dup DB */
940 unsigned char mx_dbflag;
943 /** State of FreeDB old pages, stored in the MDB_env */
944 typedef struct MDB_pgstate {
945 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
946 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
949 /** The database environment. */
951 HANDLE me_fd; /**< The main data file */
952 HANDLE me_lfd; /**< The lock file */
953 HANDLE me_mfd; /**< just for writing the meta pages */
954 /** Failed to update the meta page. Probably an I/O error. */
955 #define MDB_FATAL_ERROR 0x80000000U
956 /** Some fields are initialized. */
957 #define MDB_ENV_ACTIVE 0x20000000U
958 /** me_txkey is set */
959 #define MDB_ENV_TXKEY 0x10000000U
960 /** Have liveness lock in reader table */
961 #define MDB_LIVE_READER 0x08000000U
962 uint32_t me_flags; /**< @ref mdb_env */
963 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
964 unsigned int me_maxreaders; /**< size of the reader table */
965 unsigned int me_numreaders; /**< max numreaders set by this env */
966 MDB_dbi me_numdbs; /**< number of DBs opened */
967 MDB_dbi me_maxdbs; /**< size of the DB table */
968 pid_t me_pid; /**< process ID of this env */
969 char *me_path; /**< path to the DB files */
970 char *me_map; /**< the memory map of the data file */
971 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
972 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
973 MDB_txn *me_txn; /**< current write transaction */
974 size_t me_mapsize; /**< size of the data memory map */
975 off_t me_size; /**< current file size */
976 pgno_t me_maxpg; /**< me_mapsize / me_psize */
977 MDB_dbx *me_dbxs; /**< array of static DB info */
978 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
979 pthread_key_t me_txkey; /**< thread-key for readers */
980 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
981 # define me_pglast me_pgstate.mf_pglast
982 # define me_pghead me_pgstate.mf_pghead
983 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
984 /** IDL of pages that became unused in a write txn */
986 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
987 MDB_ID2L me_dirty_list;
988 /** Max number of freelist items that can fit in a single overflow page */
990 /** Max size of a node on a page */
991 unsigned int me_nodemax;
993 int me_pidquery; /**< Used in OpenProcess */
994 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
996 #elif defined(MDB_USE_POSIX_SEM)
997 sem_t *me_rmutex; /* Shared mutexes are not supported */
1002 /** Nested transaction */
1003 typedef struct MDB_ntxn {
1004 MDB_txn mnt_txn; /* the transaction */
1005 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
1008 /** max number of pages to commit in one writev() call */
1009 #define MDB_COMMIT_PAGES 64
1010 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1011 #undef MDB_COMMIT_PAGES
1012 #define MDB_COMMIT_PAGES IOV_MAX
1015 /* max bytes to write in one call */
1016 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1018 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1019 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1020 static int mdb_page_touch(MDB_cursor *mc);
1022 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1023 static int mdb_page_search_root(MDB_cursor *mc,
1024 MDB_val *key, int modify);
1025 #define MDB_PS_MODIFY 1
1026 #define MDB_PS_ROOTONLY 2
1027 static int mdb_page_search(MDB_cursor *mc,
1028 MDB_val *key, int flags);
1029 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1031 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1032 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1033 pgno_t newpgno, unsigned int nflags);
1035 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1036 static int mdb_env_pick_meta(const MDB_env *env);
1037 static int mdb_env_write_meta(MDB_txn *txn);
1038 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1039 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1041 static void mdb_env_close0(MDB_env *env, int excl);
1043 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1044 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1045 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1046 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1047 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1048 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1049 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1050 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1051 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1053 static int mdb_rebalance(MDB_cursor *mc);
1054 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1056 static void mdb_cursor_pop(MDB_cursor *mc);
1057 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1059 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1060 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1061 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1062 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1063 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1065 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1066 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1068 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1069 static void mdb_xcursor_init0(MDB_cursor *mc);
1070 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1072 static int mdb_drop0(MDB_cursor *mc, int subs);
1073 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1076 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1080 static SECURITY_DESCRIPTOR mdb_null_sd;
1081 static SECURITY_ATTRIBUTES mdb_all_sa;
1082 static int mdb_sec_inited;
1085 /** Return the library version info. */
1087 mdb_version(int *major, int *minor, int *patch)
1089 if (major) *major = MDB_VERSION_MAJOR;
1090 if (minor) *minor = MDB_VERSION_MINOR;
1091 if (patch) *patch = MDB_VERSION_PATCH;
1092 return MDB_VERSION_STRING;
1095 /** Table of descriptions for MDB @ref errors */
1096 static char *const mdb_errstr[] = {
1097 "MDB_KEYEXIST: Key/data pair already exists",
1098 "MDB_NOTFOUND: No matching key/data pair found",
1099 "MDB_PAGE_NOTFOUND: Requested page not found",
1100 "MDB_CORRUPTED: Located page was wrong type",
1101 "MDB_PANIC: Update of meta page failed",
1102 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1103 "MDB_INVALID: File is not an MDB file",
1104 "MDB_MAP_FULL: Environment mapsize limit reached",
1105 "MDB_DBS_FULL: Environment maxdbs limit reached",
1106 "MDB_READERS_FULL: Environment maxreaders limit reached",
1107 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1108 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1109 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1110 "MDB_PAGE_FULL: Internal error - page has no more space",
1111 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1112 "MDB_INCOMPATIBLE: Database flags changed or would change",
1113 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1117 mdb_strerror(int err)
1121 return ("Successful return: 0");
1123 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1124 i = err - MDB_KEYEXIST;
1125 return mdb_errstr[i];
1128 return strerror(err);
1132 /** Display a key in hexadecimal and return the address of the result.
1133 * @param[in] key the key to display
1134 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1135 * @return The key in hexadecimal form.
1138 mdb_dkey(MDB_val *key, char *buf)
1141 unsigned char *c = key->mv_data;
1147 if (key->mv_size > MDB_MAXKEYSIZE)
1148 return "MDB_MAXKEYSIZE";
1149 /* may want to make this a dynamic check: if the key is mostly
1150 * printable characters, print it as-is instead of converting to hex.
1154 for (i=0; i<key->mv_size; i++)
1155 ptr += sprintf(ptr, "%02x", *c++);
1157 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1162 /** Display all the keys in the page. */
1164 mdb_page_list(MDB_page *mp)
1167 unsigned int i, nkeys, nsize;
1171 nkeys = NUMKEYS(mp);
1172 fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
1173 for (i=0; i<nkeys; i++) {
1174 node = NODEPTR(mp, i);
1175 key.mv_size = node->mn_ksize;
1176 key.mv_data = node->mn_data;
1177 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1178 if (IS_BRANCH(mp)) {
1179 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1182 if (F_ISSET(node->mn_flags, F_BIGDATA))
1183 nsize += sizeof(pgno_t);
1185 nsize += NODEDSZ(node);
1186 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1192 mdb_cursor_chk(MDB_cursor *mc)
1198 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1199 for (i=0; i<mc->mc_top; i++) {
1201 node = NODEPTR(mp, mc->mc_ki[i]);
1202 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1205 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1211 /** Count all the pages in each DB and in the freelist
1212 * and make sure it matches the actual number of pages
1215 static void mdb_audit(MDB_txn *txn)
1219 MDB_ID freecount, count;
1224 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1225 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1226 freecount += *(MDB_ID *)data.mv_data;
1229 for (i = 0; i<txn->mt_numdbs; i++) {
1231 mdb_cursor_init(&mc, txn, i, &mx);
1232 if (txn->mt_dbs[i].md_root == P_INVALID)
1234 count += txn->mt_dbs[i].md_branch_pages +
1235 txn->mt_dbs[i].md_leaf_pages +
1236 txn->mt_dbs[i].md_overflow_pages;
1237 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1238 mdb_page_search(&mc, NULL, 0);
1242 mp = mc.mc_pg[mc.mc_top];
1243 for (j=0; j<NUMKEYS(mp); j++) {
1244 MDB_node *leaf = NODEPTR(mp, j);
1245 if (leaf->mn_flags & F_SUBDATA) {
1247 memcpy(&db, NODEDATA(leaf), sizeof(db));
1248 count += db.md_branch_pages + db.md_leaf_pages +
1249 db.md_overflow_pages;
1253 while (mdb_cursor_sibling(&mc, 1) == 0);
1256 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1257 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1258 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1264 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1266 return txn->mt_dbxs[dbi].md_cmp(a, b);
1270 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1272 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1275 /** Allocate memory for a page.
1276 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1279 mdb_page_malloc(MDB_txn *txn, unsigned num)
1281 MDB_env *env = txn->mt_env;
1282 MDB_page *ret = env->me_dpages;
1283 size_t sz = env->me_psize;
1286 VGMEMP_ALLOC(env, ret, sz);
1287 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1288 env->me_dpages = ret->mp_next;
1294 if ((ret = malloc(sz)) != NULL) {
1295 VGMEMP_ALLOC(env, ret, sz);
1300 /** Free a single page.
1301 * Saves single pages to a list, for future reuse.
1302 * (This is not used for multi-page overflow pages.)
1305 mdb_page_free(MDB_env *env, MDB_page *mp)
1307 mp->mp_next = env->me_dpages;
1308 VGMEMP_FREE(env, mp);
1309 env->me_dpages = mp;
1312 /* Free a dirty page */
1314 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1316 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1317 mdb_page_free(env, dp);
1319 /* large pages just get freed directly */
1320 VGMEMP_FREE(env, dp);
1325 /** Return all dirty pages to dpage list */
1327 mdb_dlist_free(MDB_txn *txn)
1329 MDB_env *env = txn->mt_env;
1330 MDB_ID2L dl = txn->mt_u.dirty_list;
1331 unsigned i, n = dl[0].mid;
1333 for (i = 1; i <= n; i++) {
1334 mdb_dpage_free(env, dl[i].mptr);
1339 /* Set or clear P_KEEP in non-overflow, non-sub pages in known cursors.
1340 * When clearing, only consider backup cursors (from parent txns) since
1341 * other P_KEEP flags have already been cleared.
1342 * @param[in] mc A cursor handle for the current operation.
1343 * @param[in] pflags Flags of the pages to update:
1344 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1347 mdb_cursorpages_mark(MDB_cursor *mc, unsigned pflags)
1349 MDB_txn *txn = mc->mc_txn;
1350 MDB_cursor *m2, *m3;
1354 if (mc->mc_flags & C_UNTRACK)
1355 mc = NULL; /* will find mc in mt_cursors */
1356 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1357 for (; mc; mc=mc->mc_next) {
1358 m2 = pflags == P_DIRTY ? mc : mc->mc_backup;
1359 for (; m2; m2 = m2->mc_backup) {
1360 for (m3=m2; m3->mc_flags & C_INITIALIZED; m3=&mx->mx_cursor) {
1361 for (j=0; j<m3->mc_snum; j++)
1362 if ((m3->mc_pg[j]->mp_flags & (P_SUBP|P_DIRTY|P_KEEP))
1364 m3->mc_pg[j]->mp_flags ^= P_KEEP;
1365 if (!(m3->mc_db->md_flags & MDB_DUPSORT))
1367 /* Cursor backups have mx malloced at the end of m2 */
1368 mx = (m3 == mc ? m3->mc_xcursor : (MDB_xcursor *)(m3+1));
1377 static int mdb_page_flush(MDB_txn *txn);
1379 /** Spill pages from the dirty list back to disk.
1380 * This is intended to prevent running into #MDB_TXN_FULL situations,
1381 * but note that they may still occur in a few cases:
1382 * 1) pages in #MDB_DUPSORT sub-DBs are never spilled, so if there
1383 * are too many of these dirtied in one txn, the txn may still get
1385 * 2) child txns may run out of space if their parents dirtied a
1386 * lot of pages and never spilled them. TODO: we probably should do
1387 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1388 * the parent's dirty_room is below a given threshold.
1389 * 3) our estimate of the txn size could be too small. At the
1390 * moment this seems unlikely.
1392 * Otherwise, if not using nested txns, it is expected that apps will
1393 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1394 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1395 * If the txn never references them again, they can be left alone.
1396 * If the txn only reads them, they can be used without any fuss.
1397 * If the txn writes them again, they can be dirtied immediately without
1398 * going thru all of the work of #mdb_page_touch(). Such references are
1399 * handled by #mdb_page_unspill().
1401 * Also note, we never spill DB root pages, nor pages of active cursors,
1402 * because we'll need these back again soon anyway. And in nested txns,
1403 * we can't spill a page in a child txn if it was already spilled in a
1404 * parent txn. That would alter the parent txns' data even though
1405 * the child hasn't committed yet, and we'd have no way to undo it if
1406 * the child aborted.
1408 * @param[in] m0 cursor A cursor handle identifying the transaction and
1409 * database for which we are checking space.
1410 * @param[in] key For a put operation, the key being stored.
1411 * @param[in] data For a put operation, the data being stored.
1412 * @return 0 on success, non-zero on failure.
1415 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1417 MDB_txn *txn = m0->mc_txn;
1419 MDB_ID2L dl = txn->mt_u.dirty_list;
1423 if (m0->mc_flags & C_SUB)
1426 /* Estimate how much space this op will take */
1427 i = m0->mc_db->md_depth;
1428 /* Named DBs also dirty the main DB */
1429 if (m0->mc_dbi > MAIN_DBI)
1430 i += txn->mt_dbs[MAIN_DBI].md_depth;
1431 /* For puts, roughly factor in the key+data size */
1433 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1434 i += i; /* double it for good measure */
1436 if (txn->mt_dirty_room > i)
1439 if (!txn->mt_spill_pgs) {
1440 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1441 if (!txn->mt_spill_pgs)
1445 /* Mark all the dirty root pages we want to preserve */
1446 for (i=0; i<txn->mt_numdbs; i++) {
1447 if (txn->mt_dbflags[i] & DB_DIRTY) {
1448 j = mdb_mid2l_search(dl, txn->mt_dbs[i].md_root);
1449 if (j <= dl[0].mid) {
1451 dp->mp_flags |= P_KEEP;
1456 /* Preserve pages used by cursors */
1457 mdb_cursorpages_mark(m0, P_DIRTY);
1459 /* Save the page IDs of all the pages we're flushing */
1460 for (i=1; i<=dl[0].mid; i++) {
1462 if (dp->mp_flags & P_KEEP)
1464 /* Can't spill twice, make sure it's not already in a parent's
1467 if (txn->mt_parent) {
1469 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1470 if (tx2->mt_spill_pgs) {
1471 j = mdb_midl_search(tx2->mt_spill_pgs, dl[i].mid);
1472 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == dl[i].mid) {
1473 dp->mp_flags |= P_KEEP;
1481 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, dl[i].mid)))
1484 mdb_midl_sort(txn->mt_spill_pgs);
1486 rc = mdb_page_flush(txn);
1488 mdb_cursorpages_mark(m0, P_DIRTY|P_KEEP);
1491 if (txn->mt_parent) {
1493 pgno_t pgno = dl[i].mid;
1494 txn->mt_dirty_room = txn->mt_parent->mt_dirty_room - dl[0].mid;
1495 /* dirty pages that are dirty in an ancestor don't
1496 * count against this txn's dirty_room.
1498 for (i=1; i<=dl[0].mid; i++) {
1499 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1500 j = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1501 if (j <= tx2->mt_u.dirty_list[0].mid &&
1502 tx2->mt_u.dirty_list[j].mid == pgno) {
1503 txn->mt_dirty_room++;
1509 txn->mt_dirty_room = MDB_IDL_UM_MAX - dl[0].mid;
1511 txn->mt_flags |= MDB_TXN_SPILLS;
1516 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1518 mdb_find_oldest(MDB_txn *txn)
1521 txnid_t mr, oldest = txn->mt_txnid - 1;
1522 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1523 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1533 /** Add a page to the txn's dirty list */
1535 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1538 int (*insert)(MDB_ID2L, MDB_ID2 *);
1540 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1541 insert = mdb_mid2l_append;
1543 insert = mdb_mid2l_insert;
1545 mid.mid = mp->mp_pgno;
1547 insert(txn->mt_u.dirty_list, &mid);
1548 txn->mt_dirty_room--;
1551 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1552 * me_pghead and mt_next_pgno.
1554 * If there are free pages available from older transactions, they
1555 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1556 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1557 * and move me_pglast to say which records were consumed. Only this
1558 * function can create me_pghead and move me_pglast/mt_next_pgno.
1559 * @param[in] mc cursor A cursor handle identifying the transaction and
1560 * database for which we are allocating.
1561 * @param[in] num the number of pages to allocate.
1562 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1563 * will always be satisfied by a single contiguous chunk of memory.
1564 * @return 0 on success, non-zero on failure.
1567 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1569 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1570 /* Get at most <Max_retries> more freeDB records once me_pghead
1571 * has enough pages. If not enough, use new pages from the map.
1572 * If <Paranoid> and mc is updating the freeDB, only get new
1573 * records if me_pghead is empty. Then the freelist cannot play
1574 * catch-up with itself by growing while trying to save it.
1576 enum { Paranoid = 1, Max_retries = 500 };
1578 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1580 int rc, n2 = num-1, retry = Max_retries;
1581 MDB_txn *txn = mc->mc_txn;
1582 MDB_env *env = txn->mt_env;
1583 pgno_t pgno, *mop = env->me_pghead;
1584 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1586 txnid_t oldest = 0, last;
1592 /* If our dirty list is already full, we can't do anything */
1593 if (txn->mt_dirty_room == 0)
1594 return MDB_TXN_FULL;
1596 for (op = MDB_FIRST;; op = MDB_NEXT) {
1599 pgno_t *idl, old_id, new_id;
1601 /* Seek a big enough contiguous page range. Prefer
1602 * pages at the tail, just truncating the list.
1604 if (mop_len >= (unsigned)num) {
1608 if (mop[i-n2] == pgno+n2)
1610 } while (--i >= (unsigned)num);
1611 if (Max_retries < INT_MAX && --retry < 0)
1615 if (op == MDB_FIRST) { /* 1st iteration */
1616 /* Prepare to fetch more and coalesce */
1617 oldest = mdb_find_oldest(txn);
1618 last = env->me_pglast;
1619 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1622 key.mv_data = &last; /* will look up last+1 */
1623 key.mv_size = sizeof(last);
1625 if (Paranoid && mc->mc_dbi == FREE_DBI)
1628 if (Paranoid && retry < 0 && mop_len)
1632 /* Do not fetch more if the record will be too recent */
1635 rc = mdb_cursor_get(&m2, &key, NULL, op);
1637 if (rc == MDB_NOTFOUND)
1641 last = *(txnid_t*)key.mv_data;
1644 np = m2.mc_pg[m2.mc_top];
1645 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1646 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1649 idl = (MDB_ID *) data.mv_data;
1652 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1655 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1657 mop = env->me_pghead;
1659 env->me_pglast = last;
1661 DPRINTF("IDL read txn %"Z"u root %"Z"u num %u",
1662 last, txn->mt_dbs[FREE_DBI].md_root, i);
1664 DPRINTF("IDL %"Z"u", idl[k]);
1666 /* Merge in descending sorted order */
1669 mop[0] = (pgno_t)-1;
1673 for (; old_id < new_id; old_id = mop[--j])
1680 /* Use new pages from the map when nothing suitable in the freeDB */
1682 pgno = txn->mt_next_pgno;
1683 if (pgno + num >= env->me_maxpg) {
1684 DPUTS("DB size maxed out");
1685 return MDB_MAP_FULL;
1689 if (env->me_flags & MDB_WRITEMAP) {
1690 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1692 if (!(np = mdb_page_malloc(txn, num)))
1696 mop[0] = mop_len -= num;
1697 /* Move any stragglers down */
1698 for (j = i-num; j < mop_len; )
1699 mop[++j] = mop[++i];
1701 txn->mt_next_pgno = pgno + num;
1704 mdb_page_dirty(txn, np);
1710 /** Copy the used portions of a non-overflow page.
1711 * @param[in] dst page to copy into
1712 * @param[in] src page to copy from
1713 * @param[in] psize size of a page
1716 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1718 enum { Align = sizeof(pgno_t) };
1719 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1721 /* If page isn't full, just copy the used portion. Adjust
1722 * alignment so memcpy may copy words instead of bytes.
1724 if ((unused &= -Align) && !IS_LEAF2(src)) {
1726 memcpy(dst, src, (lower + (Align-1)) & -Align);
1727 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1730 memcpy(dst, src, psize - unused);
1734 /** Pull a page off the txn's spill list, if present.
1735 * If a page being referenced was spilled to disk in this txn, bring
1736 * it back and make it dirty/writable again.
1737 * @param[in] tx0 the transaction handle.
1738 * @param[in] mp the page being referenced.
1739 * @param[out] ret the writable page, if any. ret is unchanged if
1740 * mp wasn't spilled.
1743 mdb_page_unspill(MDB_txn *tx0, MDB_page *mp, MDB_page **ret)
1745 MDB_env *env = tx0->mt_env;
1748 pgno_t pgno = mp->mp_pgno;
1750 for (txn = tx0; txn; txn=txn->mt_parent) {
1751 if (!txn->mt_spill_pgs)
1753 x = mdb_midl_search(txn->mt_spill_pgs, pgno);
1754 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pgno) {
1757 if (IS_OVERFLOW(mp))
1761 if (env->me_flags & MDB_WRITEMAP) {
1764 np = mdb_page_malloc(txn, num);
1768 memcpy(np, mp, num * env->me_psize);
1770 mdb_page_copy(np, mp, env->me_psize);
1773 /* If in current txn, this page is no longer spilled */
1774 for (; x < txn->mt_spill_pgs[0]; x++)
1775 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
1776 txn->mt_spill_pgs[0]--;
1777 } /* otherwise, if belonging to a parent txn, the
1778 * page remains spilled until child commits
1781 if (txn->mt_parent) {
1783 /* If this page is also in a parent's dirty list, then
1784 * it's already accounted in dirty_room, and we need to
1785 * cancel out the decrement that mdb_page_dirty does.
1787 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1788 x = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1789 if (x <= tx2->mt_u.dirty_list[0].mid &&
1790 tx2->mt_u.dirty_list[x].mid == pgno) {
1791 txn->mt_dirty_room++;
1796 mdb_page_dirty(tx0, np);
1797 np->mp_flags |= P_DIRTY;
1805 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1806 * @param[in] mc cursor pointing to the page to be touched
1807 * @return 0 on success, non-zero on failure.
1810 mdb_page_touch(MDB_cursor *mc)
1812 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1813 MDB_txn *txn = mc->mc_txn;
1814 MDB_cursor *m2, *m3;
1819 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1820 if (txn->mt_flags & MDB_TXN_SPILLS) {
1822 rc = mdb_page_unspill(txn, mp, &np);
1828 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1829 (rc = mdb_page_alloc(mc, 1, &np)))
1832 DPRINTF("touched db %u page %"Z"u -> %"Z"u", mc->mc_dbi,mp->mp_pgno,pgno);
1833 assert(mp->mp_pgno != pgno);
1834 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1835 /* Update the parent page, if any, to point to the new page */
1837 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1838 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1839 SETPGNO(node, pgno);
1841 mc->mc_db->md_root = pgno;
1843 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1844 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1846 /* If txn has a parent, make sure the page is in our
1850 unsigned x = mdb_mid2l_search(dl, pgno);
1851 if (x <= dl[0].mid && dl[x].mid == pgno) {
1852 if (mp != dl[x].mptr) { /* bad cursor? */
1853 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1854 return MDB_CORRUPTED;
1859 assert(dl[0].mid < MDB_IDL_UM_MAX);
1861 np = mdb_page_malloc(txn, 1);
1866 mdb_mid2l_insert(dl, &mid);
1871 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1873 np->mp_flags |= P_DIRTY;
1876 /* Adjust cursors pointing to mp */
1877 mc->mc_pg[mc->mc_top] = np;
1879 if (mc->mc_flags & C_SUB) {
1881 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1882 m3 = &m2->mc_xcursor->mx_cursor;
1883 if (m3->mc_snum < mc->mc_snum) continue;
1884 if (m3->mc_pg[mc->mc_top] == mp)
1885 m3->mc_pg[mc->mc_top] = np;
1888 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1889 if (m2->mc_snum < mc->mc_snum) continue;
1890 if (m2->mc_pg[mc->mc_top] == mp) {
1891 m2->mc_pg[mc->mc_top] = np;
1892 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1893 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1895 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1896 if (!(leaf->mn_flags & F_SUBDATA))
1897 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1906 mdb_env_sync(MDB_env *env, int force)
1909 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1910 if (env->me_flags & MDB_WRITEMAP) {
1911 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1912 ? MS_ASYNC : MS_SYNC;
1913 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1916 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1920 if (MDB_FDATASYNC(env->me_fd))
1927 /** Back up parent txn's cursors, then grab the originals for tracking */
1929 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1931 MDB_cursor *mc, *bk;
1936 for (i = src->mt_numdbs; --i >= 0; ) {
1937 if ((mc = src->mt_cursors[i]) != NULL) {
1938 size = sizeof(MDB_cursor);
1940 size += sizeof(MDB_xcursor);
1941 for (; mc; mc = bk->mc_next) {
1947 mc->mc_db = &dst->mt_dbs[i];
1948 /* Kill pointers into src - and dst to reduce abuse: The
1949 * user may not use mc until dst ends. Otherwise we'd...
1951 mc->mc_txn = NULL; /* ...set this to dst */
1952 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
1953 if ((mx = mc->mc_xcursor) != NULL) {
1954 *(MDB_xcursor *)(bk+1) = *mx;
1955 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
1957 mc->mc_next = dst->mt_cursors[i];
1958 dst->mt_cursors[i] = mc;
1965 /** Close this write txn's cursors, give parent txn's cursors back to parent.
1966 * @param[in] txn the transaction handle.
1967 * @param[in] merge true to keep changes to parent cursors, false to revert.
1968 * @return 0 on success, non-zero on failure.
1971 mdb_cursors_close(MDB_txn *txn, unsigned merge)
1973 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
1977 for (i = txn->mt_numdbs; --i >= 0; ) {
1978 for (mc = cursors[i]; mc; mc = next) {
1980 if ((bk = mc->mc_backup) != NULL) {
1982 /* Commit changes to parent txn */
1983 mc->mc_next = bk->mc_next;
1984 mc->mc_backup = bk->mc_backup;
1985 mc->mc_txn = bk->mc_txn;
1986 mc->mc_db = bk->mc_db;
1987 mc->mc_dbflag = bk->mc_dbflag;
1988 if ((mx = mc->mc_xcursor) != NULL)
1989 mx->mx_cursor.mc_txn = bk->mc_txn;
1991 /* Abort nested txn */
1993 if ((mx = mc->mc_xcursor) != NULL)
1994 *mx = *(MDB_xcursor *)(bk+1);
1998 /* Only malloced cursors are permanently tracked. */
2005 #ifdef MDB_DEBUG_SKIP
2006 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2009 mdb_txn_reset0(MDB_txn *txn, const char *act);
2017 Pidset = F_SETLK, Pidcheck = F_GETLK
2021 /** Set or check a pid lock. Set returns 0 on success.
2022 * Check returns 0 if lock exists (meaning the process is alive).
2024 * On Windows Pidset is a no-op, we merely check for the existence
2025 * of the process with the given pid. On POSIX we use a single byte
2026 * lock on the lockfile, set at an offset equal to the pid.
2029 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
2038 h = OpenProcess(env->me_pidquery, FALSE, pid);
2040 return GetLastError();
2047 struct flock lock_info;
2048 memset((void *)&lock_info, 0, sizeof(lock_info));
2049 lock_info.l_type = F_WRLCK;
2050 lock_info.l_whence = SEEK_SET;
2051 lock_info.l_start = pid;
2052 lock_info.l_len = 1;
2053 while ((rc = fcntl(env->me_lfd, op, &lock_info)) &&
2054 (rc = ErrCode()) == EINTR) ;
2055 if (op == F_GETLK && rc == 0 && lock_info.l_type == F_UNLCK)
2061 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2062 * @param[in] txn the transaction handle to initialize
2063 * @return 0 on success, non-zero on failure.
2066 mdb_txn_renew0(MDB_txn *txn)
2068 MDB_env *env = txn->mt_env;
2071 int rc, new_notls = 0;
2074 txn->mt_numdbs = env->me_numdbs;
2075 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2077 if (txn->mt_flags & MDB_TXN_RDONLY) {
2078 if (!env->me_txns) {
2079 i = mdb_env_pick_meta(env);
2080 txn->mt_txnid = env->me_metas[i]->mm_txnid;
2081 txn->mt_u.reader = NULL;
2083 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2084 pthread_getspecific(env->me_txkey);
2086 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2087 return MDB_BAD_RSLOT;
2089 pid_t pid = env->me_pid;
2090 pthread_t tid = pthread_self();
2092 if (!(env->me_flags & MDB_LIVE_READER)) {
2093 rc = mdb_reader_pid(env, Pidset, pid);
2095 UNLOCK_MUTEX_R(env);
2098 env->me_flags |= MDB_LIVE_READER;
2102 for (i=0; i<env->me_txns->mti_numreaders; i++)
2103 if (env->me_txns->mti_readers[i].mr_pid == 0)
2105 if (i == env->me_maxreaders) {
2106 UNLOCK_MUTEX_R(env);
2107 return MDB_READERS_FULL;
2109 env->me_txns->mti_readers[i].mr_pid = pid;
2110 env->me_txns->mti_readers[i].mr_tid = tid;
2111 if (i >= env->me_txns->mti_numreaders)
2112 env->me_txns->mti_numreaders = i+1;
2113 /* Save numreaders for un-mutexed mdb_env_close() */
2114 env->me_numreaders = env->me_txns->mti_numreaders;
2115 UNLOCK_MUTEX_R(env);
2116 r = &env->me_txns->mti_readers[i];
2117 new_notls = (env->me_flags & MDB_NOTLS);
2118 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2123 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
2124 txn->mt_u.reader = r;
2126 txn->mt_toggle = txn->mt_txnid & 1;
2130 txn->mt_txnid = env->me_txns->mti_txnid;
2131 txn->mt_toggle = txn->mt_txnid & 1;
2134 if (txn->mt_txnid == mdb_debug_start)
2137 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2138 txn->mt_u.dirty_list = env->me_dirty_list;
2139 txn->mt_u.dirty_list[0].mid = 0;
2140 txn->mt_free_pgs = env->me_free_pgs;
2141 txn->mt_free_pgs[0] = 0;
2142 txn->mt_spill_pgs = NULL;
2146 /* Copy the DB info and flags */
2147 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
2149 /* Moved to here to avoid a data race in read TXNs */
2150 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
2152 for (i=2; i<txn->mt_numdbs; i++) {
2153 x = env->me_dbflags[i];
2154 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2155 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2157 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2159 if (env->me_maxpg < txn->mt_next_pgno) {
2160 mdb_txn_reset0(txn, "renew0-mapfail");
2162 txn->mt_u.reader->mr_pid = 0;
2163 txn->mt_u.reader = NULL;
2165 return MDB_MAP_RESIZED;
2172 mdb_txn_renew(MDB_txn *txn)
2176 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2179 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2180 DPUTS("environment had fatal error, must shutdown!");
2184 rc = mdb_txn_renew0(txn);
2185 if (rc == MDB_SUCCESS) {
2186 DPRINTF("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2187 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2188 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2194 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2198 int rc, size, tsize = sizeof(MDB_txn);
2200 if (env->me_flags & MDB_FATAL_ERROR) {
2201 DPUTS("environment had fatal error, must shutdown!");
2204 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2207 /* Nested transactions: Max 1 child, write txns only, no writemap */
2208 if (parent->mt_child ||
2209 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
2210 (env->me_flags & MDB_WRITEMAP))
2214 tsize = sizeof(MDB_ntxn);
2216 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2217 if (!(flags & MDB_RDONLY))
2218 size += env->me_maxdbs * sizeof(MDB_cursor *);
2220 if ((txn = calloc(1, size)) == NULL) {
2221 DPRINTF("calloc: %s", strerror(ErrCode()));
2224 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2225 if (flags & MDB_RDONLY) {
2226 txn->mt_flags |= MDB_TXN_RDONLY;
2227 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2229 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2230 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2236 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2237 if (!txn->mt_u.dirty_list ||
2238 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2240 free(txn->mt_u.dirty_list);
2244 txn->mt_txnid = parent->mt_txnid;
2245 txn->mt_toggle = parent->mt_toggle;
2246 txn->mt_dirty_room = parent->mt_dirty_room;
2247 txn->mt_u.dirty_list[0].mid = 0;
2248 txn->mt_spill_pgs = NULL;
2249 txn->mt_next_pgno = parent->mt_next_pgno;
2250 parent->mt_child = txn;
2251 txn->mt_parent = parent;
2252 txn->mt_numdbs = parent->mt_numdbs;
2253 txn->mt_flags = parent->mt_flags;
2254 txn->mt_dbxs = parent->mt_dbxs;
2255 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2256 /* Copy parent's mt_dbflags, but clear DB_NEW */
2257 for (i=0; i<txn->mt_numdbs; i++)
2258 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2260 ntxn = (MDB_ntxn *)txn;
2261 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2262 if (env->me_pghead) {
2263 size = MDB_IDL_SIZEOF(env->me_pghead);
2264 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2266 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2271 rc = mdb_cursor_shadow(parent, txn);
2273 mdb_txn_reset0(txn, "beginchild-fail");
2275 rc = mdb_txn_renew0(txn);
2281 DPRINTF("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2282 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2283 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
2289 /** Export or close DBI handles opened in this txn. */
2291 mdb_dbis_update(MDB_txn *txn, int keep)
2294 MDB_dbi n = txn->mt_numdbs;
2295 MDB_env *env = txn->mt_env;
2296 unsigned char *tdbflags = txn->mt_dbflags;
2298 for (i = n; --i >= 2;) {
2299 if (tdbflags[i] & DB_NEW) {
2301 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2303 char *ptr = env->me_dbxs[i].md_name.mv_data;
2304 env->me_dbxs[i].md_name.mv_data = NULL;
2305 env->me_dbxs[i].md_name.mv_size = 0;
2306 env->me_dbflags[i] = 0;
2311 if (keep && env->me_numdbs < n)
2315 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2316 * May be called twice for readonly txns: First reset it, then abort.
2317 * @param[in] txn the transaction handle to reset
2318 * @param[in] act why the transaction is being reset
2321 mdb_txn_reset0(MDB_txn *txn, const char *act)
2323 MDB_env *env = txn->mt_env;
2325 /* Close any DBI handles opened in this txn */
2326 mdb_dbis_update(txn, 0);
2328 DPRINTF("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2329 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2330 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2332 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2333 if (txn->mt_u.reader) {
2334 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2335 if (!(env->me_flags & MDB_NOTLS))
2336 txn->mt_u.reader = NULL; /* txn does not own reader */
2338 txn->mt_numdbs = 0; /* close nothing if called again */
2339 txn->mt_dbxs = NULL; /* mark txn as reset */
2341 mdb_cursors_close(txn, 0);
2343 if (!(env->me_flags & MDB_WRITEMAP)) {
2344 mdb_dlist_free(txn);
2346 mdb_midl_free(env->me_pghead);
2348 if (txn->mt_parent) {
2349 txn->mt_parent->mt_child = NULL;
2350 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2351 mdb_midl_free(txn->mt_free_pgs);
2352 mdb_midl_free(txn->mt_spill_pgs);
2353 free(txn->mt_u.dirty_list);
2357 if (mdb_midl_shrink(&txn->mt_free_pgs))
2358 env->me_free_pgs = txn->mt_free_pgs;
2359 env->me_pghead = NULL;
2363 /* The writer mutex was locked in mdb_txn_begin. */
2364 UNLOCK_MUTEX_W(env);
2369 mdb_txn_reset(MDB_txn *txn)
2374 /* This call is only valid for read-only txns */
2375 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2378 mdb_txn_reset0(txn, "reset");
2382 mdb_txn_abort(MDB_txn *txn)
2388 mdb_txn_abort(txn->mt_child);
2390 mdb_txn_reset0(txn, "abort");
2391 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2392 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2393 txn->mt_u.reader->mr_pid = 0;
2398 /** Save the freelist as of this transaction to the freeDB.
2399 * This changes the freelist. Keep trying until it stabilizes.
2402 mdb_freelist_save(MDB_txn *txn)
2404 /* env->me_pghead[] can grow and shrink during this call.
2405 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2406 * Page numbers cannot disappear from txn->mt_free_pgs[].
2409 MDB_env *env = txn->mt_env;
2410 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2411 txnid_t pglast = 0, head_id = 0;
2412 pgno_t freecnt = 0, *free_pgs, *mop;
2413 ssize_t head_room = 0, total_room = 0, mop_len;
2415 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2417 if (env->me_pghead) {
2418 /* Make sure first page of freeDB is touched and on freelist */
2419 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2420 if (rc && rc != MDB_NOTFOUND)
2425 /* Come back here after each Put() in case freelist changed */
2428 /* If using records from freeDB which we have not yet
2429 * deleted, delete them and any we reserved for me_pghead.
2431 while (pglast < env->me_pglast) {
2432 rc = mdb_cursor_first(&mc, &key, NULL);
2435 pglast = head_id = *(txnid_t *)key.mv_data;
2436 total_room = head_room = 0;
2437 assert(pglast <= env->me_pglast);
2438 rc = mdb_cursor_del(&mc, 0);
2443 /* Save the IDL of pages freed by this txn, to a single record */
2444 if (freecnt < txn->mt_free_pgs[0]) {
2446 /* Make sure last page of freeDB is touched and on freelist */
2447 key.mv_size = MDB_MAXKEYSIZE+1;
2449 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2450 if (rc && rc != MDB_NOTFOUND)
2453 free_pgs = txn->mt_free_pgs;
2454 /* Write to last page of freeDB */
2455 key.mv_size = sizeof(txn->mt_txnid);
2456 key.mv_data = &txn->mt_txnid;
2458 freecnt = free_pgs[0];
2459 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2460 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2463 /* Retry if mt_free_pgs[] grew during the Put() */
2464 free_pgs = txn->mt_free_pgs;
2465 } while (freecnt < free_pgs[0]);
2466 mdb_midl_sort(free_pgs);
2467 memcpy(data.mv_data, free_pgs, data.mv_size);
2470 unsigned int i = free_pgs[0];
2471 DPRINTF("IDL write txn %"Z"u root %"Z"u num %u",
2472 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i);
2474 DPRINTF("IDL %"Z"u", free_pgs[i]);
2480 mop = env->me_pghead;
2481 mop_len = mop ? mop[0] : 0;
2483 /* Reserve records for me_pghead[]. Split it if multi-page,
2484 * to avoid searching freeDB for a page range. Use keys in
2485 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2487 if (total_room >= mop_len) {
2488 if (total_room == mop_len || --more < 0)
2490 } else if (head_room >= maxfree_1pg && head_id > 1) {
2491 /* Keep current record (overflow page), add a new one */
2495 /* (Re)write {key = head_id, IDL length = head_room} */
2496 total_room -= head_room;
2497 head_room = mop_len - total_room;
2498 if (head_room > maxfree_1pg && head_id > 1) {
2499 /* Overflow multi-page for part of me_pghead */
2500 head_room /= head_id; /* amortize page sizes */
2501 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2502 } else if (head_room < 0) {
2503 /* Rare case, not bothering to delete this record */
2506 key.mv_size = sizeof(head_id);
2507 key.mv_data = &head_id;
2508 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2509 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2512 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2513 total_room += head_room;
2516 /* Fill in the reserved, touched me_pghead records */
2522 rc = mdb_cursor_first(&mc, &key, &data);
2523 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2524 unsigned flags = MDB_CURRENT;
2525 txnid_t id = *(txnid_t *)key.mv_data;
2526 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2529 assert(len >= 0 && id <= env->me_pglast);
2531 if (len > mop_len) {
2533 data.mv_size = (len + 1) * sizeof(MDB_ID);
2536 data.mv_data = mop -= len;
2539 rc = mdb_cursor_put(&mc, &key, &data, flags);
2541 if (rc || !(mop_len -= len))
2548 /** Flush dirty pages to the map, after clearing their dirty flag.
2551 mdb_page_flush(MDB_txn *txn)
2553 MDB_env *env = txn->mt_env;
2554 MDB_ID2L dl = txn->mt_u.dirty_list;
2555 unsigned psize = env->me_psize, j;
2556 int i, pagecount = dl[0].mid, rc;
2557 size_t size = 0, pos = 0;
2559 MDB_page *dp = NULL;
2563 struct iovec iov[MDB_COMMIT_PAGES];
2564 ssize_t wpos = 0, wsize = 0, wres;
2565 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2570 if (env->me_flags & MDB_WRITEMAP) {
2571 /* Clear dirty flags */
2572 for (i = pagecount; i; i--) {
2574 /* Don't flush this page yet */
2575 if (dp->mp_flags & P_KEEP) {
2576 dp->mp_flags ^= P_KEEP;
2580 dp->mp_flags &= ~P_DIRTY;
2586 /* Write the pages */
2588 if (i <= pagecount) {
2590 /* Don't flush this page yet */
2591 if (dp->mp_flags & P_KEEP) {
2592 dp->mp_flags ^= P_KEEP;
2597 /* clear dirty flag */
2598 dp->mp_flags &= ~P_DIRTY;
2601 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2606 /* Windows actually supports scatter/gather I/O, but only on
2607 * unbuffered file handles. Since we're relying on the OS page
2608 * cache for all our data, that's self-defeating. So we just
2609 * write pages one at a time. We use the ov structure to set
2610 * the write offset, to at least save the overhead of a Seek
2613 DPRINTF("committing page %"Z"u", pgno);
2614 memset(&ov, 0, sizeof(ov));
2615 ov.Offset = pos & 0xffffffff;
2616 ov.OffsetHigh = pos >> 16 >> 16;
2617 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2619 DPRINTF("WriteFile: %d", rc);
2623 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2624 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2626 /* Write previous page(s) */
2627 #ifdef MDB_USE_PWRITEV
2628 wres = pwritev(env->me_fd, iov, n, wpos);
2631 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2633 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2635 DPRINTF("lseek: %s", strerror(rc));
2638 wres = writev(env->me_fd, iov, n);
2641 if (wres != wsize) {
2644 DPRINTF("Write error: %s", strerror(rc));
2646 rc = EIO; /* TODO: Use which error code? */
2647 DPUTS("short write, filesystem full?");
2658 DPRINTF("committing page %"Z"u", pgno);
2659 next_pos = pos + size;
2660 iov[n].iov_len = size;
2661 iov[n].iov_base = (char *)dp;
2668 for (i=1; i<=pagecount; i++) {
2670 /* This is a page we skipped above */
2673 dl[j].mid = dp->mp_pgno;
2676 mdb_dpage_free(env, dp);
2684 mdb_txn_commit(MDB_txn *txn)
2690 assert(txn != NULL);
2691 assert(txn->mt_env != NULL);
2693 if (txn->mt_child) {
2694 rc = mdb_txn_commit(txn->mt_child);
2695 txn->mt_child = NULL;
2702 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2703 mdb_dbis_update(txn, 1);
2704 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2709 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2710 DPUTS("error flag is set, can't commit");
2712 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2717 if (txn->mt_parent) {
2718 MDB_txn *parent = txn->mt_parent;
2722 /* Append our free list to parent's */
2723 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2726 mdb_midl_free(txn->mt_free_pgs);
2728 parent->mt_next_pgno = txn->mt_next_pgno;
2729 parent->mt_flags = txn->mt_flags;
2731 /* Merge our cursors into parent's and close them */
2732 mdb_cursors_close(txn, 1);
2734 /* Update parent's DB table. */
2735 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2736 parent->mt_numdbs = txn->mt_numdbs;
2737 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2738 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2739 for (i=2; i<txn->mt_numdbs; i++) {
2740 /* preserve parent's DB_NEW status */
2741 x = parent->mt_dbflags[i] & DB_NEW;
2742 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2745 dst = parent->mt_u.dirty_list;
2746 src = txn->mt_u.dirty_list;
2747 /* Remove anything in our dirty list from parent's spill list */
2748 if (parent->mt_spill_pgs) {
2749 x = parent->mt_spill_pgs[0];
2751 /* zero out our dirty pages in parent spill list */
2752 for (i=1; i<=src[0].mid; i++) {
2753 if (src[i].mid < parent->mt_spill_pgs[x])
2755 if (src[i].mid > parent->mt_spill_pgs[x]) {
2761 parent->mt_spill_pgs[x] = 0;
2764 /* OK, we had a few hits, squash zeros from the spill list */
2765 if (len < parent->mt_spill_pgs[0]) {
2767 for (y=1; y<=parent->mt_spill_pgs[0]; y++) {
2768 if (parent->mt_spill_pgs[y]) {
2770 parent->mt_spill_pgs[x] = parent->mt_spill_pgs[y];
2775 parent->mt_spill_pgs[0] = len;
2778 /* Find len = length of merging our dirty list with parent's */
2780 dst[0].mid = 0; /* simplify loops */
2781 if (parent->mt_parent) {
2782 len = x + src[0].mid;
2783 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2784 for (i = x; y && i; y--) {
2785 pgno_t yp = src[y].mid;
2786 while (yp < dst[i].mid)
2788 if (yp == dst[i].mid) {
2793 } else { /* Simplify the above for single-ancestor case */
2794 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2796 /* Merge our dirty list with parent's */
2798 for (i = len; y; dst[i--] = src[y--]) {
2799 pgno_t yp = src[y].mid;
2800 while (yp < dst[x].mid)
2801 dst[i--] = dst[x--];
2802 if (yp == dst[x].mid)
2803 free(dst[x--].mptr);
2807 free(txn->mt_u.dirty_list);
2808 parent->mt_dirty_room = txn->mt_dirty_room;
2809 if (txn->mt_spill_pgs) {
2810 if (parent->mt_spill_pgs) {
2811 mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2812 mdb_midl_free(txn->mt_spill_pgs);
2813 mdb_midl_sort(parent->mt_spill_pgs);
2815 parent->mt_spill_pgs = txn->mt_spill_pgs;
2819 parent->mt_child = NULL;
2820 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2825 if (txn != env->me_txn) {
2826 DPUTS("attempt to commit unknown transaction");
2831 mdb_cursors_close(txn, 0);
2833 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2836 DPRINTF("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2837 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2839 /* Update DB root pointers */
2840 if (txn->mt_numdbs > 2) {
2844 data.mv_size = sizeof(MDB_db);
2846 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2847 for (i = 2; i < txn->mt_numdbs; i++) {
2848 if (txn->mt_dbflags[i] & DB_DIRTY) {
2849 data.mv_data = &txn->mt_dbs[i];
2850 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2857 rc = mdb_freelist_save(txn);
2861 mdb_midl_free(env->me_pghead);
2862 env->me_pghead = NULL;
2863 if (mdb_midl_shrink(&txn->mt_free_pgs))
2864 env->me_free_pgs = txn->mt_free_pgs;
2870 if ((rc = mdb_page_flush(txn)) ||
2871 (rc = mdb_env_sync(env, 0)) ||
2872 (rc = mdb_env_write_meta(txn)))
2878 mdb_dbis_update(txn, 1);
2880 UNLOCK_MUTEX_W(env);
2890 /** Read the environment parameters of a DB environment before
2891 * mapping it into memory.
2892 * @param[in] env the environment handle
2893 * @param[out] meta address of where to store the meta information
2894 * @return 0 on success, non-zero on failure.
2897 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2904 /* We don't know the page size yet, so use a minimum value.
2905 * Read both meta pages so we can use the latest one.
2908 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2912 memset(&ov, 0, sizeof(ov));
2914 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2915 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2918 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2920 if (rc != MDB_PAGESIZE) {
2921 if (rc == 0 && off == 0)
2923 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2924 DPRINTF("read: %s", mdb_strerror(rc));
2928 p = (MDB_page *)&pbuf;
2930 if (!F_ISSET(p->mp_flags, P_META)) {
2931 DPRINTF("page %"Z"u not a meta page", p->mp_pgno);
2936 if (m->mm_magic != MDB_MAGIC) {
2937 DPUTS("meta has invalid magic");
2941 if (m->mm_version != MDB_DATA_VERSION) {
2942 DPRINTF("database is version %u, expected version %u",
2943 m->mm_version, MDB_DATA_VERSION);
2944 return MDB_VERSION_MISMATCH;
2947 if (off == 0 || m->mm_txnid > meta->mm_txnid)
2953 /** Write the environment parameters of a freshly created DB environment.
2954 * @param[in] env the environment handle
2955 * @param[out] meta address of where to store the meta information
2956 * @return 0 on success, non-zero on failure.
2959 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2967 memset(&ov, 0, sizeof(ov));
2968 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
2970 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
2973 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
2974 len = pwrite(fd, ptr, size, pos); \
2975 rc = (len >= 0); } while(0)
2978 DPUTS("writing new meta page");
2980 GET_PAGESIZE(psize);
2982 meta->mm_magic = MDB_MAGIC;
2983 meta->mm_version = MDB_DATA_VERSION;
2984 meta->mm_mapsize = env->me_mapsize;
2985 meta->mm_psize = psize;
2986 meta->mm_last_pg = 1;
2987 meta->mm_flags = env->me_flags & 0xffff;
2988 meta->mm_flags |= MDB_INTEGERKEY;
2989 meta->mm_dbs[0].md_root = P_INVALID;
2990 meta->mm_dbs[1].md_root = P_INVALID;
2992 p = calloc(2, psize);
2994 p->mp_flags = P_META;
2995 *(MDB_meta *)METADATA(p) = *meta;
2997 q = (MDB_page *)((char *)p + psize);
2999 q->mp_flags = P_META;
3000 *(MDB_meta *)METADATA(q) = *meta;
3002 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3005 else if ((unsigned) len == psize * 2)
3013 /** Update the environment info to commit a transaction.
3014 * @param[in] txn the transaction that's being committed
3015 * @return 0 on success, non-zero on failure.
3018 mdb_env_write_meta(MDB_txn *txn)
3021 MDB_meta meta, metab, *mp;
3023 int rc, len, toggle;
3032 assert(txn != NULL);
3033 assert(txn->mt_env != NULL);
3035 toggle = !txn->mt_toggle;
3036 DPRINTF("writing meta page %d for root page %"Z"u",
3037 toggle, txn->mt_dbs[MAIN_DBI].md_root);
3040 mp = env->me_metas[toggle];
3042 if (env->me_flags & MDB_WRITEMAP) {
3043 /* Persist any increases of mapsize config */
3044 if (env->me_mapsize > mp->mm_mapsize)
3045 mp->mm_mapsize = env->me_mapsize;
3046 mp->mm_dbs[0] = txn->mt_dbs[0];
3047 mp->mm_dbs[1] = txn->mt_dbs[1];
3048 mp->mm_last_pg = txn->mt_next_pgno - 1;
3049 mp->mm_txnid = txn->mt_txnid;
3050 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3051 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3054 ptr += env->me_psize;
3055 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
3062 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3063 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3065 ptr = (char *)&meta;
3066 if (env->me_mapsize > mp->mm_mapsize) {
3067 /* Persist any increases of mapsize config */
3068 meta.mm_mapsize = env->me_mapsize;
3069 off = offsetof(MDB_meta, mm_mapsize);
3071 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3073 len = sizeof(MDB_meta) - off;
3076 meta.mm_dbs[0] = txn->mt_dbs[0];
3077 meta.mm_dbs[1] = txn->mt_dbs[1];
3078 meta.mm_last_pg = txn->mt_next_pgno - 1;
3079 meta.mm_txnid = txn->mt_txnid;
3082 off += env->me_psize;
3085 /* Write to the SYNC fd */
3086 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3087 env->me_fd : env->me_mfd;
3090 memset(&ov, 0, sizeof(ov));
3092 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3096 rc = pwrite(mfd, ptr, len, off);
3099 rc = rc < 0 ? ErrCode() : EIO;
3100 DPUTS("write failed, disk error?");
3101 /* On a failure, the pagecache still contains the new data.
3102 * Write some old data back, to prevent it from being used.
3103 * Use the non-SYNC fd; we know it will fail anyway.
3105 meta.mm_last_pg = metab.mm_last_pg;
3106 meta.mm_txnid = metab.mm_txnid;
3108 memset(&ov, 0, sizeof(ov));
3110 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3112 r2 = pwrite(env->me_fd, ptr, len, off);
3115 env->me_flags |= MDB_FATAL_ERROR;
3119 /* Memory ordering issues are irrelevant; since the entire writer
3120 * is wrapped by wmutex, all of these changes will become visible
3121 * after the wmutex is unlocked. Since the DB is multi-version,
3122 * readers will get consistent data regardless of how fresh or
3123 * how stale their view of these values is.
3125 env->me_txns->mti_txnid = txn->mt_txnid;
3130 /** Check both meta pages to see which one is newer.
3131 * @param[in] env the environment handle
3132 * @return meta toggle (0 or 1).
3135 mdb_env_pick_meta(const MDB_env *env)
3137 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3141 mdb_env_create(MDB_env **env)
3145 e = calloc(1, sizeof(MDB_env));
3149 e->me_maxreaders = DEFAULT_READERS;
3150 e->me_maxdbs = e->me_numdbs = 2;
3151 e->me_fd = INVALID_HANDLE_VALUE;
3152 e->me_lfd = INVALID_HANDLE_VALUE;
3153 e->me_mfd = INVALID_HANDLE_VALUE;
3154 #ifdef MDB_USE_POSIX_SEM
3155 e->me_rmutex = SEM_FAILED;
3156 e->me_wmutex = SEM_FAILED;
3158 e->me_pid = getpid();
3159 VGMEMP_CREATE(e,0,0);
3165 mdb_env_set_mapsize(MDB_env *env, size_t size)
3169 env->me_mapsize = size;
3171 env->me_maxpg = env->me_mapsize / env->me_psize;
3176 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3180 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3185 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3187 if (env->me_map || readers < 1)
3189 env->me_maxreaders = readers;
3194 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3196 if (!env || !readers)
3198 *readers = env->me_maxreaders;
3202 /** Further setup required for opening an MDB environment
3205 mdb_env_open2(MDB_env *env)
3207 unsigned int flags = env->me_flags;
3215 memset(&meta, 0, sizeof(meta));
3217 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3220 DPUTS("new mdbenv");
3224 /* Was a mapsize configured? */
3225 if (!env->me_mapsize) {
3226 /* If this is a new environment, take the default,
3227 * else use the size recorded in the existing env.
3229 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3230 } else if (env->me_mapsize < meta.mm_mapsize) {
3231 /* If the configured size is smaller, make sure it's
3232 * still big enough. Silently round up to minimum if not.
3234 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3235 if (env->me_mapsize < minsize)
3236 env->me_mapsize = minsize;
3243 LONG sizelo, sizehi;
3244 sizelo = env->me_mapsize & 0xffffffff;
3245 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3247 /* See if we should use QueryLimited */
3249 if ((rc & 0xff) > 5)
3250 env->me_pidquery = PROCESS_QUERY_LIMITED_INFORMATION;
3252 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3254 /* Windows won't create mappings for zero length files.
3255 * Just allocate the maxsize right now.
3258 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3259 || !SetEndOfFile(env->me_fd)
3260 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3263 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3264 PAGE_READWRITE : PAGE_READONLY,
3265 sizehi, sizelo, NULL);
3268 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3269 FILE_MAP_WRITE : FILE_MAP_READ,
3270 0, 0, env->me_mapsize, meta.mm_address);
3271 rc = env->me_map ? 0 : ErrCode();
3279 if (flags & MDB_WRITEMAP) {
3281 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3284 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
3286 if (env->me_map == MAP_FAILED) {
3290 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3292 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3294 #ifdef POSIX_MADV_RANDOM
3295 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3296 #endif /* POSIX_MADV_RANDOM */
3297 #endif /* MADV_RANDOM */
3301 if (flags & MDB_FIXEDMAP)
3302 meta.mm_address = env->me_map;
3303 i = mdb_env_init_meta(env, &meta);
3304 if (i != MDB_SUCCESS) {
3307 } else if (meta.mm_address && env->me_map != meta.mm_address) {
3308 /* Can happen because the address argument to mmap() is just a
3309 * hint. mmap() can pick another, e.g. if the range is in use.
3310 * The MAP_FIXED flag would prevent that, but then mmap could
3311 * instead unmap existing pages to make room for the new map.
3313 return EBUSY; /* TODO: Make a new MDB_* error code? */
3315 env->me_psize = meta.mm_psize;
3316 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3317 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3319 env->me_maxpg = env->me_mapsize / env->me_psize;
3321 p = (MDB_page *)env->me_map;
3322 env->me_metas[0] = METADATA(p);
3323 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
3327 int toggle = mdb_env_pick_meta(env);
3328 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3330 DPRINTF("opened database version %u, pagesize %u",
3331 env->me_metas[0]->mm_version, env->me_psize);
3332 DPRINTF("using meta page %d", toggle);
3333 DPRINTF("depth: %u", db->md_depth);
3334 DPRINTF("entries: %"Z"u", db->md_entries);
3335 DPRINTF("branch pages: %"Z"u", db->md_branch_pages);
3336 DPRINTF("leaf pages: %"Z"u", db->md_leaf_pages);
3337 DPRINTF("overflow pages: %"Z"u", db->md_overflow_pages);
3338 DPRINTF("root: %"Z"u", db->md_root);
3346 /** Release a reader thread's slot in the reader lock table.
3347 * This function is called automatically when a thread exits.
3348 * @param[in] ptr This points to the slot in the reader lock table.
3351 mdb_env_reader_dest(void *ptr)
3353 MDB_reader *reader = ptr;
3359 /** Junk for arranging thread-specific callbacks on Windows. This is
3360 * necessarily platform and compiler-specific. Windows supports up
3361 * to 1088 keys. Let's assume nobody opens more than 64 environments
3362 * in a single process, for now. They can override this if needed.
3364 #ifndef MAX_TLS_KEYS
3365 #define MAX_TLS_KEYS 64
3367 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3368 static int mdb_tls_nkeys;
3370 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3374 case DLL_PROCESS_ATTACH: break;
3375 case DLL_THREAD_ATTACH: break;
3376 case DLL_THREAD_DETACH:
3377 for (i=0; i<mdb_tls_nkeys; i++) {
3378 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3379 mdb_env_reader_dest(r);
3382 case DLL_PROCESS_DETACH: break;
3387 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3389 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3393 /* Force some symbol references.
3394 * _tls_used forces the linker to create the TLS directory if not already done
3395 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3397 #pragma comment(linker, "/INCLUDE:_tls_used")
3398 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3399 #pragma const_seg(".CRT$XLB")
3400 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3401 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3404 #pragma comment(linker, "/INCLUDE:__tls_used")
3405 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3406 #pragma data_seg(".CRT$XLB")
3407 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3409 #endif /* WIN 32/64 */
3410 #endif /* !__GNUC__ */
3413 /** Downgrade the exclusive lock on the region back to shared */
3415 mdb_env_share_locks(MDB_env *env, int *excl)
3417 int rc = 0, toggle = mdb_env_pick_meta(env);
3419 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3424 /* First acquire a shared lock. The Unlock will
3425 * then release the existing exclusive lock.
3427 memset(&ov, 0, sizeof(ov));
3428 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3431 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3437 struct flock lock_info;
3438 /* The shared lock replaces the existing lock */
3439 memset((void *)&lock_info, 0, sizeof(lock_info));
3440 lock_info.l_type = F_RDLCK;
3441 lock_info.l_whence = SEEK_SET;
3442 lock_info.l_start = 0;
3443 lock_info.l_len = 1;
3444 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3445 (rc = ErrCode()) == EINTR) ;
3446 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3453 /** Try to get exlusive lock, otherwise shared.
3454 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3457 mdb_env_excl_lock(MDB_env *env, int *excl)
3461 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3465 memset(&ov, 0, sizeof(ov));
3466 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3473 struct flock lock_info;
3474 memset((void *)&lock_info, 0, sizeof(lock_info));
3475 lock_info.l_type = F_WRLCK;
3476 lock_info.l_whence = SEEK_SET;
3477 lock_info.l_start = 0;
3478 lock_info.l_len = 1;
3479 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3480 (rc = ErrCode()) == EINTR) ;
3484 # ifdef MDB_USE_POSIX_SEM
3485 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3488 lock_info.l_type = F_RDLCK;
3489 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3490 (rc = ErrCode()) == EINTR) ;
3498 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3500 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3502 * @(#) $Revision: 5.1 $
3503 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3504 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3506 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3510 * Please do not copyright this code. This code is in the public domain.
3512 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3513 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3514 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3515 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3516 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3517 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3518 * PERFORMANCE OF THIS SOFTWARE.
3521 * chongo <Landon Curt Noll> /\oo/\
3522 * http://www.isthe.com/chongo/
3524 * Share and Enjoy! :-)
3527 typedef unsigned long long mdb_hash_t;
3528 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3530 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3531 * @param[in] val value to hash
3532 * @param[in] hval initial value for hash
3533 * @return 64 bit hash
3535 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3536 * hval arg on the first call.
3539 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3541 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3542 unsigned char *end = s + val->mv_size;
3544 * FNV-1a hash each octet of the string
3547 /* xor the bottom with the current octet */
3548 hval ^= (mdb_hash_t)*s++;
3550 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3551 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3552 (hval << 7) + (hval << 8) + (hval << 40);
3554 /* return our new hash value */
3558 /** Hash the string and output the encoded hash.
3559 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3560 * very short name limits. We don't care about the encoding being reversible,
3561 * we just want to preserve as many bits of the input as possible in a
3562 * small printable string.
3563 * @param[in] str string to hash
3564 * @param[out] encbuf an array of 11 chars to hold the hash
3566 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3569 mdb_pack85(unsigned long l, char *out)
3573 for (i=0; i<5; i++) {
3574 *out++ = mdb_a85[l % 85];
3580 mdb_hash_enc(MDB_val *val, char *encbuf)
3582 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3583 unsigned long *l = (unsigned long *)&h;
3585 mdb_pack85(l[0], encbuf);
3586 mdb_pack85(l[1], encbuf+5);
3591 /** Open and/or initialize the lock region for the environment.
3592 * @param[in] env The MDB environment.
3593 * @param[in] lpath The pathname of the file used for the lock region.
3594 * @param[in] mode The Unix permissions for the file, if we create it.
3595 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3596 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3597 * @return 0 on success, non-zero on failure.
3600 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3603 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3605 # define MDB_ERRCODE_ROFS EROFS
3606 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3607 # define MDB_CLOEXEC O_CLOEXEC
3610 # define MDB_CLOEXEC 0
3617 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3618 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3619 FILE_ATTRIBUTE_NORMAL, NULL);
3621 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3623 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3625 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3630 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3631 /* Lose record locks when exec*() */
3632 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3633 fcntl(env->me_lfd, F_SETFD, fdflags);
3636 if (!(env->me_flags & MDB_NOTLS)) {
3637 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3640 env->me_flags |= MDB_ENV_TXKEY;
3642 /* Windows TLS callbacks need help finding their TLS info. */
3643 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3647 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3651 /* Try to get exclusive lock. If we succeed, then
3652 * nobody is using the lock region and we should initialize it.
3654 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3657 size = GetFileSize(env->me_lfd, NULL);
3659 size = lseek(env->me_lfd, 0, SEEK_END);
3660 if (size == -1) goto fail_errno;
3662 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3663 if (size < rsize && *excl > 0) {
3665 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3666 || !SetEndOfFile(env->me_lfd))
3669 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3673 size = rsize - sizeof(MDB_txninfo);
3674 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3679 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3681 if (!mh) goto fail_errno;
3682 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3684 if (!env->me_txns) goto fail_errno;
3686 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3688 if (m == MAP_FAILED) goto fail_errno;
3694 BY_HANDLE_FILE_INFORMATION stbuf;
3703 if (!mdb_sec_inited) {
3704 InitializeSecurityDescriptor(&mdb_null_sd,
3705 SECURITY_DESCRIPTOR_REVISION);
3706 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3707 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3708 mdb_all_sa.bInheritHandle = FALSE;
3709 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3712 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3713 idbuf.volume = stbuf.dwVolumeSerialNumber;
3714 idbuf.nhigh = stbuf.nFileIndexHigh;
3715 idbuf.nlow = stbuf.nFileIndexLow;
3716 val.mv_data = &idbuf;
3717 val.mv_size = sizeof(idbuf);
3718 mdb_hash_enc(&val, encbuf);
3719 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3720 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3721 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3722 if (!env->me_rmutex) goto fail_errno;
3723 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3724 if (!env->me_wmutex) goto fail_errno;
3725 #elif defined(MDB_USE_POSIX_SEM)
3734 #if defined(__NetBSD__)
3735 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3737 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3738 idbuf.dev = stbuf.st_dev;
3739 idbuf.ino = stbuf.st_ino;
3740 val.mv_data = &idbuf;
3741 val.mv_size = sizeof(idbuf);
3742 mdb_hash_enc(&val, encbuf);
3743 #ifdef MDB_SHORT_SEMNAMES
3744 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3746 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3747 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3748 /* Clean up after a previous run, if needed: Try to
3749 * remove both semaphores before doing anything else.
3751 sem_unlink(env->me_txns->mti_rmname);
3752 sem_unlink(env->me_txns->mti_wmname);
3753 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3754 O_CREAT|O_EXCL, mode, 1);
3755 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3756 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3757 O_CREAT|O_EXCL, mode, 1);
3758 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3759 #else /* MDB_USE_POSIX_SEM */
3760 pthread_mutexattr_t mattr;
3762 if ((rc = pthread_mutexattr_init(&mattr))
3763 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3764 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3765 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3767 pthread_mutexattr_destroy(&mattr);
3768 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3770 env->me_txns->mti_version = MDB_LOCK_VERSION;
3771 env->me_txns->mti_magic = MDB_MAGIC;
3772 env->me_txns->mti_txnid = 0;
3773 env->me_txns->mti_numreaders = 0;
3776 if (env->me_txns->mti_magic != MDB_MAGIC) {
3777 DPUTS("lock region has invalid magic");
3781 if (env->me_txns->mti_version != MDB_LOCK_VERSION) {
3782 DPRINTF("lock region is version %u, expected version %u",
3783 env->me_txns->mti_version, MDB_LOCK_VERSION);
3784 rc = MDB_VERSION_MISMATCH;
3788 if (rc && rc != EACCES && rc != EAGAIN) {
3792 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3793 if (!env->me_rmutex) goto fail_errno;
3794 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3795 if (!env->me_wmutex) goto fail_errno;
3796 #elif defined(MDB_USE_POSIX_SEM)
3797 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3798 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3799 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3800 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3811 /** The name of the lock file in the DB environment */
3812 #define LOCKNAME "/lock.mdb"
3813 /** The name of the data file in the DB environment */
3814 #define DATANAME "/data.mdb"
3815 /** The suffix of the lock file when no subdir is used */
3816 #define LOCKSUFF "-lock"
3817 /** Only a subset of the @ref mdb_env flags can be changed
3818 * at runtime. Changing other flags requires closing the
3819 * environment and re-opening it with the new flags.
3821 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3822 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3825 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3827 int oflags, rc, len, excl = -1;
3828 char *lpath, *dpath;
3830 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3834 if (flags & MDB_NOSUBDIR) {
3835 rc = len + sizeof(LOCKSUFF) + len + 1;
3837 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3842 if (flags & MDB_NOSUBDIR) {
3843 dpath = lpath + len + sizeof(LOCKSUFF);
3844 sprintf(lpath, "%s" LOCKSUFF, path);
3845 strcpy(dpath, path);
3847 dpath = lpath + len + sizeof(LOCKNAME);
3848 sprintf(lpath, "%s" LOCKNAME, path);
3849 sprintf(dpath, "%s" DATANAME, path);
3853 flags |= env->me_flags;
3854 if (flags & MDB_RDONLY) {
3855 /* silently ignore WRITEMAP when we're only getting read access */
3856 flags &= ~MDB_WRITEMAP;
3858 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3859 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3862 env->me_flags = flags |= MDB_ENV_ACTIVE;
3866 env->me_path = strdup(path);
3867 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3868 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3869 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3874 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3879 if (F_ISSET(flags, MDB_RDONLY)) {
3880 oflags = GENERIC_READ;
3881 len = OPEN_EXISTING;
3883 oflags = GENERIC_READ|GENERIC_WRITE;
3886 mode = FILE_ATTRIBUTE_NORMAL;
3887 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3888 NULL, len, mode, NULL);
3890 if (F_ISSET(flags, MDB_RDONLY))
3893 oflags = O_RDWR | O_CREAT;
3895 env->me_fd = open(dpath, oflags, mode);
3897 if (env->me_fd == INVALID_HANDLE_VALUE) {
3902 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3903 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3904 env->me_mfd = env->me_fd;
3906 /* Synchronous fd for meta writes. Needed even with
3907 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3910 env->me_mfd = CreateFile(dpath, oflags,
3911 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3912 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3914 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3916 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3921 DPRINTF("opened dbenv %p", (void *) env);
3923 rc = mdb_env_share_locks(env, &excl);
3929 mdb_env_close0(env, excl);
3935 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
3937 mdb_env_close0(MDB_env *env, int excl)
3941 if (!(env->me_flags & MDB_ENV_ACTIVE))
3944 /* Doing this here since me_dbxs may not exist during mdb_env_close */
3945 for (i = env->me_maxdbs; --i > MAIN_DBI; )
3946 free(env->me_dbxs[i].md_name.mv_data);
3948 free(env->me_dbflags);
3951 free(env->me_dirty_list);
3952 mdb_midl_free(env->me_free_pgs);
3954 if (env->me_flags & MDB_ENV_TXKEY) {
3955 pthread_key_delete(env->me_txkey);
3957 /* Delete our key from the global list */
3958 for (i=0; i<mdb_tls_nkeys; i++)
3959 if (mdb_tls_keys[i] == env->me_txkey) {
3960 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3968 munmap(env->me_map, env->me_mapsize);
3970 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3971 (void) close(env->me_mfd);
3972 if (env->me_fd != INVALID_HANDLE_VALUE)
3973 (void) close(env->me_fd);
3975 pid_t pid = env->me_pid;
3976 /* Clearing readers is done in this function because
3977 * me_txkey with its destructor must be disabled first.
3979 for (i = env->me_numreaders; --i >= 0; )
3980 if (env->me_txns->mti_readers[i].mr_pid == pid)
3981 env->me_txns->mti_readers[i].mr_pid = 0;
3983 if (env->me_rmutex) {
3984 CloseHandle(env->me_rmutex);
3985 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3987 /* Windows automatically destroys the mutexes when
3988 * the last handle closes.
3990 #elif defined(MDB_USE_POSIX_SEM)
3991 if (env->me_rmutex != SEM_FAILED) {
3992 sem_close(env->me_rmutex);
3993 if (env->me_wmutex != SEM_FAILED)
3994 sem_close(env->me_wmutex);
3995 /* If we have the filelock: If we are the
3996 * only remaining user, clean up semaphores.
3999 mdb_env_excl_lock(env, &excl);
4001 sem_unlink(env->me_txns->mti_rmname);
4002 sem_unlink(env->me_txns->mti_wmname);
4006 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4008 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4011 /* Unlock the lockfile. Windows would have unlocked it
4012 * after closing anyway, but not necessarily at once.
4014 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4017 (void) close(env->me_lfd);
4020 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4024 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4026 MDB_txn *txn = NULL;
4032 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4036 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4039 /* Do the lock/unlock of the reader mutex before starting the
4040 * write txn. Otherwise other read txns could block writers.
4042 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4047 /* We must start the actual read txn after blocking writers */
4048 mdb_txn_reset0(txn, "reset-stage1");
4050 /* Temporarily block writers until we snapshot the meta pages */
4053 rc = mdb_txn_renew0(txn);
4055 UNLOCK_MUTEX_W(env);
4060 wsize = env->me_psize * 2;
4064 DO_WRITE(rc, fd, ptr, w2, len);
4068 } else if (len > 0) {
4074 /* Non-blocking or async handles are not supported */
4080 UNLOCK_MUTEX_W(env);
4085 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4087 if (wsize > MAX_WRITE)
4091 DO_WRITE(rc, fd, ptr, w2, len);
4095 } else if (len > 0) {
4112 mdb_env_copy(MDB_env *env, const char *path)
4116 HANDLE newfd = INVALID_HANDLE_VALUE;
4118 if (env->me_flags & MDB_NOSUBDIR) {
4119 lpath = (char *)path;
4122 len += sizeof(DATANAME);
4123 lpath = malloc(len);
4126 sprintf(lpath, "%s" DATANAME, path);
4129 /* The destination path must exist, but the destination file must not.
4130 * We don't want the OS to cache the writes, since the source data is
4131 * already in the OS cache.
4134 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4135 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4137 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
4143 if (newfd == INVALID_HANDLE_VALUE) {
4148 #ifdef F_NOCACHE /* __APPLE__ */
4149 rc = fcntl(newfd, F_NOCACHE, 1);
4156 rc = mdb_env_copyfd(env, newfd);
4159 if (!(env->me_flags & MDB_NOSUBDIR))
4161 if (newfd != INVALID_HANDLE_VALUE)
4162 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4169 mdb_env_close(MDB_env *env)
4176 VGMEMP_DESTROY(env);
4177 while ((dp = env->me_dpages) != NULL) {
4178 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4179 env->me_dpages = dp->mp_next;
4183 mdb_env_close0(env, 0);
4187 /** Compare two items pointing at aligned size_t's */
4189 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4191 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4192 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4195 /** Compare two items pointing at aligned int's */
4197 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4199 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4200 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4203 /** Compare two items pointing at ints of unknown alignment.
4204 * Nodes and keys are guaranteed to be 2-byte aligned.
4207 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4209 #if BYTE_ORDER == LITTLE_ENDIAN
4210 unsigned short *u, *c;
4213 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4214 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4217 } while(!x && u > (unsigned short *)a->mv_data);
4220 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4224 /** Compare two items lexically */
4226 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4233 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4239 diff = memcmp(a->mv_data, b->mv_data, len);
4240 return diff ? diff : len_diff<0 ? -1 : len_diff;
4243 /** Compare two items in reverse byte order */
4245 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4247 const unsigned char *p1, *p2, *p1_lim;
4251 p1_lim = (const unsigned char *)a->mv_data;
4252 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4253 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4255 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4261 while (p1 > p1_lim) {
4262 diff = *--p1 - *--p2;
4266 return len_diff<0 ? -1 : len_diff;
4269 /** Search for key within a page, using binary search.
4270 * Returns the smallest entry larger or equal to the key.
4271 * If exactp is non-null, stores whether the found entry was an exact match
4272 * in *exactp (1 or 0).
4273 * Updates the cursor index with the index of the found entry.
4274 * If no entry larger or equal to the key is found, returns NULL.
4277 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4279 unsigned int i = 0, nkeys;
4282 MDB_page *mp = mc->mc_pg[mc->mc_top];
4283 MDB_node *node = NULL;
4288 nkeys = NUMKEYS(mp);
4293 COPY_PGNO(pgno, mp->mp_pgno);
4294 DPRINTF("searching %u keys in %s %spage %"Z"u",
4295 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4302 low = IS_LEAF(mp) ? 0 : 1;
4304 cmp = mc->mc_dbx->md_cmp;
4306 /* Branch pages have no data, so if using integer keys,
4307 * alignment is guaranteed. Use faster mdb_cmp_int.
4309 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4310 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4317 nodekey.mv_size = mc->mc_db->md_pad;
4318 node = NODEPTR(mp, 0); /* fake */
4319 while (low <= high) {
4320 i = (low + high) >> 1;
4321 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4322 rc = cmp(key, &nodekey);
4323 DPRINTF("found leaf index %u [%s], rc = %i",
4324 i, DKEY(&nodekey), rc);
4333 while (low <= high) {
4334 i = (low + high) >> 1;
4336 node = NODEPTR(mp, i);
4337 nodekey.mv_size = NODEKSZ(node);
4338 nodekey.mv_data = NODEKEY(node);
4340 rc = cmp(key, &nodekey);
4343 DPRINTF("found leaf index %u [%s], rc = %i",
4344 i, DKEY(&nodekey), rc);
4346 DPRINTF("found branch index %u [%s -> %"Z"u], rc = %i",
4347 i, DKEY(&nodekey), NODEPGNO(node), rc);
4358 if (rc > 0) { /* Found entry is less than the key. */
4359 i++; /* Skip to get the smallest entry larger than key. */
4361 node = NODEPTR(mp, i);
4364 *exactp = (rc == 0);
4365 /* store the key index */
4366 mc->mc_ki[mc->mc_top] = i;
4368 /* There is no entry larger or equal to the key. */
4371 /* nodeptr is fake for LEAF2 */
4377 mdb_cursor_adjust(MDB_cursor *mc, func)
4381 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4382 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4389 /** Pop a page off the top of the cursor's stack. */
4391 mdb_cursor_pop(MDB_cursor *mc)
4394 #ifndef MDB_DEBUG_SKIP
4395 MDB_page *top = mc->mc_pg[mc->mc_top];
4401 DPRINTF("popped page %"Z"u off db %u cursor %p", top->mp_pgno,
4402 mc->mc_dbi, (void *) mc);
4406 /** Push a page onto the top of the cursor's stack. */
4408 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4410 DPRINTF("pushing page %"Z"u on db %u cursor %p", mp->mp_pgno,
4411 mc->mc_dbi, (void *) mc);
4413 if (mc->mc_snum >= CURSOR_STACK) {
4414 assert(mc->mc_snum < CURSOR_STACK);
4415 return MDB_CURSOR_FULL;
4418 mc->mc_top = mc->mc_snum++;
4419 mc->mc_pg[mc->mc_top] = mp;
4420 mc->mc_ki[mc->mc_top] = 0;
4425 /** Find the address of the page corresponding to a given page number.
4426 * @param[in] txn the transaction for this access.
4427 * @param[in] pgno the page number for the page to retrieve.
4428 * @param[out] ret address of a pointer where the page's address will be stored.
4429 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4430 * @return 0 on success, non-zero on failure.
4433 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4438 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
4439 (txn->mt_env->me_flags & MDB_WRITEMAP)))
4444 MDB_ID2L dl = tx2->mt_u.dirty_list;
4446 /* Spilled pages were dirtied in this txn and flushed
4447 * because the dirty list got full. Bring this page
4448 * back in from the map (but don't unspill it here,
4449 * leave that unless page_touch happens again).
4451 if (tx2->mt_spill_pgs) {
4452 x = mdb_midl_search(tx2->mt_spill_pgs, pgno);
4453 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pgno) {
4454 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4459 unsigned x = mdb_mid2l_search(dl, pgno);
4460 if (x <= dl[0].mid && dl[x].mid == pgno) {
4466 } while ((tx2 = tx2->mt_parent) != NULL);
4469 if (pgno < txn->mt_next_pgno) {
4471 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4473 DPRINTF("page %"Z"u not found", pgno);
4475 return MDB_PAGE_NOTFOUND;
4485 /** Search for the page a given key should be in.
4486 * Pushes parent pages on the cursor stack. This function continues a
4487 * search on a cursor that has already been initialized. (Usually by
4488 * #mdb_page_search() but also by #mdb_node_move().)
4489 * @param[in,out] mc the cursor for this operation.
4490 * @param[in] key the key to search for. If NULL, search for the lowest
4491 * page. (This is used by #mdb_cursor_first().)
4492 * @param[in] modify If true, visited pages are updated with new page numbers.
4493 * @return 0 on success, non-zero on failure.
4496 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4498 MDB_page *mp = mc->mc_pg[mc->mc_top];
4503 while (IS_BRANCH(mp)) {
4507 DPRINTF("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp));
4508 assert(NUMKEYS(mp) > 1);
4509 DPRINTF("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0)));
4511 if (key == NULL) /* Initialize cursor to first page. */
4513 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4514 /* cursor to last page */
4518 node = mdb_node_search(mc, key, &exact);
4520 i = NUMKEYS(mp) - 1;
4522 i = mc->mc_ki[mc->mc_top];
4531 DPRINTF("following index %u for key [%s]",
4533 assert(i < NUMKEYS(mp));
4534 node = NODEPTR(mp, i);
4536 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4539 mc->mc_ki[mc->mc_top] = i;
4540 if ((rc = mdb_cursor_push(mc, mp)))
4544 if ((rc = mdb_page_touch(mc)) != 0)
4546 mp = mc->mc_pg[mc->mc_top];
4551 DPRINTF("internal error, index points to a %02X page!?",
4553 return MDB_CORRUPTED;
4556 DPRINTF("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4557 key ? DKEY(key) : NULL);
4558 mc->mc_flags |= C_INITIALIZED;
4559 mc->mc_flags &= ~C_EOF;
4564 /** Search for the lowest key under the current branch page.
4565 * This just bypasses a NUMKEYS check in the current page
4566 * before calling mdb_page_search_root(), because the callers
4567 * are all in situations where the current page is known to
4571 mdb_page_search_lowest(MDB_cursor *mc)
4573 MDB_page *mp = mc->mc_pg[mc->mc_top];
4574 MDB_node *node = NODEPTR(mp, 0);
4577 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4580 mc->mc_ki[mc->mc_top] = 0;
4581 if ((rc = mdb_cursor_push(mc, mp)))
4583 return mdb_page_search_root(mc, NULL, 0);
4586 /** Search for the page a given key should be in.
4587 * Pushes parent pages on the cursor stack. This function just sets up
4588 * the search; it finds the root page for \b mc's database and sets this
4589 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4590 * called to complete the search.
4591 * @param[in,out] mc the cursor for this operation.
4592 * @param[in] key the key to search for. If NULL, search for the lowest
4593 * page. (This is used by #mdb_cursor_first().)
4594 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4595 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4596 * @return 0 on success, non-zero on failure.
4599 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4604 /* Make sure the txn is still viable, then find the root from
4605 * the txn's db table.
4607 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4608 DPUTS("transaction has failed, must abort");
4611 /* Make sure we're using an up-to-date root */
4612 if (mc->mc_dbi > MAIN_DBI) {
4613 if ((*mc->mc_dbflag & DB_STALE) ||
4614 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4616 unsigned char dbflag = 0;
4617 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4618 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4621 if (*mc->mc_dbflag & DB_STALE) {
4625 MDB_node *leaf = mdb_node_search(&mc2,
4626 &mc->mc_dbx->md_name, &exact);
4628 return MDB_NOTFOUND;
4629 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4632 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4634 /* The txn may not know this DBI, or another process may
4635 * have dropped and recreated the DB with other flags.
4637 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4638 return MDB_INCOMPATIBLE;
4639 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4641 if (flags & MDB_PS_MODIFY)
4643 *mc->mc_dbflag &= ~DB_STALE;
4644 *mc->mc_dbflag |= dbflag;
4647 root = mc->mc_db->md_root;
4649 if (root == P_INVALID) { /* Tree is empty. */
4650 DPUTS("tree is empty");
4651 return MDB_NOTFOUND;
4656 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4657 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4663 DPRINTF("db %u root page %"Z"u has flags 0x%X",
4664 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4666 if (flags & MDB_PS_MODIFY) {
4667 if ((rc = mdb_page_touch(mc)))
4671 if (flags & MDB_PS_ROOTONLY)
4674 return mdb_page_search_root(mc, key, flags);
4678 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4680 MDB_txn *txn = mc->mc_txn;
4681 pgno_t pg = mp->mp_pgno;
4682 unsigned i, ovpages = mp->mp_pages;
4683 MDB_env *env = txn->mt_env;
4686 DPRINTF("free ov page %"Z"u (%d)", pg, ovpages);
4687 /* If the page is dirty or on the spill list we just acquired it,
4688 * so we should give it back to our current free list, if any.
4689 * Not currently supported in nested txns.
4690 * Otherwise put it onto the list of pages we freed in this txn.
4692 if (!(mp->mp_flags & P_DIRTY) && txn->mt_spill_pgs) {
4693 unsigned x = mdb_midl_search(txn->mt_spill_pgs, pg);
4694 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pg) {
4695 /* This page is no longer spilled */
4696 for (; x < txn->mt_spill_pgs[0]; x++)
4697 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
4698 txn->mt_spill_pgs[0]--;
4702 if ((mp->mp_flags & P_DIRTY) && !txn->mt_parent && env->me_pghead) {
4705 MDB_ID2 *dl, ix, iy;
4706 rc = mdb_midl_need(&env->me_pghead, ovpages);
4709 /* Remove from dirty list */
4710 dl = txn->mt_u.dirty_list;
4712 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4720 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4721 txn->mt_flags |= MDB_TXN_ERROR;
4722 return MDB_CORRUPTED;
4725 if (!(env->me_flags & MDB_WRITEMAP))
4726 mdb_dpage_free(env, mp);
4728 /* Insert in me_pghead */
4729 mop = env->me_pghead;
4730 j = mop[0] + ovpages;
4731 for (i = mop[0]; i && mop[i] < pg; i--)
4737 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4741 mc->mc_db->md_overflow_pages -= ovpages;
4745 /** Return the data associated with a given node.
4746 * @param[in] txn The transaction for this operation.
4747 * @param[in] leaf The node being read.
4748 * @param[out] data Updated to point to the node's data.
4749 * @return 0 on success, non-zero on failure.
4752 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4754 MDB_page *omp; /* overflow page */
4758 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4759 data->mv_size = NODEDSZ(leaf);
4760 data->mv_data = NODEDATA(leaf);
4764 /* Read overflow data.
4766 data->mv_size = NODEDSZ(leaf);
4767 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4768 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4769 DPRINTF("read overflow page %"Z"u failed", pgno);
4772 data->mv_data = METADATA(omp);
4778 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4779 MDB_val *key, MDB_val *data)
4788 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4790 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4793 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4797 mdb_cursor_init(&mc, txn, dbi, &mx);
4798 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4801 /** Find a sibling for a page.
4802 * Replaces the page at the top of the cursor's stack with the
4803 * specified sibling, if one exists.
4804 * @param[in] mc The cursor for this operation.
4805 * @param[in] move_right Non-zero if the right sibling is requested,
4806 * otherwise the left sibling.
4807 * @return 0 on success, non-zero on failure.
4810 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4816 if (mc->mc_snum < 2) {
4817 return MDB_NOTFOUND; /* root has no siblings */
4821 DPRINTF("parent page is page %"Z"u, index %u",
4822 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4824 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4825 : (mc->mc_ki[mc->mc_top] == 0)) {
4826 DPRINTF("no more keys left, moving to %s sibling",
4827 move_right ? "right" : "left");
4828 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4829 /* undo cursor_pop before returning */
4836 mc->mc_ki[mc->mc_top]++;
4838 mc->mc_ki[mc->mc_top]--;
4839 DPRINTF("just moving to %s index key %u",
4840 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4842 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4844 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4845 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4848 mdb_cursor_push(mc, mp);
4850 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4855 /** Move the cursor to the next data item. */
4857 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4863 if (mc->mc_flags & C_EOF) {
4864 return MDB_NOTFOUND;
4867 assert(mc->mc_flags & C_INITIALIZED);
4869 mp = mc->mc_pg[mc->mc_top];
4871 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4872 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4873 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4874 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4875 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4876 if (op != MDB_NEXT || rc != MDB_NOTFOUND)
4880 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4881 if (op == MDB_NEXT_DUP)
4882 return MDB_NOTFOUND;
4886 DPRINTF("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc);
4888 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4889 DPUTS("=====> move to next sibling page");
4890 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
4891 mc->mc_flags |= C_EOF;
4894 mp = mc->mc_pg[mc->mc_top];
4895 DPRINTF("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4897 mc->mc_ki[mc->mc_top]++;
4899 DPRINTF("==> cursor points to page %"Z"u with %u keys, key index %u",
4900 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4903 key->mv_size = mc->mc_db->md_pad;
4904 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4908 assert(IS_LEAF(mp));
4909 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4911 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4912 mdb_xcursor_init1(mc, leaf);
4915 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4918 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4919 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4920 if (rc != MDB_SUCCESS)
4925 MDB_GET_KEY(leaf, key);
4929 /** Move the cursor to the previous data item. */
4931 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4937 assert(mc->mc_flags & C_INITIALIZED);
4939 mp = mc->mc_pg[mc->mc_top];
4941 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4942 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4943 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4944 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4945 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4946 if (op != MDB_PREV || rc != MDB_NOTFOUND)
4949 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4950 if (op == MDB_PREV_DUP)
4951 return MDB_NOTFOUND;
4956 DPRINTF("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc);
4958 if (mc->mc_ki[mc->mc_top] == 0) {
4959 DPUTS("=====> move to prev sibling page");
4960 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
4963 mp = mc->mc_pg[mc->mc_top];
4964 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4965 DPRINTF("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4967 mc->mc_ki[mc->mc_top]--;
4969 mc->mc_flags &= ~C_EOF;
4971 DPRINTF("==> cursor points to page %"Z"u with %u keys, key index %u",
4972 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4975 key->mv_size = mc->mc_db->md_pad;
4976 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4980 assert(IS_LEAF(mp));
4981 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4983 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4984 mdb_xcursor_init1(mc, leaf);
4987 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4990 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4991 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4992 if (rc != MDB_SUCCESS)
4997 MDB_GET_KEY(leaf, key);
5001 /** Set the cursor on a specific data item. */
5003 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5004 MDB_cursor_op op, int *exactp)
5008 MDB_node *leaf = NULL;
5013 assert(key->mv_size > 0);
5016 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5018 /* See if we're already on the right page */
5019 if (mc->mc_flags & C_INITIALIZED) {
5022 mp = mc->mc_pg[mc->mc_top];
5024 mc->mc_ki[mc->mc_top] = 0;
5025 return MDB_NOTFOUND;
5027 if (mp->mp_flags & P_LEAF2) {
5028 nodekey.mv_size = mc->mc_db->md_pad;
5029 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5031 leaf = NODEPTR(mp, 0);
5032 MDB_GET_KEY(leaf, &nodekey);
5034 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5036 /* Probably happens rarely, but first node on the page
5037 * was the one we wanted.
5039 mc->mc_ki[mc->mc_top] = 0;
5046 unsigned int nkeys = NUMKEYS(mp);
5048 if (mp->mp_flags & P_LEAF2) {
5049 nodekey.mv_data = LEAF2KEY(mp,
5050 nkeys-1, nodekey.mv_size);
5052 leaf = NODEPTR(mp, nkeys-1);
5053 MDB_GET_KEY(leaf, &nodekey);
5055 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5057 /* last node was the one we wanted */
5058 mc->mc_ki[mc->mc_top] = nkeys-1;
5064 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5065 /* This is definitely the right page, skip search_page */
5066 if (mp->mp_flags & P_LEAF2) {
5067 nodekey.mv_data = LEAF2KEY(mp,
5068 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5070 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5071 MDB_GET_KEY(leaf, &nodekey);
5073 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5075 /* current node was the one we wanted */
5085 /* If any parents have right-sibs, search.
5086 * Otherwise, there's nothing further.
5088 for (i=0; i<mc->mc_top; i++)
5090 NUMKEYS(mc->mc_pg[i])-1)
5092 if (i == mc->mc_top) {
5093 /* There are no other pages */
5094 mc->mc_ki[mc->mc_top] = nkeys;
5095 return MDB_NOTFOUND;
5099 /* There are no other pages */
5100 mc->mc_ki[mc->mc_top] = 0;
5101 return MDB_NOTFOUND;
5105 rc = mdb_page_search(mc, key, 0);
5106 if (rc != MDB_SUCCESS)
5109 mp = mc->mc_pg[mc->mc_top];
5110 assert(IS_LEAF(mp));
5113 leaf = mdb_node_search(mc, key, exactp);
5114 if (exactp != NULL && !*exactp) {
5115 /* MDB_SET specified and not an exact match. */
5116 return MDB_NOTFOUND;
5120 DPUTS("===> inexact leaf not found, goto sibling");
5121 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5122 return rc; /* no entries matched */
5123 mp = mc->mc_pg[mc->mc_top];
5124 assert(IS_LEAF(mp));
5125 leaf = NODEPTR(mp, 0);
5129 mc->mc_flags |= C_INITIALIZED;
5130 mc->mc_flags &= ~C_EOF;
5133 key->mv_size = mc->mc_db->md_pad;
5134 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5138 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5139 mdb_xcursor_init1(mc, leaf);
5142 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5143 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5144 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5147 if (op == MDB_GET_BOTH) {
5153 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5154 if (rc != MDB_SUCCESS)
5157 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5159 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5161 rc = mc->mc_dbx->md_dcmp(data, &d2);
5163 if (op == MDB_GET_BOTH || rc > 0)
5164 return MDB_NOTFOUND;
5169 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5170 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5175 /* The key already matches in all other cases */
5176 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5177 MDB_GET_KEY(leaf, key);
5178 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
5183 /** Move the cursor to the first item in the database. */
5185 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5191 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5193 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5194 rc = mdb_page_search(mc, NULL, 0);
5195 if (rc != MDB_SUCCESS)
5198 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5200 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5201 mc->mc_flags |= C_INITIALIZED;
5202 mc->mc_flags &= ~C_EOF;
5204 mc->mc_ki[mc->mc_top] = 0;
5206 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5207 key->mv_size = mc->mc_db->md_pad;
5208 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5213 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5214 mdb_xcursor_init1(mc, leaf);
5215 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5219 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5223 MDB_GET_KEY(leaf, key);
5227 /** Move the cursor to the last item in the database. */
5229 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5235 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5237 if (!(mc->mc_flags & C_EOF)) {
5239 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5242 lkey.mv_size = MDB_MAXKEYSIZE+1;
5243 lkey.mv_data = NULL;
5244 rc = mdb_page_search(mc, &lkey, 0);
5245 if (rc != MDB_SUCCESS)
5248 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5251 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5252 mc->mc_flags |= C_INITIALIZED|C_EOF;
5253 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5255 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5256 key->mv_size = mc->mc_db->md_pad;
5257 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5262 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5263 mdb_xcursor_init1(mc, leaf);
5264 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5268 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5273 MDB_GET_KEY(leaf, key);
5278 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5287 case MDB_GET_CURRENT:
5288 if (!(mc->mc_flags & C_INITIALIZED)) {
5291 MDB_page *mp = mc->mc_pg[mc->mc_top];
5293 mc->mc_ki[mc->mc_top] = 0;
5299 key->mv_size = mc->mc_db->md_pad;
5300 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5302 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5303 MDB_GET_KEY(leaf, key);
5305 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5306 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5308 rc = mdb_node_read(mc->mc_txn, leaf, data);
5315 case MDB_GET_BOTH_RANGE:
5316 if (data == NULL || mc->mc_xcursor == NULL) {
5324 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
5326 } else if (op == MDB_SET_RANGE)
5327 rc = mdb_cursor_set(mc, key, data, op, NULL);
5329 rc = mdb_cursor_set(mc, key, data, op, &exact);
5331 case MDB_GET_MULTIPLE:
5333 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
5334 !(mc->mc_flags & C_INITIALIZED)) {
5339 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5340 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5343 case MDB_NEXT_MULTIPLE:
5345 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5349 if (!(mc->mc_flags & C_INITIALIZED))
5350 rc = mdb_cursor_first(mc, key, data);
5352 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5353 if (rc == MDB_SUCCESS) {
5354 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5357 mx = &mc->mc_xcursor->mx_cursor;
5358 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5360 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5361 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5369 case MDB_NEXT_NODUP:
5370 if (!(mc->mc_flags & C_INITIALIZED))
5371 rc = mdb_cursor_first(mc, key, data);
5373 rc = mdb_cursor_next(mc, key, data, op);
5377 case MDB_PREV_NODUP:
5378 if (!(mc->mc_flags & C_INITIALIZED)) {
5379 rc = mdb_cursor_last(mc, key, data);
5382 mc->mc_flags |= C_INITIALIZED;
5383 mc->mc_ki[mc->mc_top]++;
5385 rc = mdb_cursor_prev(mc, key, data, op);
5388 rc = mdb_cursor_first(mc, key, data);
5392 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5393 !(mc->mc_flags & C_INITIALIZED) ||
5394 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5398 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5401 rc = mdb_cursor_last(mc, key, data);
5405 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5406 !(mc->mc_flags & C_INITIALIZED) ||
5407 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5411 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5414 DPRINTF("unhandled/unimplemented cursor operation %u", op);
5422 /** Touch all the pages in the cursor stack.
5423 * Makes sure all the pages are writable, before attempting a write operation.
5424 * @param[in] mc The cursor to operate on.
5427 mdb_cursor_touch(MDB_cursor *mc)
5431 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5434 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5435 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5438 *mc->mc_dbflag |= DB_DIRTY;
5440 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
5441 rc = mdb_page_touch(mc);
5445 mc->mc_top = mc->mc_snum-1;
5449 /** Do not spill pages to disk if txn is getting full, may fail instead */
5450 #define MDB_NOSPILL 0x8000
5453 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5456 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5457 MDB_node *leaf = NULL;
5458 MDB_val xdata, *rdata, dkey;
5461 int do_sub = 0, insert = 0;
5462 unsigned int mcount = 0, dcount = 0, nospill;
5466 char dbuf[MDB_MAXKEYSIZE+1];
5467 unsigned int nflags;
5470 /* Check this first so counter will always be zero on any
5473 if (flags & MDB_MULTIPLE) {
5474 dcount = data[1].mv_size;
5475 data[1].mv_size = 0;
5476 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5480 nospill = flags & MDB_NOSPILL;
5481 flags &= ~MDB_NOSPILL;
5483 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5486 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5489 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5492 #if SIZE_MAX > MAXDATASIZE
5493 if (data->mv_size > MAXDATASIZE)
5497 DPRINTF("==> put db %u key [%s], size %"Z"u, data size %"Z"u",
5498 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
5502 if (flags == MDB_CURRENT) {
5503 if (!(mc->mc_flags & C_INITIALIZED))
5506 } else if (mc->mc_db->md_root == P_INVALID) {
5507 /* new database, cursor has nothing to point to */
5509 mc->mc_flags &= ~C_INITIALIZED;
5514 if (flags & MDB_APPEND) {
5516 rc = mdb_cursor_last(mc, &k2, &d2);
5518 rc = mc->mc_dbx->md_cmp(key, &k2);
5521 mc->mc_ki[mc->mc_top]++;
5523 /* new key is <= last key */
5528 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5530 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5531 DPRINTF("duplicate key [%s]", DKEY(key));
5533 return MDB_KEYEXIST;
5535 if (rc && rc != MDB_NOTFOUND)
5539 /* Cursor is positioned, check for room in the dirty list */
5541 if (flags & MDB_MULTIPLE) {
5543 xdata.mv_size = data->mv_size * dcount;
5547 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5551 if (rc == MDB_NO_ROOT) {
5553 /* new database, write a root leaf page */
5554 DPUTS("allocating new root leaf page");
5555 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5558 mdb_cursor_push(mc, np);
5559 mc->mc_db->md_root = np->mp_pgno;
5560 mc->mc_db->md_depth++;
5561 *mc->mc_dbflag |= DB_DIRTY;
5562 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5564 np->mp_flags |= P_LEAF2;
5565 mc->mc_flags |= C_INITIALIZED;
5567 /* make sure all cursor pages are writable */
5568 rc2 = mdb_cursor_touch(mc);
5573 /* The key already exists */
5574 if (rc == MDB_SUCCESS) {
5575 /* there's only a key anyway, so this is a no-op */
5576 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5577 unsigned int ksize = mc->mc_db->md_pad;
5578 if (key->mv_size != ksize)
5580 if (flags == MDB_CURRENT) {
5581 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5582 memcpy(ptr, key->mv_data, ksize);
5587 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5590 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5591 /* Was a single item before, must convert now */
5593 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5594 /* Just overwrite the current item */
5595 if (flags == MDB_CURRENT)
5598 dkey.mv_size = NODEDSZ(leaf);
5599 dkey.mv_data = NODEDATA(leaf);
5600 #if UINT_MAX < SIZE_MAX
5601 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5602 #ifdef MISALIGNED_OK
5603 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5605 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5608 /* if data matches, ignore it */
5609 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5610 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5612 /* create a fake page for the dup items */
5613 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5614 dkey.mv_data = dbuf;
5615 fp = (MDB_page *)&pbuf;
5616 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5617 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5618 fp->mp_lower = PAGEHDRSZ;
5619 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5620 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5621 fp->mp_flags |= P_LEAF2;
5622 fp->mp_pad = data->mv_size;
5623 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5625 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5626 (dkey.mv_size & 1) + (data->mv_size & 1);
5628 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5631 xdata.mv_size = fp->mp_upper;
5636 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5637 /* See if we need to convert from fake page to subDB */
5639 unsigned int offset;
5643 fp = NODEDATA(leaf);
5644 if (flags == MDB_CURRENT) {
5646 fp->mp_flags |= P_DIRTY;
5647 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5648 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5652 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5653 offset = fp->mp_pad;
5654 if (SIZELEFT(fp) >= offset)
5656 offset *= 4; /* space for 4 more */
5658 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5660 offset += offset & 1;
5661 fp_flags = fp->mp_flags;
5662 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5663 offset >= mc->mc_txn->mt_env->me_nodemax) {
5664 /* yes, convert it */
5666 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5667 dummy.md_pad = fp->mp_pad;
5668 dummy.md_flags = MDB_DUPFIXED;
5669 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5670 dummy.md_flags |= MDB_INTEGERKEY;
5673 dummy.md_branch_pages = 0;
5674 dummy.md_leaf_pages = 1;
5675 dummy.md_overflow_pages = 0;
5676 dummy.md_entries = NUMKEYS(fp);
5678 xdata.mv_size = sizeof(MDB_db);
5679 xdata.mv_data = &dummy;
5680 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5682 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5683 flags |= F_DUPDATA|F_SUBDATA;
5684 dummy.md_root = mp->mp_pgno;
5685 fp_flags &= ~P_SUBP;
5687 /* no, just grow it */
5689 xdata.mv_size = NODEDSZ(leaf) + offset;
5690 xdata.mv_data = &pbuf;
5691 mp = (MDB_page *)&pbuf;
5692 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5695 mp->mp_flags = fp_flags | P_DIRTY;
5696 mp->mp_pad = fp->mp_pad;
5697 mp->mp_lower = fp->mp_lower;
5698 mp->mp_upper = fp->mp_upper + offset;
5700 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5702 nsize = NODEDSZ(leaf) - fp->mp_upper;
5703 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5704 for (i=0; i<NUMKEYS(fp); i++)
5705 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5707 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5711 /* data is on sub-DB, just store it */
5712 flags |= F_DUPDATA|F_SUBDATA;
5716 /* overflow page overwrites need special handling */
5717 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5720 unsigned psize = mc->mc_txn->mt_env->me_psize;
5721 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5723 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5724 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5726 ovpages = omp->mp_pages;
5728 /* Is the ov page large enough? */
5729 if (ovpages >= dpages) {
5730 if (!(omp->mp_flags & P_DIRTY) &&
5731 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5733 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5736 level = 0; /* dirty in this txn or clean */
5739 if (omp->mp_flags & P_DIRTY) {
5740 /* yes, overwrite it. Note in this case we don't
5741 * bother to try shrinking the page if the new data
5742 * is smaller than the overflow threshold.
5745 /* It is writable only in a parent txn */
5746 size_t sz = (size_t) psize * ovpages, off;
5747 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5753 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5754 if (!(flags & MDB_RESERVE)) {
5755 /* Copy end of page, adjusting alignment so
5756 * compiler may copy words instead of bytes.
5758 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5759 memcpy((size_t *)((char *)np + off),
5760 (size_t *)((char *)omp + off), sz - off);
5763 memcpy(np, omp, sz); /* Copy beginning of page */
5766 SETDSZ(leaf, data->mv_size);
5767 if (F_ISSET(flags, MDB_RESERVE))
5768 data->mv_data = METADATA(omp);
5770 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5774 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5776 } else if (NODEDSZ(leaf) == data->mv_size) {
5777 /* same size, just replace it. Note that we could
5778 * also reuse this node if the new data is smaller,
5779 * but instead we opt to shrink the node in that case.
5781 if (F_ISSET(flags, MDB_RESERVE))
5782 data->mv_data = NODEDATA(leaf);
5783 else if (data->mv_size)
5784 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5786 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5789 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5790 mc->mc_db->md_entries--;
5792 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5799 nflags = flags & NODE_ADD_FLAGS;
5800 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5801 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5802 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5803 nflags &= ~MDB_APPEND;
5805 nflags |= MDB_SPLIT_REPLACE;
5806 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5808 /* There is room already in this leaf page. */
5809 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5810 if (rc == 0 && !do_sub && insert) {
5811 /* Adjust other cursors pointing to mp */
5812 MDB_cursor *m2, *m3;
5813 MDB_dbi dbi = mc->mc_dbi;
5814 unsigned i = mc->mc_top;
5815 MDB_page *mp = mc->mc_pg[i];
5817 if (mc->mc_flags & C_SUB)
5820 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5821 if (mc->mc_flags & C_SUB)
5822 m3 = &m2->mc_xcursor->mx_cursor;
5825 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5826 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5833 if (rc != MDB_SUCCESS)
5834 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5836 /* Now store the actual data in the child DB. Note that we're
5837 * storing the user data in the keys field, so there are strict
5838 * size limits on dupdata. The actual data fields of the child
5839 * DB are all zero size.
5846 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5847 if (flags & MDB_CURRENT) {
5848 xflags = MDB_CURRENT|MDB_NOSPILL;
5850 mdb_xcursor_init1(mc, leaf);
5851 xflags = (flags & MDB_NODUPDATA) ?
5852 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
5854 /* converted, write the original data first */
5856 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5860 /* Adjust other cursors pointing to mp */
5862 unsigned i = mc->mc_top;
5863 MDB_page *mp = mc->mc_pg[i];
5865 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5866 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5867 if (!(m2->mc_flags & C_INITIALIZED)) continue;
5868 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5869 mdb_xcursor_init1(m2, leaf);
5873 /* we've done our job */
5876 if (flags & MDB_APPENDDUP)
5877 xflags |= MDB_APPEND;
5878 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5879 if (flags & F_SUBDATA) {
5880 void *db = NODEDATA(leaf);
5881 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5884 /* sub-writes might have failed so check rc again.
5885 * Don't increment count if we just replaced an existing item.
5887 if (!rc && !(flags & MDB_CURRENT))
5888 mc->mc_db->md_entries++;
5889 if (flags & MDB_MULTIPLE) {
5892 if (mcount < dcount) {
5893 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5894 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5898 /* let caller know how many succeeded, if any */
5899 data[1].mv_size = mcount;
5903 /* If we succeeded and the key didn't exist before, make sure
5904 * the cursor is marked valid.
5907 mc->mc_flags |= C_INITIALIZED;
5912 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5917 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5920 if (!(mc->mc_flags & C_INITIALIZED))
5923 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
5925 flags &= ~MDB_NOSPILL; /* TODO: Or change (flags != MDB_NODUPDATA) to ~(flags & MDB_NODUPDATA), not looking at the logic of that code just now */
5927 rc = mdb_cursor_touch(mc);
5931 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5933 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5934 if (flags != MDB_NODUPDATA) {
5935 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5936 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5938 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
5939 /* If sub-DB still has entries, we're done */
5940 if (mc->mc_xcursor->mx_db.md_entries) {
5941 if (leaf->mn_flags & F_SUBDATA) {
5942 /* update subDB info */
5943 void *db = NODEDATA(leaf);
5944 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5947 /* shrink fake page */
5948 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5949 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5950 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5951 /* fix other sub-DB cursors pointed at this fake page */
5952 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5953 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5954 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
5955 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
5956 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5959 mc->mc_db->md_entries--;
5962 /* otherwise fall thru and delete the sub-DB */
5965 if (leaf->mn_flags & F_SUBDATA) {
5966 /* add all the child DB's pages to the free list */
5967 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5968 if (rc == MDB_SUCCESS) {
5969 mc->mc_db->md_entries -=
5970 mc->mc_xcursor->mx_db.md_entries;
5975 return mdb_cursor_del0(mc, leaf);
5978 /** Allocate and initialize new pages for a database.
5979 * @param[in] mc a cursor on the database being added to.
5980 * @param[in] flags flags defining what type of page is being allocated.
5981 * @param[in] num the number of pages to allocate. This is usually 1,
5982 * unless allocating overflow pages for a large record.
5983 * @param[out] mp Address of a page, or NULL on failure.
5984 * @return 0 on success, non-zero on failure.
5987 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5992 if ((rc = mdb_page_alloc(mc, num, &np)))
5994 DPRINTF("allocated new mpage %"Z"u, page size %u",
5995 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5996 np->mp_flags = flags | P_DIRTY;
5997 np->mp_lower = PAGEHDRSZ;
5998 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6001 mc->mc_db->md_branch_pages++;
6002 else if (IS_LEAF(np))
6003 mc->mc_db->md_leaf_pages++;
6004 else if (IS_OVERFLOW(np)) {
6005 mc->mc_db->md_overflow_pages += num;
6013 /** Calculate the size of a leaf node.
6014 * The size depends on the environment's page size; if a data item
6015 * is too large it will be put onto an overflow page and the node
6016 * size will only include the key and not the data. Sizes are always
6017 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6018 * of the #MDB_node headers.
6019 * @param[in] env The environment handle.
6020 * @param[in] key The key for the node.
6021 * @param[in] data The data for the node.
6022 * @return The number of bytes needed to store the node.
6025 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6029 sz = LEAFSIZE(key, data);
6030 if (sz >= env->me_nodemax) {
6031 /* put on overflow page */
6032 sz -= data->mv_size - sizeof(pgno_t);
6036 return sz + sizeof(indx_t);
6039 /** Calculate the size of a branch node.
6040 * The size should depend on the environment's page size but since
6041 * we currently don't support spilling large keys onto overflow
6042 * pages, it's simply the size of the #MDB_node header plus the
6043 * size of the key. Sizes are always rounded up to an even number
6044 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6045 * @param[in] env The environment handle.
6046 * @param[in] key The key for the node.
6047 * @return The number of bytes needed to store the node.
6050 mdb_branch_size(MDB_env *env, MDB_val *key)
6055 if (sz >= env->me_nodemax) {
6056 /* put on overflow page */
6057 /* not implemented */
6058 /* sz -= key->size - sizeof(pgno_t); */
6061 return sz + sizeof(indx_t);
6064 /** Add a node to the page pointed to by the cursor.
6065 * @param[in] mc The cursor for this operation.
6066 * @param[in] indx The index on the page where the new node should be added.
6067 * @param[in] key The key for the new node.
6068 * @param[in] data The data for the new node, if any.
6069 * @param[in] pgno The page number, if adding a branch node.
6070 * @param[in] flags Flags for the node.
6071 * @return 0 on success, non-zero on failure. Possible errors are:
6073 * <li>ENOMEM - failed to allocate overflow pages for the node.
6074 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6075 * should never happen since all callers already calculate the
6076 * page's free space before calling this function.
6080 mdb_node_add(MDB_cursor *mc, indx_t indx,
6081 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6084 size_t node_size = NODESIZE;
6087 MDB_page *mp = mc->mc_pg[mc->mc_top];
6088 MDB_page *ofp = NULL; /* overflow page */
6091 assert(mp->mp_upper >= mp->mp_lower);
6093 DPRINTF("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6094 IS_LEAF(mp) ? "leaf" : "branch",
6095 IS_SUBP(mp) ? "sub-" : "",
6096 mp->mp_pgno, indx, data ? data->mv_size : 0,
6097 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
6100 /* Move higher keys up one slot. */
6101 int ksize = mc->mc_db->md_pad, dif;
6102 char *ptr = LEAF2KEY(mp, indx, ksize);
6103 dif = NUMKEYS(mp) - indx;
6105 memmove(ptr+ksize, ptr, dif*ksize);
6106 /* insert new key */
6107 memcpy(ptr, key->mv_data, ksize);
6109 /* Just using these for counting */
6110 mp->mp_lower += sizeof(indx_t);
6111 mp->mp_upper -= ksize - sizeof(indx_t);
6116 node_size += key->mv_size;
6120 if (F_ISSET(flags, F_BIGDATA)) {
6121 /* Data already on overflow page. */
6122 node_size += sizeof(pgno_t);
6123 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6124 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6126 /* Put data on overflow page. */
6127 DPRINTF("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6128 data->mv_size, node_size+data->mv_size);
6129 node_size += sizeof(pgno_t);
6130 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6132 DPRINTF("allocated overflow page %"Z"u", ofp->mp_pgno);
6135 node_size += data->mv_size;
6138 node_size += node_size & 1;
6140 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
6141 DPRINTF("not enough room in page %"Z"u, got %u ptrs",
6142 mp->mp_pgno, NUMKEYS(mp));
6143 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
6144 mp->mp_upper - mp->mp_lower);
6145 DPRINTF("node size = %"Z"u", node_size);
6146 return MDB_PAGE_FULL;
6149 /* Move higher pointers up one slot. */
6150 for (i = NUMKEYS(mp); i > indx; i--)
6151 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6153 /* Adjust free space offsets. */
6154 ofs = mp->mp_upper - node_size;
6155 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6156 mp->mp_ptrs[indx] = ofs;
6158 mp->mp_lower += sizeof(indx_t);
6160 /* Write the node data. */
6161 node = NODEPTR(mp, indx);
6162 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6163 node->mn_flags = flags;
6165 SETDSZ(node,data->mv_size);
6170 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6175 if (F_ISSET(flags, F_BIGDATA))
6176 memcpy(node->mn_data + key->mv_size, data->mv_data,
6178 else if (F_ISSET(flags, MDB_RESERVE))
6179 data->mv_data = node->mn_data + key->mv_size;
6181 memcpy(node->mn_data + key->mv_size, data->mv_data,
6184 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6186 if (F_ISSET(flags, MDB_RESERVE))
6187 data->mv_data = METADATA(ofp);
6189 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6196 /** Delete the specified node from a page.
6197 * @param[in] mp The page to operate on.
6198 * @param[in] indx The index of the node to delete.
6199 * @param[in] ksize The size of a node. Only used if the page is
6200 * part of a #MDB_DUPFIXED database.
6203 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6206 indx_t i, j, numkeys, ptr;
6213 COPY_PGNO(pgno, mp->mp_pgno);
6214 DPRINTF("delete node %u on %s page %"Z"u", indx,
6215 IS_LEAF(mp) ? "leaf" : "branch", pgno);
6218 assert(indx < NUMKEYS(mp));
6221 int x = NUMKEYS(mp) - 1 - indx;
6222 base = LEAF2KEY(mp, indx, ksize);
6224 memmove(base, base + ksize, x * ksize);
6225 mp->mp_lower -= sizeof(indx_t);
6226 mp->mp_upper += ksize - sizeof(indx_t);
6230 node = NODEPTR(mp, indx);
6231 sz = NODESIZE + node->mn_ksize;
6233 if (F_ISSET(node->mn_flags, F_BIGDATA))
6234 sz += sizeof(pgno_t);
6236 sz += NODEDSZ(node);
6240 ptr = mp->mp_ptrs[indx];
6241 numkeys = NUMKEYS(mp);
6242 for (i = j = 0; i < numkeys; i++) {
6244 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6245 if (mp->mp_ptrs[i] < ptr)
6246 mp->mp_ptrs[j] += sz;
6251 base = (char *)mp + mp->mp_upper;
6252 memmove(base + sz, base, ptr - mp->mp_upper);
6254 mp->mp_lower -= sizeof(indx_t);
6258 /** Compact the main page after deleting a node on a subpage.
6259 * @param[in] mp The main page to operate on.
6260 * @param[in] indx The index of the subpage on the main page.
6263 mdb_node_shrink(MDB_page *mp, indx_t indx)
6270 indx_t i, numkeys, ptr;
6272 node = NODEPTR(mp, indx);
6273 sp = (MDB_page *)NODEDATA(node);
6274 osize = NODEDSZ(node);
6276 delta = sp->mp_upper - sp->mp_lower;
6277 SETDSZ(node, osize - delta);
6278 xp = (MDB_page *)((char *)sp + delta);
6280 /* shift subpage upward */
6282 nsize = NUMKEYS(sp) * sp->mp_pad;
6283 memmove(METADATA(xp), METADATA(sp), nsize);
6286 nsize = osize - sp->mp_upper;
6287 numkeys = NUMKEYS(sp);
6288 for (i=numkeys-1; i>=0; i--)
6289 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6291 xp->mp_upper = sp->mp_lower;
6292 xp->mp_lower = sp->mp_lower;
6293 xp->mp_flags = sp->mp_flags;
6294 xp->mp_pad = sp->mp_pad;
6295 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6297 /* shift lower nodes upward */
6298 ptr = mp->mp_ptrs[indx];
6299 numkeys = NUMKEYS(mp);
6300 for (i = 0; i < numkeys; i++) {
6301 if (mp->mp_ptrs[i] <= ptr)
6302 mp->mp_ptrs[i] += delta;
6305 base = (char *)mp + mp->mp_upper;
6306 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6307 mp->mp_upper += delta;
6310 /** Initial setup of a sorted-dups cursor.
6311 * Sorted duplicates are implemented as a sub-database for the given key.
6312 * The duplicate data items are actually keys of the sub-database.
6313 * Operations on the duplicate data items are performed using a sub-cursor
6314 * initialized when the sub-database is first accessed. This function does
6315 * the preliminary setup of the sub-cursor, filling in the fields that
6316 * depend only on the parent DB.
6317 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6320 mdb_xcursor_init0(MDB_cursor *mc)
6322 MDB_xcursor *mx = mc->mc_xcursor;
6324 mx->mx_cursor.mc_xcursor = NULL;
6325 mx->mx_cursor.mc_txn = mc->mc_txn;
6326 mx->mx_cursor.mc_db = &mx->mx_db;
6327 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6328 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
6329 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6330 mx->mx_cursor.mc_snum = 0;
6331 mx->mx_cursor.mc_top = 0;
6332 mx->mx_cursor.mc_flags = C_SUB;
6333 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6334 mx->mx_dbx.md_dcmp = NULL;
6335 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6338 /** Final setup of a sorted-dups cursor.
6339 * Sets up the fields that depend on the data from the main cursor.
6340 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6341 * @param[in] node The data containing the #MDB_db record for the
6342 * sorted-dup database.
6345 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6347 MDB_xcursor *mx = mc->mc_xcursor;
6349 if (node->mn_flags & F_SUBDATA) {
6350 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6351 mx->mx_cursor.mc_pg[0] = 0;
6352 mx->mx_cursor.mc_snum = 0;
6353 mx->mx_cursor.mc_flags = C_SUB;
6355 MDB_page *fp = NODEDATA(node);
6356 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6357 mx->mx_db.md_flags = 0;
6358 mx->mx_db.md_depth = 1;
6359 mx->mx_db.md_branch_pages = 0;
6360 mx->mx_db.md_leaf_pages = 1;
6361 mx->mx_db.md_overflow_pages = 0;
6362 mx->mx_db.md_entries = NUMKEYS(fp);
6363 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6364 mx->mx_cursor.mc_snum = 1;
6365 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6366 mx->mx_cursor.mc_top = 0;
6367 mx->mx_cursor.mc_pg[0] = fp;
6368 mx->mx_cursor.mc_ki[0] = 0;
6369 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6370 mx->mx_db.md_flags = MDB_DUPFIXED;
6371 mx->mx_db.md_pad = fp->mp_pad;
6372 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6373 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6376 DPRINTF("Sub-db %u for db %u root page %"Z"u", mx->mx_cursor.mc_dbi, mc->mc_dbi,
6378 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
6380 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
6381 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
6382 #if UINT_MAX < SIZE_MAX
6383 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6384 #ifdef MISALIGNED_OK
6385 mx->mx_dbx.md_cmp = mdb_cmp_long;
6387 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6392 /** Initialize a cursor for a given transaction and database. */
6394 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6397 mc->mc_backup = NULL;
6400 mc->mc_db = &txn->mt_dbs[dbi];
6401 mc->mc_dbx = &txn->mt_dbxs[dbi];
6402 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6407 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6409 mc->mc_xcursor = mx;
6410 mdb_xcursor_init0(mc);
6412 mc->mc_xcursor = NULL;
6414 if (*mc->mc_dbflag & DB_STALE) {
6415 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6420 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6423 size_t size = sizeof(MDB_cursor);
6425 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6428 /* Allow read access to the freelist */
6429 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6432 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6433 size += sizeof(MDB_xcursor);
6435 if ((mc = malloc(size)) != NULL) {
6436 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6437 if (txn->mt_cursors) {
6438 mc->mc_next = txn->mt_cursors[dbi];
6439 txn->mt_cursors[dbi] = mc;
6440 mc->mc_flags |= C_UNTRACK;
6452 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6454 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6457 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6460 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6464 /* Return the count of duplicate data items for the current key */
6466 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6470 if (mc == NULL || countp == NULL)
6473 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
6476 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6477 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6480 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6483 *countp = mc->mc_xcursor->mx_db.md_entries;
6489 mdb_cursor_close(MDB_cursor *mc)
6491 if (mc && !mc->mc_backup) {
6492 /* remove from txn, if tracked */
6493 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6494 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6495 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6497 *prev = mc->mc_next;
6504 mdb_cursor_txn(MDB_cursor *mc)
6506 if (!mc) return NULL;
6511 mdb_cursor_dbi(MDB_cursor *mc)
6517 /** Replace the key for a node with a new key.
6518 * @param[in] mc Cursor pointing to the node to operate on.
6519 * @param[in] key The new key to use.
6520 * @return 0 on success, non-zero on failure.
6523 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6530 indx_t ptr, i, numkeys, indx;
6533 indx = mc->mc_ki[mc->mc_top];
6534 mp = mc->mc_pg[mc->mc_top];
6535 node = NODEPTR(mp, indx);
6536 ptr = mp->mp_ptrs[indx];
6540 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6541 k2.mv_data = NODEKEY(node);
6542 k2.mv_size = node->mn_ksize;
6543 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6545 mdb_dkey(&k2, kbuf2),
6551 delta0 = delta = key->mv_size - node->mn_ksize;
6553 /* Must be 2-byte aligned. If new key is
6554 * shorter by 1, the shift will be skipped.
6556 delta += (delta & 1);
6558 if (delta > 0 && SIZELEFT(mp) < delta) {
6560 /* not enough space left, do a delete and split */
6561 DPRINTF("Not enough room, delta = %d, splitting...", delta);
6562 pgno = NODEPGNO(node);
6563 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6564 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6567 numkeys = NUMKEYS(mp);
6568 for (i = 0; i < numkeys; i++) {
6569 if (mp->mp_ptrs[i] <= ptr)
6570 mp->mp_ptrs[i] -= delta;
6573 base = (char *)mp + mp->mp_upper;
6574 len = ptr - mp->mp_upper + NODESIZE;
6575 memmove(base - delta, base, len);
6576 mp->mp_upper -= delta;
6578 node = NODEPTR(mp, indx);
6581 /* But even if no shift was needed, update ksize */
6583 node->mn_ksize = key->mv_size;
6586 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6592 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6594 /** Move a node from csrc to cdst.
6597 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6604 unsigned short flags;
6608 /* Mark src and dst as dirty. */
6609 if ((rc = mdb_page_touch(csrc)) ||
6610 (rc = mdb_page_touch(cdst)))
6613 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6614 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6615 key.mv_size = csrc->mc_db->md_pad;
6616 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6618 data.mv_data = NULL;
6622 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6623 assert(!((long)srcnode&1));
6624 srcpg = NODEPGNO(srcnode);
6625 flags = srcnode->mn_flags;
6626 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6627 unsigned int snum = csrc->mc_snum;
6629 /* must find the lowest key below src */
6630 mdb_page_search_lowest(csrc);
6631 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6632 key.mv_size = csrc->mc_db->md_pad;
6633 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6635 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6636 key.mv_size = NODEKSZ(s2);
6637 key.mv_data = NODEKEY(s2);
6639 csrc->mc_snum = snum--;
6640 csrc->mc_top = snum;
6642 key.mv_size = NODEKSZ(srcnode);
6643 key.mv_data = NODEKEY(srcnode);
6645 data.mv_size = NODEDSZ(srcnode);
6646 data.mv_data = NODEDATA(srcnode);
6648 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6649 unsigned int snum = cdst->mc_snum;
6652 /* must find the lowest key below dst */
6653 mdb_page_search_lowest(cdst);
6654 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6655 bkey.mv_size = cdst->mc_db->md_pad;
6656 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6658 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6659 bkey.mv_size = NODEKSZ(s2);
6660 bkey.mv_data = NODEKEY(s2);
6662 cdst->mc_snum = snum--;
6663 cdst->mc_top = snum;
6664 mdb_cursor_copy(cdst, &mn);
6666 rc = mdb_update_key(&mn, &bkey);
6671 DPRINTF("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6672 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6673 csrc->mc_ki[csrc->mc_top],
6675 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6676 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6678 /* Add the node to the destination page.
6680 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6681 if (rc != MDB_SUCCESS)
6684 /* Delete the node from the source page.
6686 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6689 /* Adjust other cursors pointing to mp */
6690 MDB_cursor *m2, *m3;
6691 MDB_dbi dbi = csrc->mc_dbi;
6692 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6694 if (csrc->mc_flags & C_SUB)
6697 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6698 if (csrc->mc_flags & C_SUB)
6699 m3 = &m2->mc_xcursor->mx_cursor;
6702 if (m3 == csrc) continue;
6703 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6704 csrc->mc_ki[csrc->mc_top]) {
6705 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6706 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6711 /* Update the parent separators.
6713 if (csrc->mc_ki[csrc->mc_top] == 0) {
6714 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6715 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6716 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6718 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6719 key.mv_size = NODEKSZ(srcnode);
6720 key.mv_data = NODEKEY(srcnode);
6722 DPRINTF("update separator for source page %"Z"u to [%s]",
6723 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6724 mdb_cursor_copy(csrc, &mn);
6727 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6730 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6732 indx_t ix = csrc->mc_ki[csrc->mc_top];
6733 nullkey.mv_size = 0;
6734 csrc->mc_ki[csrc->mc_top] = 0;
6735 rc = mdb_update_key(csrc, &nullkey);
6736 csrc->mc_ki[csrc->mc_top] = ix;
6737 assert(rc == MDB_SUCCESS);
6741 if (cdst->mc_ki[cdst->mc_top] == 0) {
6742 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6743 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6744 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6746 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6747 key.mv_size = NODEKSZ(srcnode);
6748 key.mv_data = NODEKEY(srcnode);
6750 DPRINTF("update separator for destination page %"Z"u to [%s]",
6751 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6752 mdb_cursor_copy(cdst, &mn);
6755 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6758 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6760 indx_t ix = cdst->mc_ki[cdst->mc_top];
6761 nullkey.mv_size = 0;
6762 cdst->mc_ki[cdst->mc_top] = 0;
6763 rc = mdb_update_key(cdst, &nullkey);
6764 cdst->mc_ki[cdst->mc_top] = ix;
6765 assert(rc == MDB_SUCCESS);
6772 /** Merge one page into another.
6773 * The nodes from the page pointed to by \b csrc will
6774 * be copied to the page pointed to by \b cdst and then
6775 * the \b csrc page will be freed.
6776 * @param[in] csrc Cursor pointing to the source page.
6777 * @param[in] cdst Cursor pointing to the destination page.
6780 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6788 DPRINTF("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6789 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6791 assert(csrc->mc_snum > 1); /* can't merge root page */
6792 assert(cdst->mc_snum > 1);
6794 /* Mark dst as dirty. */
6795 if ((rc = mdb_page_touch(cdst)))
6798 /* Move all nodes from src to dst.
6800 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6801 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6802 key.mv_size = csrc->mc_db->md_pad;
6803 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6804 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6805 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6806 if (rc != MDB_SUCCESS)
6808 key.mv_data = (char *)key.mv_data + key.mv_size;
6811 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6812 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6813 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6814 unsigned int snum = csrc->mc_snum;
6816 /* must find the lowest key below src */
6817 mdb_page_search_lowest(csrc);
6818 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6819 key.mv_size = csrc->mc_db->md_pad;
6820 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6822 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6823 key.mv_size = NODEKSZ(s2);
6824 key.mv_data = NODEKEY(s2);
6826 csrc->mc_snum = snum--;
6827 csrc->mc_top = snum;
6829 key.mv_size = srcnode->mn_ksize;
6830 key.mv_data = NODEKEY(srcnode);
6833 data.mv_size = NODEDSZ(srcnode);
6834 data.mv_data = NODEDATA(srcnode);
6835 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6836 if (rc != MDB_SUCCESS)
6841 DPRINTF("dst page %"Z"u now has %u keys (%.1f%% filled)",
6842 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);
6844 /* Unlink the src page from parent and add to free list.
6846 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6847 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6850 rc = mdb_update_key(csrc, &key);
6856 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
6857 csrc->mc_pg[csrc->mc_top]->mp_pgno);
6860 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6861 csrc->mc_db->md_leaf_pages--;
6863 csrc->mc_db->md_branch_pages--;
6865 /* Adjust other cursors pointing to mp */
6866 MDB_cursor *m2, *m3;
6867 MDB_dbi dbi = csrc->mc_dbi;
6868 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6870 if (csrc->mc_flags & C_SUB)
6873 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6874 if (csrc->mc_flags & C_SUB)
6875 m3 = &m2->mc_xcursor->mx_cursor;
6878 if (m3 == csrc) continue;
6879 if (m3->mc_snum < csrc->mc_snum) continue;
6880 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6881 m3->mc_pg[csrc->mc_top] = mp;
6882 m3->mc_ki[csrc->mc_top] += nkeys;
6886 mdb_cursor_pop(csrc);
6888 return mdb_rebalance(csrc);
6891 /** Copy the contents of a cursor.
6892 * @param[in] csrc The cursor to copy from.
6893 * @param[out] cdst The cursor to copy to.
6896 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6900 cdst->mc_txn = csrc->mc_txn;
6901 cdst->mc_dbi = csrc->mc_dbi;
6902 cdst->mc_db = csrc->mc_db;
6903 cdst->mc_dbx = csrc->mc_dbx;
6904 cdst->mc_snum = csrc->mc_snum;
6905 cdst->mc_top = csrc->mc_top;
6906 cdst->mc_flags = csrc->mc_flags;
6908 for (i=0; i<csrc->mc_snum; i++) {
6909 cdst->mc_pg[i] = csrc->mc_pg[i];
6910 cdst->mc_ki[i] = csrc->mc_ki[i];
6914 /** Rebalance the tree after a delete operation.
6915 * @param[in] mc Cursor pointing to the page where rebalancing
6917 * @return 0 on success, non-zero on failure.
6920 mdb_rebalance(MDB_cursor *mc)
6924 unsigned int ptop, minkeys;
6927 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6931 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6932 DPRINTF("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
6933 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6934 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6938 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6939 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6942 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6943 DPRINTF("no need to rebalance page %"Z"u, above fill threshold",
6949 if (mc->mc_snum < 2) {
6950 MDB_page *mp = mc->mc_pg[0];
6952 DPUTS("Can't rebalance a subpage, ignoring");
6955 if (NUMKEYS(mp) == 0) {
6956 DPUTS("tree is completely empty");
6957 mc->mc_db->md_root = P_INVALID;
6958 mc->mc_db->md_depth = 0;
6959 mc->mc_db->md_leaf_pages = 0;
6960 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6963 /* Adjust cursors pointing to mp */
6967 MDB_cursor *m2, *m3;
6968 MDB_dbi dbi = mc->mc_dbi;
6970 if (mc->mc_flags & C_SUB)
6973 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6974 if (mc->mc_flags & C_SUB)
6975 m3 = &m2->mc_xcursor->mx_cursor;
6978 if (m3->mc_snum < mc->mc_snum) continue;
6979 if (m3->mc_pg[0] == mp) {
6985 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6986 DPUTS("collapsing root page!");
6987 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6990 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6991 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
6994 mc->mc_db->md_depth--;
6995 mc->mc_db->md_branch_pages--;
6996 mc->mc_ki[0] = mc->mc_ki[1];
6998 /* Adjust other cursors pointing to mp */
6999 MDB_cursor *m2, *m3;
7000 MDB_dbi dbi = mc->mc_dbi;
7002 if (mc->mc_flags & C_SUB)
7005 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7006 if (mc->mc_flags & C_SUB)
7007 m3 = &m2->mc_xcursor->mx_cursor;
7010 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7011 if (m3->mc_pg[0] == mp) {
7012 m3->mc_pg[0] = mc->mc_pg[0];
7015 m3->mc_ki[0] = m3->mc_ki[1];
7020 DPUTS("root page doesn't need rebalancing");
7024 /* The parent (branch page) must have at least 2 pointers,
7025 * otherwise the tree is invalid.
7027 ptop = mc->mc_top-1;
7028 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7030 /* Leaf page fill factor is below the threshold.
7031 * Try to move keys from left or right neighbor, or
7032 * merge with a neighbor page.
7037 mdb_cursor_copy(mc, &mn);
7038 mn.mc_xcursor = NULL;
7040 if (mc->mc_ki[ptop] == 0) {
7041 /* We're the leftmost leaf in our parent.
7043 DPUTS("reading right neighbor");
7045 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7046 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7049 mn.mc_ki[mn.mc_top] = 0;
7050 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7052 /* There is at least one neighbor to the left.
7054 DPUTS("reading left neighbor");
7056 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7057 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7060 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7061 mc->mc_ki[mc->mc_top] = 0;
7064 DPRINTF("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7065 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);
7067 /* If the neighbor page is above threshold and has enough keys,
7068 * move one key from it. Otherwise we should try to merge them.
7069 * (A branch page must never have less than 2 keys.)
7071 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7072 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7073 return mdb_node_move(&mn, mc);
7075 if (mc->mc_ki[ptop] == 0)
7076 rc = mdb_page_merge(&mn, mc);
7078 rc = mdb_page_merge(mc, &mn);
7079 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7084 /** Complete a delete operation started by #mdb_cursor_del(). */
7086 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7092 mp = mc->mc_pg[mc->mc_top];
7093 ki = mc->mc_ki[mc->mc_top];
7095 /* add overflow pages to free list */
7096 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7100 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7101 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7102 (rc = mdb_ovpage_free(mc, omp)))
7105 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7106 mc->mc_db->md_entries--;
7107 rc = mdb_rebalance(mc);
7108 if (rc != MDB_SUCCESS)
7109 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7110 /* if mc points past last node in page, invalidate */
7111 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7112 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7115 /* Adjust other cursors pointing to mp */
7118 MDB_dbi dbi = mc->mc_dbi;
7120 mp = mc->mc_pg[mc->mc_top];
7121 nkeys = NUMKEYS(mp);
7122 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7125 if (!(m2->mc_flags & C_INITIALIZED))
7127 if (m2->mc_pg[mc->mc_top] == mp) {
7128 if (m2->mc_ki[mc->mc_top] > ki)
7129 m2->mc_ki[mc->mc_top]--;
7130 if (m2->mc_ki[mc->mc_top] >= nkeys)
7131 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7140 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7141 MDB_val *key, MDB_val *data)
7146 MDB_val rdata, *xdata;
7150 assert(key != NULL);
7152 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
7154 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7157 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7161 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7165 mdb_cursor_init(&mc, txn, dbi, &mx);
7176 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7178 /* let mdb_page_split know about this cursor if needed:
7179 * delete will trigger a rebalance; if it needs to move
7180 * a node from one page to another, it will have to
7181 * update the parent's separator key(s). If the new sepkey
7182 * is larger than the current one, the parent page may
7183 * run out of space, triggering a split. We need this
7184 * cursor to be consistent until the end of the rebalance.
7186 mc.mc_flags |= C_UNTRACK;
7187 mc.mc_next = txn->mt_cursors[dbi];
7188 txn->mt_cursors[dbi] = &mc;
7189 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7190 txn->mt_cursors[dbi] = mc.mc_next;
7195 /** Split a page and insert a new node.
7196 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7197 * The cursor will be updated to point to the actual page and index where
7198 * the node got inserted after the split.
7199 * @param[in] newkey The key for the newly inserted node.
7200 * @param[in] newdata The data for the newly inserted node.
7201 * @param[in] newpgno The page number, if the new node is a branch node.
7202 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7203 * @return 0 on success, non-zero on failure.
7206 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7207 unsigned int nflags)
7210 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
7213 unsigned int i, j, split_indx, nkeys, pmax;
7215 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7217 MDB_page *mp, *rp, *pp;
7222 mp = mc->mc_pg[mc->mc_top];
7223 newindx = mc->mc_ki[mc->mc_top];
7225 DPRINTF("-----> splitting %s page %"Z"u and adding [%s] at index %i",
7226 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7227 DKEY(newkey), mc->mc_ki[mc->mc_top]);
7229 /* Create a right sibling. */
7230 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7232 DPRINTF("new right sibling: page %"Z"u", rp->mp_pgno);
7234 if (mc->mc_snum < 2) {
7235 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7237 /* shift current top to make room for new parent */
7238 mc->mc_pg[1] = mc->mc_pg[0];
7239 mc->mc_ki[1] = mc->mc_ki[0];
7242 mc->mc_db->md_root = pp->mp_pgno;
7243 DPRINTF("root split! new root = %"Z"u", pp->mp_pgno);
7244 mc->mc_db->md_depth++;
7247 /* Add left (implicit) pointer. */
7248 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7249 /* undo the pre-push */
7250 mc->mc_pg[0] = mc->mc_pg[1];
7251 mc->mc_ki[0] = mc->mc_ki[1];
7252 mc->mc_db->md_root = mp->mp_pgno;
7253 mc->mc_db->md_depth--;
7260 ptop = mc->mc_top-1;
7261 DPRINTF("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno);
7264 mc->mc_flags |= C_SPLITTING;
7265 mdb_cursor_copy(mc, &mn);
7266 mn.mc_pg[mn.mc_top] = rp;
7267 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7269 if (nflags & MDB_APPEND) {
7270 mn.mc_ki[mn.mc_top] = 0;
7272 split_indx = newindx;
7277 nkeys = NUMKEYS(mp);
7278 split_indx = nkeys / 2;
7279 if (newindx < split_indx)
7285 unsigned int lsize, rsize, ksize;
7286 /* Move half of the keys to the right sibling */
7288 x = mc->mc_ki[mc->mc_top] - split_indx;
7289 ksize = mc->mc_db->md_pad;
7290 split = LEAF2KEY(mp, split_indx, ksize);
7291 rsize = (nkeys - split_indx) * ksize;
7292 lsize = (nkeys - split_indx) * sizeof(indx_t);
7293 mp->mp_lower -= lsize;
7294 rp->mp_lower += lsize;
7295 mp->mp_upper += rsize - lsize;
7296 rp->mp_upper -= rsize - lsize;
7297 sepkey.mv_size = ksize;
7298 if (newindx == split_indx) {
7299 sepkey.mv_data = newkey->mv_data;
7301 sepkey.mv_data = split;
7304 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7305 memcpy(rp->mp_ptrs, split, rsize);
7306 sepkey.mv_data = rp->mp_ptrs;
7307 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7308 memcpy(ins, newkey->mv_data, ksize);
7309 mp->mp_lower += sizeof(indx_t);
7310 mp->mp_upper -= ksize - sizeof(indx_t);
7313 memcpy(rp->mp_ptrs, split, x * ksize);
7314 ins = LEAF2KEY(rp, x, ksize);
7315 memcpy(ins, newkey->mv_data, ksize);
7316 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7317 rp->mp_lower += sizeof(indx_t);
7318 rp->mp_upper -= ksize - sizeof(indx_t);
7319 mc->mc_ki[mc->mc_top] = x;
7320 mc->mc_pg[mc->mc_top] = rp;
7325 /* For leaf pages, check the split point based on what
7326 * fits where, since otherwise mdb_node_add can fail.
7328 * This check is only needed when the data items are
7329 * relatively large, such that being off by one will
7330 * make the difference between success or failure.
7332 * It's also relevant if a page happens to be laid out
7333 * such that one half of its nodes are all "small" and
7334 * the other half of its nodes are "large." If the new
7335 * item is also "large" and falls on the half with
7336 * "large" nodes, it also may not fit.
7339 unsigned int psize, nsize;
7340 /* Maximum free space in an empty page */
7341 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
7342 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
7343 if ((nkeys < 20) || (nsize > pmax/16)) {
7344 if (newindx <= split_indx) {
7347 for (i=0; i<split_indx; i++) {
7348 node = NODEPTR(mp, i);
7349 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7350 if (F_ISSET(node->mn_flags, F_BIGDATA))
7351 psize += sizeof(pgno_t);
7353 psize += NODEDSZ(node);
7357 split_indx = newindx;
7368 for (i=nkeys-1; i>=split_indx; i--) {
7369 node = NODEPTR(mp, i);
7370 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7371 if (F_ISSET(node->mn_flags, F_BIGDATA))
7372 psize += sizeof(pgno_t);
7374 psize += NODEDSZ(node);
7378 split_indx = newindx;
7389 /* First find the separating key between the split pages.
7390 * The case where newindx == split_indx is ambiguous; the
7391 * new item could go to the new page or stay on the original
7392 * page. If newpos == 1 it goes to the new page.
7394 if (newindx == split_indx && newpos) {
7395 sepkey.mv_size = newkey->mv_size;
7396 sepkey.mv_data = newkey->mv_data;
7398 node = NODEPTR(mp, split_indx);
7399 sepkey.mv_size = node->mn_ksize;
7400 sepkey.mv_data = NODEKEY(node);
7404 DPRINTF("separator is [%s]", DKEY(&sepkey));
7406 /* Copy separator key to the parent.
7408 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
7412 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7415 if (mn.mc_snum == mc->mc_snum) {
7416 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7417 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7418 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7419 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7424 /* Right page might now have changed parent.
7425 * Check if left page also changed parent.
7427 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7428 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7429 for (i=0; i<ptop; i++) {
7430 mc->mc_pg[i] = mn.mc_pg[i];
7431 mc->mc_ki[i] = mn.mc_ki[i];
7433 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7434 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7438 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7441 mc->mc_flags ^= C_SPLITTING;
7442 if (rc != MDB_SUCCESS) {
7445 if (nflags & MDB_APPEND) {
7446 mc->mc_pg[mc->mc_top] = rp;
7447 mc->mc_ki[mc->mc_top] = 0;
7448 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7451 for (i=0; i<mc->mc_top; i++)
7452 mc->mc_ki[i] = mn.mc_ki[i];
7459 /* Move half of the keys to the right sibling. */
7461 /* grab a page to hold a temporary copy */
7462 copy = mdb_page_malloc(mc->mc_txn, 1);
7466 copy->mp_pgno = mp->mp_pgno;
7467 copy->mp_flags = mp->mp_flags;
7468 copy->mp_lower = PAGEHDRSZ;
7469 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
7470 mc->mc_pg[mc->mc_top] = copy;
7471 for (i = j = 0; i <= nkeys; j++) {
7472 if (i == split_indx) {
7473 /* Insert in right sibling. */
7474 /* Reset insert index for right sibling. */
7475 if (i != newindx || (newpos ^ ins_new)) {
7477 mc->mc_pg[mc->mc_top] = rp;
7481 if (i == newindx && !ins_new) {
7482 /* Insert the original entry that caused the split. */
7483 rkey.mv_data = newkey->mv_data;
7484 rkey.mv_size = newkey->mv_size;
7493 /* Update index for the new key. */
7494 mc->mc_ki[mc->mc_top] = j;
7495 } else if (i == nkeys) {
7498 node = NODEPTR(mp, i);
7499 rkey.mv_data = NODEKEY(node);
7500 rkey.mv_size = node->mn_ksize;
7502 xdata.mv_data = NODEDATA(node);
7503 xdata.mv_size = NODEDSZ(node);
7506 pgno = NODEPGNO(node);
7507 flags = node->mn_flags;
7512 if (!IS_LEAF(mp) && j == 0) {
7513 /* First branch index doesn't need key data. */
7517 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7521 nkeys = NUMKEYS(copy);
7522 for (i=0; i<nkeys; i++)
7523 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7524 mp->mp_lower = copy->mp_lower;
7525 mp->mp_upper = copy->mp_upper;
7526 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7527 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
7529 /* reset back to original page */
7530 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
7531 mc->mc_pg[mc->mc_top] = mp;
7532 if (nflags & MDB_RESERVE) {
7533 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7534 if (!(node->mn_flags & F_BIGDATA))
7535 newdata->mv_data = NODEDATA(node);
7539 /* Make sure mc_ki is still valid.
7541 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7542 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7543 for (i=0; i<ptop; i++) {
7544 mc->mc_pg[i] = mn.mc_pg[i];
7545 mc->mc_ki[i] = mn.mc_ki[i];
7547 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7548 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7552 /* return tmp page to freelist */
7553 mdb_page_free(mc->mc_txn->mt_env, copy);
7556 /* Adjust other cursors pointing to mp */
7557 MDB_cursor *m2, *m3;
7558 MDB_dbi dbi = mc->mc_dbi;
7559 int fixup = NUMKEYS(mp);
7561 if (mc->mc_flags & C_SUB)
7564 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7565 if (mc->mc_flags & C_SUB)
7566 m3 = &m2->mc_xcursor->mx_cursor;
7571 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7573 if (m3->mc_flags & C_SPLITTING)
7578 for (k=m3->mc_top; k>=0; k--) {
7579 m3->mc_ki[k+1] = m3->mc_ki[k];
7580 m3->mc_pg[k+1] = m3->mc_pg[k];
7582 if (m3->mc_ki[0] >= split_indx) {
7587 m3->mc_pg[0] = mc->mc_pg[0];
7591 if (m3->mc_pg[mc->mc_top] == mp) {
7592 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7593 m3->mc_ki[mc->mc_top]++;
7594 if (m3->mc_ki[mc->mc_top] >= fixup) {
7595 m3->mc_pg[mc->mc_top] = rp;
7596 m3->mc_ki[mc->mc_top] -= fixup;
7597 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7599 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7600 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7609 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7610 MDB_val *key, MDB_val *data, unsigned int flags)
7615 assert(key != NULL);
7616 assert(data != NULL);
7618 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7621 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7625 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7629 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7632 mdb_cursor_init(&mc, txn, dbi, &mx);
7633 return mdb_cursor_put(&mc, key, data, flags);
7637 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7639 if ((flag & CHANGEABLE) != flag)
7642 env->me_flags |= flag;
7644 env->me_flags &= ~flag;
7649 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7654 *arg = env->me_flags;
7659 mdb_env_get_path(MDB_env *env, const char **arg)
7664 *arg = env->me_path;
7668 /** Common code for #mdb_stat() and #mdb_env_stat().
7669 * @param[in] env the environment to operate in.
7670 * @param[in] db the #MDB_db record containing the stats to return.
7671 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7672 * @return 0, this function always succeeds.
7675 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7677 arg->ms_psize = env->me_psize;
7678 arg->ms_depth = db->md_depth;
7679 arg->ms_branch_pages = db->md_branch_pages;
7680 arg->ms_leaf_pages = db->md_leaf_pages;
7681 arg->ms_overflow_pages = db->md_overflow_pages;
7682 arg->ms_entries = db->md_entries;
7687 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7691 if (env == NULL || arg == NULL)
7694 toggle = mdb_env_pick_meta(env);
7696 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7700 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7704 if (env == NULL || arg == NULL)
7707 toggle = mdb_env_pick_meta(env);
7708 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7709 arg->me_mapsize = env->me_mapsize;
7710 arg->me_maxreaders = env->me_maxreaders;
7712 /* me_numreaders may be zero if this process never used any readers. Use
7713 * the shared numreader count if it exists.
7715 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7717 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7718 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7722 /** Set the default comparison functions for a database.
7723 * Called immediately after a database is opened to set the defaults.
7724 * The user can then override them with #mdb_set_compare() or
7725 * #mdb_set_dupsort().
7726 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7727 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7730 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7732 uint16_t f = txn->mt_dbs[dbi].md_flags;
7734 txn->mt_dbxs[dbi].md_cmp =
7735 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7736 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7738 txn->mt_dbxs[dbi].md_dcmp =
7739 !(f & MDB_DUPSORT) ? 0 :
7740 ((f & MDB_INTEGERDUP)
7741 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7742 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7745 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7750 int rc, dbflag, exact;
7751 unsigned int unused = 0;
7754 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7755 mdb_default_cmp(txn, FREE_DBI);
7758 if ((flags & VALID_FLAGS) != flags)
7764 if (flags & PERSISTENT_FLAGS) {
7765 uint16_t f2 = flags & PERSISTENT_FLAGS;
7766 /* make sure flag changes get committed */
7767 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7768 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7769 txn->mt_flags |= MDB_TXN_DIRTY;
7772 mdb_default_cmp(txn, MAIN_DBI);
7776 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7777 mdb_default_cmp(txn, MAIN_DBI);
7780 /* Is the DB already open? */
7782 for (i=2; i<txn->mt_numdbs; i++) {
7783 if (!txn->mt_dbxs[i].md_name.mv_size) {
7784 /* Remember this free slot */
7785 if (!unused) unused = i;
7788 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7789 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7795 /* If no free slot and max hit, fail */
7796 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7797 return MDB_DBS_FULL;
7799 /* Cannot mix named databases with some mainDB flags */
7800 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7801 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7803 /* Find the DB info */
7804 dbflag = DB_NEW|DB_VALID;
7807 key.mv_data = (void *)name;
7808 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7809 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7810 if (rc == MDB_SUCCESS) {
7811 /* make sure this is actually a DB */
7812 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7813 if (!(node->mn_flags & F_SUBDATA))
7815 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7816 /* Create if requested */
7818 data.mv_size = sizeof(MDB_db);
7819 data.mv_data = &dummy;
7820 memset(&dummy, 0, sizeof(dummy));
7821 dummy.md_root = P_INVALID;
7822 dummy.md_flags = flags & PERSISTENT_FLAGS;
7823 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7827 /* OK, got info, add to table */
7828 if (rc == MDB_SUCCESS) {
7829 unsigned int slot = unused ? unused : txn->mt_numdbs;
7830 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7831 txn->mt_dbxs[slot].md_name.mv_size = len;
7832 txn->mt_dbxs[slot].md_rel = NULL;
7833 txn->mt_dbflags[slot] = dbflag;
7834 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7836 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7837 mdb_default_cmp(txn, slot);
7846 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7848 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7851 if (txn->mt_dbflags[dbi] & DB_STALE) {
7854 /* Stale, must read the DB's root. cursor_init does it for us. */
7855 mdb_cursor_init(&mc, txn, dbi, &mx);
7857 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7860 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7863 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7865 ptr = env->me_dbxs[dbi].md_name.mv_data;
7866 env->me_dbxs[dbi].md_name.mv_data = NULL;
7867 env->me_dbxs[dbi].md_name.mv_size = 0;
7868 env->me_dbflags[dbi] = 0;
7872 int mdb_dbi_flags(MDB_env *env, MDB_dbi dbi, unsigned int *flags)
7874 /* We could return the flags for the FREE_DBI too but what's the point? */
7875 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
7877 *flags = env->me_dbflags[dbi];
7881 /** Add all the DB's pages to the free list.
7882 * @param[in] mc Cursor on the DB to free.
7883 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7884 * @return 0 on success, non-zero on failure.
7887 mdb_drop0(MDB_cursor *mc, int subs)
7891 rc = mdb_page_search(mc, NULL, 0);
7892 if (rc == MDB_SUCCESS) {
7893 MDB_txn *txn = mc->mc_txn;
7898 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7899 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7902 mdb_cursor_copy(mc, &mx);
7903 while (mc->mc_snum > 0) {
7904 MDB_page *mp = mc->mc_pg[mc->mc_top];
7905 unsigned n = NUMKEYS(mp);
7907 for (i=0; i<n; i++) {
7908 ni = NODEPTR(mp, i);
7909 if (ni->mn_flags & F_BIGDATA) {
7912 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7913 rc = mdb_page_get(txn, pg, &omp, NULL);
7916 assert(IS_OVERFLOW(omp));
7917 rc = mdb_midl_append_range(&txn->mt_free_pgs,
7921 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7922 mdb_xcursor_init1(mc, ni);
7923 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7929 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
7931 for (i=0; i<n; i++) {
7933 ni = NODEPTR(mp, i);
7936 mdb_midl_xappend(txn->mt_free_pgs, pg);
7941 mc->mc_ki[mc->mc_top] = i;
7942 rc = mdb_cursor_sibling(mc, 1);
7944 /* no more siblings, go back to beginning
7945 * of previous level.
7949 for (i=1; i<mc->mc_snum; i++) {
7951 mc->mc_pg[i] = mx.mc_pg[i];
7956 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
7957 } else if (rc == MDB_NOTFOUND) {
7963 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7965 MDB_cursor *mc, *m2;
7968 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7971 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7974 rc = mdb_cursor_open(txn, dbi, &mc);
7978 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7979 /* Invalidate the dropped DB's cursors */
7980 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
7981 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7985 /* Can't delete the main DB */
7986 if (del && dbi > MAIN_DBI) {
7987 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7989 txn->mt_dbflags[dbi] = DB_STALE;
7990 mdb_dbi_close(txn->mt_env, dbi);
7993 /* reset the DB record, mark it dirty */
7994 txn->mt_dbflags[dbi] |= DB_DIRTY;
7995 txn->mt_dbs[dbi].md_depth = 0;
7996 txn->mt_dbs[dbi].md_branch_pages = 0;
7997 txn->mt_dbs[dbi].md_leaf_pages = 0;
7998 txn->mt_dbs[dbi].md_overflow_pages = 0;
7999 txn->mt_dbs[dbi].md_entries = 0;
8000 txn->mt_dbs[dbi].md_root = P_INVALID;
8002 txn->mt_flags |= MDB_TXN_DIRTY;
8005 mdb_cursor_close(mc);
8009 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8011 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8014 txn->mt_dbxs[dbi].md_cmp = cmp;
8018 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8020 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8023 txn->mt_dbxs[dbi].md_dcmp = cmp;
8027 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8029 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8032 txn->mt_dbxs[dbi].md_rel = rel;
8036 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8038 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8041 txn->mt_dbxs[dbi].md_relctx = ctx;
8045 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8047 unsigned int i, rdrs;
8054 if (!env->me_txns) {
8055 return func("(no reader locks)\n", ctx);
8057 rdrs = env->me_txns->mti_numreaders;
8058 mr = env->me_txns->mti_readers;
8059 for (i=0; i<rdrs; i++) {
8064 if (mr[i].mr_txnid == (txnid_t)-1) {
8065 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8067 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8071 func(" pid thread txnid\n", ctx);
8073 rc = func(buf, ctx);
8079 func("(no active readers)\n", ctx);
8084 /* insert pid into list if not already present.
8085 * return -1 if already present.
8087 static int mdb_pid_insert(pid_t *ids, pid_t pid)
8089 /* binary search of pid in list */
8091 unsigned cursor = 1;
8093 unsigned n = ids[0];
8096 unsigned pivot = n >> 1;
8097 cursor = base + pivot + 1;
8098 val = pid - ids[cursor];
8103 } else if ( val > 0 ) {
8108 /* found, so it's a duplicate */
8117 for (n = ids[0]; n > cursor; n--)
8123 int mdb_reader_check(MDB_env *env, int *dead)
8125 unsigned int i, j, rdrs;
8136 rdrs = env->me_txns->mti_numreaders;
8137 pids = malloc((rdrs+1) * sizeof(pid_t));
8141 mr = env->me_txns->mti_readers;
8143 for (i=0; i<rdrs; i++) {
8144 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8146 if (mdb_pid_insert(pids, pid) == 0) {
8147 if (mdb_reader_pid(env, Pidcheck, pid)) {
8149 if (mdb_reader_pid(env, Pidcheck, pid)) {
8150 for (j=i; j<rdrs; j++)
8151 if (mr[j].mr_pid == pid) {
8156 UNLOCK_MUTEX_R(env);