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-2016 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
44 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
45 * as int64 which is wrong. MSVC doesn't define it at all, so just
49 #define MDB_THR_T DWORD
50 #include <sys/types.h>
53 # include <sys/param.h>
55 # define LITTLE_ENDIAN 1234
56 # define BIG_ENDIAN 4321
57 # define BYTE_ORDER LITTLE_ENDIAN
59 # define SSIZE_MAX INT_MAX
63 #include <sys/types.h>
65 #define MDB_PID_T pid_t
66 #define MDB_THR_T pthread_t
67 #include <sys/param.h>
70 #ifdef HAVE_SYS_FILE_H
76 #if defined(__mips) && defined(__linux)
77 /* MIPS has cache coherency issues, requires explicit cache control */
78 #include <asm/cachectl.h>
79 extern int cacheflush(char *addr, int nbytes, int cache);
80 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
82 #define CACHEFLUSH(addr, bytes, cache)
85 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
86 /** fdatasync is broken on ext3/ext4fs on older kernels, see
87 * description in #mdb_env_open2 comments. You can safely
88 * define MDB_FDATASYNC_WORKS if this code will only be run
89 * on kernels 3.6 and newer.
91 #define BROKEN_FDATASYNC
105 typedef SSIZE_T ssize_t;
110 #if defined(__sun) || defined(ANDROID)
111 /* Most platforms have posix_memalign, older may only have memalign */
112 #define HAVE_MEMALIGN 1
116 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
117 #include <netinet/in.h>
118 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
121 #if defined(__APPLE__) || defined (BSD)
122 # define MDB_USE_POSIX_SEM 1
123 # define MDB_FDATASYNC fsync
124 #elif defined(ANDROID)
125 # define MDB_FDATASYNC fsync
130 #ifdef MDB_USE_POSIX_SEM
131 # define MDB_USE_HASH 1
132 #include <semaphore.h>
134 #define MDB_USE_POSIX_MUTEX 1
138 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
139 + defined(MDB_USE_POSIX_MUTEX) != 1
140 # error "Ambiguous shared-lock implementation"
144 #include <valgrind/memcheck.h>
145 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
146 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
147 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
148 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
149 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
151 #define VGMEMP_CREATE(h,r,z)
152 #define VGMEMP_ALLOC(h,a,s)
153 #define VGMEMP_FREE(h,a)
154 #define VGMEMP_DESTROY(h)
155 #define VGMEMP_DEFINED(a,s)
159 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
160 /* Solaris just defines one or the other */
161 # define LITTLE_ENDIAN 1234
162 # define BIG_ENDIAN 4321
163 # ifdef _LITTLE_ENDIAN
164 # define BYTE_ORDER LITTLE_ENDIAN
166 # define BYTE_ORDER BIG_ENDIAN
169 # define BYTE_ORDER __BYTE_ORDER
173 #ifndef LITTLE_ENDIAN
174 #define LITTLE_ENDIAN __LITTLE_ENDIAN
177 #define BIG_ENDIAN __BIG_ENDIAN
180 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
181 #define MISALIGNED_OK 1
187 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
188 # error "Unknown or unsupported endianness (BYTE_ORDER)"
189 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
190 # error "Two's complement, reasonably sized integer types, please"
194 /** Put infrequently used env functions in separate section */
196 # define ESECT __attribute__ ((section("__TEXT,text_env")))
198 # define ESECT __attribute__ ((section("text_env")))
205 #define CALL_CONV WINAPI
210 /** @defgroup internal LMDB Internals
213 /** @defgroup compat Compatibility Macros
214 * A bunch of macros to minimize the amount of platform-specific ifdefs
215 * needed throughout the rest of the code. When the features this library
216 * needs are similar enough to POSIX to be hidden in a one-or-two line
217 * replacement, this macro approach is used.
221 /** Features under development */
226 /** Wrapper around __func__, which is a C99 feature */
227 #if __STDC_VERSION__ >= 199901L
228 # define mdb_func_ __func__
229 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
230 # define mdb_func_ __FUNCTION__
232 /* If a debug message says <mdb_unknown>(), update the #if statements above */
233 # define mdb_func_ "<mdb_unknown>"
236 /* Internal error codes, not exposed outside liblmdb */
237 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
239 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
240 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
241 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
245 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
247 /** Some platforms define the EOWNERDEAD error code
248 * even though they don't support Robust Mutexes.
249 * Compile with -DMDB_USE_ROBUST=0, or use some other
250 * mechanism like -DMDB_USE_POSIX_SEM instead of
251 * -DMDB_USE_POSIX_MUTEX.
252 * (Posix semaphores are not robust.)
254 #ifndef MDB_USE_ROBUST
255 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
256 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
257 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
258 # define MDB_USE_ROBUST 0
260 # define MDB_USE_ROBUST 1
261 /* glibc < 2.12 only provided _np API */
262 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
263 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
264 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
265 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
266 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
269 #endif /* MDB_USE_ROBUST */
271 #if defined(MDB_OWNERDEAD) && MDB_USE_ROBUST
272 #define MDB_ROBUST_SUPPORTED 1
276 #define MDB_USE_HASH 1
277 #define MDB_PIDLOCK 0
278 #define THREAD_RET DWORD
279 #define pthread_t HANDLE
280 #define pthread_mutex_t HANDLE
281 #define pthread_cond_t HANDLE
282 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
283 #define pthread_key_t DWORD
284 #define pthread_self() GetCurrentThreadId()
285 #define pthread_key_create(x,y) \
286 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
287 #define pthread_key_delete(x) TlsFree(x)
288 #define pthread_getspecific(x) TlsGetValue(x)
289 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
290 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
291 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
292 #define pthread_cond_signal(x) SetEvent(*x)
293 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
294 #define THREAD_CREATE(thr,start,arg) \
295 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
296 #define THREAD_FINISH(thr) \
297 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
298 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
299 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
300 #define mdb_mutex_consistent(mutex) 0
301 #define getpid() GetCurrentProcessId()
302 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
303 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
304 #define ErrCode() GetLastError()
305 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
306 #define close(fd) (CloseHandle(fd) ? 0 : -1)
307 #define munmap(ptr,len) UnmapViewOfFile(ptr)
308 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
309 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
311 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
315 #define THREAD_RET void *
316 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
317 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
318 #define Z "z" /**< printf format modifier for size_t */
320 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
321 #define MDB_PIDLOCK 1
323 #ifdef MDB_USE_POSIX_SEM
325 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
326 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
327 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
330 mdb_sem_wait(sem_t *sem)
333 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
337 #else /* MDB_USE_POSIX_MUTEX: */
338 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
339 * local variables keep it (mdb_mutexref_t).
341 * When #mdb_mutexref_t is a pointer declaration and #mdb_mutex_t is
342 * not, then it is array[size 1] so it can be assigned to a pointer.
345 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
347 /** Lock the reader or writer mutex.
348 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
350 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
351 /** Unlock the reader or writer mutex.
353 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
354 /** Mark mutex-protected data as repaired, after death of previous owner.
356 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
357 #endif /* MDB_USE_POSIX_SEM */
359 /** Get the error code for the last failed system function.
361 #define ErrCode() errno
363 /** An abstraction for a file handle.
364 * On POSIX systems file handles are small integers. On Windows
365 * they're opaque pointers.
369 /** A value for an invalid file handle.
370 * Mainly used to initialize file variables and signify that they are
373 #define INVALID_HANDLE_VALUE (-1)
375 /** Get the size of a memory page for the system.
376 * This is the basic size that the platform's memory manager uses, and is
377 * fundamental to the use of memory-mapped files.
379 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
382 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
385 #define MNAME_LEN (sizeof(pthread_mutex_t))
390 #ifdef MDB_ROBUST_SUPPORTED
391 /** Lock mutex, handle any error, set rc = result.
392 * Return 0 on success, nonzero (not rc) on error.
394 #define LOCK_MUTEX(rc, env, mutex) \
395 (((rc) = LOCK_MUTEX0(mutex)) && \
396 ((rc) = mdb_mutex_failed(env, mutex, rc)))
397 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
399 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
400 #define mdb_mutex_failed(env, mutex, rc) (rc)
404 /** A flag for opening a file and requesting synchronous data writes.
405 * This is only used when writing a meta page. It's not strictly needed;
406 * we could just do a normal write and then immediately perform a flush.
407 * But if this flag is available it saves us an extra system call.
409 * @note If O_DSYNC is undefined but exists in /usr/include,
410 * preferably set some compiler flag to get the definition.
414 # define MDB_DSYNC O_DSYNC
416 # define MDB_DSYNC O_SYNC
421 /** Function for flushing the data of a file. Define this to fsync
422 * if fdatasync() is not supported.
424 #ifndef MDB_FDATASYNC
425 # define MDB_FDATASYNC fdatasync
429 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
440 /** A page number in the database.
441 * Note that 64 bit page numbers are overkill, since pages themselves
442 * already represent 12-13 bits of addressable memory, and the OS will
443 * always limit applications to a maximum of 63 bits of address space.
445 * @note In the #MDB_node structure, we only store 48 bits of this value,
446 * which thus limits us to only 60 bits of addressable data.
448 typedef MDB_ID pgno_t;
450 /** A transaction ID.
451 * See struct MDB_txn.mt_txnid for details.
453 typedef MDB_ID txnid_t;
455 /** @defgroup debug Debug Macros
459 /** Enable debug output. Needs variable argument macros (a C99 feature).
460 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
461 * read from and written to the database (used for free space management).
467 static int mdb_debug;
468 static txnid_t mdb_debug_start;
470 /** Print a debug message with printf formatting.
471 * Requires double parenthesis around 2 or more args.
473 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
474 # define DPRINTF0(fmt, ...) \
475 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
477 # define DPRINTF(args) ((void) 0)
479 /** Print a debug string.
480 * The string is printed literally, with no format processing.
482 #define DPUTS(arg) DPRINTF(("%s", arg))
483 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
485 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
488 /** @brief The maximum size of a database page.
490 * It is 32k or 64k, since value-PAGEBASE must fit in
491 * #MDB_page.%mp_upper.
493 * LMDB will use database pages < OS pages if needed.
494 * That causes more I/O in write transactions: The OS must
495 * know (read) the whole page before writing a partial page.
497 * Note that we don't currently support Huge pages. On Linux,
498 * regular data files cannot use Huge pages, and in general
499 * Huge pages aren't actually pageable. We rely on the OS
500 * demand-pager to read our data and page it out when memory
501 * pressure from other processes is high. So until OSs have
502 * actual paging support for Huge pages, they're not viable.
504 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
506 /** The minimum number of keys required in a database page.
507 * Setting this to a larger value will place a smaller bound on the
508 * maximum size of a data item. Data items larger than this size will
509 * be pushed into overflow pages instead of being stored directly in
510 * the B-tree node. This value used to default to 4. With a page size
511 * of 4096 bytes that meant that any item larger than 1024 bytes would
512 * go into an overflow page. That also meant that on average 2-3KB of
513 * each overflow page was wasted space. The value cannot be lower than
514 * 2 because then there would no longer be a tree structure. With this
515 * value, items larger than 2KB will go into overflow pages, and on
516 * average only 1KB will be wasted.
518 #define MDB_MINKEYS 2
520 /** A stamp that identifies a file as an LMDB file.
521 * There's nothing special about this value other than that it is easily
522 * recognizable, and it will reflect any byte order mismatches.
524 #define MDB_MAGIC 0xBEEFC0DE
526 /** The version number for a database's datafile format. */
527 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
528 /** The version number for a database's lockfile format. */
529 #define MDB_LOCK_VERSION 1
531 /** @brief The max size of a key we can write, or 0 for computed max.
533 * This macro should normally be left alone or set to 0.
534 * Note that a database with big keys or dupsort data cannot be
535 * reliably modified by a liblmdb which uses a smaller max.
536 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
538 * Other values are allowed, for backwards compat. However:
539 * A value bigger than the computed max can break if you do not
540 * know what you are doing, and liblmdb <= 0.9.10 can break when
541 * modifying a DB with keys/dupsort data bigger than its max.
543 * Data items in an #MDB_DUPSORT database are also limited to
544 * this size, since they're actually keys of a sub-DB. Keys and
545 * #MDB_DUPSORT data items must fit on a node in a regular page.
547 #ifndef MDB_MAXKEYSIZE
548 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
551 /** The maximum size of a key we can write to the environment. */
553 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
555 #define ENV_MAXKEY(env) ((env)->me_maxkey)
558 /** @brief The maximum size of a data item.
560 * We only store a 32 bit value for node sizes.
562 #define MAXDATASIZE 0xffffffffUL
565 /** Key size which fits in a #DKBUF.
568 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
571 * This is used for printing a hex dump of a key's contents.
573 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
574 /** Display a key in hex.
576 * Invoke a function to display a key in hex.
578 #define DKEY(x) mdb_dkey(x, kbuf)
584 /** An invalid page number.
585 * Mainly used to denote an empty tree.
587 #define P_INVALID (~(pgno_t)0)
589 /** Test if the flags \b f are set in a flag word \b w. */
590 #define F_ISSET(w, f) (((w) & (f)) == (f))
592 /** Round \b n up to an even number. */
593 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
595 /** Used for offsets within a single page.
596 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
599 typedef uint16_t indx_t;
601 /** Default size of memory map.
602 * This is certainly too small for any actual applications. Apps should always set
603 * the size explicitly using #mdb_env_set_mapsize().
605 #define DEFAULT_MAPSIZE 1048576
607 /** @defgroup readers Reader Lock Table
608 * Readers don't acquire any locks for their data access. Instead, they
609 * simply record their transaction ID in the reader table. The reader
610 * mutex is needed just to find an empty slot in the reader table. The
611 * slot's address is saved in thread-specific data so that subsequent read
612 * transactions started by the same thread need no further locking to proceed.
614 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
616 * No reader table is used if the database is on a read-only filesystem, or
617 * if #MDB_NOLOCK is set.
619 * Since the database uses multi-version concurrency control, readers don't
620 * actually need any locking. This table is used to keep track of which
621 * readers are using data from which old transactions, so that we'll know
622 * when a particular old transaction is no longer in use. Old transactions
623 * that have discarded any data pages can then have those pages reclaimed
624 * for use by a later write transaction.
626 * The lock table is constructed such that reader slots are aligned with the
627 * processor's cache line size. Any slot is only ever used by one thread.
628 * This alignment guarantees that there will be no contention or cache
629 * thrashing as threads update their own slot info, and also eliminates
630 * any need for locking when accessing a slot.
632 * A writer thread will scan every slot in the table to determine the oldest
633 * outstanding reader transaction. Any freed pages older than this will be
634 * reclaimed by the writer. The writer doesn't use any locks when scanning
635 * this table. This means that there's no guarantee that the writer will
636 * see the most up-to-date reader info, but that's not required for correct
637 * operation - all we need is to know the upper bound on the oldest reader,
638 * we don't care at all about the newest reader. So the only consequence of
639 * reading stale information here is that old pages might hang around a
640 * while longer before being reclaimed. That's actually good anyway, because
641 * the longer we delay reclaiming old pages, the more likely it is that a
642 * string of contiguous pages can be found after coalescing old pages from
643 * many old transactions together.
646 /** Number of slots in the reader table.
647 * This value was chosen somewhat arbitrarily. 126 readers plus a
648 * couple mutexes fit exactly into 8KB on my development machine.
649 * Applications should set the table size using #mdb_env_set_maxreaders().
651 #define DEFAULT_READERS 126
653 /** The size of a CPU cache line in bytes. We want our lock structures
654 * aligned to this size to avoid false cache line sharing in the
656 * This value works for most CPUs. For Itanium this should be 128.
662 /** The information we store in a single slot of the reader table.
663 * In addition to a transaction ID, we also record the process and
664 * thread ID that owns a slot, so that we can detect stale information,
665 * e.g. threads or processes that went away without cleaning up.
666 * @note We currently don't check for stale records. We simply re-init
667 * the table when we know that we're the only process opening the
670 typedef struct MDB_rxbody {
671 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
672 * Multiple readers that start at the same time will probably have the
673 * same ID here. Again, it's not important to exclude them from
674 * anything; all we need to know is which version of the DB they
675 * started from so we can avoid overwriting any data used in that
676 * particular version.
678 volatile txnid_t mrb_txnid;
679 /** The process ID of the process owning this reader txn. */
680 volatile MDB_PID_T mrb_pid;
681 /** The thread ID of the thread owning this txn. */
682 volatile MDB_THR_T mrb_tid;
685 /** The actual reader record, with cacheline padding. */
686 typedef struct MDB_reader {
689 /** shorthand for mrb_txnid */
690 #define mr_txnid mru.mrx.mrb_txnid
691 #define mr_pid mru.mrx.mrb_pid
692 #define mr_tid mru.mrx.mrb_tid
693 /** cache line alignment */
694 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
698 /** The header for the reader table.
699 * The table resides in a memory-mapped file. (This is a different file
700 * than is used for the main database.)
702 * For POSIX the actual mutexes reside in the shared memory of this
703 * mapped file. On Windows, mutexes are named objects allocated by the
704 * kernel; we store the mutex names in this mapped file so that other
705 * processes can grab them. This same approach is also used on
706 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
707 * process-shared POSIX mutexes. For these cases where a named object
708 * is used, the object name is derived from a 64 bit FNV hash of the
709 * environment pathname. As such, naming collisions are extremely
710 * unlikely. If a collision occurs, the results are unpredictable.
712 typedef struct MDB_txbody {
713 /** Stamp identifying this as an LMDB file. It must be set
716 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
718 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
719 char mtb_rmname[MNAME_LEN];
721 /** Mutex protecting access to this table.
722 * This is the reader table lock used with LOCK_MUTEX().
724 mdb_mutex_t mtb_rmutex;
726 /** The ID of the last transaction committed to the database.
727 * This is recorded here only for convenience; the value can always
728 * be determined by reading the main database meta pages.
730 volatile txnid_t mtb_txnid;
731 /** The number of slots that have been used in the reader table.
732 * This always records the maximum count, it is not decremented
733 * when readers release their slots.
735 volatile unsigned mtb_numreaders;
738 /** The actual reader table definition. */
739 typedef struct MDB_txninfo {
742 #define mti_magic mt1.mtb.mtb_magic
743 #define mti_format mt1.mtb.mtb_format
744 #define mti_rmutex mt1.mtb.mtb_rmutex
745 #define mti_rmname mt1.mtb.mtb_rmname
746 #define mti_txnid mt1.mtb.mtb_txnid
747 #define mti_numreaders mt1.mtb.mtb_numreaders
748 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
751 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
752 char mt2_wmname[MNAME_LEN];
753 #define mti_wmname mt2.mt2_wmname
755 mdb_mutex_t mt2_wmutex;
756 #define mti_wmutex mt2.mt2_wmutex
758 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
760 MDB_reader mti_readers[1];
763 /** Lockfile format signature: version, features and field layout */
764 #define MDB_LOCK_FORMAT \
766 ((MDB_LOCK_VERSION) \
767 /* Flags which describe functionality */ \
768 + (((MDB_PIDLOCK) != 0) << 16)))
771 /** Common header for all page types.
772 * Overflow records occupy a number of contiguous pages with no
773 * headers on any page after the first.
775 typedef struct MDB_page {
776 #define mp_pgno mp_p.p_pgno
777 #define mp_next mp_p.p_next
779 pgno_t p_pgno; /**< page number */
780 struct MDB_page *p_next; /**< for in-memory list of freed pages */
783 /** @defgroup mdb_page Page Flags
785 * Flags for the page headers.
788 #define P_BRANCH 0x01 /**< branch page */
789 #define P_LEAF 0x02 /**< leaf page */
790 #define P_OVERFLOW 0x04 /**< overflow page */
791 #define P_META 0x08 /**< meta page */
792 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
793 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
794 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
795 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
796 #define P_KEEP 0x8000 /**< leave this page alone during spill */
798 uint16_t mp_flags; /**< @ref mdb_page */
799 #define mp_lower mp_pb.pb.pb_lower
800 #define mp_upper mp_pb.pb.pb_upper
801 #define mp_pages mp_pb.pb_pages
804 indx_t pb_lower; /**< lower bound of free space */
805 indx_t pb_upper; /**< upper bound of free space */
807 uint32_t pb_pages; /**< number of overflow pages */
809 indx_t mp_ptrs[1]; /**< dynamic size */
812 /** Size of the page header, excluding dynamic data at the end */
813 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
815 /** Address of first usable data byte in a page, after the header */
816 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
818 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
819 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
821 /** Number of nodes on a page */
822 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
824 /** The amount of space remaining in the page */
825 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
827 /** The percentage of space used in the page, in tenths of a percent. */
828 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
829 ((env)->me_psize - PAGEHDRSZ))
830 /** The minimum page fill factor, in tenths of a percent.
831 * Pages emptier than this are candidates for merging.
833 #define FILL_THRESHOLD 250
835 /** Test if a page is a leaf page */
836 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
837 /** Test if a page is a LEAF2 page */
838 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
839 /** Test if a page is a branch page */
840 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
841 /** Test if a page is an overflow page */
842 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
843 /** Test if a page is a sub page */
844 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
846 /** The number of overflow pages needed to store the given size. */
847 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
849 /** Link in #MDB_txn.%mt_loose_pgs list */
850 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
852 /** Header for a single key/data pair within a page.
853 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
854 * We guarantee 2-byte alignment for 'MDB_node's.
856 typedef struct MDB_node {
857 /** lo and hi are used for data size on leaf nodes and for
858 * child pgno on branch nodes. On 64 bit platforms, flags
859 * is also used for pgno. (Branch nodes have no flags).
860 * They are in host byte order in case that lets some
861 * accesses be optimized into a 32-bit word access.
863 #if BYTE_ORDER == LITTLE_ENDIAN
864 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
866 unsigned short mn_hi, mn_lo;
868 /** @defgroup mdb_node Node Flags
870 * Flags for node headers.
873 #define F_BIGDATA 0x01 /**< data put on overflow page */
874 #define F_SUBDATA 0x02 /**< data is a sub-database */
875 #define F_DUPDATA 0x04 /**< data has duplicates */
877 /** valid flags for #mdb_node_add() */
878 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
881 unsigned short mn_flags; /**< @ref mdb_node */
882 unsigned short mn_ksize; /**< key size */
883 char mn_data[1]; /**< key and data are appended here */
886 /** Size of the node header, excluding dynamic data at the end */
887 #define NODESIZE offsetof(MDB_node, mn_data)
889 /** Bit position of top word in page number, for shifting mn_flags */
890 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
892 /** Size of a node in a branch page with a given key.
893 * This is just the node header plus the key, there is no data.
895 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
897 /** Size of a node in a leaf page with a given key and data.
898 * This is node header plus key plus data size.
900 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
902 /** Address of node \b i in page \b p */
903 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
905 /** Address of the key for the node */
906 #define NODEKEY(node) (void *)((node)->mn_data)
908 /** Address of the data for a node */
909 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
911 /** Get the page number pointed to by a branch node */
912 #define NODEPGNO(node) \
913 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
914 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
915 /** Set the page number in a branch node */
916 #define SETPGNO(node,pgno) do { \
917 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
918 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
920 /** Get the size of the data in a leaf node */
921 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
922 /** Set the size of the data for a leaf node */
923 #define SETDSZ(node,size) do { \
924 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
925 /** The size of a key in a node */
926 #define NODEKSZ(node) ((node)->mn_ksize)
928 /** Copy a page number from src to dst */
930 #define COPY_PGNO(dst,src) dst = src
932 #if SIZE_MAX > 4294967295UL
933 #define COPY_PGNO(dst,src) do { \
934 unsigned short *s, *d; \
935 s = (unsigned short *)&(src); \
936 d = (unsigned short *)&(dst); \
943 #define COPY_PGNO(dst,src) do { \
944 unsigned short *s, *d; \
945 s = (unsigned short *)&(src); \
946 d = (unsigned short *)&(dst); \
952 /** The address of a key in a LEAF2 page.
953 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
954 * There are no node headers, keys are stored contiguously.
956 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
958 /** Set the \b node's key into \b keyptr, if requested. */
959 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
960 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
962 /** Set the \b node's key into \b key. */
963 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
965 /** Information about a single database in the environment. */
966 typedef struct MDB_db {
967 uint32_t md_pad; /**< also ksize for LEAF2 pages */
968 uint16_t md_flags; /**< @ref mdb_dbi_open */
969 uint16_t md_depth; /**< depth of this tree */
970 pgno_t md_branch_pages; /**< number of internal pages */
971 pgno_t md_leaf_pages; /**< number of leaf pages */
972 pgno_t md_overflow_pages; /**< number of overflow pages */
973 size_t md_entries; /**< number of data items */
974 pgno_t md_root; /**< the root page of this tree */
977 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
978 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
979 /** #mdb_dbi_open() flags */
980 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
981 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
983 /** Handle for the DB used to track free pages. */
985 /** Handle for the default DB. */
987 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
990 /** Number of meta pages - also hardcoded elsewhere */
993 /** Meta page content.
994 * A meta page is the start point for accessing a database snapshot.
995 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
997 typedef struct MDB_meta {
998 /** Stamp identifying this as an LMDB file. It must be set
1001 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1002 uint32_t mm_version;
1003 void *mm_address; /**< address for fixed mapping */
1004 size_t mm_mapsize; /**< size of mmap region */
1005 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1006 /** The size of pages used in this DB */
1007 #define mm_psize mm_dbs[FREE_DBI].md_pad
1008 /** Any persistent environment flags. @ref mdb_env */
1009 #define mm_flags mm_dbs[FREE_DBI].md_flags
1010 /** Last used page in the datafile.
1011 * Actually the file may be shorter if the freeDB lists the final pages.
1014 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1017 /** Buffer for a stack-allocated meta page.
1018 * The members define size and alignment, and silence type
1019 * aliasing warnings. They are not used directly; that could
1020 * mean incorrectly using several union members in parallel.
1022 typedef union MDB_metabuf {
1025 char mm_pad[PAGEHDRSZ];
1030 /** Auxiliary DB info.
1031 * The information here is mostly static/read-only. There is
1032 * only a single copy of this record in the environment.
1034 typedef struct MDB_dbx {
1035 MDB_val md_name; /**< name of the database */
1036 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1037 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1038 MDB_rel_func *md_rel; /**< user relocate function */
1039 void *md_relctx; /**< user-provided context for md_rel */
1042 /** A database transaction.
1043 * Every operation requires a transaction handle.
1046 MDB_txn *mt_parent; /**< parent of a nested txn */
1047 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1049 pgno_t mt_next_pgno; /**< next unallocated page */
1050 /** The ID of this transaction. IDs are integers incrementing from 1.
1051 * Only committed write transactions increment the ID. If a transaction
1052 * aborts, the ID may be re-used by the next writer.
1055 MDB_env *mt_env; /**< the DB environment */
1056 /** The list of pages that became unused during this transaction.
1058 MDB_IDL mt_free_pgs;
1059 /** The list of loose pages that became unused and may be reused
1060 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1062 MDB_page *mt_loose_pgs;
1063 /** Number of loose pages (#mt_loose_pgs) */
1065 /** The sorted list of dirty pages we temporarily wrote to disk
1066 * because the dirty list was full. page numbers in here are
1067 * shifted left by 1, deleted slots have the LSB set.
1069 MDB_IDL mt_spill_pgs;
1071 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1072 MDB_ID2L dirty_list;
1073 /** For read txns: This thread/txn's reader table slot, or NULL. */
1076 /** Array of records for each DB known in the environment. */
1078 /** Array of MDB_db records for each known DB */
1080 /** Array of sequence numbers for each DB handle */
1081 unsigned int *mt_dbiseqs;
1082 /** @defgroup mt_dbflag Transaction DB Flags
1086 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1087 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1088 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1089 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1090 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1091 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1093 /** In write txns, array of cursors for each DB */
1094 MDB_cursor **mt_cursors;
1095 /** Array of flags for each DB */
1096 unsigned char *mt_dbflags;
1097 /** Number of DB records in use, or 0 when the txn is finished.
1098 * This number only ever increments until the txn finishes; we
1099 * don't decrement it when individual DB handles are closed.
1103 /** @defgroup mdb_txn Transaction Flags
1107 /** #mdb_txn_begin() flags */
1108 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1109 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1110 /* internal txn flags */
1111 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1112 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1113 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1114 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1115 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1116 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1117 /** most operations on the txn are currently illegal */
1118 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1120 unsigned int mt_flags; /**< @ref mdb_txn */
1121 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1122 * Includes ancestor txns' dirty pages not hidden by other txns'
1123 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1124 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1126 unsigned int mt_dirty_room;
1129 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1130 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1131 * raise this on a 64 bit machine.
1133 #define CURSOR_STACK 32
1137 /** Cursors are used for all DB operations.
1138 * A cursor holds a path of (page pointer, key index) from the DB
1139 * root to a position in the DB, plus other state. #MDB_DUPSORT
1140 * cursors include an xcursor to the current data item. Write txns
1141 * track their cursors and keep them up to date when data moves.
1142 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1143 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1146 /** Next cursor on this DB in this txn */
1147 MDB_cursor *mc_next;
1148 /** Backup of the original cursor if this cursor is a shadow */
1149 MDB_cursor *mc_backup;
1150 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1151 struct MDB_xcursor *mc_xcursor;
1152 /** The transaction that owns this cursor */
1154 /** The database handle this cursor operates on */
1156 /** The database record for this cursor */
1158 /** The database auxiliary record for this cursor */
1160 /** The @ref mt_dbflag for this database */
1161 unsigned char *mc_dbflag;
1162 unsigned short mc_snum; /**< number of pushed pages */
1163 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1164 /** @defgroup mdb_cursor Cursor Flags
1166 * Cursor state flags.
1169 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1170 #define C_EOF 0x02 /**< No more data */
1171 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1172 #define C_DEL 0x08 /**< last op was a cursor_del */
1173 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1175 unsigned int mc_flags; /**< @ref mdb_cursor */
1176 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1177 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1180 /** Context for sorted-dup records.
1181 * We could have gone to a fully recursive design, with arbitrarily
1182 * deep nesting of sub-databases. But for now we only handle these
1183 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1185 typedef struct MDB_xcursor {
1186 /** A sub-cursor for traversing the Dup DB */
1187 MDB_cursor mx_cursor;
1188 /** The database record for this Dup DB */
1190 /** The auxiliary DB record for this Dup DB */
1192 /** The @ref mt_dbflag for this Dup DB */
1193 unsigned char mx_dbflag;
1196 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1197 #define XCURSOR_INITED(mc) \
1198 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1200 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1201 * when the node which contains the sub-page may have moved. Called
1202 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1204 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1205 MDB_page *xr_pg = (mp); \
1206 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1207 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1208 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1211 /** State of FreeDB old pages, stored in the MDB_env */
1212 typedef struct MDB_pgstate {
1213 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1214 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1217 /** The database environment. */
1219 HANDLE me_fd; /**< The main data file */
1220 HANDLE me_lfd; /**< The lock file */
1221 HANDLE me_mfd; /**< just for writing the meta pages */
1222 /** Failed to update the meta page. Probably an I/O error. */
1223 #define MDB_FATAL_ERROR 0x80000000U
1224 /** Some fields are initialized. */
1225 #define MDB_ENV_ACTIVE 0x20000000U
1226 /** me_txkey is set */
1227 #define MDB_ENV_TXKEY 0x10000000U
1228 /** fdatasync is unreliable */
1229 #define MDB_FSYNCONLY 0x08000000U
1230 uint32_t me_flags; /**< @ref mdb_env */
1231 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1232 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1233 unsigned int me_maxreaders; /**< size of the reader table */
1234 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1235 volatile int me_close_readers;
1236 MDB_dbi me_numdbs; /**< number of DBs opened */
1237 MDB_dbi me_maxdbs; /**< size of the DB table */
1238 MDB_PID_T me_pid; /**< process ID of this env */
1239 char *me_path; /**< path to the DB files */
1240 char *me_map; /**< the memory map of the data file */
1241 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1242 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1243 void *me_pbuf; /**< scratch area for DUPSORT put() */
1244 MDB_txn *me_txn; /**< current write transaction */
1245 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1246 size_t me_mapsize; /**< size of the data memory map */
1247 off_t me_size; /**< current file size */
1248 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1249 MDB_dbx *me_dbxs; /**< array of static DB info */
1250 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1251 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1252 pthread_key_t me_txkey; /**< thread-key for readers */
1253 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1254 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1255 # define me_pglast me_pgstate.mf_pglast
1256 # define me_pghead me_pgstate.mf_pghead
1257 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1258 /** IDL of pages that became unused in a write txn */
1259 MDB_IDL me_free_pgs;
1260 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1261 MDB_ID2L me_dirty_list;
1262 /** Max number of freelist items that can fit in a single overflow page */
1264 /** Max size of a node on a page */
1265 unsigned int me_nodemax;
1266 #if !(MDB_MAXKEYSIZE)
1267 unsigned int me_maxkey; /**< max size of a key */
1269 int me_live_reader; /**< have liveness lock in reader table */
1271 int me_pidquery; /**< Used in OpenProcess */
1273 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1274 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1275 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1277 mdb_mutex_t me_rmutex;
1278 mdb_mutex_t me_wmutex;
1280 void *me_userctx; /**< User-settable context */
1281 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1284 /** Nested transaction */
1285 typedef struct MDB_ntxn {
1286 MDB_txn mnt_txn; /**< the transaction */
1287 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1290 /** max number of pages to commit in one writev() call */
1291 #define MDB_COMMIT_PAGES 64
1292 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1293 #undef MDB_COMMIT_PAGES
1294 #define MDB_COMMIT_PAGES IOV_MAX
1297 /** max bytes to write in one call */
1298 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1300 /** Check \b txn and \b dbi arguments to a function */
1301 #define TXN_DBI_EXIST(txn, dbi, validity) \
1302 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1304 /** Check for misused \b dbi handles */
1305 #define TXN_DBI_CHANGED(txn, dbi) \
1306 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1308 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1309 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1310 static int mdb_page_touch(MDB_cursor *mc);
1312 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1313 "reset-tmp", "fail-begin", "fail-beginchild"}
1315 /* mdb_txn_end operation number, for logging */
1316 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1317 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1319 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1320 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1321 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1322 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1323 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1325 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1326 static int mdb_page_search_root(MDB_cursor *mc,
1327 MDB_val *key, int modify);
1328 #define MDB_PS_MODIFY 1
1329 #define MDB_PS_ROOTONLY 2
1330 #define MDB_PS_FIRST 4
1331 #define MDB_PS_LAST 8
1332 static int mdb_page_search(MDB_cursor *mc,
1333 MDB_val *key, int flags);
1334 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1336 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1337 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1338 pgno_t newpgno, unsigned int nflags);
1340 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1341 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1342 static int mdb_env_write_meta(MDB_txn *txn);
1343 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1344 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1346 static void mdb_env_close0(MDB_env *env, int excl);
1348 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1349 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1350 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1351 static void mdb_node_del(MDB_cursor *mc, int ksize);
1352 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1353 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1354 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1355 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1356 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1358 static int mdb_rebalance(MDB_cursor *mc);
1359 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1361 static void mdb_cursor_pop(MDB_cursor *mc);
1362 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1364 static int mdb_cursor_del0(MDB_cursor *mc);
1365 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1366 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1367 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1368 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1369 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1371 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1372 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1374 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1375 static void mdb_xcursor_init0(MDB_cursor *mc);
1376 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1377 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1379 static int mdb_drop0(MDB_cursor *mc, int subs);
1380 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1381 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1384 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1387 /** Compare two items pointing at size_t's of unknown alignment. */
1388 #ifdef MISALIGNED_OK
1389 # define mdb_cmp_clong mdb_cmp_long
1391 # define mdb_cmp_clong mdb_cmp_cint
1395 static SECURITY_DESCRIPTOR mdb_null_sd;
1396 static SECURITY_ATTRIBUTES mdb_all_sa;
1397 static int mdb_sec_inited;
1399 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1402 /** Return the library version info. */
1404 mdb_version(int *major, int *minor, int *patch)
1406 if (major) *major = MDB_VERSION_MAJOR;
1407 if (minor) *minor = MDB_VERSION_MINOR;
1408 if (patch) *patch = MDB_VERSION_PATCH;
1409 return MDB_VERSION_STRING;
1412 /** Table of descriptions for LMDB @ref errors */
1413 static char *const mdb_errstr[] = {
1414 "MDB_KEYEXIST: Key/data pair already exists",
1415 "MDB_NOTFOUND: No matching key/data pair found",
1416 "MDB_PAGE_NOTFOUND: Requested page not found",
1417 "MDB_CORRUPTED: Located page was wrong type",
1418 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1419 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1420 "MDB_INVALID: File is not an LMDB file",
1421 "MDB_MAP_FULL: Environment mapsize limit reached",
1422 "MDB_DBS_FULL: Environment maxdbs limit reached",
1423 "MDB_READERS_FULL: Environment maxreaders limit reached",
1424 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1425 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1426 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1427 "MDB_PAGE_FULL: Internal error - page has no more space",
1428 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1429 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1430 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1431 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1432 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1433 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1437 mdb_strerror(int err)
1440 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1441 * This works as long as no function between the call to mdb_strerror
1442 * and the actual use of the message uses more than 4K of stack.
1444 #define MSGSIZE 1024
1445 #define PADSIZE 4096
1446 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1450 return ("Successful return: 0");
1452 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1453 i = err - MDB_KEYEXIST;
1454 return mdb_errstr[i];
1458 /* These are the C-runtime error codes we use. The comment indicates
1459 * their numeric value, and the Win32 error they would correspond to
1460 * if the error actually came from a Win32 API. A major mess, we should
1461 * have used LMDB-specific error codes for everything.
1464 case ENOENT: /* 2, FILE_NOT_FOUND */
1465 case EIO: /* 5, ACCESS_DENIED */
1466 case ENOMEM: /* 12, INVALID_ACCESS */
1467 case EACCES: /* 13, INVALID_DATA */
1468 case EBUSY: /* 16, CURRENT_DIRECTORY */
1469 case EINVAL: /* 22, BAD_COMMAND */
1470 case ENOSPC: /* 28, OUT_OF_PAPER */
1471 return strerror(err);
1476 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1477 FORMAT_MESSAGE_IGNORE_INSERTS,
1478 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1481 return strerror(err);
1485 /** assert(3) variant in cursor context */
1486 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1487 /** assert(3) variant in transaction context */
1488 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1489 /** assert(3) variant in environment context */
1490 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1493 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1494 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1497 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1498 const char *func, const char *file, int line)
1501 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1502 file, line, expr_txt, func);
1503 if (env->me_assert_func)
1504 env->me_assert_func(env, buf);
1505 fprintf(stderr, "%s\n", buf);
1509 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1513 /** Return the page number of \b mp which may be sub-page, for debug output */
1515 mdb_dbg_pgno(MDB_page *mp)
1518 COPY_PGNO(ret, mp->mp_pgno);
1522 /** Display a key in hexadecimal and return the address of the result.
1523 * @param[in] key the key to display
1524 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1525 * @return The key in hexadecimal form.
1528 mdb_dkey(MDB_val *key, char *buf)
1531 unsigned char *c = key->mv_data;
1537 if (key->mv_size > DKBUF_MAXKEYSIZE)
1538 return "MDB_MAXKEYSIZE";
1539 /* may want to make this a dynamic check: if the key is mostly
1540 * printable characters, print it as-is instead of converting to hex.
1544 for (i=0; i<key->mv_size; i++)
1545 ptr += sprintf(ptr, "%02x", *c++);
1547 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1553 mdb_leafnode_type(MDB_node *n)
1555 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1556 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1557 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1560 /** Display all the keys in the page. */
1562 mdb_page_list(MDB_page *mp)
1564 pgno_t pgno = mdb_dbg_pgno(mp);
1565 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1567 unsigned int i, nkeys, nsize, total = 0;
1571 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1572 case P_BRANCH: type = "Branch page"; break;
1573 case P_LEAF: type = "Leaf page"; break;
1574 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1575 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1576 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1578 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1579 pgno, mp->mp_pages, state);
1582 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1583 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1586 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1590 nkeys = NUMKEYS(mp);
1591 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1593 for (i=0; i<nkeys; i++) {
1594 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1595 key.mv_size = nsize = mp->mp_pad;
1596 key.mv_data = LEAF2KEY(mp, i, nsize);
1598 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1601 node = NODEPTR(mp, i);
1602 key.mv_size = node->mn_ksize;
1603 key.mv_data = node->mn_data;
1604 nsize = NODESIZE + key.mv_size;
1605 if (IS_BRANCH(mp)) {
1606 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1610 if (F_ISSET(node->mn_flags, F_BIGDATA))
1611 nsize += sizeof(pgno_t);
1613 nsize += NODEDSZ(node);
1615 nsize += sizeof(indx_t);
1616 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1617 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1619 total = EVEN(total);
1621 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1622 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1626 mdb_cursor_chk(MDB_cursor *mc)
1632 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1633 for (i=0; i<mc->mc_top; i++) {
1635 node = NODEPTR(mp, mc->mc_ki[i]);
1636 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1639 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1641 if (XCURSOR_INITED(mc)) {
1642 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1643 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1644 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1652 /** Count all the pages in each DB and in the freelist
1653 * and make sure it matches the actual number of pages
1655 * All named DBs must be open for a correct count.
1657 static void mdb_audit(MDB_txn *txn)
1661 MDB_ID freecount, count;
1666 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1667 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1668 freecount += *(MDB_ID *)data.mv_data;
1669 mdb_tassert(txn, rc == MDB_NOTFOUND);
1672 for (i = 0; i<txn->mt_numdbs; i++) {
1674 if (!(txn->mt_dbflags[i] & DB_VALID))
1676 mdb_cursor_init(&mc, txn, i, &mx);
1677 if (txn->mt_dbs[i].md_root == P_INVALID)
1679 count += txn->mt_dbs[i].md_branch_pages +
1680 txn->mt_dbs[i].md_leaf_pages +
1681 txn->mt_dbs[i].md_overflow_pages;
1682 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1683 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1684 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1687 mp = mc.mc_pg[mc.mc_top];
1688 for (j=0; j<NUMKEYS(mp); j++) {
1689 MDB_node *leaf = NODEPTR(mp, j);
1690 if (leaf->mn_flags & F_SUBDATA) {
1692 memcpy(&db, NODEDATA(leaf), sizeof(db));
1693 count += db.md_branch_pages + db.md_leaf_pages +
1694 db.md_overflow_pages;
1698 mdb_tassert(txn, rc == MDB_NOTFOUND);
1701 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1702 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1703 txn->mt_txnid, freecount, count+NUM_METAS,
1704 freecount+count+NUM_METAS, txn->mt_next_pgno);
1710 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1712 return txn->mt_dbxs[dbi].md_cmp(a, b);
1716 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1718 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1719 #if UINT_MAX < SIZE_MAX
1720 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1721 dcmp = mdb_cmp_clong;
1726 /** Allocate memory for a page.
1727 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1730 mdb_page_malloc(MDB_txn *txn, unsigned num)
1732 MDB_env *env = txn->mt_env;
1733 MDB_page *ret = env->me_dpages;
1734 size_t psize = env->me_psize, sz = psize, off;
1735 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1736 * For a single page alloc, we init everything after the page header.
1737 * For multi-page, we init the final page; if the caller needed that
1738 * many pages they will be filling in at least up to the last page.
1742 VGMEMP_ALLOC(env, ret, sz);
1743 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1744 env->me_dpages = ret->mp_next;
1747 psize -= off = PAGEHDRSZ;
1752 if ((ret = malloc(sz)) != NULL) {
1753 VGMEMP_ALLOC(env, ret, sz);
1754 if (!(env->me_flags & MDB_NOMEMINIT)) {
1755 memset((char *)ret + off, 0, psize);
1759 txn->mt_flags |= MDB_TXN_ERROR;
1763 /** Free a single page.
1764 * Saves single pages to a list, for future reuse.
1765 * (This is not used for multi-page overflow pages.)
1768 mdb_page_free(MDB_env *env, MDB_page *mp)
1770 mp->mp_next = env->me_dpages;
1771 VGMEMP_FREE(env, mp);
1772 env->me_dpages = mp;
1775 /** Free a dirty page */
1777 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1779 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1780 mdb_page_free(env, dp);
1782 /* large pages just get freed directly */
1783 VGMEMP_FREE(env, dp);
1788 /** Return all dirty pages to dpage list */
1790 mdb_dlist_free(MDB_txn *txn)
1792 MDB_env *env = txn->mt_env;
1793 MDB_ID2L dl = txn->mt_u.dirty_list;
1794 unsigned i, n = dl[0].mid;
1796 for (i = 1; i <= n; i++) {
1797 mdb_dpage_free(env, dl[i].mptr);
1802 /** Loosen or free a single page.
1803 * Saves single pages to a list for future reuse
1804 * in this same txn. It has been pulled from the freeDB
1805 * and already resides on the dirty list, but has been
1806 * deleted. Use these pages first before pulling again
1809 * If the page wasn't dirtied in this txn, just add it
1810 * to this txn's free list.
1813 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1816 pgno_t pgno = mp->mp_pgno;
1817 MDB_txn *txn = mc->mc_txn;
1819 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1820 if (txn->mt_parent) {
1821 MDB_ID2 *dl = txn->mt_u.dirty_list;
1822 /* If txn has a parent, make sure the page is in our
1826 unsigned x = mdb_mid2l_search(dl, pgno);
1827 if (x <= dl[0].mid && dl[x].mid == pgno) {
1828 if (mp != dl[x].mptr) { /* bad cursor? */
1829 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1830 txn->mt_flags |= MDB_TXN_ERROR;
1831 return MDB_CORRUPTED;
1838 /* no parent txn, so it's just ours */
1843 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1845 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1846 txn->mt_loose_pgs = mp;
1847 txn->mt_loose_count++;
1848 mp->mp_flags |= P_LOOSE;
1850 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1858 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1859 * @param[in] mc A cursor handle for the current operation.
1860 * @param[in] pflags Flags of the pages to update:
1861 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1862 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1863 * @return 0 on success, non-zero on failure.
1866 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1868 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1869 MDB_txn *txn = mc->mc_txn;
1870 MDB_cursor *m3, *m0 = mc;
1875 int rc = MDB_SUCCESS, level;
1877 /* Mark pages seen by cursors */
1878 if (mc->mc_flags & C_UNTRACK)
1879 mc = NULL; /* will find mc in mt_cursors */
1880 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1881 for (; mc; mc=mc->mc_next) {
1882 if (!(mc->mc_flags & C_INITIALIZED))
1884 for (m3 = mc;; m3 = &mx->mx_cursor) {
1886 for (j=0; j<m3->mc_snum; j++) {
1888 if ((mp->mp_flags & Mask) == pflags)
1889 mp->mp_flags ^= P_KEEP;
1891 mx = m3->mc_xcursor;
1892 /* Proceed to mx if it is at a sub-database */
1893 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1895 if (! (mp && (mp->mp_flags & P_LEAF)))
1897 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1898 if (!(leaf->mn_flags & F_SUBDATA))
1907 /* Mark dirty root pages */
1908 for (i=0; i<txn->mt_numdbs; i++) {
1909 if (txn->mt_dbflags[i] & DB_DIRTY) {
1910 pgno_t pgno = txn->mt_dbs[i].md_root;
1911 if (pgno == P_INVALID)
1913 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1915 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1916 dp->mp_flags ^= P_KEEP;
1924 static int mdb_page_flush(MDB_txn *txn, int keep);
1926 /** Spill pages from the dirty list back to disk.
1927 * This is intended to prevent running into #MDB_TXN_FULL situations,
1928 * but note that they may still occur in a few cases:
1929 * 1) our estimate of the txn size could be too small. Currently this
1930 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1931 * 2) child txns may run out of space if their parents dirtied a
1932 * lot of pages and never spilled them. TODO: we probably should do
1933 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1934 * the parent's dirty_room is below a given threshold.
1936 * Otherwise, if not using nested txns, it is expected that apps will
1937 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1938 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1939 * If the txn never references them again, they can be left alone.
1940 * If the txn only reads them, they can be used without any fuss.
1941 * If the txn writes them again, they can be dirtied immediately without
1942 * going thru all of the work of #mdb_page_touch(). Such references are
1943 * handled by #mdb_page_unspill().
1945 * Also note, we never spill DB root pages, nor pages of active cursors,
1946 * because we'll need these back again soon anyway. And in nested txns,
1947 * we can't spill a page in a child txn if it was already spilled in a
1948 * parent txn. That would alter the parent txns' data even though
1949 * the child hasn't committed yet, and we'd have no way to undo it if
1950 * the child aborted.
1952 * @param[in] m0 cursor A cursor handle identifying the transaction and
1953 * database for which we are checking space.
1954 * @param[in] key For a put operation, the key being stored.
1955 * @param[in] data For a put operation, the data being stored.
1956 * @return 0 on success, non-zero on failure.
1959 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1961 MDB_txn *txn = m0->mc_txn;
1963 MDB_ID2L dl = txn->mt_u.dirty_list;
1964 unsigned int i, j, need;
1967 if (m0->mc_flags & C_SUB)
1970 /* Estimate how much space this op will take */
1971 i = m0->mc_db->md_depth;
1972 /* Named DBs also dirty the main DB */
1973 if (m0->mc_dbi >= CORE_DBS)
1974 i += txn->mt_dbs[MAIN_DBI].md_depth;
1975 /* For puts, roughly factor in the key+data size */
1977 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1978 i += i; /* double it for good measure */
1981 if (txn->mt_dirty_room > i)
1984 if (!txn->mt_spill_pgs) {
1985 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1986 if (!txn->mt_spill_pgs)
1989 /* purge deleted slots */
1990 MDB_IDL sl = txn->mt_spill_pgs;
1991 unsigned int num = sl[0];
1993 for (i=1; i<=num; i++) {
2000 /* Preserve pages which may soon be dirtied again */
2001 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2004 /* Less aggressive spill - we originally spilled the entire dirty list,
2005 * with a few exceptions for cursor pages and DB root pages. But this
2006 * turns out to be a lot of wasted effort because in a large txn many
2007 * of those pages will need to be used again. So now we spill only 1/8th
2008 * of the dirty pages. Testing revealed this to be a good tradeoff,
2009 * better than 1/2, 1/4, or 1/10.
2011 if (need < MDB_IDL_UM_MAX / 8)
2012 need = MDB_IDL_UM_MAX / 8;
2014 /* Save the page IDs of all the pages we're flushing */
2015 /* flush from the tail forward, this saves a lot of shifting later on. */
2016 for (i=dl[0].mid; i && need; i--) {
2017 MDB_ID pn = dl[i].mid << 1;
2019 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2021 /* Can't spill twice, make sure it's not already in a parent's
2024 if (txn->mt_parent) {
2026 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2027 if (tx2->mt_spill_pgs) {
2028 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2029 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2030 dp->mp_flags |= P_KEEP;
2038 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2042 mdb_midl_sort(txn->mt_spill_pgs);
2044 /* Flush the spilled part of dirty list */
2045 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2048 /* Reset any dirty pages we kept that page_flush didn't see */
2049 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2052 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2056 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2058 mdb_find_oldest(MDB_txn *txn)
2061 txnid_t mr, oldest = txn->mt_txnid - 1;
2062 if (txn->mt_env->me_txns) {
2063 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2064 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2075 /** Add a page to the txn's dirty list */
2077 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2080 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2082 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2083 insert = mdb_mid2l_append;
2085 insert = mdb_mid2l_insert;
2087 mid.mid = mp->mp_pgno;
2089 rc = insert(txn->mt_u.dirty_list, &mid);
2090 mdb_tassert(txn, rc == 0);
2091 txn->mt_dirty_room--;
2094 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2095 * me_pghead and mt_next_pgno.
2097 * If there are free pages available from older transactions, they
2098 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2099 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2100 * and move me_pglast to say which records were consumed. Only this
2101 * function can create me_pghead and move me_pglast/mt_next_pgno.
2102 * @param[in] mc cursor A cursor handle identifying the transaction and
2103 * database for which we are allocating.
2104 * @param[in] num the number of pages to allocate.
2105 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2106 * will always be satisfied by a single contiguous chunk of memory.
2107 * @return 0 on success, non-zero on failure.
2110 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2112 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2113 /* Get at most <Max_retries> more freeDB records once me_pghead
2114 * has enough pages. If not enough, use new pages from the map.
2115 * If <Paranoid> and mc is updating the freeDB, only get new
2116 * records if me_pghead is empty. Then the freelist cannot play
2117 * catch-up with itself by growing while trying to save it.
2119 enum { Paranoid = 1, Max_retries = 500 };
2121 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2123 int rc, retry = num * 60;
2124 MDB_txn *txn = mc->mc_txn;
2125 MDB_env *env = txn->mt_env;
2126 pgno_t pgno, *mop = env->me_pghead;
2127 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2129 txnid_t oldest = 0, last;
2134 /* If there are any loose pages, just use them */
2135 if (num == 1 && txn->mt_loose_pgs) {
2136 np = txn->mt_loose_pgs;
2137 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2138 txn->mt_loose_count--;
2139 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2147 /* If our dirty list is already full, we can't do anything */
2148 if (txn->mt_dirty_room == 0) {
2153 for (op = MDB_FIRST;; op = MDB_NEXT) {
2158 /* Seek a big enough contiguous page range. Prefer
2159 * pages at the tail, just truncating the list.
2165 if (mop[i-n2] == pgno+n2)
2172 if (op == MDB_FIRST) { /* 1st iteration */
2173 /* Prepare to fetch more and coalesce */
2174 last = env->me_pglast;
2175 oldest = env->me_pgoldest;
2176 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2179 key.mv_data = &last; /* will look up last+1 */
2180 key.mv_size = sizeof(last);
2182 if (Paranoid && mc->mc_dbi == FREE_DBI)
2185 if (Paranoid && retry < 0 && mop_len)
2189 /* Do not fetch more if the record will be too recent */
2190 if (oldest <= last) {
2192 oldest = mdb_find_oldest(txn);
2193 env->me_pgoldest = oldest;
2199 rc = mdb_cursor_get(&m2, &key, NULL, op);
2201 if (rc == MDB_NOTFOUND)
2205 last = *(txnid_t*)key.mv_data;
2206 if (oldest <= last) {
2208 oldest = mdb_find_oldest(txn);
2209 env->me_pgoldest = oldest;
2215 np = m2.mc_pg[m2.mc_top];
2216 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2217 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2220 idl = (MDB_ID *) data.mv_data;
2223 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2228 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2230 mop = env->me_pghead;
2232 env->me_pglast = last;
2234 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2235 last, txn->mt_dbs[FREE_DBI].md_root, i));
2237 DPRINTF(("IDL %"Z"u", idl[j]));
2239 /* Merge in descending sorted order */
2240 mdb_midl_xmerge(mop, idl);
2244 /* Use new pages from the map when nothing suitable in the freeDB */
2246 pgno = txn->mt_next_pgno;
2247 if (pgno + num >= env->me_maxpg) {
2248 DPUTS("DB size maxed out");
2254 if (env->me_flags & MDB_WRITEMAP) {
2255 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2257 if (!(np = mdb_page_malloc(txn, num))) {
2263 mop[0] = mop_len -= num;
2264 /* Move any stragglers down */
2265 for (j = i-num; j < mop_len; )
2266 mop[++j] = mop[++i];
2268 txn->mt_next_pgno = pgno + num;
2271 mdb_page_dirty(txn, np);
2277 txn->mt_flags |= MDB_TXN_ERROR;
2281 /** Copy the used portions of a non-overflow page.
2282 * @param[in] dst page to copy into
2283 * @param[in] src page to copy from
2284 * @param[in] psize size of a page
2287 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2289 enum { Align = sizeof(pgno_t) };
2290 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2292 /* If page isn't full, just copy the used portion. Adjust
2293 * alignment so memcpy may copy words instead of bytes.
2295 if ((unused &= -Align) && !IS_LEAF2(src)) {
2296 upper = (upper + PAGEBASE) & -Align;
2297 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2298 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2301 memcpy(dst, src, psize - unused);
2305 /** Pull a page off the txn's spill list, if present.
2306 * If a page being referenced was spilled to disk in this txn, bring
2307 * it back and make it dirty/writable again.
2308 * @param[in] txn the transaction handle.
2309 * @param[in] mp the page being referenced. It must not be dirty.
2310 * @param[out] ret the writable page, if any. ret is unchanged if
2311 * mp wasn't spilled.
2314 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2316 MDB_env *env = txn->mt_env;
2319 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2321 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2322 if (!tx2->mt_spill_pgs)
2324 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2325 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2328 if (txn->mt_dirty_room == 0)
2329 return MDB_TXN_FULL;
2330 if (IS_OVERFLOW(mp))
2334 if (env->me_flags & MDB_WRITEMAP) {
2337 np = mdb_page_malloc(txn, num);
2341 memcpy(np, mp, num * env->me_psize);
2343 mdb_page_copy(np, mp, env->me_psize);
2346 /* If in current txn, this page is no longer spilled.
2347 * If it happens to be the last page, truncate the spill list.
2348 * Otherwise mark it as deleted by setting the LSB.
2350 if (x == txn->mt_spill_pgs[0])
2351 txn->mt_spill_pgs[0]--;
2353 txn->mt_spill_pgs[x] |= 1;
2354 } /* otherwise, if belonging to a parent txn, the
2355 * page remains spilled until child commits
2358 mdb_page_dirty(txn, np);
2359 np->mp_flags |= P_DIRTY;
2367 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2368 * @param[in] mc cursor pointing to the page to be touched
2369 * @return 0 on success, non-zero on failure.
2372 mdb_page_touch(MDB_cursor *mc)
2374 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2375 MDB_txn *txn = mc->mc_txn;
2376 MDB_cursor *m2, *m3;
2380 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2381 if (txn->mt_flags & MDB_TXN_SPILLS) {
2383 rc = mdb_page_unspill(txn, mp, &np);
2389 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2390 (rc = mdb_page_alloc(mc, 1, &np)))
2393 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2394 mp->mp_pgno, pgno));
2395 mdb_cassert(mc, mp->mp_pgno != pgno);
2396 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2397 /* Update the parent page, if any, to point to the new page */
2399 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2400 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2401 SETPGNO(node, pgno);
2403 mc->mc_db->md_root = pgno;
2405 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2406 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2408 /* If txn has a parent, make sure the page is in our
2412 unsigned x = mdb_mid2l_search(dl, pgno);
2413 if (x <= dl[0].mid && dl[x].mid == pgno) {
2414 if (mp != dl[x].mptr) { /* bad cursor? */
2415 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2416 txn->mt_flags |= MDB_TXN_ERROR;
2417 return MDB_CORRUPTED;
2422 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2424 np = mdb_page_malloc(txn, 1);
2429 rc = mdb_mid2l_insert(dl, &mid);
2430 mdb_cassert(mc, rc == 0);
2435 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2437 np->mp_flags |= P_DIRTY;
2440 /* Adjust cursors pointing to mp */
2441 mc->mc_pg[mc->mc_top] = np;
2442 m2 = txn->mt_cursors[mc->mc_dbi];
2443 if (mc->mc_flags & C_SUB) {
2444 for (; m2; m2=m2->mc_next) {
2445 m3 = &m2->mc_xcursor->mx_cursor;
2446 if (m3->mc_snum < mc->mc_snum) continue;
2447 if (m3->mc_pg[mc->mc_top] == mp)
2448 m3->mc_pg[mc->mc_top] = np;
2451 for (; m2; m2=m2->mc_next) {
2452 if (m2->mc_snum < mc->mc_snum) continue;
2453 if (m2 == mc) continue;
2454 if (m2->mc_pg[mc->mc_top] == mp) {
2455 m2->mc_pg[mc->mc_top] = np;
2456 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2457 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2464 txn->mt_flags |= MDB_TXN_ERROR;
2469 mdb_env_sync(MDB_env *env, int force)
2472 if (env->me_flags & MDB_RDONLY)
2474 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2475 if (env->me_flags & MDB_WRITEMAP) {
2476 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2477 ? MS_ASYNC : MS_SYNC;
2478 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2481 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2485 #ifdef BROKEN_FDATASYNC
2486 if (env->me_flags & MDB_FSYNCONLY) {
2487 if (fsync(env->me_fd))
2491 if (MDB_FDATASYNC(env->me_fd))
2498 /** Back up parent txn's cursors, then grab the originals for tracking */
2500 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2502 MDB_cursor *mc, *bk;
2507 for (i = src->mt_numdbs; --i >= 0; ) {
2508 if ((mc = src->mt_cursors[i]) != NULL) {
2509 size = sizeof(MDB_cursor);
2511 size += sizeof(MDB_xcursor);
2512 for (; mc; mc = bk->mc_next) {
2518 mc->mc_db = &dst->mt_dbs[i];
2519 /* Kill pointers into src to reduce abuse: The
2520 * user may not use mc until dst ends. But we need a valid
2521 * txn pointer here for cursor fixups to keep working.
2524 mc->mc_dbflag = &dst->mt_dbflags[i];
2525 if ((mx = mc->mc_xcursor) != NULL) {
2526 *(MDB_xcursor *)(bk+1) = *mx;
2527 mx->mx_cursor.mc_txn = dst;
2529 mc->mc_next = dst->mt_cursors[i];
2530 dst->mt_cursors[i] = mc;
2537 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2538 * @param[in] txn the transaction handle.
2539 * @param[in] merge true to keep changes to parent cursors, false to revert.
2540 * @return 0 on success, non-zero on failure.
2543 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2545 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2549 for (i = txn->mt_numdbs; --i >= 0; ) {
2550 for (mc = cursors[i]; mc; mc = next) {
2552 if ((bk = mc->mc_backup) != NULL) {
2554 /* Commit changes to parent txn */
2555 mc->mc_next = bk->mc_next;
2556 mc->mc_backup = bk->mc_backup;
2557 mc->mc_txn = bk->mc_txn;
2558 mc->mc_db = bk->mc_db;
2559 mc->mc_dbflag = bk->mc_dbflag;
2560 if ((mx = mc->mc_xcursor) != NULL)
2561 mx->mx_cursor.mc_txn = bk->mc_txn;
2563 /* Abort nested txn */
2565 if ((mx = mc->mc_xcursor) != NULL)
2566 *mx = *(MDB_xcursor *)(bk+1);
2570 /* Only malloced cursors are permanently tracked. */
2577 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2583 Pidset = F_SETLK, Pidcheck = F_GETLK
2587 /** Set or check a pid lock. Set returns 0 on success.
2588 * Check returns 0 if the process is certainly dead, nonzero if it may
2589 * be alive (the lock exists or an error happened so we do not know).
2591 * On Windows Pidset is a no-op, we merely check for the existence
2592 * of the process with the given pid. On POSIX we use a single byte
2593 * lock on the lockfile, set at an offset equal to the pid.
2596 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2598 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2601 if (op == Pidcheck) {
2602 h = OpenProcess(env->me_pidquery, FALSE, pid);
2603 /* No documented "no such process" code, but other program use this: */
2605 return ErrCode() != ERROR_INVALID_PARAMETER;
2606 /* A process exists until all handles to it close. Has it exited? */
2607 ret = WaitForSingleObject(h, 0) != 0;
2614 struct flock lock_info;
2615 memset(&lock_info, 0, sizeof(lock_info));
2616 lock_info.l_type = F_WRLCK;
2617 lock_info.l_whence = SEEK_SET;
2618 lock_info.l_start = pid;
2619 lock_info.l_len = 1;
2620 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2621 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2623 } else if ((rc = ErrCode()) == EINTR) {
2631 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2632 * @param[in] txn the transaction handle to initialize
2633 * @return 0 on success, non-zero on failure.
2636 mdb_txn_renew0(MDB_txn *txn)
2638 MDB_env *env = txn->mt_env;
2639 MDB_txninfo *ti = env->me_txns;
2641 unsigned int i, nr, flags = txn->mt_flags;
2643 int rc, new_notls = 0;
2645 if ((flags &= MDB_TXN_RDONLY) != 0) {
2647 meta = mdb_env_pick_meta(env);
2648 txn->mt_txnid = meta->mm_txnid;
2649 txn->mt_u.reader = NULL;
2651 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2652 pthread_getspecific(env->me_txkey);
2654 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2655 return MDB_BAD_RSLOT;
2657 MDB_PID_T pid = env->me_pid;
2658 MDB_THR_T tid = pthread_self();
2659 mdb_mutexref_t rmutex = env->me_rmutex;
2661 if (!env->me_live_reader) {
2662 rc = mdb_reader_pid(env, Pidset, pid);
2665 env->me_live_reader = 1;
2668 if (LOCK_MUTEX(rc, env, rmutex))
2670 nr = ti->mti_numreaders;
2671 for (i=0; i<nr; i++)
2672 if (ti->mti_readers[i].mr_pid == 0)
2674 if (i == env->me_maxreaders) {
2675 UNLOCK_MUTEX(rmutex);
2676 return MDB_READERS_FULL;
2678 r = &ti->mti_readers[i];
2679 /* Claim the reader slot, carefully since other code
2680 * uses the reader table un-mutexed: First reset the
2681 * slot, next publish it in mti_numreaders. After
2682 * that, it is safe for mdb_env_close() to touch it.
2683 * When it will be closed, we can finally claim it.
2686 r->mr_txnid = (txnid_t)-1;
2689 ti->mti_numreaders = ++nr;
2690 env->me_close_readers = nr;
2692 UNLOCK_MUTEX(rmutex);
2694 new_notls = (env->me_flags & MDB_NOTLS);
2695 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2700 do /* LY: Retry on a race, ITS#7970. */
2701 r->mr_txnid = ti->mti_txnid;
2702 while(r->mr_txnid != ti->mti_txnid);
2703 txn->mt_txnid = r->mr_txnid;
2704 txn->mt_u.reader = r;
2705 meta = env->me_metas[txn->mt_txnid & 1];
2709 /* Not yet touching txn == env->me_txn0, it may be active */
2711 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2713 txn->mt_txnid = ti->mti_txnid;
2714 meta = env->me_metas[txn->mt_txnid & 1];
2716 meta = mdb_env_pick_meta(env);
2717 txn->mt_txnid = meta->mm_txnid;
2721 if (txn->mt_txnid == mdb_debug_start)
2724 txn->mt_child = NULL;
2725 txn->mt_loose_pgs = NULL;
2726 txn->mt_loose_count = 0;
2727 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2728 txn->mt_u.dirty_list = env->me_dirty_list;
2729 txn->mt_u.dirty_list[0].mid = 0;
2730 txn->mt_free_pgs = env->me_free_pgs;
2731 txn->mt_free_pgs[0] = 0;
2732 txn->mt_spill_pgs = NULL;
2734 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2737 /* Copy the DB info and flags */
2738 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2740 /* Moved to here to avoid a data race in read TXNs */
2741 txn->mt_next_pgno = meta->mm_last_pg+1;
2743 txn->mt_flags = flags;
2746 txn->mt_numdbs = env->me_numdbs;
2747 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2748 x = env->me_dbflags[i];
2749 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2750 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2752 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2753 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2755 if (env->me_flags & MDB_FATAL_ERROR) {
2756 DPUTS("environment had fatal error, must shutdown!");
2758 } else if (env->me_maxpg < txn->mt_next_pgno) {
2759 rc = MDB_MAP_RESIZED;
2763 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2768 mdb_txn_renew(MDB_txn *txn)
2772 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2775 rc = mdb_txn_renew0(txn);
2776 if (rc == MDB_SUCCESS) {
2777 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2778 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2779 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2785 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2789 int rc, size, tsize;
2791 flags &= MDB_TXN_BEGIN_FLAGS;
2792 flags |= env->me_flags & MDB_WRITEMAP;
2794 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2798 /* Nested transactions: Max 1 child, write txns only, no writemap */
2799 flags |= parent->mt_flags;
2800 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2801 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2803 /* Child txns save MDB_pgstate and use own copy of cursors */
2804 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2805 size += tsize = sizeof(MDB_ntxn);
2806 } else if (flags & MDB_RDONLY) {
2807 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2808 size += tsize = sizeof(MDB_txn);
2810 /* Reuse preallocated write txn. However, do not touch it until
2811 * mdb_txn_renew0() succeeds, since it currently may be active.
2816 if ((txn = calloc(1, size)) == NULL) {
2817 DPRINTF(("calloc: %s", strerror(errno)));
2820 txn->mt_dbxs = env->me_dbxs; /* static */
2821 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2822 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2823 txn->mt_flags = flags;
2828 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2829 txn->mt_dbiseqs = parent->mt_dbiseqs;
2830 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2831 if (!txn->mt_u.dirty_list ||
2832 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2834 free(txn->mt_u.dirty_list);
2838 txn->mt_txnid = parent->mt_txnid;
2839 txn->mt_dirty_room = parent->mt_dirty_room;
2840 txn->mt_u.dirty_list[0].mid = 0;
2841 txn->mt_spill_pgs = NULL;
2842 txn->mt_next_pgno = parent->mt_next_pgno;
2843 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2844 parent->mt_child = txn;
2845 txn->mt_parent = parent;
2846 txn->mt_numdbs = parent->mt_numdbs;
2847 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2848 /* Copy parent's mt_dbflags, but clear DB_NEW */
2849 for (i=0; i<txn->mt_numdbs; i++)
2850 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2852 ntxn = (MDB_ntxn *)txn;
2853 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2854 if (env->me_pghead) {
2855 size = MDB_IDL_SIZEOF(env->me_pghead);
2856 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2858 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2863 rc = mdb_cursor_shadow(parent, txn);
2865 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2866 } else { /* MDB_RDONLY */
2867 txn->mt_dbiseqs = env->me_dbiseqs;
2869 rc = mdb_txn_renew0(txn);
2872 if (txn != env->me_txn0)
2875 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2877 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2878 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2879 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2886 mdb_txn_env(MDB_txn *txn)
2888 if(!txn) return NULL;
2893 mdb_txn_id(MDB_txn *txn)
2896 return txn->mt_txnid;
2899 /** Export or close DBI handles opened in this txn. */
2901 mdb_dbis_update(MDB_txn *txn, int keep)
2904 MDB_dbi n = txn->mt_numdbs;
2905 MDB_env *env = txn->mt_env;
2906 unsigned char *tdbflags = txn->mt_dbflags;
2908 for (i = n; --i >= CORE_DBS;) {
2909 if (tdbflags[i] & DB_NEW) {
2911 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2913 char *ptr = env->me_dbxs[i].md_name.mv_data;
2915 env->me_dbxs[i].md_name.mv_data = NULL;
2916 env->me_dbxs[i].md_name.mv_size = 0;
2917 env->me_dbflags[i] = 0;
2918 env->me_dbiseqs[i]++;
2924 if (keep && env->me_numdbs < n)
2928 /** End a transaction, except successful commit of a nested transaction.
2929 * May be called twice for readonly txns: First reset it, then abort.
2930 * @param[in] txn the transaction handle to end
2931 * @param[in] mode why and how to end the transaction
2934 mdb_txn_end(MDB_txn *txn, unsigned mode)
2936 MDB_env *env = txn->mt_env;
2938 static const char *const names[] = MDB_END_NAMES;
2941 /* Export or close DBI handles opened in this txn */
2942 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2944 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2945 names[mode & MDB_END_OPMASK],
2946 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2947 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2949 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2950 if (txn->mt_u.reader) {
2951 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2952 if (!(env->me_flags & MDB_NOTLS)) {
2953 txn->mt_u.reader = NULL; /* txn does not own reader */
2954 } else if (mode & MDB_END_SLOT) {
2955 txn->mt_u.reader->mr_pid = 0;
2956 txn->mt_u.reader = NULL;
2957 } /* else txn owns the slot until it does MDB_END_SLOT */
2959 txn->mt_numdbs = 0; /* prevent further DBI activity */
2960 txn->mt_flags |= MDB_TXN_FINISHED;
2962 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2963 pgno_t *pghead = env->me_pghead;
2965 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2966 mdb_cursors_close(txn, 0);
2967 if (!(env->me_flags & MDB_WRITEMAP)) {
2968 mdb_dlist_free(txn);
2972 txn->mt_flags = MDB_TXN_FINISHED;
2974 if (!txn->mt_parent) {
2975 mdb_midl_shrink(&txn->mt_free_pgs);
2976 env->me_free_pgs = txn->mt_free_pgs;
2978 env->me_pghead = NULL;
2982 mode = 0; /* txn == env->me_txn0, do not free() it */
2984 /* The writer mutex was locked in mdb_txn_begin. */
2986 UNLOCK_MUTEX(env->me_wmutex);
2988 txn->mt_parent->mt_child = NULL;
2989 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
2990 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2991 mdb_midl_free(txn->mt_free_pgs);
2992 mdb_midl_free(txn->mt_spill_pgs);
2993 free(txn->mt_u.dirty_list);
2996 mdb_midl_free(pghead);
2999 if (mode & MDB_END_FREE)
3004 mdb_txn_reset(MDB_txn *txn)
3009 /* This call is only valid for read-only txns */
3010 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3013 mdb_txn_end(txn, MDB_END_RESET);
3017 mdb_txn_abort(MDB_txn *txn)
3023 mdb_txn_abort(txn->mt_child);
3025 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3028 /** Save the freelist as of this transaction to the freeDB.
3029 * This changes the freelist. Keep trying until it stabilizes.
3032 mdb_freelist_save(MDB_txn *txn)
3034 /* env->me_pghead[] can grow and shrink during this call.
3035 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3036 * Page numbers cannot disappear from txn->mt_free_pgs[].
3039 MDB_env *env = txn->mt_env;
3040 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3041 txnid_t pglast = 0, head_id = 0;
3042 pgno_t freecnt = 0, *free_pgs, *mop;
3043 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3045 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3047 if (env->me_pghead) {
3048 /* Make sure first page of freeDB is touched and on freelist */
3049 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3050 if (rc && rc != MDB_NOTFOUND)
3054 if (!env->me_pghead && txn->mt_loose_pgs) {
3055 /* Put loose page numbers in mt_free_pgs, since
3056 * we may be unable to return them to me_pghead.
3058 MDB_page *mp = txn->mt_loose_pgs;
3059 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3061 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3062 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3063 txn->mt_loose_pgs = NULL;
3064 txn->mt_loose_count = 0;
3067 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3068 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3069 ? SSIZE_MAX : maxfree_1pg;
3072 /* Come back here after each Put() in case freelist changed */
3077 /* If using records from freeDB which we have not yet
3078 * deleted, delete them and any we reserved for me_pghead.
3080 while (pglast < env->me_pglast) {
3081 rc = mdb_cursor_first(&mc, &key, NULL);
3084 pglast = head_id = *(txnid_t *)key.mv_data;
3085 total_room = head_room = 0;
3086 mdb_tassert(txn, pglast <= env->me_pglast);
3087 rc = mdb_cursor_del(&mc, 0);
3092 /* Save the IDL of pages freed by this txn, to a single record */
3093 if (freecnt < txn->mt_free_pgs[0]) {
3095 /* Make sure last page of freeDB is touched and on freelist */
3096 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3097 if (rc && rc != MDB_NOTFOUND)
3100 free_pgs = txn->mt_free_pgs;
3101 /* Write to last page of freeDB */
3102 key.mv_size = sizeof(txn->mt_txnid);
3103 key.mv_data = &txn->mt_txnid;
3105 freecnt = free_pgs[0];
3106 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3107 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3110 /* Retry if mt_free_pgs[] grew during the Put() */
3111 free_pgs = txn->mt_free_pgs;
3112 } while (freecnt < free_pgs[0]);
3113 mdb_midl_sort(free_pgs);
3114 memcpy(data.mv_data, free_pgs, data.mv_size);
3117 unsigned int i = free_pgs[0];
3118 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3119 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3121 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3127 mop = env->me_pghead;
3128 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3130 /* Reserve records for me_pghead[]. Split it if multi-page,
3131 * to avoid searching freeDB for a page range. Use keys in
3132 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3134 if (total_room >= mop_len) {
3135 if (total_room == mop_len || --more < 0)
3137 } else if (head_room >= maxfree_1pg && head_id > 1) {
3138 /* Keep current record (overflow page), add a new one */
3142 /* (Re)write {key = head_id, IDL length = head_room} */
3143 total_room -= head_room;
3144 head_room = mop_len - total_room;
3145 if (head_room > maxfree_1pg && head_id > 1) {
3146 /* Overflow multi-page for part of me_pghead */
3147 head_room /= head_id; /* amortize page sizes */
3148 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3149 } else if (head_room < 0) {
3150 /* Rare case, not bothering to delete this record */
3153 key.mv_size = sizeof(head_id);
3154 key.mv_data = &head_id;
3155 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3156 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3159 /* IDL is initially empty, zero out at least the length */
3160 pgs = (pgno_t *)data.mv_data;
3161 j = head_room > clean_limit ? head_room : 0;
3165 total_room += head_room;
3168 /* Return loose page numbers to me_pghead, though usually none are
3169 * left at this point. The pages themselves remain in dirty_list.
3171 if (txn->mt_loose_pgs) {
3172 MDB_page *mp = txn->mt_loose_pgs;
3173 unsigned count = txn->mt_loose_count;
3175 /* Room for loose pages + temp IDL with same */
3176 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3178 mop = env->me_pghead;
3179 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3180 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3181 loose[ ++count ] = mp->mp_pgno;
3183 mdb_midl_sort(loose);
3184 mdb_midl_xmerge(mop, loose);
3185 txn->mt_loose_pgs = NULL;
3186 txn->mt_loose_count = 0;
3190 /* Fill in the reserved me_pghead records */
3196 rc = mdb_cursor_first(&mc, &key, &data);
3197 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3198 txnid_t id = *(txnid_t *)key.mv_data;
3199 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3202 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3204 if (len > mop_len) {
3206 data.mv_size = (len + 1) * sizeof(MDB_ID);
3208 data.mv_data = mop -= len;
3211 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3213 if (rc || !(mop_len -= len))
3220 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3221 * @param[in] txn the transaction that's being committed
3222 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3223 * @return 0 on success, non-zero on failure.
3226 mdb_page_flush(MDB_txn *txn, int keep)
3228 MDB_env *env = txn->mt_env;
3229 MDB_ID2L dl = txn->mt_u.dirty_list;
3230 unsigned psize = env->me_psize, j;
3231 int i, pagecount = dl[0].mid, rc;
3232 size_t size = 0, pos = 0;
3234 MDB_page *dp = NULL;
3238 struct iovec iov[MDB_COMMIT_PAGES];
3239 ssize_t wpos = 0, wsize = 0, wres;
3240 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3246 if (env->me_flags & MDB_WRITEMAP) {
3247 /* Clear dirty flags */
3248 while (++i <= pagecount) {
3250 /* Don't flush this page yet */
3251 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3252 dp->mp_flags &= ~P_KEEP;
3256 dp->mp_flags &= ~P_DIRTY;
3261 /* Write the pages */
3263 if (++i <= pagecount) {
3265 /* Don't flush this page yet */
3266 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3267 dp->mp_flags &= ~P_KEEP;
3272 /* clear dirty flag */
3273 dp->mp_flags &= ~P_DIRTY;
3276 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3281 /* Windows actually supports scatter/gather I/O, but only on
3282 * unbuffered file handles. Since we're relying on the OS page
3283 * cache for all our data, that's self-defeating. So we just
3284 * write pages one at a time. We use the ov structure to set
3285 * the write offset, to at least save the overhead of a Seek
3288 DPRINTF(("committing page %"Z"u", pgno));
3289 memset(&ov, 0, sizeof(ov));
3290 ov.Offset = pos & 0xffffffff;
3291 ov.OffsetHigh = pos >> 16 >> 16;
3292 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3294 DPRINTF(("WriteFile: %d", rc));
3298 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3299 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3302 /* Write previous page(s) */
3303 #ifdef MDB_USE_PWRITEV
3304 wres = pwritev(env->me_fd, iov, n, wpos);
3307 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3310 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3314 DPRINTF(("lseek: %s", strerror(rc)));
3317 wres = writev(env->me_fd, iov, n);
3320 if (wres != wsize) {
3325 DPRINTF(("Write error: %s", strerror(rc)));
3327 rc = EIO; /* TODO: Use which error code? */
3328 DPUTS("short write, filesystem full?");
3339 DPRINTF(("committing page %"Z"u", pgno));
3340 next_pos = pos + size;
3341 iov[n].iov_len = size;
3342 iov[n].iov_base = (char *)dp;
3348 /* MIPS has cache coherency issues, this is a no-op everywhere else
3349 * Note: for any size >= on-chip cache size, entire on-chip cache is
3352 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3354 for (i = keep; ++i <= pagecount; ) {
3356 /* This is a page we skipped above */
3359 dl[j].mid = dp->mp_pgno;
3362 mdb_dpage_free(env, dp);
3367 txn->mt_dirty_room += i - j;
3373 mdb_txn_commit(MDB_txn *txn)
3376 unsigned int i, end_mode;
3382 /* mdb_txn_end() mode for a commit which writes nothing */
3383 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3385 if (txn->mt_child) {
3386 rc = mdb_txn_commit(txn->mt_child);
3393 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3397 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3398 DPUTS("txn has failed/finished, can't commit");
3400 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3405 if (txn->mt_parent) {
3406 MDB_txn *parent = txn->mt_parent;
3410 unsigned x, y, len, ps_len;
3412 /* Append our free list to parent's */
3413 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3416 mdb_midl_free(txn->mt_free_pgs);
3417 /* Failures after this must either undo the changes
3418 * to the parent or set MDB_TXN_ERROR in the parent.
3421 parent->mt_next_pgno = txn->mt_next_pgno;
3422 parent->mt_flags = txn->mt_flags;
3424 /* Merge our cursors into parent's and close them */
3425 mdb_cursors_close(txn, 1);
3427 /* Update parent's DB table. */
3428 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3429 parent->mt_numdbs = txn->mt_numdbs;
3430 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3431 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3432 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3433 /* preserve parent's DB_NEW status */
3434 x = parent->mt_dbflags[i] & DB_NEW;
3435 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3438 dst = parent->mt_u.dirty_list;
3439 src = txn->mt_u.dirty_list;
3440 /* Remove anything in our dirty list from parent's spill list */
3441 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3443 pspill[0] = (pgno_t)-1;
3444 /* Mark our dirty pages as deleted in parent spill list */
3445 for (i=0, len=src[0].mid; ++i <= len; ) {
3446 MDB_ID pn = src[i].mid << 1;
3447 while (pn > pspill[x])
3449 if (pn == pspill[x]) {
3454 /* Squash deleted pagenums if we deleted any */
3455 for (x=y; ++x <= ps_len; )
3456 if (!(pspill[x] & 1))
3457 pspill[++y] = pspill[x];
3461 /* Remove anything in our spill list from parent's dirty list */
3462 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3463 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3464 MDB_ID pn = txn->mt_spill_pgs[i];
3466 continue; /* deleted spillpg */
3468 y = mdb_mid2l_search(dst, pn);
3469 if (y <= dst[0].mid && dst[y].mid == pn) {
3471 while (y < dst[0].mid) {
3480 /* Find len = length of merging our dirty list with parent's */
3482 dst[0].mid = 0; /* simplify loops */
3483 if (parent->mt_parent) {
3484 len = x + src[0].mid;
3485 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3486 for (i = x; y && i; y--) {
3487 pgno_t yp = src[y].mid;
3488 while (yp < dst[i].mid)
3490 if (yp == dst[i].mid) {
3495 } else { /* Simplify the above for single-ancestor case */
3496 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3498 /* Merge our dirty list with parent's */
3500 for (i = len; y; dst[i--] = src[y--]) {
3501 pgno_t yp = src[y].mid;
3502 while (yp < dst[x].mid)
3503 dst[i--] = dst[x--];
3504 if (yp == dst[x].mid)
3505 free(dst[x--].mptr);
3507 mdb_tassert(txn, i == x);
3509 free(txn->mt_u.dirty_list);
3510 parent->mt_dirty_room = txn->mt_dirty_room;
3511 if (txn->mt_spill_pgs) {
3512 if (parent->mt_spill_pgs) {
3513 /* TODO: Prevent failure here, so parent does not fail */
3514 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3516 parent->mt_flags |= MDB_TXN_ERROR;
3517 mdb_midl_free(txn->mt_spill_pgs);
3518 mdb_midl_sort(parent->mt_spill_pgs);
3520 parent->mt_spill_pgs = txn->mt_spill_pgs;
3524 /* Append our loose page list to parent's */
3525 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3527 *lp = txn->mt_loose_pgs;
3528 parent->mt_loose_count += txn->mt_loose_count;
3530 parent->mt_child = NULL;
3531 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3536 if (txn != env->me_txn) {
3537 DPUTS("attempt to commit unknown transaction");
3542 mdb_cursors_close(txn, 0);
3544 if (!txn->mt_u.dirty_list[0].mid &&
3545 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3548 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3549 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3551 /* Update DB root pointers */
3552 if (txn->mt_numdbs > CORE_DBS) {
3556 data.mv_size = sizeof(MDB_db);
3558 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3559 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3560 if (txn->mt_dbflags[i] & DB_DIRTY) {
3561 if (TXN_DBI_CHANGED(txn, i)) {
3565 data.mv_data = &txn->mt_dbs[i];
3566 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3574 rc = mdb_freelist_save(txn);
3578 mdb_midl_free(env->me_pghead);
3579 env->me_pghead = NULL;
3580 mdb_midl_shrink(&txn->mt_free_pgs);
3586 if ((rc = mdb_page_flush(txn, 0)) ||
3587 (rc = mdb_env_sync(env, 0)) ||
3588 (rc = mdb_env_write_meta(txn)))
3590 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3593 mdb_txn_end(txn, end_mode);
3601 /** Read the environment parameters of a DB environment before
3602 * mapping it into memory.
3603 * @param[in] env the environment handle
3604 * @param[out] meta address of where to store the meta information
3605 * @return 0 on success, non-zero on failure.
3608 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3614 enum { Size = sizeof(pbuf) };
3616 /* We don't know the page size yet, so use a minimum value.
3617 * Read both meta pages so we can use the latest one.
3620 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3624 memset(&ov, 0, sizeof(ov));
3626 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3627 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3630 rc = pread(env->me_fd, &pbuf, Size, off);
3633 if (rc == 0 && off == 0)
3635 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3636 DPRINTF(("read: %s", mdb_strerror(rc)));
3640 p = (MDB_page *)&pbuf;
3642 if (!F_ISSET(p->mp_flags, P_META)) {
3643 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3648 if (m->mm_magic != MDB_MAGIC) {
3649 DPUTS("meta has invalid magic");
3653 if (m->mm_version != MDB_DATA_VERSION) {
3654 DPRINTF(("database is version %u, expected version %u",
3655 m->mm_version, MDB_DATA_VERSION));
3656 return MDB_VERSION_MISMATCH;
3659 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3665 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3667 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3669 meta->mm_magic = MDB_MAGIC;
3670 meta->mm_version = MDB_DATA_VERSION;
3671 meta->mm_mapsize = env->me_mapsize;
3672 meta->mm_psize = env->me_psize;
3673 meta->mm_last_pg = NUM_METAS-1;
3674 meta->mm_flags = env->me_flags & 0xffff;
3675 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3676 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3677 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3680 /** Write the environment parameters of a freshly created DB environment.
3681 * @param[in] env the environment handle
3682 * @param[in] meta the #MDB_meta to write
3683 * @return 0 on success, non-zero on failure.
3686 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3694 memset(&ov, 0, sizeof(ov));
3695 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3697 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3700 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3701 len = pwrite(fd, ptr, size, pos); \
3702 if (len == -1 && ErrCode() == EINTR) continue; \
3703 rc = (len >= 0); break; } while(1)
3706 DPUTS("writing new meta page");
3708 psize = env->me_psize;
3710 p = calloc(NUM_METAS, psize);
3715 p->mp_flags = P_META;
3716 *(MDB_meta *)METADATA(p) = *meta;
3718 q = (MDB_page *)((char *)p + psize);
3720 q->mp_flags = P_META;
3721 *(MDB_meta *)METADATA(q) = *meta;
3723 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3726 else if ((unsigned) len == psize * NUM_METAS)
3734 /** Update the environment info to commit a transaction.
3735 * @param[in] txn the transaction that's being committed
3736 * @return 0 on success, non-zero on failure.
3739 mdb_env_write_meta(MDB_txn *txn)
3742 MDB_meta meta, metab, *mp;
3746 int rc, len, toggle;
3755 toggle = txn->mt_txnid & 1;
3756 DPRINTF(("writing meta page %d for root page %"Z"u",
3757 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3760 flags = env->me_flags;
3761 mp = env->me_metas[toggle];
3762 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3763 /* Persist any increases of mapsize config */
3764 if (mapsize < env->me_mapsize)
3765 mapsize = env->me_mapsize;
3767 if (flags & MDB_WRITEMAP) {
3768 mp->mm_mapsize = mapsize;
3769 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3770 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3771 mp->mm_last_pg = txn->mt_next_pgno - 1;
3772 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3773 !(defined(__i386__) || defined(__x86_64__))
3774 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3775 __sync_synchronize();
3777 mp->mm_txnid = txn->mt_txnid;
3778 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3779 unsigned meta_size = env->me_psize;
3780 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3781 ptr = (char *)mp - PAGEHDRSZ;
3782 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3783 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3787 if (MDB_MSYNC(ptr, meta_size, rc)) {
3794 metab.mm_txnid = mp->mm_txnid;
3795 metab.mm_last_pg = mp->mm_last_pg;
3797 meta.mm_mapsize = mapsize;
3798 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3799 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3800 meta.mm_last_pg = txn->mt_next_pgno - 1;
3801 meta.mm_txnid = txn->mt_txnid;
3803 off = offsetof(MDB_meta, mm_mapsize);
3804 ptr = (char *)&meta + off;
3805 len = sizeof(MDB_meta) - off;
3806 off += (char *)mp - env->me_map;
3808 /* Write to the SYNC fd */
3809 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3812 memset(&ov, 0, sizeof(ov));
3814 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3819 rc = pwrite(mfd, ptr, len, off);
3822 rc = rc < 0 ? ErrCode() : EIO;
3827 DPUTS("write failed, disk error?");
3828 /* On a failure, the pagecache still contains the new data.
3829 * Write some old data back, to prevent it from being used.
3830 * Use the non-SYNC fd; we know it will fail anyway.
3832 meta.mm_last_pg = metab.mm_last_pg;
3833 meta.mm_txnid = metab.mm_txnid;
3835 memset(&ov, 0, sizeof(ov));
3837 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3839 r2 = pwrite(env->me_fd, ptr, len, off);
3840 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3843 env->me_flags |= MDB_FATAL_ERROR;
3846 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3847 CACHEFLUSH(env->me_map + off, len, DCACHE);
3849 /* Memory ordering issues are irrelevant; since the entire writer
3850 * is wrapped by wmutex, all of these changes will become visible
3851 * after the wmutex is unlocked. Since the DB is multi-version,
3852 * readers will get consistent data regardless of how fresh or
3853 * how stale their view of these values is.
3856 env->me_txns->mti_txnid = txn->mt_txnid;
3861 /** Check both meta pages to see which one is newer.
3862 * @param[in] env the environment handle
3863 * @return newest #MDB_meta.
3866 mdb_env_pick_meta(const MDB_env *env)
3868 MDB_meta *const *metas = env->me_metas;
3869 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3873 mdb_env_create(MDB_env **env)
3877 e = calloc(1, sizeof(MDB_env));
3881 e->me_maxreaders = DEFAULT_READERS;
3882 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3883 e->me_fd = INVALID_HANDLE_VALUE;
3884 e->me_lfd = INVALID_HANDLE_VALUE;
3885 e->me_mfd = INVALID_HANDLE_VALUE;
3886 #ifdef MDB_USE_POSIX_SEM
3887 e->me_rmutex = SEM_FAILED;
3888 e->me_wmutex = SEM_FAILED;
3890 e->me_pid = getpid();
3891 GET_PAGESIZE(e->me_os_psize);
3892 VGMEMP_CREATE(e,0,0);
3898 mdb_env_map(MDB_env *env, void *addr)
3901 unsigned int flags = env->me_flags;
3905 LONG sizelo, sizehi;
3908 if (flags & MDB_RDONLY) {
3909 /* Don't set explicit map size, use whatever exists */
3914 msize = env->me_mapsize;
3915 sizelo = msize & 0xffffffff;
3916 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3918 /* Windows won't create mappings for zero length files.
3919 * and won't map more than the file size.
3920 * Just set the maxsize right now.
3922 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3923 || !SetEndOfFile(env->me_fd)
3924 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3928 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3929 PAGE_READWRITE : PAGE_READONLY,
3930 sizehi, sizelo, NULL);
3933 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3934 FILE_MAP_WRITE : FILE_MAP_READ,
3936 rc = env->me_map ? 0 : ErrCode();
3941 int prot = PROT_READ;
3942 if (flags & MDB_WRITEMAP) {
3944 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3947 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3949 if (env->me_map == MAP_FAILED) {
3954 if (flags & MDB_NORDAHEAD) {
3955 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3957 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3959 #ifdef POSIX_MADV_RANDOM
3960 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3961 #endif /* POSIX_MADV_RANDOM */
3962 #endif /* MADV_RANDOM */
3966 /* Can happen because the address argument to mmap() is just a
3967 * hint. mmap() can pick another, e.g. if the range is in use.
3968 * The MAP_FIXED flag would prevent that, but then mmap could
3969 * instead unmap existing pages to make room for the new map.
3971 if (addr && env->me_map != addr)
3972 return EBUSY; /* TODO: Make a new MDB_* error code? */
3974 p = (MDB_page *)env->me_map;
3975 env->me_metas[0] = METADATA(p);
3976 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3982 mdb_env_set_mapsize(MDB_env *env, size_t size)
3984 /* If env is already open, caller is responsible for making
3985 * sure there are no active txns.
3993 meta = mdb_env_pick_meta(env);
3995 size = meta->mm_mapsize;
3997 /* Silently round up to minimum if the size is too small */
3998 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4002 munmap(env->me_map, env->me_mapsize);
4003 env->me_mapsize = size;
4004 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4005 rc = mdb_env_map(env, old);
4009 env->me_mapsize = size;
4011 env->me_maxpg = env->me_mapsize / env->me_psize;
4016 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4020 env->me_maxdbs = dbs + CORE_DBS;
4025 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4027 if (env->me_map || readers < 1)
4029 env->me_maxreaders = readers;
4034 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4036 if (!env || !readers)
4038 *readers = env->me_maxreaders;
4043 mdb_fsize(HANDLE fd, size_t *size)
4046 LARGE_INTEGER fsize;
4048 if (!GetFileSizeEx(fd, &fsize))
4051 *size = fsize.QuadPart;
4063 #ifdef BROKEN_FDATASYNC
4064 #include <sys/utsname.h>
4065 #include <sys/vfs.h>
4068 /** Further setup required for opening an LMDB environment
4071 mdb_env_open2(MDB_env *env)
4073 unsigned int flags = env->me_flags;
4074 int i, newenv = 0, rc;
4078 /* See if we should use QueryLimited */
4080 if ((rc & 0xff) > 5)
4081 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4083 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4086 #ifdef BROKEN_FDATASYNC
4087 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4088 * https://lkml.org/lkml/2012/9/3/83
4089 * Kernels after 3.6-rc6 are known good.
4090 * https://lkml.org/lkml/2012/9/10/556
4091 * See if the DB is on ext3/ext4, then check for new enough kernel
4092 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4097 fstatfs(env->me_fd, &st);
4098 while (st.f_type == 0xEF53) {
4102 if (uts.release[0] < '3') {
4103 if (!strncmp(uts.release, "2.6.32.", 7)) {
4104 i = atoi(uts.release+7);
4106 break; /* 2.6.32.60 and newer is OK */
4107 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4108 i = atoi(uts.release+7);
4110 break; /* 2.6.34.15 and newer is OK */
4112 } else if (uts.release[0] == '3') {
4113 i = atoi(uts.release+2);
4115 break; /* 3.6 and newer is OK */
4117 i = atoi(uts.release+4);
4119 break; /* 3.5.4 and newer is OK */
4120 } else if (i == 2) {
4121 i = atoi(uts.release+4);
4123 break; /* 3.2.30 and newer is OK */
4125 } else { /* 4.x and newer is OK */
4128 env->me_flags |= MDB_FSYNCONLY;
4134 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4137 DPUTS("new mdbenv");
4139 env->me_psize = env->me_os_psize;
4140 if (env->me_psize > MAX_PAGESIZE)
4141 env->me_psize = MAX_PAGESIZE;
4142 memset(&meta, 0, sizeof(meta));
4143 mdb_env_init_meta0(env, &meta);
4144 meta.mm_mapsize = DEFAULT_MAPSIZE;
4146 env->me_psize = meta.mm_psize;
4149 /* Was a mapsize configured? */
4150 if (!env->me_mapsize) {
4151 env->me_mapsize = meta.mm_mapsize;
4154 /* Make sure mapsize >= committed data size. Even when using
4155 * mm_mapsize, which could be broken in old files (ITS#7789).
4157 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4158 if (env->me_mapsize < minsize)
4159 env->me_mapsize = minsize;
4161 meta.mm_mapsize = env->me_mapsize;
4163 if (newenv && !(flags & MDB_FIXEDMAP)) {
4164 /* mdb_env_map() may grow the datafile. Write the metapages
4165 * first, so the file will be valid if initialization fails.
4166 * Except with FIXEDMAP, since we do not yet know mm_address.
4167 * We could fill in mm_address later, but then a different
4168 * program might end up doing that - one with a memory layout
4169 * and map address which does not suit the main program.
4171 rc = mdb_env_init_meta(env, &meta);
4177 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4182 if (flags & MDB_FIXEDMAP)
4183 meta.mm_address = env->me_map;
4184 i = mdb_env_init_meta(env, &meta);
4185 if (i != MDB_SUCCESS) {
4190 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4191 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4193 #if !(MDB_MAXKEYSIZE)
4194 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4196 env->me_maxpg = env->me_mapsize / env->me_psize;
4200 MDB_meta *meta = mdb_env_pick_meta(env);
4201 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4203 DPRINTF(("opened database version %u, pagesize %u",
4204 meta->mm_version, env->me_psize));
4205 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4206 DPRINTF(("depth: %u", db->md_depth));
4207 DPRINTF(("entries: %"Z"u", db->md_entries));
4208 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4209 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4210 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4211 DPRINTF(("root: %"Z"u", db->md_root));
4219 /** Release a reader thread's slot in the reader lock table.
4220 * This function is called automatically when a thread exits.
4221 * @param[in] ptr This points to the slot in the reader lock table.
4224 mdb_env_reader_dest(void *ptr)
4226 MDB_reader *reader = ptr;
4232 /** Junk for arranging thread-specific callbacks on Windows. This is
4233 * necessarily platform and compiler-specific. Windows supports up
4234 * to 1088 keys. Let's assume nobody opens more than 64 environments
4235 * in a single process, for now. They can override this if needed.
4237 #ifndef MAX_TLS_KEYS
4238 #define MAX_TLS_KEYS 64
4240 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4241 static int mdb_tls_nkeys;
4243 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4247 case DLL_PROCESS_ATTACH: break;
4248 case DLL_THREAD_ATTACH: break;
4249 case DLL_THREAD_DETACH:
4250 for (i=0; i<mdb_tls_nkeys; i++) {
4251 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4253 mdb_env_reader_dest(r);
4257 case DLL_PROCESS_DETACH: break;
4262 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4264 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4268 /* Force some symbol references.
4269 * _tls_used forces the linker to create the TLS directory if not already done
4270 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4272 #pragma comment(linker, "/INCLUDE:_tls_used")
4273 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4274 #pragma const_seg(".CRT$XLB")
4275 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4276 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4279 #pragma comment(linker, "/INCLUDE:__tls_used")
4280 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4281 #pragma data_seg(".CRT$XLB")
4282 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4284 #endif /* WIN 32/64 */
4285 #endif /* !__GNUC__ */
4288 /** Downgrade the exclusive lock on the region back to shared */
4290 mdb_env_share_locks(MDB_env *env, int *excl)
4293 MDB_meta *meta = mdb_env_pick_meta(env);
4295 env->me_txns->mti_txnid = meta->mm_txnid;
4300 /* First acquire a shared lock. The Unlock will
4301 * then release the existing exclusive lock.
4303 memset(&ov, 0, sizeof(ov));
4304 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4307 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4313 struct flock lock_info;
4314 /* The shared lock replaces the existing lock */
4315 memset((void *)&lock_info, 0, sizeof(lock_info));
4316 lock_info.l_type = F_RDLCK;
4317 lock_info.l_whence = SEEK_SET;
4318 lock_info.l_start = 0;
4319 lock_info.l_len = 1;
4320 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4321 (rc = ErrCode()) == EINTR) ;
4322 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4329 /** Try to get exclusive lock, otherwise shared.
4330 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4333 mdb_env_excl_lock(MDB_env *env, int *excl)
4337 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4341 memset(&ov, 0, sizeof(ov));
4342 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4349 struct flock lock_info;
4350 memset((void *)&lock_info, 0, sizeof(lock_info));
4351 lock_info.l_type = F_WRLCK;
4352 lock_info.l_whence = SEEK_SET;
4353 lock_info.l_start = 0;
4354 lock_info.l_len = 1;
4355 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4356 (rc = ErrCode()) == EINTR) ;
4360 # ifndef MDB_USE_POSIX_MUTEX
4361 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4364 lock_info.l_type = F_RDLCK;
4365 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4366 (rc = ErrCode()) == EINTR) ;
4376 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4378 * @(#) $Revision: 5.1 $
4379 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4380 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4382 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4386 * Please do not copyright this code. This code is in the public domain.
4388 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4389 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4390 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4391 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4392 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4393 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4394 * PERFORMANCE OF THIS SOFTWARE.
4397 * chongo <Landon Curt Noll> /\oo/\
4398 * http://www.isthe.com/chongo/
4400 * Share and Enjoy! :-)
4403 typedef unsigned long long mdb_hash_t;
4404 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4406 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4407 * @param[in] val value to hash
4408 * @param[in] hval initial value for hash
4409 * @return 64 bit hash
4411 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4412 * hval arg on the first call.
4415 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4417 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4418 unsigned char *end = s + val->mv_size;
4420 * FNV-1a hash each octet of the string
4423 /* xor the bottom with the current octet */
4424 hval ^= (mdb_hash_t)*s++;
4426 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4427 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4428 (hval << 7) + (hval << 8) + (hval << 40);
4430 /* return our new hash value */
4434 /** Hash the string and output the encoded hash.
4435 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4436 * very short name limits. We don't care about the encoding being reversible,
4437 * we just want to preserve as many bits of the input as possible in a
4438 * small printable string.
4439 * @param[in] str string to hash
4440 * @param[out] encbuf an array of 11 chars to hold the hash
4442 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4445 mdb_pack85(unsigned long l, char *out)
4449 for (i=0; i<5; i++) {
4450 *out++ = mdb_a85[l % 85];
4456 mdb_hash_enc(MDB_val *val, char *encbuf)
4458 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4460 mdb_pack85(h, encbuf);
4461 mdb_pack85(h>>32, encbuf+5);
4466 /** Open and/or initialize the lock region for the environment.
4467 * @param[in] env The LMDB environment.
4468 * @param[in] lpath The pathname of the file used for the lock region.
4469 * @param[in] mode The Unix permissions for the file, if we create it.
4470 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4471 * @return 0 on success, non-zero on failure.
4474 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4477 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4479 # define MDB_ERRCODE_ROFS EROFS
4480 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4481 # define MDB_CLOEXEC O_CLOEXEC
4484 # define MDB_CLOEXEC 0
4492 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4495 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4496 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4497 FILE_ATTRIBUTE_NORMAL, NULL);
4500 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4502 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4504 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4509 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4510 /* Lose record locks when exec*() */
4511 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4512 fcntl(env->me_lfd, F_SETFD, fdflags);
4515 if (!(env->me_flags & MDB_NOTLS)) {
4516 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4519 env->me_flags |= MDB_ENV_TXKEY;
4521 /* Windows TLS callbacks need help finding their TLS info. */
4522 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4526 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4530 /* Try to get exclusive lock. If we succeed, then
4531 * nobody is using the lock region and we should initialize it.
4533 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4536 size = GetFileSize(env->me_lfd, NULL);
4538 size = lseek(env->me_lfd, 0, SEEK_END);
4539 if (size == -1) goto fail_errno;
4541 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4542 if (size < rsize && *excl > 0) {
4544 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4545 || !SetEndOfFile(env->me_lfd))
4548 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4552 size = rsize - sizeof(MDB_txninfo);
4553 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4558 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4560 if (!mh) goto fail_errno;
4561 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4563 if (!env->me_txns) goto fail_errno;
4565 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4567 if (m == MAP_FAILED) goto fail_errno;
4573 BY_HANDLE_FILE_INFORMATION stbuf;
4582 if (!mdb_sec_inited) {
4583 InitializeSecurityDescriptor(&mdb_null_sd,
4584 SECURITY_DESCRIPTOR_REVISION);
4585 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4586 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4587 mdb_all_sa.bInheritHandle = FALSE;
4588 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4591 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4592 idbuf.volume = stbuf.dwVolumeSerialNumber;
4593 idbuf.nhigh = stbuf.nFileIndexHigh;
4594 idbuf.nlow = stbuf.nFileIndexLow;
4595 val.mv_data = &idbuf;
4596 val.mv_size = sizeof(idbuf);
4597 mdb_hash_enc(&val, encbuf);
4598 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4599 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4600 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4601 if (!env->me_rmutex) goto fail_errno;
4602 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4603 if (!env->me_wmutex) goto fail_errno;
4604 #elif defined(MDB_USE_POSIX_SEM)
4613 #if defined(__NetBSD__)
4614 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4616 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4617 idbuf.dev = stbuf.st_dev;
4618 idbuf.ino = stbuf.st_ino;
4619 val.mv_data = &idbuf;
4620 val.mv_size = sizeof(idbuf);
4621 mdb_hash_enc(&val, encbuf);
4622 #ifdef MDB_SHORT_SEMNAMES
4623 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4625 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4626 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4627 /* Clean up after a previous run, if needed: Try to
4628 * remove both semaphores before doing anything else.
4630 sem_unlink(env->me_txns->mti_rmname);
4631 sem_unlink(env->me_txns->mti_wmname);
4632 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4633 O_CREAT|O_EXCL, mode, 1);
4634 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4635 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4636 O_CREAT|O_EXCL, mode, 1);
4637 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4638 #else /* MDB_USE_POSIX_MUTEX: */
4639 pthread_mutexattr_t mattr;
4641 /* Solaris needs this before initing a robust mutex. Otherwise
4642 * it may skip the init and return EBUSY "seems someone already
4643 * inited" or EINVAL "it was inited differently".
4645 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4646 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4648 if ((rc = pthread_mutexattr_init(&mattr)))
4651 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4652 #ifdef MDB_ROBUST_SUPPORTED
4653 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4655 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4656 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4657 pthread_mutexattr_destroy(&mattr);
4660 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4662 env->me_txns->mti_magic = MDB_MAGIC;
4663 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4664 env->me_txns->mti_txnid = 0;
4665 env->me_txns->mti_numreaders = 0;
4668 if (env->me_txns->mti_magic != MDB_MAGIC) {
4669 DPUTS("lock region has invalid magic");
4673 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4674 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4675 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4676 rc = MDB_VERSION_MISMATCH;
4680 if (rc && rc != EACCES && rc != EAGAIN) {
4684 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4685 if (!env->me_rmutex) goto fail_errno;
4686 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4687 if (!env->me_wmutex) goto fail_errno;
4688 #elif defined(MDB_USE_POSIX_SEM)
4689 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4690 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4691 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4692 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4703 /** The name of the lock file in the DB environment */
4704 #define LOCKNAME "/lock.mdb"
4705 /** The name of the data file in the DB environment */
4706 #define DATANAME "/data.mdb"
4707 /** The suffix of the lock file when no subdir is used */
4708 #define LOCKSUFF "-lock"
4709 /** Only a subset of the @ref mdb_env flags can be changed
4710 * at runtime. Changing other flags requires closing the
4711 * environment and re-opening it with the new flags.
4713 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4714 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4715 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4717 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4718 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4722 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4724 int oflags, rc, len, excl = -1;
4725 char *lpath, *dpath;
4730 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4734 if (flags & MDB_NOSUBDIR) {
4735 rc = len + sizeof(LOCKSUFF) + len + 1;
4737 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4742 if (flags & MDB_NOSUBDIR) {
4743 dpath = lpath + len + sizeof(LOCKSUFF);
4744 sprintf(lpath, "%s" LOCKSUFF, path);
4745 strcpy(dpath, path);
4747 dpath = lpath + len + sizeof(LOCKNAME);
4748 sprintf(lpath, "%s" LOCKNAME, path);
4749 sprintf(dpath, "%s" DATANAME, path);
4753 flags |= env->me_flags;
4754 if (flags & MDB_RDONLY) {
4755 /* silently ignore WRITEMAP when we're only getting read access */
4756 flags &= ~MDB_WRITEMAP;
4758 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4759 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4762 env->me_flags = flags |= MDB_ENV_ACTIVE;
4766 env->me_path = strdup(path);
4767 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4768 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4769 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4770 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4774 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4776 /* For RDONLY, get lockfile after we know datafile exists */
4777 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4778 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4784 if (F_ISSET(flags, MDB_RDONLY)) {
4785 oflags = GENERIC_READ;
4786 len = OPEN_EXISTING;
4788 oflags = GENERIC_READ|GENERIC_WRITE;
4791 mode = FILE_ATTRIBUTE_NORMAL;
4792 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4795 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4796 NULL, len, mode, NULL);
4799 if (F_ISSET(flags, MDB_RDONLY))
4802 oflags = O_RDWR | O_CREAT;
4804 env->me_fd = open(dpath, oflags, mode);
4806 if (env->me_fd == INVALID_HANDLE_VALUE) {
4811 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4812 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4817 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4818 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4819 env->me_mfd = env->me_fd;
4821 /* Synchronous fd for meta writes. Needed even with
4822 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4825 len = OPEN_EXISTING;
4826 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4829 env->me_mfd = CreateFileW(wpath, oflags,
4830 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4831 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4835 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4837 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4842 DPRINTF(("opened dbenv %p", (void *) env));
4844 rc = mdb_env_share_locks(env, &excl);
4848 if (!(flags & MDB_RDONLY)) {
4850 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4851 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4852 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4853 (txn = calloc(1, size)))
4855 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4856 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4857 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4858 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4860 txn->mt_dbxs = env->me_dbxs;
4861 txn->mt_flags = MDB_TXN_FINISHED;
4871 mdb_env_close0(env, excl);
4877 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4879 mdb_env_close0(MDB_env *env, int excl)
4883 if (!(env->me_flags & MDB_ENV_ACTIVE))
4886 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4888 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4889 free(env->me_dbxs[i].md_name.mv_data);
4894 free(env->me_dbiseqs);
4895 free(env->me_dbflags);
4897 free(env->me_dirty_list);
4899 mdb_midl_free(env->me_free_pgs);
4901 if (env->me_flags & MDB_ENV_TXKEY) {
4902 pthread_key_delete(env->me_txkey);
4904 /* Delete our key from the global list */
4905 for (i=0; i<mdb_tls_nkeys; i++)
4906 if (mdb_tls_keys[i] == env->me_txkey) {
4907 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4915 munmap(env->me_map, env->me_mapsize);
4917 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4918 (void) close(env->me_mfd);
4919 if (env->me_fd != INVALID_HANDLE_VALUE)
4920 (void) close(env->me_fd);
4922 MDB_PID_T pid = env->me_pid;
4923 /* Clearing readers is done in this function because
4924 * me_txkey with its destructor must be disabled first.
4926 * We skip the the reader mutex, so we touch only
4927 * data owned by this process (me_close_readers and
4928 * our readers), and clear each reader atomically.
4930 for (i = env->me_close_readers; --i >= 0; )
4931 if (env->me_txns->mti_readers[i].mr_pid == pid)
4932 env->me_txns->mti_readers[i].mr_pid = 0;
4934 if (env->me_rmutex) {
4935 CloseHandle(env->me_rmutex);
4936 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4938 /* Windows automatically destroys the mutexes when
4939 * the last handle closes.
4941 #elif defined(MDB_USE_POSIX_SEM)
4942 if (env->me_rmutex != SEM_FAILED) {
4943 sem_close(env->me_rmutex);
4944 if (env->me_wmutex != SEM_FAILED)
4945 sem_close(env->me_wmutex);
4946 /* If we have the filelock: If we are the
4947 * only remaining user, clean up semaphores.
4950 mdb_env_excl_lock(env, &excl);
4952 sem_unlink(env->me_txns->mti_rmname);
4953 sem_unlink(env->me_txns->mti_wmname);
4957 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4959 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4962 /* Unlock the lockfile. Windows would have unlocked it
4963 * after closing anyway, but not necessarily at once.
4965 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4968 (void) close(env->me_lfd);
4971 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4975 mdb_env_close(MDB_env *env)
4982 VGMEMP_DESTROY(env);
4983 while ((dp = env->me_dpages) != NULL) {
4984 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4985 env->me_dpages = dp->mp_next;
4989 mdb_env_close0(env, 0);
4993 /** Compare two items pointing at aligned size_t's */
4995 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4997 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4998 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5001 /** Compare two items pointing at aligned unsigned int's.
5003 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5004 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5007 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5009 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5010 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5013 /** Compare two items pointing at unsigned ints of unknown alignment.
5014 * Nodes and keys are guaranteed to be 2-byte aligned.
5017 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5019 #if BYTE_ORDER == LITTLE_ENDIAN
5020 unsigned short *u, *c;
5023 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5024 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5027 } while(!x && u > (unsigned short *)a->mv_data);
5030 unsigned short *u, *c, *end;
5033 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5034 u = (unsigned short *)a->mv_data;
5035 c = (unsigned short *)b->mv_data;
5038 } while(!x && u < end);
5043 /** Compare two items lexically */
5045 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5052 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5058 diff = memcmp(a->mv_data, b->mv_data, len);
5059 return diff ? diff : len_diff<0 ? -1 : len_diff;
5062 /** Compare two items in reverse byte order */
5064 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5066 const unsigned char *p1, *p2, *p1_lim;
5070 p1_lim = (const unsigned char *)a->mv_data;
5071 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5072 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5074 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5080 while (p1 > p1_lim) {
5081 diff = *--p1 - *--p2;
5085 return len_diff<0 ? -1 : len_diff;
5088 /** Search for key within a page, using binary search.
5089 * Returns the smallest entry larger or equal to the key.
5090 * If exactp is non-null, stores whether the found entry was an exact match
5091 * in *exactp (1 or 0).
5092 * Updates the cursor index with the index of the found entry.
5093 * If no entry larger or equal to the key is found, returns NULL.
5096 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5098 unsigned int i = 0, nkeys;
5101 MDB_page *mp = mc->mc_pg[mc->mc_top];
5102 MDB_node *node = NULL;
5107 nkeys = NUMKEYS(mp);
5109 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5110 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5113 low = IS_LEAF(mp) ? 0 : 1;
5115 cmp = mc->mc_dbx->md_cmp;
5117 /* Branch pages have no data, so if using integer keys,
5118 * alignment is guaranteed. Use faster mdb_cmp_int.
5120 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5121 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5128 nodekey.mv_size = mc->mc_db->md_pad;
5129 node = NODEPTR(mp, 0); /* fake */
5130 while (low <= high) {
5131 i = (low + high) >> 1;
5132 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5133 rc = cmp(key, &nodekey);
5134 DPRINTF(("found leaf index %u [%s], rc = %i",
5135 i, DKEY(&nodekey), rc));
5144 while (low <= high) {
5145 i = (low + high) >> 1;
5147 node = NODEPTR(mp, i);
5148 nodekey.mv_size = NODEKSZ(node);
5149 nodekey.mv_data = NODEKEY(node);
5151 rc = cmp(key, &nodekey);
5154 DPRINTF(("found leaf index %u [%s], rc = %i",
5155 i, DKEY(&nodekey), rc));
5157 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5158 i, DKEY(&nodekey), NODEPGNO(node), rc));
5169 if (rc > 0) { /* Found entry is less than the key. */
5170 i++; /* Skip to get the smallest entry larger than key. */
5172 node = NODEPTR(mp, i);
5175 *exactp = (rc == 0 && nkeys > 0);
5176 /* store the key index */
5177 mc->mc_ki[mc->mc_top] = i;
5179 /* There is no entry larger or equal to the key. */
5182 /* nodeptr is fake for LEAF2 */
5188 mdb_cursor_adjust(MDB_cursor *mc, func)
5192 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5193 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5200 /** Pop a page off the top of the cursor's stack. */
5202 mdb_cursor_pop(MDB_cursor *mc)
5205 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5206 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5212 mc->mc_flags &= ~C_INITIALIZED;
5217 /** Push a page onto the top of the cursor's stack. */
5219 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5221 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5222 DDBI(mc), (void *) mc));
5224 if (mc->mc_snum >= CURSOR_STACK) {
5225 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5226 return MDB_CURSOR_FULL;
5229 mc->mc_top = mc->mc_snum++;
5230 mc->mc_pg[mc->mc_top] = mp;
5231 mc->mc_ki[mc->mc_top] = 0;
5236 /** Find the address of the page corresponding to a given page number.
5237 * @param[in] mc the cursor accessing the page.
5238 * @param[in] pgno the page number for the page to retrieve.
5239 * @param[out] ret address of a pointer where the page's address will be stored.
5240 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5241 * @return 0 on success, non-zero on failure.
5244 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5246 MDB_txn *txn = mc->mc_txn;
5247 MDB_env *env = txn->mt_env;
5251 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5255 MDB_ID2L dl = tx2->mt_u.dirty_list;
5257 /* Spilled pages were dirtied in this txn and flushed
5258 * because the dirty list got full. Bring this page
5259 * back in from the map (but don't unspill it here,
5260 * leave that unless page_touch happens again).
5262 if (tx2->mt_spill_pgs) {
5263 MDB_ID pn = pgno << 1;
5264 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5265 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5266 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5271 unsigned x = mdb_mid2l_search(dl, pgno);
5272 if (x <= dl[0].mid && dl[x].mid == pgno) {
5278 } while ((tx2 = tx2->mt_parent) != NULL);
5281 if (pgno < txn->mt_next_pgno) {
5283 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5285 DPRINTF(("page %"Z"u not found", pgno));
5286 txn->mt_flags |= MDB_TXN_ERROR;
5287 return MDB_PAGE_NOTFOUND;
5297 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5298 * The cursor is at the root page, set up the rest of it.
5301 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5303 MDB_page *mp = mc->mc_pg[mc->mc_top];
5307 while (IS_BRANCH(mp)) {
5311 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5312 /* Don't assert on branch pages in the FreeDB. We can get here
5313 * while in the process of rebalancing a FreeDB branch page; we must
5314 * let that proceed. ITS#8336
5316 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5317 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5319 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5321 if (flags & MDB_PS_LAST)
5322 i = NUMKEYS(mp) - 1;
5325 node = mdb_node_search(mc, key, &exact);
5327 i = NUMKEYS(mp) - 1;
5329 i = mc->mc_ki[mc->mc_top];
5331 mdb_cassert(mc, i > 0);
5335 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5338 mdb_cassert(mc, i < NUMKEYS(mp));
5339 node = NODEPTR(mp, i);
5341 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5344 mc->mc_ki[mc->mc_top] = i;
5345 if ((rc = mdb_cursor_push(mc, mp)))
5348 if (flags & MDB_PS_MODIFY) {
5349 if ((rc = mdb_page_touch(mc)) != 0)
5351 mp = mc->mc_pg[mc->mc_top];
5356 DPRINTF(("internal error, index points to a %02X page!?",
5358 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5359 return MDB_CORRUPTED;
5362 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5363 key ? DKEY(key) : "null"));
5364 mc->mc_flags |= C_INITIALIZED;
5365 mc->mc_flags &= ~C_EOF;
5370 /** Search for the lowest key under the current branch page.
5371 * This just bypasses a NUMKEYS check in the current page
5372 * before calling mdb_page_search_root(), because the callers
5373 * are all in situations where the current page is known to
5377 mdb_page_search_lowest(MDB_cursor *mc)
5379 MDB_page *mp = mc->mc_pg[mc->mc_top];
5380 MDB_node *node = NODEPTR(mp, 0);
5383 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5386 mc->mc_ki[mc->mc_top] = 0;
5387 if ((rc = mdb_cursor_push(mc, mp)))
5389 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5392 /** Search for the page a given key should be in.
5393 * Push it and its parent pages on the cursor stack.
5394 * @param[in,out] mc the cursor for this operation.
5395 * @param[in] key the key to search for, or NULL for first/last page.
5396 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5397 * are touched (updated with new page numbers).
5398 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5399 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5400 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5401 * @return 0 on success, non-zero on failure.
5404 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5409 /* Make sure the txn is still viable, then find the root from
5410 * the txn's db table and set it as the root of the cursor's stack.
5412 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5413 DPUTS("transaction may not be used now");
5416 /* Make sure we're using an up-to-date root */
5417 if (*mc->mc_dbflag & DB_STALE) {
5419 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5421 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5422 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5429 MDB_node *leaf = mdb_node_search(&mc2,
5430 &mc->mc_dbx->md_name, &exact);
5432 return MDB_NOTFOUND;
5433 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5434 return MDB_INCOMPATIBLE; /* not a named DB */
5435 rc = mdb_node_read(&mc2, leaf, &data);
5438 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5440 /* The txn may not know this DBI, or another process may
5441 * have dropped and recreated the DB with other flags.
5443 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5444 return MDB_INCOMPATIBLE;
5445 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5447 *mc->mc_dbflag &= ~DB_STALE;
5449 root = mc->mc_db->md_root;
5451 if (root == P_INVALID) { /* Tree is empty. */
5452 DPUTS("tree is empty");
5453 return MDB_NOTFOUND;
5457 mdb_cassert(mc, root > 1);
5458 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5459 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5465 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5466 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5468 if (flags & MDB_PS_MODIFY) {
5469 if ((rc = mdb_page_touch(mc)))
5473 if (flags & MDB_PS_ROOTONLY)
5476 return mdb_page_search_root(mc, key, flags);
5480 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5482 MDB_txn *txn = mc->mc_txn;
5483 pgno_t pg = mp->mp_pgno;
5484 unsigned x = 0, ovpages = mp->mp_pages;
5485 MDB_env *env = txn->mt_env;
5486 MDB_IDL sl = txn->mt_spill_pgs;
5487 MDB_ID pn = pg << 1;
5490 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5491 /* If the page is dirty or on the spill list we just acquired it,
5492 * so we should give it back to our current free list, if any.
5493 * Otherwise put it onto the list of pages we freed in this txn.
5495 * Won't create me_pghead: me_pglast must be inited along with it.
5496 * Unsupported in nested txns: They would need to hide the page
5497 * range in ancestor txns' dirty and spilled lists.
5499 if (env->me_pghead &&
5501 ((mp->mp_flags & P_DIRTY) ||
5502 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5506 MDB_ID2 *dl, ix, iy;
5507 rc = mdb_midl_need(&env->me_pghead, ovpages);
5510 if (!(mp->mp_flags & P_DIRTY)) {
5511 /* This page is no longer spilled */
5518 /* Remove from dirty list */
5519 dl = txn->mt_u.dirty_list;
5521 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5527 mdb_cassert(mc, x > 1);
5529 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5530 txn->mt_flags |= MDB_TXN_ERROR;
5531 return MDB_CORRUPTED;
5534 txn->mt_dirty_room++;
5535 if (!(env->me_flags & MDB_WRITEMAP))
5536 mdb_dpage_free(env, mp);
5538 /* Insert in me_pghead */
5539 mop = env->me_pghead;
5540 j = mop[0] + ovpages;
5541 for (i = mop[0]; i && mop[i] < pg; i--)
5547 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5551 mc->mc_db->md_overflow_pages -= ovpages;
5555 /** Return the data associated with a given node.
5556 * @param[in] mc The cursor for this operation.
5557 * @param[in] leaf The node being read.
5558 * @param[out] data Updated to point to the node's data.
5559 * @return 0 on success, non-zero on failure.
5562 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5564 MDB_page *omp; /* overflow page */
5568 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5569 data->mv_size = NODEDSZ(leaf);
5570 data->mv_data = NODEDATA(leaf);
5574 /* Read overflow data.
5576 data->mv_size = NODEDSZ(leaf);
5577 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5578 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5579 DPRINTF(("read overflow page %"Z"u failed", pgno));
5582 data->mv_data = METADATA(omp);
5588 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5589 MDB_val *key, MDB_val *data)
5596 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5598 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5601 if (txn->mt_flags & MDB_TXN_BLOCKED)
5604 mdb_cursor_init(&mc, txn, dbi, &mx);
5605 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5608 /** Find a sibling for a page.
5609 * Replaces the page at the top of the cursor's stack with the
5610 * specified sibling, if one exists.
5611 * @param[in] mc The cursor for this operation.
5612 * @param[in] move_right Non-zero if the right sibling is requested,
5613 * otherwise the left sibling.
5614 * @return 0 on success, non-zero on failure.
5617 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5623 if (mc->mc_snum < 2) {
5624 return MDB_NOTFOUND; /* root has no siblings */
5628 DPRINTF(("parent page is page %"Z"u, index %u",
5629 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5631 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5632 : (mc->mc_ki[mc->mc_top] == 0)) {
5633 DPRINTF(("no more keys left, moving to %s sibling",
5634 move_right ? "right" : "left"));
5635 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5636 /* undo cursor_pop before returning */
5643 mc->mc_ki[mc->mc_top]++;
5645 mc->mc_ki[mc->mc_top]--;
5646 DPRINTF(("just moving to %s index key %u",
5647 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5649 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5651 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5652 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5653 /* mc will be inconsistent if caller does mc_snum++ as above */
5654 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5658 mdb_cursor_push(mc, mp);
5660 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5665 /** Move the cursor to the next data item. */
5667 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5673 if ((mc->mc_flags & C_EOF) ||
5674 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
5675 return MDB_NOTFOUND;
5677 if (!(mc->mc_flags & C_INITIALIZED))
5678 return mdb_cursor_first(mc, key, data);
5680 mp = mc->mc_pg[mc->mc_top];
5682 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5683 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5684 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5685 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5686 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5687 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5688 if (rc == MDB_SUCCESS)
5689 MDB_GET_KEY(leaf, key);
5694 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5695 if (op == MDB_NEXT_DUP)
5696 return MDB_NOTFOUND;
5700 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5701 mdb_dbg_pgno(mp), (void *) mc));
5702 if (mc->mc_flags & C_DEL) {
5703 mc->mc_flags ^= C_DEL;
5707 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5708 DPUTS("=====> move to next sibling page");
5709 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5710 mc->mc_flags |= C_EOF;
5713 mp = mc->mc_pg[mc->mc_top];
5714 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5716 mc->mc_ki[mc->mc_top]++;
5719 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5720 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5723 key->mv_size = mc->mc_db->md_pad;
5724 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5728 mdb_cassert(mc, IS_LEAF(mp));
5729 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5731 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5732 mdb_xcursor_init1(mc, leaf);
5735 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5738 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5739 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5740 if (rc != MDB_SUCCESS)
5745 MDB_GET_KEY(leaf, key);
5749 /** Move the cursor to the previous data item. */
5751 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5757 if (!(mc->mc_flags & C_INITIALIZED)) {
5758 rc = mdb_cursor_last(mc, key, data);
5761 mc->mc_ki[mc->mc_top]++;
5764 mp = mc->mc_pg[mc->mc_top];
5766 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5767 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5768 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5769 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5770 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5771 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5772 if (rc == MDB_SUCCESS) {
5773 MDB_GET_KEY(leaf, key);
5774 mc->mc_flags &= ~C_EOF;
5780 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5781 if (op == MDB_PREV_DUP)
5782 return MDB_NOTFOUND;
5786 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5787 mdb_dbg_pgno(mp), (void *) mc));
5789 mc->mc_flags &= ~(C_EOF|C_DEL);
5791 if (mc->mc_ki[mc->mc_top] == 0) {
5792 DPUTS("=====> move to prev sibling page");
5793 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5796 mp = mc->mc_pg[mc->mc_top];
5797 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5798 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5800 mc->mc_ki[mc->mc_top]--;
5802 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5803 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5806 key->mv_size = mc->mc_db->md_pad;
5807 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5811 mdb_cassert(mc, IS_LEAF(mp));
5812 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5814 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5815 mdb_xcursor_init1(mc, leaf);
5818 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5821 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5822 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5823 if (rc != MDB_SUCCESS)
5828 MDB_GET_KEY(leaf, key);
5832 /** Set the cursor on a specific data item. */
5834 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5835 MDB_cursor_op op, int *exactp)
5839 MDB_node *leaf = NULL;
5842 if (key->mv_size == 0)
5843 return MDB_BAD_VALSIZE;
5846 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5848 /* See if we're already on the right page */
5849 if (mc->mc_flags & C_INITIALIZED) {
5852 mp = mc->mc_pg[mc->mc_top];
5854 mc->mc_ki[mc->mc_top] = 0;
5855 return MDB_NOTFOUND;
5857 if (mp->mp_flags & P_LEAF2) {
5858 nodekey.mv_size = mc->mc_db->md_pad;
5859 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5861 leaf = NODEPTR(mp, 0);
5862 MDB_GET_KEY2(leaf, nodekey);
5864 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5866 /* Probably happens rarely, but first node on the page
5867 * was the one we wanted.
5869 mc->mc_ki[mc->mc_top] = 0;
5876 unsigned int nkeys = NUMKEYS(mp);
5878 if (mp->mp_flags & P_LEAF2) {
5879 nodekey.mv_data = LEAF2KEY(mp,
5880 nkeys-1, nodekey.mv_size);
5882 leaf = NODEPTR(mp, nkeys-1);
5883 MDB_GET_KEY2(leaf, nodekey);
5885 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5887 /* last node was the one we wanted */
5888 mc->mc_ki[mc->mc_top] = nkeys-1;
5894 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5895 /* This is definitely the right page, skip search_page */
5896 if (mp->mp_flags & P_LEAF2) {
5897 nodekey.mv_data = LEAF2KEY(mp,
5898 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5900 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5901 MDB_GET_KEY2(leaf, nodekey);
5903 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5905 /* current node was the one we wanted */
5915 /* If any parents have right-sibs, search.
5916 * Otherwise, there's nothing further.
5918 for (i=0; i<mc->mc_top; i++)
5920 NUMKEYS(mc->mc_pg[i])-1)
5922 if (i == mc->mc_top) {
5923 /* There are no other pages */
5924 mc->mc_ki[mc->mc_top] = nkeys;
5925 return MDB_NOTFOUND;
5929 /* There are no other pages */
5930 mc->mc_ki[mc->mc_top] = 0;
5931 if (op == MDB_SET_RANGE && !exactp) {
5935 return MDB_NOTFOUND;
5941 rc = mdb_page_search(mc, key, 0);
5942 if (rc != MDB_SUCCESS)
5945 mp = mc->mc_pg[mc->mc_top];
5946 mdb_cassert(mc, IS_LEAF(mp));
5949 leaf = mdb_node_search(mc, key, exactp);
5950 if (exactp != NULL && !*exactp) {
5951 /* MDB_SET specified and not an exact match. */
5952 return MDB_NOTFOUND;
5956 DPUTS("===> inexact leaf not found, goto sibling");
5957 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5958 mc->mc_flags |= C_EOF;
5959 return rc; /* no entries matched */
5961 mp = mc->mc_pg[mc->mc_top];
5962 mdb_cassert(mc, IS_LEAF(mp));
5963 leaf = NODEPTR(mp, 0);
5967 mc->mc_flags |= C_INITIALIZED;
5968 mc->mc_flags &= ~C_EOF;
5971 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5972 key->mv_size = mc->mc_db->md_pad;
5973 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5978 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5979 mdb_xcursor_init1(mc, leaf);
5982 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5983 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5984 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5987 if (op == MDB_GET_BOTH) {
5993 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5994 if (rc != MDB_SUCCESS)
5997 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6000 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6002 dcmp = mc->mc_dbx->md_dcmp;
6003 #if UINT_MAX < SIZE_MAX
6004 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6005 dcmp = mdb_cmp_clong;
6007 rc = dcmp(data, &olddata);
6009 if (op == MDB_GET_BOTH || rc > 0)
6010 return MDB_NOTFOUND;
6017 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6018 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6023 /* The key already matches in all other cases */
6024 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6025 MDB_GET_KEY(leaf, key);
6026 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6031 /** Move the cursor to the first item in the database. */
6033 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6039 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6041 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6042 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6043 if (rc != MDB_SUCCESS)
6046 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6048 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6049 mc->mc_flags |= C_INITIALIZED;
6050 mc->mc_flags &= ~C_EOF;
6052 mc->mc_ki[mc->mc_top] = 0;
6054 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6055 key->mv_size = mc->mc_db->md_pad;
6056 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6061 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6062 mdb_xcursor_init1(mc, leaf);
6063 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6067 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6071 MDB_GET_KEY(leaf, key);
6075 /** Move the cursor to the last item in the database. */
6077 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6083 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6085 if (!(mc->mc_flags & C_EOF)) {
6087 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6088 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6089 if (rc != MDB_SUCCESS)
6092 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6095 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6096 mc->mc_flags |= C_INITIALIZED|C_EOF;
6097 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6099 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6100 key->mv_size = mc->mc_db->md_pad;
6101 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6106 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6107 mdb_xcursor_init1(mc, leaf);
6108 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6112 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6117 MDB_GET_KEY(leaf, key);
6122 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6127 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6132 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6136 case MDB_GET_CURRENT:
6137 if (!(mc->mc_flags & C_INITIALIZED)) {
6140 MDB_page *mp = mc->mc_pg[mc->mc_top];
6141 int nkeys = NUMKEYS(mp);
6142 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6143 mc->mc_ki[mc->mc_top] = nkeys;
6149 key->mv_size = mc->mc_db->md_pad;
6150 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6152 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6153 MDB_GET_KEY(leaf, key);
6155 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6156 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6158 rc = mdb_node_read(mc, leaf, data);
6165 case MDB_GET_BOTH_RANGE:
6170 if (mc->mc_xcursor == NULL) {
6171 rc = MDB_INCOMPATIBLE;
6181 rc = mdb_cursor_set(mc, key, data, op,
6182 op == MDB_SET_RANGE ? NULL : &exact);
6185 case MDB_GET_MULTIPLE:
6186 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6190 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6191 rc = MDB_INCOMPATIBLE;
6195 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6196 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6199 case MDB_NEXT_MULTIPLE:
6204 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6205 rc = MDB_INCOMPATIBLE;
6208 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6209 if (rc == MDB_SUCCESS) {
6210 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6213 mx = &mc->mc_xcursor->mx_cursor;
6214 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6216 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6217 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6223 case MDB_PREV_MULTIPLE:
6228 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6229 rc = MDB_INCOMPATIBLE;
6232 if (!(mc->mc_flags & C_INITIALIZED))
6233 rc = mdb_cursor_last(mc, key, data);
6236 if (rc == MDB_SUCCESS) {
6237 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6238 if (mx->mc_flags & C_INITIALIZED) {
6239 rc = mdb_cursor_sibling(mx, 0);
6240 if (rc == MDB_SUCCESS)
6249 case MDB_NEXT_NODUP:
6250 rc = mdb_cursor_next(mc, key, data, op);
6254 case MDB_PREV_NODUP:
6255 rc = mdb_cursor_prev(mc, key, data, op);
6258 rc = mdb_cursor_first(mc, key, data);
6261 mfunc = mdb_cursor_first;
6263 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6267 if (mc->mc_xcursor == NULL) {
6268 rc = MDB_INCOMPATIBLE;
6272 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6273 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6274 MDB_GET_KEY(leaf, key);
6275 rc = mdb_node_read(mc, leaf, data);
6279 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6283 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6286 rc = mdb_cursor_last(mc, key, data);
6289 mfunc = mdb_cursor_last;
6292 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6297 if (mc->mc_flags & C_DEL)
6298 mc->mc_flags ^= C_DEL;
6303 /** Touch all the pages in the cursor stack. Set mc_top.
6304 * Makes sure all the pages are writable, before attempting a write operation.
6305 * @param[in] mc The cursor to operate on.
6308 mdb_cursor_touch(MDB_cursor *mc)
6310 int rc = MDB_SUCCESS;
6312 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6313 /* Touch DB record of named DB */
6316 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6318 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6319 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6322 *mc->mc_dbflag |= DB_DIRTY;
6327 rc = mdb_page_touch(mc);
6328 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6329 mc->mc_top = mc->mc_snum-1;
6334 /** Do not spill pages to disk if txn is getting full, may fail instead */
6335 #define MDB_NOSPILL 0x8000
6338 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6342 MDB_node *leaf = NULL;
6343 MDB_page *fp, *mp, *sub_root = NULL;
6345 MDB_val xdata, *rdata, dkey, olddata;
6347 int do_sub = 0, insert_key, insert_data;
6348 unsigned int mcount = 0, dcount = 0, nospill;
6351 unsigned int nflags;
6354 if (mc == NULL || key == NULL)
6357 env = mc->mc_txn->mt_env;
6359 /* Check this first so counter will always be zero on any
6362 if (flags & MDB_MULTIPLE) {
6363 dcount = data[1].mv_size;
6364 data[1].mv_size = 0;
6365 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6366 return MDB_INCOMPATIBLE;
6369 nospill = flags & MDB_NOSPILL;
6370 flags &= ~MDB_NOSPILL;
6372 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6373 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6375 if (key->mv_size-1 >= ENV_MAXKEY(env))
6376 return MDB_BAD_VALSIZE;
6378 #if SIZE_MAX > MAXDATASIZE
6379 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6380 return MDB_BAD_VALSIZE;
6382 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6383 return MDB_BAD_VALSIZE;
6386 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6387 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6391 if (flags == MDB_CURRENT) {
6392 if (!(mc->mc_flags & C_INITIALIZED))
6395 } else if (mc->mc_db->md_root == P_INVALID) {
6396 /* new database, cursor has nothing to point to */
6399 mc->mc_flags &= ~C_INITIALIZED;
6404 if (flags & MDB_APPEND) {
6406 rc = mdb_cursor_last(mc, &k2, &d2);
6408 rc = mc->mc_dbx->md_cmp(key, &k2);
6411 mc->mc_ki[mc->mc_top]++;
6413 /* new key is <= last key */
6418 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6420 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6421 DPRINTF(("duplicate key [%s]", DKEY(key)));
6423 return MDB_KEYEXIST;
6425 if (rc && rc != MDB_NOTFOUND)
6429 if (mc->mc_flags & C_DEL)
6430 mc->mc_flags ^= C_DEL;
6432 /* Cursor is positioned, check for room in the dirty list */
6434 if (flags & MDB_MULTIPLE) {
6436 xdata.mv_size = data->mv_size * dcount;
6440 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6444 if (rc == MDB_NO_ROOT) {
6446 /* new database, write a root leaf page */
6447 DPUTS("allocating new root leaf page");
6448 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6451 mdb_cursor_push(mc, np);
6452 mc->mc_db->md_root = np->mp_pgno;
6453 mc->mc_db->md_depth++;
6454 *mc->mc_dbflag |= DB_DIRTY;
6455 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6457 np->mp_flags |= P_LEAF2;
6458 mc->mc_flags |= C_INITIALIZED;
6460 /* make sure all cursor pages are writable */
6461 rc2 = mdb_cursor_touch(mc);
6466 insert_key = insert_data = rc;
6468 /* The key does not exist */
6469 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6470 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6471 LEAFSIZE(key, data) > env->me_nodemax)
6473 /* Too big for a node, insert in sub-DB. Set up an empty
6474 * "old sub-page" for prep_subDB to expand to a full page.
6476 fp_flags = P_LEAF|P_DIRTY;
6478 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6479 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6480 olddata.mv_size = PAGEHDRSZ;
6484 /* there's only a key anyway, so this is a no-op */
6485 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6487 unsigned int ksize = mc->mc_db->md_pad;
6488 if (key->mv_size != ksize)
6489 return MDB_BAD_VALSIZE;
6490 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6491 memcpy(ptr, key->mv_data, ksize);
6493 /* if overwriting slot 0 of leaf, need to
6494 * update branch key if there is a parent page
6496 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6497 unsigned short dtop = 1;
6499 /* slot 0 is always an empty key, find real slot */
6500 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6504 if (mc->mc_ki[mc->mc_top])
6505 rc2 = mdb_update_key(mc, key);
6516 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6517 olddata.mv_size = NODEDSZ(leaf);
6518 olddata.mv_data = NODEDATA(leaf);
6521 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6522 /* Prepare (sub-)page/sub-DB to accept the new item,
6523 * if needed. fp: old sub-page or a header faking
6524 * it. mp: new (sub-)page. offset: growth in page
6525 * size. xdata: node data with new page or DB.
6527 unsigned i, offset = 0;
6528 mp = fp = xdata.mv_data = env->me_pbuf;
6529 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6531 /* Was a single item before, must convert now */
6532 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6534 /* Just overwrite the current item */
6535 if (flags == MDB_CURRENT)
6537 dcmp = mc->mc_dbx->md_dcmp;
6538 #if UINT_MAX < SIZE_MAX
6539 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6540 dcmp = mdb_cmp_clong;
6542 /* does data match? */
6543 if (!dcmp(data, &olddata)) {
6544 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6545 return MDB_KEYEXIST;
6550 /* Back up original data item */
6551 dkey.mv_size = olddata.mv_size;
6552 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6554 /* Make sub-page header for the dup items, with dummy body */
6555 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6556 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6557 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6558 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6559 fp->mp_flags |= P_LEAF2;
6560 fp->mp_pad = data->mv_size;
6561 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6563 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6564 (dkey.mv_size & 1) + (data->mv_size & 1);
6566 fp->mp_upper = xdata.mv_size - PAGEBASE;
6567 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6568 } else if (leaf->mn_flags & F_SUBDATA) {
6569 /* Data is on sub-DB, just store it */
6570 flags |= F_DUPDATA|F_SUBDATA;
6573 /* Data is on sub-page */
6574 fp = olddata.mv_data;
6577 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6578 offset = EVEN(NODESIZE + sizeof(indx_t) +
6582 offset = fp->mp_pad;
6583 if (SIZELEFT(fp) < offset) {
6584 offset *= 4; /* space for 4 more */
6587 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6589 fp->mp_flags |= P_DIRTY;
6590 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6591 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6595 xdata.mv_size = olddata.mv_size + offset;
6598 fp_flags = fp->mp_flags;
6599 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6600 /* Too big for a sub-page, convert to sub-DB */
6601 fp_flags &= ~P_SUBP;
6603 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6604 fp_flags |= P_LEAF2;
6605 dummy.md_pad = fp->mp_pad;
6606 dummy.md_flags = MDB_DUPFIXED;
6607 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6608 dummy.md_flags |= MDB_INTEGERKEY;
6614 dummy.md_branch_pages = 0;
6615 dummy.md_leaf_pages = 1;
6616 dummy.md_overflow_pages = 0;
6617 dummy.md_entries = NUMKEYS(fp);
6618 xdata.mv_size = sizeof(MDB_db);
6619 xdata.mv_data = &dummy;
6620 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6622 offset = env->me_psize - olddata.mv_size;
6623 flags |= F_DUPDATA|F_SUBDATA;
6624 dummy.md_root = mp->mp_pgno;
6628 mp->mp_flags = fp_flags | P_DIRTY;
6629 mp->mp_pad = fp->mp_pad;
6630 mp->mp_lower = fp->mp_lower;
6631 mp->mp_upper = fp->mp_upper + offset;
6632 if (fp_flags & P_LEAF2) {
6633 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6635 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6636 olddata.mv_size - fp->mp_upper - PAGEBASE);
6637 for (i=0; i<NUMKEYS(fp); i++)
6638 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6646 mdb_node_del(mc, 0);
6650 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6651 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6652 return MDB_INCOMPATIBLE;
6653 /* overflow page overwrites need special handling */
6654 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6657 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6659 memcpy(&pg, olddata.mv_data, sizeof(pg));
6660 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6662 ovpages = omp->mp_pages;
6664 /* Is the ov page large enough? */
6665 if (ovpages >= dpages) {
6666 if (!(omp->mp_flags & P_DIRTY) &&
6667 (level || (env->me_flags & MDB_WRITEMAP)))
6669 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6672 level = 0; /* dirty in this txn or clean */
6675 if (omp->mp_flags & P_DIRTY) {
6676 /* yes, overwrite it. Note in this case we don't
6677 * bother to try shrinking the page if the new data
6678 * is smaller than the overflow threshold.
6681 /* It is writable only in a parent txn */
6682 size_t sz = (size_t) env->me_psize * ovpages, off;
6683 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6689 /* Note - this page is already counted in parent's dirty_room */
6690 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6691 mdb_cassert(mc, rc2 == 0);
6692 /* Currently we make the page look as with put() in the
6693 * parent txn, in case the user peeks at MDB_RESERVEd
6694 * or unused parts. Some users treat ovpages specially.
6696 if (!(flags & MDB_RESERVE)) {
6697 /* Skip the part where LMDB will put *data.
6698 * Copy end of page, adjusting alignment so
6699 * compiler may copy words instead of bytes.
6701 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6702 memcpy((size_t *)((char *)np + off),
6703 (size_t *)((char *)omp + off), sz - off);
6706 memcpy(np, omp, sz); /* Copy beginning of page */
6709 SETDSZ(leaf, data->mv_size);
6710 if (F_ISSET(flags, MDB_RESERVE))
6711 data->mv_data = METADATA(omp);
6713 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6717 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6719 } else if (data->mv_size == olddata.mv_size) {
6720 /* same size, just replace it. Note that we could
6721 * also reuse this node if the new data is smaller,
6722 * but instead we opt to shrink the node in that case.
6724 if (F_ISSET(flags, MDB_RESERVE))
6725 data->mv_data = olddata.mv_data;
6726 else if (!(mc->mc_flags & C_SUB))
6727 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6729 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6734 mdb_node_del(mc, 0);
6740 nflags = flags & NODE_ADD_FLAGS;
6741 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6742 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6743 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6744 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6746 nflags |= MDB_SPLIT_REPLACE;
6747 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6749 /* There is room already in this leaf page. */
6750 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6752 /* Adjust other cursors pointing to mp */
6753 MDB_cursor *m2, *m3;
6754 MDB_dbi dbi = mc->mc_dbi;
6755 unsigned i = mc->mc_top;
6756 MDB_page *mp = mc->mc_pg[i];
6758 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6759 if (mc->mc_flags & C_SUB)
6760 m3 = &m2->mc_xcursor->mx_cursor;
6763 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6764 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6767 if (XCURSOR_INITED(m3))
6768 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
6773 if (rc == MDB_SUCCESS) {
6774 /* Now store the actual data in the child DB. Note that we're
6775 * storing the user data in the keys field, so there are strict
6776 * size limits on dupdata. The actual data fields of the child
6777 * DB are all zero size.
6780 int xflags, new_dupdata;
6785 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6786 if (flags & MDB_CURRENT) {
6787 xflags = MDB_CURRENT|MDB_NOSPILL;
6789 mdb_xcursor_init1(mc, leaf);
6790 xflags = (flags & MDB_NODUPDATA) ?
6791 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6794 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6795 new_dupdata = (int)dkey.mv_size;
6796 /* converted, write the original data first */
6798 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6801 /* we've done our job */
6804 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6805 /* Adjust other cursors pointing to mp */
6807 MDB_xcursor *mx = mc->mc_xcursor;
6808 unsigned i = mc->mc_top;
6809 MDB_page *mp = mc->mc_pg[i];
6810 int nkeys = NUMKEYS(mp);
6812 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6813 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6814 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6815 if (m2->mc_pg[i] == mp) {
6816 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6817 mdb_xcursor_init2(m2, mx, new_dupdata);
6818 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6819 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
6824 ecount = mc->mc_xcursor->mx_db.md_entries;
6825 if (flags & MDB_APPENDDUP)
6826 xflags |= MDB_APPEND;
6827 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6828 if (flags & F_SUBDATA) {
6829 void *db = NODEDATA(leaf);
6830 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6832 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6834 /* Increment count unless we just replaced an existing item. */
6836 mc->mc_db->md_entries++;
6838 /* Invalidate txn if we created an empty sub-DB */
6841 /* If we succeeded and the key didn't exist before,
6842 * make sure the cursor is marked valid.
6844 mc->mc_flags |= C_INITIALIZED;
6846 if (flags & MDB_MULTIPLE) {
6849 /* let caller know how many succeeded, if any */
6850 data[1].mv_size = mcount;
6851 if (mcount < dcount) {
6852 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6853 insert_key = insert_data = 0;
6860 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6863 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6868 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6874 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6875 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6877 if (!(mc->mc_flags & C_INITIALIZED))
6880 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6881 return MDB_NOTFOUND;
6883 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6886 rc = mdb_cursor_touch(mc);
6890 mp = mc->mc_pg[mc->mc_top];
6893 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6895 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6896 if (flags & MDB_NODUPDATA) {
6897 /* mdb_cursor_del0() will subtract the final entry */
6898 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6899 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6901 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6902 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6904 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6907 /* If sub-DB still has entries, we're done */
6908 if (mc->mc_xcursor->mx_db.md_entries) {
6909 if (leaf->mn_flags & F_SUBDATA) {
6910 /* update subDB info */
6911 void *db = NODEDATA(leaf);
6912 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6915 /* shrink fake page */
6916 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6917 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6918 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6919 /* fix other sub-DB cursors pointed at fake pages on this page */
6920 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6921 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6922 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6923 if (m2->mc_pg[mc->mc_top] == mp) {
6924 MDB_node *n2 = leaf;
6925 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
6926 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6927 if (n2->mn_flags & F_SUBDATA) continue;
6929 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6933 mc->mc_db->md_entries--;
6936 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6938 /* otherwise fall thru and delete the sub-DB */
6941 if (leaf->mn_flags & F_SUBDATA) {
6942 /* add all the child DB's pages to the free list */
6943 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6948 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6949 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6950 rc = MDB_INCOMPATIBLE;
6954 /* add overflow pages to free list */
6955 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6959 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6960 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
6961 (rc = mdb_ovpage_free(mc, omp)))
6966 return mdb_cursor_del0(mc);
6969 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6973 /** Allocate and initialize new pages for a database.
6974 * @param[in] mc a cursor on the database being added to.
6975 * @param[in] flags flags defining what type of page is being allocated.
6976 * @param[in] num the number of pages to allocate. This is usually 1,
6977 * unless allocating overflow pages for a large record.
6978 * @param[out] mp Address of a page, or NULL on failure.
6979 * @return 0 on success, non-zero on failure.
6982 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6987 if ((rc = mdb_page_alloc(mc, num, &np)))
6989 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6990 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6991 np->mp_flags = flags | P_DIRTY;
6992 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6993 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6996 mc->mc_db->md_branch_pages++;
6997 else if (IS_LEAF(np))
6998 mc->mc_db->md_leaf_pages++;
6999 else if (IS_OVERFLOW(np)) {
7000 mc->mc_db->md_overflow_pages += num;
7008 /** Calculate the size of a leaf node.
7009 * The size depends on the environment's page size; if a data item
7010 * is too large it will be put onto an overflow page and the node
7011 * size will only include the key and not the data. Sizes are always
7012 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7013 * of the #MDB_node headers.
7014 * @param[in] env The environment handle.
7015 * @param[in] key The key for the node.
7016 * @param[in] data The data for the node.
7017 * @return The number of bytes needed to store the node.
7020 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7024 sz = LEAFSIZE(key, data);
7025 if (sz > env->me_nodemax) {
7026 /* put on overflow page */
7027 sz -= data->mv_size - sizeof(pgno_t);
7030 return EVEN(sz + sizeof(indx_t));
7033 /** Calculate the size of a branch node.
7034 * The size should depend on the environment's page size but since
7035 * we currently don't support spilling large keys onto overflow
7036 * pages, it's simply the size of the #MDB_node header plus the
7037 * size of the key. Sizes are always rounded up to an even number
7038 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7039 * @param[in] env The environment handle.
7040 * @param[in] key The key for the node.
7041 * @return The number of bytes needed to store the node.
7044 mdb_branch_size(MDB_env *env, MDB_val *key)
7049 if (sz > env->me_nodemax) {
7050 /* put on overflow page */
7051 /* not implemented */
7052 /* sz -= key->size - sizeof(pgno_t); */
7055 return sz + sizeof(indx_t);
7058 /** Add a node to the page pointed to by the cursor.
7059 * @param[in] mc The cursor for this operation.
7060 * @param[in] indx The index on the page where the new node should be added.
7061 * @param[in] key The key for the new node.
7062 * @param[in] data The data for the new node, if any.
7063 * @param[in] pgno The page number, if adding a branch node.
7064 * @param[in] flags Flags for the node.
7065 * @return 0 on success, non-zero on failure. Possible errors are:
7067 * <li>ENOMEM - failed to allocate overflow pages for the node.
7068 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7069 * should never happen since all callers already calculate the
7070 * page's free space before calling this function.
7074 mdb_node_add(MDB_cursor *mc, indx_t indx,
7075 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7078 size_t node_size = NODESIZE;
7082 MDB_page *mp = mc->mc_pg[mc->mc_top];
7083 MDB_page *ofp = NULL; /* overflow page */
7087 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7089 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7090 IS_LEAF(mp) ? "leaf" : "branch",
7091 IS_SUBP(mp) ? "sub-" : "",
7092 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7093 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7096 /* Move higher keys up one slot. */
7097 int ksize = mc->mc_db->md_pad, dif;
7098 char *ptr = LEAF2KEY(mp, indx, ksize);
7099 dif = NUMKEYS(mp) - indx;
7101 memmove(ptr+ksize, ptr, dif*ksize);
7102 /* insert new key */
7103 memcpy(ptr, key->mv_data, ksize);
7105 /* Just using these for counting */
7106 mp->mp_lower += sizeof(indx_t);
7107 mp->mp_upper -= ksize - sizeof(indx_t);
7111 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7113 node_size += key->mv_size;
7115 mdb_cassert(mc, key && data);
7116 if (F_ISSET(flags, F_BIGDATA)) {
7117 /* Data already on overflow page. */
7118 node_size += sizeof(pgno_t);
7119 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7120 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7122 /* Put data on overflow page. */
7123 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7124 data->mv_size, node_size+data->mv_size));
7125 node_size = EVEN(node_size + sizeof(pgno_t));
7126 if ((ssize_t)node_size > room)
7128 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7130 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7134 node_size += data->mv_size;
7137 node_size = EVEN(node_size);
7138 if ((ssize_t)node_size > room)
7142 /* Move higher pointers up one slot. */
7143 for (i = NUMKEYS(mp); i > indx; i--)
7144 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7146 /* Adjust free space offsets. */
7147 ofs = mp->mp_upper - node_size;
7148 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7149 mp->mp_ptrs[indx] = ofs;
7151 mp->mp_lower += sizeof(indx_t);
7153 /* Write the node data. */
7154 node = NODEPTR(mp, indx);
7155 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7156 node->mn_flags = flags;
7158 SETDSZ(node,data->mv_size);
7163 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7166 ndata = NODEDATA(node);
7168 if (F_ISSET(flags, F_BIGDATA))
7169 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7170 else if (F_ISSET(flags, MDB_RESERVE))
7171 data->mv_data = ndata;
7173 memcpy(ndata, data->mv_data, data->mv_size);
7175 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7176 ndata = METADATA(ofp);
7177 if (F_ISSET(flags, MDB_RESERVE))
7178 data->mv_data = ndata;
7180 memcpy(ndata, data->mv_data, data->mv_size);
7187 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7188 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7189 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7190 DPRINTF(("node size = %"Z"u", node_size));
7191 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7192 return MDB_PAGE_FULL;
7195 /** Delete the specified node from a page.
7196 * @param[in] mc Cursor pointing to the node to delete.
7197 * @param[in] ksize The size of a node. Only used if the page is
7198 * part of a #MDB_DUPFIXED database.
7201 mdb_node_del(MDB_cursor *mc, int ksize)
7203 MDB_page *mp = mc->mc_pg[mc->mc_top];
7204 indx_t indx = mc->mc_ki[mc->mc_top];
7206 indx_t i, j, numkeys, ptr;
7210 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7211 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7212 numkeys = NUMKEYS(mp);
7213 mdb_cassert(mc, indx < numkeys);
7216 int x = numkeys - 1 - indx;
7217 base = LEAF2KEY(mp, indx, ksize);
7219 memmove(base, base + ksize, x * ksize);
7220 mp->mp_lower -= sizeof(indx_t);
7221 mp->mp_upper += ksize - sizeof(indx_t);
7225 node = NODEPTR(mp, indx);
7226 sz = NODESIZE + node->mn_ksize;
7228 if (F_ISSET(node->mn_flags, F_BIGDATA))
7229 sz += sizeof(pgno_t);
7231 sz += NODEDSZ(node);
7235 ptr = mp->mp_ptrs[indx];
7236 for (i = j = 0; i < numkeys; i++) {
7238 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7239 if (mp->mp_ptrs[i] < ptr)
7240 mp->mp_ptrs[j] += sz;
7245 base = (char *)mp + mp->mp_upper + PAGEBASE;
7246 memmove(base + sz, base, ptr - mp->mp_upper);
7248 mp->mp_lower -= sizeof(indx_t);
7252 /** Compact the main page after deleting a node on a subpage.
7253 * @param[in] mp The main page to operate on.
7254 * @param[in] indx The index of the subpage on the main page.
7257 mdb_node_shrink(MDB_page *mp, indx_t indx)
7262 indx_t delta, nsize, len, ptr;
7265 node = NODEPTR(mp, indx);
7266 sp = (MDB_page *)NODEDATA(node);
7267 delta = SIZELEFT(sp);
7268 nsize = NODEDSZ(node) - delta;
7270 /* Prepare to shift upward, set len = length(subpage part to shift) */
7274 return; /* do not make the node uneven-sized */
7276 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7277 for (i = NUMKEYS(sp); --i >= 0; )
7278 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7281 sp->mp_upper = sp->mp_lower;
7282 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7283 SETDSZ(node, nsize);
7285 /* Shift <lower nodes...initial part of subpage> upward */
7286 base = (char *)mp + mp->mp_upper + PAGEBASE;
7287 memmove(base + delta, base, (char *)sp + len - base);
7289 ptr = mp->mp_ptrs[indx];
7290 for (i = NUMKEYS(mp); --i >= 0; ) {
7291 if (mp->mp_ptrs[i] <= ptr)
7292 mp->mp_ptrs[i] += delta;
7294 mp->mp_upper += delta;
7297 /** Initial setup of a sorted-dups cursor.
7298 * Sorted duplicates are implemented as a sub-database for the given key.
7299 * The duplicate data items are actually keys of the sub-database.
7300 * Operations on the duplicate data items are performed using a sub-cursor
7301 * initialized when the sub-database is first accessed. This function does
7302 * the preliminary setup of the sub-cursor, filling in the fields that
7303 * depend only on the parent DB.
7304 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7307 mdb_xcursor_init0(MDB_cursor *mc)
7309 MDB_xcursor *mx = mc->mc_xcursor;
7311 mx->mx_cursor.mc_xcursor = NULL;
7312 mx->mx_cursor.mc_txn = mc->mc_txn;
7313 mx->mx_cursor.mc_db = &mx->mx_db;
7314 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7315 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7316 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7317 mx->mx_cursor.mc_snum = 0;
7318 mx->mx_cursor.mc_top = 0;
7319 mx->mx_cursor.mc_flags = C_SUB;
7320 mx->mx_dbx.md_name.mv_size = 0;
7321 mx->mx_dbx.md_name.mv_data = NULL;
7322 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7323 mx->mx_dbx.md_dcmp = NULL;
7324 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7327 /** Final setup of a sorted-dups cursor.
7328 * Sets up the fields that depend on the data from the main cursor.
7329 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7330 * @param[in] node The data containing the #MDB_db record for the
7331 * sorted-dup database.
7334 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7336 MDB_xcursor *mx = mc->mc_xcursor;
7338 if (node->mn_flags & F_SUBDATA) {
7339 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7340 mx->mx_cursor.mc_pg[0] = 0;
7341 mx->mx_cursor.mc_snum = 0;
7342 mx->mx_cursor.mc_top = 0;
7343 mx->mx_cursor.mc_flags = C_SUB;
7345 MDB_page *fp = NODEDATA(node);
7346 mx->mx_db.md_pad = 0;
7347 mx->mx_db.md_flags = 0;
7348 mx->mx_db.md_depth = 1;
7349 mx->mx_db.md_branch_pages = 0;
7350 mx->mx_db.md_leaf_pages = 1;
7351 mx->mx_db.md_overflow_pages = 0;
7352 mx->mx_db.md_entries = NUMKEYS(fp);
7353 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7354 mx->mx_cursor.mc_snum = 1;
7355 mx->mx_cursor.mc_top = 0;
7356 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7357 mx->mx_cursor.mc_pg[0] = fp;
7358 mx->mx_cursor.mc_ki[0] = 0;
7359 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7360 mx->mx_db.md_flags = MDB_DUPFIXED;
7361 mx->mx_db.md_pad = fp->mp_pad;
7362 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7363 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7366 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7367 mx->mx_db.md_root));
7368 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7369 #if UINT_MAX < SIZE_MAX
7370 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7371 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7376 /** Fixup a sorted-dups cursor due to underlying update.
7377 * Sets up some fields that depend on the data from the main cursor.
7378 * Almost the same as init1, but skips initialization steps if the
7379 * xcursor had already been used.
7380 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7381 * @param[in] src_mx The xcursor of an up-to-date cursor.
7382 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7385 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7387 MDB_xcursor *mx = mc->mc_xcursor;
7390 mx->mx_cursor.mc_snum = 1;
7391 mx->mx_cursor.mc_top = 0;
7392 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7393 mx->mx_cursor.mc_ki[0] = 0;
7394 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7395 #if UINT_MAX < SIZE_MAX
7396 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7398 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7401 mx->mx_db = src_mx->mx_db;
7402 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7403 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7404 mx->mx_db.md_root));
7407 /** Initialize a cursor for a given transaction and database. */
7409 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7412 mc->mc_backup = NULL;
7415 mc->mc_db = &txn->mt_dbs[dbi];
7416 mc->mc_dbx = &txn->mt_dbxs[dbi];
7417 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7423 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7424 mdb_tassert(txn, mx != NULL);
7425 mc->mc_xcursor = mx;
7426 mdb_xcursor_init0(mc);
7428 mc->mc_xcursor = NULL;
7430 if (*mc->mc_dbflag & DB_STALE) {
7431 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7436 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7439 size_t size = sizeof(MDB_cursor);
7441 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7444 if (txn->mt_flags & MDB_TXN_BLOCKED)
7447 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7450 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7451 size += sizeof(MDB_xcursor);
7453 if ((mc = malloc(size)) != NULL) {
7454 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7455 if (txn->mt_cursors) {
7456 mc->mc_next = txn->mt_cursors[dbi];
7457 txn->mt_cursors[dbi] = mc;
7458 mc->mc_flags |= C_UNTRACK;
7470 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7472 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7475 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7478 if (txn->mt_flags & MDB_TXN_BLOCKED)
7481 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7485 /* Return the count of duplicate data items for the current key */
7487 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7491 if (mc == NULL || countp == NULL)
7494 if (mc->mc_xcursor == NULL)
7495 return MDB_INCOMPATIBLE;
7497 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7500 if (!(mc->mc_flags & C_INITIALIZED))
7503 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7504 return MDB_NOTFOUND;
7506 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7507 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7510 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7513 *countp = mc->mc_xcursor->mx_db.md_entries;
7519 mdb_cursor_close(MDB_cursor *mc)
7521 if (mc && !mc->mc_backup) {
7522 /* remove from txn, if tracked */
7523 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7524 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7525 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7527 *prev = mc->mc_next;
7534 mdb_cursor_txn(MDB_cursor *mc)
7536 if (!mc) return NULL;
7541 mdb_cursor_dbi(MDB_cursor *mc)
7546 /** Replace the key for a branch node with a new key.
7547 * @param[in] mc Cursor pointing to the node to operate on.
7548 * @param[in] key The new key to use.
7549 * @return 0 on success, non-zero on failure.
7552 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7558 int delta, ksize, oksize;
7559 indx_t ptr, i, numkeys, indx;
7562 indx = mc->mc_ki[mc->mc_top];
7563 mp = mc->mc_pg[mc->mc_top];
7564 node = NODEPTR(mp, indx);
7565 ptr = mp->mp_ptrs[indx];
7569 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7570 k2.mv_data = NODEKEY(node);
7571 k2.mv_size = node->mn_ksize;
7572 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7574 mdb_dkey(&k2, kbuf2),
7580 /* Sizes must be 2-byte aligned. */
7581 ksize = EVEN(key->mv_size);
7582 oksize = EVEN(node->mn_ksize);
7583 delta = ksize - oksize;
7585 /* Shift node contents if EVEN(key length) changed. */
7587 if (delta > 0 && SIZELEFT(mp) < delta) {
7589 /* not enough space left, do a delete and split */
7590 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7591 pgno = NODEPGNO(node);
7592 mdb_node_del(mc, 0);
7593 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7596 numkeys = NUMKEYS(mp);
7597 for (i = 0; i < numkeys; i++) {
7598 if (mp->mp_ptrs[i] <= ptr)
7599 mp->mp_ptrs[i] -= delta;
7602 base = (char *)mp + mp->mp_upper + PAGEBASE;
7603 len = ptr - mp->mp_upper + NODESIZE;
7604 memmove(base - delta, base, len);
7605 mp->mp_upper -= delta;
7607 node = NODEPTR(mp, indx);
7610 /* But even if no shift was needed, update ksize */
7611 if (node->mn_ksize != key->mv_size)
7612 node->mn_ksize = key->mv_size;
7615 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7621 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7623 /** Perform \b act while tracking temporary cursor \b mn */
7624 #define WITH_CURSOR_TRACKING(mn, act) do { \
7625 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7626 if ((mn).mc_flags & C_SUB) { \
7627 dummy.mc_flags = C_INITIALIZED; \
7628 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7633 tracked->mc_next = *tp; \
7636 *tp = tracked->mc_next; \
7639 /** Move a node from csrc to cdst.
7642 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7649 unsigned short flags;
7653 /* Mark src and dst as dirty. */
7654 if ((rc = mdb_page_touch(csrc)) ||
7655 (rc = mdb_page_touch(cdst)))
7658 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7659 key.mv_size = csrc->mc_db->md_pad;
7660 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7662 data.mv_data = NULL;
7666 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7667 mdb_cassert(csrc, !((size_t)srcnode & 1));
7668 srcpg = NODEPGNO(srcnode);
7669 flags = srcnode->mn_flags;
7670 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7671 unsigned int snum = csrc->mc_snum;
7673 /* must find the lowest key below src */
7674 rc = mdb_page_search_lowest(csrc);
7677 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7678 key.mv_size = csrc->mc_db->md_pad;
7679 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7681 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7682 key.mv_size = NODEKSZ(s2);
7683 key.mv_data = NODEKEY(s2);
7685 csrc->mc_snum = snum--;
7686 csrc->mc_top = snum;
7688 key.mv_size = NODEKSZ(srcnode);
7689 key.mv_data = NODEKEY(srcnode);
7691 data.mv_size = NODEDSZ(srcnode);
7692 data.mv_data = NODEDATA(srcnode);
7694 mn.mc_xcursor = NULL;
7695 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7696 unsigned int snum = cdst->mc_snum;
7699 /* must find the lowest key below dst */
7700 mdb_cursor_copy(cdst, &mn);
7701 rc = mdb_page_search_lowest(&mn);
7704 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7705 bkey.mv_size = mn.mc_db->md_pad;
7706 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7708 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7709 bkey.mv_size = NODEKSZ(s2);
7710 bkey.mv_data = NODEKEY(s2);
7712 mn.mc_snum = snum--;
7715 rc = mdb_update_key(&mn, &bkey);
7720 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7721 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7722 csrc->mc_ki[csrc->mc_top],
7724 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7725 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7727 /* Add the node to the destination page.
7729 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7730 if (rc != MDB_SUCCESS)
7733 /* Delete the node from the source page.
7735 mdb_node_del(csrc, key.mv_size);
7738 /* Adjust other cursors pointing to mp */
7739 MDB_cursor *m2, *m3;
7740 MDB_dbi dbi = csrc->mc_dbi;
7741 MDB_page *mpd, *mps;
7743 mps = csrc->mc_pg[csrc->mc_top];
7744 /* If we're adding on the left, bump others up */
7746 mpd = cdst->mc_pg[csrc->mc_top];
7747 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7748 if (csrc->mc_flags & C_SUB)
7749 m3 = &m2->mc_xcursor->mx_cursor;
7752 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7755 m3->mc_pg[csrc->mc_top] == mpd &&
7756 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7757 m3->mc_ki[csrc->mc_top]++;
7760 m3->mc_pg[csrc->mc_top] == mps &&
7761 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7762 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7763 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7764 m3->mc_ki[csrc->mc_top-1]++;
7766 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7767 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7770 /* Adding on the right, bump others down */
7772 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7773 if (csrc->mc_flags & C_SUB)
7774 m3 = &m2->mc_xcursor->mx_cursor;
7777 if (m3 == csrc) continue;
7778 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7780 if (m3->mc_pg[csrc->mc_top] == mps) {
7781 if (!m3->mc_ki[csrc->mc_top]) {
7782 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7783 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7784 m3->mc_ki[csrc->mc_top-1]--;
7786 m3->mc_ki[csrc->mc_top]--;
7788 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7789 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7795 /* Update the parent separators.
7797 if (csrc->mc_ki[csrc->mc_top] == 0) {
7798 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7799 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7800 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7802 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7803 key.mv_size = NODEKSZ(srcnode);
7804 key.mv_data = NODEKEY(srcnode);
7806 DPRINTF(("update separator for source page %"Z"u to [%s]",
7807 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7808 mdb_cursor_copy(csrc, &mn);
7811 /* We want mdb_rebalance to find mn when doing fixups */
7812 WITH_CURSOR_TRACKING(mn,
7813 rc = mdb_update_key(&mn, &key));
7817 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7819 indx_t ix = csrc->mc_ki[csrc->mc_top];
7820 nullkey.mv_size = 0;
7821 csrc->mc_ki[csrc->mc_top] = 0;
7822 rc = mdb_update_key(csrc, &nullkey);
7823 csrc->mc_ki[csrc->mc_top] = ix;
7824 mdb_cassert(csrc, rc == MDB_SUCCESS);
7828 if (cdst->mc_ki[cdst->mc_top] == 0) {
7829 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7830 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7831 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7833 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7834 key.mv_size = NODEKSZ(srcnode);
7835 key.mv_data = NODEKEY(srcnode);
7837 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7838 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7839 mdb_cursor_copy(cdst, &mn);
7842 /* We want mdb_rebalance to find mn when doing fixups */
7843 WITH_CURSOR_TRACKING(mn,
7844 rc = mdb_update_key(&mn, &key));
7848 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7850 indx_t ix = cdst->mc_ki[cdst->mc_top];
7851 nullkey.mv_size = 0;
7852 cdst->mc_ki[cdst->mc_top] = 0;
7853 rc = mdb_update_key(cdst, &nullkey);
7854 cdst->mc_ki[cdst->mc_top] = ix;
7855 mdb_cassert(cdst, rc == MDB_SUCCESS);
7862 /** Merge one page into another.
7863 * The nodes from the page pointed to by \b csrc will
7864 * be copied to the page pointed to by \b cdst and then
7865 * the \b csrc page will be freed.
7866 * @param[in] csrc Cursor pointing to the source page.
7867 * @param[in] cdst Cursor pointing to the destination page.
7868 * @return 0 on success, non-zero on failure.
7871 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7873 MDB_page *psrc, *pdst;
7880 psrc = csrc->mc_pg[csrc->mc_top];
7881 pdst = cdst->mc_pg[cdst->mc_top];
7883 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7885 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7886 mdb_cassert(csrc, cdst->mc_snum > 1);
7888 /* Mark dst as dirty. */
7889 if ((rc = mdb_page_touch(cdst)))
7892 /* get dst page again now that we've touched it. */
7893 pdst = cdst->mc_pg[cdst->mc_top];
7895 /* Move all nodes from src to dst.
7897 j = nkeys = NUMKEYS(pdst);
7898 if (IS_LEAF2(psrc)) {
7899 key.mv_size = csrc->mc_db->md_pad;
7900 key.mv_data = METADATA(psrc);
7901 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7902 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7903 if (rc != MDB_SUCCESS)
7905 key.mv_data = (char *)key.mv_data + key.mv_size;
7908 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7909 srcnode = NODEPTR(psrc, i);
7910 if (i == 0 && IS_BRANCH(psrc)) {
7913 mdb_cursor_copy(csrc, &mn);
7914 mn.mc_xcursor = NULL;
7915 /* must find the lowest key below src */
7916 rc = mdb_page_search_lowest(&mn);
7919 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7920 key.mv_size = mn.mc_db->md_pad;
7921 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7923 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7924 key.mv_size = NODEKSZ(s2);
7925 key.mv_data = NODEKEY(s2);
7928 key.mv_size = srcnode->mn_ksize;
7929 key.mv_data = NODEKEY(srcnode);
7932 data.mv_size = NODEDSZ(srcnode);
7933 data.mv_data = NODEDATA(srcnode);
7934 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7935 if (rc != MDB_SUCCESS)
7940 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7941 pdst->mp_pgno, NUMKEYS(pdst),
7942 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7944 /* Unlink the src page from parent and add to free list.
7947 mdb_node_del(csrc, 0);
7948 if (csrc->mc_ki[csrc->mc_top] == 0) {
7950 rc = mdb_update_key(csrc, &key);
7958 psrc = csrc->mc_pg[csrc->mc_top];
7959 /* If not operating on FreeDB, allow this page to be reused
7960 * in this txn. Otherwise just add to free list.
7962 rc = mdb_page_loose(csrc, psrc);
7966 csrc->mc_db->md_leaf_pages--;
7968 csrc->mc_db->md_branch_pages--;
7970 /* Adjust other cursors pointing to mp */
7971 MDB_cursor *m2, *m3;
7972 MDB_dbi dbi = csrc->mc_dbi;
7973 unsigned int top = csrc->mc_top;
7975 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7976 if (csrc->mc_flags & C_SUB)
7977 m3 = &m2->mc_xcursor->mx_cursor;
7980 if (m3 == csrc) continue;
7981 if (m3->mc_snum < csrc->mc_snum) continue;
7982 if (m3->mc_pg[top] == psrc) {
7983 m3->mc_pg[top] = pdst;
7984 m3->mc_ki[top] += nkeys;
7985 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
7986 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
7987 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
7990 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
7991 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
7995 unsigned int snum = cdst->mc_snum;
7996 uint16_t depth = cdst->mc_db->md_depth;
7997 mdb_cursor_pop(cdst);
7998 rc = mdb_rebalance(cdst);
7999 /* Did the tree height change? */
8000 if (depth != cdst->mc_db->md_depth)
8001 snum += cdst->mc_db->md_depth - depth;
8002 cdst->mc_snum = snum;
8003 cdst->mc_top = snum-1;
8008 /** Copy the contents of a cursor.
8009 * @param[in] csrc The cursor to copy from.
8010 * @param[out] cdst The cursor to copy to.
8013 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8017 cdst->mc_txn = csrc->mc_txn;
8018 cdst->mc_dbi = csrc->mc_dbi;
8019 cdst->mc_db = csrc->mc_db;
8020 cdst->mc_dbx = csrc->mc_dbx;
8021 cdst->mc_snum = csrc->mc_snum;
8022 cdst->mc_top = csrc->mc_top;
8023 cdst->mc_flags = csrc->mc_flags;
8025 for (i=0; i<csrc->mc_snum; i++) {
8026 cdst->mc_pg[i] = csrc->mc_pg[i];
8027 cdst->mc_ki[i] = csrc->mc_ki[i];
8031 /** Rebalance the tree after a delete operation.
8032 * @param[in] mc Cursor pointing to the page where rebalancing
8034 * @return 0 on success, non-zero on failure.
8037 mdb_rebalance(MDB_cursor *mc)
8041 unsigned int ptop, minkeys, thresh;
8045 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8050 thresh = FILL_THRESHOLD;
8052 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8053 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8054 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8055 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8057 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8058 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8059 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8060 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8064 if (mc->mc_snum < 2) {
8065 MDB_page *mp = mc->mc_pg[0];
8067 DPUTS("Can't rebalance a subpage, ignoring");
8070 if (NUMKEYS(mp) == 0) {
8071 DPUTS("tree is completely empty");
8072 mc->mc_db->md_root = P_INVALID;
8073 mc->mc_db->md_depth = 0;
8074 mc->mc_db->md_leaf_pages = 0;
8075 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8078 /* Adjust cursors pointing to mp */
8081 mc->mc_flags &= ~C_INITIALIZED;
8083 MDB_cursor *m2, *m3;
8084 MDB_dbi dbi = mc->mc_dbi;
8086 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8087 if (mc->mc_flags & C_SUB)
8088 m3 = &m2->mc_xcursor->mx_cursor;
8091 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8093 if (m3->mc_pg[0] == mp) {
8096 m3->mc_flags &= ~C_INITIALIZED;
8100 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8102 DPUTS("collapsing root page!");
8103 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8106 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8107 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8110 mc->mc_db->md_depth--;
8111 mc->mc_db->md_branch_pages--;
8112 mc->mc_ki[0] = mc->mc_ki[1];
8113 for (i = 1; i<mc->mc_db->md_depth; i++) {
8114 mc->mc_pg[i] = mc->mc_pg[i+1];
8115 mc->mc_ki[i] = mc->mc_ki[i+1];
8118 /* Adjust other cursors pointing to mp */
8119 MDB_cursor *m2, *m3;
8120 MDB_dbi dbi = mc->mc_dbi;
8122 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8123 if (mc->mc_flags & C_SUB)
8124 m3 = &m2->mc_xcursor->mx_cursor;
8127 if (m3 == mc) continue;
8128 if (!(m3->mc_flags & C_INITIALIZED))
8130 if (m3->mc_pg[0] == mp) {
8131 for (i=0; i<mc->mc_db->md_depth; i++) {
8132 m3->mc_pg[i] = m3->mc_pg[i+1];
8133 m3->mc_ki[i] = m3->mc_ki[i+1];
8141 DPUTS("root page doesn't need rebalancing");
8145 /* The parent (branch page) must have at least 2 pointers,
8146 * otherwise the tree is invalid.
8148 ptop = mc->mc_top-1;
8149 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8151 /* Leaf page fill factor is below the threshold.
8152 * Try to move keys from left or right neighbor, or
8153 * merge with a neighbor page.
8158 mdb_cursor_copy(mc, &mn);
8159 mn.mc_xcursor = NULL;
8161 oldki = mc->mc_ki[mc->mc_top];
8162 if (mc->mc_ki[ptop] == 0) {
8163 /* We're the leftmost leaf in our parent.
8165 DPUTS("reading right neighbor");
8167 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8168 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8171 mn.mc_ki[mn.mc_top] = 0;
8172 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8175 /* There is at least one neighbor to the left.
8177 DPUTS("reading left neighbor");
8179 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8180 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8183 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8184 mc->mc_ki[mc->mc_top] = 0;
8188 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8189 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8190 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8192 /* If the neighbor page is above threshold and has enough keys,
8193 * move one key from it. Otherwise we should try to merge them.
8194 * (A branch page must never have less than 2 keys.)
8196 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8197 rc = mdb_node_move(&mn, mc, fromleft);
8199 /* if we inserted on left, bump position up */
8204 rc = mdb_page_merge(&mn, mc);
8206 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8207 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8208 /* We want mdb_rebalance to find mn when doing fixups */
8209 WITH_CURSOR_TRACKING(mn,
8210 rc = mdb_page_merge(mc, &mn));
8211 mdb_cursor_copy(&mn, mc);
8213 mc->mc_flags &= ~C_EOF;
8215 mc->mc_ki[mc->mc_top] = oldki;
8219 /** Complete a delete operation started by #mdb_cursor_del(). */
8221 mdb_cursor_del0(MDB_cursor *mc)
8227 MDB_cursor *m2, *m3;
8228 MDB_dbi dbi = mc->mc_dbi;
8230 ki = mc->mc_ki[mc->mc_top];
8231 mp = mc->mc_pg[mc->mc_top];
8232 mdb_node_del(mc, mc->mc_db->md_pad);
8233 mc->mc_db->md_entries--;
8235 /* Adjust other cursors pointing to mp */
8236 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8237 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8238 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8240 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8242 if (m3->mc_pg[mc->mc_top] == mp) {
8243 if (m3->mc_ki[mc->mc_top] == ki) {
8244 m3->mc_flags |= C_DEL;
8245 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8246 /* Sub-cursor referred into dataset which is gone */
8247 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
8250 } else if (m3->mc_ki[mc->mc_top] > ki) {
8251 m3->mc_ki[mc->mc_top]--;
8253 if (XCURSOR_INITED(m3))
8254 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8258 rc = mdb_rebalance(mc);
8260 if (rc == MDB_SUCCESS) {
8261 /* DB is totally empty now, just bail out.
8262 * Other cursors adjustments were already done
8263 * by mdb_rebalance and aren't needed here.
8268 mp = mc->mc_pg[mc->mc_top];
8269 nkeys = NUMKEYS(mp);
8271 /* Adjust other cursors pointing to mp */
8272 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8273 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8274 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8276 if (m3->mc_snum < mc->mc_snum)
8278 if (m3->mc_pg[mc->mc_top] == mp) {
8279 /* if m3 points past last node in page, find next sibling */
8280 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8281 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8282 rc = mdb_cursor_sibling(m3, 1);
8283 if (rc == MDB_NOTFOUND) {
8284 m3->mc_flags |= C_EOF;
8289 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8290 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8291 /* If this node is a fake page, it needs to be reinited
8292 * because its data has moved. But just reset mc_pg[0]
8293 * if the xcursor is already live.
8295 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
8296 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
8297 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8299 mdb_xcursor_init1(m3, node);
8305 mc->mc_flags |= C_DEL;
8309 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8314 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8315 MDB_val *key, MDB_val *data)
8317 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8320 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8321 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8323 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8324 /* must ignore any data */
8328 return mdb_del0(txn, dbi, key, data, 0);
8332 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8333 MDB_val *key, MDB_val *data, unsigned flags)
8338 MDB_val rdata, *xdata;
8342 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8344 mdb_cursor_init(&mc, txn, dbi, &mx);
8353 flags |= MDB_NODUPDATA;
8355 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8357 /* let mdb_page_split know about this cursor if needed:
8358 * delete will trigger a rebalance; if it needs to move
8359 * a node from one page to another, it will have to
8360 * update the parent's separator key(s). If the new sepkey
8361 * is larger than the current one, the parent page may
8362 * run out of space, triggering a split. We need this
8363 * cursor to be consistent until the end of the rebalance.
8365 mc.mc_flags |= C_UNTRACK;
8366 mc.mc_next = txn->mt_cursors[dbi];
8367 txn->mt_cursors[dbi] = &mc;
8368 rc = mdb_cursor_del(&mc, flags);
8369 txn->mt_cursors[dbi] = mc.mc_next;
8374 /** Split a page and insert a new node.
8375 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8376 * The cursor will be updated to point to the actual page and index where
8377 * the node got inserted after the split.
8378 * @param[in] newkey The key for the newly inserted node.
8379 * @param[in] newdata The data for the newly inserted node.
8380 * @param[in] newpgno The page number, if the new node is a branch node.
8381 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8382 * @return 0 on success, non-zero on failure.
8385 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8386 unsigned int nflags)
8389 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8392 int i, j, split_indx, nkeys, pmax;
8393 MDB_env *env = mc->mc_txn->mt_env;
8395 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8396 MDB_page *copy = NULL;
8397 MDB_page *mp, *rp, *pp;
8402 mp = mc->mc_pg[mc->mc_top];
8403 newindx = mc->mc_ki[mc->mc_top];
8404 nkeys = NUMKEYS(mp);
8406 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8407 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8408 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8410 /* Create a right sibling. */
8411 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8413 rp->mp_pad = mp->mp_pad;
8414 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8416 /* Usually when splitting the root page, the cursor
8417 * height is 1. But when called from mdb_update_key,
8418 * the cursor height may be greater because it walks
8419 * up the stack while finding the branch slot to update.
8421 if (mc->mc_top < 1) {
8422 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8424 /* shift current top to make room for new parent */
8425 for (i=mc->mc_snum; i>0; i--) {
8426 mc->mc_pg[i] = mc->mc_pg[i-1];
8427 mc->mc_ki[i] = mc->mc_ki[i-1];
8431 mc->mc_db->md_root = pp->mp_pgno;
8432 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8433 new_root = mc->mc_db->md_depth++;
8435 /* Add left (implicit) pointer. */
8436 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8437 /* undo the pre-push */
8438 mc->mc_pg[0] = mc->mc_pg[1];
8439 mc->mc_ki[0] = mc->mc_ki[1];
8440 mc->mc_db->md_root = mp->mp_pgno;
8441 mc->mc_db->md_depth--;
8448 ptop = mc->mc_top-1;
8449 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8452 mdb_cursor_copy(mc, &mn);
8453 mn.mc_xcursor = NULL;
8454 mn.mc_pg[mn.mc_top] = rp;
8455 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8457 if (nflags & MDB_APPEND) {
8458 mn.mc_ki[mn.mc_top] = 0;
8460 split_indx = newindx;
8464 split_indx = (nkeys+1) / 2;
8469 unsigned int lsize, rsize, ksize;
8470 /* Move half of the keys to the right sibling */
8471 x = mc->mc_ki[mc->mc_top] - split_indx;
8472 ksize = mc->mc_db->md_pad;
8473 split = LEAF2KEY(mp, split_indx, ksize);
8474 rsize = (nkeys - split_indx) * ksize;
8475 lsize = (nkeys - split_indx) * sizeof(indx_t);
8476 mp->mp_lower -= lsize;
8477 rp->mp_lower += lsize;
8478 mp->mp_upper += rsize - lsize;
8479 rp->mp_upper -= rsize - lsize;
8480 sepkey.mv_size = ksize;
8481 if (newindx == split_indx) {
8482 sepkey.mv_data = newkey->mv_data;
8484 sepkey.mv_data = split;
8487 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8488 memcpy(rp->mp_ptrs, split, rsize);
8489 sepkey.mv_data = rp->mp_ptrs;
8490 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8491 memcpy(ins, newkey->mv_data, ksize);
8492 mp->mp_lower += sizeof(indx_t);
8493 mp->mp_upper -= ksize - sizeof(indx_t);
8496 memcpy(rp->mp_ptrs, split, x * ksize);
8497 ins = LEAF2KEY(rp, x, ksize);
8498 memcpy(ins, newkey->mv_data, ksize);
8499 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8500 rp->mp_lower += sizeof(indx_t);
8501 rp->mp_upper -= ksize - sizeof(indx_t);
8502 mc->mc_ki[mc->mc_top] = x;
8505 int psize, nsize, k;
8506 /* Maximum free space in an empty page */
8507 pmax = env->me_psize - PAGEHDRSZ;
8509 nsize = mdb_leaf_size(env, newkey, newdata);
8511 nsize = mdb_branch_size(env, newkey);
8512 nsize = EVEN(nsize);
8514 /* grab a page to hold a temporary copy */
8515 copy = mdb_page_malloc(mc->mc_txn, 1);
8520 copy->mp_pgno = mp->mp_pgno;
8521 copy->mp_flags = mp->mp_flags;
8522 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8523 copy->mp_upper = env->me_psize - PAGEBASE;
8525 /* prepare to insert */
8526 for (i=0, j=0; i<nkeys; i++) {
8528 copy->mp_ptrs[j++] = 0;
8530 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8533 /* When items are relatively large the split point needs
8534 * to be checked, because being off-by-one will make the
8535 * difference between success or failure in mdb_node_add.
8537 * It's also relevant if a page happens to be laid out
8538 * such that one half of its nodes are all "small" and
8539 * the other half of its nodes are "large." If the new
8540 * item is also "large" and falls on the half with
8541 * "large" nodes, it also may not fit.
8543 * As a final tweak, if the new item goes on the last
8544 * spot on the page (and thus, onto the new page), bias
8545 * the split so the new page is emptier than the old page.
8546 * This yields better packing during sequential inserts.
8548 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8549 /* Find split point */
8551 if (newindx <= split_indx || newindx >= nkeys) {
8553 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8558 for (; i!=k; i+=j) {
8563 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8564 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8566 if (F_ISSET(node->mn_flags, F_BIGDATA))
8567 psize += sizeof(pgno_t);
8569 psize += NODEDSZ(node);
8571 psize = EVEN(psize);
8573 if (psize > pmax || i == k-j) {
8574 split_indx = i + (j<0);
8579 if (split_indx == newindx) {
8580 sepkey.mv_size = newkey->mv_size;
8581 sepkey.mv_data = newkey->mv_data;
8583 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8584 sepkey.mv_size = node->mn_ksize;
8585 sepkey.mv_data = NODEKEY(node);
8590 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8592 /* Copy separator key to the parent.
8594 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8595 int snum = mc->mc_snum;
8599 /* We want other splits to find mn when doing fixups */
8600 WITH_CURSOR_TRACKING(mn,
8601 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8606 if (mc->mc_snum > snum) {
8609 /* Right page might now have changed parent.
8610 * Check if left page also changed parent.
8612 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8613 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8614 for (i=0; i<ptop; i++) {
8615 mc->mc_pg[i] = mn.mc_pg[i];
8616 mc->mc_ki[i] = mn.mc_ki[i];
8618 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8619 if (mn.mc_ki[ptop]) {
8620 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8622 /* find right page's left sibling */
8623 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8624 mdb_cursor_sibling(mc, 0);
8629 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8632 if (rc != MDB_SUCCESS) {
8635 if (nflags & MDB_APPEND) {
8636 mc->mc_pg[mc->mc_top] = rp;
8637 mc->mc_ki[mc->mc_top] = 0;
8638 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8641 for (i=0; i<mc->mc_top; i++)
8642 mc->mc_ki[i] = mn.mc_ki[i];
8643 } else if (!IS_LEAF2(mp)) {
8645 mc->mc_pg[mc->mc_top] = rp;
8650 rkey.mv_data = newkey->mv_data;
8651 rkey.mv_size = newkey->mv_size;
8657 /* Update index for the new key. */
8658 mc->mc_ki[mc->mc_top] = j;
8660 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8661 rkey.mv_data = NODEKEY(node);
8662 rkey.mv_size = node->mn_ksize;
8664 xdata.mv_data = NODEDATA(node);
8665 xdata.mv_size = NODEDSZ(node);
8668 pgno = NODEPGNO(node);
8669 flags = node->mn_flags;
8672 if (!IS_LEAF(mp) && j == 0) {
8673 /* First branch index doesn't need key data. */
8677 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8683 mc->mc_pg[mc->mc_top] = copy;
8688 } while (i != split_indx);
8690 nkeys = NUMKEYS(copy);
8691 for (i=0; i<nkeys; i++)
8692 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8693 mp->mp_lower = copy->mp_lower;
8694 mp->mp_upper = copy->mp_upper;
8695 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8696 env->me_psize - copy->mp_upper - PAGEBASE);
8698 /* reset back to original page */
8699 if (newindx < split_indx) {
8700 mc->mc_pg[mc->mc_top] = mp;
8702 mc->mc_pg[mc->mc_top] = rp;
8704 /* Make sure mc_ki is still valid.
8706 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8707 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8708 for (i=0; i<=ptop; i++) {
8709 mc->mc_pg[i] = mn.mc_pg[i];
8710 mc->mc_ki[i] = mn.mc_ki[i];
8714 if (nflags & MDB_RESERVE) {
8715 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8716 if (!(node->mn_flags & F_BIGDATA))
8717 newdata->mv_data = NODEDATA(node);
8720 if (newindx >= split_indx) {
8721 mc->mc_pg[mc->mc_top] = rp;
8723 /* Make sure mc_ki is still valid.
8725 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8726 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8727 for (i=0; i<=ptop; i++) {
8728 mc->mc_pg[i] = mn.mc_pg[i];
8729 mc->mc_ki[i] = mn.mc_ki[i];
8736 /* Adjust other cursors pointing to mp */
8737 MDB_cursor *m2, *m3;
8738 MDB_dbi dbi = mc->mc_dbi;
8739 nkeys = NUMKEYS(mp);
8741 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8742 if (mc->mc_flags & C_SUB)
8743 m3 = &m2->mc_xcursor->mx_cursor;
8748 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8752 /* sub cursors may be on different DB */
8753 if (m3->mc_pg[0] != mp)
8756 for (k=new_root; k>=0; k--) {
8757 m3->mc_ki[k+1] = m3->mc_ki[k];
8758 m3->mc_pg[k+1] = m3->mc_pg[k];
8760 if (m3->mc_ki[0] >= nkeys) {
8765 m3->mc_pg[0] = mc->mc_pg[0];
8769 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8770 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8771 m3->mc_ki[mc->mc_top]++;
8772 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8773 m3->mc_pg[mc->mc_top] = rp;
8774 m3->mc_ki[mc->mc_top] -= nkeys;
8775 for (i=0; i<mc->mc_top; i++) {
8776 m3->mc_ki[i] = mn.mc_ki[i];
8777 m3->mc_pg[i] = mn.mc_pg[i];
8780 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8781 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8784 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
8785 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8788 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8791 if (copy) /* tmp page */
8792 mdb_page_free(env, copy);
8794 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8799 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8800 MDB_val *key, MDB_val *data, unsigned int flags)
8806 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8809 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8812 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8813 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8815 mdb_cursor_init(&mc, txn, dbi, &mx);
8816 mc.mc_next = txn->mt_cursors[dbi];
8817 txn->mt_cursors[dbi] = &mc;
8818 rc = mdb_cursor_put(&mc, key, data, flags);
8819 txn->mt_cursors[dbi] = mc.mc_next;
8824 #define MDB_WBUF (1024*1024)
8826 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
8828 /** State needed for a double-buffering compacting copy. */
8829 typedef struct mdb_copy {
8832 pthread_mutex_t mc_mutex;
8833 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
8838 pgno_t mc_next_pgno;
8840 int mc_toggle; /**< Buffer number in provider */
8841 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
8842 /** Error code. Never cleared if set. Both threads can set nonzero
8843 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
8845 volatile int mc_error;
8848 /** Dedicated writer thread for compacting copy. */
8849 static THREAD_RET ESECT CALL_CONV
8850 mdb_env_copythr(void *arg)
8854 int toggle = 0, wsize, rc;
8857 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8860 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8863 pthread_mutex_lock(&my->mc_mutex);
8866 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8867 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
8869 wsize = my->mc_wlen[toggle];
8870 ptr = my->mc_wbuf[toggle];
8873 while (wsize > 0 && !my->mc_error) {
8874 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8878 } else if (len > 0) {
8891 /* If there's an overflow page tail, write it too */
8892 if (my->mc_olen[toggle]) {
8893 wsize = my->mc_olen[toggle];
8894 ptr = my->mc_over[toggle];
8895 my->mc_olen[toggle] = 0;
8898 my->mc_wlen[toggle] = 0;
8900 /* Return the empty buffer to provider */
8902 pthread_cond_signal(&my->mc_cond);
8904 pthread_mutex_unlock(&my->mc_mutex);
8905 return (THREAD_RET)0;
8909 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
8911 * @param[in] my control structure.
8912 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
8915 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
8917 pthread_mutex_lock(&my->mc_mutex);
8918 my->mc_new += adjust;
8919 pthread_cond_signal(&my->mc_cond);
8920 while (my->mc_new & 2) /* both buffers in use */
8921 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8922 pthread_mutex_unlock(&my->mc_mutex);
8924 my->mc_toggle ^= (adjust & 1);
8925 /* Both threads reset mc_wlen, to be safe from threading errors */
8926 my->mc_wlen[my->mc_toggle] = 0;
8927 return my->mc_error;
8930 /** Depth-first tree traversal for compacting copy.
8931 * @param[in] my control structure.
8932 * @param[in,out] pg database root.
8933 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
8936 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8938 MDB_cursor mc = {0};
8940 MDB_page *mo, *mp, *leaf;
8945 /* Empty DB, nothing to do */
8946 if (*pg == P_INVALID)
8950 mc.mc_txn = my->mc_txn;
8952 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
8955 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8959 /* Make cursor pages writable */
8960 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8964 for (i=0; i<mc.mc_top; i++) {
8965 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8966 mc.mc_pg[i] = (MDB_page *)ptr;
8967 ptr += my->mc_env->me_psize;
8970 /* This is writable space for a leaf page. Usually not needed. */
8971 leaf = (MDB_page *)ptr;
8973 toggle = my->mc_toggle;
8974 while (mc.mc_snum > 0) {
8976 mp = mc.mc_pg[mc.mc_top];
8980 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8981 for (i=0; i<n; i++) {
8982 ni = NODEPTR(mp, i);
8983 if (ni->mn_flags & F_BIGDATA) {
8987 /* Need writable leaf */
8989 mc.mc_pg[mc.mc_top] = leaf;
8990 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8992 ni = NODEPTR(mp, i);
8995 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8996 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
8997 rc = mdb_page_get(&mc, pg, &omp, NULL);
9000 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9001 rc = mdb_env_cthr_toggle(my, 1);
9004 toggle = my->mc_toggle;
9006 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9007 memcpy(mo, omp, my->mc_env->me_psize);
9008 mo->mp_pgno = my->mc_next_pgno;
9009 my->mc_next_pgno += omp->mp_pages;
9010 my->mc_wlen[toggle] += my->mc_env->me_psize;
9011 if (omp->mp_pages > 1) {
9012 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9013 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9014 rc = mdb_env_cthr_toggle(my, 1);
9017 toggle = my->mc_toggle;
9019 } else if (ni->mn_flags & F_SUBDATA) {
9022 /* Need writable leaf */
9024 mc.mc_pg[mc.mc_top] = leaf;
9025 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9027 ni = NODEPTR(mp, i);
9030 memcpy(&db, NODEDATA(ni), sizeof(db));
9031 my->mc_toggle = toggle;
9032 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9035 toggle = my->mc_toggle;
9036 memcpy(NODEDATA(ni), &db, sizeof(db));
9041 mc.mc_ki[mc.mc_top]++;
9042 if (mc.mc_ki[mc.mc_top] < n) {
9045 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9047 rc = mdb_page_get(&mc, pg, &mp, NULL);
9052 mc.mc_ki[mc.mc_top] = 0;
9053 if (IS_BRANCH(mp)) {
9054 /* Whenever we advance to a sibling branch page,
9055 * we must proceed all the way down to its first leaf.
9057 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9060 mc.mc_pg[mc.mc_top] = mp;
9064 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9065 rc = mdb_env_cthr_toggle(my, 1);
9068 toggle = my->mc_toggle;
9070 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9071 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9072 mo->mp_pgno = my->mc_next_pgno++;
9073 my->mc_wlen[toggle] += my->mc_env->me_psize;
9075 /* Update parent if there is one */
9076 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9077 SETPGNO(ni, mo->mp_pgno);
9078 mdb_cursor_pop(&mc);
9080 /* Otherwise we're done */
9090 /** Copy environment with compaction. */
9092 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9097 MDB_txn *txn = NULL;
9099 pgno_t root, new_root;
9100 int rc = MDB_SUCCESS;
9103 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9104 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9108 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9109 if (my.mc_wbuf[0] == NULL) {
9110 /* _aligned_malloc() sets errno, but we use Windows error codes */
9111 rc = ERROR_NOT_ENOUGH_MEMORY;
9115 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9117 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9119 #ifdef HAVE_MEMALIGN
9120 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9121 if (my.mc_wbuf[0] == NULL) {
9128 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9134 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9135 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9136 my.mc_next_pgno = NUM_METAS;
9139 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9143 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9147 mp = (MDB_page *)my.mc_wbuf[0];
9148 memset(mp, 0, NUM_METAS * env->me_psize);
9150 mp->mp_flags = P_META;
9151 mm = (MDB_meta *)METADATA(mp);
9152 mdb_env_init_meta0(env, mm);
9153 mm->mm_address = env->me_metas[0]->mm_address;
9155 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9157 mp->mp_flags = P_META;
9158 *(MDB_meta *)METADATA(mp) = *mm;
9159 mm = (MDB_meta *)METADATA(mp);
9161 /* Set metapage 1 with current main DB */
9162 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9163 if (root != P_INVALID) {
9164 /* Count free pages + freeDB pages. Subtract from last_pg
9165 * to find the new last_pg, which also becomes the new root.
9167 MDB_ID freecount = 0;
9170 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9171 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9172 freecount += *(MDB_ID *)data.mv_data;
9173 if (rc != MDB_NOTFOUND)
9175 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9176 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9177 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9179 new_root = txn->mt_next_pgno - 1 - freecount;
9180 mm->mm_last_pg = new_root;
9181 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9182 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9184 /* When the DB is empty, handle it specially to
9185 * fix any breakage like page leaks from ITS#8174.
9187 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9189 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9190 mm->mm_txnid = 1; /* use metapage 1 */
9193 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9195 rc = mdb_env_cwalk(&my, &root, 0);
9196 if (rc == MDB_SUCCESS && root != new_root) {
9197 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9203 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9204 rc = THREAD_FINISH(thr);
9209 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9210 if (my.mc_cond) CloseHandle(my.mc_cond);
9211 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9213 free(my.mc_wbuf[0]);
9214 pthread_cond_destroy(&my.mc_cond);
9216 pthread_mutex_destroy(&my.mc_mutex);
9218 return rc ? rc : my.mc_error;
9221 /** Copy environment as-is. */
9223 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9225 MDB_txn *txn = NULL;
9226 mdb_mutexref_t wmutex = NULL;
9232 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9236 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9239 /* Do the lock/unlock of the reader mutex before starting the
9240 * write txn. Otherwise other read txns could block writers.
9242 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9247 /* We must start the actual read txn after blocking writers */
9248 mdb_txn_end(txn, MDB_END_RESET_TMP);
9250 /* Temporarily block writers until we snapshot the meta pages */
9251 wmutex = env->me_wmutex;
9252 if (LOCK_MUTEX(rc, env, wmutex))
9255 rc = mdb_txn_renew0(txn);
9257 UNLOCK_MUTEX(wmutex);
9262 wsize = env->me_psize * NUM_METAS;
9266 DO_WRITE(rc, fd, ptr, w2, len);
9270 } else if (len > 0) {
9276 /* Non-blocking or async handles are not supported */
9282 UNLOCK_MUTEX(wmutex);
9287 w3 = txn->mt_next_pgno * env->me_psize;
9290 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9297 if (wsize > MAX_WRITE)
9301 DO_WRITE(rc, fd, ptr, w2, len);
9305 } else if (len > 0) {
9322 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9324 if (flags & MDB_CP_COMPACT)
9325 return mdb_env_copyfd1(env, fd);
9327 return mdb_env_copyfd0(env, fd);
9331 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9333 return mdb_env_copyfd2(env, fd, 0);
9337 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9341 HANDLE newfd = INVALID_HANDLE_VALUE;
9346 if (env->me_flags & MDB_NOSUBDIR) {
9347 lpath = (char *)path;
9350 len += sizeof(DATANAME);
9351 lpath = malloc(len);
9354 sprintf(lpath, "%s" DATANAME, path);
9357 /* The destination path must exist, but the destination file must not.
9358 * We don't want the OS to cache the writes, since the source data is
9359 * already in the OS cache.
9362 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
9365 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9366 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9369 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9371 if (newfd == INVALID_HANDLE_VALUE) {
9376 if (env->me_psize >= env->me_os_psize) {
9378 /* Set O_DIRECT if the file system supports it */
9379 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9380 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9382 #ifdef F_NOCACHE /* __APPLE__ */
9383 rc = fcntl(newfd, F_NOCACHE, 1);
9391 rc = mdb_env_copyfd2(env, newfd, flags);
9394 if (!(env->me_flags & MDB_NOSUBDIR))
9396 if (newfd != INVALID_HANDLE_VALUE)
9397 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9404 mdb_env_copy(MDB_env *env, const char *path)
9406 return mdb_env_copy2(env, path, 0);
9410 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9412 if (flag & ~CHANGEABLE)
9415 env->me_flags |= flag;
9417 env->me_flags &= ~flag;
9422 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9427 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9432 mdb_env_set_userctx(MDB_env *env, void *ctx)
9436 env->me_userctx = ctx;
9441 mdb_env_get_userctx(MDB_env *env)
9443 return env ? env->me_userctx : NULL;
9447 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9452 env->me_assert_func = func;
9458 mdb_env_get_path(MDB_env *env, const char **arg)
9463 *arg = env->me_path;
9468 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9477 /** Common code for #mdb_stat() and #mdb_env_stat().
9478 * @param[in] env the environment to operate in.
9479 * @param[in] db the #MDB_db record containing the stats to return.
9480 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9481 * @return 0, this function always succeeds.
9484 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9486 arg->ms_psize = env->me_psize;
9487 arg->ms_depth = db->md_depth;
9488 arg->ms_branch_pages = db->md_branch_pages;
9489 arg->ms_leaf_pages = db->md_leaf_pages;
9490 arg->ms_overflow_pages = db->md_overflow_pages;
9491 arg->ms_entries = db->md_entries;
9497 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9501 if (env == NULL || arg == NULL)
9504 meta = mdb_env_pick_meta(env);
9506 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9510 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9514 if (env == NULL || arg == NULL)
9517 meta = mdb_env_pick_meta(env);
9518 arg->me_mapaddr = meta->mm_address;
9519 arg->me_last_pgno = meta->mm_last_pg;
9520 arg->me_last_txnid = meta->mm_txnid;
9522 arg->me_mapsize = env->me_mapsize;
9523 arg->me_maxreaders = env->me_maxreaders;
9524 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9528 /** Set the default comparison functions for a database.
9529 * Called immediately after a database is opened to set the defaults.
9530 * The user can then override them with #mdb_set_compare() or
9531 * #mdb_set_dupsort().
9532 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9533 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9536 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9538 uint16_t f = txn->mt_dbs[dbi].md_flags;
9540 txn->mt_dbxs[dbi].md_cmp =
9541 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9542 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9544 txn->mt_dbxs[dbi].md_dcmp =
9545 !(f & MDB_DUPSORT) ? 0 :
9546 ((f & MDB_INTEGERDUP)
9547 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9548 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9551 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9557 int rc, dbflag, exact;
9558 unsigned int unused = 0, seq;
9562 if (flags & ~VALID_FLAGS)
9564 if (txn->mt_flags & MDB_TXN_BLOCKED)
9570 if (flags & PERSISTENT_FLAGS) {
9571 uint16_t f2 = flags & PERSISTENT_FLAGS;
9572 /* make sure flag changes get committed */
9573 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9574 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9575 txn->mt_flags |= MDB_TXN_DIRTY;
9578 mdb_default_cmp(txn, MAIN_DBI);
9582 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9583 mdb_default_cmp(txn, MAIN_DBI);
9586 /* Is the DB already open? */
9588 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9589 if (!txn->mt_dbxs[i].md_name.mv_size) {
9590 /* Remember this free slot */
9591 if (!unused) unused = i;
9594 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9595 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9601 /* If no free slot and max hit, fail */
9602 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9603 return MDB_DBS_FULL;
9605 /* Cannot mix named databases with some mainDB flags */
9606 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9607 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9609 /* Find the DB info */
9610 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9613 key.mv_data = (void *)name;
9614 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9615 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9616 if (rc == MDB_SUCCESS) {
9617 /* make sure this is actually a DB */
9618 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9619 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9620 return MDB_INCOMPATIBLE;
9621 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
9625 /* Done here so we cannot fail after creating a new DB */
9626 if ((namedup = strdup(name)) == NULL)
9630 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9631 data.mv_size = sizeof(MDB_db);
9632 data.mv_data = &dummy;
9633 memset(&dummy, 0, sizeof(dummy));
9634 dummy.md_root = P_INVALID;
9635 dummy.md_flags = flags & PERSISTENT_FLAGS;
9636 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9643 /* Got info, register DBI in this txn */
9644 unsigned int slot = unused ? unused : txn->mt_numdbs;
9645 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9646 txn->mt_dbxs[slot].md_name.mv_size = len;
9647 txn->mt_dbxs[slot].md_rel = NULL;
9648 txn->mt_dbflags[slot] = dbflag;
9649 /* txn-> and env-> are the same in read txns, use
9650 * tmp variable to avoid undefined assignment
9652 seq = ++txn->mt_env->me_dbiseqs[slot];
9653 txn->mt_dbiseqs[slot] = seq;
9655 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9657 mdb_default_cmp(txn, slot);
9667 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9669 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9672 if (txn->mt_flags & MDB_TXN_BLOCKED)
9675 if (txn->mt_dbflags[dbi] & DB_STALE) {
9678 /* Stale, must read the DB's root. cursor_init does it for us. */
9679 mdb_cursor_init(&mc, txn, dbi, &mx);
9681 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9684 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9687 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9689 ptr = env->me_dbxs[dbi].md_name.mv_data;
9690 /* If there was no name, this was already closed */
9692 env->me_dbxs[dbi].md_name.mv_data = NULL;
9693 env->me_dbxs[dbi].md_name.mv_size = 0;
9694 env->me_dbflags[dbi] = 0;
9695 env->me_dbiseqs[dbi]++;
9700 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9702 /* We could return the flags for the FREE_DBI too but what's the point? */
9703 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9705 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9709 /** Add all the DB's pages to the free list.
9710 * @param[in] mc Cursor on the DB to free.
9711 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9712 * @return 0 on success, non-zero on failure.
9715 mdb_drop0(MDB_cursor *mc, int subs)
9719 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9720 if (rc == MDB_SUCCESS) {
9721 MDB_txn *txn = mc->mc_txn;
9726 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9727 * This also avoids any P_LEAF2 pages, which have no nodes.
9728 * Also if the DB doesn't have sub-DBs and has no overflow
9729 * pages, omit scanning leaves.
9731 if ((mc->mc_flags & C_SUB) ||
9732 (!subs && !mc->mc_db->md_overflow_pages))
9735 mdb_cursor_copy(mc, &mx);
9736 while (mc->mc_snum > 0) {
9737 MDB_page *mp = mc->mc_pg[mc->mc_top];
9738 unsigned n = NUMKEYS(mp);
9740 for (i=0; i<n; i++) {
9741 ni = NODEPTR(mp, i);
9742 if (ni->mn_flags & F_BIGDATA) {
9745 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9746 rc = mdb_page_get(mc, pg, &omp, NULL);
9749 mdb_cassert(mc, IS_OVERFLOW(omp));
9750 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9754 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9755 if (!mc->mc_db->md_overflow_pages && !subs)
9757 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9758 mdb_xcursor_init1(mc, ni);
9759 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9764 if (!subs && !mc->mc_db->md_overflow_pages)
9767 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9769 for (i=0; i<n; i++) {
9771 ni = NODEPTR(mp, i);
9774 mdb_midl_xappend(txn->mt_free_pgs, pg);
9779 mc->mc_ki[mc->mc_top] = i;
9780 rc = mdb_cursor_sibling(mc, 1);
9782 if (rc != MDB_NOTFOUND)
9784 /* no more siblings, go back to beginning
9785 * of previous level.
9790 for (i=1; i<mc->mc_snum; i++) {
9792 mc->mc_pg[i] = mx.mc_pg[i];
9797 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9800 txn->mt_flags |= MDB_TXN_ERROR;
9801 } else if (rc == MDB_NOTFOUND) {
9804 mc->mc_flags &= ~C_INITIALIZED;
9808 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9810 MDB_cursor *mc, *m2;
9813 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9816 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9819 if (TXN_DBI_CHANGED(txn, dbi))
9822 rc = mdb_cursor_open(txn, dbi, &mc);
9826 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9827 /* Invalidate the dropped DB's cursors */
9828 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9829 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9833 /* Can't delete the main DB */
9834 if (del && dbi >= CORE_DBS) {
9835 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9837 txn->mt_dbflags[dbi] = DB_STALE;
9838 mdb_dbi_close(txn->mt_env, dbi);
9840 txn->mt_flags |= MDB_TXN_ERROR;
9843 /* reset the DB record, mark it dirty */
9844 txn->mt_dbflags[dbi] |= DB_DIRTY;
9845 txn->mt_dbs[dbi].md_depth = 0;
9846 txn->mt_dbs[dbi].md_branch_pages = 0;
9847 txn->mt_dbs[dbi].md_leaf_pages = 0;
9848 txn->mt_dbs[dbi].md_overflow_pages = 0;
9849 txn->mt_dbs[dbi].md_entries = 0;
9850 txn->mt_dbs[dbi].md_root = P_INVALID;
9852 txn->mt_flags |= MDB_TXN_DIRTY;
9855 mdb_cursor_close(mc);
9859 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9861 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9864 txn->mt_dbxs[dbi].md_cmp = cmp;
9868 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9870 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9873 txn->mt_dbxs[dbi].md_dcmp = cmp;
9877 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9879 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9882 txn->mt_dbxs[dbi].md_rel = rel;
9886 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9888 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9891 txn->mt_dbxs[dbi].md_relctx = ctx;
9896 mdb_env_get_maxkeysize(MDB_env *env)
9898 return ENV_MAXKEY(env);
9902 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9904 unsigned int i, rdrs;
9907 int rc = 0, first = 1;
9911 if (!env->me_txns) {
9912 return func("(no reader locks)\n", ctx);
9914 rdrs = env->me_txns->mti_numreaders;
9915 mr = env->me_txns->mti_readers;
9916 for (i=0; i<rdrs; i++) {
9918 txnid_t txnid = mr[i].mr_txnid;
9919 sprintf(buf, txnid == (txnid_t)-1 ?
9920 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9921 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9924 rc = func(" pid thread txnid\n", ctx);
9928 rc = func(buf, ctx);
9934 rc = func("(no active readers)\n", ctx);
9939 /** Insert pid into list if not already present.
9940 * return -1 if already present.
9943 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9945 /* binary search of pid in list */
9947 unsigned cursor = 1;
9949 unsigned n = ids[0];
9952 unsigned pivot = n >> 1;
9953 cursor = base + pivot + 1;
9954 val = pid - ids[cursor];
9959 } else if ( val > 0 ) {
9964 /* found, so it's a duplicate */
9973 for (n = ids[0]; n > cursor; n--)
9980 mdb_reader_check(MDB_env *env, int *dead)
9986 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9989 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9991 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9993 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
9994 unsigned int i, j, rdrs;
9996 MDB_PID_T *pids, pid;
9997 int rc = MDB_SUCCESS, count = 0;
9999 rdrs = env->me_txns->mti_numreaders;
10000 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10004 mr = env->me_txns->mti_readers;
10005 for (i=0; i<rdrs; i++) {
10006 pid = mr[i].mr_pid;
10007 if (pid && pid != env->me_pid) {
10008 if (mdb_pid_insert(pids, pid) == 0) {
10009 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10010 /* Stale reader found */
10013 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10014 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10016 rdrs = 0; /* the above checked all readers */
10018 /* Recheck, a new process may have reused pid */
10019 if (mdb_reader_pid(env, Pidcheck, pid))
10023 for (; j<rdrs; j++)
10024 if (mr[j].mr_pid == pid) {
10025 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10026 (unsigned) pid, mr[j].mr_txnid));
10031 UNLOCK_MUTEX(rmutex);
10042 #ifdef MDB_ROBUST_SUPPORTED
10043 /** Handle #LOCK_MUTEX0() failure.
10044 * Try to repair the lock file if the mutex owner died.
10045 * @param[in] env the environment handle
10046 * @param[in] mutex LOCK_MUTEX0() mutex
10047 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10048 * @return 0 on success with the mutex locked, or an error code on failure.
10051 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10056 if (rc == MDB_OWNERDEAD) {
10057 /* We own the mutex. Clean up after dead previous owner. */
10059 rlocked = (mutex == env->me_rmutex);
10061 /* Keep mti_txnid updated, otherwise next writer can
10062 * overwrite data which latest meta page refers to.
10064 meta = mdb_env_pick_meta(env);
10065 env->me_txns->mti_txnid = meta->mm_txnid;
10066 /* env is hosed if the dead thread was ours */
10068 env->me_flags |= MDB_FATAL_ERROR;
10069 env->me_txn = NULL;
10073 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10074 (rc ? "this process' env is hosed" : "recovering")));
10075 rc2 = mdb_reader_check0(env, rlocked, NULL);
10077 rc2 = mdb_mutex_consistent(mutex);
10078 if (rc || (rc = rc2)) {
10079 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10080 UNLOCK_MUTEX(mutex);
10086 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10091 #endif /* MDB_ROBUST_SUPPORTED */
10094 #if defined(_WIN32)
10095 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10099 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10100 if (need == 0xFFFD)
10104 result = malloc(sizeof(wchar_t) * need);
10107 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10113 #endif /* defined(_WIN32) */