2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2014 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.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
83 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
84 #include <netinet/in.h>
85 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
88 #if defined(__APPLE__) || defined (BSD)
89 # define MDB_USE_POSIX_SEM 1
90 # define MDB_FDATASYNC fsync
91 #elif defined(ANDROID)
92 # define MDB_FDATASYNC fsync
97 #ifdef MDB_USE_POSIX_SEM
98 # define MDB_USE_HASH 1
99 #include <semaphore.h>
104 #include <valgrind/memcheck.h>
105 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
106 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
107 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
108 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
109 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
111 #define VGMEMP_CREATE(h,r,z)
112 #define VGMEMP_ALLOC(h,a,s)
113 #define VGMEMP_FREE(h,a)
114 #define VGMEMP_DESTROY(h)
115 #define VGMEMP_DEFINED(a,s)
119 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
120 /* Solaris just defines one or the other */
121 # define LITTLE_ENDIAN 1234
122 # define BIG_ENDIAN 4321
123 # ifdef _LITTLE_ENDIAN
124 # define BYTE_ORDER LITTLE_ENDIAN
126 # define BYTE_ORDER BIG_ENDIAN
129 # define BYTE_ORDER __BYTE_ORDER
133 #ifndef LITTLE_ENDIAN
134 #define LITTLE_ENDIAN __LITTLE_ENDIAN
137 #define BIG_ENDIAN __BIG_ENDIAN
140 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
141 #define MISALIGNED_OK 1
147 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
148 # error "Unknown or unsupported endianness (BYTE_ORDER)"
149 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
150 # error "Two's complement, reasonably sized integer types, please"
153 /** @defgroup internal LMDB Internals
156 /** @defgroup compat Compatibility Macros
157 * A bunch of macros to minimize the amount of platform-specific ifdefs
158 * needed throughout the rest of the code. When the features this library
159 * needs are similar enough to POSIX to be hidden in a one-or-two line
160 * replacement, this macro approach is used.
164 /** Wrapper around __func__, which is a C99 feature */
165 #if __STDC_VERSION__ >= 199901L
166 # define mdb_func_ __func__
167 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
168 # define mdb_func_ __FUNCTION__
170 /* If a debug message says <mdb_unknown>(), update the #if statements above */
171 # define mdb_func_ "<mdb_unknown>"
175 #define MDB_USE_HASH 1
176 #define MDB_PIDLOCK 0
177 #define THREAD_RET DWORD
178 #define pthread_t HANDLE
179 #define pthread_mutex_t HANDLE
180 #define pthread_key_t DWORD
181 #define pthread_self() GetCurrentThreadId()
182 #define pthread_key_create(x,y) \
183 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
184 #define pthread_key_delete(x) TlsFree(x)
185 #define pthread_getspecific(x) TlsGetValue(x)
186 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
187 #define pthread_mutex_unlock(x) ReleaseMutex(x)
188 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
189 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
190 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
191 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
192 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
193 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
194 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
195 #define getpid() GetCurrentProcessId()
196 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
197 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
198 #define ErrCode() GetLastError()
199 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
200 #define close(fd) (CloseHandle(fd) ? 0 : -1)
201 #define munmap(ptr,len) UnmapViewOfFile(ptr)
202 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
203 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
205 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
209 #define THREAD_RET void *
210 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
211 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
212 #define Z "z" /**< printf format modifier for size_t */
214 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
215 #define MDB_PIDLOCK 1
217 #ifdef MDB_USE_POSIX_SEM
219 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
220 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
221 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
222 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
225 mdb_sem_wait(sem_t *sem)
228 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
233 /** Lock the reader mutex.
235 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
236 /** Unlock the reader mutex.
238 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
240 /** Lock the writer mutex.
241 * Only a single write transaction is allowed at a time. Other writers
242 * will block waiting for this mutex.
244 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
245 /** Unlock the writer mutex.
247 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
248 #endif /* MDB_USE_POSIX_SEM */
250 /** Get the error code for the last failed system function.
252 #define ErrCode() errno
254 /** An abstraction for a file handle.
255 * On POSIX systems file handles are small integers. On Windows
256 * they're opaque pointers.
260 /** A value for an invalid file handle.
261 * Mainly used to initialize file variables and signify that they are
264 #define INVALID_HANDLE_VALUE (-1)
266 /** Get the size of a memory page for the system.
267 * This is the basic size that the platform's memory manager uses, and is
268 * fundamental to the use of memory-mapped files.
270 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
273 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
276 #define MNAME_LEN (sizeof(pthread_mutex_t))
282 /** A flag for opening a file and requesting synchronous data writes.
283 * This is only used when writing a meta page. It's not strictly needed;
284 * we could just do a normal write and then immediately perform a flush.
285 * But if this flag is available it saves us an extra system call.
287 * @note If O_DSYNC is undefined but exists in /usr/include,
288 * preferably set some compiler flag to get the definition.
289 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
292 # define MDB_DSYNC O_DSYNC
296 /** Function for flushing the data of a file. Define this to fsync
297 * if fdatasync() is not supported.
299 #ifndef MDB_FDATASYNC
300 # define MDB_FDATASYNC fdatasync
304 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
315 /** A page number in the database.
316 * Note that 64 bit page numbers are overkill, since pages themselves
317 * already represent 12-13 bits of addressable memory, and the OS will
318 * always limit applications to a maximum of 63 bits of address space.
320 * @note In the #MDB_node structure, we only store 48 bits of this value,
321 * which thus limits us to only 60 bits of addressable data.
323 typedef MDB_ID pgno_t;
325 /** A transaction ID.
326 * See struct MDB_txn.mt_txnid for details.
328 typedef MDB_ID txnid_t;
330 /** @defgroup debug Debug Macros
334 /** Enable debug output. Needs variable argument macros (a C99 feature).
335 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
336 * read from and written to the database (used for free space management).
342 static int mdb_debug;
343 static txnid_t mdb_debug_start;
345 /** Print a debug message with printf formatting.
346 * Requires double parenthesis around 2 or more args.
348 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
349 # define DPRINTF0(fmt, ...) \
350 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
352 # define DPRINTF(args) ((void) 0)
354 /** Print a debug string.
355 * The string is printed literally, with no format processing.
357 #define DPUTS(arg) DPRINTF(("%s", arg))
358 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
360 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
363 /** @brief The maximum size of a database page.
365 * This is 32k, since it must fit in #MDB_page.%mp_upper.
367 * LMDB will use database pages < OS pages if needed.
368 * That causes more I/O in write transactions: The OS must
369 * know (read) the whole page before writing a partial page.
371 * Note that we don't currently support Huge pages. On Linux,
372 * regular data files cannot use Huge pages, and in general
373 * Huge pages aren't actually pageable. We rely on the OS
374 * demand-pager to read our data and page it out when memory
375 * pressure from other processes is high. So until OSs have
376 * actual paging support for Huge pages, they're not viable.
378 #define MAX_PAGESIZE 0x8000
380 /** The minimum number of keys required in a database page.
381 * Setting this to a larger value will place a smaller bound on the
382 * maximum size of a data item. Data items larger than this size will
383 * be pushed into overflow pages instead of being stored directly in
384 * the B-tree node. This value used to default to 4. With a page size
385 * of 4096 bytes that meant that any item larger than 1024 bytes would
386 * go into an overflow page. That also meant that on average 2-3KB of
387 * each overflow page was wasted space. The value cannot be lower than
388 * 2 because then there would no longer be a tree structure. With this
389 * value, items larger than 2KB will go into overflow pages, and on
390 * average only 1KB will be wasted.
392 #define MDB_MINKEYS 2
394 /** A stamp that identifies a file as an LMDB file.
395 * There's nothing special about this value other than that it is easily
396 * recognizable, and it will reflect any byte order mismatches.
398 #define MDB_MAGIC 0xBEEFC0DE
400 /** The version number for a database's datafile format. */
401 #define MDB_DATA_VERSION 1
402 /** The version number for a database's lockfile format. */
403 #define MDB_LOCK_VERSION 1
405 /** @brief The max size of a key we can write, or 0 for dynamic max.
407 * Define this as 0 to compute the max from the page size. 511
408 * is default for backwards compat: liblmdb <= 0.9.10 can break
409 * when modifying a DB with keys/dupsort data bigger than its max.
411 * Data items in an #MDB_DUPSORT database are also limited to
412 * this size, since they're actually keys of a sub-DB. Keys and
413 * #MDB_DUPSORT data items must fit on a node in a regular page.
415 #ifndef MDB_MAXKEYSIZE
416 #define MDB_MAXKEYSIZE 511
419 /** The maximum size of a key we can write to the environment. */
421 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
423 #define ENV_MAXKEY(env) ((env)->me_maxkey)
426 /** @brief The maximum size of a data item.
428 * We only store a 32 bit value for node sizes.
430 #define MAXDATASIZE 0xffffffffUL
433 /** Key size which fits in a #DKBUF.
436 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
439 * This is used for printing a hex dump of a key's contents.
441 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
442 /** Display a key in hex.
444 * Invoke a function to display a key in hex.
446 #define DKEY(x) mdb_dkey(x, kbuf)
452 /** An invalid page number.
453 * Mainly used to denote an empty tree.
455 #define P_INVALID (~(pgno_t)0)
457 /** Test if the flags \b f are set in a flag word \b w. */
458 #define F_ISSET(w, f) (((w) & (f)) == (f))
460 /** Round \b n up to an even number. */
461 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
463 /** Used for offsets within a single page.
464 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
467 typedef uint16_t indx_t;
469 /** Default size of memory map.
470 * This is certainly too small for any actual applications. Apps should always set
471 * the size explicitly using #mdb_env_set_mapsize().
473 #define DEFAULT_MAPSIZE 1048576
475 /** @defgroup readers Reader Lock Table
476 * Readers don't acquire any locks for their data access. Instead, they
477 * simply record their transaction ID in the reader table. The reader
478 * mutex is needed just to find an empty slot in the reader table. The
479 * slot's address is saved in thread-specific data so that subsequent read
480 * transactions started by the same thread need no further locking to proceed.
482 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
484 * No reader table is used if the database is on a read-only filesystem, or
485 * if #MDB_NOLOCK is set.
487 * Since the database uses multi-version concurrency control, readers don't
488 * actually need any locking. This table is used to keep track of which
489 * readers are using data from which old transactions, so that we'll know
490 * when a particular old transaction is no longer in use. Old transactions
491 * that have discarded any data pages can then have those pages reclaimed
492 * for use by a later write transaction.
494 * The lock table is constructed such that reader slots are aligned with the
495 * processor's cache line size. Any slot is only ever used by one thread.
496 * This alignment guarantees that there will be no contention or cache
497 * thrashing as threads update their own slot info, and also eliminates
498 * any need for locking when accessing a slot.
500 * A writer thread will scan every slot in the table to determine the oldest
501 * outstanding reader transaction. Any freed pages older than this will be
502 * reclaimed by the writer. The writer doesn't use any locks when scanning
503 * this table. This means that there's no guarantee that the writer will
504 * see the most up-to-date reader info, but that's not required for correct
505 * operation - all we need is to know the upper bound on the oldest reader,
506 * we don't care at all about the newest reader. So the only consequence of
507 * reading stale information here is that old pages might hang around a
508 * while longer before being reclaimed. That's actually good anyway, because
509 * the longer we delay reclaiming old pages, the more likely it is that a
510 * string of contiguous pages can be found after coalescing old pages from
511 * many old transactions together.
514 /** Number of slots in the reader table.
515 * This value was chosen somewhat arbitrarily. 126 readers plus a
516 * couple mutexes fit exactly into 8KB on my development machine.
517 * Applications should set the table size using #mdb_env_set_maxreaders().
519 #define DEFAULT_READERS 126
521 /** The size of a CPU cache line in bytes. We want our lock structures
522 * aligned to this size to avoid false cache line sharing in the
524 * This value works for most CPUs. For Itanium this should be 128.
530 /** The information we store in a single slot of the reader table.
531 * In addition to a transaction ID, we also record the process and
532 * thread ID that owns a slot, so that we can detect stale information,
533 * e.g. threads or processes that went away without cleaning up.
534 * @note We currently don't check for stale records. We simply re-init
535 * the table when we know that we're the only process opening the
538 typedef struct MDB_rxbody {
539 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
540 * Multiple readers that start at the same time will probably have the
541 * same ID here. Again, it's not important to exclude them from
542 * anything; all we need to know is which version of the DB they
543 * started from so we can avoid overwriting any data used in that
544 * particular version.
547 /** The process ID of the process owning this reader txn. */
549 /** The thread ID of the thread owning this txn. */
553 /** The actual reader record, with cacheline padding. */
554 typedef struct MDB_reader {
557 /** shorthand for mrb_txnid */
558 #define mr_txnid mru.mrx.mrb_txnid
559 #define mr_pid mru.mrx.mrb_pid
560 #define mr_tid mru.mrx.mrb_tid
561 /** cache line alignment */
562 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
566 /** The header for the reader table.
567 * The table resides in a memory-mapped file. (This is a different file
568 * than is used for the main database.)
570 * For POSIX the actual mutexes reside in the shared memory of this
571 * mapped file. On Windows, mutexes are named objects allocated by the
572 * kernel; we store the mutex names in this mapped file so that other
573 * processes can grab them. This same approach is also used on
574 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
575 * process-shared POSIX mutexes. For these cases where a named object
576 * is used, the object name is derived from a 64 bit FNV hash of the
577 * environment pathname. As such, naming collisions are extremely
578 * unlikely. If a collision occurs, the results are unpredictable.
580 typedef struct MDB_txbody {
581 /** Stamp identifying this as an LMDB file. It must be set
584 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
586 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
587 char mtb_rmname[MNAME_LEN];
589 /** Mutex protecting access to this table.
590 * This is the reader lock that #LOCK_MUTEX_R acquires.
592 pthread_mutex_t mtb_mutex;
594 /** The ID of the last transaction committed to the database.
595 * This is recorded here only for convenience; the value can always
596 * be determined by reading the main database meta pages.
599 /** The number of slots that have been used in the reader table.
600 * This always records the maximum count, it is not decremented
601 * when readers release their slots.
603 unsigned mtb_numreaders;
606 /** The actual reader table definition. */
607 typedef struct MDB_txninfo {
610 #define mti_magic mt1.mtb.mtb_magic
611 #define mti_format mt1.mtb.mtb_format
612 #define mti_mutex mt1.mtb.mtb_mutex
613 #define mti_rmname mt1.mtb.mtb_rmname
614 #define mti_txnid mt1.mtb.mtb_txnid
615 #define mti_numreaders mt1.mtb.mtb_numreaders
616 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
619 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
620 char mt2_wmname[MNAME_LEN];
621 #define mti_wmname mt2.mt2_wmname
623 pthread_mutex_t mt2_wmutex;
624 #define mti_wmutex mt2.mt2_wmutex
626 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
628 MDB_reader mti_readers[1];
631 /** Lockfile format signature: version, features and field layout */
632 #define MDB_LOCK_FORMAT \
634 ((MDB_LOCK_VERSION) \
635 /* Flags which describe functionality */ \
636 + (((MDB_PIDLOCK) != 0) << 16)))
639 /** Common header for all page types.
640 * Overflow records occupy a number of contiguous pages with no
641 * headers on any page after the first.
643 typedef struct MDB_page {
644 #define mp_pgno mp_p.p_pgno
645 #define mp_next mp_p.p_next
647 pgno_t p_pgno; /**< page number */
648 void * p_next; /**< for in-memory list of freed structs */
651 /** @defgroup mdb_page Page Flags
653 * Flags for the page headers.
656 #define P_BRANCH 0x01 /**< branch page */
657 #define P_LEAF 0x02 /**< leaf page */
658 #define P_OVERFLOW 0x04 /**< overflow page */
659 #define P_META 0x08 /**< meta page */
660 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
661 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
662 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
663 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
664 #define P_KEEP 0x8000 /**< leave this page alone during spill */
666 uint16_t mp_flags; /**< @ref mdb_page */
667 #define mp_lower mp_pb.pb.pb_lower
668 #define mp_upper mp_pb.pb.pb_upper
669 #define mp_pages mp_pb.pb_pages
672 indx_t pb_lower; /**< lower bound of free space */
673 indx_t pb_upper; /**< upper bound of free space */
675 uint32_t pb_pages; /**< number of overflow pages */
677 indx_t mp_ptrs[1]; /**< dynamic size */
680 /** Size of the page header, excluding dynamic data at the end */
681 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
683 /** Address of first usable data byte in a page, after the header */
684 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
686 /** Number of nodes on a page */
687 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
689 /** The amount of space remaining in the page */
690 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
692 /** The percentage of space used in the page, in tenths of a percent. */
693 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
694 ((env)->me_psize - PAGEHDRSZ))
695 /** The minimum page fill factor, in tenths of a percent.
696 * Pages emptier than this are candidates for merging.
698 #define FILL_THRESHOLD 250
700 /** Test if a page is a leaf page */
701 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
702 /** Test if a page is a LEAF2 page */
703 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
704 /** Test if a page is a branch page */
705 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
706 /** Test if a page is an overflow page */
707 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
708 /** Test if a page is a sub page */
709 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
711 /** The number of overflow pages needed to store the given size. */
712 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
714 /** Link in #MDB_txn.%mt_loose_pages list */
715 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)METADATA(p))
717 /** Header for a single key/data pair within a page.
718 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
719 * We guarantee 2-byte alignment for 'MDB_node's.
721 typedef struct MDB_node {
722 /** lo and hi are used for data size on leaf nodes and for
723 * child pgno on branch nodes. On 64 bit platforms, flags
724 * is also used for pgno. (Branch nodes have no flags).
725 * They are in host byte order in case that lets some
726 * accesses be optimized into a 32-bit word access.
728 #if BYTE_ORDER == LITTLE_ENDIAN
729 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
731 unsigned short mn_hi, mn_lo;
733 /** @defgroup mdb_node Node Flags
735 * Flags for node headers.
738 #define F_BIGDATA 0x01 /**< data put on overflow page */
739 #define F_SUBDATA 0x02 /**< data is a sub-database */
740 #define F_DUPDATA 0x04 /**< data has duplicates */
742 /** valid flags for #mdb_node_add() */
743 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
746 unsigned short mn_flags; /**< @ref mdb_node */
747 unsigned short mn_ksize; /**< key size */
748 char mn_data[1]; /**< key and data are appended here */
751 /** Size of the node header, excluding dynamic data at the end */
752 #define NODESIZE offsetof(MDB_node, mn_data)
754 /** Bit position of top word in page number, for shifting mn_flags */
755 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
757 /** Size of a node in a branch page with a given key.
758 * This is just the node header plus the key, there is no data.
760 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
762 /** Size of a node in a leaf page with a given key and data.
763 * This is node header plus key plus data size.
765 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
767 /** Address of node \b i in page \b p */
768 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
770 /** Address of the key for the node */
771 #define NODEKEY(node) (void *)((node)->mn_data)
773 /** Address of the data for a node */
774 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
776 /** Get the page number pointed to by a branch node */
777 #define NODEPGNO(node) \
778 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
779 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
780 /** Set the page number in a branch node */
781 #define SETPGNO(node,pgno) do { \
782 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
783 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
785 /** Get the size of the data in a leaf node */
786 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
787 /** Set the size of the data for a leaf node */
788 #define SETDSZ(node,size) do { \
789 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
790 /** The size of a key in a node */
791 #define NODEKSZ(node) ((node)->mn_ksize)
793 /** Copy a page number from src to dst */
795 #define COPY_PGNO(dst,src) dst = src
797 #if SIZE_MAX > 4294967295UL
798 #define COPY_PGNO(dst,src) do { \
799 unsigned short *s, *d; \
800 s = (unsigned short *)&(src); \
801 d = (unsigned short *)&(dst); \
808 #define COPY_PGNO(dst,src) do { \
809 unsigned short *s, *d; \
810 s = (unsigned short *)&(src); \
811 d = (unsigned short *)&(dst); \
817 /** The address of a key in a LEAF2 page.
818 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
819 * There are no node headers, keys are stored contiguously.
821 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
823 /** Set the \b node's key into \b keyptr, if requested. */
824 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
825 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
827 /** Set the \b node's key into \b key. */
828 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
830 /** Information about a single database in the environment. */
831 typedef struct MDB_db {
832 uint32_t md_pad; /**< also ksize for LEAF2 pages */
833 uint16_t md_flags; /**< @ref mdb_dbi_open */
834 uint16_t md_depth; /**< depth of this tree */
835 pgno_t md_branch_pages; /**< number of internal pages */
836 pgno_t md_leaf_pages; /**< number of leaf pages */
837 pgno_t md_overflow_pages; /**< number of overflow pages */
838 size_t md_entries; /**< number of data items */
839 pgno_t md_root; /**< the root page of this tree */
842 /** mdb_dbi_open flags */
843 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
844 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
845 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
846 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
848 /** Handle for the DB used to track free pages. */
850 /** Handle for the default DB. */
853 /** Meta page content.
854 * A meta page is the start point for accessing a database snapshot.
855 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
857 typedef struct MDB_meta {
858 /** Stamp identifying this as an LMDB file. It must be set
861 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
863 void *mm_address; /**< address for fixed mapping */
864 size_t mm_mapsize; /**< size of mmap region */
865 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
866 /** The size of pages used in this DB */
867 #define mm_psize mm_dbs[0].md_pad
868 /** Any persistent environment flags. @ref mdb_env */
869 #define mm_flags mm_dbs[0].md_flags
870 pgno_t mm_last_pg; /**< last used page in file */
871 txnid_t mm_txnid; /**< txnid that committed this page */
874 /** Buffer for a stack-allocated meta page.
875 * The members define size and alignment, and silence type
876 * aliasing warnings. They are not used directly; that could
877 * mean incorrectly using several union members in parallel.
879 typedef union MDB_metabuf {
882 char mm_pad[PAGEHDRSZ];
887 /** Auxiliary DB info.
888 * The information here is mostly static/read-only. There is
889 * only a single copy of this record in the environment.
891 typedef struct MDB_dbx {
892 MDB_val md_name; /**< name of the database */
893 MDB_cmp_func *md_cmp; /**< function for comparing keys */
894 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
895 MDB_rel_func *md_rel; /**< user relocate function */
896 void *md_relctx; /**< user-provided context for md_rel */
899 /** A database transaction.
900 * Every operation requires a transaction handle.
903 MDB_txn *mt_parent; /**< parent of a nested txn */
904 MDB_txn *mt_child; /**< nested txn under this txn */
905 pgno_t mt_next_pgno; /**< next unallocated page */
906 /** The ID of this transaction. IDs are integers incrementing from 1.
907 * Only committed write transactions increment the ID. If a transaction
908 * aborts, the ID may be re-used by the next writer.
911 MDB_env *mt_env; /**< the DB environment */
912 /** The list of pages that became unused during this transaction.
915 /** The list of loose pages that became unused and may be reused
916 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
918 MDB_page *mt_loose_pgs;
919 /** The sorted list of dirty pages we temporarily wrote to disk
920 * because the dirty list was full. page numbers in here are
921 * shifted left by 1, deleted slots have the LSB set.
923 MDB_IDL mt_spill_pgs;
925 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
927 /** For read txns: This thread/txn's reader table slot, or NULL. */
930 /** Array of records for each DB known in the environment. */
932 /** Array of MDB_db records for each known DB */
934 /** @defgroup mt_dbflag Transaction DB Flags
938 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
939 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
940 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
941 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
943 /** In write txns, array of cursors for each DB */
944 MDB_cursor **mt_cursors;
945 /** Array of flags for each DB */
946 unsigned char *mt_dbflags;
947 /** Number of DB records in use. This number only ever increments;
948 * we don't decrement it when individual DB handles are closed.
952 /** @defgroup mdb_txn Transaction Flags
956 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
957 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
958 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
959 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
961 unsigned int mt_flags; /**< @ref mdb_txn */
962 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
963 * Includes ancestor txns' dirty pages not hidden by other txns'
964 * dirty/spilled pages. Thus commit(nested txn) has room to merge
965 * dirty_list into mt_parent after freeing hidden mt_parent pages.
967 unsigned int mt_dirty_room;
970 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
971 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
972 * raise this on a 64 bit machine.
974 #define CURSOR_STACK 32
978 /** Cursors are used for all DB operations.
979 * A cursor holds a path of (page pointer, key index) from the DB
980 * root to a position in the DB, plus other state. #MDB_DUPSORT
981 * cursors include an xcursor to the current data item. Write txns
982 * track their cursors and keep them up to date when data moves.
983 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
984 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
987 /** Next cursor on this DB in this txn */
989 /** Backup of the original cursor if this cursor is a shadow */
990 MDB_cursor *mc_backup;
991 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
992 struct MDB_xcursor *mc_xcursor;
993 /** The transaction that owns this cursor */
995 /** The database handle this cursor operates on */
997 /** The database record for this cursor */
999 /** The database auxiliary record for this cursor */
1001 /** The @ref mt_dbflag for this database */
1002 unsigned char *mc_dbflag;
1003 unsigned short mc_snum; /**< number of pushed pages */
1004 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1005 /** @defgroup mdb_cursor Cursor Flags
1007 * Cursor state flags.
1010 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1011 #define C_EOF 0x02 /**< No more data */
1012 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1013 #define C_DEL 0x08 /**< last op was a cursor_del */
1014 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1015 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1017 unsigned int mc_flags; /**< @ref mdb_cursor */
1018 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1019 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1022 /** Context for sorted-dup records.
1023 * We could have gone to a fully recursive design, with arbitrarily
1024 * deep nesting of sub-databases. But for now we only handle these
1025 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1027 typedef struct MDB_xcursor {
1028 /** A sub-cursor for traversing the Dup DB */
1029 MDB_cursor mx_cursor;
1030 /** The database record for this Dup DB */
1032 /** The auxiliary DB record for this Dup DB */
1034 /** The @ref mt_dbflag for this Dup DB */
1035 unsigned char mx_dbflag;
1038 /** State of FreeDB old pages, stored in the MDB_env */
1039 typedef struct MDB_pgstate {
1040 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1041 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1044 /** The database environment. */
1046 HANDLE me_fd; /**< The main data file */
1047 HANDLE me_lfd; /**< The lock file */
1048 HANDLE me_mfd; /**< just for writing the meta pages */
1049 /** Failed to update the meta page. Probably an I/O error. */
1050 #define MDB_FATAL_ERROR 0x80000000U
1051 /** Some fields are initialized. */
1052 #define MDB_ENV_ACTIVE 0x20000000U
1053 /** me_txkey is set */
1054 #define MDB_ENV_TXKEY 0x10000000U
1055 uint32_t me_flags; /**< @ref mdb_env */
1056 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1057 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1058 unsigned int me_maxreaders; /**< size of the reader table */
1059 unsigned int me_numreaders; /**< max numreaders set by this env */
1060 MDB_dbi me_numdbs; /**< number of DBs opened */
1061 MDB_dbi me_maxdbs; /**< size of the DB table */
1062 MDB_PID_T me_pid; /**< process ID of this env */
1063 char *me_path; /**< path to the DB files */
1064 char *me_map; /**< the memory map of the data file */
1065 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1066 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1067 void *me_pbuf; /**< scratch area for DUPSORT put() */
1068 MDB_txn *me_txn; /**< current write transaction */
1069 size_t me_mapsize; /**< size of the data memory map */
1070 off_t me_size; /**< current file size */
1071 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1072 MDB_dbx *me_dbxs; /**< array of static DB info */
1073 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1074 pthread_key_t me_txkey; /**< thread-key for readers */
1075 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1076 # define me_pglast me_pgstate.mf_pglast
1077 # define me_pghead me_pgstate.mf_pghead
1078 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1079 /** IDL of pages that became unused in a write txn */
1080 MDB_IDL me_free_pgs;
1081 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1082 MDB_ID2L me_dirty_list;
1083 /** Max number of freelist items that can fit in a single overflow page */
1085 /** Max size of a node on a page */
1086 unsigned int me_nodemax;
1087 #if !(MDB_MAXKEYSIZE)
1088 unsigned int me_maxkey; /**< max size of a key */
1090 int me_live_reader; /**< have liveness lock in reader table */
1092 int me_pidquery; /**< Used in OpenProcess */
1093 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1095 #elif defined(MDB_USE_POSIX_SEM)
1096 sem_t *me_rmutex; /* Shared mutexes are not supported */
1099 void *me_userctx; /**< User-settable context */
1100 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1103 /** Nested transaction */
1104 typedef struct MDB_ntxn {
1105 MDB_txn mnt_txn; /**< the transaction */
1106 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1109 /** max number of pages to commit in one writev() call */
1110 #define MDB_COMMIT_PAGES 64
1111 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1112 #undef MDB_COMMIT_PAGES
1113 #define MDB_COMMIT_PAGES IOV_MAX
1116 /** max bytes to write in one call */
1117 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1119 /** Check \b txn and \b dbi arguments to a function */
1120 #define TXN_DBI_EXIST(txn, dbi) \
1121 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1123 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1124 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1125 static int mdb_page_touch(MDB_cursor *mc);
1127 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1128 static int mdb_page_search_root(MDB_cursor *mc,
1129 MDB_val *key, int modify);
1130 #define MDB_PS_MODIFY 1
1131 #define MDB_PS_ROOTONLY 2
1132 #define MDB_PS_FIRST 4
1133 #define MDB_PS_LAST 8
1134 static int mdb_page_search(MDB_cursor *mc,
1135 MDB_val *key, int flags);
1136 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1138 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1139 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1140 pgno_t newpgno, unsigned int nflags);
1142 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1143 static int mdb_env_pick_meta(const MDB_env *env);
1144 static int mdb_env_write_meta(MDB_txn *txn);
1145 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1146 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1148 static void mdb_env_close0(MDB_env *env, int excl);
1150 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1151 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1152 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1153 static void mdb_node_del(MDB_cursor *mc, int ksize);
1154 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1155 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1156 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1157 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1158 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1160 static int mdb_rebalance(MDB_cursor *mc);
1161 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1163 static void mdb_cursor_pop(MDB_cursor *mc);
1164 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1166 static int mdb_cursor_del0(MDB_cursor *mc);
1167 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1168 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1169 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1170 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1171 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1173 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1174 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1176 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1177 static void mdb_xcursor_init0(MDB_cursor *mc);
1178 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1180 static int mdb_drop0(MDB_cursor *mc, int subs);
1181 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1184 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1188 static SECURITY_DESCRIPTOR mdb_null_sd;
1189 static SECURITY_ATTRIBUTES mdb_all_sa;
1190 static int mdb_sec_inited;
1193 /** Return the library version info. */
1195 mdb_version(int *major, int *minor, int *patch)
1197 if (major) *major = MDB_VERSION_MAJOR;
1198 if (minor) *minor = MDB_VERSION_MINOR;
1199 if (patch) *patch = MDB_VERSION_PATCH;
1200 return MDB_VERSION_STRING;
1203 /** Table of descriptions for LMDB @ref errors */
1204 static char *const mdb_errstr[] = {
1205 "MDB_KEYEXIST: Key/data pair already exists",
1206 "MDB_NOTFOUND: No matching key/data pair found",
1207 "MDB_PAGE_NOTFOUND: Requested page not found",
1208 "MDB_CORRUPTED: Located page was wrong type",
1209 "MDB_PANIC: Update of meta page failed",
1210 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1211 "MDB_INVALID: File is not an LMDB file",
1212 "MDB_MAP_FULL: Environment mapsize limit reached",
1213 "MDB_DBS_FULL: Environment maxdbs limit reached",
1214 "MDB_READERS_FULL: Environment maxreaders limit reached",
1215 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1216 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1217 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1218 "MDB_PAGE_FULL: Internal error - page has no more space",
1219 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1220 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1221 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1222 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1223 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1227 mdb_strerror(int err)
1231 return ("Successful return: 0");
1233 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1234 i = err - MDB_KEYEXIST;
1235 return mdb_errstr[i];
1238 return strerror(err);
1241 /** assert(3) variant in cursor context */
1242 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1243 /** assert(3) variant in transaction context */
1244 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1245 /** assert(3) variant in environment context */
1246 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1249 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1250 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1253 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1254 const char *func, const char *file, int line)
1257 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1258 file, line, expr_txt, func);
1259 if (env->me_assert_func)
1260 env->me_assert_func(env, buf);
1261 fprintf(stderr, "%s\n", buf);
1265 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1269 /** Return the page number of \b mp which may be sub-page, for debug output */
1271 mdb_dbg_pgno(MDB_page *mp)
1274 COPY_PGNO(ret, mp->mp_pgno);
1278 /** Display a key in hexadecimal and return the address of the result.
1279 * @param[in] key the key to display
1280 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1281 * @return The key in hexadecimal form.
1284 mdb_dkey(MDB_val *key, char *buf)
1287 unsigned char *c = key->mv_data;
1293 if (key->mv_size > DKBUF_MAXKEYSIZE)
1294 return "MDB_MAXKEYSIZE";
1295 /* may want to make this a dynamic check: if the key is mostly
1296 * printable characters, print it as-is instead of converting to hex.
1300 for (i=0; i<key->mv_size; i++)
1301 ptr += sprintf(ptr, "%02x", *c++);
1303 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1309 mdb_leafnode_type(MDB_node *n)
1311 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1312 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1313 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1316 /** Display all the keys in the page. */
1318 mdb_page_list(MDB_page *mp)
1320 pgno_t pgno = mdb_dbg_pgno(mp);
1321 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1323 unsigned int i, nkeys, nsize, total = 0;
1327 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1328 case P_BRANCH: type = "Branch page"; break;
1329 case P_LEAF: type = "Leaf page"; break;
1330 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1331 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1332 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1334 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1335 pgno, mp->mp_pages, state);
1338 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1339 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1342 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1346 nkeys = NUMKEYS(mp);
1347 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1349 for (i=0; i<nkeys; i++) {
1350 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1351 key.mv_size = nsize = mp->mp_pad;
1352 key.mv_data = LEAF2KEY(mp, i, nsize);
1354 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1357 node = NODEPTR(mp, i);
1358 key.mv_size = node->mn_ksize;
1359 key.mv_data = node->mn_data;
1360 nsize = NODESIZE + key.mv_size;
1361 if (IS_BRANCH(mp)) {
1362 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1366 if (F_ISSET(node->mn_flags, F_BIGDATA))
1367 nsize += sizeof(pgno_t);
1369 nsize += NODEDSZ(node);
1371 nsize += sizeof(indx_t);
1372 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1373 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1375 total = EVEN(total);
1377 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1378 IS_LEAF2(mp) ? PAGEHDRSZ : mp->mp_lower, total, SIZELEFT(mp));
1382 mdb_cursor_chk(MDB_cursor *mc)
1388 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1389 for (i=0; i<mc->mc_top; i++) {
1391 node = NODEPTR(mp, mc->mc_ki[i]);
1392 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1395 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1401 /** Count all the pages in each DB and in the freelist
1402 * and make sure it matches the actual number of pages
1404 * All named DBs must be open for a correct count.
1406 static void mdb_audit(MDB_txn *txn)
1410 MDB_ID freecount, count;
1415 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1416 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1417 freecount += *(MDB_ID *)data.mv_data;
1418 mdb_tassert(txn, rc == MDB_NOTFOUND);
1421 for (i = 0; i<txn->mt_numdbs; i++) {
1423 if (!(txn->mt_dbflags[i] & DB_VALID))
1425 mdb_cursor_init(&mc, txn, i, &mx);
1426 if (txn->mt_dbs[i].md_root == P_INVALID)
1428 count += txn->mt_dbs[i].md_branch_pages +
1429 txn->mt_dbs[i].md_leaf_pages +
1430 txn->mt_dbs[i].md_overflow_pages;
1431 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1432 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1433 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1436 mp = mc.mc_pg[mc.mc_top];
1437 for (j=0; j<NUMKEYS(mp); j++) {
1438 MDB_node *leaf = NODEPTR(mp, j);
1439 if (leaf->mn_flags & F_SUBDATA) {
1441 memcpy(&db, NODEDATA(leaf), sizeof(db));
1442 count += db.md_branch_pages + db.md_leaf_pages +
1443 db.md_overflow_pages;
1447 mdb_tassert(txn, rc == MDB_NOTFOUND);
1450 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1451 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1452 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1458 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1460 return txn->mt_dbxs[dbi].md_cmp(a, b);
1464 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1466 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1469 /** Allocate memory for a page.
1470 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1473 mdb_page_malloc(MDB_txn *txn, unsigned num)
1475 MDB_env *env = txn->mt_env;
1476 MDB_page *ret = env->me_dpages;
1477 size_t psize = env->me_psize, sz = psize, off;
1478 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1479 * For a single page alloc, we init everything after the page header.
1480 * For multi-page, we init the final page; if the caller needed that
1481 * many pages they will be filling in at least up to the last page.
1485 VGMEMP_ALLOC(env, ret, sz);
1486 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1487 env->me_dpages = ret->mp_next;
1490 psize -= off = PAGEHDRSZ;
1495 if ((ret = malloc(sz)) != NULL) {
1496 VGMEMP_ALLOC(env, ret, sz);
1497 if (!(env->me_flags & MDB_NOMEMINIT)) {
1498 memset((char *)ret + off, 0, psize);
1502 txn->mt_flags |= MDB_TXN_ERROR;
1506 /** Free a single page.
1507 * Saves single pages to a list, for future reuse.
1508 * (This is not used for multi-page overflow pages.)
1511 mdb_page_free(MDB_env *env, MDB_page *mp)
1513 mp->mp_next = env->me_dpages;
1514 VGMEMP_FREE(env, mp);
1515 env->me_dpages = mp;
1518 /** Free a dirty page */
1520 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1522 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1523 mdb_page_free(env, dp);
1525 /* large pages just get freed directly */
1526 VGMEMP_FREE(env, dp);
1531 /** Return all dirty pages to dpage list */
1533 mdb_dlist_free(MDB_txn *txn)
1535 MDB_env *env = txn->mt_env;
1536 MDB_ID2L dl = txn->mt_u.dirty_list;
1537 unsigned i, n = dl[0].mid;
1539 for (i = 1; i <= n; i++) {
1540 mdb_dpage_free(env, dl[i].mptr);
1545 /** Loosen or free a single page.
1546 * Saves single pages to a list for future reuse
1547 * in this same txn. It has been pulled from the freeDB
1548 * and already resides on the dirty list, but has been
1549 * deleted. Use these pages first before pulling again
1552 * If the page wasn't dirtied in this txn, just add it
1553 * to this txn's free list.
1556 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1559 pgno_t pgno = mp->mp_pgno;
1561 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1562 if (mc->mc_txn->mt_parent) {
1563 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1564 /* If txn has a parent, make sure the page is in our
1568 unsigned x = mdb_mid2l_search(dl, pgno);
1569 if (x <= dl[0].mid && dl[x].mid == pgno) {
1570 if (mp != dl[x].mptr) { /* bad cursor? */
1571 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1572 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1573 return MDB_CORRUPTED;
1580 /* no parent txn, so it's just ours */
1585 NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
1586 mc->mc_txn->mt_loose_pgs = mp;
1587 mp->mp_flags |= P_LOOSE;
1589 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1597 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1598 * @param[in] mc A cursor handle for the current operation.
1599 * @param[in] pflags Flags of the pages to update:
1600 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1601 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1602 * @return 0 on success, non-zero on failure.
1605 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1607 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1608 MDB_txn *txn = mc->mc_txn;
1614 int rc = MDB_SUCCESS, level;
1616 /* Mark pages seen by cursors */
1617 if (mc->mc_flags & C_UNTRACK)
1618 mc = NULL; /* will find mc in mt_cursors */
1619 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1620 for (; mc; mc=mc->mc_next) {
1621 if (!(mc->mc_flags & C_INITIALIZED))
1623 for (m3 = mc;; m3 = &mx->mx_cursor) {
1625 for (j=0; j<m3->mc_snum; j++) {
1627 if ((mp->mp_flags & Mask) == pflags)
1628 mp->mp_flags ^= P_KEEP;
1630 mx = m3->mc_xcursor;
1631 /* Proceed to mx if it is at a sub-database */
1632 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1634 if (! (mp && (mp->mp_flags & P_LEAF)))
1636 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1637 if (!(leaf->mn_flags & F_SUBDATA))
1645 /* Loose pages shouldn't be spilled */
1646 for (dp = txn->mt_loose_pgs; dp; dp = NEXT_LOOSE_PAGE(dp)) {
1647 if ((dp->mp_flags & Mask) == pflags)
1648 dp->mp_flags ^= P_KEEP;
1652 /* Mark dirty root pages */
1653 for (i=0; i<txn->mt_numdbs; i++) {
1654 if (txn->mt_dbflags[i] & DB_DIRTY) {
1655 pgno_t pgno = txn->mt_dbs[i].md_root;
1656 if (pgno == P_INVALID)
1658 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1660 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1661 dp->mp_flags ^= P_KEEP;
1669 static int mdb_page_flush(MDB_txn *txn, int keep);
1671 /** Spill pages from the dirty list back to disk.
1672 * This is intended to prevent running into #MDB_TXN_FULL situations,
1673 * but note that they may still occur in a few cases:
1674 * 1) our estimate of the txn size could be too small. Currently this
1675 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1676 * 2) child txns may run out of space if their parents dirtied a
1677 * lot of pages and never spilled them. TODO: we probably should do
1678 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1679 * the parent's dirty_room is below a given threshold.
1681 * Otherwise, if not using nested txns, it is expected that apps will
1682 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1683 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1684 * If the txn never references them again, they can be left alone.
1685 * If the txn only reads them, they can be used without any fuss.
1686 * If the txn writes them again, they can be dirtied immediately without
1687 * going thru all of the work of #mdb_page_touch(). Such references are
1688 * handled by #mdb_page_unspill().
1690 * Also note, we never spill DB root pages, nor pages of active cursors,
1691 * because we'll need these back again soon anyway. And in nested txns,
1692 * we can't spill a page in a child txn if it was already spilled in a
1693 * parent txn. That would alter the parent txns' data even though
1694 * the child hasn't committed yet, and we'd have no way to undo it if
1695 * the child aborted.
1697 * @param[in] m0 cursor A cursor handle identifying the transaction and
1698 * database for which we are checking space.
1699 * @param[in] key For a put operation, the key being stored.
1700 * @param[in] data For a put operation, the data being stored.
1701 * @return 0 on success, non-zero on failure.
1704 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1706 MDB_txn *txn = m0->mc_txn;
1708 MDB_ID2L dl = txn->mt_u.dirty_list;
1709 unsigned int i, j, need;
1712 if (m0->mc_flags & C_SUB)
1715 /* Estimate how much space this op will take */
1716 i = m0->mc_db->md_depth;
1717 /* Named DBs also dirty the main DB */
1718 if (m0->mc_dbi > MAIN_DBI)
1719 i += txn->mt_dbs[MAIN_DBI].md_depth;
1720 /* For puts, roughly factor in the key+data size */
1722 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1723 i += i; /* double it for good measure */
1726 if (txn->mt_dirty_room > i)
1729 if (!txn->mt_spill_pgs) {
1730 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1731 if (!txn->mt_spill_pgs)
1734 /* purge deleted slots */
1735 MDB_IDL sl = txn->mt_spill_pgs;
1736 unsigned int num = sl[0];
1738 for (i=1; i<=num; i++) {
1745 /* Preserve pages which may soon be dirtied again */
1746 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1749 /* Less aggressive spill - we originally spilled the entire dirty list,
1750 * with a few exceptions for cursor pages and DB root pages. But this
1751 * turns out to be a lot of wasted effort because in a large txn many
1752 * of those pages will need to be used again. So now we spill only 1/8th
1753 * of the dirty pages. Testing revealed this to be a good tradeoff,
1754 * better than 1/2, 1/4, or 1/10.
1756 if (need < MDB_IDL_UM_MAX / 8)
1757 need = MDB_IDL_UM_MAX / 8;
1759 /* Save the page IDs of all the pages we're flushing */
1760 /* flush from the tail forward, this saves a lot of shifting later on. */
1761 for (i=dl[0].mid; i && need; i--) {
1762 MDB_ID pn = dl[i].mid << 1;
1764 if (dp->mp_flags & P_KEEP)
1766 /* Can't spill twice, make sure it's not already in a parent's
1769 if (txn->mt_parent) {
1771 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1772 if (tx2->mt_spill_pgs) {
1773 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1774 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1775 dp->mp_flags |= P_KEEP;
1783 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1787 mdb_midl_sort(txn->mt_spill_pgs);
1789 /* Flush the spilled part of dirty list */
1790 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1793 /* Reset any dirty pages we kept that page_flush didn't see */
1794 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1797 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1801 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1803 mdb_find_oldest(MDB_txn *txn)
1806 txnid_t mr, oldest = txn->mt_txnid - 1;
1807 if (txn->mt_env->me_txns) {
1808 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1809 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1820 /** Add a page to the txn's dirty list */
1822 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1825 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1827 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1828 insert = mdb_mid2l_append;
1830 insert = mdb_mid2l_insert;
1832 mid.mid = mp->mp_pgno;
1834 rc = insert(txn->mt_u.dirty_list, &mid);
1835 mdb_tassert(txn, rc == 0);
1836 txn->mt_dirty_room--;
1839 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1840 * me_pghead and mt_next_pgno.
1842 * If there are free pages available from older transactions, they
1843 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1844 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1845 * and move me_pglast to say which records were consumed. Only this
1846 * function can create me_pghead and move me_pglast/mt_next_pgno.
1847 * @param[in] mc cursor A cursor handle identifying the transaction and
1848 * database for which we are allocating.
1849 * @param[in] num the number of pages to allocate.
1850 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1851 * will always be satisfied by a single contiguous chunk of memory.
1852 * @return 0 on success, non-zero on failure.
1855 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1857 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1858 /* Get at most <Max_retries> more freeDB records once me_pghead
1859 * has enough pages. If not enough, use new pages from the map.
1860 * If <Paranoid> and mc is updating the freeDB, only get new
1861 * records if me_pghead is empty. Then the freelist cannot play
1862 * catch-up with itself by growing while trying to save it.
1864 enum { Paranoid = 1, Max_retries = 500 };
1866 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1868 int rc, retry = num * 20;
1869 MDB_txn *txn = mc->mc_txn;
1870 MDB_env *env = txn->mt_env;
1871 pgno_t pgno, *mop = env->me_pghead;
1872 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1874 txnid_t oldest = 0, last;
1878 /* If there are any loose pages, just use them */
1879 if (num == 1 && txn->mt_loose_pgs) {
1880 np = txn->mt_loose_pgs;
1881 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1888 /* If our dirty list is already full, we can't do anything */
1889 if (txn->mt_dirty_room == 0) {
1894 for (op = MDB_FIRST;; op = MDB_NEXT) {
1897 pgno_t *idl, old_id, new_id;
1899 /* Seek a big enough contiguous page range. Prefer
1900 * pages at the tail, just truncating the list.
1906 if (mop[i-n2] == pgno+n2)
1913 if (op == MDB_FIRST) { /* 1st iteration */
1914 /* Prepare to fetch more and coalesce */
1915 oldest = mdb_find_oldest(txn);
1916 last = env->me_pglast;
1917 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1920 key.mv_data = &last; /* will look up last+1 */
1921 key.mv_size = sizeof(last);
1923 if (Paranoid && mc->mc_dbi == FREE_DBI)
1926 if (Paranoid && retry < 0 && mop_len)
1930 /* Do not fetch more if the record will be too recent */
1933 rc = mdb_cursor_get(&m2, &key, NULL, op);
1935 if (rc == MDB_NOTFOUND)
1939 last = *(txnid_t*)key.mv_data;
1942 np = m2.mc_pg[m2.mc_top];
1943 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1944 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1947 idl = (MDB_ID *) data.mv_data;
1950 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
1955 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1957 mop = env->me_pghead;
1959 env->me_pglast = last;
1961 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1962 last, txn->mt_dbs[FREE_DBI].md_root, i));
1964 DPRINTF(("IDL %"Z"u", idl[k]));
1966 /* Merge in descending sorted order */
1969 mop[0] = (pgno_t)-1;
1973 for (; old_id < new_id; old_id = mop[--j])
1980 /* Use new pages from the map when nothing suitable in the freeDB */
1982 pgno = txn->mt_next_pgno;
1983 if (pgno + num >= env->me_maxpg) {
1984 DPUTS("DB size maxed out");
1990 if (env->me_flags & MDB_WRITEMAP) {
1991 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1993 if (!(np = mdb_page_malloc(txn, num))) {
1999 mop[0] = mop_len -= num;
2000 /* Move any stragglers down */
2001 for (j = i-num; j < mop_len; )
2002 mop[++j] = mop[++i];
2004 txn->mt_next_pgno = pgno + num;
2007 mdb_page_dirty(txn, np);
2013 txn->mt_flags |= MDB_TXN_ERROR;
2017 /** Copy the used portions of a non-overflow page.
2018 * @param[in] dst page to copy into
2019 * @param[in] src page to copy from
2020 * @param[in] psize size of a page
2023 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2025 enum { Align = sizeof(pgno_t) };
2026 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2028 /* If page isn't full, just copy the used portion. Adjust
2029 * alignment so memcpy may copy words instead of bytes.
2031 if ((unused &= -Align) && !IS_LEAF2(src)) {
2033 memcpy(dst, src, (lower + (Align-1)) & -Align);
2034 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2037 memcpy(dst, src, psize - unused);
2041 /** Pull a page off the txn's spill list, if present.
2042 * If a page being referenced was spilled to disk in this txn, bring
2043 * it back and make it dirty/writable again.
2044 * @param[in] txn the transaction handle.
2045 * @param[in] mp the page being referenced. It must not be dirty.
2046 * @param[out] ret the writable page, if any. ret is unchanged if
2047 * mp wasn't spilled.
2050 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2052 MDB_env *env = txn->mt_env;
2055 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2057 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2058 if (!tx2->mt_spill_pgs)
2060 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2061 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2064 if (txn->mt_dirty_room == 0)
2065 return MDB_TXN_FULL;
2066 if (IS_OVERFLOW(mp))
2070 if (env->me_flags & MDB_WRITEMAP) {
2073 np = mdb_page_malloc(txn, num);
2077 memcpy(np, mp, num * env->me_psize);
2079 mdb_page_copy(np, mp, env->me_psize);
2082 /* If in current txn, this page is no longer spilled.
2083 * If it happens to be the last page, truncate the spill list.
2084 * Otherwise mark it as deleted by setting the LSB.
2086 if (x == txn->mt_spill_pgs[0])
2087 txn->mt_spill_pgs[0]--;
2089 txn->mt_spill_pgs[x] |= 1;
2090 } /* otherwise, if belonging to a parent txn, the
2091 * page remains spilled until child commits
2094 mdb_page_dirty(txn, np);
2095 np->mp_flags |= P_DIRTY;
2103 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2104 * @param[in] mc cursor pointing to the page to be touched
2105 * @return 0 on success, non-zero on failure.
2108 mdb_page_touch(MDB_cursor *mc)
2110 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2111 MDB_txn *txn = mc->mc_txn;
2112 MDB_cursor *m2, *m3;
2116 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2117 if (txn->mt_flags & MDB_TXN_SPILLS) {
2119 rc = mdb_page_unspill(txn, mp, &np);
2125 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2126 (rc = mdb_page_alloc(mc, 1, &np)))
2129 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2130 mp->mp_pgno, pgno));
2131 mdb_cassert(mc, mp->mp_pgno != pgno);
2132 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2133 /* Update the parent page, if any, to point to the new page */
2135 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2136 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2137 SETPGNO(node, pgno);
2139 mc->mc_db->md_root = pgno;
2141 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2142 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2144 /* If txn has a parent, make sure the page is in our
2148 unsigned x = mdb_mid2l_search(dl, pgno);
2149 if (x <= dl[0].mid && dl[x].mid == pgno) {
2150 if (mp != dl[x].mptr) { /* bad cursor? */
2151 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2152 txn->mt_flags |= MDB_TXN_ERROR;
2153 return MDB_CORRUPTED;
2158 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2160 np = mdb_page_malloc(txn, 1);
2165 rc = mdb_mid2l_insert(dl, &mid);
2166 mdb_cassert(mc, rc == 0);
2171 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2173 np->mp_flags |= P_DIRTY;
2176 /* Adjust cursors pointing to mp */
2177 mc->mc_pg[mc->mc_top] = np;
2178 m2 = txn->mt_cursors[mc->mc_dbi];
2179 if (mc->mc_flags & C_SUB) {
2180 for (; m2; m2=m2->mc_next) {
2181 m3 = &m2->mc_xcursor->mx_cursor;
2182 if (m3->mc_snum < mc->mc_snum) continue;
2183 if (m3->mc_pg[mc->mc_top] == mp)
2184 m3->mc_pg[mc->mc_top] = np;
2187 for (; m2; m2=m2->mc_next) {
2188 if (m2->mc_snum < mc->mc_snum) continue;
2189 if (m2->mc_pg[mc->mc_top] == mp) {
2190 m2->mc_pg[mc->mc_top] = np;
2191 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2193 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2195 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2196 if (!(leaf->mn_flags & F_SUBDATA))
2197 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2205 txn->mt_flags |= MDB_TXN_ERROR;
2210 mdb_env_sync(MDB_env *env, int force)
2213 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2214 if (env->me_flags & MDB_WRITEMAP) {
2215 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2216 ? MS_ASYNC : MS_SYNC;
2217 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2220 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2224 if (MDB_FDATASYNC(env->me_fd))
2231 /** Back up parent txn's cursors, then grab the originals for tracking */
2233 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2235 MDB_cursor *mc, *bk;
2240 for (i = src->mt_numdbs; --i >= 0; ) {
2241 if ((mc = src->mt_cursors[i]) != NULL) {
2242 size = sizeof(MDB_cursor);
2244 size += sizeof(MDB_xcursor);
2245 for (; mc; mc = bk->mc_next) {
2251 mc->mc_db = &dst->mt_dbs[i];
2252 /* Kill pointers into src - and dst to reduce abuse: The
2253 * user may not use mc until dst ends. Otherwise we'd...
2255 mc->mc_txn = NULL; /* ...set this to dst */
2256 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2257 if ((mx = mc->mc_xcursor) != NULL) {
2258 *(MDB_xcursor *)(bk+1) = *mx;
2259 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2261 mc->mc_next = dst->mt_cursors[i];
2262 dst->mt_cursors[i] = mc;
2269 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2270 * @param[in] txn the transaction handle.
2271 * @param[in] merge true to keep changes to parent cursors, false to revert.
2272 * @return 0 on success, non-zero on failure.
2275 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2277 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2281 for (i = txn->mt_numdbs; --i >= 0; ) {
2282 for (mc = cursors[i]; mc; mc = next) {
2284 if ((bk = mc->mc_backup) != NULL) {
2286 /* Commit changes to parent txn */
2287 mc->mc_next = bk->mc_next;
2288 mc->mc_backup = bk->mc_backup;
2289 mc->mc_txn = bk->mc_txn;
2290 mc->mc_db = bk->mc_db;
2291 mc->mc_dbflag = bk->mc_dbflag;
2292 if ((mx = mc->mc_xcursor) != NULL)
2293 mx->mx_cursor.mc_txn = bk->mc_txn;
2295 /* Abort nested txn */
2297 if ((mx = mc->mc_xcursor) != NULL)
2298 *mx = *(MDB_xcursor *)(bk+1);
2302 /* Only malloced cursors are permanently tracked. */
2310 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2313 mdb_txn_reset0(MDB_txn *txn, const char *act);
2315 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2321 Pidset = F_SETLK, Pidcheck = F_GETLK
2325 /** Set or check a pid lock. Set returns 0 on success.
2326 * Check returns 0 if the process is certainly dead, nonzero if it may
2327 * be alive (the lock exists or an error happened so we do not know).
2329 * On Windows Pidset is a no-op, we merely check for the existence
2330 * of the process with the given pid. On POSIX we use a single byte
2331 * lock on the lockfile, set at an offset equal to the pid.
2334 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2336 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2339 if (op == Pidcheck) {
2340 h = OpenProcess(env->me_pidquery, FALSE, pid);
2341 /* No documented "no such process" code, but other program use this: */
2343 return ErrCode() != ERROR_INVALID_PARAMETER;
2344 /* A process exists until all handles to it close. Has it exited? */
2345 ret = WaitForSingleObject(h, 0) != 0;
2352 struct flock lock_info;
2353 memset(&lock_info, 0, sizeof(lock_info));
2354 lock_info.l_type = F_WRLCK;
2355 lock_info.l_whence = SEEK_SET;
2356 lock_info.l_start = pid;
2357 lock_info.l_len = 1;
2358 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2359 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2361 } else if ((rc = ErrCode()) == EINTR) {
2369 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2370 * @param[in] txn the transaction handle to initialize
2371 * @return 0 on success, non-zero on failure.
2374 mdb_txn_renew0(MDB_txn *txn)
2376 MDB_env *env = txn->mt_env;
2377 MDB_txninfo *ti = env->me_txns;
2381 int rc, new_notls = 0;
2384 txn->mt_numdbs = env->me_numdbs;
2385 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2387 if (txn->mt_flags & MDB_TXN_RDONLY) {
2389 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2390 txn->mt_txnid = meta->mm_txnid;
2391 txn->mt_u.reader = NULL;
2393 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2394 pthread_getspecific(env->me_txkey);
2396 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2397 return MDB_BAD_RSLOT;
2399 MDB_PID_T pid = env->me_pid;
2400 MDB_THR_T tid = pthread_self();
2402 if (!env->me_live_reader) {
2403 rc = mdb_reader_pid(env, Pidset, pid);
2406 env->me_live_reader = 1;
2410 nr = ti->mti_numreaders;
2411 for (i=0; i<nr; i++)
2412 if (ti->mti_readers[i].mr_pid == 0)
2414 if (i == env->me_maxreaders) {
2415 UNLOCK_MUTEX_R(env);
2416 return MDB_READERS_FULL;
2418 ti->mti_readers[i].mr_pid = pid;
2419 ti->mti_readers[i].mr_tid = tid;
2421 ti->mti_numreaders = ++nr;
2422 /* Save numreaders for un-mutexed mdb_env_close() */
2423 env->me_numreaders = nr;
2424 UNLOCK_MUTEX_R(env);
2426 r = &ti->mti_readers[i];
2427 new_notls = (env->me_flags & MDB_NOTLS);
2428 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2433 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2434 txn->mt_u.reader = r;
2435 meta = env->me_metas[txn->mt_txnid & 1];
2441 txn->mt_txnid = ti->mti_txnid;
2442 meta = env->me_metas[txn->mt_txnid & 1];
2444 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2445 txn->mt_txnid = meta->mm_txnid;
2449 if (txn->mt_txnid == mdb_debug_start)
2452 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2453 txn->mt_u.dirty_list = env->me_dirty_list;
2454 txn->mt_u.dirty_list[0].mid = 0;
2455 txn->mt_free_pgs = env->me_free_pgs;
2456 txn->mt_free_pgs[0] = 0;
2457 txn->mt_spill_pgs = NULL;
2461 /* Copy the DB info and flags */
2462 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2464 /* Moved to here to avoid a data race in read TXNs */
2465 txn->mt_next_pgno = meta->mm_last_pg+1;
2467 for (i=2; i<txn->mt_numdbs; i++) {
2468 x = env->me_dbflags[i];
2469 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2470 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2472 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2474 if (env->me_maxpg < txn->mt_next_pgno) {
2475 mdb_txn_reset0(txn, "renew0-mapfail");
2477 txn->mt_u.reader->mr_pid = 0;
2478 txn->mt_u.reader = NULL;
2480 return MDB_MAP_RESIZED;
2487 mdb_txn_renew(MDB_txn *txn)
2491 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2494 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2495 DPUTS("environment had fatal error, must shutdown!");
2499 rc = mdb_txn_renew0(txn);
2500 if (rc == MDB_SUCCESS) {
2501 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2502 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2503 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2509 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2513 int rc, size, tsize = sizeof(MDB_txn);
2515 if (env->me_flags & MDB_FATAL_ERROR) {
2516 DPUTS("environment had fatal error, must shutdown!");
2519 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2522 /* Nested transactions: Max 1 child, write txns only, no writemap */
2523 if (parent->mt_child ||
2524 (flags & MDB_RDONLY) ||
2525 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2526 (env->me_flags & MDB_WRITEMAP))
2528 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2530 tsize = sizeof(MDB_ntxn);
2532 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2533 if (!(flags & MDB_RDONLY))
2534 size += env->me_maxdbs * sizeof(MDB_cursor *);
2536 if ((txn = calloc(1, size)) == NULL) {
2537 DPRINTF(("calloc: %s", strerror(ErrCode())));
2540 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2541 if (flags & MDB_RDONLY) {
2542 txn->mt_flags |= MDB_TXN_RDONLY;
2543 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2545 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2546 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2552 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2553 if (!txn->mt_u.dirty_list ||
2554 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2556 free(txn->mt_u.dirty_list);
2560 txn->mt_txnid = parent->mt_txnid;
2561 txn->mt_dirty_room = parent->mt_dirty_room;
2562 txn->mt_u.dirty_list[0].mid = 0;
2563 txn->mt_spill_pgs = NULL;
2564 txn->mt_next_pgno = parent->mt_next_pgno;
2565 parent->mt_child = txn;
2566 txn->mt_parent = parent;
2567 txn->mt_numdbs = parent->mt_numdbs;
2568 txn->mt_flags = parent->mt_flags;
2569 txn->mt_dbxs = parent->mt_dbxs;
2570 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2571 /* Copy parent's mt_dbflags, but clear DB_NEW */
2572 for (i=0; i<txn->mt_numdbs; i++)
2573 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2575 ntxn = (MDB_ntxn *)txn;
2576 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2577 if (env->me_pghead) {
2578 size = MDB_IDL_SIZEOF(env->me_pghead);
2579 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2581 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2586 rc = mdb_cursor_shadow(parent, txn);
2588 mdb_txn_reset0(txn, "beginchild-fail");
2590 rc = mdb_txn_renew0(txn);
2596 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2597 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2598 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2605 mdb_txn_env(MDB_txn *txn)
2607 if(!txn) return NULL;
2611 /** Export or close DBI handles opened in this txn. */
2613 mdb_dbis_update(MDB_txn *txn, int keep)
2616 MDB_dbi n = txn->mt_numdbs;
2617 MDB_env *env = txn->mt_env;
2618 unsigned char *tdbflags = txn->mt_dbflags;
2620 for (i = n; --i >= 2;) {
2621 if (tdbflags[i] & DB_NEW) {
2623 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2625 char *ptr = env->me_dbxs[i].md_name.mv_data;
2626 env->me_dbxs[i].md_name.mv_data = NULL;
2627 env->me_dbxs[i].md_name.mv_size = 0;
2628 env->me_dbflags[i] = 0;
2633 if (keep && env->me_numdbs < n)
2637 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2638 * May be called twice for readonly txns: First reset it, then abort.
2639 * @param[in] txn the transaction handle to reset
2640 * @param[in] act why the transaction is being reset
2643 mdb_txn_reset0(MDB_txn *txn, const char *act)
2645 MDB_env *env = txn->mt_env;
2647 /* Close any DBI handles opened in this txn */
2648 mdb_dbis_update(txn, 0);
2650 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2651 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2652 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2654 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2655 if (txn->mt_u.reader) {
2656 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2657 if (!(env->me_flags & MDB_NOTLS))
2658 txn->mt_u.reader = NULL; /* txn does not own reader */
2660 txn->mt_numdbs = 0; /* close nothing if called again */
2661 txn->mt_dbxs = NULL; /* mark txn as reset */
2663 mdb_cursors_close(txn, 0);
2665 if (!(env->me_flags & MDB_WRITEMAP)) {
2666 mdb_dlist_free(txn);
2668 mdb_midl_free(env->me_pghead);
2670 if (txn->mt_parent) {
2671 txn->mt_parent->mt_child = NULL;
2672 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2673 mdb_midl_free(txn->mt_free_pgs);
2674 mdb_midl_free(txn->mt_spill_pgs);
2675 free(txn->mt_u.dirty_list);
2679 if (mdb_midl_shrink(&txn->mt_free_pgs))
2680 env->me_free_pgs = txn->mt_free_pgs;
2681 env->me_pghead = NULL;
2685 /* The writer mutex was locked in mdb_txn_begin. */
2687 UNLOCK_MUTEX_W(env);
2692 mdb_txn_reset(MDB_txn *txn)
2697 /* This call is only valid for read-only txns */
2698 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2701 mdb_txn_reset0(txn, "reset");
2705 mdb_txn_abort(MDB_txn *txn)
2711 mdb_txn_abort(txn->mt_child);
2713 mdb_txn_reset0(txn, "abort");
2714 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2715 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2716 txn->mt_u.reader->mr_pid = 0;
2721 /** Save the freelist as of this transaction to the freeDB.
2722 * This changes the freelist. Keep trying until it stabilizes.
2725 mdb_freelist_save(MDB_txn *txn)
2727 /* env->me_pghead[] can grow and shrink during this call.
2728 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2729 * Page numbers cannot disappear from txn->mt_free_pgs[].
2732 MDB_env *env = txn->mt_env;
2733 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2734 txnid_t pglast = 0, head_id = 0;
2735 pgno_t freecnt = 0, *free_pgs, *mop;
2736 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2738 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2740 if (env->me_pghead) {
2741 /* Make sure first page of freeDB is touched and on freelist */
2742 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2743 if (rc && rc != MDB_NOTFOUND)
2747 /* Dispose of loose pages. Usually they will have all
2748 * been used up by the time we get here.
2750 if (txn->mt_loose_pgs) {
2751 MDB_page *mp = txn->mt_loose_pgs;
2752 /* Just return them to freeDB */
2753 if (env->me_pghead) {
2755 mop = env->me_pghead;
2756 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2757 pgno_t pg = mp->mp_pgno;
2759 for (i = mop[0]; i && mop[i] < pg; i--)
2765 /* Oh well, they were wasted. Put on freelist */
2766 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2767 mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
2770 txn->mt_loose_pgs = NULL;
2773 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2774 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2775 ? SSIZE_MAX : maxfree_1pg;
2778 /* Come back here after each Put() in case freelist changed */
2783 /* If using records from freeDB which we have not yet
2784 * deleted, delete them and any we reserved for me_pghead.
2786 while (pglast < env->me_pglast) {
2787 rc = mdb_cursor_first(&mc, &key, NULL);
2790 pglast = head_id = *(txnid_t *)key.mv_data;
2791 total_room = head_room = 0;
2792 mdb_tassert(txn, pglast <= env->me_pglast);
2793 rc = mdb_cursor_del(&mc, 0);
2798 /* Save the IDL of pages freed by this txn, to a single record */
2799 if (freecnt < txn->mt_free_pgs[0]) {
2801 /* Make sure last page of freeDB is touched and on freelist */
2802 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2803 if (rc && rc != MDB_NOTFOUND)
2806 free_pgs = txn->mt_free_pgs;
2807 /* Write to last page of freeDB */
2808 key.mv_size = sizeof(txn->mt_txnid);
2809 key.mv_data = &txn->mt_txnid;
2811 freecnt = free_pgs[0];
2812 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2813 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2816 /* Retry if mt_free_pgs[] grew during the Put() */
2817 free_pgs = txn->mt_free_pgs;
2818 } while (freecnt < free_pgs[0]);
2819 mdb_midl_sort(free_pgs);
2820 memcpy(data.mv_data, free_pgs, data.mv_size);
2823 unsigned int i = free_pgs[0];
2824 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2825 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2827 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2833 mop = env->me_pghead;
2834 mop_len = mop ? mop[0] : 0;
2836 /* Reserve records for me_pghead[]. Split it if multi-page,
2837 * to avoid searching freeDB for a page range. Use keys in
2838 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2840 if (total_room >= mop_len) {
2841 if (total_room == mop_len || --more < 0)
2843 } else if (head_room >= maxfree_1pg && head_id > 1) {
2844 /* Keep current record (overflow page), add a new one */
2848 /* (Re)write {key = head_id, IDL length = head_room} */
2849 total_room -= head_room;
2850 head_room = mop_len - total_room;
2851 if (head_room > maxfree_1pg && head_id > 1) {
2852 /* Overflow multi-page for part of me_pghead */
2853 head_room /= head_id; /* amortize page sizes */
2854 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2855 } else if (head_room < 0) {
2856 /* Rare case, not bothering to delete this record */
2859 key.mv_size = sizeof(head_id);
2860 key.mv_data = &head_id;
2861 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2862 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2865 /* IDL is initially empty, zero out at least the length */
2866 pgs = (pgno_t *)data.mv_data;
2867 j = head_room > clean_limit ? head_room : 0;
2871 total_room += head_room;
2874 /* Fill in the reserved me_pghead records */
2880 rc = mdb_cursor_first(&mc, &key, &data);
2881 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2882 txnid_t id = *(txnid_t *)key.mv_data;
2883 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2886 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2888 if (len > mop_len) {
2890 data.mv_size = (len + 1) * sizeof(MDB_ID);
2892 data.mv_data = mop -= len;
2895 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2897 if (rc || !(mop_len -= len))
2904 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2905 * @param[in] txn the transaction that's being committed
2906 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2907 * @return 0 on success, non-zero on failure.
2910 mdb_page_flush(MDB_txn *txn, int keep)
2912 MDB_env *env = txn->mt_env;
2913 MDB_ID2L dl = txn->mt_u.dirty_list;
2914 unsigned psize = env->me_psize, j;
2915 int i, pagecount = dl[0].mid, rc;
2916 size_t size = 0, pos = 0;
2918 MDB_page *dp = NULL;
2922 struct iovec iov[MDB_COMMIT_PAGES];
2923 ssize_t wpos = 0, wsize = 0, wres;
2924 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2930 if (env->me_flags & MDB_WRITEMAP) {
2931 /* Clear dirty flags */
2932 while (++i <= pagecount) {
2934 /* Don't flush this page yet */
2935 if (dp->mp_flags & P_KEEP) {
2936 dp->mp_flags ^= P_KEEP;
2940 dp->mp_flags &= ~P_DIRTY;
2945 /* Write the pages */
2947 if (++i <= pagecount) {
2949 /* Don't flush this page yet */
2950 if (dp->mp_flags & P_KEEP) {
2951 dp->mp_flags ^= P_KEEP;
2956 /* clear dirty flag */
2957 dp->mp_flags &= ~P_DIRTY;
2960 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2965 /* Windows actually supports scatter/gather I/O, but only on
2966 * unbuffered file handles. Since we're relying on the OS page
2967 * cache for all our data, that's self-defeating. So we just
2968 * write pages one at a time. We use the ov structure to set
2969 * the write offset, to at least save the overhead of a Seek
2972 DPRINTF(("committing page %"Z"u", pgno));
2973 memset(&ov, 0, sizeof(ov));
2974 ov.Offset = pos & 0xffffffff;
2975 ov.OffsetHigh = pos >> 16 >> 16;
2976 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2978 DPRINTF(("WriteFile: %d", rc));
2982 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2983 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2985 /* Write previous page(s) */
2986 #ifdef MDB_USE_PWRITEV
2987 wres = pwritev(env->me_fd, iov, n, wpos);
2990 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2992 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2994 DPRINTF(("lseek: %s", strerror(rc)));
2997 wres = writev(env->me_fd, iov, n);
3000 if (wres != wsize) {
3003 DPRINTF(("Write error: %s", strerror(rc)));
3005 rc = EIO; /* TODO: Use which error code? */
3006 DPUTS("short write, filesystem full?");
3017 DPRINTF(("committing page %"Z"u", pgno));
3018 next_pos = pos + size;
3019 iov[n].iov_len = size;
3020 iov[n].iov_base = (char *)dp;
3026 for (i = keep; ++i <= pagecount; ) {
3028 /* This is a page we skipped above */
3031 dl[j].mid = dp->mp_pgno;
3034 mdb_dpage_free(env, dp);
3039 txn->mt_dirty_room += i - j;
3045 mdb_txn_commit(MDB_txn *txn)
3051 if (txn == NULL || txn->mt_env == NULL)
3054 if (txn->mt_child) {
3055 rc = mdb_txn_commit(txn->mt_child);
3056 txn->mt_child = NULL;
3063 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3064 mdb_dbis_update(txn, 1);
3065 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3070 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3071 DPUTS("error flag is set, can't commit");
3073 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3078 if (txn->mt_parent) {
3079 MDB_txn *parent = txn->mt_parent;
3082 unsigned x, y, len, ps_len;
3084 /* Append our free list to parent's */
3085 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3088 mdb_midl_free(txn->mt_free_pgs);
3089 /* Failures after this must either undo the changes
3090 * to the parent or set MDB_TXN_ERROR in the parent.
3093 parent->mt_next_pgno = txn->mt_next_pgno;
3094 parent->mt_flags = txn->mt_flags;
3096 /* Merge our cursors into parent's and close them */
3097 mdb_cursors_close(txn, 1);
3099 /* Update parent's DB table. */
3100 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3101 parent->mt_numdbs = txn->mt_numdbs;
3102 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3103 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3104 for (i=2; i<txn->mt_numdbs; i++) {
3105 /* preserve parent's DB_NEW status */
3106 x = parent->mt_dbflags[i] & DB_NEW;
3107 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3110 dst = parent->mt_u.dirty_list;
3111 src = txn->mt_u.dirty_list;
3112 /* Remove anything in our dirty list from parent's spill list */
3113 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3115 pspill[0] = (pgno_t)-1;
3116 /* Mark our dirty pages as deleted in parent spill list */
3117 for (i=0, len=src[0].mid; ++i <= len; ) {
3118 MDB_ID pn = src[i].mid << 1;
3119 while (pn > pspill[x])
3121 if (pn == pspill[x]) {
3126 /* Squash deleted pagenums if we deleted any */
3127 for (x=y; ++x <= ps_len; )
3128 if (!(pspill[x] & 1))
3129 pspill[++y] = pspill[x];
3133 /* Find len = length of merging our dirty list with parent's */
3135 dst[0].mid = 0; /* simplify loops */
3136 if (parent->mt_parent) {
3137 len = x + src[0].mid;
3138 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3139 for (i = x; y && i; y--) {
3140 pgno_t yp = src[y].mid;
3141 while (yp < dst[i].mid)
3143 if (yp == dst[i].mid) {
3148 } else { /* Simplify the above for single-ancestor case */
3149 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3151 /* Merge our dirty list with parent's */
3153 for (i = len; y; dst[i--] = src[y--]) {
3154 pgno_t yp = src[y].mid;
3155 while (yp < dst[x].mid)
3156 dst[i--] = dst[x--];
3157 if (yp == dst[x].mid)
3158 free(dst[x--].mptr);
3160 mdb_tassert(txn, i == x);
3162 free(txn->mt_u.dirty_list);
3163 parent->mt_dirty_room = txn->mt_dirty_room;
3164 if (txn->mt_spill_pgs) {
3165 if (parent->mt_spill_pgs) {
3166 /* TODO: Prevent failure here, so parent does not fail */
3167 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3169 parent->mt_flags |= MDB_TXN_ERROR;
3170 mdb_midl_free(txn->mt_spill_pgs);
3171 mdb_midl_sort(parent->mt_spill_pgs);
3173 parent->mt_spill_pgs = txn->mt_spill_pgs;
3177 parent->mt_child = NULL;
3178 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3183 if (txn != env->me_txn) {
3184 DPUTS("attempt to commit unknown transaction");
3189 mdb_cursors_close(txn, 0);
3191 if (!txn->mt_u.dirty_list[0].mid &&
3192 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3195 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3196 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3198 /* Update DB root pointers */
3199 if (txn->mt_numdbs > 2) {
3203 data.mv_size = sizeof(MDB_db);
3205 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3206 for (i = 2; i < txn->mt_numdbs; i++) {
3207 if (txn->mt_dbflags[i] & DB_DIRTY) {
3208 data.mv_data = &txn->mt_dbs[i];
3209 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3216 rc = mdb_freelist_save(txn);
3220 mdb_midl_free(env->me_pghead);
3221 env->me_pghead = NULL;
3222 if (mdb_midl_shrink(&txn->mt_free_pgs))
3223 env->me_free_pgs = txn->mt_free_pgs;
3229 if ((rc = mdb_page_flush(txn, 0)) ||
3230 (rc = mdb_env_sync(env, 0)) ||
3231 (rc = mdb_env_write_meta(txn)))
3237 mdb_dbis_update(txn, 1);
3240 UNLOCK_MUTEX_W(env);
3250 /** Read the environment parameters of a DB environment before
3251 * mapping it into memory.
3252 * @param[in] env the environment handle
3253 * @param[out] meta address of where to store the meta information
3254 * @return 0 on success, non-zero on failure.
3257 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3263 enum { Size = sizeof(pbuf) };
3265 /* We don't know the page size yet, so use a minimum value.
3266 * Read both meta pages so we can use the latest one.
3269 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3273 memset(&ov, 0, sizeof(ov));
3275 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3276 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3279 rc = pread(env->me_fd, &pbuf, Size, off);
3282 if (rc == 0 && off == 0)
3284 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3285 DPRINTF(("read: %s", mdb_strerror(rc)));
3289 p = (MDB_page *)&pbuf;
3291 if (!F_ISSET(p->mp_flags, P_META)) {
3292 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3297 if (m->mm_magic != MDB_MAGIC) {
3298 DPUTS("meta has invalid magic");
3302 if (m->mm_version != MDB_DATA_VERSION) {
3303 DPRINTF(("database is version %u, expected version %u",
3304 m->mm_version, MDB_DATA_VERSION));
3305 return MDB_VERSION_MISMATCH;
3308 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3315 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3317 meta->mm_magic = MDB_MAGIC;
3318 meta->mm_version = MDB_DATA_VERSION;
3319 meta->mm_mapsize = env->me_mapsize;
3320 meta->mm_psize = env->me_psize;
3321 meta->mm_last_pg = 1;
3322 meta->mm_flags = env->me_flags & 0xffff;
3323 meta->mm_flags |= MDB_INTEGERKEY;
3324 meta->mm_dbs[0].md_root = P_INVALID;
3325 meta->mm_dbs[1].md_root = P_INVALID;
3328 /** Write the environment parameters of a freshly created DB environment.
3329 * @param[in] env the environment handle
3330 * @param[out] meta address of where to store the meta information
3331 * @return 0 on success, non-zero on failure.
3334 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3342 memset(&ov, 0, sizeof(ov));
3343 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3345 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3348 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3349 len = pwrite(fd, ptr, size, pos); \
3350 rc = (len >= 0); } while(0)
3353 DPUTS("writing new meta page");
3355 psize = env->me_psize;
3357 mdb_env_init_meta0(env, meta);
3359 p = calloc(2, psize);
3361 p->mp_flags = P_META;
3362 *(MDB_meta *)METADATA(p) = *meta;
3364 q = (MDB_page *)((char *)p + psize);
3366 q->mp_flags = P_META;
3367 *(MDB_meta *)METADATA(q) = *meta;
3369 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3372 else if ((unsigned) len == psize * 2)
3380 /** Update the environment info to commit a transaction.
3381 * @param[in] txn the transaction that's being committed
3382 * @return 0 on success, non-zero on failure.
3385 mdb_env_write_meta(MDB_txn *txn)
3388 MDB_meta meta, metab, *mp;
3390 int rc, len, toggle;
3399 toggle = txn->mt_txnid & 1;
3400 DPRINTF(("writing meta page %d for root page %"Z"u",
3401 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3404 mp = env->me_metas[toggle];
3406 if (env->me_flags & MDB_WRITEMAP) {
3407 /* Persist any increases of mapsize config */
3408 if (env->me_mapsize > mp->mm_mapsize)
3409 mp->mm_mapsize = env->me_mapsize;
3410 mp->mm_dbs[0] = txn->mt_dbs[0];
3411 mp->mm_dbs[1] = txn->mt_dbs[1];
3412 mp->mm_last_pg = txn->mt_next_pgno - 1;
3413 mp->mm_txnid = txn->mt_txnid;
3414 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3415 unsigned meta_size = env->me_psize;
3416 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3419 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3420 if (meta_size < env->me_os_psize)
3421 meta_size += meta_size;
3426 if (MDB_MSYNC(ptr, meta_size, rc)) {
3433 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3434 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3436 ptr = (char *)&meta;
3437 if (env->me_mapsize > mp->mm_mapsize) {
3438 /* Persist any increases of mapsize config */
3439 meta.mm_mapsize = env->me_mapsize;
3440 off = offsetof(MDB_meta, mm_mapsize);
3442 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3444 len = sizeof(MDB_meta) - off;
3447 meta.mm_dbs[0] = txn->mt_dbs[0];
3448 meta.mm_dbs[1] = txn->mt_dbs[1];
3449 meta.mm_last_pg = txn->mt_next_pgno - 1;
3450 meta.mm_txnid = txn->mt_txnid;
3453 off += env->me_psize;
3456 /* Write to the SYNC fd */
3457 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3458 env->me_fd : env->me_mfd;
3461 memset(&ov, 0, sizeof(ov));
3463 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3467 rc = pwrite(mfd, ptr, len, off);
3470 rc = rc < 0 ? ErrCode() : EIO;
3471 DPUTS("write failed, disk error?");
3472 /* On a failure, the pagecache still contains the new data.
3473 * Write some old data back, to prevent it from being used.
3474 * Use the non-SYNC fd; we know it will fail anyway.
3476 meta.mm_last_pg = metab.mm_last_pg;
3477 meta.mm_txnid = metab.mm_txnid;
3479 memset(&ov, 0, sizeof(ov));
3481 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3483 r2 = pwrite(env->me_fd, ptr, len, off);
3484 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3487 env->me_flags |= MDB_FATAL_ERROR;
3491 /* Memory ordering issues are irrelevant; since the entire writer
3492 * is wrapped by wmutex, all of these changes will become visible
3493 * after the wmutex is unlocked. Since the DB is multi-version,
3494 * readers will get consistent data regardless of how fresh or
3495 * how stale their view of these values is.
3498 env->me_txns->mti_txnid = txn->mt_txnid;
3503 /** Check both meta pages to see which one is newer.
3504 * @param[in] env the environment handle
3505 * @return meta toggle (0 or 1).
3508 mdb_env_pick_meta(const MDB_env *env)
3510 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3514 mdb_env_create(MDB_env **env)
3518 e = calloc(1, sizeof(MDB_env));
3522 e->me_maxreaders = DEFAULT_READERS;
3523 e->me_maxdbs = e->me_numdbs = 2;
3524 e->me_fd = INVALID_HANDLE_VALUE;
3525 e->me_lfd = INVALID_HANDLE_VALUE;
3526 e->me_mfd = INVALID_HANDLE_VALUE;
3527 #ifdef MDB_USE_POSIX_SEM
3528 e->me_rmutex = SEM_FAILED;
3529 e->me_wmutex = SEM_FAILED;
3531 e->me_pid = getpid();
3532 GET_PAGESIZE(e->me_os_psize);
3533 VGMEMP_CREATE(e,0,0);
3539 mdb_env_map(MDB_env *env, void *addr, int newsize)
3542 unsigned int flags = env->me_flags;
3546 LONG sizelo, sizehi;
3549 if (flags & MDB_RDONLY) {
3554 msize = env->me_mapsize;
3555 sizelo = msize & 0xffffffff;
3556 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3559 /* Windows won't create mappings for zero length files.
3560 * Just allocate the maxsize right now.
3563 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3564 || !SetEndOfFile(env->me_fd)
3565 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3568 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3569 PAGE_READWRITE : PAGE_READONLY,
3570 sizehi, sizelo, NULL);
3573 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3574 FILE_MAP_WRITE : FILE_MAP_READ,
3576 rc = env->me_map ? 0 : ErrCode();
3581 int prot = PROT_READ;
3582 if (flags & MDB_WRITEMAP) {
3584 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3587 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3589 if (env->me_map == MAP_FAILED) {
3594 if (flags & MDB_NORDAHEAD) {
3595 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3597 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3599 #ifdef POSIX_MADV_RANDOM
3600 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3601 #endif /* POSIX_MADV_RANDOM */
3602 #endif /* MADV_RANDOM */
3606 /* Can happen because the address argument to mmap() is just a
3607 * hint. mmap() can pick another, e.g. if the range is in use.
3608 * The MAP_FIXED flag would prevent that, but then mmap could
3609 * instead unmap existing pages to make room for the new map.
3611 if (addr && env->me_map != addr)
3612 return EBUSY; /* TODO: Make a new MDB_* error code? */
3614 p = (MDB_page *)env->me_map;
3615 env->me_metas[0] = METADATA(p);
3616 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3622 mdb_env_set_mapsize(MDB_env *env, size_t size)
3624 /* If env is already open, caller is responsible for making
3625 * sure there are no active txns.
3633 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3634 else if (size < env->me_mapsize) {
3635 /* If the configured size is smaller, make sure it's
3636 * still big enough. Silently round up to minimum if not.
3638 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3642 munmap(env->me_map, env->me_mapsize);
3643 env->me_mapsize = size;
3644 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3645 rc = mdb_env_map(env, old, 1);
3649 env->me_mapsize = size;
3651 env->me_maxpg = env->me_mapsize / env->me_psize;
3656 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3660 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3665 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3667 if (env->me_map || readers < 1)
3669 env->me_maxreaders = readers;
3674 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3676 if (!env || !readers)
3678 *readers = env->me_maxreaders;
3682 /** Further setup required for opening an LMDB environment
3685 mdb_env_open2(MDB_env *env)
3687 unsigned int flags = env->me_flags;
3688 int i, newenv = 0, rc;
3692 /* See if we should use QueryLimited */
3694 if ((rc & 0xff) > 5)
3695 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3697 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3700 memset(&meta, 0, sizeof(meta));
3702 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3705 DPUTS("new mdbenv");
3707 env->me_psize = env->me_os_psize;
3708 if (env->me_psize > MAX_PAGESIZE)
3709 env->me_psize = MAX_PAGESIZE;
3711 env->me_psize = meta.mm_psize;
3714 /* Was a mapsize configured? */
3715 if (!env->me_mapsize) {
3716 /* If this is a new environment, take the default,
3717 * else use the size recorded in the existing env.
3719 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3720 } else if (env->me_mapsize < meta.mm_mapsize) {
3721 /* If the configured size is smaller, make sure it's
3722 * still big enough. Silently round up to minimum if not.
3724 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3725 if (env->me_mapsize < minsize)
3726 env->me_mapsize = minsize;
3729 rc = mdb_env_map(env, meta.mm_address, newenv || env->me_mapsize != meta.mm_mapsize);
3734 if (flags & MDB_FIXEDMAP)
3735 meta.mm_address = env->me_map;
3736 i = mdb_env_init_meta(env, &meta);
3737 if (i != MDB_SUCCESS) {
3742 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3743 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3745 #if !(MDB_MAXKEYSIZE)
3746 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3748 env->me_maxpg = env->me_mapsize / env->me_psize;
3752 int toggle = mdb_env_pick_meta(env);
3753 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3755 DPRINTF(("opened database version %u, pagesize %u",
3756 env->me_metas[0]->mm_version, env->me_psize));
3757 DPRINTF(("using meta page %d", toggle));
3758 DPRINTF(("depth: %u", db->md_depth));
3759 DPRINTF(("entries: %"Z"u", db->md_entries));
3760 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3761 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3762 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3763 DPRINTF(("root: %"Z"u", db->md_root));
3771 /** Release a reader thread's slot in the reader lock table.
3772 * This function is called automatically when a thread exits.
3773 * @param[in] ptr This points to the slot in the reader lock table.
3776 mdb_env_reader_dest(void *ptr)
3778 MDB_reader *reader = ptr;
3784 /** Junk for arranging thread-specific callbacks on Windows. This is
3785 * necessarily platform and compiler-specific. Windows supports up
3786 * to 1088 keys. Let's assume nobody opens more than 64 environments
3787 * in a single process, for now. They can override this if needed.
3789 #ifndef MAX_TLS_KEYS
3790 #define MAX_TLS_KEYS 64
3792 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3793 static int mdb_tls_nkeys;
3795 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3799 case DLL_PROCESS_ATTACH: break;
3800 case DLL_THREAD_ATTACH: break;
3801 case DLL_THREAD_DETACH:
3802 for (i=0; i<mdb_tls_nkeys; i++) {
3803 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3805 mdb_env_reader_dest(r);
3809 case DLL_PROCESS_DETACH: break;
3814 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3816 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3820 /* Force some symbol references.
3821 * _tls_used forces the linker to create the TLS directory if not already done
3822 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3824 #pragma comment(linker, "/INCLUDE:_tls_used")
3825 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3826 #pragma const_seg(".CRT$XLB")
3827 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3828 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3831 #pragma comment(linker, "/INCLUDE:__tls_used")
3832 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3833 #pragma data_seg(".CRT$XLB")
3834 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3836 #endif /* WIN 32/64 */
3837 #endif /* !__GNUC__ */
3840 /** Downgrade the exclusive lock on the region back to shared */
3842 mdb_env_share_locks(MDB_env *env, int *excl)
3844 int rc = 0, toggle = mdb_env_pick_meta(env);
3846 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3851 /* First acquire a shared lock. The Unlock will
3852 * then release the existing exclusive lock.
3854 memset(&ov, 0, sizeof(ov));
3855 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3858 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3864 struct flock lock_info;
3865 /* The shared lock replaces the existing lock */
3866 memset((void *)&lock_info, 0, sizeof(lock_info));
3867 lock_info.l_type = F_RDLCK;
3868 lock_info.l_whence = SEEK_SET;
3869 lock_info.l_start = 0;
3870 lock_info.l_len = 1;
3871 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3872 (rc = ErrCode()) == EINTR) ;
3873 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3880 /** Try to get exlusive lock, otherwise shared.
3881 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3884 mdb_env_excl_lock(MDB_env *env, int *excl)
3888 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3892 memset(&ov, 0, sizeof(ov));
3893 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3900 struct flock lock_info;
3901 memset((void *)&lock_info, 0, sizeof(lock_info));
3902 lock_info.l_type = F_WRLCK;
3903 lock_info.l_whence = SEEK_SET;
3904 lock_info.l_start = 0;
3905 lock_info.l_len = 1;
3906 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3907 (rc = ErrCode()) == EINTR) ;
3911 # ifdef MDB_USE_POSIX_SEM
3912 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3915 lock_info.l_type = F_RDLCK;
3916 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3917 (rc = ErrCode()) == EINTR) ;
3927 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3929 * @(#) $Revision: 5.1 $
3930 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3931 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3933 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3937 * Please do not copyright this code. This code is in the public domain.
3939 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3940 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3941 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3942 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3943 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3944 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3945 * PERFORMANCE OF THIS SOFTWARE.
3948 * chongo <Landon Curt Noll> /\oo/\
3949 * http://www.isthe.com/chongo/
3951 * Share and Enjoy! :-)
3954 typedef unsigned long long mdb_hash_t;
3955 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3957 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3958 * @param[in] val value to hash
3959 * @param[in] hval initial value for hash
3960 * @return 64 bit hash
3962 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3963 * hval arg on the first call.
3966 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3968 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3969 unsigned char *end = s + val->mv_size;
3971 * FNV-1a hash each octet of the string
3974 /* xor the bottom with the current octet */
3975 hval ^= (mdb_hash_t)*s++;
3977 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3978 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3979 (hval << 7) + (hval << 8) + (hval << 40);
3981 /* return our new hash value */
3985 /** Hash the string and output the encoded hash.
3986 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3987 * very short name limits. We don't care about the encoding being reversible,
3988 * we just want to preserve as many bits of the input as possible in a
3989 * small printable string.
3990 * @param[in] str string to hash
3991 * @param[out] encbuf an array of 11 chars to hold the hash
3993 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3996 mdb_pack85(unsigned long l, char *out)
4000 for (i=0; i<5; i++) {
4001 *out++ = mdb_a85[l % 85];
4007 mdb_hash_enc(MDB_val *val, char *encbuf)
4009 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4011 mdb_pack85(h, encbuf);
4012 mdb_pack85(h>>32, encbuf+5);
4017 /** Open and/or initialize the lock region for the environment.
4018 * @param[in] env The LMDB environment.
4019 * @param[in] lpath The pathname of the file used for the lock region.
4020 * @param[in] mode The Unix permissions for the file, if we create it.
4021 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4022 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4023 * @return 0 on success, non-zero on failure.
4026 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4029 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4031 # define MDB_ERRCODE_ROFS EROFS
4032 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4033 # define MDB_CLOEXEC O_CLOEXEC
4036 # define MDB_CLOEXEC 0
4043 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4044 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4045 FILE_ATTRIBUTE_NORMAL, NULL);
4047 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4049 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4051 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4056 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4057 /* Lose record locks when exec*() */
4058 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4059 fcntl(env->me_lfd, F_SETFD, fdflags);
4062 if (!(env->me_flags & MDB_NOTLS)) {
4063 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4066 env->me_flags |= MDB_ENV_TXKEY;
4068 /* Windows TLS callbacks need help finding their TLS info. */
4069 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4073 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4077 /* Try to get exclusive lock. If we succeed, then
4078 * nobody is using the lock region and we should initialize it.
4080 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4083 size = GetFileSize(env->me_lfd, NULL);
4085 size = lseek(env->me_lfd, 0, SEEK_END);
4086 if (size == -1) goto fail_errno;
4088 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4089 if (size < rsize && *excl > 0) {
4091 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4092 || !SetEndOfFile(env->me_lfd))
4095 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4099 size = rsize - sizeof(MDB_txninfo);
4100 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4105 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4107 if (!mh) goto fail_errno;
4108 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4110 if (!env->me_txns) goto fail_errno;
4112 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4114 if (m == MAP_FAILED) goto fail_errno;
4120 BY_HANDLE_FILE_INFORMATION stbuf;
4129 if (!mdb_sec_inited) {
4130 InitializeSecurityDescriptor(&mdb_null_sd,
4131 SECURITY_DESCRIPTOR_REVISION);
4132 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4133 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4134 mdb_all_sa.bInheritHandle = FALSE;
4135 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4138 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4139 idbuf.volume = stbuf.dwVolumeSerialNumber;
4140 idbuf.nhigh = stbuf.nFileIndexHigh;
4141 idbuf.nlow = stbuf.nFileIndexLow;
4142 val.mv_data = &idbuf;
4143 val.mv_size = sizeof(idbuf);
4144 mdb_hash_enc(&val, encbuf);
4145 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4146 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4147 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4148 if (!env->me_rmutex) goto fail_errno;
4149 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4150 if (!env->me_wmutex) goto fail_errno;
4151 #elif defined(MDB_USE_POSIX_SEM)
4160 #if defined(__NetBSD__)
4161 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4163 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4164 idbuf.dev = stbuf.st_dev;
4165 idbuf.ino = stbuf.st_ino;
4166 val.mv_data = &idbuf;
4167 val.mv_size = sizeof(idbuf);
4168 mdb_hash_enc(&val, encbuf);
4169 #ifdef MDB_SHORT_SEMNAMES
4170 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4172 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4173 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4174 /* Clean up after a previous run, if needed: Try to
4175 * remove both semaphores before doing anything else.
4177 sem_unlink(env->me_txns->mti_rmname);
4178 sem_unlink(env->me_txns->mti_wmname);
4179 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4180 O_CREAT|O_EXCL, mode, 1);
4181 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4182 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4183 O_CREAT|O_EXCL, mode, 1);
4184 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4185 #else /* MDB_USE_POSIX_SEM */
4186 pthread_mutexattr_t mattr;
4188 if ((rc = pthread_mutexattr_init(&mattr))
4189 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4190 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4191 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4193 pthread_mutexattr_destroy(&mattr);
4194 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4196 env->me_txns->mti_magic = MDB_MAGIC;
4197 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4198 env->me_txns->mti_txnid = 0;
4199 env->me_txns->mti_numreaders = 0;
4202 if (env->me_txns->mti_magic != MDB_MAGIC) {
4203 DPUTS("lock region has invalid magic");
4207 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4208 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4209 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4210 rc = MDB_VERSION_MISMATCH;
4214 if (rc && rc != EACCES && rc != EAGAIN) {
4218 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4219 if (!env->me_rmutex) goto fail_errno;
4220 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4221 if (!env->me_wmutex) goto fail_errno;
4222 #elif defined(MDB_USE_POSIX_SEM)
4223 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4224 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4225 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4226 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4237 /** The name of the lock file in the DB environment */
4238 #define LOCKNAME "/lock.mdb"
4239 /** The name of the data file in the DB environment */
4240 #define DATANAME "/data.mdb"
4241 /** The suffix of the lock file when no subdir is used */
4242 #define LOCKSUFF "-lock"
4243 /** Only a subset of the @ref mdb_env flags can be changed
4244 * at runtime. Changing other flags requires closing the
4245 * environment and re-opening it with the new flags.
4247 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4248 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4249 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4251 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4252 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4256 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4258 int oflags, rc, len, excl = -1;
4259 char *lpath, *dpath;
4261 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4265 if (flags & MDB_NOSUBDIR) {
4266 rc = len + sizeof(LOCKSUFF) + len + 1;
4268 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4273 if (flags & MDB_NOSUBDIR) {
4274 dpath = lpath + len + sizeof(LOCKSUFF);
4275 sprintf(lpath, "%s" LOCKSUFF, path);
4276 strcpy(dpath, path);
4278 dpath = lpath + len + sizeof(LOCKNAME);
4279 sprintf(lpath, "%s" LOCKNAME, path);
4280 sprintf(dpath, "%s" DATANAME, path);
4284 flags |= env->me_flags;
4285 if (flags & MDB_RDONLY) {
4286 /* silently ignore WRITEMAP when we're only getting read access */
4287 flags &= ~MDB_WRITEMAP;
4289 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4290 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4293 env->me_flags = flags |= MDB_ENV_ACTIVE;
4297 env->me_path = strdup(path);
4298 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4299 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4300 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4305 /* For RDONLY, get lockfile after we know datafile exists */
4306 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4307 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4313 if (F_ISSET(flags, MDB_RDONLY)) {
4314 oflags = GENERIC_READ;
4315 len = OPEN_EXISTING;
4317 oflags = GENERIC_READ|GENERIC_WRITE;
4320 mode = FILE_ATTRIBUTE_NORMAL;
4321 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4322 NULL, len, mode, NULL);
4324 if (F_ISSET(flags, MDB_RDONLY))
4327 oflags = O_RDWR | O_CREAT;
4329 env->me_fd = open(dpath, oflags, mode);
4331 if (env->me_fd == INVALID_HANDLE_VALUE) {
4336 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4337 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4342 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4343 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4344 env->me_mfd = env->me_fd;
4346 /* Synchronous fd for meta writes. Needed even with
4347 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4350 len = OPEN_EXISTING;
4351 env->me_mfd = CreateFile(dpath, oflags,
4352 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4353 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4356 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4358 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4363 DPRINTF(("opened dbenv %p", (void *) env));
4365 rc = mdb_env_share_locks(env, &excl);
4369 if (!((flags & MDB_RDONLY) ||
4370 (env->me_pbuf = calloc(1, env->me_psize))))
4376 mdb_env_close0(env, excl);
4382 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4384 mdb_env_close0(MDB_env *env, int excl)
4388 if (!(env->me_flags & MDB_ENV_ACTIVE))
4391 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4392 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4393 free(env->me_dbxs[i].md_name.mv_data);
4396 free(env->me_dbflags);
4399 free(env->me_dirty_list);
4400 mdb_midl_free(env->me_free_pgs);
4402 if (env->me_flags & MDB_ENV_TXKEY) {
4403 pthread_key_delete(env->me_txkey);
4405 /* Delete our key from the global list */
4406 for (i=0; i<mdb_tls_nkeys; i++)
4407 if (mdb_tls_keys[i] == env->me_txkey) {
4408 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4416 munmap(env->me_map, env->me_mapsize);
4418 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4419 (void) close(env->me_mfd);
4420 if (env->me_fd != INVALID_HANDLE_VALUE)
4421 (void) close(env->me_fd);
4423 MDB_PID_T pid = env->me_pid;
4424 /* Clearing readers is done in this function because
4425 * me_txkey with its destructor must be disabled first.
4427 for (i = env->me_numreaders; --i >= 0; )
4428 if (env->me_txns->mti_readers[i].mr_pid == pid)
4429 env->me_txns->mti_readers[i].mr_pid = 0;
4431 if (env->me_rmutex) {
4432 CloseHandle(env->me_rmutex);
4433 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4435 /* Windows automatically destroys the mutexes when
4436 * the last handle closes.
4438 #elif defined(MDB_USE_POSIX_SEM)
4439 if (env->me_rmutex != SEM_FAILED) {
4440 sem_close(env->me_rmutex);
4441 if (env->me_wmutex != SEM_FAILED)
4442 sem_close(env->me_wmutex);
4443 /* If we have the filelock: If we are the
4444 * only remaining user, clean up semaphores.
4447 mdb_env_excl_lock(env, &excl);
4449 sem_unlink(env->me_txns->mti_rmname);
4450 sem_unlink(env->me_txns->mti_wmname);
4454 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4456 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4459 /* Unlock the lockfile. Windows would have unlocked it
4460 * after closing anyway, but not necessarily at once.
4462 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4465 (void) close(env->me_lfd);
4468 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4473 mdb_env_close(MDB_env *env)
4480 VGMEMP_DESTROY(env);
4481 while ((dp = env->me_dpages) != NULL) {
4482 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4483 env->me_dpages = dp->mp_next;
4487 mdb_env_close0(env, 0);
4491 /** Compare two items pointing at aligned size_t's */
4493 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4495 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4496 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4499 /** Compare two items pointing at aligned unsigned int's */
4501 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4503 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4504 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4507 /** Compare two items pointing at unsigned ints of unknown alignment.
4508 * Nodes and keys are guaranteed to be 2-byte aligned.
4511 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4513 #if BYTE_ORDER == LITTLE_ENDIAN
4514 unsigned short *u, *c;
4517 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4518 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4521 } while(!x && u > (unsigned short *)a->mv_data);
4524 unsigned short *u, *c, *end;
4527 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4528 u = (unsigned short *)a->mv_data;
4529 c = (unsigned short *)b->mv_data;
4532 } while(!x && u < end);
4537 /** Compare two items pointing at size_t's of unknown alignment. */
4538 #ifdef MISALIGNED_OK
4539 # define mdb_cmp_clong mdb_cmp_long
4541 # define mdb_cmp_clong mdb_cmp_cint
4544 /** Compare two items lexically */
4546 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4553 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4559 diff = memcmp(a->mv_data, b->mv_data, len);
4560 return diff ? diff : len_diff<0 ? -1 : len_diff;
4563 /** Compare two items in reverse byte order */
4565 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4567 const unsigned char *p1, *p2, *p1_lim;
4571 p1_lim = (const unsigned char *)a->mv_data;
4572 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4573 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4575 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4581 while (p1 > p1_lim) {
4582 diff = *--p1 - *--p2;
4586 return len_diff<0 ? -1 : len_diff;
4589 /** Search for key within a page, using binary search.
4590 * Returns the smallest entry larger or equal to the key.
4591 * If exactp is non-null, stores whether the found entry was an exact match
4592 * in *exactp (1 or 0).
4593 * Updates the cursor index with the index of the found entry.
4594 * If no entry larger or equal to the key is found, returns NULL.
4597 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4599 unsigned int i = 0, nkeys;
4602 MDB_page *mp = mc->mc_pg[mc->mc_top];
4603 MDB_node *node = NULL;
4608 nkeys = NUMKEYS(mp);
4610 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4611 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4614 low = IS_LEAF(mp) ? 0 : 1;
4616 cmp = mc->mc_dbx->md_cmp;
4618 /* Branch pages have no data, so if using integer keys,
4619 * alignment is guaranteed. Use faster mdb_cmp_int.
4621 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4622 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4629 nodekey.mv_size = mc->mc_db->md_pad;
4630 node = NODEPTR(mp, 0); /* fake */
4631 while (low <= high) {
4632 i = (low + high) >> 1;
4633 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4634 rc = cmp(key, &nodekey);
4635 DPRINTF(("found leaf index %u [%s], rc = %i",
4636 i, DKEY(&nodekey), rc));
4645 while (low <= high) {
4646 i = (low + high) >> 1;
4648 node = NODEPTR(mp, i);
4649 nodekey.mv_size = NODEKSZ(node);
4650 nodekey.mv_data = NODEKEY(node);
4652 rc = cmp(key, &nodekey);
4655 DPRINTF(("found leaf index %u [%s], rc = %i",
4656 i, DKEY(&nodekey), rc));
4658 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4659 i, DKEY(&nodekey), NODEPGNO(node), rc));
4670 if (rc > 0) { /* Found entry is less than the key. */
4671 i++; /* Skip to get the smallest entry larger than key. */
4673 node = NODEPTR(mp, i);
4676 *exactp = (rc == 0 && nkeys > 0);
4677 /* store the key index */
4678 mc->mc_ki[mc->mc_top] = i;
4680 /* There is no entry larger or equal to the key. */
4683 /* nodeptr is fake for LEAF2 */
4689 mdb_cursor_adjust(MDB_cursor *mc, func)
4693 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4694 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4701 /** Pop a page off the top of the cursor's stack. */
4703 mdb_cursor_pop(MDB_cursor *mc)
4707 MDB_page *top = mc->mc_pg[mc->mc_top];
4713 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4714 DDBI(mc), (void *) mc));
4718 /** Push a page onto the top of the cursor's stack. */
4720 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4722 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4723 DDBI(mc), (void *) mc));
4725 if (mc->mc_snum >= CURSOR_STACK) {
4726 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4727 return MDB_CURSOR_FULL;
4730 mc->mc_top = mc->mc_snum++;
4731 mc->mc_pg[mc->mc_top] = mp;
4732 mc->mc_ki[mc->mc_top] = 0;
4737 /** Find the address of the page corresponding to a given page number.
4738 * @param[in] txn the transaction for this access.
4739 * @param[in] pgno the page number for the page to retrieve.
4740 * @param[out] ret address of a pointer where the page's address will be stored.
4741 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4742 * @return 0 on success, non-zero on failure.
4745 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4747 MDB_env *env = txn->mt_env;
4751 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4755 MDB_ID2L dl = tx2->mt_u.dirty_list;
4757 /* Spilled pages were dirtied in this txn and flushed
4758 * because the dirty list got full. Bring this page
4759 * back in from the map (but don't unspill it here,
4760 * leave that unless page_touch happens again).
4762 if (tx2->mt_spill_pgs) {
4763 MDB_ID pn = pgno << 1;
4764 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4765 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4766 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4771 unsigned x = mdb_mid2l_search(dl, pgno);
4772 if (x <= dl[0].mid && dl[x].mid == pgno) {
4778 } while ((tx2 = tx2->mt_parent) != NULL);
4781 if (pgno < txn->mt_next_pgno) {
4783 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4785 DPRINTF(("page %"Z"u not found", pgno));
4786 txn->mt_flags |= MDB_TXN_ERROR;
4787 return MDB_PAGE_NOTFOUND;
4797 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4798 * The cursor is at the root page, set up the rest of it.
4801 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4803 MDB_page *mp = mc->mc_pg[mc->mc_top];
4807 while (IS_BRANCH(mp)) {
4811 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4812 mdb_cassert(mc, NUMKEYS(mp) > 1);
4813 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4815 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4817 if (flags & MDB_PS_LAST)
4818 i = NUMKEYS(mp) - 1;
4821 node = mdb_node_search(mc, key, &exact);
4823 i = NUMKEYS(mp) - 1;
4825 i = mc->mc_ki[mc->mc_top];
4827 mdb_cassert(mc, i > 0);
4831 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4834 mdb_cassert(mc, i < NUMKEYS(mp));
4835 node = NODEPTR(mp, i);
4837 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4840 mc->mc_ki[mc->mc_top] = i;
4841 if ((rc = mdb_cursor_push(mc, mp)))
4844 if (flags & MDB_PS_MODIFY) {
4845 if ((rc = mdb_page_touch(mc)) != 0)
4847 mp = mc->mc_pg[mc->mc_top];
4852 DPRINTF(("internal error, index points to a %02X page!?",
4854 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4855 return MDB_CORRUPTED;
4858 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4859 key ? DKEY(key) : "null"));
4860 mc->mc_flags |= C_INITIALIZED;
4861 mc->mc_flags &= ~C_EOF;
4866 /** Search for the lowest key under the current branch page.
4867 * This just bypasses a NUMKEYS check in the current page
4868 * before calling mdb_page_search_root(), because the callers
4869 * are all in situations where the current page is known to
4873 mdb_page_search_lowest(MDB_cursor *mc)
4875 MDB_page *mp = mc->mc_pg[mc->mc_top];
4876 MDB_node *node = NODEPTR(mp, 0);
4879 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4882 mc->mc_ki[mc->mc_top] = 0;
4883 if ((rc = mdb_cursor_push(mc, mp)))
4885 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4888 /** Search for the page a given key should be in.
4889 * Push it and its parent pages on the cursor stack.
4890 * @param[in,out] mc the cursor for this operation.
4891 * @param[in] key the key to search for, or NULL for first/last page.
4892 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4893 * are touched (updated with new page numbers).
4894 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4895 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4896 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4897 * @return 0 on success, non-zero on failure.
4900 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4905 /* Make sure the txn is still viable, then find the root from
4906 * the txn's db table and set it as the root of the cursor's stack.
4908 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4909 DPUTS("transaction has failed, must abort");
4912 /* Make sure we're using an up-to-date root */
4913 if (*mc->mc_dbflag & DB_STALE) {
4915 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4916 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4923 MDB_node *leaf = mdb_node_search(&mc2,
4924 &mc->mc_dbx->md_name, &exact);
4926 return MDB_NOTFOUND;
4927 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4930 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4932 /* The txn may not know this DBI, or another process may
4933 * have dropped and recreated the DB with other flags.
4935 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4936 return MDB_INCOMPATIBLE;
4937 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4939 *mc->mc_dbflag &= ~DB_STALE;
4941 root = mc->mc_db->md_root;
4943 if (root == P_INVALID) { /* Tree is empty. */
4944 DPUTS("tree is empty");
4945 return MDB_NOTFOUND;
4949 mdb_cassert(mc, root > 1);
4950 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4951 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4957 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4958 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4960 if (flags & MDB_PS_MODIFY) {
4961 if ((rc = mdb_page_touch(mc)))
4965 if (flags & MDB_PS_ROOTONLY)
4968 return mdb_page_search_root(mc, key, flags);
4972 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4974 MDB_txn *txn = mc->mc_txn;
4975 pgno_t pg = mp->mp_pgno;
4976 unsigned x = 0, ovpages = mp->mp_pages;
4977 MDB_env *env = txn->mt_env;
4978 MDB_IDL sl = txn->mt_spill_pgs;
4979 MDB_ID pn = pg << 1;
4982 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4983 /* If the page is dirty or on the spill list we just acquired it,
4984 * so we should give it back to our current free list, if any.
4985 * Otherwise put it onto the list of pages we freed in this txn.
4987 * Won't create me_pghead: me_pglast must be inited along with it.
4988 * Unsupported in nested txns: They would need to hide the page
4989 * range in ancestor txns' dirty and spilled lists.
4991 if (env->me_pghead &&
4993 ((mp->mp_flags & P_DIRTY) ||
4994 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4998 MDB_ID2 *dl, ix, iy;
4999 rc = mdb_midl_need(&env->me_pghead, ovpages);
5002 if (!(mp->mp_flags & P_DIRTY)) {
5003 /* This page is no longer spilled */
5010 /* Remove from dirty list */
5011 dl = txn->mt_u.dirty_list;
5013 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5019 mdb_cassert(mc, x > 1);
5021 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5022 txn->mt_flags |= MDB_TXN_ERROR;
5023 return MDB_CORRUPTED;
5026 if (!(env->me_flags & MDB_WRITEMAP))
5027 mdb_dpage_free(env, mp);
5029 /* Insert in me_pghead */
5030 mop = env->me_pghead;
5031 j = mop[0] + ovpages;
5032 for (i = mop[0]; i && mop[i] < pg; i--)
5038 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5042 mc->mc_db->md_overflow_pages -= ovpages;
5046 /** Return the data associated with a given node.
5047 * @param[in] txn The transaction for this operation.
5048 * @param[in] leaf The node being read.
5049 * @param[out] data Updated to point to the node's data.
5050 * @return 0 on success, non-zero on failure.
5053 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5055 MDB_page *omp; /* overflow page */
5059 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5060 data->mv_size = NODEDSZ(leaf);
5061 data->mv_data = NODEDATA(leaf);
5065 /* Read overflow data.
5067 data->mv_size = NODEDSZ(leaf);
5068 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5069 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5070 DPRINTF(("read overflow page %"Z"u failed", pgno));
5073 data->mv_data = METADATA(omp);
5079 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5080 MDB_val *key, MDB_val *data)
5087 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5089 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5092 if (txn->mt_flags & MDB_TXN_ERROR)
5095 mdb_cursor_init(&mc, txn, dbi, &mx);
5096 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5099 /** Find a sibling for a page.
5100 * Replaces the page at the top of the cursor's stack with the
5101 * specified sibling, if one exists.
5102 * @param[in] mc The cursor for this operation.
5103 * @param[in] move_right Non-zero if the right sibling is requested,
5104 * otherwise the left sibling.
5105 * @return 0 on success, non-zero on failure.
5108 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5114 if (mc->mc_snum < 2) {
5115 return MDB_NOTFOUND; /* root has no siblings */
5119 DPRINTF(("parent page is page %"Z"u, index %u",
5120 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5122 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5123 : (mc->mc_ki[mc->mc_top] == 0)) {
5124 DPRINTF(("no more keys left, moving to %s sibling",
5125 move_right ? "right" : "left"));
5126 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5127 /* undo cursor_pop before returning */
5134 mc->mc_ki[mc->mc_top]++;
5136 mc->mc_ki[mc->mc_top]--;
5137 DPRINTF(("just moving to %s index key %u",
5138 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5140 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5142 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5143 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5144 /* mc will be inconsistent if caller does mc_snum++ as above */
5145 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5149 mdb_cursor_push(mc, mp);
5151 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5156 /** Move the cursor to the next data item. */
5158 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5164 if (mc->mc_flags & C_EOF) {
5165 return MDB_NOTFOUND;
5168 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5170 mp = mc->mc_pg[mc->mc_top];
5172 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5173 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5174 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5175 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5176 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5177 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5178 if (rc == MDB_SUCCESS)
5179 MDB_GET_KEY(leaf, key);
5184 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5185 if (op == MDB_NEXT_DUP)
5186 return MDB_NOTFOUND;
5190 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5191 mdb_dbg_pgno(mp), (void *) mc));
5192 if (mc->mc_flags & C_DEL)
5195 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5196 DPUTS("=====> move to next sibling page");
5197 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5198 mc->mc_flags |= C_EOF;
5201 mp = mc->mc_pg[mc->mc_top];
5202 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5204 mc->mc_ki[mc->mc_top]++;
5207 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5208 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5211 key->mv_size = mc->mc_db->md_pad;
5212 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5216 mdb_cassert(mc, IS_LEAF(mp));
5217 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5219 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5220 mdb_xcursor_init1(mc, leaf);
5223 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5226 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5227 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5228 if (rc != MDB_SUCCESS)
5233 MDB_GET_KEY(leaf, key);
5237 /** Move the cursor to the previous data item. */
5239 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5245 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5247 mp = mc->mc_pg[mc->mc_top];
5249 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5250 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5251 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5252 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5253 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5254 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5255 if (rc == MDB_SUCCESS)
5256 MDB_GET_KEY(leaf, key);
5260 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5261 if (op == MDB_PREV_DUP)
5262 return MDB_NOTFOUND;
5267 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5268 mdb_dbg_pgno(mp), (void *) mc));
5270 if (mc->mc_ki[mc->mc_top] == 0) {
5271 DPUTS("=====> move to prev sibling page");
5272 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5275 mp = mc->mc_pg[mc->mc_top];
5276 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5277 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5279 mc->mc_ki[mc->mc_top]--;
5281 mc->mc_flags &= ~C_EOF;
5283 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5284 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5287 key->mv_size = mc->mc_db->md_pad;
5288 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5292 mdb_cassert(mc, IS_LEAF(mp));
5293 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5295 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5296 mdb_xcursor_init1(mc, leaf);
5299 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5302 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5303 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5304 if (rc != MDB_SUCCESS)
5309 MDB_GET_KEY(leaf, key);
5313 /** Set the cursor on a specific data item. */
5315 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5316 MDB_cursor_op op, int *exactp)
5320 MDB_node *leaf = NULL;
5323 if (key->mv_size == 0)
5324 return MDB_BAD_VALSIZE;
5327 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5329 /* See if we're already on the right page */
5330 if (mc->mc_flags & C_INITIALIZED) {
5333 mp = mc->mc_pg[mc->mc_top];
5335 mc->mc_ki[mc->mc_top] = 0;
5336 return MDB_NOTFOUND;
5338 if (mp->mp_flags & P_LEAF2) {
5339 nodekey.mv_size = mc->mc_db->md_pad;
5340 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5342 leaf = NODEPTR(mp, 0);
5343 MDB_GET_KEY2(leaf, nodekey);
5345 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5347 /* Probably happens rarely, but first node on the page
5348 * was the one we wanted.
5350 mc->mc_ki[mc->mc_top] = 0;
5357 unsigned int nkeys = NUMKEYS(mp);
5359 if (mp->mp_flags & P_LEAF2) {
5360 nodekey.mv_data = LEAF2KEY(mp,
5361 nkeys-1, nodekey.mv_size);
5363 leaf = NODEPTR(mp, nkeys-1);
5364 MDB_GET_KEY2(leaf, nodekey);
5366 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5368 /* last node was the one we wanted */
5369 mc->mc_ki[mc->mc_top] = nkeys-1;
5375 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5376 /* This is definitely the right page, skip search_page */
5377 if (mp->mp_flags & P_LEAF2) {
5378 nodekey.mv_data = LEAF2KEY(mp,
5379 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5381 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5382 MDB_GET_KEY2(leaf, nodekey);
5384 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5386 /* current node was the one we wanted */
5396 /* If any parents have right-sibs, search.
5397 * Otherwise, there's nothing further.
5399 for (i=0; i<mc->mc_top; i++)
5401 NUMKEYS(mc->mc_pg[i])-1)
5403 if (i == mc->mc_top) {
5404 /* There are no other pages */
5405 mc->mc_ki[mc->mc_top] = nkeys;
5406 return MDB_NOTFOUND;
5410 /* There are no other pages */
5411 mc->mc_ki[mc->mc_top] = 0;
5412 if (op == MDB_SET_RANGE && !exactp) {
5416 return MDB_NOTFOUND;
5420 rc = mdb_page_search(mc, key, 0);
5421 if (rc != MDB_SUCCESS)
5424 mp = mc->mc_pg[mc->mc_top];
5425 mdb_cassert(mc, IS_LEAF(mp));
5428 leaf = mdb_node_search(mc, key, exactp);
5429 if (exactp != NULL && !*exactp) {
5430 /* MDB_SET specified and not an exact match. */
5431 return MDB_NOTFOUND;
5435 DPUTS("===> inexact leaf not found, goto sibling");
5436 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5437 return rc; /* no entries matched */
5438 mp = mc->mc_pg[mc->mc_top];
5439 mdb_cassert(mc, IS_LEAF(mp));
5440 leaf = NODEPTR(mp, 0);
5444 mc->mc_flags |= C_INITIALIZED;
5445 mc->mc_flags &= ~C_EOF;
5448 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5449 key->mv_size = mc->mc_db->md_pad;
5450 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5455 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5456 mdb_xcursor_init1(mc, leaf);
5459 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5460 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5461 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5464 if (op == MDB_GET_BOTH) {
5470 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5471 if (rc != MDB_SUCCESS)
5474 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5476 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5478 rc = mc->mc_dbx->md_dcmp(data, &d2);
5480 if (op == MDB_GET_BOTH || rc > 0)
5481 return MDB_NOTFOUND;
5488 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5489 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5494 /* The key already matches in all other cases */
5495 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5496 MDB_GET_KEY(leaf, key);
5497 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5502 /** Move the cursor to the first item in the database. */
5504 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5510 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5512 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5513 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5514 if (rc != MDB_SUCCESS)
5517 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5519 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5520 mc->mc_flags |= C_INITIALIZED;
5521 mc->mc_flags &= ~C_EOF;
5523 mc->mc_ki[mc->mc_top] = 0;
5525 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5526 key->mv_size = mc->mc_db->md_pad;
5527 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5532 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5533 mdb_xcursor_init1(mc, leaf);
5534 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5538 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5542 MDB_GET_KEY(leaf, key);
5546 /** Move the cursor to the last item in the database. */
5548 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5554 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5556 if (!(mc->mc_flags & C_EOF)) {
5558 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5559 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5560 if (rc != MDB_SUCCESS)
5563 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5566 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5567 mc->mc_flags |= C_INITIALIZED|C_EOF;
5568 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5570 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5571 key->mv_size = mc->mc_db->md_pad;
5572 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5577 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5578 mdb_xcursor_init1(mc, leaf);
5579 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5583 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5588 MDB_GET_KEY(leaf, key);
5593 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5598 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5603 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5607 case MDB_GET_CURRENT:
5608 if (!(mc->mc_flags & C_INITIALIZED)) {
5611 MDB_page *mp = mc->mc_pg[mc->mc_top];
5612 int nkeys = NUMKEYS(mp);
5613 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5614 mc->mc_ki[mc->mc_top] = nkeys;
5620 key->mv_size = mc->mc_db->md_pad;
5621 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5623 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5624 MDB_GET_KEY(leaf, key);
5626 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5627 if (mc->mc_flags & C_DEL)
5628 mdb_xcursor_init1(mc, leaf);
5629 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5631 rc = mdb_node_read(mc->mc_txn, leaf, data);
5638 case MDB_GET_BOTH_RANGE:
5643 if (mc->mc_xcursor == NULL) {
5644 rc = MDB_INCOMPATIBLE;
5654 rc = mdb_cursor_set(mc, key, data, op,
5655 op == MDB_SET_RANGE ? NULL : &exact);
5658 case MDB_GET_MULTIPLE:
5659 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5663 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5664 rc = MDB_INCOMPATIBLE;
5668 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5669 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5672 case MDB_NEXT_MULTIPLE:
5677 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5678 rc = MDB_INCOMPATIBLE;
5681 if (!(mc->mc_flags & C_INITIALIZED))
5682 rc = mdb_cursor_first(mc, key, data);
5684 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5685 if (rc == MDB_SUCCESS) {
5686 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5689 mx = &mc->mc_xcursor->mx_cursor;
5690 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5692 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5693 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5701 case MDB_NEXT_NODUP:
5702 if (!(mc->mc_flags & C_INITIALIZED))
5703 rc = mdb_cursor_first(mc, key, data);
5705 rc = mdb_cursor_next(mc, key, data, op);
5709 case MDB_PREV_NODUP:
5710 if (!(mc->mc_flags & C_INITIALIZED)) {
5711 rc = mdb_cursor_last(mc, key, data);
5714 mc->mc_flags |= C_INITIALIZED;
5715 mc->mc_ki[mc->mc_top]++;
5717 rc = mdb_cursor_prev(mc, key, data, op);
5720 rc = mdb_cursor_first(mc, key, data);
5723 mfunc = mdb_cursor_first;
5725 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5729 if (mc->mc_xcursor == NULL) {
5730 rc = MDB_INCOMPATIBLE;
5733 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5737 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5740 rc = mdb_cursor_last(mc, key, data);
5743 mfunc = mdb_cursor_last;
5746 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5751 if (mc->mc_flags & C_DEL)
5752 mc->mc_flags ^= C_DEL;
5757 /** Touch all the pages in the cursor stack. Set mc_top.
5758 * Makes sure all the pages are writable, before attempting a write operation.
5759 * @param[in] mc The cursor to operate on.
5762 mdb_cursor_touch(MDB_cursor *mc)
5764 int rc = MDB_SUCCESS;
5766 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5769 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5770 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5773 *mc->mc_dbflag |= DB_DIRTY;
5778 rc = mdb_page_touch(mc);
5779 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5780 mc->mc_top = mc->mc_snum-1;
5785 /** Do not spill pages to disk if txn is getting full, may fail instead */
5786 #define MDB_NOSPILL 0x8000
5789 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5792 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5794 MDB_node *leaf = NULL;
5797 MDB_val xdata, *rdata, dkey, olddata;
5799 int do_sub = 0, insert_key, insert_data;
5800 unsigned int mcount = 0, dcount = 0, nospill;
5803 unsigned int nflags;
5806 if (mc == NULL || key == NULL)
5809 env = mc->mc_txn->mt_env;
5811 /* Check this first so counter will always be zero on any
5814 if (flags & MDB_MULTIPLE) {
5815 dcount = data[1].mv_size;
5816 data[1].mv_size = 0;
5817 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5818 return MDB_INCOMPATIBLE;
5821 nospill = flags & MDB_NOSPILL;
5822 flags &= ~MDB_NOSPILL;
5824 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5825 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5827 if (key->mv_size-1 >= ENV_MAXKEY(env))
5828 return MDB_BAD_VALSIZE;
5830 #if SIZE_MAX > MAXDATASIZE
5831 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5832 return MDB_BAD_VALSIZE;
5834 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5835 return MDB_BAD_VALSIZE;
5838 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5839 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5843 if (flags == MDB_CURRENT) {
5844 if (!(mc->mc_flags & C_INITIALIZED))
5847 } else if (mc->mc_db->md_root == P_INVALID) {
5848 /* new database, cursor has nothing to point to */
5851 mc->mc_flags &= ~C_INITIALIZED;
5856 if (flags & MDB_APPEND) {
5858 rc = mdb_cursor_last(mc, &k2, &d2);
5860 rc = mc->mc_dbx->md_cmp(key, &k2);
5863 mc->mc_ki[mc->mc_top]++;
5865 /* new key is <= last key */
5870 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5872 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5873 DPRINTF(("duplicate key [%s]", DKEY(key)));
5875 return MDB_KEYEXIST;
5877 if (rc && rc != MDB_NOTFOUND)
5881 if (mc->mc_flags & C_DEL)
5882 mc->mc_flags ^= C_DEL;
5884 /* Cursor is positioned, check for room in the dirty list */
5886 if (flags & MDB_MULTIPLE) {
5888 xdata.mv_size = data->mv_size * dcount;
5892 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5896 if (rc == MDB_NO_ROOT) {
5898 /* new database, write a root leaf page */
5899 DPUTS("allocating new root leaf page");
5900 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5903 mdb_cursor_push(mc, np);
5904 mc->mc_db->md_root = np->mp_pgno;
5905 mc->mc_db->md_depth++;
5906 *mc->mc_dbflag |= DB_DIRTY;
5907 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5909 np->mp_flags |= P_LEAF2;
5910 mc->mc_flags |= C_INITIALIZED;
5912 /* make sure all cursor pages are writable */
5913 rc2 = mdb_cursor_touch(mc);
5918 insert_key = insert_data = rc;
5920 /* The key does not exist */
5921 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5922 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
5923 LEAFSIZE(key, data) > env->me_nodemax)
5925 /* Too big for a node, insert in sub-DB */
5926 fp_flags = P_LEAF|P_DIRTY;
5928 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
5929 fp->mp_lower = fp->mp_upper = olddata.mv_size = PAGEHDRSZ;
5933 /* there's only a key anyway, so this is a no-op */
5934 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5936 unsigned int ksize = mc->mc_db->md_pad;
5937 if (key->mv_size != ksize)
5938 return MDB_BAD_VALSIZE;
5939 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5940 memcpy(ptr, key->mv_data, ksize);
5945 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5946 olddata.mv_size = NODEDSZ(leaf);
5947 olddata.mv_data = NODEDATA(leaf);
5950 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5951 /* Prepare (sub-)page/sub-DB to accept the new item,
5952 * if needed. fp: old sub-page or a header faking
5953 * it. mp: new (sub-)page. offset: growth in page
5954 * size. xdata: node data with new page or DB.
5956 unsigned i, offset = 0;
5957 mp = fp = xdata.mv_data = env->me_pbuf;
5958 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5960 /* Was a single item before, must convert now */
5961 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5962 /* Just overwrite the current item */
5963 if (flags == MDB_CURRENT)
5966 #if UINT_MAX < SIZE_MAX
5967 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5968 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
5970 /* does data match? */
5971 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
5972 if (flags & MDB_NODUPDATA)
5973 return MDB_KEYEXIST;
5978 /* Back up original data item */
5979 dkey.mv_size = olddata.mv_size;
5980 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
5982 /* Make sub-page header for the dup items, with dummy body */
5983 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5984 fp->mp_lower = PAGEHDRSZ;
5985 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5986 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5987 fp->mp_flags |= P_LEAF2;
5988 fp->mp_pad = data->mv_size;
5989 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
5991 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5992 (dkey.mv_size & 1) + (data->mv_size & 1);
5994 fp->mp_upper = xdata.mv_size;
5995 olddata.mv_size = fp->mp_upper; /* pretend olddata is fp */
5996 } else if (leaf->mn_flags & F_SUBDATA) {
5997 /* Data is on sub-DB, just store it */
5998 flags |= F_DUPDATA|F_SUBDATA;
6001 /* Data is on sub-page */
6002 fp = olddata.mv_data;
6005 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6006 offset = EVEN(NODESIZE + sizeof(indx_t) +
6010 offset = fp->mp_pad;
6011 if (SIZELEFT(fp) < offset) {
6012 offset *= 4; /* space for 4 more */
6015 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6017 fp->mp_flags |= P_DIRTY;
6018 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6019 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6023 xdata.mv_size = olddata.mv_size + offset;
6026 fp_flags = fp->mp_flags;
6027 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6028 /* Too big for a sub-page, convert to sub-DB */
6029 fp_flags &= ~P_SUBP;
6031 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6032 fp_flags |= P_LEAF2;
6033 dummy.md_pad = fp->mp_pad;
6034 dummy.md_flags = MDB_DUPFIXED;
6035 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6036 dummy.md_flags |= MDB_INTEGERKEY;
6042 dummy.md_branch_pages = 0;
6043 dummy.md_leaf_pages = 1;
6044 dummy.md_overflow_pages = 0;
6045 dummy.md_entries = NUMKEYS(fp);
6046 xdata.mv_size = sizeof(MDB_db);
6047 xdata.mv_data = &dummy;
6048 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6050 offset = env->me_psize - olddata.mv_size;
6051 flags |= F_DUPDATA|F_SUBDATA;
6052 dummy.md_root = mp->mp_pgno;
6055 mp->mp_flags = fp_flags | P_DIRTY;
6056 mp->mp_pad = fp->mp_pad;
6057 mp->mp_lower = fp->mp_lower;
6058 mp->mp_upper = fp->mp_upper + offset;
6059 if (fp_flags & P_LEAF2) {
6060 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6062 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
6063 olddata.mv_size - fp->mp_upper);
6064 for (i=0; i<NUMKEYS(fp); i++)
6065 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6073 mdb_node_del(mc, 0);
6077 /* overflow page overwrites need special handling */
6078 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6081 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6083 memcpy(&pg, olddata.mv_data, sizeof(pg));
6084 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6086 ovpages = omp->mp_pages;
6088 /* Is the ov page large enough? */
6089 if (ovpages >= dpages) {
6090 if (!(omp->mp_flags & P_DIRTY) &&
6091 (level || (env->me_flags & MDB_WRITEMAP)))
6093 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6096 level = 0; /* dirty in this txn or clean */
6099 if (omp->mp_flags & P_DIRTY) {
6100 /* yes, overwrite it. Note in this case we don't
6101 * bother to try shrinking the page if the new data
6102 * is smaller than the overflow threshold.
6105 /* It is writable only in a parent txn */
6106 size_t sz = (size_t) env->me_psize * ovpages, off;
6107 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6113 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6114 mdb_cassert(mc, rc2 == 0);
6115 if (!(flags & MDB_RESERVE)) {
6116 /* Copy end of page, adjusting alignment so
6117 * compiler may copy words instead of bytes.
6119 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6120 memcpy((size_t *)((char *)np + off),
6121 (size_t *)((char *)omp + off), sz - off);
6124 memcpy(np, omp, sz); /* Copy beginning of page */
6127 SETDSZ(leaf, data->mv_size);
6128 if (F_ISSET(flags, MDB_RESERVE))
6129 data->mv_data = METADATA(omp);
6131 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6135 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6137 } else if (data->mv_size == olddata.mv_size) {
6138 /* same size, just replace it. Note that we could
6139 * also reuse this node if the new data is smaller,
6140 * but instead we opt to shrink the node in that case.
6142 if (F_ISSET(flags, MDB_RESERVE))
6143 data->mv_data = olddata.mv_data;
6144 else if (!(mc->mc_flags & C_SUB))
6145 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6147 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6150 mdb_node_del(mc, 0);
6156 nflags = flags & NODE_ADD_FLAGS;
6157 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6158 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6159 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6160 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6162 nflags |= MDB_SPLIT_REPLACE;
6163 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6165 /* There is room already in this leaf page. */
6166 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6167 if (rc == 0 && insert_key) {
6168 /* Adjust other cursors pointing to mp */
6169 MDB_cursor *m2, *m3;
6170 MDB_dbi dbi = mc->mc_dbi;
6171 unsigned i = mc->mc_top;
6172 MDB_page *mp = mc->mc_pg[i];
6174 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6175 if (mc->mc_flags & C_SUB)
6176 m3 = &m2->mc_xcursor->mx_cursor;
6179 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6180 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6187 if (rc == MDB_SUCCESS) {
6188 /* Now store the actual data in the child DB. Note that we're
6189 * storing the user data in the keys field, so there are strict
6190 * size limits on dupdata. The actual data fields of the child
6191 * DB are all zero size.
6199 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6200 if (flags & MDB_CURRENT) {
6201 xflags = MDB_CURRENT|MDB_NOSPILL;
6203 mdb_xcursor_init1(mc, leaf);
6204 xflags = (flags & MDB_NODUPDATA) ?
6205 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6207 /* converted, write the original data first */
6209 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6213 /* Adjust other cursors pointing to mp */
6215 unsigned i = mc->mc_top;
6216 MDB_page *mp = mc->mc_pg[i];
6218 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6219 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6220 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6221 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6222 mdb_xcursor_init1(m2, leaf);
6226 /* we've done our job */
6229 ecount = mc->mc_xcursor->mx_db.md_entries;
6230 if (flags & MDB_APPENDDUP)
6231 xflags |= MDB_APPEND;
6232 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6233 if (flags & F_SUBDATA) {
6234 void *db = NODEDATA(leaf);
6235 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6237 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6239 /* Increment count unless we just replaced an existing item. */
6241 mc->mc_db->md_entries++;
6243 /* Invalidate txn if we created an empty sub-DB */
6246 /* If we succeeded and the key didn't exist before,
6247 * make sure the cursor is marked valid.
6249 mc->mc_flags |= C_INITIALIZED;
6251 if (flags & MDB_MULTIPLE) {
6254 /* let caller know how many succeeded, if any */
6255 data[1].mv_size = mcount;
6256 if (mcount < dcount) {
6257 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6258 insert_key = insert_data = 0;
6265 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6268 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6273 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6279 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6280 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6282 if (!(mc->mc_flags & C_INITIALIZED))
6285 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6286 return MDB_NOTFOUND;
6288 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6291 rc = mdb_cursor_touch(mc);
6295 mp = mc->mc_pg[mc->mc_top];
6298 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6300 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6301 if (flags & MDB_NODUPDATA) {
6302 /* mdb_cursor_del0() will subtract the final entry */
6303 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6305 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6306 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6308 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6311 /* If sub-DB still has entries, we're done */
6312 if (mc->mc_xcursor->mx_db.md_entries) {
6313 if (leaf->mn_flags & F_SUBDATA) {
6314 /* update subDB info */
6315 void *db = NODEDATA(leaf);
6316 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6319 /* shrink fake page */
6320 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6321 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6322 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6323 /* fix other sub-DB cursors pointed at this fake page */
6324 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6325 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6326 if (m2->mc_pg[mc->mc_top] == mp &&
6327 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6328 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6331 mc->mc_db->md_entries--;
6332 mc->mc_flags |= C_DEL;
6335 /* otherwise fall thru and delete the sub-DB */
6338 if (leaf->mn_flags & F_SUBDATA) {
6339 /* add all the child DB's pages to the free list */
6340 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6346 /* add overflow pages to free list */
6347 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6351 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6352 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6353 (rc = mdb_ovpage_free(mc, omp)))
6358 return mdb_cursor_del0(mc);
6361 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6365 /** Allocate and initialize new pages for a database.
6366 * @param[in] mc a cursor on the database being added to.
6367 * @param[in] flags flags defining what type of page is being allocated.
6368 * @param[in] num the number of pages to allocate. This is usually 1,
6369 * unless allocating overflow pages for a large record.
6370 * @param[out] mp Address of a page, or NULL on failure.
6371 * @return 0 on success, non-zero on failure.
6374 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6379 if ((rc = mdb_page_alloc(mc, num, &np)))
6381 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6382 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6383 np->mp_flags = flags | P_DIRTY;
6384 np->mp_lower = PAGEHDRSZ;
6385 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6388 mc->mc_db->md_branch_pages++;
6389 else if (IS_LEAF(np))
6390 mc->mc_db->md_leaf_pages++;
6391 else if (IS_OVERFLOW(np)) {
6392 mc->mc_db->md_overflow_pages += num;
6400 /** Calculate the size of a leaf node.
6401 * The size depends on the environment's page size; if a data item
6402 * is too large it will be put onto an overflow page and the node
6403 * size will only include the key and not the data. Sizes are always
6404 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6405 * of the #MDB_node headers.
6406 * @param[in] env The environment handle.
6407 * @param[in] key The key for the node.
6408 * @param[in] data The data for the node.
6409 * @return The number of bytes needed to store the node.
6412 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6416 sz = LEAFSIZE(key, data);
6417 if (sz > env->me_nodemax) {
6418 /* put on overflow page */
6419 sz -= data->mv_size - sizeof(pgno_t);
6422 return EVEN(sz + sizeof(indx_t));
6425 /** Calculate the size of a branch node.
6426 * The size should depend on the environment's page size but since
6427 * we currently don't support spilling large keys onto overflow
6428 * pages, it's simply the size of the #MDB_node header plus the
6429 * size of the key. Sizes are always rounded up to an even number
6430 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6431 * @param[in] env The environment handle.
6432 * @param[in] key The key for the node.
6433 * @return The number of bytes needed to store the node.
6436 mdb_branch_size(MDB_env *env, MDB_val *key)
6441 if (sz > env->me_nodemax) {
6442 /* put on overflow page */
6443 /* not implemented */
6444 /* sz -= key->size - sizeof(pgno_t); */
6447 return sz + sizeof(indx_t);
6450 /** Add a node to the page pointed to by the cursor.
6451 * @param[in] mc The cursor for this operation.
6452 * @param[in] indx The index on the page where the new node should be added.
6453 * @param[in] key The key for the new node.
6454 * @param[in] data The data for the new node, if any.
6455 * @param[in] pgno The page number, if adding a branch node.
6456 * @param[in] flags Flags for the node.
6457 * @return 0 on success, non-zero on failure. Possible errors are:
6459 * <li>ENOMEM - failed to allocate overflow pages for the node.
6460 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6461 * should never happen since all callers already calculate the
6462 * page's free space before calling this function.
6466 mdb_node_add(MDB_cursor *mc, indx_t indx,
6467 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6470 size_t node_size = NODESIZE;
6474 MDB_page *mp = mc->mc_pg[mc->mc_top];
6475 MDB_page *ofp = NULL; /* overflow page */
6478 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6480 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6481 IS_LEAF(mp) ? "leaf" : "branch",
6482 IS_SUBP(mp) ? "sub-" : "",
6483 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6484 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6487 /* Move higher keys up one slot. */
6488 int ksize = mc->mc_db->md_pad, dif;
6489 char *ptr = LEAF2KEY(mp, indx, ksize);
6490 dif = NUMKEYS(mp) - indx;
6492 memmove(ptr+ksize, ptr, dif*ksize);
6493 /* insert new key */
6494 memcpy(ptr, key->mv_data, ksize);
6496 /* Just using these for counting */
6497 mp->mp_lower += sizeof(indx_t);
6498 mp->mp_upper -= ksize - sizeof(indx_t);
6502 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6504 node_size += key->mv_size;
6506 mdb_cassert(mc, data);
6507 if (F_ISSET(flags, F_BIGDATA)) {
6508 /* Data already on overflow page. */
6509 node_size += sizeof(pgno_t);
6510 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6511 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6513 /* Put data on overflow page. */
6514 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6515 data->mv_size, node_size+data->mv_size));
6516 node_size = EVEN(node_size + sizeof(pgno_t));
6517 if ((ssize_t)node_size > room)
6519 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6521 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6525 node_size += data->mv_size;
6528 node_size = EVEN(node_size);
6529 if ((ssize_t)node_size > room)
6533 /* Move higher pointers up one slot. */
6534 for (i = NUMKEYS(mp); i > indx; i--)
6535 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6537 /* Adjust free space offsets. */
6538 ofs = mp->mp_upper - node_size;
6539 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6540 mp->mp_ptrs[indx] = ofs;
6542 mp->mp_lower += sizeof(indx_t);
6544 /* Write the node data. */
6545 node = NODEPTR(mp, indx);
6546 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6547 node->mn_flags = flags;
6549 SETDSZ(node,data->mv_size);
6554 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6557 mdb_cassert(mc, key);
6559 if (F_ISSET(flags, F_BIGDATA))
6560 memcpy(node->mn_data + key->mv_size, data->mv_data,
6562 else if (F_ISSET(flags, MDB_RESERVE))
6563 data->mv_data = node->mn_data + key->mv_size;
6565 memcpy(node->mn_data + key->mv_size, data->mv_data,
6568 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6570 if (F_ISSET(flags, MDB_RESERVE))
6571 data->mv_data = METADATA(ofp);
6573 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6580 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6581 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6582 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6583 DPRINTF(("node size = %"Z"u", node_size));
6584 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6585 return MDB_PAGE_FULL;
6588 /** Delete the specified node from a page.
6589 * @param[in] mc Cursor pointing to the node to delete.
6590 * @param[in] ksize The size of a node. Only used if the page is
6591 * part of a #MDB_DUPFIXED database.
6594 mdb_node_del(MDB_cursor *mc, int ksize)
6596 MDB_page *mp = mc->mc_pg[mc->mc_top];
6597 indx_t indx = mc->mc_ki[mc->mc_top];
6599 indx_t i, j, numkeys, ptr;
6603 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6604 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6605 numkeys = NUMKEYS(mp);
6606 mdb_cassert(mc, indx < numkeys);
6609 int x = numkeys - 1 - indx;
6610 base = LEAF2KEY(mp, indx, ksize);
6612 memmove(base, base + ksize, x * ksize);
6613 mp->mp_lower -= sizeof(indx_t);
6614 mp->mp_upper += ksize - sizeof(indx_t);
6618 node = NODEPTR(mp, indx);
6619 sz = NODESIZE + node->mn_ksize;
6621 if (F_ISSET(node->mn_flags, F_BIGDATA))
6622 sz += sizeof(pgno_t);
6624 sz += NODEDSZ(node);
6628 ptr = mp->mp_ptrs[indx];
6629 for (i = j = 0; i < numkeys; i++) {
6631 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6632 if (mp->mp_ptrs[i] < ptr)
6633 mp->mp_ptrs[j] += sz;
6638 base = (char *)mp + mp->mp_upper;
6639 memmove(base + sz, base, ptr - mp->mp_upper);
6641 mp->mp_lower -= sizeof(indx_t);
6645 /** Compact the main page after deleting a node on a subpage.
6646 * @param[in] mp The main page to operate on.
6647 * @param[in] indx The index of the subpage on the main page.
6650 mdb_node_shrink(MDB_page *mp, indx_t indx)
6656 indx_t i, numkeys, ptr;
6658 node = NODEPTR(mp, indx);
6659 sp = (MDB_page *)NODEDATA(node);
6660 delta = SIZELEFT(sp);
6661 xp = (MDB_page *)((char *)sp + delta);
6663 /* shift subpage upward */
6665 nsize = NUMKEYS(sp) * sp->mp_pad;
6667 return; /* do not make the node uneven-sized */
6668 memmove(METADATA(xp), METADATA(sp), nsize);
6671 numkeys = NUMKEYS(sp);
6672 for (i=numkeys-1; i>=0; i--)
6673 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6675 xp->mp_upper = sp->mp_lower;
6676 xp->mp_lower = sp->mp_lower;
6677 xp->mp_flags = sp->mp_flags;
6678 xp->mp_pad = sp->mp_pad;
6679 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6681 nsize = NODEDSZ(node) - delta;
6682 SETDSZ(node, nsize);
6684 /* shift lower nodes upward */
6685 ptr = mp->mp_ptrs[indx];
6686 numkeys = NUMKEYS(mp);
6687 for (i = 0; i < numkeys; i++) {
6688 if (mp->mp_ptrs[i] <= ptr)
6689 mp->mp_ptrs[i] += delta;
6692 base = (char *)mp + mp->mp_upper;
6693 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6694 mp->mp_upper += delta;
6697 /** Initial setup of a sorted-dups cursor.
6698 * Sorted duplicates are implemented as a sub-database for the given key.
6699 * The duplicate data items are actually keys of the sub-database.
6700 * Operations on the duplicate data items are performed using a sub-cursor
6701 * initialized when the sub-database is first accessed. This function does
6702 * the preliminary setup of the sub-cursor, filling in the fields that
6703 * depend only on the parent DB.
6704 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6707 mdb_xcursor_init0(MDB_cursor *mc)
6709 MDB_xcursor *mx = mc->mc_xcursor;
6711 mx->mx_cursor.mc_xcursor = NULL;
6712 mx->mx_cursor.mc_txn = mc->mc_txn;
6713 mx->mx_cursor.mc_db = &mx->mx_db;
6714 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6715 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6716 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6717 mx->mx_cursor.mc_snum = 0;
6718 mx->mx_cursor.mc_top = 0;
6719 mx->mx_cursor.mc_flags = C_SUB;
6720 mx->mx_dbx.md_name.mv_size = 0;
6721 mx->mx_dbx.md_name.mv_data = NULL;
6722 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6723 mx->mx_dbx.md_dcmp = NULL;
6724 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6727 /** Final setup of a sorted-dups cursor.
6728 * Sets up the fields that depend on the data from the main cursor.
6729 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6730 * @param[in] node The data containing the #MDB_db record for the
6731 * sorted-dup database.
6734 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6736 MDB_xcursor *mx = mc->mc_xcursor;
6738 if (node->mn_flags & F_SUBDATA) {
6739 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6740 mx->mx_cursor.mc_pg[0] = 0;
6741 mx->mx_cursor.mc_snum = 0;
6742 mx->mx_cursor.mc_top = 0;
6743 mx->mx_cursor.mc_flags = C_SUB;
6745 MDB_page *fp = NODEDATA(node);
6746 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6747 mx->mx_db.md_flags = 0;
6748 mx->mx_db.md_depth = 1;
6749 mx->mx_db.md_branch_pages = 0;
6750 mx->mx_db.md_leaf_pages = 1;
6751 mx->mx_db.md_overflow_pages = 0;
6752 mx->mx_db.md_entries = NUMKEYS(fp);
6753 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6754 mx->mx_cursor.mc_snum = 1;
6755 mx->mx_cursor.mc_top = 0;
6756 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6757 mx->mx_cursor.mc_pg[0] = fp;
6758 mx->mx_cursor.mc_ki[0] = 0;
6759 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6760 mx->mx_db.md_flags = MDB_DUPFIXED;
6761 mx->mx_db.md_pad = fp->mp_pad;
6762 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6763 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6766 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6767 mx->mx_db.md_root));
6768 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6769 #if UINT_MAX < SIZE_MAX
6770 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6771 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6775 /** Initialize a cursor for a given transaction and database. */
6777 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6780 mc->mc_backup = NULL;
6783 mc->mc_db = &txn->mt_dbs[dbi];
6784 mc->mc_dbx = &txn->mt_dbxs[dbi];
6785 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6790 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6791 mdb_tassert(txn, mx != NULL);
6792 mc->mc_xcursor = mx;
6793 mdb_xcursor_init0(mc);
6795 mc->mc_xcursor = NULL;
6797 if (*mc->mc_dbflag & DB_STALE) {
6798 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6803 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6806 size_t size = sizeof(MDB_cursor);
6808 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6811 if (txn->mt_flags & MDB_TXN_ERROR)
6814 /* Allow read access to the freelist */
6815 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6818 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6819 size += sizeof(MDB_xcursor);
6821 if ((mc = malloc(size)) != NULL) {
6822 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6823 if (txn->mt_cursors) {
6824 mc->mc_next = txn->mt_cursors[dbi];
6825 txn->mt_cursors[dbi] = mc;
6826 mc->mc_flags |= C_UNTRACK;
6838 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6840 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6843 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6846 if (txn->mt_flags & MDB_TXN_ERROR)
6849 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6853 /* Return the count of duplicate data items for the current key */
6855 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6859 if (mc == NULL || countp == NULL)
6862 if (mc->mc_xcursor == NULL)
6863 return MDB_INCOMPATIBLE;
6865 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
6868 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6869 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6872 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6875 *countp = mc->mc_xcursor->mx_db.md_entries;
6881 mdb_cursor_close(MDB_cursor *mc)
6883 if (mc && !mc->mc_backup) {
6884 /* remove from txn, if tracked */
6885 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6886 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6887 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6889 *prev = mc->mc_next;
6896 mdb_cursor_txn(MDB_cursor *mc)
6898 if (!mc) return NULL;
6903 mdb_cursor_dbi(MDB_cursor *mc)
6908 /** Replace the key for a branch node with a new key.
6909 * @param[in] mc Cursor pointing to the node to operate on.
6910 * @param[in] key The new key to use.
6911 * @return 0 on success, non-zero on failure.
6914 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6920 int delta, ksize, oksize;
6921 indx_t ptr, i, numkeys, indx;
6924 indx = mc->mc_ki[mc->mc_top];
6925 mp = mc->mc_pg[mc->mc_top];
6926 node = NODEPTR(mp, indx);
6927 ptr = mp->mp_ptrs[indx];
6931 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
6932 k2.mv_data = NODEKEY(node);
6933 k2.mv_size = node->mn_ksize;
6934 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6936 mdb_dkey(&k2, kbuf2),
6942 /* Sizes must be 2-byte aligned. */
6943 ksize = EVEN(key->mv_size);
6944 oksize = EVEN(node->mn_ksize);
6945 delta = ksize - oksize;
6947 /* Shift node contents if EVEN(key length) changed. */
6949 if (delta > 0 && SIZELEFT(mp) < delta) {
6951 /* not enough space left, do a delete and split */
6952 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6953 pgno = NODEPGNO(node);
6954 mdb_node_del(mc, 0);
6955 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6958 numkeys = NUMKEYS(mp);
6959 for (i = 0; i < numkeys; i++) {
6960 if (mp->mp_ptrs[i] <= ptr)
6961 mp->mp_ptrs[i] -= delta;
6964 base = (char *)mp + mp->mp_upper;
6965 len = ptr - mp->mp_upper + NODESIZE;
6966 memmove(base - delta, base, len);
6967 mp->mp_upper -= delta;
6969 node = NODEPTR(mp, indx);
6972 /* But even if no shift was needed, update ksize */
6973 if (node->mn_ksize != key->mv_size)
6974 node->mn_ksize = key->mv_size;
6977 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6983 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6985 /** Move a node from csrc to cdst.
6988 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6995 unsigned short flags;
6999 /* Mark src and dst as dirty. */
7000 if ((rc = mdb_page_touch(csrc)) ||
7001 (rc = mdb_page_touch(cdst)))
7004 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7005 key.mv_size = csrc->mc_db->md_pad;
7006 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7008 data.mv_data = NULL;
7012 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7013 mdb_cassert(csrc, !((size_t)srcnode & 1));
7014 srcpg = NODEPGNO(srcnode);
7015 flags = srcnode->mn_flags;
7016 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7017 unsigned int snum = csrc->mc_snum;
7019 /* must find the lowest key below src */
7020 rc = mdb_page_search_lowest(csrc);
7023 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7024 key.mv_size = csrc->mc_db->md_pad;
7025 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7027 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7028 key.mv_size = NODEKSZ(s2);
7029 key.mv_data = NODEKEY(s2);
7031 csrc->mc_snum = snum--;
7032 csrc->mc_top = snum;
7034 key.mv_size = NODEKSZ(srcnode);
7035 key.mv_data = NODEKEY(srcnode);
7037 data.mv_size = NODEDSZ(srcnode);
7038 data.mv_data = NODEDATA(srcnode);
7040 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7041 unsigned int snum = cdst->mc_snum;
7044 /* must find the lowest key below dst */
7045 mdb_cursor_copy(cdst, &mn);
7046 rc = mdb_page_search_lowest(&mn);
7049 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7050 bkey.mv_size = mn.mc_db->md_pad;
7051 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7053 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7054 bkey.mv_size = NODEKSZ(s2);
7055 bkey.mv_data = NODEKEY(s2);
7057 mn.mc_snum = snum--;
7060 rc = mdb_update_key(&mn, &bkey);
7065 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7066 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7067 csrc->mc_ki[csrc->mc_top],
7069 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7070 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7072 /* Add the node to the destination page.
7074 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7075 if (rc != MDB_SUCCESS)
7078 /* Delete the node from the source page.
7080 mdb_node_del(csrc, key.mv_size);
7083 /* Adjust other cursors pointing to mp */
7084 MDB_cursor *m2, *m3;
7085 MDB_dbi dbi = csrc->mc_dbi;
7086 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7088 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7089 if (csrc->mc_flags & C_SUB)
7090 m3 = &m2->mc_xcursor->mx_cursor;
7093 if (m3 == csrc) continue;
7094 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7095 csrc->mc_ki[csrc->mc_top]) {
7096 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7097 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7102 /* Update the parent separators.
7104 if (csrc->mc_ki[csrc->mc_top] == 0) {
7105 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7106 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7107 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7109 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7110 key.mv_size = NODEKSZ(srcnode);
7111 key.mv_data = NODEKEY(srcnode);
7113 DPRINTF(("update separator for source page %"Z"u to [%s]",
7114 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7115 mdb_cursor_copy(csrc, &mn);
7118 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7121 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7123 indx_t ix = csrc->mc_ki[csrc->mc_top];
7124 nullkey.mv_size = 0;
7125 csrc->mc_ki[csrc->mc_top] = 0;
7126 rc = mdb_update_key(csrc, &nullkey);
7127 csrc->mc_ki[csrc->mc_top] = ix;
7128 mdb_cassert(csrc, rc == MDB_SUCCESS);
7132 if (cdst->mc_ki[cdst->mc_top] == 0) {
7133 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7134 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7135 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7137 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7138 key.mv_size = NODEKSZ(srcnode);
7139 key.mv_data = NODEKEY(srcnode);
7141 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7142 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7143 mdb_cursor_copy(cdst, &mn);
7146 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7149 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7151 indx_t ix = cdst->mc_ki[cdst->mc_top];
7152 nullkey.mv_size = 0;
7153 cdst->mc_ki[cdst->mc_top] = 0;
7154 rc = mdb_update_key(cdst, &nullkey);
7155 cdst->mc_ki[cdst->mc_top] = ix;
7156 mdb_cassert(csrc, rc == MDB_SUCCESS);
7163 /** Merge one page into another.
7164 * The nodes from the page pointed to by \b csrc will
7165 * be copied to the page pointed to by \b cdst and then
7166 * the \b csrc page will be freed.
7167 * @param[in] csrc Cursor pointing to the source page.
7168 * @param[in] cdst Cursor pointing to the destination page.
7169 * @return 0 on success, non-zero on failure.
7172 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7174 MDB_page *psrc, *pdst;
7181 psrc = csrc->mc_pg[csrc->mc_top];
7182 pdst = cdst->mc_pg[cdst->mc_top];
7184 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7186 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7187 mdb_cassert(csrc, cdst->mc_snum > 1);
7189 /* Mark dst as dirty. */
7190 if ((rc = mdb_page_touch(cdst)))
7193 /* Move all nodes from src to dst.
7195 j = nkeys = NUMKEYS(pdst);
7196 if (IS_LEAF2(psrc)) {
7197 key.mv_size = csrc->mc_db->md_pad;
7198 key.mv_data = METADATA(psrc);
7199 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7200 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7201 if (rc != MDB_SUCCESS)
7203 key.mv_data = (char *)key.mv_data + key.mv_size;
7206 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7207 srcnode = NODEPTR(psrc, i);
7208 if (i == 0 && IS_BRANCH(psrc)) {
7211 mdb_cursor_copy(csrc, &mn);
7212 /* must find the lowest key below src */
7213 rc = mdb_page_search_lowest(&mn);
7216 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7217 key.mv_size = mn.mc_db->md_pad;
7218 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7220 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7221 key.mv_size = NODEKSZ(s2);
7222 key.mv_data = NODEKEY(s2);
7225 key.mv_size = srcnode->mn_ksize;
7226 key.mv_data = NODEKEY(srcnode);
7229 data.mv_size = NODEDSZ(srcnode);
7230 data.mv_data = NODEDATA(srcnode);
7231 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7232 if (rc != MDB_SUCCESS)
7237 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7238 pdst->mp_pgno, NUMKEYS(pdst),
7239 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7241 /* Unlink the src page from parent and add to free list.
7244 mdb_node_del(csrc, 0);
7245 if (csrc->mc_ki[csrc->mc_top] == 0) {
7247 rc = mdb_update_key(csrc, &key);
7255 psrc = csrc->mc_pg[csrc->mc_top];
7256 /* If not operating on FreeDB, allow this page to be reused
7257 * in this txn. Otherwise just add to free list.
7259 rc = mdb_page_loose(csrc, psrc);
7263 csrc->mc_db->md_leaf_pages--;
7265 csrc->mc_db->md_branch_pages--;
7267 /* Adjust other cursors pointing to mp */
7268 MDB_cursor *m2, *m3;
7269 MDB_dbi dbi = csrc->mc_dbi;
7271 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7272 if (csrc->mc_flags & C_SUB)
7273 m3 = &m2->mc_xcursor->mx_cursor;
7276 if (m3 == csrc) continue;
7277 if (m3->mc_snum < csrc->mc_snum) continue;
7278 if (m3->mc_pg[csrc->mc_top] == psrc) {
7279 m3->mc_pg[csrc->mc_top] = pdst;
7280 m3->mc_ki[csrc->mc_top] += nkeys;
7285 unsigned int snum = cdst->mc_snum;
7286 uint16_t depth = cdst->mc_db->md_depth;
7287 mdb_cursor_pop(cdst);
7288 rc = mdb_rebalance(cdst);
7289 /* Did the tree shrink? */
7290 if (depth > cdst->mc_db->md_depth)
7292 cdst->mc_snum = snum;
7293 cdst->mc_top = snum-1;
7298 /** Copy the contents of a cursor.
7299 * @param[in] csrc The cursor to copy from.
7300 * @param[out] cdst The cursor to copy to.
7303 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7307 cdst->mc_txn = csrc->mc_txn;
7308 cdst->mc_dbi = csrc->mc_dbi;
7309 cdst->mc_db = csrc->mc_db;
7310 cdst->mc_dbx = csrc->mc_dbx;
7311 cdst->mc_snum = csrc->mc_snum;
7312 cdst->mc_top = csrc->mc_top;
7313 cdst->mc_flags = csrc->mc_flags;
7315 for (i=0; i<csrc->mc_snum; i++) {
7316 cdst->mc_pg[i] = csrc->mc_pg[i];
7317 cdst->mc_ki[i] = csrc->mc_ki[i];
7321 /** Rebalance the tree after a delete operation.
7322 * @param[in] mc Cursor pointing to the page where rebalancing
7324 * @return 0 on success, non-zero on failure.
7327 mdb_rebalance(MDB_cursor *mc)
7331 unsigned int ptop, minkeys;
7335 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7336 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7337 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7338 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7339 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7341 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7342 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7343 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7344 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7348 if (mc->mc_snum < 2) {
7349 MDB_page *mp = mc->mc_pg[0];
7351 DPUTS("Can't rebalance a subpage, ignoring");
7354 if (NUMKEYS(mp) == 0) {
7355 DPUTS("tree is completely empty");
7356 mc->mc_db->md_root = P_INVALID;
7357 mc->mc_db->md_depth = 0;
7358 mc->mc_db->md_leaf_pages = 0;
7359 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7362 /* Adjust cursors pointing to mp */
7365 mc->mc_flags &= ~C_INITIALIZED;
7367 MDB_cursor *m2, *m3;
7368 MDB_dbi dbi = mc->mc_dbi;
7370 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7371 if (mc->mc_flags & C_SUB)
7372 m3 = &m2->mc_xcursor->mx_cursor;
7375 if (m3->mc_snum < mc->mc_snum) continue;
7376 if (m3->mc_pg[0] == mp) {
7379 m3->mc_flags &= ~C_INITIALIZED;
7383 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7385 DPUTS("collapsing root page!");
7386 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7389 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7390 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7393 mc->mc_db->md_depth--;
7394 mc->mc_db->md_branch_pages--;
7395 mc->mc_ki[0] = mc->mc_ki[1];
7396 for (i = 1; i<mc->mc_db->md_depth; i++) {
7397 mc->mc_pg[i] = mc->mc_pg[i+1];
7398 mc->mc_ki[i] = mc->mc_ki[i+1];
7401 /* Adjust other cursors pointing to mp */
7402 MDB_cursor *m2, *m3;
7403 MDB_dbi dbi = mc->mc_dbi;
7405 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7406 if (mc->mc_flags & C_SUB)
7407 m3 = &m2->mc_xcursor->mx_cursor;
7410 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7411 if (m3->mc_pg[0] == mp) {
7414 for (i=0; i<m3->mc_snum; i++) {
7415 m3->mc_pg[i] = m3->mc_pg[i+1];
7416 m3->mc_ki[i] = m3->mc_ki[i+1];
7422 DPUTS("root page doesn't need rebalancing");
7426 /* The parent (branch page) must have at least 2 pointers,
7427 * otherwise the tree is invalid.
7429 ptop = mc->mc_top-1;
7430 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7432 /* Leaf page fill factor is below the threshold.
7433 * Try to move keys from left or right neighbor, or
7434 * merge with a neighbor page.
7439 mdb_cursor_copy(mc, &mn);
7440 mn.mc_xcursor = NULL;
7442 oldki = mc->mc_ki[mc->mc_top];
7443 if (mc->mc_ki[ptop] == 0) {
7444 /* We're the leftmost leaf in our parent.
7446 DPUTS("reading right neighbor");
7448 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7449 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7452 mn.mc_ki[mn.mc_top] = 0;
7453 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7455 /* There is at least one neighbor to the left.
7457 DPUTS("reading left neighbor");
7459 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7460 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7463 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7464 mc->mc_ki[mc->mc_top] = 0;
7467 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7468 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7469 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7471 /* If the neighbor page is above threshold and has enough keys,
7472 * move one key from it. Otherwise we should try to merge them.
7473 * (A branch page must never have less than 2 keys.)
7475 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7476 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7477 rc = mdb_node_move(&mn, mc);
7478 if (mc->mc_ki[ptop]) {
7482 if (mc->mc_ki[ptop] == 0) {
7483 rc = mdb_page_merge(&mn, mc);
7485 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7486 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7487 rc = mdb_page_merge(mc, &mn);
7488 mdb_cursor_copy(&mn, mc);
7490 mc->mc_flags &= ~C_EOF;
7492 mc->mc_ki[mc->mc_top] = oldki;
7496 /** Complete a delete operation started by #mdb_cursor_del(). */
7498 mdb_cursor_del0(MDB_cursor *mc)
7505 ki = mc->mc_ki[mc->mc_top];
7506 mdb_node_del(mc, mc->mc_db->md_pad);
7507 mc->mc_db->md_entries--;
7508 rc = mdb_rebalance(mc);
7510 if (rc == MDB_SUCCESS) {
7511 MDB_cursor *m2, *m3;
7512 MDB_dbi dbi = mc->mc_dbi;
7514 mp = mc->mc_pg[mc->mc_top];
7515 nkeys = NUMKEYS(mp);
7517 /* if mc points past last node in page, find next sibling */
7518 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7519 rc = mdb_cursor_sibling(mc, 1);
7520 if (rc == MDB_NOTFOUND)
7524 /* Adjust other cursors pointing to mp */
7525 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7526 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7527 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7529 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7531 if (m3->mc_pg[mc->mc_top] == mp) {
7532 if (m3->mc_ki[mc->mc_top] >= ki) {
7533 m3->mc_flags |= C_DEL;
7534 if (m3->mc_ki[mc->mc_top] > ki)
7535 m3->mc_ki[mc->mc_top]--;
7537 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7538 rc = mdb_cursor_sibling(m3, 1);
7539 if (rc == MDB_NOTFOUND)
7544 mc->mc_flags |= C_DEL;
7548 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7553 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7554 MDB_val *key, MDB_val *data)
7556 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7559 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7560 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7562 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7563 /* must ignore any data */
7567 return mdb_del0(txn, dbi, key, data, 0);
7571 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7572 MDB_val *key, MDB_val *data, unsigned flags)
7577 MDB_val rdata, *xdata;
7581 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7583 mdb_cursor_init(&mc, txn, dbi, &mx);
7592 flags |= MDB_NODUPDATA;
7594 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7596 /* let mdb_page_split know about this cursor if needed:
7597 * delete will trigger a rebalance; if it needs to move
7598 * a node from one page to another, it will have to
7599 * update the parent's separator key(s). If the new sepkey
7600 * is larger than the current one, the parent page may
7601 * run out of space, triggering a split. We need this
7602 * cursor to be consistent until the end of the rebalance.
7604 mc.mc_flags |= C_UNTRACK;
7605 mc.mc_next = txn->mt_cursors[dbi];
7606 txn->mt_cursors[dbi] = &mc;
7607 rc = mdb_cursor_del(&mc, flags);
7608 txn->mt_cursors[dbi] = mc.mc_next;
7613 /** Split a page and insert a new node.
7614 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7615 * The cursor will be updated to point to the actual page and index where
7616 * the node got inserted after the split.
7617 * @param[in] newkey The key for the newly inserted node.
7618 * @param[in] newdata The data for the newly inserted node.
7619 * @param[in] newpgno The page number, if the new node is a branch node.
7620 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7621 * @return 0 on success, non-zero on failure.
7624 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7625 unsigned int nflags)
7628 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7631 int i, j, split_indx, nkeys, pmax;
7632 MDB_env *env = mc->mc_txn->mt_env;
7634 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7635 MDB_page *copy = NULL;
7636 MDB_page *mp, *rp, *pp;
7641 mp = mc->mc_pg[mc->mc_top];
7642 newindx = mc->mc_ki[mc->mc_top];
7643 nkeys = NUMKEYS(mp);
7645 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7646 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7647 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7649 /* Create a right sibling. */
7650 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7652 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7654 if (mc->mc_snum < 2) {
7655 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7657 /* shift current top to make room for new parent */
7658 mc->mc_pg[1] = mc->mc_pg[0];
7659 mc->mc_ki[1] = mc->mc_ki[0];
7662 mc->mc_db->md_root = pp->mp_pgno;
7663 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7664 mc->mc_db->md_depth++;
7667 /* Add left (implicit) pointer. */
7668 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7669 /* undo the pre-push */
7670 mc->mc_pg[0] = mc->mc_pg[1];
7671 mc->mc_ki[0] = mc->mc_ki[1];
7672 mc->mc_db->md_root = mp->mp_pgno;
7673 mc->mc_db->md_depth--;
7680 ptop = mc->mc_top-1;
7681 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7684 mc->mc_flags |= C_SPLITTING;
7685 mdb_cursor_copy(mc, &mn);
7686 mn.mc_pg[mn.mc_top] = rp;
7687 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7689 if (nflags & MDB_APPEND) {
7690 mn.mc_ki[mn.mc_top] = 0;
7692 split_indx = newindx;
7696 split_indx = (nkeys+1) / 2;
7701 unsigned int lsize, rsize, ksize;
7702 /* Move half of the keys to the right sibling */
7703 x = mc->mc_ki[mc->mc_top] - split_indx;
7704 ksize = mc->mc_db->md_pad;
7705 split = LEAF2KEY(mp, split_indx, ksize);
7706 rsize = (nkeys - split_indx) * ksize;
7707 lsize = (nkeys - split_indx) * sizeof(indx_t);
7708 mp->mp_lower -= lsize;
7709 rp->mp_lower += lsize;
7710 mp->mp_upper += rsize - lsize;
7711 rp->mp_upper -= rsize - lsize;
7712 sepkey.mv_size = ksize;
7713 if (newindx == split_indx) {
7714 sepkey.mv_data = newkey->mv_data;
7716 sepkey.mv_data = split;
7719 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7720 memcpy(rp->mp_ptrs, split, rsize);
7721 sepkey.mv_data = rp->mp_ptrs;
7722 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7723 memcpy(ins, newkey->mv_data, ksize);
7724 mp->mp_lower += sizeof(indx_t);
7725 mp->mp_upper -= ksize - sizeof(indx_t);
7728 memcpy(rp->mp_ptrs, split, x * ksize);
7729 ins = LEAF2KEY(rp, x, ksize);
7730 memcpy(ins, newkey->mv_data, ksize);
7731 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7732 rp->mp_lower += sizeof(indx_t);
7733 rp->mp_upper -= ksize - sizeof(indx_t);
7734 mc->mc_ki[mc->mc_top] = x;
7735 mc->mc_pg[mc->mc_top] = rp;
7738 int psize, nsize, k;
7739 /* Maximum free space in an empty page */
7740 pmax = env->me_psize - PAGEHDRSZ;
7742 nsize = mdb_leaf_size(env, newkey, newdata);
7744 nsize = mdb_branch_size(env, newkey);
7745 nsize = EVEN(nsize);
7747 /* grab a page to hold a temporary copy */
7748 copy = mdb_page_malloc(mc->mc_txn, 1);
7753 copy->mp_pgno = mp->mp_pgno;
7754 copy->mp_flags = mp->mp_flags;
7755 copy->mp_lower = PAGEHDRSZ;
7756 copy->mp_upper = env->me_psize;
7758 /* prepare to insert */
7759 for (i=0, j=0; i<nkeys; i++) {
7761 copy->mp_ptrs[j++] = 0;
7763 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7766 /* When items are relatively large the split point needs
7767 * to be checked, because being off-by-one will make the
7768 * difference between success or failure in mdb_node_add.
7770 * It's also relevant if a page happens to be laid out
7771 * such that one half of its nodes are all "small" and
7772 * the other half of its nodes are "large." If the new
7773 * item is also "large" and falls on the half with
7774 * "large" nodes, it also may not fit.
7776 * As a final tweak, if the new item goes on the last
7777 * spot on the page (and thus, onto the new page), bias
7778 * the split so the new page is emptier than the old page.
7779 * This yields better packing during sequential inserts.
7781 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7782 /* Find split point */
7784 if (newindx <= split_indx || newindx >= nkeys) {
7786 k = newindx >= nkeys ? nkeys : split_indx+2;
7791 for (; i!=k; i+=j) {
7796 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7797 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7799 if (F_ISSET(node->mn_flags, F_BIGDATA))
7800 psize += sizeof(pgno_t);
7802 psize += NODEDSZ(node);
7804 psize = EVEN(psize);
7806 if (psize > pmax || i == k-j) {
7807 split_indx = i + (j<0);
7812 if (split_indx == newindx) {
7813 sepkey.mv_size = newkey->mv_size;
7814 sepkey.mv_data = newkey->mv_data;
7816 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7817 sepkey.mv_size = node->mn_ksize;
7818 sepkey.mv_data = NODEKEY(node);
7823 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7825 /* Copy separator key to the parent.
7827 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7831 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7836 if (mn.mc_snum == mc->mc_snum) {
7837 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7838 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7839 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7840 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7845 /* Right page might now have changed parent.
7846 * Check if left page also changed parent.
7848 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7849 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7850 for (i=0; i<ptop; i++) {
7851 mc->mc_pg[i] = mn.mc_pg[i];
7852 mc->mc_ki[i] = mn.mc_ki[i];
7854 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7855 if (mn.mc_ki[ptop]) {
7856 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7858 /* find right page's left sibling */
7859 mc->mc_ki[ptop] = mn.mc_ki[ptop];
7860 mdb_cursor_sibling(mc, 0);
7865 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7868 mc->mc_flags ^= C_SPLITTING;
7869 if (rc != MDB_SUCCESS) {
7872 if (nflags & MDB_APPEND) {
7873 mc->mc_pg[mc->mc_top] = rp;
7874 mc->mc_ki[mc->mc_top] = 0;
7875 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7878 for (i=0; i<mc->mc_top; i++)
7879 mc->mc_ki[i] = mn.mc_ki[i];
7880 } else if (!IS_LEAF2(mp)) {
7882 mc->mc_pg[mc->mc_top] = rp;
7887 rkey.mv_data = newkey->mv_data;
7888 rkey.mv_size = newkey->mv_size;
7894 /* Update index for the new key. */
7895 mc->mc_ki[mc->mc_top] = j;
7897 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7898 rkey.mv_data = NODEKEY(node);
7899 rkey.mv_size = node->mn_ksize;
7901 xdata.mv_data = NODEDATA(node);
7902 xdata.mv_size = NODEDSZ(node);
7905 pgno = NODEPGNO(node);
7906 flags = node->mn_flags;
7909 if (!IS_LEAF(mp) && j == 0) {
7910 /* First branch index doesn't need key data. */
7914 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7920 mc->mc_pg[mc->mc_top] = copy;
7925 } while (i != split_indx);
7927 nkeys = NUMKEYS(copy);
7928 for (i=0; i<nkeys; i++)
7929 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7930 mp->mp_lower = copy->mp_lower;
7931 mp->mp_upper = copy->mp_upper;
7932 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7933 env->me_psize - copy->mp_upper);
7935 /* reset back to original page */
7936 if (newindx < split_indx) {
7937 mc->mc_pg[mc->mc_top] = mp;
7938 if (nflags & MDB_RESERVE) {
7939 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7940 if (!(node->mn_flags & F_BIGDATA))
7941 newdata->mv_data = NODEDATA(node);
7944 mc->mc_pg[mc->mc_top] = rp;
7946 /* Make sure mc_ki is still valid.
7948 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7949 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7950 for (i=0; i<=ptop; i++) {
7951 mc->mc_pg[i] = mn.mc_pg[i];
7952 mc->mc_ki[i] = mn.mc_ki[i];
7959 /* Adjust other cursors pointing to mp */
7960 MDB_cursor *m2, *m3;
7961 MDB_dbi dbi = mc->mc_dbi;
7962 int fixup = NUMKEYS(mp);
7964 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7965 if (mc->mc_flags & C_SUB)
7966 m3 = &m2->mc_xcursor->mx_cursor;
7971 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7973 if (m3->mc_flags & C_SPLITTING)
7978 for (k=m3->mc_top; k>=0; k--) {
7979 m3->mc_ki[k+1] = m3->mc_ki[k];
7980 m3->mc_pg[k+1] = m3->mc_pg[k];
7982 if (m3->mc_ki[0] >= split_indx) {
7987 m3->mc_pg[0] = mc->mc_pg[0];
7991 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7992 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7993 m3->mc_ki[mc->mc_top]++;
7994 if (m3->mc_ki[mc->mc_top] >= fixup) {
7995 m3->mc_pg[mc->mc_top] = rp;
7996 m3->mc_ki[mc->mc_top] -= fixup;
7997 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7999 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8000 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8005 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8008 if (copy) /* tmp page */
8009 mdb_page_free(env, copy);
8011 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8016 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8017 MDB_val *key, MDB_val *data, unsigned int flags)
8022 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8025 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8028 mdb_cursor_init(&mc, txn, dbi, &mx);
8029 return mdb_cursor_put(&mc, key, data, flags);
8033 #define MDB_WBUF (1024*1024)
8036 typedef struct mdb_copy {
8037 pthread_mutex_t mc_mutex[2];
8044 pgno_t mc_next_pgno;
8051 mdb_env_copythr(void *arg)
8055 int toggle = 0, wsize, rc;
8058 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8061 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8064 pthread_mutex_lock(&my->mc_mutex[toggle^1]);
8066 pthread_mutex_lock(&my->mc_mutex[toggle]);
8067 pthread_mutex_unlock(&my->mc_mutex[toggle^1]);
8068 if (!my->mc_wlen[toggle]) {
8069 pthread_mutex_unlock(&my->mc_mutex[toggle]);
8072 wsize = my->mc_wlen[toggle];
8073 ptr = my->mc_wbuf[toggle];
8076 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8080 } else if (len > 0) {
8092 pthread_mutex_unlock(&my->mc_mutex[toggle]);
8095 /* If there's an overflow page tail, write it too */
8096 if (my->mc_olen[toggle]) {
8097 wsize = my->mc_olen[toggle];
8098 ptr = my->mc_over[toggle];
8099 my->mc_olen[toggle] = 0;
8102 my->mc_wlen[toggle] = 0;
8105 return (THREAD_RET)0;
8110 mdb_env_cthr_toggle(mdb_copy *my)
8112 int toggle = my->mc_toggle ^ 1;
8114 pthread_mutex_unlock(&my->mc_mutex[my->mc_toggle]);
8115 pthread_mutex_lock(&my->mc_mutex[toggle]);
8116 if (my->mc_status) {
8117 pthread_mutex_unlock(&my->mc_mutex[toggle]);
8118 return my->mc_status;
8120 my->mc_toggle = toggle;
8125 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8128 MDB_txn *txn = my->mc_txn;
8130 MDB_page *mo, *mp, *leaf;
8135 /* Empty DB, nothing to do */
8136 if (*pg == P_INVALID)
8143 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8146 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8150 /* Make cursor pages writable */
8151 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8155 for (i=0; i<mc.mc_top; i++) {
8156 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8157 mc.mc_pg[i] = (MDB_page *)ptr;
8158 ptr += my->mc_env->me_psize;
8161 /* This is writable space for a leaf page. Usually not needed. */
8162 leaf = (MDB_page *)ptr;
8164 toggle = my->mc_toggle;
8165 while (mc.mc_snum > 0) {
8167 mp = mc.mc_pg[mc.mc_top];
8171 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8172 for (i=0; i<n; i++) {
8173 ni = NODEPTR(mp, i);
8174 if (ni->mn_flags & F_BIGDATA) {
8178 /* Need writable leaf */
8180 mc.mc_pg[mc.mc_top] = leaf;
8181 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8183 ni = NODEPTR(mp, i);
8186 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8187 rc = mdb_page_get(txn, pg, &omp, NULL);
8190 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8191 rc = mdb_env_cthr_toggle(my);
8196 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8197 memcpy(mo, omp, my->mc_env->me_psize);
8198 mo->mp_pgno = my->mc_next_pgno;
8199 my->mc_next_pgno += omp->mp_pages;
8200 my->mc_wlen[toggle] += my->mc_env->me_psize;
8201 if (omp->mp_pages > 1) {
8202 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8203 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8204 rc = mdb_env_cthr_toggle(my);
8209 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8210 } else if (ni->mn_flags & F_SUBDATA) {
8213 /* Need writable leaf */
8215 mc.mc_pg[mc.mc_top] = leaf;
8216 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8218 ni = NODEPTR(mp, i);
8221 memcpy(&db, NODEDATA(ni), sizeof(db));
8222 my->mc_toggle = toggle;
8223 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8226 toggle = my->mc_toggle;
8227 memcpy(NODEDATA(ni), &db, sizeof(db));
8232 mc.mc_ki[mc.mc_top]++;
8233 if (mc.mc_ki[mc.mc_top] < n) {
8236 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8238 rc = mdb_page_get(txn, pg, &mp, NULL);
8243 mc.mc_ki[mc.mc_top] = 0;
8244 if (IS_BRANCH(mp)) {
8245 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8248 mc.mc_pg[mc.mc_top] = mp;
8252 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8253 rc = mdb_env_cthr_toggle(my);
8258 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8259 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8260 mo->mp_pgno = my->mc_next_pgno++;
8261 my->mc_wlen[toggle] += my->mc_env->me_psize;
8263 /* Update parent if there is one */
8264 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8265 SETPGNO(ni, mo->mp_pgno);
8266 mdb_cursor_pop(&mc);
8268 /* Otherwise we're done */
8279 mdb_env_copyfd2(MDB_env *env, HANDLE fd)
8284 MDB_txn *txn = NULL;
8289 my.mc_mutex[0] = CreateMutex(NULL, FALSE, NULL);
8290 my.mc_mutex[1] = CreateMutex(NULL, FALSE, NULL);
8291 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_psize);
8292 if (my.mc_wbuf[0] == NULL)
8295 pthread_mutex_init(&my.mc_mutex[0], NULL);
8296 pthread_mutex_init(&my.mc_mutex[1], NULL);
8297 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_psize, MDB_WBUF*2);
8301 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8306 my.mc_next_pgno = 2;
8311 pthread_mutex_lock(&my.mc_mutex[0]);
8312 THREAD_CREATE(thr, mdb_env_copythr, &my);
8314 /* Do the lock/unlock of the reader mutex before starting the
8315 * write txn. Otherwise other read txns could block writers.
8317 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8322 /* We must start the actual read txn after blocking writers */
8323 mdb_txn_reset0(txn, "reset-stage1");
8325 /* Temporarily block writers until we snapshot the meta pages */
8328 rc = mdb_txn_renew0(txn);
8330 UNLOCK_MUTEX_W(env);
8335 mp = (MDB_page *)my.mc_wbuf[0];
8336 memset(mp, 0, 2*env->me_psize);
8338 mp->mp_flags = P_META;
8339 mm = (MDB_meta *)METADATA(mp);
8340 mdb_env_init_meta0(env, mm);
8341 mm->mm_address = env->me_metas[0]->mm_address;
8343 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8345 mp->mp_flags = P_META;
8346 *(MDB_meta *)METADATA(mp) = *mm;
8347 mm = (MDB_meta *)METADATA(mp);
8349 /* Count the number of free pages, subtract from lastpg to find
8350 * number of active pages
8353 MDB_ID freecount = 0;
8356 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8357 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8358 freecount += *(MDB_ID *)data.mv_data;
8359 freecount += txn->mt_dbs[0].md_branch_pages +
8360 txn->mt_dbs[0].md_leaf_pages +
8361 txn->mt_dbs[0].md_overflow_pages;
8363 /* Set metapage 1 */
8364 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8365 mm->mm_dbs[1] = txn->mt_dbs[1];
8366 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8369 my.mc_wlen[0] = env->me_psize * 2;
8371 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8372 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8373 rc = mdb_env_cthr_toggle(&my);
8374 my.mc_wlen[my.mc_toggle] = 0;
8375 pthread_mutex_unlock(&my.mc_mutex[my.mc_toggle]);
8380 CloseHandle(my.mc_mutex[1]);
8381 CloseHandle(my.mc_mutex[0]);
8382 _aligned_free(my.mc_wbuf[0]);
8384 pthread_mutex_destroy(&my.mc_mutex[1]);
8385 pthread_mutex_destroy(&my.mc_mutex[0]);
8386 free(my.mc_wbuf[0]);
8392 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8394 MDB_txn *txn = NULL;
8400 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8404 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8407 /* Do the lock/unlock of the reader mutex before starting the
8408 * write txn. Otherwise other read txns could block writers.
8410 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8415 /* We must start the actual read txn after blocking writers */
8416 mdb_txn_reset0(txn, "reset-stage1");
8418 /* Temporarily block writers until we snapshot the meta pages */
8421 rc = mdb_txn_renew0(txn);
8423 UNLOCK_MUTEX_W(env);
8428 wsize = env->me_psize * 2;
8432 DO_WRITE(rc, fd, ptr, w2, len);
8436 } else if (len > 0) {
8442 /* Non-blocking or async handles are not supported */
8448 UNLOCK_MUTEX_W(env);
8453 w2 = txn->mt_next_pgno * env->me_psize;
8456 LARGE_INTEGER fsize;
8457 GetFileSizeEx(env->me_fd, &fsize);
8458 if (w2 > fsize.QuadPart)
8459 w2 = fsize.QuadPart;
8464 fstat(env->me_fd, &st);
8465 if (w2 > (size_t)st.st_size)
8471 if (wsize > MAX_WRITE)
8475 DO_WRITE(rc, fd, ptr, w2, len);
8479 } else if (len > 0) {
8496 mdb_env_copy0(MDB_env *env, const char *path, int flag)
8500 HANDLE newfd = INVALID_HANDLE_VALUE;
8502 if (env->me_flags & MDB_NOSUBDIR) {
8503 lpath = (char *)path;
8506 len += sizeof(DATANAME);
8507 lpath = malloc(len);
8510 sprintf(lpath, "%s" DATANAME, path);
8513 /* The destination path must exist, but the destination file must not.
8514 * We don't want the OS to cache the writes, since the source data is
8515 * already in the OS cache.
8518 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8519 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8521 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8523 if (newfd == INVALID_HANDLE_VALUE) {
8529 /* Set O_DIRECT if the file system supports it */
8530 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8531 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8533 #ifdef F_NOCACHE /* __APPLE__ */
8534 rc = fcntl(newfd, F_NOCACHE, 1);
8542 rc = mdb_env_copyfd2(env, newfd);
8544 rc = mdb_env_copyfd(env, newfd);
8547 if (!(env->me_flags & MDB_NOSUBDIR))
8549 if (newfd != INVALID_HANDLE_VALUE)
8550 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8557 mdb_env_copy(MDB_env *env, const char *path)
8559 return mdb_env_copy0(env, path, 0);
8563 mdb_env_copy2(MDB_env *env, const char *path)
8565 return mdb_env_copy0(env, path, 1);
8569 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8571 if ((flag & CHANGEABLE) != flag)
8574 env->me_flags |= flag;
8576 env->me_flags &= ~flag;
8581 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8586 *arg = env->me_flags;
8591 mdb_env_set_userctx(MDB_env *env, void *ctx)
8595 env->me_userctx = ctx;
8600 mdb_env_get_userctx(MDB_env *env)
8602 return env ? env->me_userctx : NULL;
8606 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8611 env->me_assert_func = func;
8617 mdb_env_get_path(MDB_env *env, const char **arg)
8622 *arg = env->me_path;
8627 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8636 /** Common code for #mdb_stat() and #mdb_env_stat().
8637 * @param[in] env the environment to operate in.
8638 * @param[in] db the #MDB_db record containing the stats to return.
8639 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8640 * @return 0, this function always succeeds.
8643 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8645 arg->ms_psize = env->me_psize;
8646 arg->ms_depth = db->md_depth;
8647 arg->ms_branch_pages = db->md_branch_pages;
8648 arg->ms_leaf_pages = db->md_leaf_pages;
8649 arg->ms_overflow_pages = db->md_overflow_pages;
8650 arg->ms_entries = db->md_entries;
8655 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8659 if (env == NULL || arg == NULL)
8662 toggle = mdb_env_pick_meta(env);
8664 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8668 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8672 if (env == NULL || arg == NULL)
8675 toggle = mdb_env_pick_meta(env);
8676 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8677 arg->me_mapsize = env->me_mapsize;
8678 arg->me_maxreaders = env->me_maxreaders;
8680 /* me_numreaders may be zero if this process never used any readers. Use
8681 * the shared numreader count if it exists.
8683 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8685 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8686 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8690 /** Set the default comparison functions for a database.
8691 * Called immediately after a database is opened to set the defaults.
8692 * The user can then override them with #mdb_set_compare() or
8693 * #mdb_set_dupsort().
8694 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8695 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8698 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8700 uint16_t f = txn->mt_dbs[dbi].md_flags;
8702 txn->mt_dbxs[dbi].md_cmp =
8703 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8704 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8706 txn->mt_dbxs[dbi].md_dcmp =
8707 !(f & MDB_DUPSORT) ? 0 :
8708 ((f & MDB_INTEGERDUP)
8709 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8710 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8713 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8718 int rc, dbflag, exact;
8719 unsigned int unused = 0;
8722 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8723 mdb_default_cmp(txn, FREE_DBI);
8726 if ((flags & VALID_FLAGS) != flags)
8728 if (txn->mt_flags & MDB_TXN_ERROR)
8734 if (flags & PERSISTENT_FLAGS) {
8735 uint16_t f2 = flags & PERSISTENT_FLAGS;
8736 /* make sure flag changes get committed */
8737 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8738 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8739 txn->mt_flags |= MDB_TXN_DIRTY;
8742 mdb_default_cmp(txn, MAIN_DBI);
8746 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8747 mdb_default_cmp(txn, MAIN_DBI);
8750 /* Is the DB already open? */
8752 for (i=2; i<txn->mt_numdbs; i++) {
8753 if (!txn->mt_dbxs[i].md_name.mv_size) {
8754 /* Remember this free slot */
8755 if (!unused) unused = i;
8758 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8759 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8765 /* If no free slot and max hit, fail */
8766 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8767 return MDB_DBS_FULL;
8769 /* Cannot mix named databases with some mainDB flags */
8770 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8771 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8773 /* Find the DB info */
8774 dbflag = DB_NEW|DB_VALID;
8777 key.mv_data = (void *)name;
8778 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8779 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8780 if (rc == MDB_SUCCESS) {
8781 /* make sure this is actually a DB */
8782 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8783 if (!(node->mn_flags & F_SUBDATA))
8784 return MDB_INCOMPATIBLE;
8785 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8786 /* Create if requested */
8788 data.mv_size = sizeof(MDB_db);
8789 data.mv_data = &dummy;
8790 memset(&dummy, 0, sizeof(dummy));
8791 dummy.md_root = P_INVALID;
8792 dummy.md_flags = flags & PERSISTENT_FLAGS;
8793 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8797 /* OK, got info, add to table */
8798 if (rc == MDB_SUCCESS) {
8799 unsigned int slot = unused ? unused : txn->mt_numdbs;
8800 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8801 txn->mt_dbxs[slot].md_name.mv_size = len;
8802 txn->mt_dbxs[slot].md_rel = NULL;
8803 txn->mt_dbflags[slot] = dbflag;
8804 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8806 mdb_default_cmp(txn, slot);
8815 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8817 if (!arg || !TXN_DBI_EXIST(txn, dbi))
8820 if (txn->mt_flags & MDB_TXN_ERROR)
8823 if (txn->mt_dbflags[dbi] & DB_STALE) {
8826 /* Stale, must read the DB's root. cursor_init does it for us. */
8827 mdb_cursor_init(&mc, txn, dbi, &mx);
8829 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8832 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8835 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8837 ptr = env->me_dbxs[dbi].md_name.mv_data;
8838 env->me_dbxs[dbi].md_name.mv_data = NULL;
8839 env->me_dbxs[dbi].md_name.mv_size = 0;
8840 env->me_dbflags[dbi] = 0;
8844 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8846 /* We could return the flags for the FREE_DBI too but what's the point? */
8847 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8849 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8853 /** Add all the DB's pages to the free list.
8854 * @param[in] mc Cursor on the DB to free.
8855 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8856 * @return 0 on success, non-zero on failure.
8859 mdb_drop0(MDB_cursor *mc, int subs)
8863 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8864 if (rc == MDB_SUCCESS) {
8865 MDB_txn *txn = mc->mc_txn;
8870 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8871 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8874 mdb_cursor_copy(mc, &mx);
8875 while (mc->mc_snum > 0) {
8876 MDB_page *mp = mc->mc_pg[mc->mc_top];
8877 unsigned n = NUMKEYS(mp);
8879 for (i=0; i<n; i++) {
8880 ni = NODEPTR(mp, i);
8881 if (ni->mn_flags & F_BIGDATA) {
8884 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8885 rc = mdb_page_get(txn, pg, &omp, NULL);
8888 mdb_cassert(mc, IS_OVERFLOW(omp));
8889 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8893 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8894 mdb_xcursor_init1(mc, ni);
8895 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8901 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8903 for (i=0; i<n; i++) {
8905 ni = NODEPTR(mp, i);
8908 mdb_midl_xappend(txn->mt_free_pgs, pg);
8913 mc->mc_ki[mc->mc_top] = i;
8914 rc = mdb_cursor_sibling(mc, 1);
8916 if (rc != MDB_NOTFOUND)
8918 /* no more siblings, go back to beginning
8919 * of previous level.
8923 for (i=1; i<mc->mc_snum; i++) {
8925 mc->mc_pg[i] = mx.mc_pg[i];
8930 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8933 txn->mt_flags |= MDB_TXN_ERROR;
8934 } else if (rc == MDB_NOTFOUND) {
8940 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8942 MDB_cursor *mc, *m2;
8945 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8948 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8951 rc = mdb_cursor_open(txn, dbi, &mc);
8955 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8956 /* Invalidate the dropped DB's cursors */
8957 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8958 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8962 /* Can't delete the main DB */
8963 if (del && dbi > MAIN_DBI) {
8964 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
8966 txn->mt_dbflags[dbi] = DB_STALE;
8967 mdb_dbi_close(txn->mt_env, dbi);
8969 txn->mt_flags |= MDB_TXN_ERROR;
8972 /* reset the DB record, mark it dirty */
8973 txn->mt_dbflags[dbi] |= DB_DIRTY;
8974 txn->mt_dbs[dbi].md_depth = 0;
8975 txn->mt_dbs[dbi].md_branch_pages = 0;
8976 txn->mt_dbs[dbi].md_leaf_pages = 0;
8977 txn->mt_dbs[dbi].md_overflow_pages = 0;
8978 txn->mt_dbs[dbi].md_entries = 0;
8979 txn->mt_dbs[dbi].md_root = P_INVALID;
8981 txn->mt_flags |= MDB_TXN_DIRTY;
8984 mdb_cursor_close(mc);
8988 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8990 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8993 txn->mt_dbxs[dbi].md_cmp = cmp;
8997 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8999 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9002 txn->mt_dbxs[dbi].md_dcmp = cmp;
9006 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9008 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9011 txn->mt_dbxs[dbi].md_rel = rel;
9015 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9017 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9020 txn->mt_dbxs[dbi].md_relctx = ctx;
9024 int mdb_env_get_maxkeysize(MDB_env *env)
9026 return ENV_MAXKEY(env);
9029 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9031 unsigned int i, rdrs;
9034 int rc = 0, first = 1;
9038 if (!env->me_txns) {
9039 return func("(no reader locks)\n", ctx);
9041 rdrs = env->me_txns->mti_numreaders;
9042 mr = env->me_txns->mti_readers;
9043 for (i=0; i<rdrs; i++) {
9045 txnid_t txnid = mr[i].mr_txnid;
9046 sprintf(buf, txnid == (txnid_t)-1 ?
9047 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9048 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9051 rc = func(" pid thread txnid\n", ctx);
9055 rc = func(buf, ctx);
9061 rc = func("(no active readers)\n", ctx);
9066 /** Insert pid into list if not already present.
9067 * return -1 if already present.
9069 static int mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9071 /* binary search of pid in list */
9073 unsigned cursor = 1;
9075 unsigned n = ids[0];
9078 unsigned pivot = n >> 1;
9079 cursor = base + pivot + 1;
9080 val = pid - ids[cursor];
9085 } else if ( val > 0 ) {
9090 /* found, so it's a duplicate */
9099 for (n = ids[0]; n > cursor; n--)
9105 int mdb_reader_check(MDB_env *env, int *dead)
9107 unsigned int i, j, rdrs;
9109 MDB_PID_T *pids, pid;
9118 rdrs = env->me_txns->mti_numreaders;
9119 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9123 mr = env->me_txns->mti_readers;
9124 for (i=0; i<rdrs; i++) {
9125 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9127 if (mdb_pid_insert(pids, pid) == 0) {
9128 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9130 /* Recheck, a new process may have reused pid */
9131 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9132 for (j=i; j<rdrs; j++)
9133 if (mr[j].mr_pid == pid) {
9134 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9135 (unsigned) pid, mr[j].mr_txnid));
9140 UNLOCK_MUTEX_R(env);