2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2014 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
93 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
94 #include <netinet/in.h>
95 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
98 #if defined(__APPLE__) || defined (BSD)
99 # define MDB_USE_POSIX_SEM 1
100 # define MDB_FDATASYNC fsync
101 #elif defined(ANDROID)
102 # define MDB_FDATASYNC fsync
107 #ifdef MDB_USE_POSIX_SEM
108 # define MDB_USE_HASH 1
109 #include <semaphore.h>
114 #include <valgrind/memcheck.h>
115 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
116 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
117 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
118 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
119 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
121 #define VGMEMP_CREATE(h,r,z)
122 #define VGMEMP_ALLOC(h,a,s)
123 #define VGMEMP_FREE(h,a)
124 #define VGMEMP_DESTROY(h)
125 #define VGMEMP_DEFINED(a,s)
129 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
130 /* Solaris just defines one or the other */
131 # define LITTLE_ENDIAN 1234
132 # define BIG_ENDIAN 4321
133 # ifdef _LITTLE_ENDIAN
134 # define BYTE_ORDER LITTLE_ENDIAN
136 # define BYTE_ORDER BIG_ENDIAN
139 # define BYTE_ORDER __BYTE_ORDER
143 #ifndef LITTLE_ENDIAN
144 #define LITTLE_ENDIAN __LITTLE_ENDIAN
147 #define BIG_ENDIAN __BIG_ENDIAN
150 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
151 #define MISALIGNED_OK 1
157 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
158 # error "Unknown or unsupported endianness (BYTE_ORDER)"
159 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
160 # error "Two's complement, reasonably sized integer types, please"
164 /** Put infrequently used env functions in separate section */
166 # define ESECT __attribute__ ((section("__TEXT,text_env")))
168 # define ESECT __attribute__ ((section("text_env")))
174 /** @defgroup internal LMDB Internals
177 /** @defgroup compat Compatibility Macros
178 * A bunch of macros to minimize the amount of platform-specific ifdefs
179 * needed throughout the rest of the code. When the features this library
180 * needs are similar enough to POSIX to be hidden in a one-or-two line
181 * replacement, this macro approach is used.
185 /** Features under development */
190 /** Wrapper around __func__, which is a C99 feature */
191 #if __STDC_VERSION__ >= 199901L
192 # define mdb_func_ __func__
193 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
194 # define mdb_func_ __FUNCTION__
196 /* If a debug message says <mdb_unknown>(), update the #if statements above */
197 # define mdb_func_ "<mdb_unknown>"
201 #define MDB_USE_HASH 1
202 #define MDB_PIDLOCK 0
203 #define THREAD_RET DWORD
204 #define pthread_t HANDLE
205 #define pthread_mutex_t HANDLE
206 #define pthread_cond_t HANDLE
207 #define pthread_key_t DWORD
208 #define pthread_self() GetCurrentThreadId()
209 #define pthread_key_create(x,y) \
210 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
211 #define pthread_key_delete(x) TlsFree(x)
212 #define pthread_getspecific(x) TlsGetValue(x)
213 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
214 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
215 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
216 #define pthread_cond_signal(x) SetEvent(*x)
217 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
218 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
219 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
220 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_rmutex)
221 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_rmutex)
222 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_wmutex)
223 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_wmutex)
224 #define getpid() GetCurrentProcessId()
225 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
226 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
227 #define ErrCode() GetLastError()
228 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
229 #define close(fd) (CloseHandle(fd) ? 0 : -1)
230 #define munmap(ptr,len) UnmapViewOfFile(ptr)
231 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
232 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
234 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
238 #define THREAD_RET void *
239 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
240 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
241 #define Z "z" /**< printf format modifier for size_t */
243 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
244 #define MDB_PIDLOCK 1
246 #ifdef MDB_USE_POSIX_SEM
248 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
249 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
250 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
251 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
254 mdb_sem_wait(sem_t *sem)
257 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
262 /** Lock the reader mutex.
264 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
265 /** Unlock the reader mutex.
267 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
269 /** Lock the writer mutex.
270 * Only a single write transaction is allowed at a time. Other writers
271 * will block waiting for this mutex.
273 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
274 /** Unlock the writer mutex.
276 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
277 #endif /* MDB_USE_POSIX_SEM */
279 /** Get the error code for the last failed system function.
281 #define ErrCode() errno
283 /** An abstraction for a file handle.
284 * On POSIX systems file handles are small integers. On Windows
285 * they're opaque pointers.
289 /** A value for an invalid file handle.
290 * Mainly used to initialize file variables and signify that they are
293 #define INVALID_HANDLE_VALUE (-1)
295 /** Get the size of a memory page for the system.
296 * This is the basic size that the platform's memory manager uses, and is
297 * fundamental to the use of memory-mapped files.
299 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
302 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
305 #define MNAME_LEN (sizeof(pthread_mutex_t))
311 /** A flag for opening a file and requesting synchronous data writes.
312 * This is only used when writing a meta page. It's not strictly needed;
313 * we could just do a normal write and then immediately perform a flush.
314 * But if this flag is available it saves us an extra system call.
316 * @note If O_DSYNC is undefined but exists in /usr/include,
317 * preferably set some compiler flag to get the definition.
318 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
321 # define MDB_DSYNC O_DSYNC
325 /** Function for flushing the data of a file. Define this to fsync
326 * if fdatasync() is not supported.
328 #ifndef MDB_FDATASYNC
329 # define MDB_FDATASYNC fdatasync
333 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
344 /** A page number in the database.
345 * Note that 64 bit page numbers are overkill, since pages themselves
346 * already represent 12-13 bits of addressable memory, and the OS will
347 * always limit applications to a maximum of 63 bits of address space.
349 * @note In the #MDB_node structure, we only store 48 bits of this value,
350 * which thus limits us to only 60 bits of addressable data.
352 typedef MDB_ID pgno_t;
354 /** A transaction ID.
355 * See struct MDB_txn.mt_txnid for details.
357 typedef MDB_ID txnid_t;
359 /** @defgroup debug Debug Macros
363 /** Enable debug output. Needs variable argument macros (a C99 feature).
364 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
365 * read from and written to the database (used for free space management).
371 static int mdb_debug;
372 static txnid_t mdb_debug_start;
374 /** Print a debug message with printf formatting.
375 * Requires double parenthesis around 2 or more args.
377 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
378 # define DPRINTF0(fmt, ...) \
379 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
381 # define DPRINTF(args) ((void) 0)
383 /** Print a debug string.
384 * The string is printed literally, with no format processing.
386 #define DPUTS(arg) DPRINTF(("%s", arg))
387 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
389 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
392 /** @brief The maximum size of a database page.
394 * It is 32k or 64k, since value-PAGEBASE must fit in
395 * #MDB_page.%mp_upper.
397 * LMDB will use database pages < OS pages if needed.
398 * That causes more I/O in write transactions: The OS must
399 * know (read) the whole page before writing a partial page.
401 * Note that we don't currently support Huge pages. On Linux,
402 * regular data files cannot use Huge pages, and in general
403 * Huge pages aren't actually pageable. We rely on the OS
404 * demand-pager to read our data and page it out when memory
405 * pressure from other processes is high. So until OSs have
406 * actual paging support for Huge pages, they're not viable.
408 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
410 /** The minimum number of keys required in a database page.
411 * Setting this to a larger value will place a smaller bound on the
412 * maximum size of a data item. Data items larger than this size will
413 * be pushed into overflow pages instead of being stored directly in
414 * the B-tree node. This value used to default to 4. With a page size
415 * of 4096 bytes that meant that any item larger than 1024 bytes would
416 * go into an overflow page. That also meant that on average 2-3KB of
417 * each overflow page was wasted space. The value cannot be lower than
418 * 2 because then there would no longer be a tree structure. With this
419 * value, items larger than 2KB will go into overflow pages, and on
420 * average only 1KB will be wasted.
422 #define MDB_MINKEYS 2
424 /** A stamp that identifies a file as an LMDB file.
425 * There's nothing special about this value other than that it is easily
426 * recognizable, and it will reflect any byte order mismatches.
428 #define MDB_MAGIC 0xBEEFC0DE
430 /** The version number for a database's datafile format. */
431 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
432 /** The version number for a database's lockfile format. */
433 #define MDB_LOCK_VERSION 1
435 /** @brief The max size of a key we can write, or 0 for dynamic max.
437 * Define this as 0 to compute the max from the page size. 511
438 * is default for backwards compat: liblmdb <= 0.9.10 can break
439 * when modifying a DB with keys/dupsort data bigger than its max.
440 * #MDB_DEVEL sets the default to 0.
442 * Data items in an #MDB_DUPSORT database are also limited to
443 * this size, since they're actually keys of a sub-DB. Keys and
444 * #MDB_DUPSORT data items must fit on a node in a regular page.
446 #ifndef MDB_MAXKEYSIZE
447 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
450 /** The maximum size of a key we can write to the environment. */
452 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
454 #define ENV_MAXKEY(env) ((env)->me_maxkey)
457 /** @brief The maximum size of a data item.
459 * We only store a 32 bit value for node sizes.
461 #define MAXDATASIZE 0xffffffffUL
464 /** Key size which fits in a #DKBUF.
467 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
470 * This is used for printing a hex dump of a key's contents.
472 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
473 /** Display a key in hex.
475 * Invoke a function to display a key in hex.
477 #define DKEY(x) mdb_dkey(x, kbuf)
483 /** An invalid page number.
484 * Mainly used to denote an empty tree.
486 #define P_INVALID (~(pgno_t)0)
488 /** Test if the flags \b f are set in a flag word \b w. */
489 #define F_ISSET(w, f) (((w) & (f)) == (f))
491 /** Round \b n up to an even number. */
492 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
494 /** Used for offsets within a single page.
495 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
498 typedef uint16_t indx_t;
500 /** Default size of memory map.
501 * This is certainly too small for any actual applications. Apps should always set
502 * the size explicitly using #mdb_env_set_mapsize().
504 #define DEFAULT_MAPSIZE 1048576
506 /** @defgroup readers Reader Lock Table
507 * Readers don't acquire any locks for their data access. Instead, they
508 * simply record their transaction ID in the reader table. The reader
509 * mutex is needed just to find an empty slot in the reader table. The
510 * slot's address is saved in thread-specific data so that subsequent read
511 * transactions started by the same thread need no further locking to proceed.
513 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
515 * No reader table is used if the database is on a read-only filesystem, or
516 * if #MDB_NOLOCK is set.
518 * Since the database uses multi-version concurrency control, readers don't
519 * actually need any locking. This table is used to keep track of which
520 * readers are using data from which old transactions, so that we'll know
521 * when a particular old transaction is no longer in use. Old transactions
522 * that have discarded any data pages can then have those pages reclaimed
523 * for use by a later write transaction.
525 * The lock table is constructed such that reader slots are aligned with the
526 * processor's cache line size. Any slot is only ever used by one thread.
527 * This alignment guarantees that there will be no contention or cache
528 * thrashing as threads update their own slot info, and also eliminates
529 * any need for locking when accessing a slot.
531 * A writer thread will scan every slot in the table to determine the oldest
532 * outstanding reader transaction. Any freed pages older than this will be
533 * reclaimed by the writer. The writer doesn't use any locks when scanning
534 * this table. This means that there's no guarantee that the writer will
535 * see the most up-to-date reader info, but that's not required for correct
536 * operation - all we need is to know the upper bound on the oldest reader,
537 * we don't care at all about the newest reader. So the only consequence of
538 * reading stale information here is that old pages might hang around a
539 * while longer before being reclaimed. That's actually good anyway, because
540 * the longer we delay reclaiming old pages, the more likely it is that a
541 * string of contiguous pages can be found after coalescing old pages from
542 * many old transactions together.
545 /** Number of slots in the reader table.
546 * This value was chosen somewhat arbitrarily. 126 readers plus a
547 * couple mutexes fit exactly into 8KB on my development machine.
548 * Applications should set the table size using #mdb_env_set_maxreaders().
550 #define DEFAULT_READERS 126
552 /** The size of a CPU cache line in bytes. We want our lock structures
553 * aligned to this size to avoid false cache line sharing in the
555 * This value works for most CPUs. For Itanium this should be 128.
561 /** The information we store in a single slot of the reader table.
562 * In addition to a transaction ID, we also record the process and
563 * thread ID that owns a slot, so that we can detect stale information,
564 * e.g. threads or processes that went away without cleaning up.
565 * @note We currently don't check for stale records. We simply re-init
566 * the table when we know that we're the only process opening the
569 typedef struct MDB_rxbody {
570 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
571 * Multiple readers that start at the same time will probably have the
572 * same ID here. Again, it's not important to exclude them from
573 * anything; all we need to know is which version of the DB they
574 * started from so we can avoid overwriting any data used in that
575 * particular version.
578 /** The process ID of the process owning this reader txn. */
580 /** The thread ID of the thread owning this txn. */
584 /** The actual reader record, with cacheline padding. */
585 typedef struct MDB_reader {
588 /** shorthand for mrb_txnid */
589 #define mr_txnid mru.mrx.mrb_txnid
590 #define mr_pid mru.mrx.mrb_pid
591 #define mr_tid mru.mrx.mrb_tid
592 /** cache line alignment */
593 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
597 /** The header for the reader table.
598 * The table resides in a memory-mapped file. (This is a different file
599 * than is used for the main database.)
601 * For POSIX the actual mutexes reside in the shared memory of this
602 * mapped file. On Windows, mutexes are named objects allocated by the
603 * kernel; we store the mutex names in this mapped file so that other
604 * processes can grab them. This same approach is also used on
605 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
606 * process-shared POSIX mutexes. For these cases where a named object
607 * is used, the object name is derived from a 64 bit FNV hash of the
608 * environment pathname. As such, naming collisions are extremely
609 * unlikely. If a collision occurs, the results are unpredictable.
611 typedef struct MDB_txbody {
612 /** Stamp identifying this as an LMDB file. It must be set
615 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
617 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
618 char mtb_rmname[MNAME_LEN];
620 /** Mutex protecting access to this table.
621 * This is the reader lock that #LOCK_MUTEX_R acquires.
623 pthread_mutex_t mtb_mutex;
625 /** The ID of the last transaction committed to the database.
626 * This is recorded here only for convenience; the value can always
627 * be determined by reading the main database meta pages.
630 /** The number of slots that have been used in the reader table.
631 * This always records the maximum count, it is not decremented
632 * when readers release their slots.
634 unsigned mtb_numreaders;
637 /** The actual reader table definition. */
638 typedef struct MDB_txninfo {
641 #define mti_magic mt1.mtb.mtb_magic
642 #define mti_format mt1.mtb.mtb_format
643 #define mti_mutex mt1.mtb.mtb_mutex
644 #define mti_rmname mt1.mtb.mtb_rmname
645 #define mti_txnid mt1.mtb.mtb_txnid
646 #define mti_numreaders mt1.mtb.mtb_numreaders
647 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
650 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
651 char mt2_wmname[MNAME_LEN];
652 #define mti_wmname mt2.mt2_wmname
654 pthread_mutex_t mt2_wmutex;
655 #define mti_wmutex mt2.mt2_wmutex
657 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
659 MDB_reader mti_readers[1];
662 /** Lockfile format signature: version, features and field layout */
663 #define MDB_LOCK_FORMAT \
665 ((MDB_LOCK_VERSION) \
666 /* Flags which describe functionality */ \
667 + (((MDB_PIDLOCK) != 0) << 16)))
670 /** Common header for all page types.
671 * Overflow records occupy a number of contiguous pages with no
672 * headers on any page after the first.
674 typedef struct MDB_page {
675 #define mp_pgno mp_p.p_pgno
676 #define mp_next mp_p.p_next
678 pgno_t p_pgno; /**< page number */
679 struct MDB_page *p_next; /**< for in-memory list of freed pages */
682 /** @defgroup mdb_page Page Flags
684 * Flags for the page headers.
687 #define P_BRANCH 0x01 /**< branch page */
688 #define P_LEAF 0x02 /**< leaf page */
689 #define P_OVERFLOW 0x04 /**< overflow page */
690 #define P_META 0x08 /**< meta page */
691 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
692 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
693 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
694 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
695 #define P_KEEP 0x8000 /**< leave this page alone during spill */
697 uint16_t mp_flags; /**< @ref mdb_page */
698 #define mp_lower mp_pb.pb.pb_lower
699 #define mp_upper mp_pb.pb.pb_upper
700 #define mp_pages mp_pb.pb_pages
703 indx_t pb_lower; /**< lower bound of free space */
704 indx_t pb_upper; /**< upper bound of free space */
706 uint32_t pb_pages; /**< number of overflow pages */
708 indx_t mp_ptrs[1]; /**< dynamic size */
711 /** Size of the page header, excluding dynamic data at the end */
712 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
714 /** Address of first usable data byte in a page, after the header */
715 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
717 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
718 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
720 /** Number of nodes on a page */
721 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
723 /** The amount of space remaining in the page */
724 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
726 /** The percentage of space used in the page, in tenths of a percent. */
727 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
728 ((env)->me_psize - PAGEHDRSZ))
729 /** The minimum page fill factor, in tenths of a percent.
730 * Pages emptier than this are candidates for merging.
732 #define FILL_THRESHOLD 250
734 /** Test if a page is a leaf page */
735 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
736 /** Test if a page is a LEAF2 page */
737 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
738 /** Test if a page is a branch page */
739 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
740 /** Test if a page is an overflow page */
741 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
742 /** Test if a page is a sub page */
743 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
745 /** The number of overflow pages needed to store the given size. */
746 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
748 /** Link in #MDB_txn.%mt_loose_pgs list */
749 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
751 /** Header for a single key/data pair within a page.
752 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
753 * We guarantee 2-byte alignment for 'MDB_node's.
755 typedef struct MDB_node {
756 /** lo and hi are used for data size on leaf nodes and for
757 * child pgno on branch nodes. On 64 bit platforms, flags
758 * is also used for pgno. (Branch nodes have no flags).
759 * They are in host byte order in case that lets some
760 * accesses be optimized into a 32-bit word access.
762 #if BYTE_ORDER == LITTLE_ENDIAN
763 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
765 unsigned short mn_hi, mn_lo;
767 /** @defgroup mdb_node Node Flags
769 * Flags for node headers.
772 #define F_BIGDATA 0x01 /**< data put on overflow page */
773 #define F_SUBDATA 0x02 /**< data is a sub-database */
774 #define F_DUPDATA 0x04 /**< data has duplicates */
776 /** valid flags for #mdb_node_add() */
777 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
780 unsigned short mn_flags; /**< @ref mdb_node */
781 unsigned short mn_ksize; /**< key size */
782 char mn_data[1]; /**< key and data are appended here */
785 /** Size of the node header, excluding dynamic data at the end */
786 #define NODESIZE offsetof(MDB_node, mn_data)
788 /** Bit position of top word in page number, for shifting mn_flags */
789 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
791 /** Size of a node in a branch page with a given key.
792 * This is just the node header plus the key, there is no data.
794 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
796 /** Size of a node in a leaf page with a given key and data.
797 * This is node header plus key plus data size.
799 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
801 /** Address of node \b i in page \b p */
802 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
804 /** Address of the key for the node */
805 #define NODEKEY(node) (void *)((node)->mn_data)
807 /** Address of the data for a node */
808 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
810 /** Get the page number pointed to by a branch node */
811 #define NODEPGNO(node) \
812 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
813 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
814 /** Set the page number in a branch node */
815 #define SETPGNO(node,pgno) do { \
816 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
817 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
819 /** Get the size of the data in a leaf node */
820 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
821 /** Set the size of the data for a leaf node */
822 #define SETDSZ(node,size) do { \
823 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
824 /** The size of a key in a node */
825 #define NODEKSZ(node) ((node)->mn_ksize)
827 /** Copy a page number from src to dst */
829 #define COPY_PGNO(dst,src) dst = src
831 #if SIZE_MAX > 4294967295UL
832 #define COPY_PGNO(dst,src) do { \
833 unsigned short *s, *d; \
834 s = (unsigned short *)&(src); \
835 d = (unsigned short *)&(dst); \
842 #define COPY_PGNO(dst,src) do { \
843 unsigned short *s, *d; \
844 s = (unsigned short *)&(src); \
845 d = (unsigned short *)&(dst); \
851 /** The address of a key in a LEAF2 page.
852 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
853 * There are no node headers, keys are stored contiguously.
855 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
857 /** Set the \b node's key into \b keyptr, if requested. */
858 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
859 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
861 /** Set the \b node's key into \b key. */
862 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
864 /** Information about a single database in the environment. */
865 typedef struct MDB_db {
866 uint32_t md_pad; /**< also ksize for LEAF2 pages */
867 uint16_t md_flags; /**< @ref mdb_dbi_open */
868 uint16_t md_depth; /**< depth of this tree */
869 pgno_t md_branch_pages; /**< number of internal pages */
870 pgno_t md_leaf_pages; /**< number of leaf pages */
871 pgno_t md_overflow_pages; /**< number of overflow pages */
872 size_t md_entries; /**< number of data items */
873 pgno_t md_root; /**< the root page of this tree */
876 /** mdb_dbi_open flags */
877 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
878 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
879 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
880 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
882 /** Handle for the DB used to track free pages. */
884 /** Handle for the default DB. */
887 /** Meta page content.
888 * A meta page is the start point for accessing a database snapshot.
889 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
891 typedef struct MDB_meta {
892 /** Stamp identifying this as an LMDB file. It must be set
895 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
897 void *mm_address; /**< address for fixed mapping */
898 size_t mm_mapsize; /**< size of mmap region */
899 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
900 /** The size of pages used in this DB */
901 #define mm_psize mm_dbs[0].md_pad
902 /** Any persistent environment flags. @ref mdb_env */
903 #define mm_flags mm_dbs[0].md_flags
904 pgno_t mm_last_pg; /**< last used page in file */
905 txnid_t mm_txnid; /**< txnid that committed this page */
908 /** Buffer for a stack-allocated meta page.
909 * The members define size and alignment, and silence type
910 * aliasing warnings. They are not used directly; that could
911 * mean incorrectly using several union members in parallel.
913 typedef union MDB_metabuf {
916 char mm_pad[PAGEHDRSZ];
921 /** Auxiliary DB info.
922 * The information here is mostly static/read-only. There is
923 * only a single copy of this record in the environment.
925 typedef struct MDB_dbx {
926 MDB_val md_name; /**< name of the database */
927 MDB_cmp_func *md_cmp; /**< function for comparing keys */
928 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
929 MDB_rel_func *md_rel; /**< user relocate function */
930 void *md_relctx; /**< user-provided context for md_rel */
933 /** A database transaction.
934 * Every operation requires a transaction handle.
937 MDB_txn *mt_parent; /**< parent of a nested txn */
938 MDB_txn *mt_child; /**< nested txn under this txn */
939 pgno_t mt_next_pgno; /**< next unallocated page */
940 /** The ID of this transaction. IDs are integers incrementing from 1.
941 * Only committed write transactions increment the ID. If a transaction
942 * aborts, the ID may be re-used by the next writer.
945 MDB_env *mt_env; /**< the DB environment */
946 /** The list of pages that became unused during this transaction.
949 /** The list of loose pages that became unused and may be reused
950 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
952 MDB_page *mt_loose_pgs;
953 /* #Number of loose pages (#mt_loose_pgs) */
955 /** The sorted list of dirty pages we temporarily wrote to disk
956 * because the dirty list was full. page numbers in here are
957 * shifted left by 1, deleted slots have the LSB set.
959 MDB_IDL mt_spill_pgs;
961 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
963 /** For read txns: This thread/txn's reader table slot, or NULL. */
966 /** Array of records for each DB known in the environment. */
968 /** Array of MDB_db records for each known DB */
970 /** Array of sequence numbers for each DB handle */
971 unsigned int *mt_dbiseqs;
972 /** @defgroup mt_dbflag Transaction DB Flags
976 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
977 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
978 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
979 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
981 /** In write txns, array of cursors for each DB */
982 MDB_cursor **mt_cursors;
983 /** Array of flags for each DB */
984 unsigned char *mt_dbflags;
985 /** Number of DB records in use. This number only ever increments;
986 * we don't decrement it when individual DB handles are closed.
990 /** @defgroup mdb_txn Transaction Flags
994 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
995 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
996 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
997 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
999 unsigned int mt_flags; /**< @ref mdb_txn */
1000 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1001 * Includes ancestor txns' dirty pages not hidden by other txns'
1002 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1003 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1005 unsigned int mt_dirty_room;
1008 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1009 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1010 * raise this on a 64 bit machine.
1012 #define CURSOR_STACK 32
1016 /** Cursors are used for all DB operations.
1017 * A cursor holds a path of (page pointer, key index) from the DB
1018 * root to a position in the DB, plus other state. #MDB_DUPSORT
1019 * cursors include an xcursor to the current data item. Write txns
1020 * track their cursors and keep them up to date when data moves.
1021 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1022 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1025 /** Next cursor on this DB in this txn */
1026 MDB_cursor *mc_next;
1027 /** Backup of the original cursor if this cursor is a shadow */
1028 MDB_cursor *mc_backup;
1029 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1030 struct MDB_xcursor *mc_xcursor;
1031 /** The transaction that owns this cursor */
1033 /** The database handle this cursor operates on */
1035 /** The database record for this cursor */
1037 /** The database auxiliary record for this cursor */
1039 /** The @ref mt_dbflag for this database */
1040 unsigned char *mc_dbflag;
1041 unsigned short mc_snum; /**< number of pushed pages */
1042 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1043 /** @defgroup mdb_cursor Cursor Flags
1045 * Cursor state flags.
1048 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1049 #define C_EOF 0x02 /**< No more data */
1050 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1051 #define C_DEL 0x08 /**< last op was a cursor_del */
1052 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1053 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1055 unsigned int mc_flags; /**< @ref mdb_cursor */
1056 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1057 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1060 /** Context for sorted-dup records.
1061 * We could have gone to a fully recursive design, with arbitrarily
1062 * deep nesting of sub-databases. But for now we only handle these
1063 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1065 typedef struct MDB_xcursor {
1066 /** A sub-cursor for traversing the Dup DB */
1067 MDB_cursor mx_cursor;
1068 /** The database record for this Dup DB */
1070 /** The auxiliary DB record for this Dup DB */
1072 /** The @ref mt_dbflag for this Dup DB */
1073 unsigned char mx_dbflag;
1076 /** State of FreeDB old pages, stored in the MDB_env */
1077 typedef struct MDB_pgstate {
1078 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1079 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1082 /** The database environment. */
1084 HANDLE me_fd; /**< The main data file */
1085 HANDLE me_lfd; /**< The lock file */
1086 HANDLE me_mfd; /**< just for writing the meta pages */
1087 /** Failed to update the meta page. Probably an I/O error. */
1088 #define MDB_FATAL_ERROR 0x80000000U
1089 /** Some fields are initialized. */
1090 #define MDB_ENV_ACTIVE 0x20000000U
1091 /** me_txkey is set */
1092 #define MDB_ENV_TXKEY 0x10000000U
1093 uint32_t me_flags; /**< @ref mdb_env */
1094 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1095 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1096 unsigned int me_maxreaders; /**< size of the reader table */
1097 unsigned int me_numreaders; /**< max numreaders set by this env */
1098 MDB_dbi me_numdbs; /**< number of DBs opened */
1099 MDB_dbi me_maxdbs; /**< size of the DB table */
1100 MDB_PID_T me_pid; /**< process ID of this env */
1101 char *me_path; /**< path to the DB files */
1102 char *me_map; /**< the memory map of the data file */
1103 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1104 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1105 void *me_pbuf; /**< scratch area for DUPSORT put() */
1106 MDB_txn *me_txn; /**< current write transaction */
1107 size_t me_mapsize; /**< size of the data memory map */
1108 off_t me_size; /**< current file size */
1109 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1110 MDB_dbx *me_dbxs; /**< array of static DB info */
1111 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1112 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1113 pthread_key_t me_txkey; /**< thread-key for readers */
1114 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1115 # define me_pglast me_pgstate.mf_pglast
1116 # define me_pghead me_pgstate.mf_pghead
1117 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1118 /** IDL of pages that became unused in a write txn */
1119 MDB_IDL me_free_pgs;
1120 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1121 MDB_ID2L me_dirty_list;
1122 /** Max number of freelist items that can fit in a single overflow page */
1124 /** Max size of a node on a page */
1125 unsigned int me_nodemax;
1126 #if !(MDB_MAXKEYSIZE)
1127 unsigned int me_maxkey; /**< max size of a key */
1129 int me_live_reader; /**< have liveness lock in reader table */
1131 int me_pidquery; /**< Used in OpenProcess */
1132 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1134 #elif defined(MDB_USE_POSIX_SEM)
1135 sem_t *me_rmutex; /* Shared mutexes are not supported */
1138 void *me_userctx; /**< User-settable context */
1139 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1142 /** Nested transaction */
1143 typedef struct MDB_ntxn {
1144 MDB_txn mnt_txn; /**< the transaction */
1145 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1148 /** max number of pages to commit in one writev() call */
1149 #define MDB_COMMIT_PAGES 64
1150 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1151 #undef MDB_COMMIT_PAGES
1152 #define MDB_COMMIT_PAGES IOV_MAX
1155 /** max bytes to write in one call */
1156 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1158 /** Check \b txn and \b dbi arguments to a function */
1159 #define TXN_DBI_EXIST(txn, dbi) \
1160 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1162 /** Check for misused \b dbi handles */
1163 #define TXN_DBI_CHANGED(txn, dbi) \
1164 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1166 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1167 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1168 static int mdb_page_touch(MDB_cursor *mc);
1170 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1171 static int mdb_page_search_root(MDB_cursor *mc,
1172 MDB_val *key, int modify);
1173 #define MDB_PS_MODIFY 1
1174 #define MDB_PS_ROOTONLY 2
1175 #define MDB_PS_FIRST 4
1176 #define MDB_PS_LAST 8
1177 static int mdb_page_search(MDB_cursor *mc,
1178 MDB_val *key, int flags);
1179 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1181 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1182 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1183 pgno_t newpgno, unsigned int nflags);
1185 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1186 static int mdb_env_pick_meta(const MDB_env *env);
1187 static int mdb_env_write_meta(MDB_txn *txn);
1188 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1189 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1191 static void mdb_env_close0(MDB_env *env, int excl);
1193 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1194 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1195 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1196 static void mdb_node_del(MDB_cursor *mc, int ksize);
1197 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1198 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1199 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1200 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1201 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1203 static int mdb_rebalance(MDB_cursor *mc);
1204 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1206 static void mdb_cursor_pop(MDB_cursor *mc);
1207 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1209 static int mdb_cursor_del0(MDB_cursor *mc);
1210 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1211 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1212 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1213 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1214 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1216 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1217 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1219 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1220 static void mdb_xcursor_init0(MDB_cursor *mc);
1221 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1223 static int mdb_drop0(MDB_cursor *mc, int subs);
1224 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1227 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1231 static SECURITY_DESCRIPTOR mdb_null_sd;
1232 static SECURITY_ATTRIBUTES mdb_all_sa;
1233 static int mdb_sec_inited;
1236 /** Return the library version info. */
1238 mdb_version(int *major, int *minor, int *patch)
1240 if (major) *major = MDB_VERSION_MAJOR;
1241 if (minor) *minor = MDB_VERSION_MINOR;
1242 if (patch) *patch = MDB_VERSION_PATCH;
1243 return MDB_VERSION_STRING;
1246 /** Table of descriptions for LMDB @ref errors */
1247 static char *const mdb_errstr[] = {
1248 "MDB_KEYEXIST: Key/data pair already exists",
1249 "MDB_NOTFOUND: No matching key/data pair found",
1250 "MDB_PAGE_NOTFOUND: Requested page not found",
1251 "MDB_CORRUPTED: Located page was wrong type",
1252 "MDB_PANIC: Update of meta page failed",
1253 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1254 "MDB_INVALID: File is not an LMDB file",
1255 "MDB_MAP_FULL: Environment mapsize limit reached",
1256 "MDB_DBS_FULL: Environment maxdbs limit reached",
1257 "MDB_READERS_FULL: Environment maxreaders limit reached",
1258 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1259 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1260 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1261 "MDB_PAGE_FULL: Internal error - page has no more space",
1262 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1263 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1264 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1265 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1266 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1267 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1271 mdb_strerror(int err)
1274 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1275 * This works as long as no function between the call to mdb_strerror
1276 * and the actual use of the message uses more than 4K of stack.
1279 char buf[1024], *ptr = buf;
1283 return ("Successful return: 0");
1285 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1286 i = err - MDB_KEYEXIST;
1287 return mdb_errstr[i];
1291 /* These are the C-runtime error codes we use. The comment indicates
1292 * their numeric value, and the Win32 error they would correspond to
1293 * if the error actually came from a Win32 API. A major mess, we should
1294 * have used LMDB-specific error codes for everything.
1297 case ENOENT: /* 2, FILE_NOT_FOUND */
1298 case EIO: /* 5, ACCESS_DENIED */
1299 case ENOMEM: /* 12, INVALID_ACCESS */
1300 case EACCES: /* 13, INVALID_DATA */
1301 case EBUSY: /* 16, CURRENT_DIRECTORY */
1302 case EINVAL: /* 22, BAD_COMMAND */
1303 case ENOSPC: /* 28, OUT_OF_PAPER */
1304 return strerror(err);
1309 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1310 FORMAT_MESSAGE_IGNORE_INSERTS,
1311 NULL, err, 0, ptr, sizeof(buf), pad);
1314 return strerror(err);
1318 /** assert(3) variant in cursor context */
1319 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1320 /** assert(3) variant in transaction context */
1321 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1322 /** assert(3) variant in environment context */
1323 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1326 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1327 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1330 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1331 const char *func, const char *file, int line)
1334 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1335 file, line, expr_txt, func);
1336 if (env->me_assert_func)
1337 env->me_assert_func(env, buf);
1338 fprintf(stderr, "%s\n", buf);
1342 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1346 /** Return the page number of \b mp which may be sub-page, for debug output */
1348 mdb_dbg_pgno(MDB_page *mp)
1351 COPY_PGNO(ret, mp->mp_pgno);
1355 /** Display a key in hexadecimal and return the address of the result.
1356 * @param[in] key the key to display
1357 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1358 * @return The key in hexadecimal form.
1361 mdb_dkey(MDB_val *key, char *buf)
1364 unsigned char *c = key->mv_data;
1370 if (key->mv_size > DKBUF_MAXKEYSIZE)
1371 return "MDB_MAXKEYSIZE";
1372 /* may want to make this a dynamic check: if the key is mostly
1373 * printable characters, print it as-is instead of converting to hex.
1377 for (i=0; i<key->mv_size; i++)
1378 ptr += sprintf(ptr, "%02x", *c++);
1380 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1386 mdb_leafnode_type(MDB_node *n)
1388 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1389 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1390 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1393 /** Display all the keys in the page. */
1395 mdb_page_list(MDB_page *mp)
1397 pgno_t pgno = mdb_dbg_pgno(mp);
1398 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1400 unsigned int i, nkeys, nsize, total = 0;
1404 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1405 case P_BRANCH: type = "Branch page"; break;
1406 case P_LEAF: type = "Leaf page"; break;
1407 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1408 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1409 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1411 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1412 pgno, mp->mp_pages, state);
1415 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1416 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1419 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1423 nkeys = NUMKEYS(mp);
1424 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1426 for (i=0; i<nkeys; i++) {
1427 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1428 key.mv_size = nsize = mp->mp_pad;
1429 key.mv_data = LEAF2KEY(mp, i, nsize);
1431 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1434 node = NODEPTR(mp, i);
1435 key.mv_size = node->mn_ksize;
1436 key.mv_data = node->mn_data;
1437 nsize = NODESIZE + key.mv_size;
1438 if (IS_BRANCH(mp)) {
1439 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1443 if (F_ISSET(node->mn_flags, F_BIGDATA))
1444 nsize += sizeof(pgno_t);
1446 nsize += NODEDSZ(node);
1448 nsize += sizeof(indx_t);
1449 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1450 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1452 total = EVEN(total);
1454 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1455 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1459 mdb_cursor_chk(MDB_cursor *mc)
1465 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1466 for (i=0; i<mc->mc_top; i++) {
1468 node = NODEPTR(mp, mc->mc_ki[i]);
1469 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1472 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1478 /** Count all the pages in each DB and in the freelist
1479 * and make sure it matches the actual number of pages
1481 * All named DBs must be open for a correct count.
1483 static void mdb_audit(MDB_txn *txn)
1487 MDB_ID freecount, count;
1492 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1493 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1494 freecount += *(MDB_ID *)data.mv_data;
1495 mdb_tassert(txn, rc == MDB_NOTFOUND);
1498 for (i = 0; i<txn->mt_numdbs; i++) {
1500 if (!(txn->mt_dbflags[i] & DB_VALID))
1502 mdb_cursor_init(&mc, txn, i, &mx);
1503 if (txn->mt_dbs[i].md_root == P_INVALID)
1505 count += txn->mt_dbs[i].md_branch_pages +
1506 txn->mt_dbs[i].md_leaf_pages +
1507 txn->mt_dbs[i].md_overflow_pages;
1508 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1509 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1510 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1513 mp = mc.mc_pg[mc.mc_top];
1514 for (j=0; j<NUMKEYS(mp); j++) {
1515 MDB_node *leaf = NODEPTR(mp, j);
1516 if (leaf->mn_flags & F_SUBDATA) {
1518 memcpy(&db, NODEDATA(leaf), sizeof(db));
1519 count += db.md_branch_pages + db.md_leaf_pages +
1520 db.md_overflow_pages;
1524 mdb_tassert(txn, rc == MDB_NOTFOUND);
1527 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1528 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1529 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1535 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1537 return txn->mt_dbxs[dbi].md_cmp(a, b);
1541 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1543 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1546 /** Allocate memory for a page.
1547 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1550 mdb_page_malloc(MDB_txn *txn, unsigned num)
1552 MDB_env *env = txn->mt_env;
1553 MDB_page *ret = env->me_dpages;
1554 size_t psize = env->me_psize, sz = psize, off;
1555 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1556 * For a single page alloc, we init everything after the page header.
1557 * For multi-page, we init the final page; if the caller needed that
1558 * many pages they will be filling in at least up to the last page.
1562 VGMEMP_ALLOC(env, ret, sz);
1563 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1564 env->me_dpages = ret->mp_next;
1567 psize -= off = PAGEHDRSZ;
1572 if ((ret = malloc(sz)) != NULL) {
1573 VGMEMP_ALLOC(env, ret, sz);
1574 if (!(env->me_flags & MDB_NOMEMINIT)) {
1575 memset((char *)ret + off, 0, psize);
1579 txn->mt_flags |= MDB_TXN_ERROR;
1583 /** Free a single page.
1584 * Saves single pages to a list, for future reuse.
1585 * (This is not used for multi-page overflow pages.)
1588 mdb_page_free(MDB_env *env, MDB_page *mp)
1590 mp->mp_next = env->me_dpages;
1591 VGMEMP_FREE(env, mp);
1592 env->me_dpages = mp;
1595 /** Free a dirty page */
1597 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1599 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1600 mdb_page_free(env, dp);
1602 /* large pages just get freed directly */
1603 VGMEMP_FREE(env, dp);
1608 /** Return all dirty pages to dpage list */
1610 mdb_dlist_free(MDB_txn *txn)
1612 MDB_env *env = txn->mt_env;
1613 MDB_ID2L dl = txn->mt_u.dirty_list;
1614 unsigned i, n = dl[0].mid;
1616 for (i = 1; i <= n; i++) {
1617 mdb_dpage_free(env, dl[i].mptr);
1622 /** Loosen or free a single page.
1623 * Saves single pages to a list for future reuse
1624 * in this same txn. It has been pulled from the freeDB
1625 * and already resides on the dirty list, but has been
1626 * deleted. Use these pages first before pulling again
1629 * If the page wasn't dirtied in this txn, just add it
1630 * to this txn's free list.
1633 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1636 pgno_t pgno = mp->mp_pgno;
1637 MDB_txn *txn = mc->mc_txn;
1639 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1640 if (txn->mt_parent) {
1641 MDB_ID2 *dl = txn->mt_u.dirty_list;
1642 /* If txn has a parent, make sure the page is in our
1646 unsigned x = mdb_mid2l_search(dl, pgno);
1647 if (x <= dl[0].mid && dl[x].mid == pgno) {
1648 if (mp != dl[x].mptr) { /* bad cursor? */
1649 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1650 txn->mt_flags |= MDB_TXN_ERROR;
1651 return MDB_CORRUPTED;
1658 /* no parent txn, so it's just ours */
1663 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1665 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1666 txn->mt_loose_pgs = mp;
1667 txn->mt_loose_count++;
1668 mp->mp_flags |= P_LOOSE;
1670 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1678 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1679 * @param[in] mc A cursor handle for the current operation.
1680 * @param[in] pflags Flags of the pages to update:
1681 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1682 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1683 * @return 0 on success, non-zero on failure.
1686 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1688 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1689 MDB_txn *txn = mc->mc_txn;
1695 int rc = MDB_SUCCESS, level;
1697 /* Mark pages seen by cursors */
1698 if (mc->mc_flags & C_UNTRACK)
1699 mc = NULL; /* will find mc in mt_cursors */
1700 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1701 for (; mc; mc=mc->mc_next) {
1702 if (!(mc->mc_flags & C_INITIALIZED))
1704 for (m3 = mc;; m3 = &mx->mx_cursor) {
1706 for (j=0; j<m3->mc_snum; j++) {
1708 if ((mp->mp_flags & Mask) == pflags)
1709 mp->mp_flags ^= P_KEEP;
1711 mx = m3->mc_xcursor;
1712 /* Proceed to mx if it is at a sub-database */
1713 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1715 if (! (mp && (mp->mp_flags & P_LEAF)))
1717 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1718 if (!(leaf->mn_flags & F_SUBDATA))
1727 /* Mark dirty root pages */
1728 for (i=0; i<txn->mt_numdbs; i++) {
1729 if (txn->mt_dbflags[i] & DB_DIRTY) {
1730 pgno_t pgno = txn->mt_dbs[i].md_root;
1731 if (pgno == P_INVALID)
1733 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1735 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1736 dp->mp_flags ^= P_KEEP;
1744 static int mdb_page_flush(MDB_txn *txn, int keep);
1746 /** Spill pages from the dirty list back to disk.
1747 * This is intended to prevent running into #MDB_TXN_FULL situations,
1748 * but note that they may still occur in a few cases:
1749 * 1) our estimate of the txn size could be too small. Currently this
1750 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1751 * 2) child txns may run out of space if their parents dirtied a
1752 * lot of pages and never spilled them. TODO: we probably should do
1753 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1754 * the parent's dirty_room is below a given threshold.
1756 * Otherwise, if not using nested txns, it is expected that apps will
1757 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1758 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1759 * If the txn never references them again, they can be left alone.
1760 * If the txn only reads them, they can be used without any fuss.
1761 * If the txn writes them again, they can be dirtied immediately without
1762 * going thru all of the work of #mdb_page_touch(). Such references are
1763 * handled by #mdb_page_unspill().
1765 * Also note, we never spill DB root pages, nor pages of active cursors,
1766 * because we'll need these back again soon anyway. And in nested txns,
1767 * we can't spill a page in a child txn if it was already spilled in a
1768 * parent txn. That would alter the parent txns' data even though
1769 * the child hasn't committed yet, and we'd have no way to undo it if
1770 * the child aborted.
1772 * @param[in] m0 cursor A cursor handle identifying the transaction and
1773 * database for which we are checking space.
1774 * @param[in] key For a put operation, the key being stored.
1775 * @param[in] data For a put operation, the data being stored.
1776 * @return 0 on success, non-zero on failure.
1779 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1781 MDB_txn *txn = m0->mc_txn;
1783 MDB_ID2L dl = txn->mt_u.dirty_list;
1784 unsigned int i, j, need;
1787 if (m0->mc_flags & C_SUB)
1790 /* Estimate how much space this op will take */
1791 i = m0->mc_db->md_depth;
1792 /* Named DBs also dirty the main DB */
1793 if (m0->mc_dbi > MAIN_DBI)
1794 i += txn->mt_dbs[MAIN_DBI].md_depth;
1795 /* For puts, roughly factor in the key+data size */
1797 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1798 i += i; /* double it for good measure */
1801 if (txn->mt_dirty_room > i)
1804 if (!txn->mt_spill_pgs) {
1805 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1806 if (!txn->mt_spill_pgs)
1809 /* purge deleted slots */
1810 MDB_IDL sl = txn->mt_spill_pgs;
1811 unsigned int num = sl[0];
1813 for (i=1; i<=num; i++) {
1820 /* Preserve pages which may soon be dirtied again */
1821 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1824 /* Less aggressive spill - we originally spilled the entire dirty list,
1825 * with a few exceptions for cursor pages and DB root pages. But this
1826 * turns out to be a lot of wasted effort because in a large txn many
1827 * of those pages will need to be used again. So now we spill only 1/8th
1828 * of the dirty pages. Testing revealed this to be a good tradeoff,
1829 * better than 1/2, 1/4, or 1/10.
1831 if (need < MDB_IDL_UM_MAX / 8)
1832 need = MDB_IDL_UM_MAX / 8;
1834 /* Save the page IDs of all the pages we're flushing */
1835 /* flush from the tail forward, this saves a lot of shifting later on. */
1836 for (i=dl[0].mid; i && need; i--) {
1837 MDB_ID pn = dl[i].mid << 1;
1839 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1841 /* Can't spill twice, make sure it's not already in a parent's
1844 if (txn->mt_parent) {
1846 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1847 if (tx2->mt_spill_pgs) {
1848 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1849 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1850 dp->mp_flags |= P_KEEP;
1858 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1862 mdb_midl_sort(txn->mt_spill_pgs);
1864 /* Flush the spilled part of dirty list */
1865 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1868 /* Reset any dirty pages we kept that page_flush didn't see */
1869 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1872 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1876 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1878 mdb_find_oldest(MDB_txn *txn)
1881 txnid_t mr, oldest = txn->mt_txnid - 1;
1882 if (txn->mt_env->me_txns) {
1883 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1884 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1895 /** Add a page to the txn's dirty list */
1897 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1900 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1902 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1903 insert = mdb_mid2l_append;
1905 insert = mdb_mid2l_insert;
1907 mid.mid = mp->mp_pgno;
1909 rc = insert(txn->mt_u.dirty_list, &mid);
1910 mdb_tassert(txn, rc == 0);
1911 txn->mt_dirty_room--;
1914 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1915 * me_pghead and mt_next_pgno.
1917 * If there are free pages available from older transactions, they
1918 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1919 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1920 * and move me_pglast to say which records were consumed. Only this
1921 * function can create me_pghead and move me_pglast/mt_next_pgno.
1922 * @param[in] mc cursor A cursor handle identifying the transaction and
1923 * database for which we are allocating.
1924 * @param[in] num the number of pages to allocate.
1925 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1926 * will always be satisfied by a single contiguous chunk of memory.
1927 * @return 0 on success, non-zero on failure.
1930 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1932 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1933 /* Get at most <Max_retries> more freeDB records once me_pghead
1934 * has enough pages. If not enough, use new pages from the map.
1935 * If <Paranoid> and mc is updating the freeDB, only get new
1936 * records if me_pghead is empty. Then the freelist cannot play
1937 * catch-up with itself by growing while trying to save it.
1939 enum { Paranoid = 1, Max_retries = 500 };
1941 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1943 int rc, retry = num * 20;
1944 MDB_txn *txn = mc->mc_txn;
1945 MDB_env *env = txn->mt_env;
1946 pgno_t pgno, *mop = env->me_pghead;
1947 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
1949 txnid_t oldest = 0, last;
1953 /* If there are any loose pages, just use them */
1954 if (num == 1 && txn->mt_loose_pgs) {
1955 np = txn->mt_loose_pgs;
1956 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1957 txn->mt_loose_count--;
1958 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1966 /* If our dirty list is already full, we can't do anything */
1967 if (txn->mt_dirty_room == 0) {
1972 for (op = MDB_FIRST;; op = MDB_NEXT) {
1977 /* Seek a big enough contiguous page range. Prefer
1978 * pages at the tail, just truncating the list.
1984 if (mop[i-n2] == pgno+n2)
1991 if (op == MDB_FIRST) { /* 1st iteration */
1992 /* Prepare to fetch more and coalesce */
1993 oldest = mdb_find_oldest(txn);
1994 last = env->me_pglast;
1995 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1998 key.mv_data = &last; /* will look up last+1 */
1999 key.mv_size = sizeof(last);
2001 if (Paranoid && mc->mc_dbi == FREE_DBI)
2004 if (Paranoid && retry < 0 && mop_len)
2008 /* Do not fetch more if the record will be too recent */
2011 rc = mdb_cursor_get(&m2, &key, NULL, op);
2013 if (rc == MDB_NOTFOUND)
2017 last = *(txnid_t*)key.mv_data;
2020 np = m2.mc_pg[m2.mc_top];
2021 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2022 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2025 idl = (MDB_ID *) data.mv_data;
2028 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2033 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2035 mop = env->me_pghead;
2037 env->me_pglast = last;
2039 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2040 last, txn->mt_dbs[FREE_DBI].md_root, i));
2042 DPRINTF(("IDL %"Z"u", idl[j]));
2044 /* Merge in descending sorted order */
2045 mdb_midl_xmerge(mop, idl);
2049 /* Use new pages from the map when nothing suitable in the freeDB */
2051 pgno = txn->mt_next_pgno;
2052 if (pgno + num >= env->me_maxpg) {
2053 DPUTS("DB size maxed out");
2059 if (env->me_flags & MDB_WRITEMAP) {
2060 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2062 if (!(np = mdb_page_malloc(txn, num))) {
2068 mop[0] = mop_len -= num;
2069 /* Move any stragglers down */
2070 for (j = i-num; j < mop_len; )
2071 mop[++j] = mop[++i];
2073 txn->mt_next_pgno = pgno + num;
2076 mdb_page_dirty(txn, np);
2082 txn->mt_flags |= MDB_TXN_ERROR;
2086 /** Copy the used portions of a non-overflow page.
2087 * @param[in] dst page to copy into
2088 * @param[in] src page to copy from
2089 * @param[in] psize size of a page
2092 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2094 enum { Align = sizeof(pgno_t) };
2095 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2097 /* If page isn't full, just copy the used portion. Adjust
2098 * alignment so memcpy may copy words instead of bytes.
2100 if ((unused &= -Align) && !IS_LEAF2(src)) {
2101 upper = (upper + PAGEBASE) & -Align;
2102 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2103 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2106 memcpy(dst, src, psize - unused);
2110 /** Pull a page off the txn's spill list, if present.
2111 * If a page being referenced was spilled to disk in this txn, bring
2112 * it back and make it dirty/writable again.
2113 * @param[in] txn the transaction handle.
2114 * @param[in] mp the page being referenced. It must not be dirty.
2115 * @param[out] ret the writable page, if any. ret is unchanged if
2116 * mp wasn't spilled.
2119 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2121 MDB_env *env = txn->mt_env;
2124 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2126 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2127 if (!tx2->mt_spill_pgs)
2129 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2130 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2133 if (txn->mt_dirty_room == 0)
2134 return MDB_TXN_FULL;
2135 if (IS_OVERFLOW(mp))
2139 if (env->me_flags & MDB_WRITEMAP) {
2142 np = mdb_page_malloc(txn, num);
2146 memcpy(np, mp, num * env->me_psize);
2148 mdb_page_copy(np, mp, env->me_psize);
2151 /* If in current txn, this page is no longer spilled.
2152 * If it happens to be the last page, truncate the spill list.
2153 * Otherwise mark it as deleted by setting the LSB.
2155 if (x == txn->mt_spill_pgs[0])
2156 txn->mt_spill_pgs[0]--;
2158 txn->mt_spill_pgs[x] |= 1;
2159 } /* otherwise, if belonging to a parent txn, the
2160 * page remains spilled until child commits
2163 mdb_page_dirty(txn, np);
2164 np->mp_flags |= P_DIRTY;
2172 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2173 * @param[in] mc cursor pointing to the page to be touched
2174 * @return 0 on success, non-zero on failure.
2177 mdb_page_touch(MDB_cursor *mc)
2179 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2180 MDB_txn *txn = mc->mc_txn;
2181 MDB_cursor *m2, *m3;
2185 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2186 if (txn->mt_flags & MDB_TXN_SPILLS) {
2188 rc = mdb_page_unspill(txn, mp, &np);
2194 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2195 (rc = mdb_page_alloc(mc, 1, &np)))
2198 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2199 mp->mp_pgno, pgno));
2200 mdb_cassert(mc, mp->mp_pgno != pgno);
2201 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2202 /* Update the parent page, if any, to point to the new page */
2204 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2205 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2206 SETPGNO(node, pgno);
2208 mc->mc_db->md_root = pgno;
2210 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2211 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2213 /* If txn has a parent, make sure the page is in our
2217 unsigned x = mdb_mid2l_search(dl, pgno);
2218 if (x <= dl[0].mid && dl[x].mid == pgno) {
2219 if (mp != dl[x].mptr) { /* bad cursor? */
2220 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2221 txn->mt_flags |= MDB_TXN_ERROR;
2222 return MDB_CORRUPTED;
2227 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2229 np = mdb_page_malloc(txn, 1);
2234 rc = mdb_mid2l_insert(dl, &mid);
2235 mdb_cassert(mc, rc == 0);
2240 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2242 np->mp_flags |= P_DIRTY;
2245 /* Adjust cursors pointing to mp */
2246 mc->mc_pg[mc->mc_top] = np;
2247 m2 = txn->mt_cursors[mc->mc_dbi];
2248 if (mc->mc_flags & C_SUB) {
2249 for (; m2; m2=m2->mc_next) {
2250 m3 = &m2->mc_xcursor->mx_cursor;
2251 if (m3->mc_snum < mc->mc_snum) continue;
2252 if (m3->mc_pg[mc->mc_top] == mp)
2253 m3->mc_pg[mc->mc_top] = np;
2256 for (; m2; m2=m2->mc_next) {
2257 if (m2->mc_snum < mc->mc_snum) continue;
2258 if (m2->mc_pg[mc->mc_top] == mp) {
2259 m2->mc_pg[mc->mc_top] = np;
2260 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2262 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2264 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2265 if (!(leaf->mn_flags & F_SUBDATA))
2266 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2274 txn->mt_flags |= MDB_TXN_ERROR;
2279 mdb_env_sync(MDB_env *env, int force)
2282 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2283 if (env->me_flags & MDB_WRITEMAP) {
2284 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2285 ? MS_ASYNC : MS_SYNC;
2286 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2289 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2293 if (MDB_FDATASYNC(env->me_fd))
2300 /** Back up parent txn's cursors, then grab the originals for tracking */
2302 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2304 MDB_cursor *mc, *bk;
2309 for (i = src->mt_numdbs; --i >= 0; ) {
2310 if ((mc = src->mt_cursors[i]) != NULL) {
2311 size = sizeof(MDB_cursor);
2313 size += sizeof(MDB_xcursor);
2314 for (; mc; mc = bk->mc_next) {
2320 mc->mc_db = &dst->mt_dbs[i];
2321 /* Kill pointers into src - and dst to reduce abuse: The
2322 * user may not use mc until dst ends. Otherwise we'd...
2324 mc->mc_txn = NULL; /* ...set this to dst */
2325 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2326 if ((mx = mc->mc_xcursor) != NULL) {
2327 *(MDB_xcursor *)(bk+1) = *mx;
2328 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2330 mc->mc_next = dst->mt_cursors[i];
2331 dst->mt_cursors[i] = mc;
2338 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2339 * @param[in] txn the transaction handle.
2340 * @param[in] merge true to keep changes to parent cursors, false to revert.
2341 * @return 0 on success, non-zero on failure.
2344 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2346 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2350 for (i = txn->mt_numdbs; --i >= 0; ) {
2351 for (mc = cursors[i]; mc; mc = next) {
2353 if ((bk = mc->mc_backup) != NULL) {
2355 /* Commit changes to parent txn */
2356 mc->mc_next = bk->mc_next;
2357 mc->mc_backup = bk->mc_backup;
2358 mc->mc_txn = bk->mc_txn;
2359 mc->mc_db = bk->mc_db;
2360 mc->mc_dbflag = bk->mc_dbflag;
2361 if ((mx = mc->mc_xcursor) != NULL)
2362 mx->mx_cursor.mc_txn = bk->mc_txn;
2364 /* Abort nested txn */
2366 if ((mx = mc->mc_xcursor) != NULL)
2367 *mx = *(MDB_xcursor *)(bk+1);
2371 /* Only malloced cursors are permanently tracked. */
2379 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2382 mdb_txn_reset0(MDB_txn *txn, const char *act);
2384 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2390 Pidset = F_SETLK, Pidcheck = F_GETLK
2394 /** Set or check a pid lock. Set returns 0 on success.
2395 * Check returns 0 if the process is certainly dead, nonzero if it may
2396 * be alive (the lock exists or an error happened so we do not know).
2398 * On Windows Pidset is a no-op, we merely check for the existence
2399 * of the process with the given pid. On POSIX we use a single byte
2400 * lock on the lockfile, set at an offset equal to the pid.
2403 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2405 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2408 if (op == Pidcheck) {
2409 h = OpenProcess(env->me_pidquery, FALSE, pid);
2410 /* No documented "no such process" code, but other program use this: */
2412 return ErrCode() != ERROR_INVALID_PARAMETER;
2413 /* A process exists until all handles to it close. Has it exited? */
2414 ret = WaitForSingleObject(h, 0) != 0;
2421 struct flock lock_info;
2422 memset(&lock_info, 0, sizeof(lock_info));
2423 lock_info.l_type = F_WRLCK;
2424 lock_info.l_whence = SEEK_SET;
2425 lock_info.l_start = pid;
2426 lock_info.l_len = 1;
2427 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2428 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2430 } else if ((rc = ErrCode()) == EINTR) {
2438 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2439 * @param[in] txn the transaction handle to initialize
2440 * @return 0 on success, non-zero on failure.
2443 mdb_txn_renew0(MDB_txn *txn)
2445 MDB_env *env = txn->mt_env;
2446 MDB_txninfo *ti = env->me_txns;
2450 int rc, new_notls = 0;
2453 txn->mt_numdbs = env->me_numdbs;
2454 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2456 if (txn->mt_flags & MDB_TXN_RDONLY) {
2458 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2459 txn->mt_txnid = meta->mm_txnid;
2460 txn->mt_u.reader = NULL;
2462 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2463 pthread_getspecific(env->me_txkey);
2465 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2466 return MDB_BAD_RSLOT;
2468 MDB_PID_T pid = env->me_pid;
2469 MDB_THR_T tid = pthread_self();
2471 if (!env->me_live_reader) {
2472 rc = mdb_reader_pid(env, Pidset, pid);
2475 env->me_live_reader = 1;
2479 nr = ti->mti_numreaders;
2480 for (i=0; i<nr; i++)
2481 if (ti->mti_readers[i].mr_pid == 0)
2483 if (i == env->me_maxreaders) {
2484 UNLOCK_MUTEX_R(env);
2485 return MDB_READERS_FULL;
2487 ti->mti_readers[i].mr_pid = pid;
2488 ti->mti_readers[i].mr_tid = tid;
2490 ti->mti_numreaders = ++nr;
2491 /* Save numreaders for un-mutexed mdb_env_close() */
2492 env->me_numreaders = nr;
2493 UNLOCK_MUTEX_R(env);
2495 r = &ti->mti_readers[i];
2496 new_notls = (env->me_flags & MDB_NOTLS);
2497 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2502 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2503 txn->mt_u.reader = r;
2504 meta = env->me_metas[txn->mt_txnid & 1];
2510 txn->mt_txnid = ti->mti_txnid;
2511 meta = env->me_metas[txn->mt_txnid & 1];
2513 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2514 txn->mt_txnid = meta->mm_txnid;
2518 if (txn->mt_txnid == mdb_debug_start)
2521 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2522 txn->mt_u.dirty_list = env->me_dirty_list;
2523 txn->mt_u.dirty_list[0].mid = 0;
2524 txn->mt_free_pgs = env->me_free_pgs;
2525 txn->mt_free_pgs[0] = 0;
2526 txn->mt_spill_pgs = NULL;
2528 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2531 /* Copy the DB info and flags */
2532 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2534 /* Moved to here to avoid a data race in read TXNs */
2535 txn->mt_next_pgno = meta->mm_last_pg+1;
2537 for (i=2; i<txn->mt_numdbs; i++) {
2538 x = env->me_dbflags[i];
2539 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2540 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2542 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2544 if (env->me_maxpg < txn->mt_next_pgno) {
2545 mdb_txn_reset0(txn, "renew0-mapfail");
2547 txn->mt_u.reader->mr_pid = 0;
2548 txn->mt_u.reader = NULL;
2550 return MDB_MAP_RESIZED;
2557 mdb_txn_renew(MDB_txn *txn)
2561 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2564 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2565 DPUTS("environment had fatal error, must shutdown!");
2569 rc = mdb_txn_renew0(txn);
2570 if (rc == MDB_SUCCESS) {
2571 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2572 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2573 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2579 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2583 int rc, size, tsize = sizeof(MDB_txn);
2585 if (env->me_flags & MDB_FATAL_ERROR) {
2586 DPUTS("environment had fatal error, must shutdown!");
2589 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2592 /* Nested transactions: Max 1 child, write txns only, no writemap */
2593 if (parent->mt_child ||
2594 (flags & MDB_RDONLY) ||
2595 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2596 (env->me_flags & MDB_WRITEMAP))
2598 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2600 tsize = sizeof(MDB_ntxn);
2602 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2603 if (!(flags & MDB_RDONLY)) {
2604 size += env->me_maxdbs * sizeof(MDB_cursor *);
2605 /* child txns use parent's dbiseqs */
2607 size += env->me_maxdbs * sizeof(unsigned int);
2610 if ((txn = calloc(1, size)) == NULL) {
2611 DPRINTF(("calloc: %s", strerror(errno)));
2614 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2615 if (flags & MDB_RDONLY) {
2616 txn->mt_flags |= MDB_TXN_RDONLY;
2617 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2618 txn->mt_dbiseqs = env->me_dbiseqs;
2620 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2622 txn->mt_dbiseqs = parent->mt_dbiseqs;
2623 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2625 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2626 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2633 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2634 if (!txn->mt_u.dirty_list ||
2635 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2637 free(txn->mt_u.dirty_list);
2641 txn->mt_txnid = parent->mt_txnid;
2642 txn->mt_dirty_room = parent->mt_dirty_room;
2643 txn->mt_u.dirty_list[0].mid = 0;
2644 txn->mt_spill_pgs = NULL;
2645 txn->mt_next_pgno = parent->mt_next_pgno;
2646 parent->mt_child = txn;
2647 txn->mt_parent = parent;
2648 txn->mt_numdbs = parent->mt_numdbs;
2649 txn->mt_flags = parent->mt_flags;
2650 txn->mt_dbxs = parent->mt_dbxs;
2651 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2652 /* Copy parent's mt_dbflags, but clear DB_NEW */
2653 for (i=0; i<txn->mt_numdbs; i++)
2654 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2656 ntxn = (MDB_ntxn *)txn;
2657 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2658 if (env->me_pghead) {
2659 size = MDB_IDL_SIZEOF(env->me_pghead);
2660 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2662 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2667 rc = mdb_cursor_shadow(parent, txn);
2669 mdb_txn_reset0(txn, "beginchild-fail");
2671 rc = mdb_txn_renew0(txn);
2677 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2678 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2679 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2686 mdb_txn_env(MDB_txn *txn)
2688 if(!txn) return NULL;
2692 /** Export or close DBI handles opened in this txn. */
2694 mdb_dbis_update(MDB_txn *txn, int keep)
2697 MDB_dbi n = txn->mt_numdbs;
2698 MDB_env *env = txn->mt_env;
2699 unsigned char *tdbflags = txn->mt_dbflags;
2701 for (i = n; --i >= 2;) {
2702 if (tdbflags[i] & DB_NEW) {
2704 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2706 char *ptr = env->me_dbxs[i].md_name.mv_data;
2708 env->me_dbxs[i].md_name.mv_data = NULL;
2709 env->me_dbxs[i].md_name.mv_size = 0;
2710 env->me_dbflags[i] = 0;
2711 env->me_dbiseqs[i]++;
2717 if (keep && env->me_numdbs < n)
2721 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2722 * May be called twice for readonly txns: First reset it, then abort.
2723 * @param[in] txn the transaction handle to reset
2724 * @param[in] act why the transaction is being reset
2727 mdb_txn_reset0(MDB_txn *txn, const char *act)
2729 MDB_env *env = txn->mt_env;
2731 /* Close any DBI handles opened in this txn */
2732 mdb_dbis_update(txn, 0);
2734 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2735 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2736 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2738 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2739 if (txn->mt_u.reader) {
2740 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2741 if (!(env->me_flags & MDB_NOTLS))
2742 txn->mt_u.reader = NULL; /* txn does not own reader */
2744 txn->mt_numdbs = 0; /* close nothing if called again */
2745 txn->mt_dbxs = NULL; /* mark txn as reset */
2747 mdb_cursors_close(txn, 0);
2749 if (!(env->me_flags & MDB_WRITEMAP)) {
2750 mdb_dlist_free(txn);
2752 mdb_midl_free(env->me_pghead);
2754 if (txn->mt_parent) {
2755 txn->mt_parent->mt_child = NULL;
2756 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2757 mdb_midl_free(txn->mt_free_pgs);
2758 mdb_midl_free(txn->mt_spill_pgs);
2759 free(txn->mt_u.dirty_list);
2763 if (mdb_midl_shrink(&txn->mt_free_pgs))
2764 env->me_free_pgs = txn->mt_free_pgs;
2765 env->me_pghead = NULL;
2769 /* The writer mutex was locked in mdb_txn_begin. */
2771 UNLOCK_MUTEX_W(env);
2776 mdb_txn_reset(MDB_txn *txn)
2781 /* This call is only valid for read-only txns */
2782 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2785 mdb_txn_reset0(txn, "reset");
2789 mdb_txn_abort(MDB_txn *txn)
2795 mdb_txn_abort(txn->mt_child);
2797 mdb_txn_reset0(txn, "abort");
2798 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2799 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2800 txn->mt_u.reader->mr_pid = 0;
2805 /** Save the freelist as of this transaction to the freeDB.
2806 * This changes the freelist. Keep trying until it stabilizes.
2809 mdb_freelist_save(MDB_txn *txn)
2811 /* env->me_pghead[] can grow and shrink during this call.
2812 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2813 * Page numbers cannot disappear from txn->mt_free_pgs[].
2816 MDB_env *env = txn->mt_env;
2817 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2818 txnid_t pglast = 0, head_id = 0;
2819 pgno_t freecnt = 0, *free_pgs, *mop;
2820 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2822 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2824 if (env->me_pghead) {
2825 /* Make sure first page of freeDB is touched and on freelist */
2826 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2827 if (rc && rc != MDB_NOTFOUND)
2831 if (!env->me_pghead && txn->mt_loose_pgs) {
2832 /* Put loose page numbers in mt_free_pgs, since
2833 * we may be unable to return them to me_pghead.
2835 MDB_page *mp = txn->mt_loose_pgs;
2836 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
2838 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
2839 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2840 txn->mt_loose_pgs = NULL;
2841 txn->mt_loose_count = 0;
2844 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2845 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2846 ? SSIZE_MAX : maxfree_1pg;
2849 /* Come back here after each Put() in case freelist changed */
2854 /* If using records from freeDB which we have not yet
2855 * deleted, delete them and any we reserved for me_pghead.
2857 while (pglast < env->me_pglast) {
2858 rc = mdb_cursor_first(&mc, &key, NULL);
2861 pglast = head_id = *(txnid_t *)key.mv_data;
2862 total_room = head_room = 0;
2863 mdb_tassert(txn, pglast <= env->me_pglast);
2864 rc = mdb_cursor_del(&mc, 0);
2869 /* Save the IDL of pages freed by this txn, to a single record */
2870 if (freecnt < txn->mt_free_pgs[0]) {
2872 /* Make sure last page of freeDB is touched and on freelist */
2873 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2874 if (rc && rc != MDB_NOTFOUND)
2877 free_pgs = txn->mt_free_pgs;
2878 /* Write to last page of freeDB */
2879 key.mv_size = sizeof(txn->mt_txnid);
2880 key.mv_data = &txn->mt_txnid;
2882 freecnt = free_pgs[0];
2883 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2884 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2887 /* Retry if mt_free_pgs[] grew during the Put() */
2888 free_pgs = txn->mt_free_pgs;
2889 } while (freecnt < free_pgs[0]);
2890 mdb_midl_sort(free_pgs);
2891 memcpy(data.mv_data, free_pgs, data.mv_size);
2894 unsigned int i = free_pgs[0];
2895 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2896 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2898 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2904 mop = env->me_pghead;
2905 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
2907 /* Reserve records for me_pghead[]. Split it if multi-page,
2908 * to avoid searching freeDB for a page range. Use keys in
2909 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2911 if (total_room >= mop_len) {
2912 if (total_room == mop_len || --more < 0)
2914 } else if (head_room >= maxfree_1pg && head_id > 1) {
2915 /* Keep current record (overflow page), add a new one */
2919 /* (Re)write {key = head_id, IDL length = head_room} */
2920 total_room -= head_room;
2921 head_room = mop_len - total_room;
2922 if (head_room > maxfree_1pg && head_id > 1) {
2923 /* Overflow multi-page for part of me_pghead */
2924 head_room /= head_id; /* amortize page sizes */
2925 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2926 } else if (head_room < 0) {
2927 /* Rare case, not bothering to delete this record */
2930 key.mv_size = sizeof(head_id);
2931 key.mv_data = &head_id;
2932 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2933 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2936 /* IDL is initially empty, zero out at least the length */
2937 pgs = (pgno_t *)data.mv_data;
2938 j = head_room > clean_limit ? head_room : 0;
2942 total_room += head_room;
2945 /* Return loose page numbers to me_pghead, though usually none are
2946 * left at this point. The pages themselves remain in dirty_list.
2948 if (txn->mt_loose_pgs) {
2949 MDB_page *mp = txn->mt_loose_pgs;
2950 unsigned count = txn->mt_loose_count;
2952 /* Room for loose pages + temp IDL with same */
2953 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
2955 mop = env->me_pghead;
2956 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
2957 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
2958 loose[ ++count ] = mp->mp_pgno;
2960 mdb_midl_sort(loose);
2961 mdb_midl_xmerge(mop, loose);
2962 txn->mt_loose_pgs = NULL;
2963 txn->mt_loose_count = 0;
2967 /* Fill in the reserved me_pghead records */
2973 rc = mdb_cursor_first(&mc, &key, &data);
2974 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2975 txnid_t id = *(txnid_t *)key.mv_data;
2976 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2979 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2981 if (len > mop_len) {
2983 data.mv_size = (len + 1) * sizeof(MDB_ID);
2985 data.mv_data = mop -= len;
2988 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2990 if (rc || !(mop_len -= len))
2997 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2998 * @param[in] txn the transaction that's being committed
2999 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3000 * @return 0 on success, non-zero on failure.
3003 mdb_page_flush(MDB_txn *txn, int keep)
3005 MDB_env *env = txn->mt_env;
3006 MDB_ID2L dl = txn->mt_u.dirty_list;
3007 unsigned psize = env->me_psize, j;
3008 int i, pagecount = dl[0].mid, rc;
3009 size_t size = 0, pos = 0;
3011 MDB_page *dp = NULL;
3015 struct iovec iov[MDB_COMMIT_PAGES];
3016 ssize_t wpos = 0, wsize = 0, wres;
3017 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3023 if (env->me_flags & MDB_WRITEMAP) {
3024 /* Clear dirty flags */
3025 while (++i <= pagecount) {
3027 /* Don't flush this page yet */
3028 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3029 dp->mp_flags &= ~P_KEEP;
3033 dp->mp_flags &= ~P_DIRTY;
3038 /* Write the pages */
3040 if (++i <= pagecount) {
3042 /* Don't flush this page yet */
3043 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3044 dp->mp_flags &= ~P_KEEP;
3049 /* clear dirty flag */
3050 dp->mp_flags &= ~P_DIRTY;
3053 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3058 /* Windows actually supports scatter/gather I/O, but only on
3059 * unbuffered file handles. Since we're relying on the OS page
3060 * cache for all our data, that's self-defeating. So we just
3061 * write pages one at a time. We use the ov structure to set
3062 * the write offset, to at least save the overhead of a Seek
3065 DPRINTF(("committing page %"Z"u", pgno));
3066 memset(&ov, 0, sizeof(ov));
3067 ov.Offset = pos & 0xffffffff;
3068 ov.OffsetHigh = pos >> 16 >> 16;
3069 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3071 DPRINTF(("WriteFile: %d", rc));
3075 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3076 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3078 /* Write previous page(s) */
3079 #ifdef MDB_USE_PWRITEV
3080 wres = pwritev(env->me_fd, iov, n, wpos);
3083 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3085 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3087 DPRINTF(("lseek: %s", strerror(rc)));
3090 wres = writev(env->me_fd, iov, n);
3093 if (wres != wsize) {
3096 DPRINTF(("Write error: %s", strerror(rc)));
3098 rc = EIO; /* TODO: Use which error code? */
3099 DPUTS("short write, filesystem full?");
3110 DPRINTF(("committing page %"Z"u", pgno));
3111 next_pos = pos + size;
3112 iov[n].iov_len = size;
3113 iov[n].iov_base = (char *)dp;
3119 /* MIPS has cache coherency issues, this is a no-op everywhere else
3120 * Note: for any size >= on-chip cache size, entire on-chip cache is
3123 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3125 for (i = keep; ++i <= pagecount; ) {
3127 /* This is a page we skipped above */
3130 dl[j].mid = dp->mp_pgno;
3133 mdb_dpage_free(env, dp);
3138 txn->mt_dirty_room += i - j;
3144 mdb_txn_commit(MDB_txn *txn)
3150 if (txn == NULL || txn->mt_env == NULL)
3153 if (txn->mt_child) {
3154 rc = mdb_txn_commit(txn->mt_child);
3155 txn->mt_child = NULL;
3162 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3163 mdb_dbis_update(txn, 1);
3164 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3169 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3170 DPUTS("error flag is set, can't commit");
3172 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3177 if (txn->mt_parent) {
3178 MDB_txn *parent = txn->mt_parent;
3182 unsigned x, y, len, ps_len;
3184 /* Append our free list to parent's */
3185 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3188 mdb_midl_free(txn->mt_free_pgs);
3189 /* Failures after this must either undo the changes
3190 * to the parent or set MDB_TXN_ERROR in the parent.
3193 parent->mt_next_pgno = txn->mt_next_pgno;
3194 parent->mt_flags = txn->mt_flags;
3196 /* Merge our cursors into parent's and close them */
3197 mdb_cursors_close(txn, 1);
3199 /* Update parent's DB table. */
3200 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3201 parent->mt_numdbs = txn->mt_numdbs;
3202 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3203 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3204 for (i=2; i<txn->mt_numdbs; i++) {
3205 /* preserve parent's DB_NEW status */
3206 x = parent->mt_dbflags[i] & DB_NEW;
3207 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3210 dst = parent->mt_u.dirty_list;
3211 src = txn->mt_u.dirty_list;
3212 /* Remove anything in our dirty list from parent's spill list */
3213 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3215 pspill[0] = (pgno_t)-1;
3216 /* Mark our dirty pages as deleted in parent spill list */
3217 for (i=0, len=src[0].mid; ++i <= len; ) {
3218 MDB_ID pn = src[i].mid << 1;
3219 while (pn > pspill[x])
3221 if (pn == pspill[x]) {
3226 /* Squash deleted pagenums if we deleted any */
3227 for (x=y; ++x <= ps_len; )
3228 if (!(pspill[x] & 1))
3229 pspill[++y] = pspill[x];
3233 /* Find len = length of merging our dirty list with parent's */
3235 dst[0].mid = 0; /* simplify loops */
3236 if (parent->mt_parent) {
3237 len = x + src[0].mid;
3238 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3239 for (i = x; y && i; y--) {
3240 pgno_t yp = src[y].mid;
3241 while (yp < dst[i].mid)
3243 if (yp == dst[i].mid) {
3248 } else { /* Simplify the above for single-ancestor case */
3249 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3251 /* Merge our dirty list with parent's */
3253 for (i = len; y; dst[i--] = src[y--]) {
3254 pgno_t yp = src[y].mid;
3255 while (yp < dst[x].mid)
3256 dst[i--] = dst[x--];
3257 if (yp == dst[x].mid)
3258 free(dst[x--].mptr);
3260 mdb_tassert(txn, i == x);
3262 free(txn->mt_u.dirty_list);
3263 parent->mt_dirty_room = txn->mt_dirty_room;
3264 if (txn->mt_spill_pgs) {
3265 if (parent->mt_spill_pgs) {
3266 /* TODO: Prevent failure here, so parent does not fail */
3267 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3269 parent->mt_flags |= MDB_TXN_ERROR;
3270 mdb_midl_free(txn->mt_spill_pgs);
3271 mdb_midl_sort(parent->mt_spill_pgs);
3273 parent->mt_spill_pgs = txn->mt_spill_pgs;
3277 /* Append our loose page list to parent's */
3278 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3280 *lp = txn->mt_loose_pgs;
3281 parent->mt_loose_count += txn->mt_loose_count;
3283 parent->mt_child = NULL;
3284 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3289 if (txn != env->me_txn) {
3290 DPUTS("attempt to commit unknown transaction");
3295 mdb_cursors_close(txn, 0);
3297 if (!txn->mt_u.dirty_list[0].mid &&
3298 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3301 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3302 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3304 /* Update DB root pointers */
3305 if (txn->mt_numdbs > 2) {
3309 data.mv_size = sizeof(MDB_db);
3311 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3312 for (i = 2; i < txn->mt_numdbs; i++) {
3313 if (txn->mt_dbflags[i] & DB_DIRTY) {
3314 if (TXN_DBI_CHANGED(txn, i)) {
3318 data.mv_data = &txn->mt_dbs[i];
3319 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3326 rc = mdb_freelist_save(txn);
3330 mdb_midl_free(env->me_pghead);
3331 env->me_pghead = NULL;
3332 if (mdb_midl_shrink(&txn->mt_free_pgs))
3333 env->me_free_pgs = txn->mt_free_pgs;
3339 if ((rc = mdb_page_flush(txn, 0)) ||
3340 (rc = mdb_env_sync(env, 0)) ||
3341 (rc = mdb_env_write_meta(txn)))
3344 /* Free P_LOOSE pages left behind in dirty_list */
3345 if (!(env->me_flags & MDB_WRITEMAP))
3346 mdb_dlist_free(txn);
3351 mdb_dbis_update(txn, 1);
3354 UNLOCK_MUTEX_W(env);
3364 /** Read the environment parameters of a DB environment before
3365 * mapping it into memory.
3366 * @param[in] env the environment handle
3367 * @param[out] meta address of where to store the meta information
3368 * @return 0 on success, non-zero on failure.
3371 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3377 enum { Size = sizeof(pbuf) };
3379 /* We don't know the page size yet, so use a minimum value.
3380 * Read both meta pages so we can use the latest one.
3383 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3387 memset(&ov, 0, sizeof(ov));
3389 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3390 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3393 rc = pread(env->me_fd, &pbuf, Size, off);
3396 if (rc == 0 && off == 0)
3398 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3399 DPRINTF(("read: %s", mdb_strerror(rc)));
3403 p = (MDB_page *)&pbuf;
3405 if (!F_ISSET(p->mp_flags, P_META)) {
3406 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3411 if (m->mm_magic != MDB_MAGIC) {
3412 DPUTS("meta has invalid magic");
3416 if (m->mm_version != MDB_DATA_VERSION) {
3417 DPRINTF(("database is version %u, expected version %u",
3418 m->mm_version, MDB_DATA_VERSION));
3419 return MDB_VERSION_MISMATCH;
3422 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3429 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3431 meta->mm_magic = MDB_MAGIC;
3432 meta->mm_version = MDB_DATA_VERSION;
3433 meta->mm_mapsize = env->me_mapsize;
3434 meta->mm_psize = env->me_psize;
3435 meta->mm_last_pg = 1;
3436 meta->mm_flags = env->me_flags & 0xffff;
3437 meta->mm_flags |= MDB_INTEGERKEY;
3438 meta->mm_dbs[0].md_root = P_INVALID;
3439 meta->mm_dbs[1].md_root = P_INVALID;
3442 /** Write the environment parameters of a freshly created DB environment.
3443 * @param[in] env the environment handle
3444 * @param[out] meta address of where to store the meta information
3445 * @return 0 on success, non-zero on failure.
3448 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3456 memset(&ov, 0, sizeof(ov));
3457 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3459 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3462 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3463 len = pwrite(fd, ptr, size, pos); \
3464 rc = (len >= 0); } while(0)
3467 DPUTS("writing new meta page");
3469 psize = env->me_psize;
3471 mdb_env_init_meta0(env, meta);
3473 p = calloc(2, psize);
3475 p->mp_flags = P_META;
3476 *(MDB_meta *)METADATA(p) = *meta;
3478 q = (MDB_page *)((char *)p + psize);
3480 q->mp_flags = P_META;
3481 *(MDB_meta *)METADATA(q) = *meta;
3483 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3486 else if ((unsigned) len == psize * 2)
3494 /** Update the environment info to commit a transaction.
3495 * @param[in] txn the transaction that's being committed
3496 * @return 0 on success, non-zero on failure.
3499 mdb_env_write_meta(MDB_txn *txn)
3502 MDB_meta meta, metab, *mp;
3505 int rc, len, toggle;
3514 toggle = txn->mt_txnid & 1;
3515 DPRINTF(("writing meta page %d for root page %"Z"u",
3516 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3519 mp = env->me_metas[toggle];
3520 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3521 /* Persist any increases of mapsize config */
3522 if (mapsize < env->me_mapsize)
3523 mapsize = env->me_mapsize;
3525 if (env->me_flags & MDB_WRITEMAP) {
3526 mp->mm_mapsize = mapsize;
3527 mp->mm_dbs[0] = txn->mt_dbs[0];
3528 mp->mm_dbs[1] = txn->mt_dbs[1];
3529 mp->mm_last_pg = txn->mt_next_pgno - 1;
3530 mp->mm_txnid = txn->mt_txnid;
3531 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3532 unsigned meta_size = env->me_psize;
3533 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3536 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3537 if (meta_size < env->me_os_psize)
3538 meta_size += meta_size;
3543 if (MDB_MSYNC(ptr, meta_size, rc)) {
3550 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3551 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3553 meta.mm_mapsize = mapsize;
3554 meta.mm_dbs[0] = txn->mt_dbs[0];
3555 meta.mm_dbs[1] = txn->mt_dbs[1];
3556 meta.mm_last_pg = txn->mt_next_pgno - 1;
3557 meta.mm_txnid = txn->mt_txnid;
3559 off = offsetof(MDB_meta, mm_mapsize);
3560 ptr = (char *)&meta + off;
3561 len = sizeof(MDB_meta) - off;
3563 off += env->me_psize;
3566 /* Write to the SYNC fd */
3567 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3568 env->me_fd : env->me_mfd;
3571 memset(&ov, 0, sizeof(ov));
3573 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3577 rc = pwrite(mfd, ptr, len, off);
3580 rc = rc < 0 ? ErrCode() : EIO;
3581 DPUTS("write failed, disk error?");
3582 /* On a failure, the pagecache still contains the new data.
3583 * Write some old data back, to prevent it from being used.
3584 * Use the non-SYNC fd; we know it will fail anyway.
3586 meta.mm_last_pg = metab.mm_last_pg;
3587 meta.mm_txnid = metab.mm_txnid;
3589 memset(&ov, 0, sizeof(ov));
3591 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3593 r2 = pwrite(env->me_fd, ptr, len, off);
3594 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3597 env->me_flags |= MDB_FATAL_ERROR;
3601 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3602 if (!(env->me_flags & MDB_WRITEMAP)) {
3603 CACHEFLUSH(env->me_map + off, len, DCACHE);
3605 /* Memory ordering issues are irrelevant; since the entire writer
3606 * is wrapped by wmutex, all of these changes will become visible
3607 * after the wmutex is unlocked. Since the DB is multi-version,
3608 * readers will get consistent data regardless of how fresh or
3609 * how stale their view of these values is.
3612 env->me_txns->mti_txnid = txn->mt_txnid;
3617 /** Check both meta pages to see which one is newer.
3618 * @param[in] env the environment handle
3619 * @return meta toggle (0 or 1).
3622 mdb_env_pick_meta(const MDB_env *env)
3624 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3628 mdb_env_create(MDB_env **env)
3632 e = calloc(1, sizeof(MDB_env));
3636 e->me_maxreaders = DEFAULT_READERS;
3637 e->me_maxdbs = e->me_numdbs = 2;
3638 e->me_fd = INVALID_HANDLE_VALUE;
3639 e->me_lfd = INVALID_HANDLE_VALUE;
3640 e->me_mfd = INVALID_HANDLE_VALUE;
3641 #ifdef MDB_USE_POSIX_SEM
3642 e->me_rmutex = SEM_FAILED;
3643 e->me_wmutex = SEM_FAILED;
3645 e->me_pid = getpid();
3646 GET_PAGESIZE(e->me_os_psize);
3647 VGMEMP_CREATE(e,0,0);
3653 mdb_env_map(MDB_env *env, void *addr)
3656 unsigned int flags = env->me_flags;
3660 LONG sizelo, sizehi;
3663 if (flags & MDB_RDONLY) {
3664 /* Don't set explicit map size, use whatever exists */
3669 msize = env->me_mapsize;
3670 sizelo = msize & 0xffffffff;
3671 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3673 /* Windows won't create mappings for zero length files.
3674 * and won't map more than the file size.
3675 * Just set the maxsize right now.
3677 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3678 || !SetEndOfFile(env->me_fd)
3679 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3683 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3684 PAGE_READWRITE : PAGE_READONLY,
3685 sizehi, sizelo, NULL);
3688 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3689 FILE_MAP_WRITE : FILE_MAP_READ,
3691 rc = env->me_map ? 0 : ErrCode();
3696 int prot = PROT_READ;
3697 if (flags & MDB_WRITEMAP) {
3699 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3702 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3704 if (env->me_map == MAP_FAILED) {
3709 if (flags & MDB_NORDAHEAD) {
3710 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3712 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3714 #ifdef POSIX_MADV_RANDOM
3715 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3716 #endif /* POSIX_MADV_RANDOM */
3717 #endif /* MADV_RANDOM */
3721 /* Can happen because the address argument to mmap() is just a
3722 * hint. mmap() can pick another, e.g. if the range is in use.
3723 * The MAP_FIXED flag would prevent that, but then mmap could
3724 * instead unmap existing pages to make room for the new map.
3726 if (addr && env->me_map != addr)
3727 return EBUSY; /* TODO: Make a new MDB_* error code? */
3729 p = (MDB_page *)env->me_map;
3730 env->me_metas[0] = METADATA(p);
3731 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3737 mdb_env_set_mapsize(MDB_env *env, size_t size)
3739 /* If env is already open, caller is responsible for making
3740 * sure there are no active txns.
3748 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3749 else if (size < env->me_mapsize) {
3750 /* If the configured size is smaller, make sure it's
3751 * still big enough. Silently round up to minimum if not.
3753 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3757 munmap(env->me_map, env->me_mapsize);
3758 env->me_mapsize = size;
3759 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3760 rc = mdb_env_map(env, old);
3764 env->me_mapsize = size;
3766 env->me_maxpg = env->me_mapsize / env->me_psize;
3771 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3775 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3780 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3782 if (env->me_map || readers < 1)
3784 env->me_maxreaders = readers;
3789 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3791 if (!env || !readers)
3793 *readers = env->me_maxreaders;
3797 /** Further setup required for opening an LMDB environment
3800 mdb_env_open2(MDB_env *env)
3802 unsigned int flags = env->me_flags;
3803 int i, newenv = 0, rc;
3807 /* See if we should use QueryLimited */
3809 if ((rc & 0xff) > 5)
3810 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3812 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3815 memset(&meta, 0, sizeof(meta));
3817 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3820 DPUTS("new mdbenv");
3822 env->me_psize = env->me_os_psize;
3823 if (env->me_psize > MAX_PAGESIZE)
3824 env->me_psize = MAX_PAGESIZE;
3826 env->me_psize = meta.mm_psize;
3829 /* Was a mapsize configured? */
3830 if (!env->me_mapsize) {
3831 /* If this is a new environment, take the default,
3832 * else use the size recorded in the existing env.
3834 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3835 } else if (env->me_mapsize < meta.mm_mapsize) {
3836 /* If the configured size is smaller, make sure it's
3837 * still big enough. Silently round up to minimum if not.
3839 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3840 if (env->me_mapsize < minsize)
3841 env->me_mapsize = minsize;
3844 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
3849 if (flags & MDB_FIXEDMAP)
3850 meta.mm_address = env->me_map;
3851 i = mdb_env_init_meta(env, &meta);
3852 if (i != MDB_SUCCESS) {
3857 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3858 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3860 #if !(MDB_MAXKEYSIZE)
3861 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3863 env->me_maxpg = env->me_mapsize / env->me_psize;
3867 int toggle = mdb_env_pick_meta(env);
3868 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3870 DPRINTF(("opened database version %u, pagesize %u",
3871 env->me_metas[0]->mm_version, env->me_psize));
3872 DPRINTF(("using meta page %d", toggle));
3873 DPRINTF(("depth: %u", db->md_depth));
3874 DPRINTF(("entries: %"Z"u", db->md_entries));
3875 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3876 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3877 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3878 DPRINTF(("root: %"Z"u", db->md_root));
3886 /** Release a reader thread's slot in the reader lock table.
3887 * This function is called automatically when a thread exits.
3888 * @param[in] ptr This points to the slot in the reader lock table.
3891 mdb_env_reader_dest(void *ptr)
3893 MDB_reader *reader = ptr;
3899 /** Junk for arranging thread-specific callbacks on Windows. This is
3900 * necessarily platform and compiler-specific. Windows supports up
3901 * to 1088 keys. Let's assume nobody opens more than 64 environments
3902 * in a single process, for now. They can override this if needed.
3904 #ifndef MAX_TLS_KEYS
3905 #define MAX_TLS_KEYS 64
3907 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3908 static int mdb_tls_nkeys;
3910 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3914 case DLL_PROCESS_ATTACH: break;
3915 case DLL_THREAD_ATTACH: break;
3916 case DLL_THREAD_DETACH:
3917 for (i=0; i<mdb_tls_nkeys; i++) {
3918 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3920 mdb_env_reader_dest(r);
3924 case DLL_PROCESS_DETACH: break;
3929 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3931 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3935 /* Force some symbol references.
3936 * _tls_used forces the linker to create the TLS directory if not already done
3937 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3939 #pragma comment(linker, "/INCLUDE:_tls_used")
3940 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3941 #pragma const_seg(".CRT$XLB")
3942 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3943 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3946 #pragma comment(linker, "/INCLUDE:__tls_used")
3947 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3948 #pragma data_seg(".CRT$XLB")
3949 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3951 #endif /* WIN 32/64 */
3952 #endif /* !__GNUC__ */
3955 /** Downgrade the exclusive lock on the region back to shared */
3957 mdb_env_share_locks(MDB_env *env, int *excl)
3959 int rc = 0, toggle = mdb_env_pick_meta(env);
3961 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3966 /* First acquire a shared lock. The Unlock will
3967 * then release the existing exclusive lock.
3969 memset(&ov, 0, sizeof(ov));
3970 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3973 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3979 struct flock lock_info;
3980 /* The shared lock replaces the existing lock */
3981 memset((void *)&lock_info, 0, sizeof(lock_info));
3982 lock_info.l_type = F_RDLCK;
3983 lock_info.l_whence = SEEK_SET;
3984 lock_info.l_start = 0;
3985 lock_info.l_len = 1;
3986 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3987 (rc = ErrCode()) == EINTR) ;
3988 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3995 /** Try to get exlusive lock, otherwise shared.
3996 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3999 mdb_env_excl_lock(MDB_env *env, int *excl)
4003 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4007 memset(&ov, 0, sizeof(ov));
4008 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4015 struct flock lock_info;
4016 memset((void *)&lock_info, 0, sizeof(lock_info));
4017 lock_info.l_type = F_WRLCK;
4018 lock_info.l_whence = SEEK_SET;
4019 lock_info.l_start = 0;
4020 lock_info.l_len = 1;
4021 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4022 (rc = ErrCode()) == EINTR) ;
4026 # ifdef MDB_USE_POSIX_SEM
4027 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4030 lock_info.l_type = F_RDLCK;
4031 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4032 (rc = ErrCode()) == EINTR) ;
4042 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4044 * @(#) $Revision: 5.1 $
4045 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4046 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4048 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4052 * Please do not copyright this code. This code is in the public domain.
4054 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4055 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4056 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4057 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4058 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4059 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4060 * PERFORMANCE OF THIS SOFTWARE.
4063 * chongo <Landon Curt Noll> /\oo/\
4064 * http://www.isthe.com/chongo/
4066 * Share and Enjoy! :-)
4069 typedef unsigned long long mdb_hash_t;
4070 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4072 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4073 * @param[in] val value to hash
4074 * @param[in] hval initial value for hash
4075 * @return 64 bit hash
4077 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4078 * hval arg on the first call.
4081 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4083 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4084 unsigned char *end = s + val->mv_size;
4086 * FNV-1a hash each octet of the string
4089 /* xor the bottom with the current octet */
4090 hval ^= (mdb_hash_t)*s++;
4092 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4093 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4094 (hval << 7) + (hval << 8) + (hval << 40);
4096 /* return our new hash value */
4100 /** Hash the string and output the encoded hash.
4101 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4102 * very short name limits. We don't care about the encoding being reversible,
4103 * we just want to preserve as many bits of the input as possible in a
4104 * small printable string.
4105 * @param[in] str string to hash
4106 * @param[out] encbuf an array of 11 chars to hold the hash
4108 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4111 mdb_pack85(unsigned long l, char *out)
4115 for (i=0; i<5; i++) {
4116 *out++ = mdb_a85[l % 85];
4122 mdb_hash_enc(MDB_val *val, char *encbuf)
4124 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4126 mdb_pack85(h, encbuf);
4127 mdb_pack85(h>>32, encbuf+5);
4132 /** Open and/or initialize the lock region for the environment.
4133 * @param[in] env The LMDB environment.
4134 * @param[in] lpath The pathname of the file used for the lock region.
4135 * @param[in] mode The Unix permissions for the file, if we create it.
4136 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4137 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4138 * @return 0 on success, non-zero on failure.
4141 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4144 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4146 # define MDB_ERRCODE_ROFS EROFS
4147 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4148 # define MDB_CLOEXEC O_CLOEXEC
4151 # define MDB_CLOEXEC 0
4158 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4159 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4160 FILE_ATTRIBUTE_NORMAL, NULL);
4162 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4164 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4166 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4171 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4172 /* Lose record locks when exec*() */
4173 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4174 fcntl(env->me_lfd, F_SETFD, fdflags);
4177 if (!(env->me_flags & MDB_NOTLS)) {
4178 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4181 env->me_flags |= MDB_ENV_TXKEY;
4183 /* Windows TLS callbacks need help finding their TLS info. */
4184 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4188 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4192 /* Try to get exclusive lock. If we succeed, then
4193 * nobody is using the lock region and we should initialize it.
4195 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4198 size = GetFileSize(env->me_lfd, NULL);
4200 size = lseek(env->me_lfd, 0, SEEK_END);
4201 if (size == -1) goto fail_errno;
4203 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4204 if (size < rsize && *excl > 0) {
4206 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4207 || !SetEndOfFile(env->me_lfd))
4210 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4214 size = rsize - sizeof(MDB_txninfo);
4215 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4220 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4222 if (!mh) goto fail_errno;
4223 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4225 if (!env->me_txns) goto fail_errno;
4227 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4229 if (m == MAP_FAILED) goto fail_errno;
4235 BY_HANDLE_FILE_INFORMATION stbuf;
4244 if (!mdb_sec_inited) {
4245 InitializeSecurityDescriptor(&mdb_null_sd,
4246 SECURITY_DESCRIPTOR_REVISION);
4247 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4248 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4249 mdb_all_sa.bInheritHandle = FALSE;
4250 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4253 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4254 idbuf.volume = stbuf.dwVolumeSerialNumber;
4255 idbuf.nhigh = stbuf.nFileIndexHigh;
4256 idbuf.nlow = stbuf.nFileIndexLow;
4257 val.mv_data = &idbuf;
4258 val.mv_size = sizeof(idbuf);
4259 mdb_hash_enc(&val, encbuf);
4260 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4261 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4262 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4263 if (!env->me_rmutex) goto fail_errno;
4264 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4265 if (!env->me_wmutex) goto fail_errno;
4266 #elif defined(MDB_USE_POSIX_SEM)
4275 #if defined(__NetBSD__)
4276 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4278 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4279 idbuf.dev = stbuf.st_dev;
4280 idbuf.ino = stbuf.st_ino;
4281 val.mv_data = &idbuf;
4282 val.mv_size = sizeof(idbuf);
4283 mdb_hash_enc(&val, encbuf);
4284 #ifdef MDB_SHORT_SEMNAMES
4285 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4287 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4288 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4289 /* Clean up after a previous run, if needed: Try to
4290 * remove both semaphores before doing anything else.
4292 sem_unlink(env->me_txns->mti_rmname);
4293 sem_unlink(env->me_txns->mti_wmname);
4294 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4295 O_CREAT|O_EXCL, mode, 1);
4296 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4297 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4298 O_CREAT|O_EXCL, mode, 1);
4299 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4300 #else /* MDB_USE_POSIX_SEM */
4301 pthread_mutexattr_t mattr;
4303 if ((rc = pthread_mutexattr_init(&mattr))
4304 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4305 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4306 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4308 pthread_mutexattr_destroy(&mattr);
4309 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4311 env->me_txns->mti_magic = MDB_MAGIC;
4312 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4313 env->me_txns->mti_txnid = 0;
4314 env->me_txns->mti_numreaders = 0;
4317 if (env->me_txns->mti_magic != MDB_MAGIC) {
4318 DPUTS("lock region has invalid magic");
4322 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4323 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4324 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4325 rc = MDB_VERSION_MISMATCH;
4329 if (rc && rc != EACCES && rc != EAGAIN) {
4333 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4334 if (!env->me_rmutex) goto fail_errno;
4335 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4336 if (!env->me_wmutex) goto fail_errno;
4337 #elif defined(MDB_USE_POSIX_SEM)
4338 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4339 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4340 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4341 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4352 /** The name of the lock file in the DB environment */
4353 #define LOCKNAME "/lock.mdb"
4354 /** The name of the data file in the DB environment */
4355 #define DATANAME "/data.mdb"
4356 /** The suffix of the lock file when no subdir is used */
4357 #define LOCKSUFF "-lock"
4358 /** Only a subset of the @ref mdb_env flags can be changed
4359 * at runtime. Changing other flags requires closing the
4360 * environment and re-opening it with the new flags.
4362 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4363 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4364 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4366 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4367 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4371 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4373 int oflags, rc, len, excl = -1;
4374 char *lpath, *dpath;
4376 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4380 if (flags & MDB_NOSUBDIR) {
4381 rc = len + sizeof(LOCKSUFF) + len + 1;
4383 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4388 if (flags & MDB_NOSUBDIR) {
4389 dpath = lpath + len + sizeof(LOCKSUFF);
4390 sprintf(lpath, "%s" LOCKSUFF, path);
4391 strcpy(dpath, path);
4393 dpath = lpath + len + sizeof(LOCKNAME);
4394 sprintf(lpath, "%s" LOCKNAME, path);
4395 sprintf(dpath, "%s" DATANAME, path);
4399 flags |= env->me_flags;
4400 if (flags & MDB_RDONLY) {
4401 /* silently ignore WRITEMAP when we're only getting read access */
4402 flags &= ~MDB_WRITEMAP;
4404 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4405 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4408 env->me_flags = flags |= MDB_ENV_ACTIVE;
4412 env->me_path = strdup(path);
4413 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4414 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4415 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4416 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4421 /* For RDONLY, get lockfile after we know datafile exists */
4422 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4423 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4429 if (F_ISSET(flags, MDB_RDONLY)) {
4430 oflags = GENERIC_READ;
4431 len = OPEN_EXISTING;
4433 oflags = GENERIC_READ|GENERIC_WRITE;
4436 mode = FILE_ATTRIBUTE_NORMAL;
4437 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4438 NULL, len, mode, NULL);
4440 if (F_ISSET(flags, MDB_RDONLY))
4443 oflags = O_RDWR | O_CREAT;
4445 env->me_fd = open(dpath, oflags, mode);
4447 if (env->me_fd == INVALID_HANDLE_VALUE) {
4452 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4453 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4458 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4459 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4460 env->me_mfd = env->me_fd;
4462 /* Synchronous fd for meta writes. Needed even with
4463 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4466 len = OPEN_EXISTING;
4467 env->me_mfd = CreateFile(dpath, oflags,
4468 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4469 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4472 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4474 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4479 DPRINTF(("opened dbenv %p", (void *) env));
4481 rc = mdb_env_share_locks(env, &excl);
4485 if (!((flags & MDB_RDONLY) ||
4486 (env->me_pbuf = calloc(1, env->me_psize))))
4492 mdb_env_close0(env, excl);
4498 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4500 mdb_env_close0(MDB_env *env, int excl)
4504 if (!(env->me_flags & MDB_ENV_ACTIVE))
4507 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4508 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4509 free(env->me_dbxs[i].md_name.mv_data);
4512 free(env->me_dbiseqs);
4513 free(env->me_dbflags);
4516 free(env->me_dirty_list);
4517 mdb_midl_free(env->me_free_pgs);
4519 if (env->me_flags & MDB_ENV_TXKEY) {
4520 pthread_key_delete(env->me_txkey);
4522 /* Delete our key from the global list */
4523 for (i=0; i<mdb_tls_nkeys; i++)
4524 if (mdb_tls_keys[i] == env->me_txkey) {
4525 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4533 munmap(env->me_map, env->me_mapsize);
4535 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4536 (void) close(env->me_mfd);
4537 if (env->me_fd != INVALID_HANDLE_VALUE)
4538 (void) close(env->me_fd);
4540 MDB_PID_T pid = env->me_pid;
4541 /* Clearing readers is done in this function because
4542 * me_txkey with its destructor must be disabled first.
4544 for (i = env->me_numreaders; --i >= 0; )
4545 if (env->me_txns->mti_readers[i].mr_pid == pid)
4546 env->me_txns->mti_readers[i].mr_pid = 0;
4548 if (env->me_rmutex) {
4549 CloseHandle(env->me_rmutex);
4550 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4552 /* Windows automatically destroys the mutexes when
4553 * the last handle closes.
4555 #elif defined(MDB_USE_POSIX_SEM)
4556 if (env->me_rmutex != SEM_FAILED) {
4557 sem_close(env->me_rmutex);
4558 if (env->me_wmutex != SEM_FAILED)
4559 sem_close(env->me_wmutex);
4560 /* If we have the filelock: If we are the
4561 * only remaining user, clean up semaphores.
4564 mdb_env_excl_lock(env, &excl);
4566 sem_unlink(env->me_txns->mti_rmname);
4567 sem_unlink(env->me_txns->mti_wmname);
4571 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4573 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4576 /* Unlock the lockfile. Windows would have unlocked it
4577 * after closing anyway, but not necessarily at once.
4579 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4582 (void) close(env->me_lfd);
4585 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4590 mdb_env_close(MDB_env *env)
4597 VGMEMP_DESTROY(env);
4598 while ((dp = env->me_dpages) != NULL) {
4599 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4600 env->me_dpages = dp->mp_next;
4604 mdb_env_close0(env, 0);
4608 /** Compare two items pointing at aligned size_t's */
4610 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4612 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4613 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4616 /** Compare two items pointing at aligned unsigned int's */
4618 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4620 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4621 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4624 /** Compare two items pointing at unsigned ints of unknown alignment.
4625 * Nodes and keys are guaranteed to be 2-byte aligned.
4628 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4630 #if BYTE_ORDER == LITTLE_ENDIAN
4631 unsigned short *u, *c;
4634 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4635 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4638 } while(!x && u > (unsigned short *)a->mv_data);
4641 unsigned short *u, *c, *end;
4644 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4645 u = (unsigned short *)a->mv_data;
4646 c = (unsigned short *)b->mv_data;
4649 } while(!x && u < end);
4654 /** Compare two items pointing at size_t's of unknown alignment. */
4655 #ifdef MISALIGNED_OK
4656 # define mdb_cmp_clong mdb_cmp_long
4658 # define mdb_cmp_clong mdb_cmp_cint
4661 /** Compare two items lexically */
4663 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4670 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4676 diff = memcmp(a->mv_data, b->mv_data, len);
4677 return diff ? diff : len_diff<0 ? -1 : len_diff;
4680 /** Compare two items in reverse byte order */
4682 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4684 const unsigned char *p1, *p2, *p1_lim;
4688 p1_lim = (const unsigned char *)a->mv_data;
4689 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4690 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4692 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4698 while (p1 > p1_lim) {
4699 diff = *--p1 - *--p2;
4703 return len_diff<0 ? -1 : len_diff;
4706 /** Search for key within a page, using binary search.
4707 * Returns the smallest entry larger or equal to the key.
4708 * If exactp is non-null, stores whether the found entry was an exact match
4709 * in *exactp (1 or 0).
4710 * Updates the cursor index with the index of the found entry.
4711 * If no entry larger or equal to the key is found, returns NULL.
4714 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4716 unsigned int i = 0, nkeys;
4719 MDB_page *mp = mc->mc_pg[mc->mc_top];
4720 MDB_node *node = NULL;
4725 nkeys = NUMKEYS(mp);
4727 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4728 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4731 low = IS_LEAF(mp) ? 0 : 1;
4733 cmp = mc->mc_dbx->md_cmp;
4735 /* Branch pages have no data, so if using integer keys,
4736 * alignment is guaranteed. Use faster mdb_cmp_int.
4738 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4739 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4746 nodekey.mv_size = mc->mc_db->md_pad;
4747 node = NODEPTR(mp, 0); /* fake */
4748 while (low <= high) {
4749 i = (low + high) >> 1;
4750 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4751 rc = cmp(key, &nodekey);
4752 DPRINTF(("found leaf index %u [%s], rc = %i",
4753 i, DKEY(&nodekey), rc));
4762 while (low <= high) {
4763 i = (low + high) >> 1;
4765 node = NODEPTR(mp, i);
4766 nodekey.mv_size = NODEKSZ(node);
4767 nodekey.mv_data = NODEKEY(node);
4769 rc = cmp(key, &nodekey);
4772 DPRINTF(("found leaf index %u [%s], rc = %i",
4773 i, DKEY(&nodekey), rc));
4775 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4776 i, DKEY(&nodekey), NODEPGNO(node), rc));
4787 if (rc > 0) { /* Found entry is less than the key. */
4788 i++; /* Skip to get the smallest entry larger than key. */
4790 node = NODEPTR(mp, i);
4793 *exactp = (rc == 0 && nkeys > 0);
4794 /* store the key index */
4795 mc->mc_ki[mc->mc_top] = i;
4797 /* There is no entry larger or equal to the key. */
4800 /* nodeptr is fake for LEAF2 */
4806 mdb_cursor_adjust(MDB_cursor *mc, func)
4810 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4811 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4818 /** Pop a page off the top of the cursor's stack. */
4820 mdb_cursor_pop(MDB_cursor *mc)
4824 MDB_page *top = mc->mc_pg[mc->mc_top];
4830 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4831 DDBI(mc), (void *) mc));
4835 /** Push a page onto the top of the cursor's stack. */
4837 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4839 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4840 DDBI(mc), (void *) mc));
4842 if (mc->mc_snum >= CURSOR_STACK) {
4843 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4844 return MDB_CURSOR_FULL;
4847 mc->mc_top = mc->mc_snum++;
4848 mc->mc_pg[mc->mc_top] = mp;
4849 mc->mc_ki[mc->mc_top] = 0;
4854 /** Find the address of the page corresponding to a given page number.
4855 * @param[in] txn the transaction for this access.
4856 * @param[in] pgno the page number for the page to retrieve.
4857 * @param[out] ret address of a pointer where the page's address will be stored.
4858 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4859 * @return 0 on success, non-zero on failure.
4862 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4864 MDB_env *env = txn->mt_env;
4868 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4872 MDB_ID2L dl = tx2->mt_u.dirty_list;
4874 /* Spilled pages were dirtied in this txn and flushed
4875 * because the dirty list got full. Bring this page
4876 * back in from the map (but don't unspill it here,
4877 * leave that unless page_touch happens again).
4879 if (tx2->mt_spill_pgs) {
4880 MDB_ID pn = pgno << 1;
4881 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4882 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4883 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4888 unsigned x = mdb_mid2l_search(dl, pgno);
4889 if (x <= dl[0].mid && dl[x].mid == pgno) {
4895 } while ((tx2 = tx2->mt_parent) != NULL);
4898 if (pgno < txn->mt_next_pgno) {
4900 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4902 DPRINTF(("page %"Z"u not found", pgno));
4903 txn->mt_flags |= MDB_TXN_ERROR;
4904 return MDB_PAGE_NOTFOUND;
4914 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4915 * The cursor is at the root page, set up the rest of it.
4918 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4920 MDB_page *mp = mc->mc_pg[mc->mc_top];
4924 while (IS_BRANCH(mp)) {
4928 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4929 mdb_cassert(mc, NUMKEYS(mp) > 1);
4930 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4932 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4934 if (flags & MDB_PS_LAST)
4935 i = NUMKEYS(mp) - 1;
4938 node = mdb_node_search(mc, key, &exact);
4940 i = NUMKEYS(mp) - 1;
4942 i = mc->mc_ki[mc->mc_top];
4944 mdb_cassert(mc, i > 0);
4948 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4951 mdb_cassert(mc, i < NUMKEYS(mp));
4952 node = NODEPTR(mp, i);
4954 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4957 mc->mc_ki[mc->mc_top] = i;
4958 if ((rc = mdb_cursor_push(mc, mp)))
4961 if (flags & MDB_PS_MODIFY) {
4962 if ((rc = mdb_page_touch(mc)) != 0)
4964 mp = mc->mc_pg[mc->mc_top];
4969 DPRINTF(("internal error, index points to a %02X page!?",
4971 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4972 return MDB_CORRUPTED;
4975 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4976 key ? DKEY(key) : "null"));
4977 mc->mc_flags |= C_INITIALIZED;
4978 mc->mc_flags &= ~C_EOF;
4983 /** Search for the lowest key under the current branch page.
4984 * This just bypasses a NUMKEYS check in the current page
4985 * before calling mdb_page_search_root(), because the callers
4986 * are all in situations where the current page is known to
4990 mdb_page_search_lowest(MDB_cursor *mc)
4992 MDB_page *mp = mc->mc_pg[mc->mc_top];
4993 MDB_node *node = NODEPTR(mp, 0);
4996 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4999 mc->mc_ki[mc->mc_top] = 0;
5000 if ((rc = mdb_cursor_push(mc, mp)))
5002 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5005 /** Search for the page a given key should be in.
5006 * Push it and its parent pages on the cursor stack.
5007 * @param[in,out] mc the cursor for this operation.
5008 * @param[in] key the key to search for, or NULL for first/last page.
5009 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5010 * are touched (updated with new page numbers).
5011 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5012 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5013 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5014 * @return 0 on success, non-zero on failure.
5017 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5022 /* Make sure the txn is still viable, then find the root from
5023 * the txn's db table and set it as the root of the cursor's stack.
5025 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5026 DPUTS("transaction has failed, must abort");
5029 /* Make sure we're using an up-to-date root */
5030 if (*mc->mc_dbflag & DB_STALE) {
5032 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5034 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5035 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5042 MDB_node *leaf = mdb_node_search(&mc2,
5043 &mc->mc_dbx->md_name, &exact);
5045 return MDB_NOTFOUND;
5046 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5049 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5051 /* The txn may not know this DBI, or another process may
5052 * have dropped and recreated the DB with other flags.
5054 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5055 return MDB_INCOMPATIBLE;
5056 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5058 *mc->mc_dbflag &= ~DB_STALE;
5060 root = mc->mc_db->md_root;
5062 if (root == P_INVALID) { /* Tree is empty. */
5063 DPUTS("tree is empty");
5064 return MDB_NOTFOUND;
5068 mdb_cassert(mc, root > 1);
5069 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5070 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5076 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5077 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5079 if (flags & MDB_PS_MODIFY) {
5080 if ((rc = mdb_page_touch(mc)))
5084 if (flags & MDB_PS_ROOTONLY)
5087 return mdb_page_search_root(mc, key, flags);
5091 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5093 MDB_txn *txn = mc->mc_txn;
5094 pgno_t pg = mp->mp_pgno;
5095 unsigned x = 0, ovpages = mp->mp_pages;
5096 MDB_env *env = txn->mt_env;
5097 MDB_IDL sl = txn->mt_spill_pgs;
5098 MDB_ID pn = pg << 1;
5101 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5102 /* If the page is dirty or on the spill list we just acquired it,
5103 * so we should give it back to our current free list, if any.
5104 * Otherwise put it onto the list of pages we freed in this txn.
5106 * Won't create me_pghead: me_pglast must be inited along with it.
5107 * Unsupported in nested txns: They would need to hide the page
5108 * range in ancestor txns' dirty and spilled lists.
5110 if (env->me_pghead &&
5112 ((mp->mp_flags & P_DIRTY) ||
5113 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5117 MDB_ID2 *dl, ix, iy;
5118 rc = mdb_midl_need(&env->me_pghead, ovpages);
5121 if (!(mp->mp_flags & P_DIRTY)) {
5122 /* This page is no longer spilled */
5129 /* Remove from dirty list */
5130 dl = txn->mt_u.dirty_list;
5132 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5138 mdb_cassert(mc, x > 1);
5140 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5141 txn->mt_flags |= MDB_TXN_ERROR;
5142 return MDB_CORRUPTED;
5145 if (!(env->me_flags & MDB_WRITEMAP))
5146 mdb_dpage_free(env, mp);
5148 /* Insert in me_pghead */
5149 mop = env->me_pghead;
5150 j = mop[0] + ovpages;
5151 for (i = mop[0]; i && mop[i] < pg; i--)
5157 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5161 mc->mc_db->md_overflow_pages -= ovpages;
5165 /** Return the data associated with a given node.
5166 * @param[in] txn The transaction for this operation.
5167 * @param[in] leaf The node being read.
5168 * @param[out] data Updated to point to the node's data.
5169 * @return 0 on success, non-zero on failure.
5172 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5174 MDB_page *omp; /* overflow page */
5178 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5179 data->mv_size = NODEDSZ(leaf);
5180 data->mv_data = NODEDATA(leaf);
5184 /* Read overflow data.
5186 data->mv_size = NODEDSZ(leaf);
5187 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5188 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5189 DPRINTF(("read overflow page %"Z"u failed", pgno));
5192 data->mv_data = METADATA(omp);
5198 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5199 MDB_val *key, MDB_val *data)
5206 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5208 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5211 if (txn->mt_flags & MDB_TXN_ERROR)
5214 mdb_cursor_init(&mc, txn, dbi, &mx);
5215 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5218 /** Find a sibling for a page.
5219 * Replaces the page at the top of the cursor's stack with the
5220 * specified sibling, if one exists.
5221 * @param[in] mc The cursor for this operation.
5222 * @param[in] move_right Non-zero if the right sibling is requested,
5223 * otherwise the left sibling.
5224 * @return 0 on success, non-zero on failure.
5227 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5233 if (mc->mc_snum < 2) {
5234 return MDB_NOTFOUND; /* root has no siblings */
5238 DPRINTF(("parent page is page %"Z"u, index %u",
5239 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5241 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5242 : (mc->mc_ki[mc->mc_top] == 0)) {
5243 DPRINTF(("no more keys left, moving to %s sibling",
5244 move_right ? "right" : "left"));
5245 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5246 /* undo cursor_pop before returning */
5253 mc->mc_ki[mc->mc_top]++;
5255 mc->mc_ki[mc->mc_top]--;
5256 DPRINTF(("just moving to %s index key %u",
5257 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5259 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5261 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5262 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5263 /* mc will be inconsistent if caller does mc_snum++ as above */
5264 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5268 mdb_cursor_push(mc, mp);
5270 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5275 /** Move the cursor to the next data item. */
5277 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5283 if (mc->mc_flags & C_EOF) {
5284 return MDB_NOTFOUND;
5287 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5289 mp = mc->mc_pg[mc->mc_top];
5291 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5292 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5293 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5294 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5295 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5296 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5297 if (rc == MDB_SUCCESS)
5298 MDB_GET_KEY(leaf, key);
5303 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5304 if (op == MDB_NEXT_DUP)
5305 return MDB_NOTFOUND;
5309 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5310 mdb_dbg_pgno(mp), (void *) mc));
5311 if (mc->mc_flags & C_DEL)
5314 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5315 DPUTS("=====> move to next sibling page");
5316 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5317 mc->mc_flags |= C_EOF;
5320 mp = mc->mc_pg[mc->mc_top];
5321 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5323 mc->mc_ki[mc->mc_top]++;
5326 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5327 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5330 key->mv_size = mc->mc_db->md_pad;
5331 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5335 mdb_cassert(mc, IS_LEAF(mp));
5336 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5338 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5339 mdb_xcursor_init1(mc, leaf);
5342 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5345 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5346 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5347 if (rc != MDB_SUCCESS)
5352 MDB_GET_KEY(leaf, key);
5356 /** Move the cursor to the previous data item. */
5358 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5364 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5366 mp = mc->mc_pg[mc->mc_top];
5368 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5369 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5370 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5371 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5372 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5373 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5374 if (rc == MDB_SUCCESS) {
5375 MDB_GET_KEY(leaf, key);
5376 mc->mc_flags &= ~C_EOF;
5381 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5382 if (op == MDB_PREV_DUP)
5383 return MDB_NOTFOUND;
5388 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5389 mdb_dbg_pgno(mp), (void *) mc));
5391 if (mc->mc_ki[mc->mc_top] == 0) {
5392 DPUTS("=====> move to prev sibling page");
5393 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5396 mp = mc->mc_pg[mc->mc_top];
5397 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5398 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5400 mc->mc_ki[mc->mc_top]--;
5402 mc->mc_flags &= ~C_EOF;
5404 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5405 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5408 key->mv_size = mc->mc_db->md_pad;
5409 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5413 mdb_cassert(mc, IS_LEAF(mp));
5414 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5416 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5417 mdb_xcursor_init1(mc, leaf);
5420 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5423 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5424 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5425 if (rc != MDB_SUCCESS)
5430 MDB_GET_KEY(leaf, key);
5434 /** Set the cursor on a specific data item. */
5436 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5437 MDB_cursor_op op, int *exactp)
5441 MDB_node *leaf = NULL;
5444 if (key->mv_size == 0)
5445 return MDB_BAD_VALSIZE;
5448 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5450 /* See if we're already on the right page */
5451 if (mc->mc_flags & C_INITIALIZED) {
5454 mp = mc->mc_pg[mc->mc_top];
5456 mc->mc_ki[mc->mc_top] = 0;
5457 return MDB_NOTFOUND;
5459 if (mp->mp_flags & P_LEAF2) {
5460 nodekey.mv_size = mc->mc_db->md_pad;
5461 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5463 leaf = NODEPTR(mp, 0);
5464 MDB_GET_KEY2(leaf, nodekey);
5466 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5468 /* Probably happens rarely, but first node on the page
5469 * was the one we wanted.
5471 mc->mc_ki[mc->mc_top] = 0;
5478 unsigned int nkeys = NUMKEYS(mp);
5480 if (mp->mp_flags & P_LEAF2) {
5481 nodekey.mv_data = LEAF2KEY(mp,
5482 nkeys-1, nodekey.mv_size);
5484 leaf = NODEPTR(mp, nkeys-1);
5485 MDB_GET_KEY2(leaf, nodekey);
5487 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5489 /* last node was the one we wanted */
5490 mc->mc_ki[mc->mc_top] = nkeys-1;
5496 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5497 /* This is definitely the right page, skip search_page */
5498 if (mp->mp_flags & P_LEAF2) {
5499 nodekey.mv_data = LEAF2KEY(mp,
5500 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5502 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5503 MDB_GET_KEY2(leaf, nodekey);
5505 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5507 /* current node was the one we wanted */
5517 /* If any parents have right-sibs, search.
5518 * Otherwise, there's nothing further.
5520 for (i=0; i<mc->mc_top; i++)
5522 NUMKEYS(mc->mc_pg[i])-1)
5524 if (i == mc->mc_top) {
5525 /* There are no other pages */
5526 mc->mc_ki[mc->mc_top] = nkeys;
5527 return MDB_NOTFOUND;
5531 /* There are no other pages */
5532 mc->mc_ki[mc->mc_top] = 0;
5533 if (op == MDB_SET_RANGE && !exactp) {
5537 return MDB_NOTFOUND;
5541 rc = mdb_page_search(mc, key, 0);
5542 if (rc != MDB_SUCCESS)
5545 mp = mc->mc_pg[mc->mc_top];
5546 mdb_cassert(mc, IS_LEAF(mp));
5549 leaf = mdb_node_search(mc, key, exactp);
5550 if (exactp != NULL && !*exactp) {
5551 /* MDB_SET specified and not an exact match. */
5552 return MDB_NOTFOUND;
5556 DPUTS("===> inexact leaf not found, goto sibling");
5557 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5558 return rc; /* no entries matched */
5559 mp = mc->mc_pg[mc->mc_top];
5560 mdb_cassert(mc, IS_LEAF(mp));
5561 leaf = NODEPTR(mp, 0);
5565 mc->mc_flags |= C_INITIALIZED;
5566 mc->mc_flags &= ~C_EOF;
5569 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5570 key->mv_size = mc->mc_db->md_pad;
5571 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5576 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5577 mdb_xcursor_init1(mc, leaf);
5580 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5581 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5582 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5585 if (op == MDB_GET_BOTH) {
5591 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5592 if (rc != MDB_SUCCESS)
5595 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5597 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5599 rc = mc->mc_dbx->md_dcmp(data, &d2);
5601 if (op == MDB_GET_BOTH || rc > 0)
5602 return MDB_NOTFOUND;
5609 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5610 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5615 /* The key already matches in all other cases */
5616 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5617 MDB_GET_KEY(leaf, key);
5618 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5623 /** Move the cursor to the first item in the database. */
5625 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5631 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5633 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5634 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5635 if (rc != MDB_SUCCESS)
5638 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5640 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5641 mc->mc_flags |= C_INITIALIZED;
5642 mc->mc_flags &= ~C_EOF;
5644 mc->mc_ki[mc->mc_top] = 0;
5646 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5647 key->mv_size = mc->mc_db->md_pad;
5648 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5653 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5654 mdb_xcursor_init1(mc, leaf);
5655 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5659 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5663 MDB_GET_KEY(leaf, key);
5667 /** Move the cursor to the last item in the database. */
5669 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5675 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5677 if (!(mc->mc_flags & C_EOF)) {
5679 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5680 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5681 if (rc != MDB_SUCCESS)
5684 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5687 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5688 mc->mc_flags |= C_INITIALIZED|C_EOF;
5689 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5691 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5692 key->mv_size = mc->mc_db->md_pad;
5693 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5698 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5699 mdb_xcursor_init1(mc, leaf);
5700 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5704 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5709 MDB_GET_KEY(leaf, key);
5714 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5719 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5724 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5728 case MDB_GET_CURRENT:
5729 if (!(mc->mc_flags & C_INITIALIZED)) {
5732 MDB_page *mp = mc->mc_pg[mc->mc_top];
5733 int nkeys = NUMKEYS(mp);
5734 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5735 mc->mc_ki[mc->mc_top] = nkeys;
5741 key->mv_size = mc->mc_db->md_pad;
5742 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5744 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5745 MDB_GET_KEY(leaf, key);
5747 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5748 if (mc->mc_flags & C_DEL)
5749 mdb_xcursor_init1(mc, leaf);
5750 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5752 rc = mdb_node_read(mc->mc_txn, leaf, data);
5759 case MDB_GET_BOTH_RANGE:
5764 if (mc->mc_xcursor == NULL) {
5765 rc = MDB_INCOMPATIBLE;
5775 rc = mdb_cursor_set(mc, key, data, op,
5776 op == MDB_SET_RANGE ? NULL : &exact);
5779 case MDB_GET_MULTIPLE:
5780 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5784 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5785 rc = MDB_INCOMPATIBLE;
5789 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5790 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5793 case MDB_NEXT_MULTIPLE:
5798 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5799 rc = MDB_INCOMPATIBLE;
5802 if (!(mc->mc_flags & C_INITIALIZED))
5803 rc = mdb_cursor_first(mc, key, data);
5805 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5806 if (rc == MDB_SUCCESS) {
5807 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5810 mx = &mc->mc_xcursor->mx_cursor;
5811 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5813 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5814 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5822 case MDB_NEXT_NODUP:
5823 if (!(mc->mc_flags & C_INITIALIZED))
5824 rc = mdb_cursor_first(mc, key, data);
5826 rc = mdb_cursor_next(mc, key, data, op);
5830 case MDB_PREV_NODUP:
5831 if (!(mc->mc_flags & C_INITIALIZED)) {
5832 rc = mdb_cursor_last(mc, key, data);
5835 mc->mc_flags |= C_INITIALIZED;
5836 mc->mc_ki[mc->mc_top]++;
5838 rc = mdb_cursor_prev(mc, key, data, op);
5841 rc = mdb_cursor_first(mc, key, data);
5844 mfunc = mdb_cursor_first;
5846 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5850 if (mc->mc_xcursor == NULL) {
5851 rc = MDB_INCOMPATIBLE;
5855 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5856 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5857 MDB_GET_KEY(leaf, key);
5859 rc = mdb_node_read(mc->mc_txn, leaf, data);
5863 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5867 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5870 rc = mdb_cursor_last(mc, key, data);
5873 mfunc = mdb_cursor_last;
5876 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5881 if (mc->mc_flags & C_DEL)
5882 mc->mc_flags ^= C_DEL;
5887 /** Touch all the pages in the cursor stack. Set mc_top.
5888 * Makes sure all the pages are writable, before attempting a write operation.
5889 * @param[in] mc The cursor to operate on.
5892 mdb_cursor_touch(MDB_cursor *mc)
5894 int rc = MDB_SUCCESS;
5896 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5899 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5901 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5902 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5905 *mc->mc_dbflag |= DB_DIRTY;
5910 rc = mdb_page_touch(mc);
5911 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5912 mc->mc_top = mc->mc_snum-1;
5917 /** Do not spill pages to disk if txn is getting full, may fail instead */
5918 #define MDB_NOSPILL 0x8000
5921 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5924 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5926 MDB_node *leaf = NULL;
5929 MDB_val xdata, *rdata, dkey, olddata;
5931 int do_sub = 0, insert_key, insert_data;
5932 unsigned int mcount = 0, dcount = 0, nospill;
5935 unsigned int nflags;
5938 if (mc == NULL || key == NULL)
5941 env = mc->mc_txn->mt_env;
5943 /* Check this first so counter will always be zero on any
5946 if (flags & MDB_MULTIPLE) {
5947 dcount = data[1].mv_size;
5948 data[1].mv_size = 0;
5949 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5950 return MDB_INCOMPATIBLE;
5953 nospill = flags & MDB_NOSPILL;
5954 flags &= ~MDB_NOSPILL;
5956 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5957 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5959 if (key->mv_size-1 >= ENV_MAXKEY(env))
5960 return MDB_BAD_VALSIZE;
5962 #if SIZE_MAX > MAXDATASIZE
5963 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5964 return MDB_BAD_VALSIZE;
5966 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5967 return MDB_BAD_VALSIZE;
5970 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5971 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5975 if (flags == MDB_CURRENT) {
5976 if (!(mc->mc_flags & C_INITIALIZED))
5979 } else if (mc->mc_db->md_root == P_INVALID) {
5980 /* new database, cursor has nothing to point to */
5983 mc->mc_flags &= ~C_INITIALIZED;
5988 if (flags & MDB_APPEND) {
5990 rc = mdb_cursor_last(mc, &k2, &d2);
5992 rc = mc->mc_dbx->md_cmp(key, &k2);
5995 mc->mc_ki[mc->mc_top]++;
5997 /* new key is <= last key */
6002 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6004 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6005 DPRINTF(("duplicate key [%s]", DKEY(key)));
6007 return MDB_KEYEXIST;
6009 if (rc && rc != MDB_NOTFOUND)
6013 if (mc->mc_flags & C_DEL)
6014 mc->mc_flags ^= C_DEL;
6016 /* Cursor is positioned, check for room in the dirty list */
6018 if (flags & MDB_MULTIPLE) {
6020 xdata.mv_size = data->mv_size * dcount;
6024 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6028 if (rc == MDB_NO_ROOT) {
6030 /* new database, write a root leaf page */
6031 DPUTS("allocating new root leaf page");
6032 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6035 mdb_cursor_push(mc, np);
6036 mc->mc_db->md_root = np->mp_pgno;
6037 mc->mc_db->md_depth++;
6038 *mc->mc_dbflag |= DB_DIRTY;
6039 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6041 np->mp_flags |= P_LEAF2;
6042 mc->mc_flags |= C_INITIALIZED;
6044 /* make sure all cursor pages are writable */
6045 rc2 = mdb_cursor_touch(mc);
6050 insert_key = insert_data = rc;
6052 /* The key does not exist */
6053 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6054 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6055 LEAFSIZE(key, data) > env->me_nodemax)
6057 /* Too big for a node, insert in sub-DB. Set up an empty
6058 * "old sub-page" for prep_subDB to expand to a full page.
6060 fp_flags = P_LEAF|P_DIRTY;
6062 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6063 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6064 olddata.mv_size = PAGEHDRSZ;
6068 /* there's only a key anyway, so this is a no-op */
6069 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6071 unsigned int ksize = mc->mc_db->md_pad;
6072 if (key->mv_size != ksize)
6073 return MDB_BAD_VALSIZE;
6074 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6075 memcpy(ptr, key->mv_data, ksize);
6077 /* if overwriting slot 0 of leaf, need to
6078 * update branch key if there is a parent page
6080 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6081 unsigned short top = mc->mc_top;
6083 /* slot 0 is always an empty key, find real slot */
6084 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6086 if (mc->mc_ki[mc->mc_top])
6087 rc2 = mdb_update_key(mc, key);
6098 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6099 olddata.mv_size = NODEDSZ(leaf);
6100 olddata.mv_data = NODEDATA(leaf);
6103 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6104 /* Prepare (sub-)page/sub-DB to accept the new item,
6105 * if needed. fp: old sub-page or a header faking
6106 * it. mp: new (sub-)page. offset: growth in page
6107 * size. xdata: node data with new page or DB.
6109 unsigned i, offset = 0;
6110 mp = fp = xdata.mv_data = env->me_pbuf;
6111 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6113 /* Was a single item before, must convert now */
6114 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6115 /* Just overwrite the current item */
6116 if (flags == MDB_CURRENT)
6119 #if UINT_MAX < SIZE_MAX
6120 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6121 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6123 /* does data match? */
6124 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6125 if (flags & MDB_NODUPDATA)
6126 return MDB_KEYEXIST;
6131 /* Back up original data item */
6132 dkey.mv_size = olddata.mv_size;
6133 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6135 /* Make sub-page header for the dup items, with dummy body */
6136 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6137 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6138 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6139 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6140 fp->mp_flags |= P_LEAF2;
6141 fp->mp_pad = data->mv_size;
6142 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6144 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6145 (dkey.mv_size & 1) + (data->mv_size & 1);
6147 fp->mp_upper = xdata.mv_size - PAGEBASE;
6148 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6149 } else if (leaf->mn_flags & F_SUBDATA) {
6150 /* Data is on sub-DB, just store it */
6151 flags |= F_DUPDATA|F_SUBDATA;
6154 /* Data is on sub-page */
6155 fp = olddata.mv_data;
6158 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6159 offset = EVEN(NODESIZE + sizeof(indx_t) +
6163 offset = fp->mp_pad;
6164 if (SIZELEFT(fp) < offset) {
6165 offset *= 4; /* space for 4 more */
6168 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6170 fp->mp_flags |= P_DIRTY;
6171 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6172 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6176 xdata.mv_size = olddata.mv_size + offset;
6179 fp_flags = fp->mp_flags;
6180 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6181 /* Too big for a sub-page, convert to sub-DB */
6182 fp_flags &= ~P_SUBP;
6184 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6185 fp_flags |= P_LEAF2;
6186 dummy.md_pad = fp->mp_pad;
6187 dummy.md_flags = MDB_DUPFIXED;
6188 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6189 dummy.md_flags |= MDB_INTEGERKEY;
6195 dummy.md_branch_pages = 0;
6196 dummy.md_leaf_pages = 1;
6197 dummy.md_overflow_pages = 0;
6198 dummy.md_entries = NUMKEYS(fp);
6199 xdata.mv_size = sizeof(MDB_db);
6200 xdata.mv_data = &dummy;
6201 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6203 offset = env->me_psize - olddata.mv_size;
6204 flags |= F_DUPDATA|F_SUBDATA;
6205 dummy.md_root = mp->mp_pgno;
6208 mp->mp_flags = fp_flags | P_DIRTY;
6209 mp->mp_pad = fp->mp_pad;
6210 mp->mp_lower = fp->mp_lower;
6211 mp->mp_upper = fp->mp_upper + offset;
6212 if (fp_flags & P_LEAF2) {
6213 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6215 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6216 olddata.mv_size - fp->mp_upper - PAGEBASE);
6217 for (i=0; i<NUMKEYS(fp); i++)
6218 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6226 mdb_node_del(mc, 0);
6230 /* overflow page overwrites need special handling */
6231 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6234 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6236 memcpy(&pg, olddata.mv_data, sizeof(pg));
6237 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6239 ovpages = omp->mp_pages;
6241 /* Is the ov page large enough? */
6242 if (ovpages >= dpages) {
6243 if (!(omp->mp_flags & P_DIRTY) &&
6244 (level || (env->me_flags & MDB_WRITEMAP)))
6246 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6249 level = 0; /* dirty in this txn or clean */
6252 if (omp->mp_flags & P_DIRTY) {
6253 /* yes, overwrite it. Note in this case we don't
6254 * bother to try shrinking the page if the new data
6255 * is smaller than the overflow threshold.
6258 /* It is writable only in a parent txn */
6259 size_t sz = (size_t) env->me_psize * ovpages, off;
6260 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6266 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6267 mdb_cassert(mc, rc2 == 0);
6268 if (!(flags & MDB_RESERVE)) {
6269 /* Copy end of page, adjusting alignment so
6270 * compiler may copy words instead of bytes.
6272 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6273 memcpy((size_t *)((char *)np + off),
6274 (size_t *)((char *)omp + off), sz - off);
6277 memcpy(np, omp, sz); /* Copy beginning of page */
6280 SETDSZ(leaf, data->mv_size);
6281 if (F_ISSET(flags, MDB_RESERVE))
6282 data->mv_data = METADATA(omp);
6284 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6288 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6290 } else if (data->mv_size == olddata.mv_size) {
6291 /* same size, just replace it. Note that we could
6292 * also reuse this node if the new data is smaller,
6293 * but instead we opt to shrink the node in that case.
6295 if (F_ISSET(flags, MDB_RESERVE))
6296 data->mv_data = olddata.mv_data;
6297 else if (!(mc->mc_flags & C_SUB))
6298 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6300 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6305 mdb_node_del(mc, 0);
6311 nflags = flags & NODE_ADD_FLAGS;
6312 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6313 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6314 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6315 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6317 nflags |= MDB_SPLIT_REPLACE;
6318 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6320 /* There is room already in this leaf page. */
6321 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6322 if (rc == 0 && insert_key) {
6323 /* Adjust other cursors pointing to mp */
6324 MDB_cursor *m2, *m3;
6325 MDB_dbi dbi = mc->mc_dbi;
6326 unsigned i = mc->mc_top;
6327 MDB_page *mp = mc->mc_pg[i];
6329 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6330 if (mc->mc_flags & C_SUB)
6331 m3 = &m2->mc_xcursor->mx_cursor;
6334 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6335 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6342 if (rc == MDB_SUCCESS) {
6343 /* Now store the actual data in the child DB. Note that we're
6344 * storing the user data in the keys field, so there are strict
6345 * size limits on dupdata. The actual data fields of the child
6346 * DB are all zero size.
6354 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6355 if (flags & MDB_CURRENT) {
6356 xflags = MDB_CURRENT|MDB_NOSPILL;
6358 mdb_xcursor_init1(mc, leaf);
6359 xflags = (flags & MDB_NODUPDATA) ?
6360 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6362 /* converted, write the original data first */
6364 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6368 /* Adjust other cursors pointing to mp */
6370 unsigned i = mc->mc_top;
6371 MDB_page *mp = mc->mc_pg[i];
6373 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6374 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6375 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6376 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6377 mdb_xcursor_init1(m2, leaf);
6381 /* we've done our job */
6384 ecount = mc->mc_xcursor->mx_db.md_entries;
6385 if (flags & MDB_APPENDDUP)
6386 xflags |= MDB_APPEND;
6387 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6388 if (flags & F_SUBDATA) {
6389 void *db = NODEDATA(leaf);
6390 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6392 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6394 /* Increment count unless we just replaced an existing item. */
6396 mc->mc_db->md_entries++;
6398 /* Invalidate txn if we created an empty sub-DB */
6401 /* If we succeeded and the key didn't exist before,
6402 * make sure the cursor is marked valid.
6404 mc->mc_flags |= C_INITIALIZED;
6406 if (flags & MDB_MULTIPLE) {
6409 /* let caller know how many succeeded, if any */
6410 data[1].mv_size = mcount;
6411 if (mcount < dcount) {
6412 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6413 insert_key = insert_data = 0;
6420 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6423 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6428 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6434 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6435 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6437 if (!(mc->mc_flags & C_INITIALIZED))
6440 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6441 return MDB_NOTFOUND;
6443 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6446 rc = mdb_cursor_touch(mc);
6450 mp = mc->mc_pg[mc->mc_top];
6453 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6455 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6456 if (flags & MDB_NODUPDATA) {
6457 /* mdb_cursor_del0() will subtract the final entry */
6458 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6460 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6461 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6463 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6466 /* If sub-DB still has entries, we're done */
6467 if (mc->mc_xcursor->mx_db.md_entries) {
6468 if (leaf->mn_flags & F_SUBDATA) {
6469 /* update subDB info */
6470 void *db = NODEDATA(leaf);
6471 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6474 /* shrink fake page */
6475 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6476 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6477 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6478 /* fix other sub-DB cursors pointed at this fake page */
6479 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6480 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6481 if (m2->mc_pg[mc->mc_top] == mp &&
6482 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6483 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6486 mc->mc_db->md_entries--;
6487 mc->mc_flags |= C_DEL;
6490 /* otherwise fall thru and delete the sub-DB */
6493 if (leaf->mn_flags & F_SUBDATA) {
6494 /* add all the child DB's pages to the free list */
6495 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6501 /* add overflow pages to free list */
6502 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6506 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6507 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6508 (rc = mdb_ovpage_free(mc, omp)))
6513 return mdb_cursor_del0(mc);
6516 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6520 /** Allocate and initialize new pages for a database.
6521 * @param[in] mc a cursor on the database being added to.
6522 * @param[in] flags flags defining what type of page is being allocated.
6523 * @param[in] num the number of pages to allocate. This is usually 1,
6524 * unless allocating overflow pages for a large record.
6525 * @param[out] mp Address of a page, or NULL on failure.
6526 * @return 0 on success, non-zero on failure.
6529 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6534 if ((rc = mdb_page_alloc(mc, num, &np)))
6536 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6537 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6538 np->mp_flags = flags | P_DIRTY;
6539 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6540 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6543 mc->mc_db->md_branch_pages++;
6544 else if (IS_LEAF(np))
6545 mc->mc_db->md_leaf_pages++;
6546 else if (IS_OVERFLOW(np)) {
6547 mc->mc_db->md_overflow_pages += num;
6555 /** Calculate the size of a leaf node.
6556 * The size depends on the environment's page size; if a data item
6557 * is too large it will be put onto an overflow page and the node
6558 * size will only include the key and not the data. Sizes are always
6559 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6560 * of the #MDB_node headers.
6561 * @param[in] env The environment handle.
6562 * @param[in] key The key for the node.
6563 * @param[in] data The data for the node.
6564 * @return The number of bytes needed to store the node.
6567 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6571 sz = LEAFSIZE(key, data);
6572 if (sz > env->me_nodemax) {
6573 /* put on overflow page */
6574 sz -= data->mv_size - sizeof(pgno_t);
6577 return EVEN(sz + sizeof(indx_t));
6580 /** Calculate the size of a branch node.
6581 * The size should depend on the environment's page size but since
6582 * we currently don't support spilling large keys onto overflow
6583 * pages, it's simply the size of the #MDB_node header plus the
6584 * size of the key. Sizes are always rounded up to an even number
6585 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6586 * @param[in] env The environment handle.
6587 * @param[in] key The key for the node.
6588 * @return The number of bytes needed to store the node.
6591 mdb_branch_size(MDB_env *env, MDB_val *key)
6596 if (sz > env->me_nodemax) {
6597 /* put on overflow page */
6598 /* not implemented */
6599 /* sz -= key->size - sizeof(pgno_t); */
6602 return sz + sizeof(indx_t);
6605 /** Add a node to the page pointed to by the cursor.
6606 * @param[in] mc The cursor for this operation.
6607 * @param[in] indx The index on the page where the new node should be added.
6608 * @param[in] key The key for the new node.
6609 * @param[in] data The data for the new node, if any.
6610 * @param[in] pgno The page number, if adding a branch node.
6611 * @param[in] flags Flags for the node.
6612 * @return 0 on success, non-zero on failure. Possible errors are:
6614 * <li>ENOMEM - failed to allocate overflow pages for the node.
6615 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6616 * should never happen since all callers already calculate the
6617 * page's free space before calling this function.
6621 mdb_node_add(MDB_cursor *mc, indx_t indx,
6622 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6625 size_t node_size = NODESIZE;
6629 MDB_page *mp = mc->mc_pg[mc->mc_top];
6630 MDB_page *ofp = NULL; /* overflow page */
6633 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6635 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6636 IS_LEAF(mp) ? "leaf" : "branch",
6637 IS_SUBP(mp) ? "sub-" : "",
6638 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6639 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6642 /* Move higher keys up one slot. */
6643 int ksize = mc->mc_db->md_pad, dif;
6644 char *ptr = LEAF2KEY(mp, indx, ksize);
6645 dif = NUMKEYS(mp) - indx;
6647 memmove(ptr+ksize, ptr, dif*ksize);
6648 /* insert new key */
6649 memcpy(ptr, key->mv_data, ksize);
6651 /* Just using these for counting */
6652 mp->mp_lower += sizeof(indx_t);
6653 mp->mp_upper -= ksize - sizeof(indx_t);
6657 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6659 node_size += key->mv_size;
6661 mdb_cassert(mc, data);
6662 if (F_ISSET(flags, F_BIGDATA)) {
6663 /* Data already on overflow page. */
6664 node_size += sizeof(pgno_t);
6665 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6666 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6668 /* Put data on overflow page. */
6669 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6670 data->mv_size, node_size+data->mv_size));
6671 node_size = EVEN(node_size + sizeof(pgno_t));
6672 if ((ssize_t)node_size > room)
6674 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6676 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6680 node_size += data->mv_size;
6683 node_size = EVEN(node_size);
6684 if ((ssize_t)node_size > room)
6688 /* Move higher pointers up one slot. */
6689 for (i = NUMKEYS(mp); i > indx; i--)
6690 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6692 /* Adjust free space offsets. */
6693 ofs = mp->mp_upper - node_size;
6694 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6695 mp->mp_ptrs[indx] = ofs;
6697 mp->mp_lower += sizeof(indx_t);
6699 /* Write the node data. */
6700 node = NODEPTR(mp, indx);
6701 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6702 node->mn_flags = flags;
6704 SETDSZ(node,data->mv_size);
6709 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6712 mdb_cassert(mc, key);
6714 if (F_ISSET(flags, F_BIGDATA))
6715 memcpy(node->mn_data + key->mv_size, data->mv_data,
6717 else if (F_ISSET(flags, MDB_RESERVE))
6718 data->mv_data = node->mn_data + key->mv_size;
6720 memcpy(node->mn_data + key->mv_size, data->mv_data,
6723 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6725 if (F_ISSET(flags, MDB_RESERVE))
6726 data->mv_data = METADATA(ofp);
6728 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6735 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6736 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6737 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6738 DPRINTF(("node size = %"Z"u", node_size));
6739 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6740 return MDB_PAGE_FULL;
6743 /** Delete the specified node from a page.
6744 * @param[in] mc Cursor pointing to the node to delete.
6745 * @param[in] ksize The size of a node. Only used if the page is
6746 * part of a #MDB_DUPFIXED database.
6749 mdb_node_del(MDB_cursor *mc, int ksize)
6751 MDB_page *mp = mc->mc_pg[mc->mc_top];
6752 indx_t indx = mc->mc_ki[mc->mc_top];
6754 indx_t i, j, numkeys, ptr;
6758 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6759 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6760 numkeys = NUMKEYS(mp);
6761 mdb_cassert(mc, indx < numkeys);
6764 int x = numkeys - 1 - indx;
6765 base = LEAF2KEY(mp, indx, ksize);
6767 memmove(base, base + ksize, x * ksize);
6768 mp->mp_lower -= sizeof(indx_t);
6769 mp->mp_upper += ksize - sizeof(indx_t);
6773 node = NODEPTR(mp, indx);
6774 sz = NODESIZE + node->mn_ksize;
6776 if (F_ISSET(node->mn_flags, F_BIGDATA))
6777 sz += sizeof(pgno_t);
6779 sz += NODEDSZ(node);
6783 ptr = mp->mp_ptrs[indx];
6784 for (i = j = 0; i < numkeys; i++) {
6786 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6787 if (mp->mp_ptrs[i] < ptr)
6788 mp->mp_ptrs[j] += sz;
6793 base = (char *)mp + mp->mp_upper + PAGEBASE;
6794 memmove(base + sz, base, ptr - mp->mp_upper);
6796 mp->mp_lower -= sizeof(indx_t);
6800 /** Compact the main page after deleting a node on a subpage.
6801 * @param[in] mp The main page to operate on.
6802 * @param[in] indx The index of the subpage on the main page.
6805 mdb_node_shrink(MDB_page *mp, indx_t indx)
6811 indx_t i, numkeys, ptr;
6813 node = NODEPTR(mp, indx);
6814 sp = (MDB_page *)NODEDATA(node);
6815 delta = SIZELEFT(sp);
6816 xp = (MDB_page *)((char *)sp + delta);
6818 /* shift subpage upward */
6820 nsize = NUMKEYS(sp) * sp->mp_pad;
6822 return; /* do not make the node uneven-sized */
6823 memmove(METADATA(xp), METADATA(sp), nsize);
6826 numkeys = NUMKEYS(sp);
6827 for (i=numkeys-1; i>=0; i--)
6828 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6830 xp->mp_upper = sp->mp_lower;
6831 xp->mp_lower = sp->mp_lower;
6832 xp->mp_flags = sp->mp_flags;
6833 xp->mp_pad = sp->mp_pad;
6834 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6836 nsize = NODEDSZ(node) - delta;
6837 SETDSZ(node, nsize);
6839 /* shift lower nodes upward */
6840 ptr = mp->mp_ptrs[indx];
6841 numkeys = NUMKEYS(mp);
6842 for (i = 0; i < numkeys; i++) {
6843 if (mp->mp_ptrs[i] <= ptr)
6844 mp->mp_ptrs[i] += delta;
6847 base = (char *)mp + mp->mp_upper + PAGEBASE;
6848 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6849 mp->mp_upper += delta;
6852 /** Initial setup of a sorted-dups cursor.
6853 * Sorted duplicates are implemented as a sub-database for the given key.
6854 * The duplicate data items are actually keys of the sub-database.
6855 * Operations on the duplicate data items are performed using a sub-cursor
6856 * initialized when the sub-database is first accessed. This function does
6857 * the preliminary setup of the sub-cursor, filling in the fields that
6858 * depend only on the parent DB.
6859 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6862 mdb_xcursor_init0(MDB_cursor *mc)
6864 MDB_xcursor *mx = mc->mc_xcursor;
6866 mx->mx_cursor.mc_xcursor = NULL;
6867 mx->mx_cursor.mc_txn = mc->mc_txn;
6868 mx->mx_cursor.mc_db = &mx->mx_db;
6869 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6870 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6871 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6872 mx->mx_cursor.mc_snum = 0;
6873 mx->mx_cursor.mc_top = 0;
6874 mx->mx_cursor.mc_flags = C_SUB;
6875 mx->mx_dbx.md_name.mv_size = 0;
6876 mx->mx_dbx.md_name.mv_data = NULL;
6877 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6878 mx->mx_dbx.md_dcmp = NULL;
6879 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6882 /** Final setup of a sorted-dups cursor.
6883 * Sets up the fields that depend on the data from the main cursor.
6884 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6885 * @param[in] node The data containing the #MDB_db record for the
6886 * sorted-dup database.
6889 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6891 MDB_xcursor *mx = mc->mc_xcursor;
6893 if (node->mn_flags & F_SUBDATA) {
6894 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6895 mx->mx_cursor.mc_pg[0] = 0;
6896 mx->mx_cursor.mc_snum = 0;
6897 mx->mx_cursor.mc_top = 0;
6898 mx->mx_cursor.mc_flags = C_SUB;
6900 MDB_page *fp = NODEDATA(node);
6901 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6902 mx->mx_db.md_flags = 0;
6903 mx->mx_db.md_depth = 1;
6904 mx->mx_db.md_branch_pages = 0;
6905 mx->mx_db.md_leaf_pages = 1;
6906 mx->mx_db.md_overflow_pages = 0;
6907 mx->mx_db.md_entries = NUMKEYS(fp);
6908 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6909 mx->mx_cursor.mc_snum = 1;
6910 mx->mx_cursor.mc_top = 0;
6911 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6912 mx->mx_cursor.mc_pg[0] = fp;
6913 mx->mx_cursor.mc_ki[0] = 0;
6914 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6915 mx->mx_db.md_flags = MDB_DUPFIXED;
6916 mx->mx_db.md_pad = fp->mp_pad;
6917 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6918 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6921 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6922 mx->mx_db.md_root));
6923 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6924 #if UINT_MAX < SIZE_MAX
6925 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6926 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6930 /** Initialize a cursor for a given transaction and database. */
6932 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6935 mc->mc_backup = NULL;
6938 mc->mc_db = &txn->mt_dbs[dbi];
6939 mc->mc_dbx = &txn->mt_dbxs[dbi];
6940 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6945 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6946 mdb_tassert(txn, mx != NULL);
6947 mc->mc_xcursor = mx;
6948 mdb_xcursor_init0(mc);
6950 mc->mc_xcursor = NULL;
6952 if (*mc->mc_dbflag & DB_STALE) {
6953 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6958 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6961 size_t size = sizeof(MDB_cursor);
6963 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6966 if (txn->mt_flags & MDB_TXN_ERROR)
6969 /* Allow read access to the freelist */
6970 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6973 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6974 size += sizeof(MDB_xcursor);
6976 if ((mc = malloc(size)) != NULL) {
6977 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6978 if (txn->mt_cursors) {
6979 mc->mc_next = txn->mt_cursors[dbi];
6980 txn->mt_cursors[dbi] = mc;
6981 mc->mc_flags |= C_UNTRACK;
6993 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6995 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6998 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7001 if (txn->mt_flags & MDB_TXN_ERROR)
7004 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7008 /* Return the count of duplicate data items for the current key */
7010 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7014 if (mc == NULL || countp == NULL)
7017 if (mc->mc_xcursor == NULL)
7018 return MDB_INCOMPATIBLE;
7020 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7023 if (!(mc->mc_flags & C_INITIALIZED))
7026 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7027 return MDB_NOTFOUND;
7029 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7030 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7033 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7036 *countp = mc->mc_xcursor->mx_db.md_entries;
7042 mdb_cursor_close(MDB_cursor *mc)
7044 if (mc && !mc->mc_backup) {
7045 /* remove from txn, if tracked */
7046 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7047 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7048 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7050 *prev = mc->mc_next;
7057 mdb_cursor_txn(MDB_cursor *mc)
7059 if (!mc) return NULL;
7064 mdb_cursor_dbi(MDB_cursor *mc)
7069 /** Replace the key for a branch node with a new key.
7070 * @param[in] mc Cursor pointing to the node to operate on.
7071 * @param[in] key The new key to use.
7072 * @return 0 on success, non-zero on failure.
7075 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7081 int delta, ksize, oksize;
7082 indx_t ptr, i, numkeys, indx;
7085 indx = mc->mc_ki[mc->mc_top];
7086 mp = mc->mc_pg[mc->mc_top];
7087 node = NODEPTR(mp, indx);
7088 ptr = mp->mp_ptrs[indx];
7092 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7093 k2.mv_data = NODEKEY(node);
7094 k2.mv_size = node->mn_ksize;
7095 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7097 mdb_dkey(&k2, kbuf2),
7103 /* Sizes must be 2-byte aligned. */
7104 ksize = EVEN(key->mv_size);
7105 oksize = EVEN(node->mn_ksize);
7106 delta = ksize - oksize;
7108 /* Shift node contents if EVEN(key length) changed. */
7110 if (delta > 0 && SIZELEFT(mp) < delta) {
7112 /* not enough space left, do a delete and split */
7113 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7114 pgno = NODEPGNO(node);
7115 mdb_node_del(mc, 0);
7116 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7119 numkeys = NUMKEYS(mp);
7120 for (i = 0; i < numkeys; i++) {
7121 if (mp->mp_ptrs[i] <= ptr)
7122 mp->mp_ptrs[i] -= delta;
7125 base = (char *)mp + mp->mp_upper + PAGEBASE;
7126 len = ptr - mp->mp_upper + NODESIZE;
7127 memmove(base - delta, base, len);
7128 mp->mp_upper -= delta;
7130 node = NODEPTR(mp, indx);
7133 /* But even if no shift was needed, update ksize */
7134 if (node->mn_ksize != key->mv_size)
7135 node->mn_ksize = key->mv_size;
7138 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7144 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7146 /** Move a node from csrc to cdst.
7149 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7156 unsigned short flags;
7160 /* Mark src and dst as dirty. */
7161 if ((rc = mdb_page_touch(csrc)) ||
7162 (rc = mdb_page_touch(cdst)))
7165 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7166 key.mv_size = csrc->mc_db->md_pad;
7167 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7169 data.mv_data = NULL;
7173 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7174 mdb_cassert(csrc, !((size_t)srcnode & 1));
7175 srcpg = NODEPGNO(srcnode);
7176 flags = srcnode->mn_flags;
7177 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7178 unsigned int snum = csrc->mc_snum;
7180 /* must find the lowest key below src */
7181 rc = mdb_page_search_lowest(csrc);
7184 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7185 key.mv_size = csrc->mc_db->md_pad;
7186 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7188 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7189 key.mv_size = NODEKSZ(s2);
7190 key.mv_data = NODEKEY(s2);
7192 csrc->mc_snum = snum--;
7193 csrc->mc_top = snum;
7195 key.mv_size = NODEKSZ(srcnode);
7196 key.mv_data = NODEKEY(srcnode);
7198 data.mv_size = NODEDSZ(srcnode);
7199 data.mv_data = NODEDATA(srcnode);
7201 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7202 unsigned int snum = cdst->mc_snum;
7205 /* must find the lowest key below dst */
7206 mdb_cursor_copy(cdst, &mn);
7207 rc = mdb_page_search_lowest(&mn);
7210 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7211 bkey.mv_size = mn.mc_db->md_pad;
7212 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7214 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7215 bkey.mv_size = NODEKSZ(s2);
7216 bkey.mv_data = NODEKEY(s2);
7218 mn.mc_snum = snum--;
7221 rc = mdb_update_key(&mn, &bkey);
7226 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7227 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7228 csrc->mc_ki[csrc->mc_top],
7230 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7231 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7233 /* Add the node to the destination page.
7235 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7236 if (rc != MDB_SUCCESS)
7239 /* Delete the node from the source page.
7241 mdb_node_del(csrc, key.mv_size);
7244 /* Adjust other cursors pointing to mp */
7245 MDB_cursor *m2, *m3;
7246 MDB_dbi dbi = csrc->mc_dbi;
7247 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7249 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7250 if (csrc->mc_flags & C_SUB)
7251 m3 = &m2->mc_xcursor->mx_cursor;
7254 if (m3 == csrc) continue;
7255 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7256 csrc->mc_ki[csrc->mc_top]) {
7257 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7258 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7263 /* Update the parent separators.
7265 if (csrc->mc_ki[csrc->mc_top] == 0) {
7266 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7267 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7268 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7270 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7271 key.mv_size = NODEKSZ(srcnode);
7272 key.mv_data = NODEKEY(srcnode);
7274 DPRINTF(("update separator for source page %"Z"u to [%s]",
7275 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7276 mdb_cursor_copy(csrc, &mn);
7279 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7282 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7284 indx_t ix = csrc->mc_ki[csrc->mc_top];
7285 nullkey.mv_size = 0;
7286 csrc->mc_ki[csrc->mc_top] = 0;
7287 rc = mdb_update_key(csrc, &nullkey);
7288 csrc->mc_ki[csrc->mc_top] = ix;
7289 mdb_cassert(csrc, rc == MDB_SUCCESS);
7293 if (cdst->mc_ki[cdst->mc_top] == 0) {
7294 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7295 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7296 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7298 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7299 key.mv_size = NODEKSZ(srcnode);
7300 key.mv_data = NODEKEY(srcnode);
7302 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7303 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7304 mdb_cursor_copy(cdst, &mn);
7307 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7310 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7312 indx_t ix = cdst->mc_ki[cdst->mc_top];
7313 nullkey.mv_size = 0;
7314 cdst->mc_ki[cdst->mc_top] = 0;
7315 rc = mdb_update_key(cdst, &nullkey);
7316 cdst->mc_ki[cdst->mc_top] = ix;
7317 mdb_cassert(csrc, rc == MDB_SUCCESS);
7324 /** Merge one page into another.
7325 * The nodes from the page pointed to by \b csrc will
7326 * be copied to the page pointed to by \b cdst and then
7327 * the \b csrc page will be freed.
7328 * @param[in] csrc Cursor pointing to the source page.
7329 * @param[in] cdst Cursor pointing to the destination page.
7330 * @return 0 on success, non-zero on failure.
7333 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7335 MDB_page *psrc, *pdst;
7342 psrc = csrc->mc_pg[csrc->mc_top];
7343 pdst = cdst->mc_pg[cdst->mc_top];
7345 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7347 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7348 mdb_cassert(csrc, cdst->mc_snum > 1);
7350 /* Mark dst as dirty. */
7351 if ((rc = mdb_page_touch(cdst)))
7354 /* Move all nodes from src to dst.
7356 j = nkeys = NUMKEYS(pdst);
7357 if (IS_LEAF2(psrc)) {
7358 key.mv_size = csrc->mc_db->md_pad;
7359 key.mv_data = METADATA(psrc);
7360 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7361 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7362 if (rc != MDB_SUCCESS)
7364 key.mv_data = (char *)key.mv_data + key.mv_size;
7367 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7368 srcnode = NODEPTR(psrc, i);
7369 if (i == 0 && IS_BRANCH(psrc)) {
7372 mdb_cursor_copy(csrc, &mn);
7373 /* must find the lowest key below src */
7374 rc = mdb_page_search_lowest(&mn);
7377 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7378 key.mv_size = mn.mc_db->md_pad;
7379 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7381 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7382 key.mv_size = NODEKSZ(s2);
7383 key.mv_data = NODEKEY(s2);
7386 key.mv_size = srcnode->mn_ksize;
7387 key.mv_data = NODEKEY(srcnode);
7390 data.mv_size = NODEDSZ(srcnode);
7391 data.mv_data = NODEDATA(srcnode);
7392 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7393 if (rc != MDB_SUCCESS)
7398 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7399 pdst->mp_pgno, NUMKEYS(pdst),
7400 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7402 /* Unlink the src page from parent and add to free list.
7405 mdb_node_del(csrc, 0);
7406 if (csrc->mc_ki[csrc->mc_top] == 0) {
7408 rc = mdb_update_key(csrc, &key);
7416 psrc = csrc->mc_pg[csrc->mc_top];
7417 /* If not operating on FreeDB, allow this page to be reused
7418 * in this txn. Otherwise just add to free list.
7420 rc = mdb_page_loose(csrc, psrc);
7424 csrc->mc_db->md_leaf_pages--;
7426 csrc->mc_db->md_branch_pages--;
7428 /* Adjust other cursors pointing to mp */
7429 MDB_cursor *m2, *m3;
7430 MDB_dbi dbi = csrc->mc_dbi;
7432 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7433 if (csrc->mc_flags & C_SUB)
7434 m3 = &m2->mc_xcursor->mx_cursor;
7437 if (m3 == csrc) continue;
7438 if (m3->mc_snum < csrc->mc_snum) continue;
7439 if (m3->mc_pg[csrc->mc_top] == psrc) {
7440 m3->mc_pg[csrc->mc_top] = pdst;
7441 m3->mc_ki[csrc->mc_top] += nkeys;
7446 unsigned int snum = cdst->mc_snum;
7447 uint16_t depth = cdst->mc_db->md_depth;
7448 mdb_cursor_pop(cdst);
7449 rc = mdb_rebalance(cdst);
7450 /* Did the tree shrink? */
7451 if (depth > cdst->mc_db->md_depth)
7453 cdst->mc_snum = snum;
7454 cdst->mc_top = snum-1;
7459 /** Copy the contents of a cursor.
7460 * @param[in] csrc The cursor to copy from.
7461 * @param[out] cdst The cursor to copy to.
7464 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7468 cdst->mc_txn = csrc->mc_txn;
7469 cdst->mc_dbi = csrc->mc_dbi;
7470 cdst->mc_db = csrc->mc_db;
7471 cdst->mc_dbx = csrc->mc_dbx;
7472 cdst->mc_snum = csrc->mc_snum;
7473 cdst->mc_top = csrc->mc_top;
7474 cdst->mc_flags = csrc->mc_flags;
7476 for (i=0; i<csrc->mc_snum; i++) {
7477 cdst->mc_pg[i] = csrc->mc_pg[i];
7478 cdst->mc_ki[i] = csrc->mc_ki[i];
7482 /** Rebalance the tree after a delete operation.
7483 * @param[in] mc Cursor pointing to the page where rebalancing
7485 * @return 0 on success, non-zero on failure.
7488 mdb_rebalance(MDB_cursor *mc)
7492 unsigned int ptop, minkeys;
7496 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7497 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7498 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7499 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7500 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7502 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7503 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7504 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7505 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7509 if (mc->mc_snum < 2) {
7510 MDB_page *mp = mc->mc_pg[0];
7512 DPUTS("Can't rebalance a subpage, ignoring");
7515 if (NUMKEYS(mp) == 0) {
7516 DPUTS("tree is completely empty");
7517 mc->mc_db->md_root = P_INVALID;
7518 mc->mc_db->md_depth = 0;
7519 mc->mc_db->md_leaf_pages = 0;
7520 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7523 /* Adjust cursors pointing to mp */
7526 mc->mc_flags &= ~C_INITIALIZED;
7528 MDB_cursor *m2, *m3;
7529 MDB_dbi dbi = mc->mc_dbi;
7531 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7532 if (mc->mc_flags & C_SUB)
7533 m3 = &m2->mc_xcursor->mx_cursor;
7536 if (m3->mc_snum < mc->mc_snum) continue;
7537 if (m3->mc_pg[0] == mp) {
7540 m3->mc_flags &= ~C_INITIALIZED;
7544 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7546 DPUTS("collapsing root page!");
7547 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7550 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7551 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7554 mc->mc_db->md_depth--;
7555 mc->mc_db->md_branch_pages--;
7556 mc->mc_ki[0] = mc->mc_ki[1];
7557 for (i = 1; i<mc->mc_db->md_depth; i++) {
7558 mc->mc_pg[i] = mc->mc_pg[i+1];
7559 mc->mc_ki[i] = mc->mc_ki[i+1];
7562 /* Adjust other cursors pointing to mp */
7563 MDB_cursor *m2, *m3;
7564 MDB_dbi dbi = mc->mc_dbi;
7566 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7567 if (mc->mc_flags & C_SUB)
7568 m3 = &m2->mc_xcursor->mx_cursor;
7571 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7572 if (m3->mc_pg[0] == mp) {
7575 for (i=0; i<m3->mc_snum; i++) {
7576 m3->mc_pg[i] = m3->mc_pg[i+1];
7577 m3->mc_ki[i] = m3->mc_ki[i+1];
7583 DPUTS("root page doesn't need rebalancing");
7587 /* The parent (branch page) must have at least 2 pointers,
7588 * otherwise the tree is invalid.
7590 ptop = mc->mc_top-1;
7591 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7593 /* Leaf page fill factor is below the threshold.
7594 * Try to move keys from left or right neighbor, or
7595 * merge with a neighbor page.
7600 mdb_cursor_copy(mc, &mn);
7601 mn.mc_xcursor = NULL;
7603 oldki = mc->mc_ki[mc->mc_top];
7604 if (mc->mc_ki[ptop] == 0) {
7605 /* We're the leftmost leaf in our parent.
7607 DPUTS("reading right neighbor");
7609 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7610 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7613 mn.mc_ki[mn.mc_top] = 0;
7614 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7616 /* There is at least one neighbor to the left.
7618 DPUTS("reading left neighbor");
7620 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7621 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7624 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7625 mc->mc_ki[mc->mc_top] = 0;
7628 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7629 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7630 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7632 /* If the neighbor page is above threshold and has enough keys,
7633 * move one key from it. Otherwise we should try to merge them.
7634 * (A branch page must never have less than 2 keys.)
7636 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7637 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7638 rc = mdb_node_move(&mn, mc);
7639 if (mc->mc_ki[ptop]) {
7643 if (mc->mc_ki[ptop] == 0) {
7644 rc = mdb_page_merge(&mn, mc);
7646 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7647 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7648 rc = mdb_page_merge(mc, &mn);
7649 mdb_cursor_copy(&mn, mc);
7651 mc->mc_flags &= ~C_EOF;
7653 mc->mc_ki[mc->mc_top] = oldki;
7657 /** Complete a delete operation started by #mdb_cursor_del(). */
7659 mdb_cursor_del0(MDB_cursor *mc)
7666 ki = mc->mc_ki[mc->mc_top];
7667 mdb_node_del(mc, mc->mc_db->md_pad);
7668 mc->mc_db->md_entries--;
7669 rc = mdb_rebalance(mc);
7671 if (rc == MDB_SUCCESS) {
7672 MDB_cursor *m2, *m3;
7673 MDB_dbi dbi = mc->mc_dbi;
7675 mp = mc->mc_pg[mc->mc_top];
7676 nkeys = NUMKEYS(mp);
7678 /* if mc points past last node in page, find next sibling */
7679 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7680 rc = mdb_cursor_sibling(mc, 1);
7681 if (rc == MDB_NOTFOUND) {
7682 mc->mc_flags |= C_EOF;
7687 /* Adjust other cursors pointing to mp */
7688 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7689 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7690 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7692 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7694 if (m3->mc_pg[mc->mc_top] == mp) {
7695 if (m3->mc_ki[mc->mc_top] >= ki) {
7696 m3->mc_flags |= C_DEL;
7697 if (m3->mc_ki[mc->mc_top] > ki)
7698 m3->mc_ki[mc->mc_top]--;
7699 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7700 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7702 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7703 rc = mdb_cursor_sibling(m3, 1);
7704 if (rc == MDB_NOTFOUND) {
7705 m3->mc_flags |= C_EOF;
7711 mc->mc_flags |= C_DEL;
7715 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7720 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7721 MDB_val *key, MDB_val *data)
7723 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7726 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7727 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7729 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7730 /* must ignore any data */
7734 return mdb_del0(txn, dbi, key, data, 0);
7738 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7739 MDB_val *key, MDB_val *data, unsigned flags)
7744 MDB_val rdata, *xdata;
7748 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7750 mdb_cursor_init(&mc, txn, dbi, &mx);
7759 flags |= MDB_NODUPDATA;
7761 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7763 /* let mdb_page_split know about this cursor if needed:
7764 * delete will trigger a rebalance; if it needs to move
7765 * a node from one page to another, it will have to
7766 * update the parent's separator key(s). If the new sepkey
7767 * is larger than the current one, the parent page may
7768 * run out of space, triggering a split. We need this
7769 * cursor to be consistent until the end of the rebalance.
7771 mc.mc_flags |= C_UNTRACK;
7772 mc.mc_next = txn->mt_cursors[dbi];
7773 txn->mt_cursors[dbi] = &mc;
7774 rc = mdb_cursor_del(&mc, flags);
7775 txn->mt_cursors[dbi] = mc.mc_next;
7780 /** Split a page and insert a new node.
7781 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7782 * The cursor will be updated to point to the actual page and index where
7783 * the node got inserted after the split.
7784 * @param[in] newkey The key for the newly inserted node.
7785 * @param[in] newdata The data for the newly inserted node.
7786 * @param[in] newpgno The page number, if the new node is a branch node.
7787 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7788 * @return 0 on success, non-zero on failure.
7791 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7792 unsigned int nflags)
7795 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7798 int i, j, split_indx, nkeys, pmax;
7799 MDB_env *env = mc->mc_txn->mt_env;
7801 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7802 MDB_page *copy = NULL;
7803 MDB_page *mp, *rp, *pp;
7808 mp = mc->mc_pg[mc->mc_top];
7809 newindx = mc->mc_ki[mc->mc_top];
7810 nkeys = NUMKEYS(mp);
7812 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7813 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7814 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7816 /* Create a right sibling. */
7817 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7819 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7821 if (mc->mc_snum < 2) {
7822 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7824 /* shift current top to make room for new parent */
7825 mc->mc_pg[1] = mc->mc_pg[0];
7826 mc->mc_ki[1] = mc->mc_ki[0];
7829 mc->mc_db->md_root = pp->mp_pgno;
7830 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7831 mc->mc_db->md_depth++;
7834 /* Add left (implicit) pointer. */
7835 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7836 /* undo the pre-push */
7837 mc->mc_pg[0] = mc->mc_pg[1];
7838 mc->mc_ki[0] = mc->mc_ki[1];
7839 mc->mc_db->md_root = mp->mp_pgno;
7840 mc->mc_db->md_depth--;
7847 ptop = mc->mc_top-1;
7848 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7851 mc->mc_flags |= C_SPLITTING;
7852 mdb_cursor_copy(mc, &mn);
7853 mn.mc_pg[mn.mc_top] = rp;
7854 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7856 if (nflags & MDB_APPEND) {
7857 mn.mc_ki[mn.mc_top] = 0;
7859 split_indx = newindx;
7863 split_indx = (nkeys+1) / 2;
7868 unsigned int lsize, rsize, ksize;
7869 /* Move half of the keys to the right sibling */
7870 x = mc->mc_ki[mc->mc_top] - split_indx;
7871 ksize = mc->mc_db->md_pad;
7872 split = LEAF2KEY(mp, split_indx, ksize);
7873 rsize = (nkeys - split_indx) * ksize;
7874 lsize = (nkeys - split_indx) * sizeof(indx_t);
7875 mp->mp_lower -= lsize;
7876 rp->mp_lower += lsize;
7877 mp->mp_upper += rsize - lsize;
7878 rp->mp_upper -= rsize - lsize;
7879 sepkey.mv_size = ksize;
7880 if (newindx == split_indx) {
7881 sepkey.mv_data = newkey->mv_data;
7883 sepkey.mv_data = split;
7886 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7887 memcpy(rp->mp_ptrs, split, rsize);
7888 sepkey.mv_data = rp->mp_ptrs;
7889 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7890 memcpy(ins, newkey->mv_data, ksize);
7891 mp->mp_lower += sizeof(indx_t);
7892 mp->mp_upper -= ksize - sizeof(indx_t);
7895 memcpy(rp->mp_ptrs, split, x * ksize);
7896 ins = LEAF2KEY(rp, x, ksize);
7897 memcpy(ins, newkey->mv_data, ksize);
7898 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7899 rp->mp_lower += sizeof(indx_t);
7900 rp->mp_upper -= ksize - sizeof(indx_t);
7901 mc->mc_ki[mc->mc_top] = x;
7902 mc->mc_pg[mc->mc_top] = rp;
7905 int psize, nsize, k;
7906 /* Maximum free space in an empty page */
7907 pmax = env->me_psize - PAGEHDRSZ;
7909 nsize = mdb_leaf_size(env, newkey, newdata);
7911 nsize = mdb_branch_size(env, newkey);
7912 nsize = EVEN(nsize);
7914 /* grab a page to hold a temporary copy */
7915 copy = mdb_page_malloc(mc->mc_txn, 1);
7920 copy->mp_pgno = mp->mp_pgno;
7921 copy->mp_flags = mp->mp_flags;
7922 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
7923 copy->mp_upper = env->me_psize - PAGEBASE;
7925 /* prepare to insert */
7926 for (i=0, j=0; i<nkeys; i++) {
7928 copy->mp_ptrs[j++] = 0;
7930 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7933 /* When items are relatively large the split point needs
7934 * to be checked, because being off-by-one will make the
7935 * difference between success or failure in mdb_node_add.
7937 * It's also relevant if a page happens to be laid out
7938 * such that one half of its nodes are all "small" and
7939 * the other half of its nodes are "large." If the new
7940 * item is also "large" and falls on the half with
7941 * "large" nodes, it also may not fit.
7943 * As a final tweak, if the new item goes on the last
7944 * spot on the page (and thus, onto the new page), bias
7945 * the split so the new page is emptier than the old page.
7946 * This yields better packing during sequential inserts.
7948 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7949 /* Find split point */
7951 if (newindx <= split_indx || newindx >= nkeys) {
7953 k = newindx >= nkeys ? nkeys : split_indx+2;
7958 for (; i!=k; i+=j) {
7963 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7964 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7966 if (F_ISSET(node->mn_flags, F_BIGDATA))
7967 psize += sizeof(pgno_t);
7969 psize += NODEDSZ(node);
7971 psize = EVEN(psize);
7973 if (psize > pmax || i == k-j) {
7974 split_indx = i + (j<0);
7979 if (split_indx == newindx) {
7980 sepkey.mv_size = newkey->mv_size;
7981 sepkey.mv_data = newkey->mv_data;
7983 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
7984 sepkey.mv_size = node->mn_ksize;
7985 sepkey.mv_data = NODEKEY(node);
7990 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7992 /* Copy separator key to the parent.
7994 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7998 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8003 if (mn.mc_snum == mc->mc_snum) {
8004 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8005 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8006 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8007 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8012 /* Right page might now have changed parent.
8013 * Check if left page also changed parent.
8015 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8016 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8017 for (i=0; i<ptop; i++) {
8018 mc->mc_pg[i] = mn.mc_pg[i];
8019 mc->mc_ki[i] = mn.mc_ki[i];
8021 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8022 if (mn.mc_ki[ptop]) {
8023 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8025 /* find right page's left sibling */
8026 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8027 mdb_cursor_sibling(mc, 0);
8032 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8035 mc->mc_flags ^= C_SPLITTING;
8036 if (rc != MDB_SUCCESS) {
8039 if (nflags & MDB_APPEND) {
8040 mc->mc_pg[mc->mc_top] = rp;
8041 mc->mc_ki[mc->mc_top] = 0;
8042 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8045 for (i=0; i<mc->mc_top; i++)
8046 mc->mc_ki[i] = mn.mc_ki[i];
8047 } else if (!IS_LEAF2(mp)) {
8049 mc->mc_pg[mc->mc_top] = rp;
8054 rkey.mv_data = newkey->mv_data;
8055 rkey.mv_size = newkey->mv_size;
8061 /* Update index for the new key. */
8062 mc->mc_ki[mc->mc_top] = j;
8064 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8065 rkey.mv_data = NODEKEY(node);
8066 rkey.mv_size = node->mn_ksize;
8068 xdata.mv_data = NODEDATA(node);
8069 xdata.mv_size = NODEDSZ(node);
8072 pgno = NODEPGNO(node);
8073 flags = node->mn_flags;
8076 if (!IS_LEAF(mp) && j == 0) {
8077 /* First branch index doesn't need key data. */
8081 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8087 mc->mc_pg[mc->mc_top] = copy;
8092 } while (i != split_indx);
8094 nkeys = NUMKEYS(copy);
8095 for (i=0; i<nkeys; i++)
8096 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8097 mp->mp_lower = copy->mp_lower;
8098 mp->mp_upper = copy->mp_upper;
8099 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8100 env->me_psize - copy->mp_upper - PAGEBASE);
8102 /* reset back to original page */
8103 if (newindx < split_indx) {
8104 mc->mc_pg[mc->mc_top] = mp;
8105 if (nflags & MDB_RESERVE) {
8106 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8107 if (!(node->mn_flags & F_BIGDATA))
8108 newdata->mv_data = NODEDATA(node);
8111 mc->mc_pg[mc->mc_top] = rp;
8113 /* Make sure mc_ki is still valid.
8115 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8116 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8117 for (i=0; i<=ptop; i++) {
8118 mc->mc_pg[i] = mn.mc_pg[i];
8119 mc->mc_ki[i] = mn.mc_ki[i];
8126 /* Adjust other cursors pointing to mp */
8127 MDB_cursor *m2, *m3;
8128 MDB_dbi dbi = mc->mc_dbi;
8129 int fixup = NUMKEYS(mp);
8131 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8132 if (mc->mc_flags & C_SUB)
8133 m3 = &m2->mc_xcursor->mx_cursor;
8138 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8140 if (m3->mc_flags & C_SPLITTING)
8145 for (k=m3->mc_top; k>=0; k--) {
8146 m3->mc_ki[k+1] = m3->mc_ki[k];
8147 m3->mc_pg[k+1] = m3->mc_pg[k];
8149 if (m3->mc_ki[0] >= split_indx) {
8154 m3->mc_pg[0] = mc->mc_pg[0];
8158 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8159 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8160 m3->mc_ki[mc->mc_top]++;
8161 if (m3->mc_ki[mc->mc_top] >= fixup) {
8162 m3->mc_pg[mc->mc_top] = rp;
8163 m3->mc_ki[mc->mc_top] -= fixup;
8164 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8166 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8167 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8172 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8175 if (copy) /* tmp page */
8176 mdb_page_free(env, copy);
8178 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8183 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8184 MDB_val *key, MDB_val *data, unsigned int flags)
8189 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8192 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8195 mdb_cursor_init(&mc, txn, dbi, &mx);
8196 return mdb_cursor_put(&mc, key, data, flags);
8200 #define MDB_WBUF (1024*1024)
8203 /** State needed for a compacting copy. */
8204 typedef struct mdb_copy {
8205 pthread_mutex_t mc_mutex;
8206 pthread_cond_t mc_cond;
8213 pgno_t mc_next_pgno;
8216 volatile int mc_new;
8221 /** Dedicated writer thread for compacting copy. */
8222 static THREAD_RET ESECT
8223 mdb_env_copythr(void *arg)
8227 int toggle = 0, wsize, rc;
8230 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8233 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8236 pthread_mutex_lock(&my->mc_mutex);
8238 pthread_cond_signal(&my->mc_cond);
8241 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8242 if (my->mc_new < 0) {
8247 wsize = my->mc_wlen[toggle];
8248 ptr = my->mc_wbuf[toggle];
8251 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8255 } else if (len > 0) {
8269 /* If there's an overflow page tail, write it too */
8270 if (my->mc_olen[toggle]) {
8271 wsize = my->mc_olen[toggle];
8272 ptr = my->mc_over[toggle];
8273 my->mc_olen[toggle] = 0;
8276 my->mc_wlen[toggle] = 0;
8278 pthread_cond_signal(&my->mc_cond);
8280 pthread_cond_signal(&my->mc_cond);
8281 pthread_mutex_unlock(&my->mc_mutex);
8282 return (THREAD_RET)0;
8286 /** Tell the writer thread there's a buffer ready to write */
8288 mdb_env_cthr_toggle(mdb_copy *my, int st)
8290 int toggle = my->mc_toggle ^ 1;
8291 pthread_mutex_lock(&my->mc_mutex);
8292 if (my->mc_status) {
8293 pthread_mutex_unlock(&my->mc_mutex);
8294 return my->mc_status;
8296 while (my->mc_new == 1)
8297 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8299 my->mc_toggle = toggle;
8300 pthread_cond_signal(&my->mc_cond);
8301 pthread_mutex_unlock(&my->mc_mutex);
8305 /** Depth-first tree traversal for compacting copy. */
8307 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8310 MDB_txn *txn = my->mc_txn;
8312 MDB_page *mo, *mp, *leaf;
8317 /* Empty DB, nothing to do */
8318 if (*pg == P_INVALID)
8325 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8328 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8332 /* Make cursor pages writable */
8333 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8337 for (i=0; i<mc.mc_top; i++) {
8338 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8339 mc.mc_pg[i] = (MDB_page *)ptr;
8340 ptr += my->mc_env->me_psize;
8343 /* This is writable space for a leaf page. Usually not needed. */
8344 leaf = (MDB_page *)ptr;
8346 toggle = my->mc_toggle;
8347 while (mc.mc_snum > 0) {
8349 mp = mc.mc_pg[mc.mc_top];
8353 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8354 for (i=0; i<n; i++) {
8355 ni = NODEPTR(mp, i);
8356 if (ni->mn_flags & F_BIGDATA) {
8360 /* Need writable leaf */
8362 mc.mc_pg[mc.mc_top] = leaf;
8363 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8365 ni = NODEPTR(mp, i);
8368 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8369 rc = mdb_page_get(txn, pg, &omp, NULL);
8372 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8373 rc = mdb_env_cthr_toggle(my, 1);
8376 toggle = my->mc_toggle;
8378 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8379 memcpy(mo, omp, my->mc_env->me_psize);
8380 mo->mp_pgno = my->mc_next_pgno;
8381 my->mc_next_pgno += omp->mp_pages;
8382 my->mc_wlen[toggle] += my->mc_env->me_psize;
8383 if (omp->mp_pages > 1) {
8384 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8385 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8386 rc = mdb_env_cthr_toggle(my, 1);
8389 toggle = my->mc_toggle;
8391 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8392 } else if (ni->mn_flags & F_SUBDATA) {
8395 /* Need writable leaf */
8397 mc.mc_pg[mc.mc_top] = leaf;
8398 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8400 ni = NODEPTR(mp, i);
8403 memcpy(&db, NODEDATA(ni), sizeof(db));
8404 my->mc_toggle = toggle;
8405 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8408 toggle = my->mc_toggle;
8409 memcpy(NODEDATA(ni), &db, sizeof(db));
8414 mc.mc_ki[mc.mc_top]++;
8415 if (mc.mc_ki[mc.mc_top] < n) {
8418 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8420 rc = mdb_page_get(txn, pg, &mp, NULL);
8425 mc.mc_ki[mc.mc_top] = 0;
8426 if (IS_BRANCH(mp)) {
8427 /* Whenever we advance to a sibling branch page,
8428 * we must proceed all the way down to its first leaf.
8430 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8433 mc.mc_pg[mc.mc_top] = mp;
8437 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8438 rc = mdb_env_cthr_toggle(my, 1);
8441 toggle = my->mc_toggle;
8443 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8444 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8445 mo->mp_pgno = my->mc_next_pgno++;
8446 my->mc_wlen[toggle] += my->mc_env->me_psize;
8448 /* Update parent if there is one */
8449 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8450 SETPGNO(ni, mo->mp_pgno);
8451 mdb_cursor_pop(&mc);
8453 /* Otherwise we're done */
8463 /** Copy environment with compaction. */
8465 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8470 MDB_txn *txn = NULL;
8475 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8476 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8477 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8478 if (my.mc_wbuf[0] == NULL)
8481 pthread_mutex_init(&my.mc_mutex, NULL);
8482 pthread_cond_init(&my.mc_cond, NULL);
8483 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8484 if (my.mc_wbuf[0] == NULL)
8487 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8488 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8493 my.mc_next_pgno = 2;
8499 THREAD_CREATE(thr, mdb_env_copythr, &my);
8501 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8505 mp = (MDB_page *)my.mc_wbuf[0];
8506 memset(mp, 0, 2*env->me_psize);
8508 mp->mp_flags = P_META;
8509 mm = (MDB_meta *)METADATA(mp);
8510 mdb_env_init_meta0(env, mm);
8511 mm->mm_address = env->me_metas[0]->mm_address;
8513 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8515 mp->mp_flags = P_META;
8516 *(MDB_meta *)METADATA(mp) = *mm;
8517 mm = (MDB_meta *)METADATA(mp);
8519 /* Count the number of free pages, subtract from lastpg to find
8520 * number of active pages
8523 MDB_ID freecount = 0;
8526 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8527 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8528 freecount += *(MDB_ID *)data.mv_data;
8529 freecount += txn->mt_dbs[0].md_branch_pages +
8530 txn->mt_dbs[0].md_leaf_pages +
8531 txn->mt_dbs[0].md_overflow_pages;
8533 /* Set metapage 1 */
8534 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8535 mm->mm_dbs[1] = txn->mt_dbs[1];
8536 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8539 my.mc_wlen[0] = env->me_psize * 2;
8541 pthread_mutex_lock(&my.mc_mutex);
8543 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8544 pthread_mutex_unlock(&my.mc_mutex);
8545 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8546 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8547 rc = mdb_env_cthr_toggle(&my, 1);
8548 mdb_env_cthr_toggle(&my, -1);
8549 pthread_mutex_lock(&my.mc_mutex);
8551 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8552 pthread_mutex_unlock(&my.mc_mutex);
8557 CloseHandle(my.mc_cond);
8558 CloseHandle(my.mc_mutex);
8559 _aligned_free(my.mc_wbuf[0]);
8561 pthread_cond_destroy(&my.mc_cond);
8562 pthread_mutex_destroy(&my.mc_mutex);
8563 free(my.mc_wbuf[0]);
8568 /** Copy environment as-is. */
8570 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8572 MDB_txn *txn = NULL;
8578 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8582 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8585 /* Do the lock/unlock of the reader mutex before starting the
8586 * write txn. Otherwise other read txns could block writers.
8588 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8593 /* We must start the actual read txn after blocking writers */
8594 mdb_txn_reset0(txn, "reset-stage1");
8596 /* Temporarily block writers until we snapshot the meta pages */
8599 rc = mdb_txn_renew0(txn);
8601 UNLOCK_MUTEX_W(env);
8606 wsize = env->me_psize * 2;
8610 DO_WRITE(rc, fd, ptr, w2, len);
8614 } else if (len > 0) {
8620 /* Non-blocking or async handles are not supported */
8626 UNLOCK_MUTEX_W(env);
8631 w2 = txn->mt_next_pgno * env->me_psize;
8634 LARGE_INTEGER fsize;
8635 GetFileSizeEx(env->me_fd, &fsize);
8636 if (w2 > fsize.QuadPart)
8637 w2 = fsize.QuadPart;
8642 fstat(env->me_fd, &st);
8643 if (w2 > (size_t)st.st_size)
8649 if (wsize > MAX_WRITE)
8653 DO_WRITE(rc, fd, ptr, w2, len);
8657 } else if (len > 0) {
8674 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8676 if (flags & MDB_CP_COMPACT)
8677 return mdb_env_copyfd1(env, fd);
8679 return mdb_env_copyfd0(env, fd);
8683 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8685 return mdb_env_copyfd2(env, fd, 0);
8689 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8693 HANDLE newfd = INVALID_HANDLE_VALUE;
8695 if (env->me_flags & MDB_NOSUBDIR) {
8696 lpath = (char *)path;
8699 len += sizeof(DATANAME);
8700 lpath = malloc(len);
8703 sprintf(lpath, "%s" DATANAME, path);
8706 /* The destination path must exist, but the destination file must not.
8707 * We don't want the OS to cache the writes, since the source data is
8708 * already in the OS cache.
8711 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8712 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8714 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8716 if (newfd == INVALID_HANDLE_VALUE) {
8721 if (env->me_psize >= env->me_os_psize) {
8723 /* Set O_DIRECT if the file system supports it */
8724 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8725 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8727 #ifdef F_NOCACHE /* __APPLE__ */
8728 rc = fcntl(newfd, F_NOCACHE, 1);
8736 rc = mdb_env_copyfd2(env, newfd, flags);
8739 if (!(env->me_flags & MDB_NOSUBDIR))
8741 if (newfd != INVALID_HANDLE_VALUE)
8742 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8749 mdb_env_copy(MDB_env *env, const char *path)
8751 return mdb_env_copy2(env, path, 0);
8755 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8757 if ((flag & CHANGEABLE) != flag)
8760 env->me_flags |= flag;
8762 env->me_flags &= ~flag;
8767 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8772 *arg = env->me_flags;
8777 mdb_env_set_userctx(MDB_env *env, void *ctx)
8781 env->me_userctx = ctx;
8786 mdb_env_get_userctx(MDB_env *env)
8788 return env ? env->me_userctx : NULL;
8792 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8797 env->me_assert_func = func;
8803 mdb_env_get_path(MDB_env *env, const char **arg)
8808 *arg = env->me_path;
8813 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8822 /** Common code for #mdb_stat() and #mdb_env_stat().
8823 * @param[in] env the environment to operate in.
8824 * @param[in] db the #MDB_db record containing the stats to return.
8825 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8826 * @return 0, this function always succeeds.
8829 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8831 arg->ms_psize = env->me_psize;
8832 arg->ms_depth = db->md_depth;
8833 arg->ms_branch_pages = db->md_branch_pages;
8834 arg->ms_leaf_pages = db->md_leaf_pages;
8835 arg->ms_overflow_pages = db->md_overflow_pages;
8836 arg->ms_entries = db->md_entries;
8842 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8846 if (env == NULL || arg == NULL)
8849 toggle = mdb_env_pick_meta(env);
8851 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8855 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8859 if (env == NULL || arg == NULL)
8862 toggle = mdb_env_pick_meta(env);
8863 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8864 arg->me_mapsize = env->me_mapsize;
8865 arg->me_maxreaders = env->me_maxreaders;
8867 /* me_numreaders may be zero if this process never used any readers. Use
8868 * the shared numreader count if it exists.
8870 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8872 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8873 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8877 /** Set the default comparison functions for a database.
8878 * Called immediately after a database is opened to set the defaults.
8879 * The user can then override them with #mdb_set_compare() or
8880 * #mdb_set_dupsort().
8881 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8882 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8885 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8887 uint16_t f = txn->mt_dbs[dbi].md_flags;
8889 txn->mt_dbxs[dbi].md_cmp =
8890 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8891 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8893 txn->mt_dbxs[dbi].md_dcmp =
8894 !(f & MDB_DUPSORT) ? 0 :
8895 ((f & MDB_INTEGERDUP)
8896 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8897 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8900 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8906 int rc, dbflag, exact;
8907 unsigned int unused = 0, seq;
8910 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8911 mdb_default_cmp(txn, FREE_DBI);
8914 if ((flags & VALID_FLAGS) != flags)
8916 if (txn->mt_flags & MDB_TXN_ERROR)
8922 if (flags & PERSISTENT_FLAGS) {
8923 uint16_t f2 = flags & PERSISTENT_FLAGS;
8924 /* make sure flag changes get committed */
8925 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8926 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8927 txn->mt_flags |= MDB_TXN_DIRTY;
8930 mdb_default_cmp(txn, MAIN_DBI);
8934 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8935 mdb_default_cmp(txn, MAIN_DBI);
8938 /* Is the DB already open? */
8940 for (i=2; i<txn->mt_numdbs; i++) {
8941 if (!txn->mt_dbxs[i].md_name.mv_size) {
8942 /* Remember this free slot */
8943 if (!unused) unused = i;
8946 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8947 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8953 /* If no free slot and max hit, fail */
8954 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8955 return MDB_DBS_FULL;
8957 /* Cannot mix named databases with some mainDB flags */
8958 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8959 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8961 /* Find the DB info */
8962 dbflag = DB_NEW|DB_VALID;
8965 key.mv_data = (void *)name;
8966 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8967 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8968 if (rc == MDB_SUCCESS) {
8969 /* make sure this is actually a DB */
8970 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8971 if (!(node->mn_flags & F_SUBDATA))
8972 return MDB_INCOMPATIBLE;
8973 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8974 /* Create if requested */
8975 data.mv_size = sizeof(MDB_db);
8976 data.mv_data = &dummy;
8977 memset(&dummy, 0, sizeof(dummy));
8978 dummy.md_root = P_INVALID;
8979 dummy.md_flags = flags & PERSISTENT_FLAGS;
8980 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8984 /* OK, got info, add to table */
8985 if (rc == MDB_SUCCESS) {
8986 unsigned int slot = unused ? unused : txn->mt_numdbs;
8987 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8988 txn->mt_dbxs[slot].md_name.mv_size = len;
8989 txn->mt_dbxs[slot].md_rel = NULL;
8990 txn->mt_dbflags[slot] = dbflag;
8991 /* txn-> and env-> are the same in read txns, use
8992 * tmp variable to avoid undefined assignment
8994 seq = ++txn->mt_env->me_dbiseqs[slot];
8995 txn->mt_dbiseqs[slot] = seq;
8997 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8999 mdb_default_cmp(txn, slot);
9008 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9010 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9013 if (txn->mt_flags & MDB_TXN_ERROR)
9016 if (txn->mt_dbflags[dbi] & DB_STALE) {
9019 /* Stale, must read the DB's root. cursor_init does it for us. */
9020 mdb_cursor_init(&mc, txn, dbi, &mx);
9022 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9025 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9028 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9030 ptr = env->me_dbxs[dbi].md_name.mv_data;
9031 /* If there was no name, this was already closed */
9033 env->me_dbxs[dbi].md_name.mv_data = NULL;
9034 env->me_dbxs[dbi].md_name.mv_size = 0;
9035 env->me_dbflags[dbi] = 0;
9036 env->me_dbiseqs[dbi]++;
9041 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9043 /* We could return the flags for the FREE_DBI too but what's the point? */
9044 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9046 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9050 /** Add all the DB's pages to the free list.
9051 * @param[in] mc Cursor on the DB to free.
9052 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9053 * @return 0 on success, non-zero on failure.
9056 mdb_drop0(MDB_cursor *mc, int subs)
9060 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9061 if (rc == MDB_SUCCESS) {
9062 MDB_txn *txn = mc->mc_txn;
9067 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9068 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9071 mdb_cursor_copy(mc, &mx);
9072 while (mc->mc_snum > 0) {
9073 MDB_page *mp = mc->mc_pg[mc->mc_top];
9074 unsigned n = NUMKEYS(mp);
9076 for (i=0; i<n; i++) {
9077 ni = NODEPTR(mp, i);
9078 if (ni->mn_flags & F_BIGDATA) {
9081 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9082 rc = mdb_page_get(txn, pg, &omp, NULL);
9085 mdb_cassert(mc, IS_OVERFLOW(omp));
9086 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9090 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9091 mdb_xcursor_init1(mc, ni);
9092 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9098 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9100 for (i=0; i<n; i++) {
9102 ni = NODEPTR(mp, i);
9105 mdb_midl_xappend(txn->mt_free_pgs, pg);
9110 mc->mc_ki[mc->mc_top] = i;
9111 rc = mdb_cursor_sibling(mc, 1);
9113 if (rc != MDB_NOTFOUND)
9115 /* no more siblings, go back to beginning
9116 * of previous level.
9120 for (i=1; i<mc->mc_snum; i++) {
9122 mc->mc_pg[i] = mx.mc_pg[i];
9127 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9130 txn->mt_flags |= MDB_TXN_ERROR;
9131 } else if (rc == MDB_NOTFOUND) {
9137 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9139 MDB_cursor *mc, *m2;
9142 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9145 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9148 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9151 rc = mdb_cursor_open(txn, dbi, &mc);
9155 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9156 /* Invalidate the dropped DB's cursors */
9157 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9158 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9162 /* Can't delete the main DB */
9163 if (del && dbi > MAIN_DBI) {
9164 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9166 txn->mt_dbflags[dbi] = DB_STALE;
9167 mdb_dbi_close(txn->mt_env, dbi);
9169 txn->mt_flags |= MDB_TXN_ERROR;
9172 /* reset the DB record, mark it dirty */
9173 txn->mt_dbflags[dbi] |= DB_DIRTY;
9174 txn->mt_dbs[dbi].md_depth = 0;
9175 txn->mt_dbs[dbi].md_branch_pages = 0;
9176 txn->mt_dbs[dbi].md_leaf_pages = 0;
9177 txn->mt_dbs[dbi].md_overflow_pages = 0;
9178 txn->mt_dbs[dbi].md_entries = 0;
9179 txn->mt_dbs[dbi].md_root = P_INVALID;
9181 txn->mt_flags |= MDB_TXN_DIRTY;
9184 mdb_cursor_close(mc);
9188 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9190 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9193 txn->mt_dbxs[dbi].md_cmp = cmp;
9197 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9199 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9202 txn->mt_dbxs[dbi].md_dcmp = cmp;
9206 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9208 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9211 txn->mt_dbxs[dbi].md_rel = rel;
9215 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9217 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9220 txn->mt_dbxs[dbi].md_relctx = ctx;
9225 mdb_env_get_maxkeysize(MDB_env *env)
9227 return ENV_MAXKEY(env);
9231 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9233 unsigned int i, rdrs;
9236 int rc = 0, first = 1;
9240 if (!env->me_txns) {
9241 return func("(no reader locks)\n", ctx);
9243 rdrs = env->me_txns->mti_numreaders;
9244 mr = env->me_txns->mti_readers;
9245 for (i=0; i<rdrs; i++) {
9247 txnid_t txnid = mr[i].mr_txnid;
9248 sprintf(buf, txnid == (txnid_t)-1 ?
9249 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9250 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9253 rc = func(" pid thread txnid\n", ctx);
9257 rc = func(buf, ctx);
9263 rc = func("(no active readers)\n", ctx);
9268 /** Insert pid into list if not already present.
9269 * return -1 if already present.
9272 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9274 /* binary search of pid in list */
9276 unsigned cursor = 1;
9278 unsigned n = ids[0];
9281 unsigned pivot = n >> 1;
9282 cursor = base + pivot + 1;
9283 val = pid - ids[cursor];
9288 } else if ( val > 0 ) {
9293 /* found, so it's a duplicate */
9302 for (n = ids[0]; n > cursor; n--)
9309 mdb_reader_check(MDB_env *env, int *dead)
9311 unsigned int i, j, rdrs;
9313 MDB_PID_T *pids, pid;
9322 rdrs = env->me_txns->mti_numreaders;
9323 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9327 mr = env->me_txns->mti_readers;
9328 for (i=0; i<rdrs; i++) {
9329 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9331 if (mdb_pid_insert(pids, pid) == 0) {
9332 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9334 /* Recheck, a new process may have reused pid */
9335 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9336 for (j=i; j<rdrs; j++)
9337 if (mr[j].mr_pid == pid) {
9338 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9339 (unsigned) pid, mr[j].mr_txnid));
9344 UNLOCK_MUTEX_R(env);