2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_USE_HASH 1
71 # define MDB_FDATASYNC fsync
72 #elif defined(ANDROID)
73 # define MDB_FDATASYNC fsync
78 #ifdef MDB_USE_POSIX_SEM
79 #include <semaphore.h>
84 #include <valgrind/memcheck.h>
85 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
86 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
87 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
88 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
89 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
91 #define VGMEMP_CREATE(h,r,z)
92 #define VGMEMP_ALLOC(h,a,s)
93 #define VGMEMP_FREE(h,a)
94 #define VGMEMP_DESTROY(h)
95 #define VGMEMP_DEFINED(a,s)
99 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
100 /* Solaris just defines one or the other */
101 # define LITTLE_ENDIAN 1234
102 # define BIG_ENDIAN 4321
103 # ifdef _LITTLE_ENDIAN
104 # define BYTE_ORDER LITTLE_ENDIAN
106 # define BYTE_ORDER BIG_ENDIAN
109 # define BYTE_ORDER __BYTE_ORDER
113 #ifndef LITTLE_ENDIAN
114 #define LITTLE_ENDIAN __LITTLE_ENDIAN
117 #define BIG_ENDIAN __BIG_ENDIAN
120 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
121 #define MISALIGNED_OK 1
127 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
128 # error "Unknown or unsupported endianness (BYTE_ORDER)"
129 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
130 # error "Two's complement, reasonably sized integer types, please"
133 /** @defgroup internal MDB Internals
136 /** @defgroup compat Windows Compatibility Macros
137 * A bunch of macros to minimize the amount of platform-specific ifdefs
138 * needed throughout the rest of the code. When the features this library
139 * needs are similar enough to POSIX to be hidden in a one-or-two line
140 * replacement, this macro approach is used.
144 #define MDB_USE_HASH 1
145 #define MDB_PIDLOCK 0
146 #define pthread_t DWORD
147 #define pthread_mutex_t HANDLE
148 #define pthread_key_t DWORD
149 #define pthread_self() GetCurrentThreadId()
150 #define pthread_key_create(x,y) \
151 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
152 #define pthread_key_delete(x) TlsFree(x)
153 #define pthread_getspecific(x) TlsGetValue(x)
154 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
155 #define pthread_mutex_unlock(x) ReleaseMutex(x)
156 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
157 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
158 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
159 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
160 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
161 #define getpid() GetCurrentProcessId()
162 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
163 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
164 #define ErrCode() GetLastError()
165 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
166 #define close(fd) (CloseHandle(fd) ? 0 : -1)
167 #define munmap(ptr,len) UnmapViewOfFile(ptr)
168 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
169 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
171 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
176 #define Z "z" /**< printf format modifier for size_t */
178 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
179 #define MDB_PIDLOCK 1
181 #ifdef MDB_USE_POSIX_SEM
183 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
184 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
185 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
186 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
189 mdb_sem_wait(sem_t *sem)
192 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
197 /** Lock the reader mutex.
199 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
200 /** Unlock the reader mutex.
202 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
204 /** Lock the writer mutex.
205 * Only a single write transaction is allowed at a time. Other writers
206 * will block waiting for this mutex.
208 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
209 /** Unlock the writer mutex.
211 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
212 #endif /* MDB_USE_POSIX_SEM */
214 /** Get the error code for the last failed system function.
216 #define ErrCode() errno
218 /** An abstraction for a file handle.
219 * On POSIX systems file handles are small integers. On Windows
220 * they're opaque pointers.
224 /** A value for an invalid file handle.
225 * Mainly used to initialize file variables and signify that they are
228 #define INVALID_HANDLE_VALUE (-1)
230 /** Get the size of a memory page for the system.
231 * This is the basic size that the platform's memory manager uses, and is
232 * fundamental to the use of memory-mapped files.
234 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
237 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
240 #define MNAME_LEN (sizeof(pthread_mutex_t))
246 /** A flag for opening a file and requesting synchronous data writes.
247 * This is only used when writing a meta page. It's not strictly needed;
248 * we could just do a normal write and then immediately perform a flush.
249 * But if this flag is available it saves us an extra system call.
251 * @note If O_DSYNC is undefined but exists in /usr/include,
252 * preferably set some compiler flag to get the definition.
253 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
256 # define MDB_DSYNC O_DSYNC
260 /** Function for flushing the data of a file. Define this to fsync
261 * if fdatasync() is not supported.
263 #ifndef MDB_FDATASYNC
264 # define MDB_FDATASYNC fdatasync
268 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
279 /** A page number in the database.
280 * Note that 64 bit page numbers are overkill, since pages themselves
281 * already represent 12-13 bits of addressable memory, and the OS will
282 * always limit applications to a maximum of 63 bits of address space.
284 * @note In the #MDB_node structure, we only store 48 bits of this value,
285 * which thus limits us to only 60 bits of addressable data.
287 typedef MDB_ID pgno_t;
289 /** A transaction ID.
290 * See struct MDB_txn.mt_txnid for details.
292 typedef MDB_ID txnid_t;
294 /** @defgroup debug Debug Macros
298 /** Enable debug output. Needs variable argument macros (a C99 feature).
299 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
300 * read from and written to the database (used for free space management).
306 static int mdb_debug;
307 static txnid_t mdb_debug_start;
309 /** Print a debug message with printf formatting.
310 * Requires double parenthesis around 2 or more args.
312 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
313 # define DPRINTF0(fmt, ...) \
314 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
316 # define DPRINTF(args) ((void) 0)
318 /** Print a debug string.
319 * The string is printed literally, with no format processing.
321 #define DPUTS(arg) DPRINTF(("%s", arg))
322 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
324 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
327 /** A default memory page size.
328 * The actual size is platform-dependent, but we use this for
329 * boot-strapping. We probably should not be using this any more.
330 * The #GET_PAGESIZE() macro is used to get the actual size.
332 * Note that we don't currently support Huge pages. On Linux,
333 * regular data files cannot use Huge pages, and in general
334 * Huge pages aren't actually pageable. We rely on the OS
335 * demand-pager to read our data and page it out when memory
336 * pressure from other processes is high. So until OSs have
337 * actual paging support for Huge pages, they're not viable.
339 #define MDB_PAGESIZE 4096
341 /** The minimum number of keys required in a database page.
342 * Setting this to a larger value will place a smaller bound on the
343 * maximum size of a data item. Data items larger than this size will
344 * be pushed into overflow pages instead of being stored directly in
345 * the B-tree node. This value used to default to 4. With a page size
346 * of 4096 bytes that meant that any item larger than 1024 bytes would
347 * go into an overflow page. That also meant that on average 2-3KB of
348 * each overflow page was wasted space. The value cannot be lower than
349 * 2 because then there would no longer be a tree structure. With this
350 * value, items larger than 2KB will go into overflow pages, and on
351 * average only 1KB will be wasted.
353 #define MDB_MINKEYS 2
355 /** A stamp that identifies a file as an MDB file.
356 * There's nothing special about this value other than that it is easily
357 * recognizable, and it will reflect any byte order mismatches.
359 #define MDB_MAGIC 0xBEEFC0DE
361 /** The version number for a database's datafile format. */
362 #define MDB_DATA_VERSION 1
363 /** The version number for a database's lockfile format. */
364 #define MDB_LOCK_VERSION 1
366 /** @brief The maximum size of a key in the database.
368 * The library rejects bigger keys, and cannot deal with records
369 * with bigger keys stored by a library with bigger max keysize.
371 * We require that keys all fit onto a regular page. This limit
372 * could be raised a bit further if needed; to something just
373 * under #MDB_PAGESIZE / #MDB_MINKEYS.
375 * Note that data items in an #MDB_DUPSORT database are actually keys
376 * of a subDB, so they're also limited to this size.
378 #ifndef MDB_MAXKEYSIZE
379 #define MDB_MAXKEYSIZE 511
382 /** @brief The maximum size of a data item.
384 * We only store a 32 bit value for node sizes.
386 #define MAXDATASIZE 0xffffffffUL
391 * This is used for printing a hex dump of a key's contents.
393 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
394 /** Display a key in hex.
396 * Invoke a function to display a key in hex.
398 #define DKEY(x) mdb_dkey(x, kbuf)
404 /** An invalid page number.
405 * Mainly used to denote an empty tree.
407 #define P_INVALID (~(pgno_t)0)
409 /** Test if the flags \b f are set in a flag word \b w. */
410 #define F_ISSET(w, f) (((w) & (f)) == (f))
412 /** Used for offsets within a single page.
413 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
416 typedef uint16_t indx_t;
418 /** Default size of memory map.
419 * This is certainly too small for any actual applications. Apps should always set
420 * the size explicitly using #mdb_env_set_mapsize().
422 #define DEFAULT_MAPSIZE 1048576
424 /** @defgroup readers Reader Lock Table
425 * Readers don't acquire any locks for their data access. Instead, they
426 * simply record their transaction ID in the reader table. The reader
427 * mutex is needed just to find an empty slot in the reader table. The
428 * slot's address is saved in thread-specific data so that subsequent read
429 * transactions started by the same thread need no further locking to proceed.
431 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
433 * No reader table is used if the database is on a read-only filesystem, or
434 * if #MDB_NOLOCK is set.
436 * Since the database uses multi-version concurrency control, readers don't
437 * actually need any locking. This table is used to keep track of which
438 * readers are using data from which old transactions, so that we'll know
439 * when a particular old transaction is no longer in use. Old transactions
440 * that have discarded any data pages can then have those pages reclaimed
441 * for use by a later write transaction.
443 * The lock table is constructed such that reader slots are aligned with the
444 * processor's cache line size. Any slot is only ever used by one thread.
445 * This alignment guarantees that there will be no contention or cache
446 * thrashing as threads update their own slot info, and also eliminates
447 * any need for locking when accessing a slot.
449 * A writer thread will scan every slot in the table to determine the oldest
450 * outstanding reader transaction. Any freed pages older than this will be
451 * reclaimed by the writer. The writer doesn't use any locks when scanning
452 * this table. This means that there's no guarantee that the writer will
453 * see the most up-to-date reader info, but that's not required for correct
454 * operation - all we need is to know the upper bound on the oldest reader,
455 * we don't care at all about the newest reader. So the only consequence of
456 * reading stale information here is that old pages might hang around a
457 * while longer before being reclaimed. That's actually good anyway, because
458 * the longer we delay reclaiming old pages, the more likely it is that a
459 * string of contiguous pages can be found after coalescing old pages from
460 * many old transactions together.
463 /** Number of slots in the reader table.
464 * This value was chosen somewhat arbitrarily. 126 readers plus a
465 * couple mutexes fit exactly into 8KB on my development machine.
466 * Applications should set the table size using #mdb_env_set_maxreaders().
468 #define DEFAULT_READERS 126
470 /** The size of a CPU cache line in bytes. We want our lock structures
471 * aligned to this size to avoid false cache line sharing in the
473 * This value works for most CPUs. For Itanium this should be 128.
479 /** The information we store in a single slot of the reader table.
480 * In addition to a transaction ID, we also record the process and
481 * thread ID that owns a slot, so that we can detect stale information,
482 * e.g. threads or processes that went away without cleaning up.
483 * @note We currently don't check for stale records. We simply re-init
484 * the table when we know that we're the only process opening the
487 typedef struct MDB_rxbody {
488 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
489 * Multiple readers that start at the same time will probably have the
490 * same ID here. Again, it's not important to exclude them from
491 * anything; all we need to know is which version of the DB they
492 * started from so we can avoid overwriting any data used in that
493 * particular version.
496 /** The process ID of the process owning this reader txn. */
498 /** The thread ID of the thread owning this txn. */
502 /** The actual reader record, with cacheline padding. */
503 typedef struct MDB_reader {
506 /** shorthand for mrb_txnid */
507 #define mr_txnid mru.mrx.mrb_txnid
508 #define mr_pid mru.mrx.mrb_pid
509 #define mr_tid mru.mrx.mrb_tid
510 /** cache line alignment */
511 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
515 /** The header for the reader table.
516 * The table resides in a memory-mapped file. (This is a different file
517 * than is used for the main database.)
519 * For POSIX the actual mutexes reside in the shared memory of this
520 * mapped file. On Windows, mutexes are named objects allocated by the
521 * kernel; we store the mutex names in this mapped file so that other
522 * processes can grab them. This same approach is also used on
523 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
524 * process-shared POSIX mutexes. For these cases where a named object
525 * is used, the object name is derived from a 64 bit FNV hash of the
526 * environment pathname. As such, naming collisions are extremely
527 * unlikely. If a collision occurs, the results are unpredictable.
529 typedef struct MDB_txbody {
530 /** Stamp identifying this as an MDB file. It must be set
533 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
535 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
536 char mtb_rmname[MNAME_LEN];
538 /** Mutex protecting access to this table.
539 * This is the reader lock that #LOCK_MUTEX_R acquires.
541 pthread_mutex_t mtb_mutex;
543 /** The ID of the last transaction committed to the database.
544 * This is recorded here only for convenience; the value can always
545 * be determined by reading the main database meta pages.
548 /** The number of slots that have been used in the reader table.
549 * This always records the maximum count, it is not decremented
550 * when readers release their slots.
552 unsigned mtb_numreaders;
555 /** The actual reader table definition. */
556 typedef struct MDB_txninfo {
559 #define mti_magic mt1.mtb.mtb_magic
560 #define mti_format mt1.mtb.mtb_format
561 #define mti_mutex mt1.mtb.mtb_mutex
562 #define mti_rmname mt1.mtb.mtb_rmname
563 #define mti_txnid mt1.mtb.mtb_txnid
564 #define mti_numreaders mt1.mtb.mtb_numreaders
565 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
568 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
569 char mt2_wmname[MNAME_LEN];
570 #define mti_wmname mt2.mt2_wmname
572 pthread_mutex_t mt2_wmutex;
573 #define mti_wmutex mt2.mt2_wmutex
575 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
577 MDB_reader mti_readers[1];
580 /** Lockfile format signature: version, features and field layout */
581 #define MDB_LOCK_FORMAT \
583 ((MDB_LOCK_VERSION) \
584 /* Flags which describe functionality */ \
585 + (((MDB_PIDLOCK) != 0) << 16)))
588 /** Common header for all page types.
589 * Overflow records occupy a number of contiguous pages with no
590 * headers on any page after the first.
592 typedef struct MDB_page {
593 #define mp_pgno mp_p.p_pgno
594 #define mp_next mp_p.p_next
596 pgno_t p_pgno; /**< page number */
597 void * p_next; /**< for in-memory list of freed structs */
600 /** @defgroup mdb_page Page Flags
602 * Flags for the page headers.
605 #define P_BRANCH 0x01 /**< branch page */
606 #define P_LEAF 0x02 /**< leaf page */
607 #define P_OVERFLOW 0x04 /**< overflow page */
608 #define P_META 0x08 /**< meta page */
609 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
610 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
611 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
612 #define P_KEEP 0x8000 /**< leave this page alone during spill */
614 uint16_t mp_flags; /**< @ref mdb_page */
615 #define mp_lower mp_pb.pb.pb_lower
616 #define mp_upper mp_pb.pb.pb_upper
617 #define mp_pages mp_pb.pb_pages
620 indx_t pb_lower; /**< lower bound of free space */
621 indx_t pb_upper; /**< upper bound of free space */
623 uint32_t pb_pages; /**< number of overflow pages */
625 indx_t mp_ptrs[1]; /**< dynamic size */
628 /** Size of the page header, excluding dynamic data at the end */
629 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
631 /** Address of first usable data byte in a page, after the header */
632 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
634 /** Number of nodes on a page */
635 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
637 /** The amount of space remaining in the page */
638 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
640 /** The percentage of space used in the page, in tenths of a percent. */
641 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
642 ((env)->me_psize - PAGEHDRSZ))
643 /** The minimum page fill factor, in tenths of a percent.
644 * Pages emptier than this are candidates for merging.
646 #define FILL_THRESHOLD 250
648 /** Test if a page is a leaf page */
649 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
650 /** Test if a page is a LEAF2 page */
651 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
652 /** Test if a page is a branch page */
653 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
654 /** Test if a page is an overflow page */
655 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
656 /** Test if a page is a sub page */
657 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
659 /** The number of overflow pages needed to store the given size. */
660 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
662 /** Header for a single key/data pair within a page.
663 * We guarantee 2-byte alignment for nodes.
665 typedef struct MDB_node {
666 /** lo and hi are used for data size on leaf nodes and for
667 * child pgno on branch nodes. On 64 bit platforms, flags
668 * is also used for pgno. (Branch nodes have no flags).
669 * They are in host byte order in case that lets some
670 * accesses be optimized into a 32-bit word access.
672 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
673 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
674 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
675 /** @defgroup mdb_node Node Flags
677 * Flags for node headers.
680 #define F_BIGDATA 0x01 /**< data put on overflow page */
681 #define F_SUBDATA 0x02 /**< data is a sub-database */
682 #define F_DUPDATA 0x04 /**< data has duplicates */
684 /** valid flags for #mdb_node_add() */
685 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
688 unsigned short mn_flags; /**< @ref mdb_node */
689 unsigned short mn_ksize; /**< key size */
690 char mn_data[1]; /**< key and data are appended here */
693 /** Size of the node header, excluding dynamic data at the end */
694 #define NODESIZE offsetof(MDB_node, mn_data)
696 /** Bit position of top word in page number, for shifting mn_flags */
697 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
699 /** Size of a node in a branch page with a given key.
700 * This is just the node header plus the key, there is no data.
702 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
704 /** Size of a node in a leaf page with a given key and data.
705 * This is node header plus key plus data size.
707 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
709 /** Address of node \b i in page \b p */
710 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
712 /** Address of the key for the node */
713 #define NODEKEY(node) (void *)((node)->mn_data)
715 /** Address of the data for a node */
716 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
718 /** Get the page number pointed to by a branch node */
719 #define NODEPGNO(node) \
720 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
721 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
722 /** Set the page number in a branch node */
723 #define SETPGNO(node,pgno) do { \
724 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
725 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
727 /** Get the size of the data in a leaf node */
728 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
729 /** Set the size of the data for a leaf node */
730 #define SETDSZ(node,size) do { \
731 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
732 /** The size of a key in a node */
733 #define NODEKSZ(node) ((node)->mn_ksize)
735 /** Copy a page number from src to dst */
737 #define COPY_PGNO(dst,src) dst = src
739 #if SIZE_MAX > 4294967295UL
740 #define COPY_PGNO(dst,src) do { \
741 unsigned short *s, *d; \
742 s = (unsigned short *)&(src); \
743 d = (unsigned short *)&(dst); \
750 #define COPY_PGNO(dst,src) do { \
751 unsigned short *s, *d; \
752 s = (unsigned short *)&(src); \
753 d = (unsigned short *)&(dst); \
759 /** The address of a key in a LEAF2 page.
760 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
761 * There are no node headers, keys are stored contiguously.
763 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
765 /** Set the \b node's key into \b keyptr, if requested. */
766 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
767 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
769 /** Set the \b node's key into \b key. */
770 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
772 /** Information about a single database in the environment. */
773 typedef struct MDB_db {
774 uint32_t md_pad; /**< also ksize for LEAF2 pages */
775 uint16_t md_flags; /**< @ref mdb_dbi_open */
776 uint16_t md_depth; /**< depth of this tree */
777 pgno_t md_branch_pages; /**< number of internal pages */
778 pgno_t md_leaf_pages; /**< number of leaf pages */
779 pgno_t md_overflow_pages; /**< number of overflow pages */
780 size_t md_entries; /**< number of data items */
781 pgno_t md_root; /**< the root page of this tree */
784 /** mdb_dbi_open flags */
785 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
786 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
787 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
788 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
790 /** Handle for the DB used to track free pages. */
792 /** Handle for the default DB. */
795 /** Meta page content.
796 * A meta page is the start point for accessing a database snapshot.
797 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
799 typedef struct MDB_meta {
800 /** Stamp identifying this as an MDB file. It must be set
803 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
805 void *mm_address; /**< address for fixed mapping */
806 size_t mm_mapsize; /**< size of mmap region */
807 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
808 /** The size of pages used in this DB */
809 #define mm_psize mm_dbs[0].md_pad
810 /** Any persistent environment flags. @ref mdb_env */
811 #define mm_flags mm_dbs[0].md_flags
812 pgno_t mm_last_pg; /**< last used page in file */
813 txnid_t mm_txnid; /**< txnid that committed this page */
816 /** Buffer for a stack-allocated dirty page.
817 * The members define size and alignment, and silence type
818 * aliasing warnings. They are not used directly; that could
819 * mean incorrectly using several union members in parallel.
821 typedef union MDB_pagebuf {
822 char mb_raw[MDB_PAGESIZE];
825 char mm_pad[PAGEHDRSZ];
830 /** Auxiliary DB info.
831 * The information here is mostly static/read-only. There is
832 * only a single copy of this record in the environment.
834 typedef struct MDB_dbx {
835 MDB_val md_name; /**< name of the database */
836 MDB_cmp_func *md_cmp; /**< function for comparing keys */
837 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
838 MDB_rel_func *md_rel; /**< user relocate function */
839 void *md_relctx; /**< user-provided context for md_rel */
842 /** A database transaction.
843 * Every operation requires a transaction handle.
846 MDB_txn *mt_parent; /**< parent of a nested txn */
847 MDB_txn *mt_child; /**< nested txn under this txn */
848 pgno_t mt_next_pgno; /**< next unallocated page */
849 /** The ID of this transaction. IDs are integers incrementing from 1.
850 * Only committed write transactions increment the ID. If a transaction
851 * aborts, the ID may be re-used by the next writer.
854 MDB_env *mt_env; /**< the DB environment */
855 /** The list of pages that became unused during this transaction.
858 /** The sorted list of dirty pages we temporarily wrote to disk
859 * because the dirty list was full. page numbers in here are
860 * shifted left by 1, deleted slots have the LSB set.
862 MDB_IDL mt_spill_pgs;
864 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
866 /** For read txns: This thread/txn's reader table slot, or NULL. */
869 /** Array of records for each DB known in the environment. */
871 /** Array of MDB_db records for each known DB */
873 /** @defgroup mt_dbflag Transaction DB Flags
877 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
878 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
879 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
880 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
882 /** In write txns, array of cursors for each DB */
883 MDB_cursor **mt_cursors;
884 /** Array of flags for each DB */
885 unsigned char *mt_dbflags;
886 /** Number of DB records in use. This number only ever increments;
887 * we don't decrement it when individual DB handles are closed.
891 /** @defgroup mdb_txn Transaction Flags
895 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
896 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
897 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
898 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
900 unsigned int mt_flags; /**< @ref mdb_txn */
901 /** dirty_list room: Array size - #dirty pages visible to this txn.
902 * Includes ancestor txns' dirty pages not hidden by other txns'
903 * dirty/spilled pages. Thus commit(nested txn) has room to merge
904 * dirty_list into mt_parent after freeing hidden mt_parent pages.
906 unsigned int mt_dirty_room;
909 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
910 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
911 * raise this on a 64 bit machine.
913 #define CURSOR_STACK 32
917 /** Cursors are used for all DB operations.
918 * A cursor holds a path of (page pointer, key index) from the DB
919 * root to a position in the DB, plus other state. #MDB_DUPSORT
920 * cursors include an xcursor to the current data item. Write txns
921 * track their cursors and keep them up to date when data moves.
922 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
923 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
926 /** Next cursor on this DB in this txn */
928 /** Backup of the original cursor if this cursor is a shadow */
929 MDB_cursor *mc_backup;
930 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
931 struct MDB_xcursor *mc_xcursor;
932 /** The transaction that owns this cursor */
934 /** The database handle this cursor operates on */
936 /** The database record for this cursor */
938 /** The database auxiliary record for this cursor */
940 /** The @ref mt_dbflag for this database */
941 unsigned char *mc_dbflag;
942 unsigned short mc_snum; /**< number of pushed pages */
943 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
944 /** @defgroup mdb_cursor Cursor Flags
946 * Cursor state flags.
949 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
950 #define C_EOF 0x02 /**< No more data */
951 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
952 #define C_DEL 0x08 /**< last op was a cursor_del */
953 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
954 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
956 unsigned int mc_flags; /**< @ref mdb_cursor */
957 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
958 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
961 /** Context for sorted-dup records.
962 * We could have gone to a fully recursive design, with arbitrarily
963 * deep nesting of sub-databases. But for now we only handle these
964 * levels - main DB, optional sub-DB, sorted-duplicate DB.
966 typedef struct MDB_xcursor {
967 /** A sub-cursor for traversing the Dup DB */
968 MDB_cursor mx_cursor;
969 /** The database record for this Dup DB */
971 /** The auxiliary DB record for this Dup DB */
973 /** The @ref mt_dbflag for this Dup DB */
974 unsigned char mx_dbflag;
977 /** State of FreeDB old pages, stored in the MDB_env */
978 typedef struct MDB_pgstate {
979 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
980 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
983 /** The database environment. */
985 HANDLE me_fd; /**< The main data file */
986 HANDLE me_lfd; /**< The lock file */
987 HANDLE me_mfd; /**< just for writing the meta pages */
988 /** Failed to update the meta page. Probably an I/O error. */
989 #define MDB_FATAL_ERROR 0x80000000U
990 /** Some fields are initialized. */
991 #define MDB_ENV_ACTIVE 0x20000000U
992 /** me_txkey is set */
993 #define MDB_ENV_TXKEY 0x10000000U
994 /** Have liveness lock in reader table */
995 #define MDB_LIVE_READER 0x08000000U
996 uint32_t me_flags; /**< @ref mdb_env */
997 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
998 unsigned int me_maxreaders; /**< size of the reader table */
999 unsigned int me_numreaders; /**< max numreaders set by this env */
1000 MDB_dbi me_numdbs; /**< number of DBs opened */
1001 MDB_dbi me_maxdbs; /**< size of the DB table */
1002 pid_t me_pid; /**< process ID of this env */
1003 char *me_path; /**< path to the DB files */
1004 char *me_map; /**< the memory map of the data file */
1005 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1006 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1007 MDB_txn *me_txn; /**< current write transaction */
1008 size_t me_mapsize; /**< size of the data memory map */
1009 off_t me_size; /**< current file size */
1010 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1011 MDB_dbx *me_dbxs; /**< array of static DB info */
1012 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1013 pthread_key_t me_txkey; /**< thread-key for readers */
1014 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1015 # define me_pglast me_pgstate.mf_pglast
1016 # define me_pghead me_pgstate.mf_pghead
1017 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1018 /** IDL of pages that became unused in a write txn */
1019 MDB_IDL me_free_pgs;
1020 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1021 MDB_ID2L me_dirty_list;
1022 /** Max number of freelist items that can fit in a single overflow page */
1024 /** Max size of a node on a page */
1025 unsigned int me_nodemax;
1027 int me_pidquery; /**< Used in OpenProcess */
1028 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1030 #elif defined(MDB_USE_POSIX_SEM)
1031 sem_t *me_rmutex; /* Shared mutexes are not supported */
1036 /** Nested transaction */
1037 typedef struct MDB_ntxn {
1038 MDB_txn mnt_txn; /**< the transaction */
1039 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1042 /** max number of pages to commit in one writev() call */
1043 #define MDB_COMMIT_PAGES 64
1044 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1045 #undef MDB_COMMIT_PAGES
1046 #define MDB_COMMIT_PAGES IOV_MAX
1049 /* max bytes to write in one call */
1050 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1052 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1053 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1054 static int mdb_page_touch(MDB_cursor *mc);
1056 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1057 static int mdb_page_search_root(MDB_cursor *mc,
1058 MDB_val *key, int modify);
1059 #define MDB_PS_MODIFY 1
1060 #define MDB_PS_ROOTONLY 2
1061 #define MDB_PS_FIRST 4
1062 #define MDB_PS_LAST 8
1063 static int mdb_page_search(MDB_cursor *mc,
1064 MDB_val *key, int flags);
1065 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1067 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1068 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1069 pgno_t newpgno, unsigned int nflags);
1071 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1072 static int mdb_env_pick_meta(const MDB_env *env);
1073 static int mdb_env_write_meta(MDB_txn *txn);
1074 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1075 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1077 static void mdb_env_close0(MDB_env *env, int excl);
1079 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1080 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1081 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1082 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1083 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1084 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1085 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1086 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1087 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1089 static int mdb_rebalance(MDB_cursor *mc);
1090 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1092 static void mdb_cursor_pop(MDB_cursor *mc);
1093 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1095 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1096 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1097 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1098 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1099 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1101 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1102 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1104 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1105 static void mdb_xcursor_init0(MDB_cursor *mc);
1106 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1108 static int mdb_drop0(MDB_cursor *mc, int subs);
1109 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1112 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1116 static SECURITY_DESCRIPTOR mdb_null_sd;
1117 static SECURITY_ATTRIBUTES mdb_all_sa;
1118 static int mdb_sec_inited;
1121 /** Return the library version info. */
1123 mdb_version(int *major, int *minor, int *patch)
1125 if (major) *major = MDB_VERSION_MAJOR;
1126 if (minor) *minor = MDB_VERSION_MINOR;
1127 if (patch) *patch = MDB_VERSION_PATCH;
1128 return MDB_VERSION_STRING;
1131 /** Table of descriptions for MDB @ref errors */
1132 static char *const mdb_errstr[] = {
1133 "MDB_KEYEXIST: Key/data pair already exists",
1134 "MDB_NOTFOUND: No matching key/data pair found",
1135 "MDB_PAGE_NOTFOUND: Requested page not found",
1136 "MDB_CORRUPTED: Located page was wrong type",
1137 "MDB_PANIC: Update of meta page failed",
1138 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1139 "MDB_INVALID: File is not an MDB file",
1140 "MDB_MAP_FULL: Environment mapsize limit reached",
1141 "MDB_DBS_FULL: Environment maxdbs limit reached",
1142 "MDB_READERS_FULL: Environment maxreaders limit reached",
1143 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1144 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1145 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1146 "MDB_PAGE_FULL: Internal error - page has no more space",
1147 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1148 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1149 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1150 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1151 "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1155 mdb_strerror(int err)
1159 return ("Successful return: 0");
1161 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1162 i = err - MDB_KEYEXIST;
1163 return mdb_errstr[i];
1166 return strerror(err);
1170 /** Display a key in hexadecimal and return the address of the result.
1171 * @param[in] key the key to display
1172 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1173 * @return The key in hexadecimal form.
1176 mdb_dkey(MDB_val *key, char *buf)
1179 unsigned char *c = key->mv_data;
1185 if (key->mv_size > MDB_MAXKEYSIZE)
1186 return "MDB_MAXKEYSIZE";
1187 /* may want to make this a dynamic check: if the key is mostly
1188 * printable characters, print it as-is instead of converting to hex.
1192 for (i=0; i<key->mv_size; i++)
1193 ptr += sprintf(ptr, "%02x", *c++);
1195 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1200 /** Display all the keys in the page. */
1202 mdb_page_list(MDB_page *mp)
1205 unsigned int i, nkeys, nsize;
1209 nkeys = NUMKEYS(mp);
1210 fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
1211 for (i=0; i<nkeys; i++) {
1212 node = NODEPTR(mp, i);
1213 key.mv_size = node->mn_ksize;
1214 key.mv_data = node->mn_data;
1215 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1216 if (IS_BRANCH(mp)) {
1217 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1220 if (F_ISSET(node->mn_flags, F_BIGDATA))
1221 nsize += sizeof(pgno_t);
1223 nsize += NODEDSZ(node);
1224 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1230 mdb_cursor_chk(MDB_cursor *mc)
1236 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1237 for (i=0; i<mc->mc_top; i++) {
1239 node = NODEPTR(mp, mc->mc_ki[i]);
1240 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1243 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1249 /** Count all the pages in each DB and in the freelist
1250 * and make sure it matches the actual number of pages
1253 static void mdb_audit(MDB_txn *txn)
1257 MDB_ID freecount, count;
1262 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1263 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1264 freecount += *(MDB_ID *)data.mv_data;
1267 for (i = 0; i<txn->mt_numdbs; i++) {
1269 mdb_cursor_init(&mc, txn, i, &mx);
1270 if (txn->mt_dbs[i].md_root == P_INVALID)
1272 count += txn->mt_dbs[i].md_branch_pages +
1273 txn->mt_dbs[i].md_leaf_pages +
1274 txn->mt_dbs[i].md_overflow_pages;
1275 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1276 mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1280 mp = mc.mc_pg[mc.mc_top];
1281 for (j=0; j<NUMKEYS(mp); j++) {
1282 MDB_node *leaf = NODEPTR(mp, j);
1283 if (leaf->mn_flags & F_SUBDATA) {
1285 memcpy(&db, NODEDATA(leaf), sizeof(db));
1286 count += db.md_branch_pages + db.md_leaf_pages +
1287 db.md_overflow_pages;
1291 while (mdb_cursor_sibling(&mc, 1) == 0);
1294 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1295 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1296 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1302 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1304 return txn->mt_dbxs[dbi].md_cmp(a, b);
1308 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1310 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1313 /** Allocate memory for a page.
1314 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1317 mdb_page_malloc(MDB_txn *txn, unsigned num)
1319 MDB_env *env = txn->mt_env;
1320 MDB_page *ret = env->me_dpages;
1321 size_t sz = env->me_psize;
1324 VGMEMP_ALLOC(env, ret, sz);
1325 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1326 env->me_dpages = ret->mp_next;
1332 if ((ret = malloc(sz)) != NULL) {
1333 VGMEMP_ALLOC(env, ret, sz);
1338 /** Free a single page.
1339 * Saves single pages to a list, for future reuse.
1340 * (This is not used for multi-page overflow pages.)
1343 mdb_page_free(MDB_env *env, MDB_page *mp)
1345 mp->mp_next = env->me_dpages;
1346 VGMEMP_FREE(env, mp);
1347 env->me_dpages = mp;
1350 /** Free a dirty page */
1352 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1354 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1355 mdb_page_free(env, dp);
1357 /* large pages just get freed directly */
1358 VGMEMP_FREE(env, dp);
1363 /** Return all dirty pages to dpage list */
1365 mdb_dlist_free(MDB_txn *txn)
1367 MDB_env *env = txn->mt_env;
1368 MDB_ID2L dl = txn->mt_u.dirty_list;
1369 unsigned i, n = dl[0].mid;
1371 for (i = 1; i <= n; i++) {
1372 mdb_dpage_free(env, dl[i].mptr);
1377 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1378 * @param[in] mc A cursor handle for the current operation.
1379 * @param[in] pflags Flags of the pages to update:
1380 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1381 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1382 * @return 0 on success, non-zero on failure.
1385 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1387 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1388 MDB_txn *txn = mc->mc_txn;
1394 int rc = MDB_SUCCESS, level;
1396 /* Mark pages seen by cursors */
1397 if (mc->mc_flags & C_UNTRACK)
1398 mc = NULL; /* will find mc in mt_cursors */
1399 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1400 for (; mc; mc=mc->mc_next) {
1401 if (!(mc->mc_flags & C_INITIALIZED))
1403 for (m3 = mc;; m3 = &mx->mx_cursor) {
1405 for (j=0; j<m3->mc_snum; j++) {
1407 if ((mp->mp_flags & Mask) == pflags)
1408 mp->mp_flags ^= P_KEEP;
1410 mx = m3->mc_xcursor;
1411 /* Proceed to mx if it is at a sub-database */
1412 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1414 if (! (mp && (mp->mp_flags & P_LEAF)))
1416 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1417 if (!(leaf->mn_flags & F_SUBDATA))
1426 /* Mark dirty root pages */
1427 for (i=0; i<txn->mt_numdbs; i++) {
1428 if (txn->mt_dbflags[i] & DB_DIRTY) {
1429 pgno_t pgno = txn->mt_dbs[i].md_root;
1430 if (pgno == P_INVALID)
1432 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1434 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1435 dp->mp_flags ^= P_KEEP;
1443 static int mdb_page_flush(MDB_txn *txn, int keep);
1445 /** Spill pages from the dirty list back to disk.
1446 * This is intended to prevent running into #MDB_TXN_FULL situations,
1447 * but note that they may still occur in a few cases:
1448 * 1) our estimate of the txn size could be too small. Currently this
1449 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1450 * 2) child txns may run out of space if their parents dirtied a
1451 * lot of pages and never spilled them. TODO: we probably should do
1452 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1453 * the parent's dirty_room is below a given threshold.
1455 * Otherwise, if not using nested txns, it is expected that apps will
1456 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1457 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1458 * If the txn never references them again, they can be left alone.
1459 * If the txn only reads them, they can be used without any fuss.
1460 * If the txn writes them again, they can be dirtied immediately without
1461 * going thru all of the work of #mdb_page_touch(). Such references are
1462 * handled by #mdb_page_unspill().
1464 * Also note, we never spill DB root pages, nor pages of active cursors,
1465 * because we'll need these back again soon anyway. And in nested txns,
1466 * we can't spill a page in a child txn if it was already spilled in a
1467 * parent txn. That would alter the parent txns' data even though
1468 * the child hasn't committed yet, and we'd have no way to undo it if
1469 * the child aborted.
1471 * @param[in] m0 cursor A cursor handle identifying the transaction and
1472 * database for which we are checking space.
1473 * @param[in] key For a put operation, the key being stored.
1474 * @param[in] data For a put operation, the data being stored.
1475 * @return 0 on success, non-zero on failure.
1478 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1480 MDB_txn *txn = m0->mc_txn;
1482 MDB_ID2L dl = txn->mt_u.dirty_list;
1483 unsigned int i, j, need;
1486 if (m0->mc_flags & C_SUB)
1489 /* Estimate how much space this op will take */
1490 i = m0->mc_db->md_depth;
1491 /* Named DBs also dirty the main DB */
1492 if (m0->mc_dbi > MAIN_DBI)
1493 i += txn->mt_dbs[MAIN_DBI].md_depth;
1494 /* For puts, roughly factor in the key+data size */
1496 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1497 i += i; /* double it for good measure */
1500 if (txn->mt_dirty_room > i)
1503 if (!txn->mt_spill_pgs) {
1504 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1505 if (!txn->mt_spill_pgs)
1508 /* purge deleted slots */
1509 MDB_IDL sl = txn->mt_spill_pgs;
1510 unsigned int num = sl[0];
1512 for (i=1; i<=num; i++) {
1519 /* Preserve pages which may soon be dirtied again */
1520 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1523 /* Less aggressive spill - we originally spilled the entire dirty list,
1524 * with a few exceptions for cursor pages and DB root pages. But this
1525 * turns out to be a lot of wasted effort because in a large txn many
1526 * of those pages will need to be used again. So now we spill only 1/8th
1527 * of the dirty pages. Testing revealed this to be a good tradeoff,
1528 * better than 1/2, 1/4, or 1/10.
1530 if (need < MDB_IDL_UM_MAX / 8)
1531 need = MDB_IDL_UM_MAX / 8;
1533 /* Save the page IDs of all the pages we're flushing */
1534 /* flush from the tail forward, this saves a lot of shifting later on. */
1535 for (i=dl[0].mid; i && need; i--) {
1536 MDB_ID pn = dl[i].mid << 1;
1538 if (dp->mp_flags & P_KEEP)
1540 /* Can't spill twice, make sure it's not already in a parent's
1543 if (txn->mt_parent) {
1545 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1546 if (tx2->mt_spill_pgs) {
1547 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1548 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1549 dp->mp_flags |= P_KEEP;
1557 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1561 mdb_midl_sort(txn->mt_spill_pgs);
1563 /* Flush the spilled part of dirty list */
1564 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1567 /* Reset any dirty pages we kept that page_flush didn't see */
1568 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1571 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1575 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1577 mdb_find_oldest(MDB_txn *txn)
1580 txnid_t mr, oldest = txn->mt_txnid - 1;
1581 if (txn->mt_env->me_txns) {
1582 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1583 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1594 /** Add a page to the txn's dirty list */
1596 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1599 int (*insert)(MDB_ID2L, MDB_ID2 *);
1601 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1602 insert = mdb_mid2l_append;
1604 insert = mdb_mid2l_insert;
1606 mid.mid = mp->mp_pgno;
1608 insert(txn->mt_u.dirty_list, &mid);
1609 txn->mt_dirty_room--;
1612 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1613 * me_pghead and mt_next_pgno.
1615 * If there are free pages available from older transactions, they
1616 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1617 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1618 * and move me_pglast to say which records were consumed. Only this
1619 * function can create me_pghead and move me_pglast/mt_next_pgno.
1620 * @param[in] mc cursor A cursor handle identifying the transaction and
1621 * database for which we are allocating.
1622 * @param[in] num the number of pages to allocate.
1623 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1624 * will always be satisfied by a single contiguous chunk of memory.
1625 * @return 0 on success, non-zero on failure.
1628 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1630 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1631 /* Get at most <Max_retries> more freeDB records once me_pghead
1632 * has enough pages. If not enough, use new pages from the map.
1633 * If <Paranoid> and mc is updating the freeDB, only get new
1634 * records if me_pghead is empty. Then the freelist cannot play
1635 * catch-up with itself by growing while trying to save it.
1637 enum { Paranoid = 1, Max_retries = 500 };
1639 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1641 int rc, n2 = num-1, retry = Max_retries;
1642 MDB_txn *txn = mc->mc_txn;
1643 MDB_env *env = txn->mt_env;
1644 pgno_t pgno, *mop = env->me_pghead;
1645 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1647 txnid_t oldest = 0, last;
1653 /* If our dirty list is already full, we can't do anything */
1654 if (txn->mt_dirty_room == 0)
1655 return MDB_TXN_FULL;
1657 for (op = MDB_FIRST;; op = MDB_NEXT) {
1660 pgno_t *idl, old_id, new_id;
1662 /* Seek a big enough contiguous page range. Prefer
1663 * pages at the tail, just truncating the list.
1665 if (mop_len >= (unsigned)num) {
1669 if (mop[i-n2] == pgno+n2)
1671 } while (--i >= (unsigned)num);
1672 if (Max_retries < INT_MAX && --retry < 0)
1676 if (op == MDB_FIRST) { /* 1st iteration */
1677 /* Prepare to fetch more and coalesce */
1678 oldest = mdb_find_oldest(txn);
1679 last = env->me_pglast;
1680 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1683 key.mv_data = &last; /* will look up last+1 */
1684 key.mv_size = sizeof(last);
1686 if (Paranoid && mc->mc_dbi == FREE_DBI)
1689 if (Paranoid && retry < 0 && mop_len)
1693 /* Do not fetch more if the record will be too recent */
1696 rc = mdb_cursor_get(&m2, &key, NULL, op);
1698 if (rc == MDB_NOTFOUND)
1702 last = *(txnid_t*)key.mv_data;
1705 np = m2.mc_pg[m2.mc_top];
1706 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1707 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1710 idl = (MDB_ID *) data.mv_data;
1713 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1716 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1718 mop = env->me_pghead;
1720 env->me_pglast = last;
1722 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1723 last, txn->mt_dbs[FREE_DBI].md_root, i));
1725 DPRINTF(("IDL %"Z"u", idl[k]));
1727 /* Merge in descending sorted order */
1730 mop[0] = (pgno_t)-1;
1734 for (; old_id < new_id; old_id = mop[--j])
1741 /* Use new pages from the map when nothing suitable in the freeDB */
1743 pgno = txn->mt_next_pgno;
1744 if (pgno + num >= env->me_maxpg) {
1745 DPUTS("DB size maxed out");
1746 return MDB_MAP_FULL;
1750 if (env->me_flags & MDB_WRITEMAP) {
1751 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1753 if (!(np = mdb_page_malloc(txn, num)))
1757 mop[0] = mop_len -= num;
1758 /* Move any stragglers down */
1759 for (j = i-num; j < mop_len; )
1760 mop[++j] = mop[++i];
1762 txn->mt_next_pgno = pgno + num;
1765 mdb_page_dirty(txn, np);
1771 /** Copy the used portions of a non-overflow page.
1772 * @param[in] dst page to copy into
1773 * @param[in] src page to copy from
1774 * @param[in] psize size of a page
1777 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1779 enum { Align = sizeof(pgno_t) };
1780 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1782 /* If page isn't full, just copy the used portion. Adjust
1783 * alignment so memcpy may copy words instead of bytes.
1785 if ((unused &= -Align) && !IS_LEAF2(src)) {
1787 memcpy(dst, src, (lower + (Align-1)) & -Align);
1788 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1791 memcpy(dst, src, psize - unused);
1795 /** Pull a page off the txn's spill list, if present.
1796 * If a page being referenced was spilled to disk in this txn, bring
1797 * it back and make it dirty/writable again.
1798 * @param[in] txn the transaction handle.
1799 * @param[in] mp the page being referenced.
1800 * @param[out] ret the writable page, if any. ret is unchanged if
1801 * mp wasn't spilled.
1804 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1806 MDB_env *env = txn->mt_env;
1809 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1811 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1812 if (!tx2->mt_spill_pgs)
1814 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1815 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1818 if (txn->mt_dirty_room == 0)
1819 return MDB_TXN_FULL;
1820 if (IS_OVERFLOW(mp))
1824 if (env->me_flags & MDB_WRITEMAP) {
1827 np = mdb_page_malloc(txn, num);
1831 memcpy(np, mp, num * env->me_psize);
1833 mdb_page_copy(np, mp, env->me_psize);
1836 /* If in current txn, this page is no longer spilled.
1837 * If it happens to be the last page, truncate the spill list.
1838 * Otherwise mark it as deleted by setting the LSB.
1840 if (x == txn->mt_spill_pgs[0])
1841 txn->mt_spill_pgs[0]--;
1843 txn->mt_spill_pgs[x] |= 1;
1844 } /* otherwise, if belonging to a parent txn, the
1845 * page remains spilled until child commits
1848 mdb_page_dirty(txn, np);
1849 np->mp_flags |= P_DIRTY;
1857 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1858 * @param[in] mc cursor pointing to the page to be touched
1859 * @return 0 on success, non-zero on failure.
1862 mdb_page_touch(MDB_cursor *mc)
1864 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1865 MDB_txn *txn = mc->mc_txn;
1866 MDB_cursor *m2, *m3;
1870 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1871 if (txn->mt_flags & MDB_TXN_SPILLS) {
1873 rc = mdb_page_unspill(txn, mp, &np);
1879 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1880 (rc = mdb_page_alloc(mc, 1, &np)))
1883 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1884 mp->mp_pgno, pgno));
1885 assert(mp->mp_pgno != pgno);
1886 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1887 /* Update the parent page, if any, to point to the new page */
1889 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1890 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1891 SETPGNO(node, pgno);
1893 mc->mc_db->md_root = pgno;
1895 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1896 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1898 /* If txn has a parent, make sure the page is in our
1902 unsigned x = mdb_mid2l_search(dl, pgno);
1903 if (x <= dl[0].mid && dl[x].mid == pgno) {
1904 if (mp != dl[x].mptr) { /* bad cursor? */
1905 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1906 return MDB_CORRUPTED;
1911 assert(dl[0].mid < MDB_IDL_UM_MAX);
1913 np = mdb_page_malloc(txn, 1);
1918 mdb_mid2l_insert(dl, &mid);
1923 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1925 np->mp_flags |= P_DIRTY;
1928 /* Adjust cursors pointing to mp */
1929 mc->mc_pg[mc->mc_top] = np;
1930 m2 = txn->mt_cursors[mc->mc_dbi];
1931 if (mc->mc_flags & C_SUB) {
1932 for (; m2; m2=m2->mc_next) {
1933 m3 = &m2->mc_xcursor->mx_cursor;
1934 if (m3->mc_snum < mc->mc_snum) continue;
1935 if (m3->mc_pg[mc->mc_top] == mp)
1936 m3->mc_pg[mc->mc_top] = np;
1939 for (; m2; m2=m2->mc_next) {
1940 if (m2->mc_snum < mc->mc_snum) continue;
1941 if (m2->mc_pg[mc->mc_top] == mp) {
1942 m2->mc_pg[mc->mc_top] = np;
1943 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1944 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1946 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1947 if (!(leaf->mn_flags & F_SUBDATA))
1948 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1957 mdb_env_sync(MDB_env *env, int force)
1960 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1961 if (env->me_flags & MDB_WRITEMAP) {
1962 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1963 ? MS_ASYNC : MS_SYNC;
1964 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1967 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1971 if (MDB_FDATASYNC(env->me_fd))
1978 /** Back up parent txn's cursors, then grab the originals for tracking */
1980 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1982 MDB_cursor *mc, *bk;
1987 for (i = src->mt_numdbs; --i >= 0; ) {
1988 if ((mc = src->mt_cursors[i]) != NULL) {
1989 size = sizeof(MDB_cursor);
1991 size += sizeof(MDB_xcursor);
1992 for (; mc; mc = bk->mc_next) {
1998 mc->mc_db = &dst->mt_dbs[i];
1999 /* Kill pointers into src - and dst to reduce abuse: The
2000 * user may not use mc until dst ends. Otherwise we'd...
2002 mc->mc_txn = NULL; /* ...set this to dst */
2003 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2004 if ((mx = mc->mc_xcursor) != NULL) {
2005 *(MDB_xcursor *)(bk+1) = *mx;
2006 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2008 mc->mc_next = dst->mt_cursors[i];
2009 dst->mt_cursors[i] = mc;
2016 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2017 * @param[in] txn the transaction handle.
2018 * @param[in] merge true to keep changes to parent cursors, false to revert.
2019 * @return 0 on success, non-zero on failure.
2022 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2024 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2028 for (i = txn->mt_numdbs; --i >= 0; ) {
2029 for (mc = cursors[i]; mc; mc = next) {
2031 if ((bk = mc->mc_backup) != NULL) {
2033 /* Commit changes to parent txn */
2034 mc->mc_next = bk->mc_next;
2035 mc->mc_backup = bk->mc_backup;
2036 mc->mc_txn = bk->mc_txn;
2037 mc->mc_db = bk->mc_db;
2038 mc->mc_dbflag = bk->mc_dbflag;
2039 if ((mx = mc->mc_xcursor) != NULL)
2040 mx->mx_cursor.mc_txn = bk->mc_txn;
2042 /* Abort nested txn */
2044 if ((mx = mc->mc_xcursor) != NULL)
2045 *mx = *(MDB_xcursor *)(bk+1);
2049 /* Only malloced cursors are permanently tracked. */
2057 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2060 mdb_txn_reset0(MDB_txn *txn, const char *act);
2062 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2068 Pidset = F_SETLK, Pidcheck = F_GETLK
2072 /** Set or check a pid lock. Set returns 0 on success.
2073 * Check returns 0 if the process is certainly dead, nonzero if it may
2074 * be alive (the lock exists or an error happened so we do not know).
2076 * On Windows Pidset is a no-op, we merely check for the existence
2077 * of the process with the given pid. On POSIX we use a single byte
2078 * lock on the lockfile, set at an offset equal to the pid.
2081 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
2083 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2086 if (op == Pidcheck) {
2087 h = OpenProcess(env->me_pidquery, FALSE, pid);
2088 /* No documented "no such process" code, but other program use this: */
2090 return ErrCode() != ERROR_INVALID_PARAMETER;
2091 /* A process exists until all handles to it close. Has it exited? */
2092 ret = WaitForSingleObject(h, 0) != 0;
2099 struct flock lock_info;
2100 memset(&lock_info, 0, sizeof(lock_info));
2101 lock_info.l_type = F_WRLCK;
2102 lock_info.l_whence = SEEK_SET;
2103 lock_info.l_start = pid;
2104 lock_info.l_len = 1;
2105 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2106 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2108 } else if ((rc = ErrCode()) == EINTR) {
2116 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2117 * @param[in] txn the transaction handle to initialize
2118 * @return 0 on success, non-zero on failure.
2121 mdb_txn_renew0(MDB_txn *txn)
2123 MDB_env *env = txn->mt_env;
2124 MDB_txninfo *ti = env->me_txns;
2128 int rc, new_notls = 0;
2131 txn->mt_numdbs = env->me_numdbs;
2132 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2134 if (txn->mt_flags & MDB_TXN_RDONLY) {
2136 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2137 txn->mt_txnid = meta->mm_txnid;
2138 txn->mt_u.reader = NULL;
2140 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2141 pthread_getspecific(env->me_txkey);
2143 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2144 return MDB_BAD_RSLOT;
2146 pid_t pid = env->me_pid;
2147 pthread_t tid = pthread_self();
2149 if (!(env->me_flags & MDB_LIVE_READER)) {
2150 rc = mdb_reader_pid(env, Pidset, pid);
2152 UNLOCK_MUTEX_R(env);
2155 env->me_flags |= MDB_LIVE_READER;
2159 nr = ti->mti_numreaders;
2160 for (i=0; i<nr; i++)
2161 if (ti->mti_readers[i].mr_pid == 0)
2163 if (i == env->me_maxreaders) {
2164 UNLOCK_MUTEX_R(env);
2165 return MDB_READERS_FULL;
2167 ti->mti_readers[i].mr_pid = pid;
2168 ti->mti_readers[i].mr_tid = tid;
2170 ti->mti_numreaders = ++nr;
2171 /* Save numreaders for un-mutexed mdb_env_close() */
2172 env->me_numreaders = nr;
2173 UNLOCK_MUTEX_R(env);
2175 r = &ti->mti_readers[i];
2176 new_notls = (env->me_flags & MDB_NOTLS);
2177 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2182 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2183 txn->mt_u.reader = r;
2184 meta = env->me_metas[txn->mt_txnid & 1];
2190 txn->mt_txnid = ti->mti_txnid;
2191 meta = env->me_metas[txn->mt_txnid & 1];
2193 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2194 txn->mt_txnid = meta->mm_txnid;
2198 if (txn->mt_txnid == mdb_debug_start)
2201 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2202 txn->mt_u.dirty_list = env->me_dirty_list;
2203 txn->mt_u.dirty_list[0].mid = 0;
2204 txn->mt_free_pgs = env->me_free_pgs;
2205 txn->mt_free_pgs[0] = 0;
2206 txn->mt_spill_pgs = NULL;
2210 /* Copy the DB info and flags */
2211 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2213 /* Moved to here to avoid a data race in read TXNs */
2214 txn->mt_next_pgno = meta->mm_last_pg+1;
2216 for (i=2; i<txn->mt_numdbs; i++) {
2217 x = env->me_dbflags[i];
2218 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2219 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2221 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2223 if (env->me_maxpg < txn->mt_next_pgno) {
2224 mdb_txn_reset0(txn, "renew0-mapfail");
2226 txn->mt_u.reader->mr_pid = 0;
2227 txn->mt_u.reader = NULL;
2229 return MDB_MAP_RESIZED;
2236 mdb_txn_renew(MDB_txn *txn)
2240 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2243 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2244 DPUTS("environment had fatal error, must shutdown!");
2248 rc = mdb_txn_renew0(txn);
2249 if (rc == MDB_SUCCESS) {
2250 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2251 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2252 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2258 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2262 int rc, size, tsize = sizeof(MDB_txn);
2264 if (env->me_flags & MDB_FATAL_ERROR) {
2265 DPUTS("environment had fatal error, must shutdown!");
2268 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2271 /* Nested transactions: Max 1 child, write txns only, no writemap */
2272 if (parent->mt_child ||
2273 (flags & MDB_RDONLY) ||
2274 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2275 (env->me_flags & MDB_WRITEMAP))
2277 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2279 tsize = sizeof(MDB_ntxn);
2281 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2282 if (!(flags & MDB_RDONLY))
2283 size += env->me_maxdbs * sizeof(MDB_cursor *);
2285 if ((txn = calloc(1, size)) == NULL) {
2286 DPRINTF(("calloc: %s", strerror(ErrCode())));
2289 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2290 if (flags & MDB_RDONLY) {
2291 txn->mt_flags |= MDB_TXN_RDONLY;
2292 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2294 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2295 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2301 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2302 if (!txn->mt_u.dirty_list ||
2303 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2305 free(txn->mt_u.dirty_list);
2309 txn->mt_txnid = parent->mt_txnid;
2310 txn->mt_dirty_room = parent->mt_dirty_room;
2311 txn->mt_u.dirty_list[0].mid = 0;
2312 txn->mt_spill_pgs = NULL;
2313 txn->mt_next_pgno = parent->mt_next_pgno;
2314 parent->mt_child = txn;
2315 txn->mt_parent = parent;
2316 txn->mt_numdbs = parent->mt_numdbs;
2317 txn->mt_flags = parent->mt_flags;
2318 txn->mt_dbxs = parent->mt_dbxs;
2319 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2320 /* Copy parent's mt_dbflags, but clear DB_NEW */
2321 for (i=0; i<txn->mt_numdbs; i++)
2322 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2324 ntxn = (MDB_ntxn *)txn;
2325 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2326 if (env->me_pghead) {
2327 size = MDB_IDL_SIZEOF(env->me_pghead);
2328 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2330 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2335 rc = mdb_cursor_shadow(parent, txn);
2337 mdb_txn_reset0(txn, "beginchild-fail");
2339 rc = mdb_txn_renew0(txn);
2345 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2346 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2347 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2354 mdb_txn_env(MDB_txn *txn)
2356 if(!txn) return NULL;
2360 /** Export or close DBI handles opened in this txn. */
2362 mdb_dbis_update(MDB_txn *txn, int keep)
2365 MDB_dbi n = txn->mt_numdbs;
2366 MDB_env *env = txn->mt_env;
2367 unsigned char *tdbflags = txn->mt_dbflags;
2369 for (i = n; --i >= 2;) {
2370 if (tdbflags[i] & DB_NEW) {
2372 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2374 char *ptr = env->me_dbxs[i].md_name.mv_data;
2375 env->me_dbxs[i].md_name.mv_data = NULL;
2376 env->me_dbxs[i].md_name.mv_size = 0;
2377 env->me_dbflags[i] = 0;
2382 if (keep && env->me_numdbs < n)
2386 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2387 * May be called twice for readonly txns: First reset it, then abort.
2388 * @param[in] txn the transaction handle to reset
2389 * @param[in] act why the transaction is being reset
2392 mdb_txn_reset0(MDB_txn *txn, const char *act)
2394 MDB_env *env = txn->mt_env;
2396 /* Close any DBI handles opened in this txn */
2397 mdb_dbis_update(txn, 0);
2399 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2400 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2401 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2403 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2404 if (txn->mt_u.reader) {
2405 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2406 if (!(env->me_flags & MDB_NOTLS))
2407 txn->mt_u.reader = NULL; /* txn does not own reader */
2409 txn->mt_numdbs = 0; /* close nothing if called again */
2410 txn->mt_dbxs = NULL; /* mark txn as reset */
2412 mdb_cursors_close(txn, 0);
2414 if (!(env->me_flags & MDB_WRITEMAP)) {
2415 mdb_dlist_free(txn);
2417 mdb_midl_free(env->me_pghead);
2419 if (txn->mt_parent) {
2420 txn->mt_parent->mt_child = NULL;
2421 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2422 mdb_midl_free(txn->mt_free_pgs);
2423 mdb_midl_free(txn->mt_spill_pgs);
2424 free(txn->mt_u.dirty_list);
2428 if (mdb_midl_shrink(&txn->mt_free_pgs))
2429 env->me_free_pgs = txn->mt_free_pgs;
2430 env->me_pghead = NULL;
2434 /* The writer mutex was locked in mdb_txn_begin. */
2436 UNLOCK_MUTEX_W(env);
2441 mdb_txn_reset(MDB_txn *txn)
2446 /* This call is only valid for read-only txns */
2447 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2450 mdb_txn_reset0(txn, "reset");
2454 mdb_txn_abort(MDB_txn *txn)
2460 mdb_txn_abort(txn->mt_child);
2462 mdb_txn_reset0(txn, "abort");
2463 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2464 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2465 txn->mt_u.reader->mr_pid = 0;
2470 /** Save the freelist as of this transaction to the freeDB.
2471 * This changes the freelist. Keep trying until it stabilizes.
2474 mdb_freelist_save(MDB_txn *txn)
2476 /* env->me_pghead[] can grow and shrink during this call.
2477 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2478 * Page numbers cannot disappear from txn->mt_free_pgs[].
2481 MDB_env *env = txn->mt_env;
2482 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2483 txnid_t pglast = 0, head_id = 0;
2484 pgno_t freecnt = 0, *free_pgs, *mop;
2485 ssize_t head_room = 0, total_room = 0, mop_len;
2487 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2489 if (env->me_pghead) {
2490 /* Make sure first page of freeDB is touched and on freelist */
2491 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2492 if (rc && rc != MDB_NOTFOUND)
2497 /* Come back here after each Put() in case freelist changed */
2500 /* If using records from freeDB which we have not yet
2501 * deleted, delete them and any we reserved for me_pghead.
2503 while (pglast < env->me_pglast) {
2504 rc = mdb_cursor_first(&mc, &key, NULL);
2507 pglast = head_id = *(txnid_t *)key.mv_data;
2508 total_room = head_room = 0;
2509 assert(pglast <= env->me_pglast);
2510 rc = mdb_cursor_del(&mc, 0);
2515 /* Save the IDL of pages freed by this txn, to a single record */
2516 if (freecnt < txn->mt_free_pgs[0]) {
2518 /* Make sure last page of freeDB is touched and on freelist */
2519 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2520 if (rc && rc != MDB_NOTFOUND)
2523 free_pgs = txn->mt_free_pgs;
2524 /* Write to last page of freeDB */
2525 key.mv_size = sizeof(txn->mt_txnid);
2526 key.mv_data = &txn->mt_txnid;
2528 freecnt = free_pgs[0];
2529 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2530 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2533 /* Retry if mt_free_pgs[] grew during the Put() */
2534 free_pgs = txn->mt_free_pgs;
2535 } while (freecnt < free_pgs[0]);
2536 mdb_midl_sort(free_pgs);
2537 memcpy(data.mv_data, free_pgs, data.mv_size);
2540 unsigned int i = free_pgs[0];
2541 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2542 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2544 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2550 mop = env->me_pghead;
2551 mop_len = mop ? mop[0] : 0;
2553 /* Reserve records for me_pghead[]. Split it if multi-page,
2554 * to avoid searching freeDB for a page range. Use keys in
2555 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2557 if (total_room >= mop_len) {
2558 if (total_room == mop_len || --more < 0)
2560 } else if (head_room >= maxfree_1pg && head_id > 1) {
2561 /* Keep current record (overflow page), add a new one */
2565 /* (Re)write {key = head_id, IDL length = head_room} */
2566 total_room -= head_room;
2567 head_room = mop_len - total_room;
2568 if (head_room > maxfree_1pg && head_id > 1) {
2569 /* Overflow multi-page for part of me_pghead */
2570 head_room /= head_id; /* amortize page sizes */
2571 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2572 } else if (head_room < 0) {
2573 /* Rare case, not bothering to delete this record */
2576 key.mv_size = sizeof(head_id);
2577 key.mv_data = &head_id;
2578 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2579 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2582 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2583 total_room += head_room;
2586 /* Fill in the reserved me_pghead records */
2592 rc = mdb_cursor_first(&mc, &key, &data);
2593 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2594 unsigned flags = MDB_CURRENT;
2595 txnid_t id = *(txnid_t *)key.mv_data;
2596 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2599 assert(len >= 0 && id <= env->me_pglast);
2601 if (len > mop_len) {
2603 data.mv_size = (len + 1) * sizeof(MDB_ID);
2606 data.mv_data = mop -= len;
2609 rc = mdb_cursor_put(&mc, &key, &data, flags);
2611 if (rc || !(mop_len -= len))
2618 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2619 * @param[in] txn the transaction that's being committed
2620 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2621 * @return 0 on success, non-zero on failure.
2624 mdb_page_flush(MDB_txn *txn, int keep)
2626 MDB_env *env = txn->mt_env;
2627 MDB_ID2L dl = txn->mt_u.dirty_list;
2628 unsigned psize = env->me_psize, j;
2629 int i, pagecount = dl[0].mid, rc;
2630 size_t size = 0, pos = 0;
2632 MDB_page *dp = NULL;
2636 struct iovec iov[MDB_COMMIT_PAGES];
2637 ssize_t wpos = 0, wsize = 0, wres;
2638 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2644 if (env->me_flags & MDB_WRITEMAP) {
2645 /* Clear dirty flags */
2646 while (++i <= pagecount) {
2648 /* Don't flush this page yet */
2649 if (dp->mp_flags & P_KEEP) {
2650 dp->mp_flags ^= P_KEEP;
2654 dp->mp_flags &= ~P_DIRTY;
2659 /* Write the pages */
2661 if (++i <= pagecount) {
2663 /* Don't flush this page yet */
2664 if (dp->mp_flags & P_KEEP) {
2665 dp->mp_flags ^= P_KEEP;
2670 /* clear dirty flag */
2671 dp->mp_flags &= ~P_DIRTY;
2674 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2679 /* Windows actually supports scatter/gather I/O, but only on
2680 * unbuffered file handles. Since we're relying on the OS page
2681 * cache for all our data, that's self-defeating. So we just
2682 * write pages one at a time. We use the ov structure to set
2683 * the write offset, to at least save the overhead of a Seek
2686 DPRINTF(("committing page %"Z"u", pgno));
2687 memset(&ov, 0, sizeof(ov));
2688 ov.Offset = pos & 0xffffffff;
2689 ov.OffsetHigh = pos >> 16 >> 16;
2690 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2692 DPRINTF(("WriteFile: %d", rc));
2696 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2697 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2699 /* Write previous page(s) */
2700 #ifdef MDB_USE_PWRITEV
2701 wres = pwritev(env->me_fd, iov, n, wpos);
2704 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2706 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2708 DPRINTF(("lseek: %s", strerror(rc)));
2711 wres = writev(env->me_fd, iov, n);
2714 if (wres != wsize) {
2717 DPRINTF(("Write error: %s", strerror(rc)));
2719 rc = EIO; /* TODO: Use which error code? */
2720 DPUTS("short write, filesystem full?");
2731 DPRINTF(("committing page %"Z"u", pgno));
2732 next_pos = pos + size;
2733 iov[n].iov_len = size;
2734 iov[n].iov_base = (char *)dp;
2740 for (i = keep; ++i <= pagecount; ) {
2742 /* This is a page we skipped above */
2745 dl[j].mid = dp->mp_pgno;
2748 mdb_dpage_free(env, dp);
2753 txn->mt_dirty_room += i - j;
2759 mdb_txn_commit(MDB_txn *txn)
2765 assert(txn != NULL);
2766 assert(txn->mt_env != NULL);
2768 if (txn->mt_child) {
2769 rc = mdb_txn_commit(txn->mt_child);
2770 txn->mt_child = NULL;
2777 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2778 mdb_dbis_update(txn, 1);
2779 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2784 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2785 DPUTS("error flag is set, can't commit");
2787 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2792 if (txn->mt_parent) {
2793 MDB_txn *parent = txn->mt_parent;
2796 unsigned x, y, len, ps_len;
2798 /* Append our free list to parent's */
2799 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2802 mdb_midl_free(txn->mt_free_pgs);
2803 /* Failures after this must either undo the changes
2804 * to the parent or set MDB_TXN_ERROR in the parent.
2807 parent->mt_next_pgno = txn->mt_next_pgno;
2808 parent->mt_flags = txn->mt_flags;
2810 /* Merge our cursors into parent's and close them */
2811 mdb_cursors_close(txn, 1);
2813 /* Update parent's DB table. */
2814 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2815 parent->mt_numdbs = txn->mt_numdbs;
2816 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2817 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2818 for (i=2; i<txn->mt_numdbs; i++) {
2819 /* preserve parent's DB_NEW status */
2820 x = parent->mt_dbflags[i] & DB_NEW;
2821 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2824 dst = parent->mt_u.dirty_list;
2825 src = txn->mt_u.dirty_list;
2826 /* Remove anything in our dirty list from parent's spill list */
2827 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2829 pspill[0] = (pgno_t)-1;
2830 /* Mark our dirty pages as deleted in parent spill list */
2831 for (i=0, len=src[0].mid; ++i <= len; ) {
2832 MDB_ID pn = src[i].mid << 1;
2833 while (pn > pspill[x])
2835 if (pn == pspill[x]) {
2840 /* Squash deleted pagenums if we deleted any */
2841 for (x=y; ++x <= ps_len; )
2842 if (!(pspill[x] & 1))
2843 pspill[++y] = pspill[x];
2847 /* Find len = length of merging our dirty list with parent's */
2849 dst[0].mid = 0; /* simplify loops */
2850 if (parent->mt_parent) {
2851 len = x + src[0].mid;
2852 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2853 for (i = x; y && i; y--) {
2854 pgno_t yp = src[y].mid;
2855 while (yp < dst[i].mid)
2857 if (yp == dst[i].mid) {
2862 } else { /* Simplify the above for single-ancestor case */
2863 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2865 /* Merge our dirty list with parent's */
2867 for (i = len; y; dst[i--] = src[y--]) {
2868 pgno_t yp = src[y].mid;
2869 while (yp < dst[x].mid)
2870 dst[i--] = dst[x--];
2871 if (yp == dst[x].mid)
2872 free(dst[x--].mptr);
2876 free(txn->mt_u.dirty_list);
2877 parent->mt_dirty_room = txn->mt_dirty_room;
2878 if (txn->mt_spill_pgs) {
2879 if (parent->mt_spill_pgs) {
2880 /* TODO: Prevent failure here, so parent does not fail */
2881 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2883 parent->mt_flags |= MDB_TXN_ERROR;
2884 mdb_midl_free(txn->mt_spill_pgs);
2885 mdb_midl_sort(parent->mt_spill_pgs);
2887 parent->mt_spill_pgs = txn->mt_spill_pgs;
2891 parent->mt_child = NULL;
2892 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2897 if (txn != env->me_txn) {
2898 DPUTS("attempt to commit unknown transaction");
2903 mdb_cursors_close(txn, 0);
2905 if (!txn->mt_u.dirty_list[0].mid &&
2906 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2909 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2910 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2912 /* Update DB root pointers */
2913 if (txn->mt_numdbs > 2) {
2917 data.mv_size = sizeof(MDB_db);
2919 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2920 for (i = 2; i < txn->mt_numdbs; i++) {
2921 if (txn->mt_dbflags[i] & DB_DIRTY) {
2922 data.mv_data = &txn->mt_dbs[i];
2923 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2930 rc = mdb_freelist_save(txn);
2934 mdb_midl_free(env->me_pghead);
2935 env->me_pghead = NULL;
2936 if (mdb_midl_shrink(&txn->mt_free_pgs))
2937 env->me_free_pgs = txn->mt_free_pgs;
2943 if ((rc = mdb_page_flush(txn, 0)) ||
2944 (rc = mdb_env_sync(env, 0)) ||
2945 (rc = mdb_env_write_meta(txn)))
2951 mdb_dbis_update(txn, 1);
2954 UNLOCK_MUTEX_W(env);
2964 /** Read the environment parameters of a DB environment before
2965 * mapping it into memory.
2966 * @param[in] env the environment handle
2967 * @param[out] meta address of where to store the meta information
2968 * @return 0 on success, non-zero on failure.
2971 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2978 /* We don't know the page size yet, so use a minimum value.
2979 * Read both meta pages so we can use the latest one.
2982 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2986 memset(&ov, 0, sizeof(ov));
2988 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2989 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2992 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2994 if (rc != MDB_PAGESIZE) {
2995 if (rc == 0 && off == 0)
2997 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2998 DPRINTF(("read: %s", mdb_strerror(rc)));
3002 p = (MDB_page *)&pbuf;
3004 if (!F_ISSET(p->mp_flags, P_META)) {
3005 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3010 if (m->mm_magic != MDB_MAGIC) {
3011 DPUTS("meta has invalid magic");
3015 if (m->mm_version != MDB_DATA_VERSION) {
3016 DPRINTF(("database is version %u, expected version %u",
3017 m->mm_version, MDB_DATA_VERSION));
3018 return MDB_VERSION_MISMATCH;
3021 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3027 /** Write the environment parameters of a freshly created DB environment.
3028 * @param[in] env the environment handle
3029 * @param[out] meta address of where to store the meta information
3030 * @return 0 on success, non-zero on failure.
3033 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3041 memset(&ov, 0, sizeof(ov));
3042 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3044 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3047 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3048 len = pwrite(fd, ptr, size, pos); \
3049 rc = (len >= 0); } while(0)
3052 DPUTS("writing new meta page");
3054 psize = env->me_psize;
3056 meta->mm_magic = MDB_MAGIC;
3057 meta->mm_version = MDB_DATA_VERSION;
3058 meta->mm_mapsize = env->me_mapsize;
3059 meta->mm_psize = psize;
3060 meta->mm_last_pg = 1;
3061 meta->mm_flags = env->me_flags & 0xffff;
3062 meta->mm_flags |= MDB_INTEGERKEY;
3063 meta->mm_dbs[0].md_root = P_INVALID;
3064 meta->mm_dbs[1].md_root = P_INVALID;
3066 p = calloc(2, psize);
3068 p->mp_flags = P_META;
3069 *(MDB_meta *)METADATA(p) = *meta;
3071 q = (MDB_page *)((char *)p + psize);
3073 q->mp_flags = P_META;
3074 *(MDB_meta *)METADATA(q) = *meta;
3076 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3079 else if ((unsigned) len == psize * 2)
3087 /** Update the environment info to commit a transaction.
3088 * @param[in] txn the transaction that's being committed
3089 * @return 0 on success, non-zero on failure.
3092 mdb_env_write_meta(MDB_txn *txn)
3095 MDB_meta meta, metab, *mp;
3097 int rc, len, toggle;
3106 assert(txn != NULL);
3107 assert(txn->mt_env != NULL);
3109 toggle = txn->mt_txnid & 1;
3110 DPRINTF(("writing meta page %d for root page %"Z"u",
3111 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3114 mp = env->me_metas[toggle];
3116 if (env->me_flags & MDB_WRITEMAP) {
3117 /* Persist any increases of mapsize config */
3118 if (env->me_mapsize > mp->mm_mapsize)
3119 mp->mm_mapsize = env->me_mapsize;
3120 mp->mm_dbs[0] = txn->mt_dbs[0];
3121 mp->mm_dbs[1] = txn->mt_dbs[1];
3122 mp->mm_last_pg = txn->mt_next_pgno - 1;
3123 mp->mm_txnid = txn->mt_txnid;
3124 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3125 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3128 ptr += env->me_psize;
3129 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
3136 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3137 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3139 ptr = (char *)&meta;
3140 if (env->me_mapsize > mp->mm_mapsize) {
3141 /* Persist any increases of mapsize config */
3142 meta.mm_mapsize = env->me_mapsize;
3143 off = offsetof(MDB_meta, mm_mapsize);
3145 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3147 len = sizeof(MDB_meta) - off;
3150 meta.mm_dbs[0] = txn->mt_dbs[0];
3151 meta.mm_dbs[1] = txn->mt_dbs[1];
3152 meta.mm_last_pg = txn->mt_next_pgno - 1;
3153 meta.mm_txnid = txn->mt_txnid;
3156 off += env->me_psize;
3159 /* Write to the SYNC fd */
3160 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3161 env->me_fd : env->me_mfd;
3164 memset(&ov, 0, sizeof(ov));
3166 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3170 rc = pwrite(mfd, ptr, len, off);
3173 rc = rc < 0 ? ErrCode() : EIO;
3174 DPUTS("write failed, disk error?");
3175 /* On a failure, the pagecache still contains the new data.
3176 * Write some old data back, to prevent it from being used.
3177 * Use the non-SYNC fd; we know it will fail anyway.
3179 meta.mm_last_pg = metab.mm_last_pg;
3180 meta.mm_txnid = metab.mm_txnid;
3182 memset(&ov, 0, sizeof(ov));
3184 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3186 r2 = pwrite(env->me_fd, ptr, len, off);
3187 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3190 env->me_flags |= MDB_FATAL_ERROR;
3194 /* Memory ordering issues are irrelevant; since the entire writer
3195 * is wrapped by wmutex, all of these changes will become visible
3196 * after the wmutex is unlocked. Since the DB is multi-version,
3197 * readers will get consistent data regardless of how fresh or
3198 * how stale their view of these values is.
3201 env->me_txns->mti_txnid = txn->mt_txnid;
3206 /** Check both meta pages to see which one is newer.
3207 * @param[in] env the environment handle
3208 * @return meta toggle (0 or 1).
3211 mdb_env_pick_meta(const MDB_env *env)
3213 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3217 mdb_env_create(MDB_env **env)
3221 e = calloc(1, sizeof(MDB_env));
3225 e->me_maxreaders = DEFAULT_READERS;
3226 e->me_maxdbs = e->me_numdbs = 2;
3227 e->me_fd = INVALID_HANDLE_VALUE;
3228 e->me_lfd = INVALID_HANDLE_VALUE;
3229 e->me_mfd = INVALID_HANDLE_VALUE;
3230 #ifdef MDB_USE_POSIX_SEM
3231 e->me_rmutex = SEM_FAILED;
3232 e->me_wmutex = SEM_FAILED;
3234 e->me_pid = getpid();
3235 VGMEMP_CREATE(e,0,0);
3241 mdb_env_map(MDB_env *env, void *addr, int newsize)
3244 unsigned int flags = env->me_flags;
3248 LONG sizelo, sizehi;
3249 sizelo = env->me_mapsize & 0xffffffff;
3250 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3252 /* Windows won't create mappings for zero length files.
3253 * Just allocate the maxsize right now.
3256 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3257 || !SetEndOfFile(env->me_fd)
3258 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3261 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3262 PAGE_READWRITE : PAGE_READONLY,
3263 sizehi, sizelo, NULL);
3266 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3267 FILE_MAP_WRITE : FILE_MAP_READ,
3268 0, 0, env->me_mapsize, addr);
3269 rc = env->me_map ? 0 : ErrCode();
3274 int prot = PROT_READ;
3275 if (flags & MDB_WRITEMAP) {
3277 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3280 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3282 if (env->me_map == MAP_FAILED) {
3286 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3288 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3290 #ifdef POSIX_MADV_RANDOM
3291 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3292 #endif /* POSIX_MADV_RANDOM */
3293 #endif /* MADV_RANDOM */
3296 /* Can happen because the address argument to mmap() is just a
3297 * hint. mmap() can pick another, e.g. if the range is in use.
3298 * The MAP_FIXED flag would prevent that, but then mmap could
3299 * instead unmap existing pages to make room for the new map.
3301 if (addr && env->me_map != addr)
3302 return EBUSY; /* TODO: Make a new MDB_* error code? */
3304 p = (MDB_page *)env->me_map;
3305 env->me_metas[0] = METADATA(p);
3306 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3312 mdb_env_set_mapsize(MDB_env *env, size_t size)
3314 /* If env is already open, caller is responsible for making
3315 * sure there are no active txns.
3323 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3324 else if (size < env->me_mapsize) {
3325 /* If the configured size is smaller, make sure it's
3326 * still big enough. Silently round up to minimum if not.
3328 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3332 munmap(env->me_map, env->me_mapsize);
3333 env->me_mapsize = size;
3334 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3335 rc = mdb_env_map(env, old, 1);
3339 env->me_mapsize = size;
3341 env->me_maxpg = env->me_mapsize / env->me_psize;
3346 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3350 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3355 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3357 if (env->me_map || readers < 1)
3359 env->me_maxreaders = readers;
3364 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3366 if (!env || !readers)
3368 *readers = env->me_maxreaders;
3372 /** Further setup required for opening an MDB environment
3375 mdb_env_open2(MDB_env *env)
3377 unsigned int flags = env->me_flags;
3378 int i, newenv = 0, rc;
3382 /* See if we should use QueryLimited */
3384 if ((rc & 0xff) > 5)
3385 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3387 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3390 memset(&meta, 0, sizeof(meta));
3392 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3395 DPUTS("new mdbenv");
3397 GET_PAGESIZE(env->me_psize);
3399 env->me_psize = meta.mm_psize;
3402 /* Was a mapsize configured? */
3403 if (!env->me_mapsize) {
3404 /* If this is a new environment, take the default,
3405 * else use the size recorded in the existing env.
3407 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3408 } else if (env->me_mapsize < meta.mm_mapsize) {
3409 /* If the configured size is smaller, make sure it's
3410 * still big enough. Silently round up to minimum if not.
3412 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3413 if (env->me_mapsize < minsize)
3414 env->me_mapsize = minsize;
3417 rc = mdb_env_map(env, meta.mm_address, newenv);
3422 if (flags & MDB_FIXEDMAP)
3423 meta.mm_address = env->me_map;
3424 i = mdb_env_init_meta(env, &meta);
3425 if (i != MDB_SUCCESS) {
3429 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3430 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3432 env->me_maxpg = env->me_mapsize / env->me_psize;
3435 int toggle = mdb_env_pick_meta(env);
3436 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3438 DPRINTF(("opened database version %u, pagesize %u",
3439 env->me_metas[0]->mm_version, env->me_psize));
3440 DPRINTF(("using meta page %d", toggle));
3441 DPRINTF(("depth: %u", db->md_depth));
3442 DPRINTF(("entries: %"Z"u", db->md_entries));
3443 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3444 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3445 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3446 DPRINTF(("root: %"Z"u", db->md_root));
3454 /** Release a reader thread's slot in the reader lock table.
3455 * This function is called automatically when a thread exits.
3456 * @param[in] ptr This points to the slot in the reader lock table.
3459 mdb_env_reader_dest(void *ptr)
3461 MDB_reader *reader = ptr;
3467 /** Junk for arranging thread-specific callbacks on Windows. This is
3468 * necessarily platform and compiler-specific. Windows supports up
3469 * to 1088 keys. Let's assume nobody opens more than 64 environments
3470 * in a single process, for now. They can override this if needed.
3472 #ifndef MAX_TLS_KEYS
3473 #define MAX_TLS_KEYS 64
3475 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3476 static int mdb_tls_nkeys;
3478 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3482 case DLL_PROCESS_ATTACH: break;
3483 case DLL_THREAD_ATTACH: break;
3484 case DLL_THREAD_DETACH:
3485 for (i=0; i<mdb_tls_nkeys; i++) {
3486 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3487 mdb_env_reader_dest(r);
3490 case DLL_PROCESS_DETACH: break;
3495 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3497 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3501 /* Force some symbol references.
3502 * _tls_used forces the linker to create the TLS directory if not already done
3503 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3505 #pragma comment(linker, "/INCLUDE:_tls_used")
3506 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3507 #pragma const_seg(".CRT$XLB")
3508 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3509 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3512 #pragma comment(linker, "/INCLUDE:__tls_used")
3513 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3514 #pragma data_seg(".CRT$XLB")
3515 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3517 #endif /* WIN 32/64 */
3518 #endif /* !__GNUC__ */
3521 /** Downgrade the exclusive lock on the region back to shared */
3523 mdb_env_share_locks(MDB_env *env, int *excl)
3525 int rc = 0, toggle = mdb_env_pick_meta(env);
3527 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3532 /* First acquire a shared lock. The Unlock will
3533 * then release the existing exclusive lock.
3535 memset(&ov, 0, sizeof(ov));
3536 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3539 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3545 struct flock lock_info;
3546 /* The shared lock replaces the existing lock */
3547 memset((void *)&lock_info, 0, sizeof(lock_info));
3548 lock_info.l_type = F_RDLCK;
3549 lock_info.l_whence = SEEK_SET;
3550 lock_info.l_start = 0;
3551 lock_info.l_len = 1;
3552 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3553 (rc = ErrCode()) == EINTR) ;
3554 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3561 /** Try to get exlusive lock, otherwise shared.
3562 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3565 mdb_env_excl_lock(MDB_env *env, int *excl)
3569 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3573 memset(&ov, 0, sizeof(ov));
3574 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3581 struct flock lock_info;
3582 memset((void *)&lock_info, 0, sizeof(lock_info));
3583 lock_info.l_type = F_WRLCK;
3584 lock_info.l_whence = SEEK_SET;
3585 lock_info.l_start = 0;
3586 lock_info.l_len = 1;
3587 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3588 (rc = ErrCode()) == EINTR) ;
3592 # ifdef MDB_USE_POSIX_SEM
3593 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3596 lock_info.l_type = F_RDLCK;
3597 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3598 (rc = ErrCode()) == EINTR) ;
3608 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3610 * @(#) $Revision: 5.1 $
3611 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3612 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3614 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3618 * Please do not copyright this code. This code is in the public domain.
3620 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3621 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3622 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3623 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3624 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3625 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3626 * PERFORMANCE OF THIS SOFTWARE.
3629 * chongo <Landon Curt Noll> /\oo/\
3630 * http://www.isthe.com/chongo/
3632 * Share and Enjoy! :-)
3635 typedef unsigned long long mdb_hash_t;
3636 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3638 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3639 * @param[in] val value to hash
3640 * @param[in] hval initial value for hash
3641 * @return 64 bit hash
3643 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3644 * hval arg on the first call.
3647 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3649 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3650 unsigned char *end = s + val->mv_size;
3652 * FNV-1a hash each octet of the string
3655 /* xor the bottom with the current octet */
3656 hval ^= (mdb_hash_t)*s++;
3658 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3659 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3660 (hval << 7) + (hval << 8) + (hval << 40);
3662 /* return our new hash value */
3666 /** Hash the string and output the encoded hash.
3667 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3668 * very short name limits. We don't care about the encoding being reversible,
3669 * we just want to preserve as many bits of the input as possible in a
3670 * small printable string.
3671 * @param[in] str string to hash
3672 * @param[out] encbuf an array of 11 chars to hold the hash
3674 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3677 mdb_pack85(unsigned long l, char *out)
3681 for (i=0; i<5; i++) {
3682 *out++ = mdb_a85[l % 85];
3688 mdb_hash_enc(MDB_val *val, char *encbuf)
3690 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3692 mdb_pack85(h, encbuf);
3693 mdb_pack85(h>>32, encbuf+5);
3698 /** Open and/or initialize the lock region for the environment.
3699 * @param[in] env The MDB environment.
3700 * @param[in] lpath The pathname of the file used for the lock region.
3701 * @param[in] mode The Unix permissions for the file, if we create it.
3702 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3703 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3704 * @return 0 on success, non-zero on failure.
3707 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3710 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3712 # define MDB_ERRCODE_ROFS EROFS
3713 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3714 # define MDB_CLOEXEC O_CLOEXEC
3717 # define MDB_CLOEXEC 0
3724 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3725 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3726 FILE_ATTRIBUTE_NORMAL, NULL);
3728 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3730 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3732 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3737 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3738 /* Lose record locks when exec*() */
3739 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3740 fcntl(env->me_lfd, F_SETFD, fdflags);
3743 if (!(env->me_flags & MDB_NOTLS)) {
3744 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3747 env->me_flags |= MDB_ENV_TXKEY;
3749 /* Windows TLS callbacks need help finding their TLS info. */
3750 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3754 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3758 /* Try to get exclusive lock. If we succeed, then
3759 * nobody is using the lock region and we should initialize it.
3761 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3764 size = GetFileSize(env->me_lfd, NULL);
3766 size = lseek(env->me_lfd, 0, SEEK_END);
3767 if (size == -1) goto fail_errno;
3769 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3770 if (size < rsize && *excl > 0) {
3772 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3773 || !SetEndOfFile(env->me_lfd))
3776 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3780 size = rsize - sizeof(MDB_txninfo);
3781 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3786 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3788 if (!mh) goto fail_errno;
3789 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3791 if (!env->me_txns) goto fail_errno;
3793 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3795 if (m == MAP_FAILED) goto fail_errno;
3801 BY_HANDLE_FILE_INFORMATION stbuf;
3810 if (!mdb_sec_inited) {
3811 InitializeSecurityDescriptor(&mdb_null_sd,
3812 SECURITY_DESCRIPTOR_REVISION);
3813 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3814 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3815 mdb_all_sa.bInheritHandle = FALSE;
3816 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3819 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3820 idbuf.volume = stbuf.dwVolumeSerialNumber;
3821 idbuf.nhigh = stbuf.nFileIndexHigh;
3822 idbuf.nlow = stbuf.nFileIndexLow;
3823 val.mv_data = &idbuf;
3824 val.mv_size = sizeof(idbuf);
3825 mdb_hash_enc(&val, encbuf);
3826 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3827 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3828 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3829 if (!env->me_rmutex) goto fail_errno;
3830 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3831 if (!env->me_wmutex) goto fail_errno;
3832 #elif defined(MDB_USE_POSIX_SEM)
3841 #if defined(__NetBSD__)
3842 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3844 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3845 idbuf.dev = stbuf.st_dev;
3846 idbuf.ino = stbuf.st_ino;
3847 val.mv_data = &idbuf;
3848 val.mv_size = sizeof(idbuf);
3849 mdb_hash_enc(&val, encbuf);
3850 #ifdef MDB_SHORT_SEMNAMES
3851 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3853 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3854 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3855 /* Clean up after a previous run, if needed: Try to
3856 * remove both semaphores before doing anything else.
3858 sem_unlink(env->me_txns->mti_rmname);
3859 sem_unlink(env->me_txns->mti_wmname);
3860 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3861 O_CREAT|O_EXCL, mode, 1);
3862 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3863 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3864 O_CREAT|O_EXCL, mode, 1);
3865 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3866 #else /* MDB_USE_POSIX_SEM */
3867 pthread_mutexattr_t mattr;
3869 if ((rc = pthread_mutexattr_init(&mattr))
3870 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3871 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3872 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3874 pthread_mutexattr_destroy(&mattr);
3875 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3877 env->me_txns->mti_magic = MDB_MAGIC;
3878 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3879 env->me_txns->mti_txnid = 0;
3880 env->me_txns->mti_numreaders = 0;
3883 if (env->me_txns->mti_magic != MDB_MAGIC) {
3884 DPUTS("lock region has invalid magic");
3888 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3889 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3890 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3891 rc = MDB_VERSION_MISMATCH;
3895 if (rc && rc != EACCES && rc != EAGAIN) {
3899 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3900 if (!env->me_rmutex) goto fail_errno;
3901 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3902 if (!env->me_wmutex) goto fail_errno;
3903 #elif defined(MDB_USE_POSIX_SEM)
3904 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3905 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3906 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3907 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3918 /** The name of the lock file in the DB environment */
3919 #define LOCKNAME "/lock.mdb"
3920 /** The name of the data file in the DB environment */
3921 #define DATANAME "/data.mdb"
3922 /** The suffix of the lock file when no subdir is used */
3923 #define LOCKSUFF "-lock"
3924 /** Only a subset of the @ref mdb_env flags can be changed
3925 * at runtime. Changing other flags requires closing the
3926 * environment and re-opening it with the new flags.
3928 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3929 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK)
3932 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3934 int oflags, rc, len, excl = -1;
3935 char *lpath, *dpath;
3937 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3941 if (flags & MDB_NOSUBDIR) {
3942 rc = len + sizeof(LOCKSUFF) + len + 1;
3944 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3949 if (flags & MDB_NOSUBDIR) {
3950 dpath = lpath + len + sizeof(LOCKSUFF);
3951 sprintf(lpath, "%s" LOCKSUFF, path);
3952 strcpy(dpath, path);
3954 dpath = lpath + len + sizeof(LOCKNAME);
3955 sprintf(lpath, "%s" LOCKNAME, path);
3956 sprintf(dpath, "%s" DATANAME, path);
3960 flags |= env->me_flags;
3961 if (flags & MDB_RDONLY) {
3962 /* silently ignore WRITEMAP when we're only getting read access */
3963 flags &= ~MDB_WRITEMAP;
3965 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3966 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3969 env->me_flags = flags |= MDB_ENV_ACTIVE;
3973 env->me_path = strdup(path);
3974 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3975 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3976 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3981 /* For RDONLY, get lockfile after we know datafile exists */
3982 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
3983 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3989 if (F_ISSET(flags, MDB_RDONLY)) {
3990 oflags = GENERIC_READ;
3991 len = OPEN_EXISTING;
3993 oflags = GENERIC_READ|GENERIC_WRITE;
3996 mode = FILE_ATTRIBUTE_NORMAL;
3997 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3998 NULL, len, mode, NULL);
4000 if (F_ISSET(flags, MDB_RDONLY))
4003 oflags = O_RDWR | O_CREAT;
4005 env->me_fd = open(dpath, oflags, mode);
4007 if (env->me_fd == INVALID_HANDLE_VALUE) {
4012 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4013 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4018 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4019 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4020 env->me_mfd = env->me_fd;
4022 /* Synchronous fd for meta writes. Needed even with
4023 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4026 len = OPEN_EXISTING;
4027 env->me_mfd = CreateFile(dpath, oflags,
4028 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4029 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4032 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4034 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4039 DPRINTF(("opened dbenv %p", (void *) env));
4041 rc = mdb_env_share_locks(env, &excl);
4047 mdb_env_close0(env, excl);
4053 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4055 mdb_env_close0(MDB_env *env, int excl)
4059 if (!(env->me_flags & MDB_ENV_ACTIVE))
4062 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4063 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4064 free(env->me_dbxs[i].md_name.mv_data);
4066 free(env->me_dbflags);
4069 free(env->me_dirty_list);
4070 mdb_midl_free(env->me_free_pgs);
4072 if (env->me_flags & MDB_ENV_TXKEY) {
4073 pthread_key_delete(env->me_txkey);
4075 /* Delete our key from the global list */
4076 for (i=0; i<mdb_tls_nkeys; i++)
4077 if (mdb_tls_keys[i] == env->me_txkey) {
4078 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4086 munmap(env->me_map, env->me_mapsize);
4088 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4089 (void) close(env->me_mfd);
4090 if (env->me_fd != INVALID_HANDLE_VALUE)
4091 (void) close(env->me_fd);
4093 pid_t pid = env->me_pid;
4094 /* Clearing readers is done in this function because
4095 * me_txkey with its destructor must be disabled first.
4097 for (i = env->me_numreaders; --i >= 0; )
4098 if (env->me_txns->mti_readers[i].mr_pid == pid)
4099 env->me_txns->mti_readers[i].mr_pid = 0;
4101 if (env->me_rmutex) {
4102 CloseHandle(env->me_rmutex);
4103 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4105 /* Windows automatically destroys the mutexes when
4106 * the last handle closes.
4108 #elif defined(MDB_USE_POSIX_SEM)
4109 if (env->me_rmutex != SEM_FAILED) {
4110 sem_close(env->me_rmutex);
4111 if (env->me_wmutex != SEM_FAILED)
4112 sem_close(env->me_wmutex);
4113 /* If we have the filelock: If we are the
4114 * only remaining user, clean up semaphores.
4117 mdb_env_excl_lock(env, &excl);
4119 sem_unlink(env->me_txns->mti_rmname);
4120 sem_unlink(env->me_txns->mti_wmname);
4124 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4126 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4129 /* Unlock the lockfile. Windows would have unlocked it
4130 * after closing anyway, but not necessarily at once.
4132 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4135 (void) close(env->me_lfd);
4138 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4142 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4144 MDB_txn *txn = NULL;
4150 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4154 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4157 /* Do the lock/unlock of the reader mutex before starting the
4158 * write txn. Otherwise other read txns could block writers.
4160 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4165 /* We must start the actual read txn after blocking writers */
4166 mdb_txn_reset0(txn, "reset-stage1");
4168 /* Temporarily block writers until we snapshot the meta pages */
4171 rc = mdb_txn_renew0(txn);
4173 UNLOCK_MUTEX_W(env);
4178 wsize = env->me_psize * 2;
4182 DO_WRITE(rc, fd, ptr, w2, len);
4186 } else if (len > 0) {
4192 /* Non-blocking or async handles are not supported */
4198 UNLOCK_MUTEX_W(env);
4203 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4205 if (wsize > MAX_WRITE)
4209 DO_WRITE(rc, fd, ptr, w2, len);
4213 } else if (len > 0) {
4230 mdb_env_copy(MDB_env *env, const char *path)
4234 HANDLE newfd = INVALID_HANDLE_VALUE;
4236 if (env->me_flags & MDB_NOSUBDIR) {
4237 lpath = (char *)path;
4240 len += sizeof(DATANAME);
4241 lpath = malloc(len);
4244 sprintf(lpath, "%s" DATANAME, path);
4247 /* The destination path must exist, but the destination file must not.
4248 * We don't want the OS to cache the writes, since the source data is
4249 * already in the OS cache.
4252 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4253 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4255 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4257 if (newfd == INVALID_HANDLE_VALUE) {
4263 /* Set O_DIRECT if the file system supports it */
4264 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4265 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4267 #ifdef F_NOCACHE /* __APPLE__ */
4268 rc = fcntl(newfd, F_NOCACHE, 1);
4275 rc = mdb_env_copyfd(env, newfd);
4278 if (!(env->me_flags & MDB_NOSUBDIR))
4280 if (newfd != INVALID_HANDLE_VALUE)
4281 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4288 mdb_env_close(MDB_env *env)
4295 VGMEMP_DESTROY(env);
4296 while ((dp = env->me_dpages) != NULL) {
4297 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4298 env->me_dpages = dp->mp_next;
4302 mdb_env_close0(env, 0);
4306 /** Compare two items pointing at aligned size_t's */
4308 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4310 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4311 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4314 /** Compare two items pointing at aligned unsigned int's */
4316 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4318 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4319 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4322 /** Compare two items pointing at unsigned ints of unknown alignment.
4323 * Nodes and keys are guaranteed to be 2-byte aligned.
4326 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4328 #if BYTE_ORDER == LITTLE_ENDIAN
4329 unsigned short *u, *c;
4332 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4333 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4336 } while(!x && u > (unsigned short *)a->mv_data);
4339 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4343 /** Compare two items lexically */
4345 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4352 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4358 diff = memcmp(a->mv_data, b->mv_data, len);
4359 return diff ? diff : len_diff<0 ? -1 : len_diff;
4362 /** Compare two items in reverse byte order */
4364 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4366 const unsigned char *p1, *p2, *p1_lim;
4370 p1_lim = (const unsigned char *)a->mv_data;
4371 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4372 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4374 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4380 while (p1 > p1_lim) {
4381 diff = *--p1 - *--p2;
4385 return len_diff<0 ? -1 : len_diff;
4388 /** Search for key within a page, using binary search.
4389 * Returns the smallest entry larger or equal to the key.
4390 * If exactp is non-null, stores whether the found entry was an exact match
4391 * in *exactp (1 or 0).
4392 * Updates the cursor index with the index of the found entry.
4393 * If no entry larger or equal to the key is found, returns NULL.
4396 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4398 unsigned int i = 0, nkeys;
4401 MDB_page *mp = mc->mc_pg[mc->mc_top];
4402 MDB_node *node = NULL;
4407 nkeys = NUMKEYS(mp);
4412 COPY_PGNO(pgno, mp->mp_pgno);
4413 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4414 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4421 low = IS_LEAF(mp) ? 0 : 1;
4423 cmp = mc->mc_dbx->md_cmp;
4425 /* Branch pages have no data, so if using integer keys,
4426 * alignment is guaranteed. Use faster mdb_cmp_int.
4428 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4429 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4436 nodekey.mv_size = mc->mc_db->md_pad;
4437 node = NODEPTR(mp, 0); /* fake */
4438 while (low <= high) {
4439 i = (low + high) >> 1;
4440 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4441 rc = cmp(key, &nodekey);
4442 DPRINTF(("found leaf index %u [%s], rc = %i",
4443 i, DKEY(&nodekey), rc));
4452 while (low <= high) {
4453 i = (low + high) >> 1;
4455 node = NODEPTR(mp, i);
4456 nodekey.mv_size = NODEKSZ(node);
4457 nodekey.mv_data = NODEKEY(node);
4459 rc = cmp(key, &nodekey);
4462 DPRINTF(("found leaf index %u [%s], rc = %i",
4463 i, DKEY(&nodekey), rc));
4465 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4466 i, DKEY(&nodekey), NODEPGNO(node), rc));
4477 if (rc > 0) { /* Found entry is less than the key. */
4478 i++; /* Skip to get the smallest entry larger than key. */
4480 node = NODEPTR(mp, i);
4483 *exactp = (rc == 0);
4484 /* store the key index */
4485 mc->mc_ki[mc->mc_top] = i;
4487 /* There is no entry larger or equal to the key. */
4490 /* nodeptr is fake for LEAF2 */
4496 mdb_cursor_adjust(MDB_cursor *mc, func)
4500 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4501 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4508 /** Pop a page off the top of the cursor's stack. */
4510 mdb_cursor_pop(MDB_cursor *mc)
4514 MDB_page *top = mc->mc_pg[mc->mc_top];
4520 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4521 DDBI(mc), (void *) mc));
4525 /** Push a page onto the top of the cursor's stack. */
4527 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4529 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4530 DDBI(mc), (void *) mc));
4532 if (mc->mc_snum >= CURSOR_STACK) {
4533 assert(mc->mc_snum < CURSOR_STACK);
4534 return MDB_CURSOR_FULL;
4537 mc->mc_top = mc->mc_snum++;
4538 mc->mc_pg[mc->mc_top] = mp;
4539 mc->mc_ki[mc->mc_top] = 0;
4544 /** Find the address of the page corresponding to a given page number.
4545 * @param[in] txn the transaction for this access.
4546 * @param[in] pgno the page number for the page to retrieve.
4547 * @param[out] ret address of a pointer where the page's address will be stored.
4548 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4549 * @return 0 on success, non-zero on failure.
4552 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4554 MDB_env *env = txn->mt_env;
4558 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4562 MDB_ID2L dl = tx2->mt_u.dirty_list;
4564 /* Spilled pages were dirtied in this txn and flushed
4565 * because the dirty list got full. Bring this page
4566 * back in from the map (but don't unspill it here,
4567 * leave that unless page_touch happens again).
4569 if (tx2->mt_spill_pgs) {
4570 MDB_ID pn = pgno << 1;
4571 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4572 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4573 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4578 unsigned x = mdb_mid2l_search(dl, pgno);
4579 if (x <= dl[0].mid && dl[x].mid == pgno) {
4585 } while ((tx2 = tx2->mt_parent) != NULL);
4588 if (pgno < txn->mt_next_pgno) {
4590 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4592 DPRINTF(("page %"Z"u not found", pgno));
4594 return MDB_PAGE_NOTFOUND;
4604 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4605 * The cursor is at the root page, set up the rest of it.
4608 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4610 MDB_page *mp = mc->mc_pg[mc->mc_top];
4614 while (IS_BRANCH(mp)) {
4618 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4619 assert(NUMKEYS(mp) > 1);
4620 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4622 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4624 if (flags & MDB_PS_LAST)
4625 i = NUMKEYS(mp) - 1;
4628 node = mdb_node_search(mc, key, &exact);
4630 i = NUMKEYS(mp) - 1;
4632 i = mc->mc_ki[mc->mc_top];
4638 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4641 assert(i < NUMKEYS(mp));
4642 node = NODEPTR(mp, i);
4644 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4647 mc->mc_ki[mc->mc_top] = i;
4648 if ((rc = mdb_cursor_push(mc, mp)))
4651 if (flags & MDB_PS_MODIFY) {
4652 if ((rc = mdb_page_touch(mc)) != 0)
4654 mp = mc->mc_pg[mc->mc_top];
4659 DPRINTF(("internal error, index points to a %02X page!?",
4661 return MDB_CORRUPTED;
4664 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4665 key ? DKEY(key) : "null"));
4666 mc->mc_flags |= C_INITIALIZED;
4667 mc->mc_flags &= ~C_EOF;
4672 /** Search for the lowest key under the current branch page.
4673 * This just bypasses a NUMKEYS check in the current page
4674 * before calling mdb_page_search_root(), because the callers
4675 * are all in situations where the current page is known to
4679 mdb_page_search_lowest(MDB_cursor *mc)
4681 MDB_page *mp = mc->mc_pg[mc->mc_top];
4682 MDB_node *node = NODEPTR(mp, 0);
4685 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4688 mc->mc_ki[mc->mc_top] = 0;
4689 if ((rc = mdb_cursor_push(mc, mp)))
4691 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4694 /** Search for the page a given key should be in.
4695 * Push it and its parent pages on the cursor stack.
4696 * @param[in,out] mc the cursor for this operation.
4697 * @param[in] key the key to search for, or NULL for first/last page.
4698 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4699 * are touched (updated with new page numbers).
4700 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4701 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4702 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4703 * @return 0 on success, non-zero on failure.
4706 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4711 /* Make sure the txn is still viable, then find the root from
4712 * the txn's db table and set it as the root of the cursor's stack.
4714 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4715 DPUTS("transaction has failed, must abort");
4718 /* Make sure we're using an up-to-date root */
4719 if (*mc->mc_dbflag & DB_STALE) {
4721 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4722 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4729 MDB_node *leaf = mdb_node_search(&mc2,
4730 &mc->mc_dbx->md_name, &exact);
4732 return MDB_NOTFOUND;
4733 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4736 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4738 /* The txn may not know this DBI, or another process may
4739 * have dropped and recreated the DB with other flags.
4741 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4742 return MDB_INCOMPATIBLE;
4743 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4745 *mc->mc_dbflag &= ~DB_STALE;
4747 root = mc->mc_db->md_root;
4749 if (root == P_INVALID) { /* Tree is empty. */
4750 DPUTS("tree is empty");
4751 return MDB_NOTFOUND;
4756 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4757 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4763 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4764 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4766 if (flags & MDB_PS_MODIFY) {
4767 if ((rc = mdb_page_touch(mc)))
4771 if (flags & MDB_PS_ROOTONLY)
4774 return mdb_page_search_root(mc, key, flags);
4778 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4780 MDB_txn *txn = mc->mc_txn;
4781 pgno_t pg = mp->mp_pgno;
4782 unsigned x = 0, ovpages = mp->mp_pages;
4783 MDB_env *env = txn->mt_env;
4784 MDB_IDL sl = txn->mt_spill_pgs;
4785 MDB_ID pn = pg << 1;
4788 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4789 /* If the page is dirty or on the spill list we just acquired it,
4790 * so we should give it back to our current free list, if any.
4791 * Otherwise put it onto the list of pages we freed in this txn.
4793 * Won't create me_pghead: me_pglast must be inited along with it.
4794 * Unsupported in nested txns: They would need to hide the page
4795 * range in ancestor txns' dirty and spilled lists.
4797 if (env->me_pghead &&
4799 ((mp->mp_flags & P_DIRTY) ||
4800 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4804 MDB_ID2 *dl, ix, iy;
4805 rc = mdb_midl_need(&env->me_pghead, ovpages);
4808 if (!(mp->mp_flags & P_DIRTY)) {
4809 /* This page is no longer spilled */
4816 /* Remove from dirty list */
4817 dl = txn->mt_u.dirty_list;
4819 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4827 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4828 txn->mt_flags |= MDB_TXN_ERROR;
4829 return MDB_CORRUPTED;
4832 if (!(env->me_flags & MDB_WRITEMAP))
4833 mdb_dpage_free(env, mp);
4835 /* Insert in me_pghead */
4836 mop = env->me_pghead;
4837 j = mop[0] + ovpages;
4838 for (i = mop[0]; i && mop[i] < pg; i--)
4844 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4848 mc->mc_db->md_overflow_pages -= ovpages;
4852 /** Return the data associated with a given node.
4853 * @param[in] txn The transaction for this operation.
4854 * @param[in] leaf The node being read.
4855 * @param[out] data Updated to point to the node's data.
4856 * @return 0 on success, non-zero on failure.
4859 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4861 MDB_page *omp; /* overflow page */
4865 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4866 data->mv_size = NODEDSZ(leaf);
4867 data->mv_data = NODEDATA(leaf);
4871 /* Read overflow data.
4873 data->mv_size = NODEDSZ(leaf);
4874 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4875 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4876 DPRINTF(("read overflow page %"Z"u failed", pgno));
4879 data->mv_data = METADATA(omp);
4885 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4886 MDB_val *key, MDB_val *data)
4895 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
4897 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4900 if (txn->mt_flags & MDB_TXN_ERROR)
4903 if (key->mv_size > MDB_MAXKEYSIZE) {
4904 return MDB_BAD_VALSIZE;
4907 mdb_cursor_init(&mc, txn, dbi, &mx);
4908 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4911 /** Find a sibling for a page.
4912 * Replaces the page at the top of the cursor's stack with the
4913 * specified sibling, if one exists.
4914 * @param[in] mc The cursor for this operation.
4915 * @param[in] move_right Non-zero if the right sibling is requested,
4916 * otherwise the left sibling.
4917 * @return 0 on success, non-zero on failure.
4920 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4926 if (mc->mc_snum < 2) {
4927 return MDB_NOTFOUND; /* root has no siblings */
4931 DPRINTF(("parent page is page %"Z"u, index %u",
4932 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
4934 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4935 : (mc->mc_ki[mc->mc_top] == 0)) {
4936 DPRINTF(("no more keys left, moving to %s sibling",
4937 move_right ? "right" : "left"));
4938 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4939 /* undo cursor_pop before returning */
4946 mc->mc_ki[mc->mc_top]++;
4948 mc->mc_ki[mc->mc_top]--;
4949 DPRINTF(("just moving to %s index key %u",
4950 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
4952 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4954 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4955 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
4956 /* mc will be inconsistent if caller does mc_snum++ as above */
4957 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
4961 mdb_cursor_push(mc, mp);
4963 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4968 /** Move the cursor to the next data item. */
4970 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4976 if (mc->mc_flags & C_EOF) {
4977 return MDB_NOTFOUND;
4980 assert(mc->mc_flags & C_INITIALIZED);
4982 mp = mc->mc_pg[mc->mc_top];
4984 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4985 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4986 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4987 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4988 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4989 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
4990 if (rc == MDB_SUCCESS)
4991 MDB_GET_KEY(leaf, key);
4996 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4997 if (op == MDB_NEXT_DUP)
4998 return MDB_NOTFOUND;
5002 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5003 if (mc->mc_flags & C_DEL)
5006 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5007 DPUTS("=====> move to next sibling page");
5008 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5009 mc->mc_flags |= C_EOF;
5012 mp = mc->mc_pg[mc->mc_top];
5013 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5015 mc->mc_ki[mc->mc_top]++;
5018 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5019 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5022 key->mv_size = mc->mc_db->md_pad;
5023 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5027 assert(IS_LEAF(mp));
5028 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5030 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5031 mdb_xcursor_init1(mc, leaf);
5034 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5037 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5038 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5039 if (rc != MDB_SUCCESS)
5044 MDB_GET_KEY(leaf, key);
5048 /** Move the cursor to the previous data item. */
5050 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5056 assert(mc->mc_flags & C_INITIALIZED);
5058 mp = mc->mc_pg[mc->mc_top];
5060 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5061 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5062 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5063 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5064 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5065 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5066 if (rc == MDB_SUCCESS)
5067 MDB_GET_KEY(leaf, key);
5071 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5072 if (op == MDB_PREV_DUP)
5073 return MDB_NOTFOUND;
5078 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5080 if (mc->mc_ki[mc->mc_top] == 0) {
5081 DPUTS("=====> move to prev sibling page");
5082 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5085 mp = mc->mc_pg[mc->mc_top];
5086 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5087 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5089 mc->mc_ki[mc->mc_top]--;
5091 mc->mc_flags &= ~C_EOF;
5093 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5094 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5097 key->mv_size = mc->mc_db->md_pad;
5098 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5102 assert(IS_LEAF(mp));
5103 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5105 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5106 mdb_xcursor_init1(mc, leaf);
5109 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5112 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5113 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5114 if (rc != MDB_SUCCESS)
5119 MDB_GET_KEY(leaf, key);
5123 /** Set the cursor on a specific data item. */
5125 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5126 MDB_cursor_op op, int *exactp)
5130 MDB_node *leaf = NULL;
5135 if (key->mv_size == 0)
5136 return MDB_BAD_VALSIZE;
5139 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5141 /* See if we're already on the right page */
5142 if (mc->mc_flags & C_INITIALIZED) {
5145 mp = mc->mc_pg[mc->mc_top];
5147 mc->mc_ki[mc->mc_top] = 0;
5148 return MDB_NOTFOUND;
5150 if (mp->mp_flags & P_LEAF2) {
5151 nodekey.mv_size = mc->mc_db->md_pad;
5152 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5154 leaf = NODEPTR(mp, 0);
5155 MDB_GET_KEY2(leaf, nodekey);
5157 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5159 /* Probably happens rarely, but first node on the page
5160 * was the one we wanted.
5162 mc->mc_ki[mc->mc_top] = 0;
5169 unsigned int nkeys = NUMKEYS(mp);
5171 if (mp->mp_flags & P_LEAF2) {
5172 nodekey.mv_data = LEAF2KEY(mp,
5173 nkeys-1, nodekey.mv_size);
5175 leaf = NODEPTR(mp, nkeys-1);
5176 MDB_GET_KEY2(leaf, nodekey);
5178 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5180 /* last node was the one we wanted */
5181 mc->mc_ki[mc->mc_top] = nkeys-1;
5187 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5188 /* This is definitely the right page, skip search_page */
5189 if (mp->mp_flags & P_LEAF2) {
5190 nodekey.mv_data = LEAF2KEY(mp,
5191 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5193 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5194 MDB_GET_KEY2(leaf, nodekey);
5196 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5198 /* current node was the one we wanted */
5208 /* If any parents have right-sibs, search.
5209 * Otherwise, there's nothing further.
5211 for (i=0; i<mc->mc_top; i++)
5213 NUMKEYS(mc->mc_pg[i])-1)
5215 if (i == mc->mc_top) {
5216 /* There are no other pages */
5217 mc->mc_ki[mc->mc_top] = nkeys;
5218 return MDB_NOTFOUND;
5222 /* There are no other pages */
5223 mc->mc_ki[mc->mc_top] = 0;
5224 if (op == MDB_SET_RANGE) {
5228 return MDB_NOTFOUND;
5232 rc = mdb_page_search(mc, key, 0);
5233 if (rc != MDB_SUCCESS)
5236 mp = mc->mc_pg[mc->mc_top];
5237 assert(IS_LEAF(mp));
5240 leaf = mdb_node_search(mc, key, exactp);
5241 if (exactp != NULL && !*exactp) {
5242 /* MDB_SET specified and not an exact match. */
5243 return MDB_NOTFOUND;
5247 DPUTS("===> inexact leaf not found, goto sibling");
5248 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5249 return rc; /* no entries matched */
5250 mp = mc->mc_pg[mc->mc_top];
5251 assert(IS_LEAF(mp));
5252 leaf = NODEPTR(mp, 0);
5256 mc->mc_flags |= C_INITIALIZED;
5257 mc->mc_flags &= ~C_EOF;
5260 key->mv_size = mc->mc_db->md_pad;
5261 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5265 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5266 mdb_xcursor_init1(mc, leaf);
5269 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5270 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5271 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5274 if (op == MDB_GET_BOTH) {
5280 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5281 if (rc != MDB_SUCCESS)
5284 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5286 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5288 rc = mc->mc_dbx->md_dcmp(data, &d2);
5290 if (op == MDB_GET_BOTH || rc > 0)
5291 return MDB_NOTFOUND;
5297 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5298 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5303 /* The key already matches in all other cases */
5304 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5305 MDB_GET_KEY(leaf, key);
5306 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5311 /** Move the cursor to the first item in the database. */
5313 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5319 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5321 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5322 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5323 if (rc != MDB_SUCCESS)
5326 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5328 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5329 mc->mc_flags |= C_INITIALIZED;
5330 mc->mc_flags &= ~C_EOF;
5332 mc->mc_ki[mc->mc_top] = 0;
5334 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5335 key->mv_size = mc->mc_db->md_pad;
5336 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5341 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5342 mdb_xcursor_init1(mc, leaf);
5343 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5347 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5351 MDB_GET_KEY(leaf, key);
5355 /** Move the cursor to the last item in the database. */
5357 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5363 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5365 if (!(mc->mc_flags & C_EOF)) {
5367 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5368 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5369 if (rc != MDB_SUCCESS)
5372 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5375 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5376 mc->mc_flags |= C_INITIALIZED|C_EOF;
5377 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5379 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5380 key->mv_size = mc->mc_db->md_pad;
5381 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5386 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5387 mdb_xcursor_init1(mc, leaf);
5388 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5392 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5397 MDB_GET_KEY(leaf, key);
5402 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5407 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5411 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5415 case MDB_GET_CURRENT:
5416 if (!(mc->mc_flags & C_INITIALIZED)) {
5419 MDB_page *mp = mc->mc_pg[mc->mc_top];
5421 mc->mc_ki[mc->mc_top] = 0;
5427 key->mv_size = mc->mc_db->md_pad;
5428 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5430 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5431 MDB_GET_KEY(leaf, key);
5433 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5434 if (mc->mc_flags & C_DEL)
5435 mdb_xcursor_init1(mc, leaf);
5436 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5438 rc = mdb_node_read(mc->mc_txn, leaf, data);
5445 case MDB_GET_BOTH_RANGE:
5450 if (mc->mc_xcursor == NULL) {
5451 rc = MDB_INCOMPATIBLE;
5460 } else if (key->mv_size > MDB_MAXKEYSIZE) {
5461 rc = MDB_BAD_VALSIZE;
5462 } else if (op == MDB_SET_RANGE)
5463 rc = mdb_cursor_set(mc, key, data, op, NULL);
5465 rc = mdb_cursor_set(mc, key, data, op, &exact);
5467 case MDB_GET_MULTIPLE:
5468 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5472 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5473 rc = MDB_INCOMPATIBLE;
5477 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5478 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5481 case MDB_NEXT_MULTIPLE:
5486 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5487 rc = MDB_INCOMPATIBLE;
5490 if (!(mc->mc_flags & C_INITIALIZED))
5491 rc = mdb_cursor_first(mc, key, data);
5493 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5494 if (rc == MDB_SUCCESS) {
5495 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5498 mx = &mc->mc_xcursor->mx_cursor;
5499 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5501 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5502 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5510 case MDB_NEXT_NODUP:
5511 if (!(mc->mc_flags & C_INITIALIZED))
5512 rc = mdb_cursor_first(mc, key, data);
5514 rc = mdb_cursor_next(mc, key, data, op);
5518 case MDB_PREV_NODUP:
5519 if (!(mc->mc_flags & C_INITIALIZED)) {
5520 rc = mdb_cursor_last(mc, key, data);
5523 mc->mc_flags |= C_INITIALIZED;
5524 mc->mc_ki[mc->mc_top]++;
5526 rc = mdb_cursor_prev(mc, key, data, op);
5529 rc = mdb_cursor_first(mc, key, data);
5532 mfunc = mdb_cursor_first;
5534 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5538 if (mc->mc_xcursor == NULL) {
5539 rc = MDB_INCOMPATIBLE;
5542 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5546 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5549 rc = mdb_cursor_last(mc, key, data);
5552 mfunc = mdb_cursor_last;
5555 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5560 if (mc->mc_flags & C_DEL)
5561 mc->mc_flags ^= C_DEL;
5566 /** Touch all the pages in the cursor stack. Set mc_top.
5567 * Makes sure all the pages are writable, before attempting a write operation.
5568 * @param[in] mc The cursor to operate on.
5571 mdb_cursor_touch(MDB_cursor *mc)
5573 int rc = MDB_SUCCESS;
5575 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5578 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5579 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5582 *mc->mc_dbflag |= DB_DIRTY;
5587 rc = mdb_page_touch(mc);
5588 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5589 mc->mc_top = mc->mc_snum-1;
5594 /** Do not spill pages to disk if txn is getting full, may fail instead */
5595 #define MDB_NOSPILL 0x8000
5598 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5601 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5602 MDB_node *leaf = NULL;
5603 MDB_val xdata, *rdata, dkey;
5606 int do_sub = 0, insert = 0;
5607 unsigned int mcount = 0, dcount = 0, nospill;
5611 char dbuf[MDB_MAXKEYSIZE+1];
5612 unsigned int nflags;
5615 /* Check this first so counter will always be zero on any
5618 if (flags & MDB_MULTIPLE) {
5619 dcount = data[1].mv_size;
5620 data[1].mv_size = 0;
5621 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5622 return MDB_INCOMPATIBLE;
5625 nospill = flags & MDB_NOSPILL;
5626 flags &= ~MDB_NOSPILL;
5628 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5629 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5631 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5632 return MDB_BAD_VALSIZE;
5634 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5635 return MDB_BAD_VALSIZE;
5637 #if SIZE_MAX > MAXDATASIZE
5638 if (data->mv_size > MAXDATASIZE)
5639 return MDB_BAD_VALSIZE;
5642 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5643 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5647 if (flags == MDB_CURRENT) {
5648 if (!(mc->mc_flags & C_INITIALIZED))
5651 } else if (mc->mc_db->md_root == P_INVALID) {
5652 /* new database, cursor has nothing to point to */
5655 mc->mc_flags &= ~C_INITIALIZED;
5660 if (flags & MDB_APPEND) {
5662 rc = mdb_cursor_last(mc, &k2, &d2);
5664 rc = mc->mc_dbx->md_cmp(key, &k2);
5667 mc->mc_ki[mc->mc_top]++;
5669 /* new key is <= last key */
5674 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5676 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5677 DPRINTF(("duplicate key [%s]", DKEY(key)));
5679 return MDB_KEYEXIST;
5681 if (rc && rc != MDB_NOTFOUND)
5685 if (mc->mc_flags & C_DEL)
5686 mc->mc_flags ^= C_DEL;
5688 /* Cursor is positioned, check for room in the dirty list */
5690 if (flags & MDB_MULTIPLE) {
5692 xdata.mv_size = data->mv_size * dcount;
5696 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5700 if (rc == MDB_NO_ROOT) {
5702 /* new database, write a root leaf page */
5703 DPUTS("allocating new root leaf page");
5704 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5707 mdb_cursor_push(mc, np);
5708 mc->mc_db->md_root = np->mp_pgno;
5709 mc->mc_db->md_depth++;
5710 *mc->mc_dbflag |= DB_DIRTY;
5711 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5713 np->mp_flags |= P_LEAF2;
5714 mc->mc_flags |= C_INITIALIZED;
5716 /* make sure all cursor pages are writable */
5717 rc2 = mdb_cursor_touch(mc);
5722 /* The key already exists */
5723 if (rc == MDB_SUCCESS) {
5724 /* there's only a key anyway, so this is a no-op */
5725 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5726 unsigned int ksize = mc->mc_db->md_pad;
5727 if (key->mv_size != ksize)
5728 return MDB_BAD_VALSIZE;
5729 if (flags == MDB_CURRENT) {
5730 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5731 memcpy(ptr, key->mv_data, ksize);
5736 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5739 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5740 /* Was a single item before, must convert now */
5742 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5743 /* Just overwrite the current item */
5744 if (flags == MDB_CURRENT)
5747 dkey.mv_size = NODEDSZ(leaf);
5748 dkey.mv_data = NODEDATA(leaf);
5749 #if UINT_MAX < SIZE_MAX
5750 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5751 #ifdef MISALIGNED_OK
5752 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5754 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5757 /* if data matches, skip it */
5758 if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
5759 if (flags & MDB_NODUPDATA)
5761 else if (flags & MDB_MULTIPLE)
5768 /* create a fake page for the dup items */
5769 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5770 dkey.mv_data = dbuf;
5771 fp = (MDB_page *)&pbuf;
5772 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5773 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5774 fp->mp_lower = PAGEHDRSZ;
5775 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5776 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5777 fp->mp_flags |= P_LEAF2;
5778 fp->mp_pad = data->mv_size;
5779 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5781 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5782 (dkey.mv_size & 1) + (data->mv_size & 1);
5784 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5787 xdata.mv_size = fp->mp_upper;
5792 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5793 /* See if we need to convert from fake page to subDB */
5795 unsigned int offset;
5799 fp = NODEDATA(leaf);
5800 if (flags == MDB_CURRENT) {
5802 fp->mp_flags |= P_DIRTY;
5803 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5804 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5808 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5809 offset = fp->mp_pad;
5810 if (SIZELEFT(fp) >= offset)
5812 offset *= 4; /* space for 4 more */
5814 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5816 offset += offset & 1;
5817 fp_flags = fp->mp_flags;
5818 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5819 offset >= mc->mc_txn->mt_env->me_nodemax) {
5820 /* yes, convert it */
5822 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5823 dummy.md_pad = fp->mp_pad;
5824 dummy.md_flags = MDB_DUPFIXED;
5825 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5826 dummy.md_flags |= MDB_INTEGERKEY;
5829 dummy.md_branch_pages = 0;
5830 dummy.md_leaf_pages = 1;
5831 dummy.md_overflow_pages = 0;
5832 dummy.md_entries = NUMKEYS(fp);
5834 xdata.mv_size = sizeof(MDB_db);
5835 xdata.mv_data = &dummy;
5836 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5838 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5839 flags |= F_DUPDATA|F_SUBDATA;
5840 dummy.md_root = mp->mp_pgno;
5841 fp_flags &= ~P_SUBP;
5843 /* no, just grow it */
5845 xdata.mv_size = NODEDSZ(leaf) + offset;
5846 xdata.mv_data = &pbuf;
5847 mp = (MDB_page *)&pbuf;
5848 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5851 mp->mp_flags = fp_flags | P_DIRTY;
5852 mp->mp_pad = fp->mp_pad;
5853 mp->mp_lower = fp->mp_lower;
5854 mp->mp_upper = fp->mp_upper + offset;
5856 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5858 nsize = NODEDSZ(leaf) - fp->mp_upper;
5859 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5860 for (i=0; i<NUMKEYS(fp); i++)
5861 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5863 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5867 /* data is on sub-DB, just store it */
5868 flags |= F_DUPDATA|F_SUBDATA;
5872 /* overflow page overwrites need special handling */
5873 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5876 unsigned psize = mc->mc_txn->mt_env->me_psize;
5877 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5879 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5880 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5882 ovpages = omp->mp_pages;
5884 /* Is the ov page large enough? */
5885 if (ovpages >= dpages) {
5886 if (!(omp->mp_flags & P_DIRTY) &&
5887 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5889 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5892 level = 0; /* dirty in this txn or clean */
5895 if (omp->mp_flags & P_DIRTY) {
5896 /* yes, overwrite it. Note in this case we don't
5897 * bother to try shrinking the page if the new data
5898 * is smaller than the overflow threshold.
5901 /* It is writable only in a parent txn */
5902 size_t sz = (size_t) psize * ovpages, off;
5903 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5909 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5910 if (!(flags & MDB_RESERVE)) {
5911 /* Copy end of page, adjusting alignment so
5912 * compiler may copy words instead of bytes.
5914 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5915 memcpy((size_t *)((char *)np + off),
5916 (size_t *)((char *)omp + off), sz - off);
5919 memcpy(np, omp, sz); /* Copy beginning of page */
5922 SETDSZ(leaf, data->mv_size);
5923 if (F_ISSET(flags, MDB_RESERVE))
5924 data->mv_data = METADATA(omp);
5926 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5930 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5932 } else if (NODEDSZ(leaf) == data->mv_size) {
5933 /* same size, just replace it. Note that we could
5934 * also reuse this node if the new data is smaller,
5935 * but instead we opt to shrink the node in that case.
5937 if (F_ISSET(flags, MDB_RESERVE))
5938 data->mv_data = NODEDATA(leaf);
5939 else if (data->mv_size)
5940 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5942 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5945 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5946 mc->mc_db->md_entries--;
5948 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5955 nflags = flags & NODE_ADD_FLAGS;
5956 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5957 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5958 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5959 nflags &= ~MDB_APPEND;
5961 nflags |= MDB_SPLIT_REPLACE;
5962 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5964 /* There is room already in this leaf page. */
5965 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5966 if (rc == 0 && !do_sub && insert) {
5967 /* Adjust other cursors pointing to mp */
5968 MDB_cursor *m2, *m3;
5969 MDB_dbi dbi = mc->mc_dbi;
5970 unsigned i = mc->mc_top;
5971 MDB_page *mp = mc->mc_pg[i];
5973 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5974 if (mc->mc_flags & C_SUB)
5975 m3 = &m2->mc_xcursor->mx_cursor;
5978 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5979 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5986 if (rc != MDB_SUCCESS)
5987 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5989 /* Now store the actual data in the child DB. Note that we're
5990 * storing the user data in the keys field, so there are strict
5991 * size limits on dupdata. The actual data fields of the child
5992 * DB are all zero size.
5999 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6000 if (flags & MDB_CURRENT) {
6001 xflags = MDB_CURRENT|MDB_NOSPILL;
6003 mdb_xcursor_init1(mc, leaf);
6004 xflags = (flags & MDB_NODUPDATA) ?
6005 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6007 /* converted, write the original data first */
6009 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6013 /* Adjust other cursors pointing to mp */
6015 unsigned i = mc->mc_top;
6016 MDB_page *mp = mc->mc_pg[i];
6018 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6019 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6020 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6021 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6022 mdb_xcursor_init1(m2, leaf);
6026 /* we've done our job */
6029 if (flags & MDB_APPENDDUP)
6030 xflags |= MDB_APPEND;
6031 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6032 if (flags & F_SUBDATA) {
6033 void *db = NODEDATA(leaf);
6034 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6037 /* sub-writes might have failed so check rc again.
6038 * Don't increment count if we just replaced an existing item.
6040 if (!rc && !(flags & MDB_CURRENT))
6041 mc->mc_db->md_entries++;
6042 if (flags & MDB_MULTIPLE) {
6046 /* let caller know how many succeeded, if any */
6047 data[1].mv_size = mcount;
6048 if (mcount < dcount) {
6049 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6050 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6057 /* If we succeeded and the key didn't exist before, make sure
6058 * the cursor is marked valid.
6061 mc->mc_flags |= C_INITIALIZED;
6066 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6071 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6072 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6074 if (!(mc->mc_flags & C_INITIALIZED))
6077 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6080 rc = mdb_cursor_touch(mc);
6084 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6086 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6087 if (!(flags & MDB_NODUPDATA)) {
6088 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6089 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6091 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6092 /* If sub-DB still has entries, we're done */
6093 if (mc->mc_xcursor->mx_db.md_entries) {
6094 if (leaf->mn_flags & F_SUBDATA) {
6095 /* update subDB info */
6096 void *db = NODEDATA(leaf);
6097 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6100 /* shrink fake page */
6101 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6102 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6103 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6104 /* fix other sub-DB cursors pointed at this fake page */
6105 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6106 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6107 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
6108 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6109 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6112 mc->mc_db->md_entries--;
6113 mc->mc_flags |= C_DEL;
6116 /* otherwise fall thru and delete the sub-DB */
6119 if (leaf->mn_flags & F_SUBDATA) {
6120 /* add all the child DB's pages to the free list */
6121 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6122 if (rc == MDB_SUCCESS) {
6123 mc->mc_db->md_entries -=
6124 mc->mc_xcursor->mx_db.md_entries;
6129 return mdb_cursor_del0(mc, leaf);
6132 /** Allocate and initialize new pages for a database.
6133 * @param[in] mc a cursor on the database being added to.
6134 * @param[in] flags flags defining what type of page is being allocated.
6135 * @param[in] num the number of pages to allocate. This is usually 1,
6136 * unless allocating overflow pages for a large record.
6137 * @param[out] mp Address of a page, or NULL on failure.
6138 * @return 0 on success, non-zero on failure.
6141 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6146 if ((rc = mdb_page_alloc(mc, num, &np)))
6148 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6149 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6150 np->mp_flags = flags | P_DIRTY;
6151 np->mp_lower = PAGEHDRSZ;
6152 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6155 mc->mc_db->md_branch_pages++;
6156 else if (IS_LEAF(np))
6157 mc->mc_db->md_leaf_pages++;
6158 else if (IS_OVERFLOW(np)) {
6159 mc->mc_db->md_overflow_pages += num;
6167 /** Calculate the size of a leaf node.
6168 * The size depends on the environment's page size; if a data item
6169 * is too large it will be put onto an overflow page and the node
6170 * size will only include the key and not the data. Sizes are always
6171 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6172 * of the #MDB_node headers.
6173 * @param[in] env The environment handle.
6174 * @param[in] key The key for the node.
6175 * @param[in] data The data for the node.
6176 * @return The number of bytes needed to store the node.
6179 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6183 sz = LEAFSIZE(key, data);
6184 if (sz >= env->me_nodemax) {
6185 /* put on overflow page */
6186 sz -= data->mv_size - sizeof(pgno_t);
6190 return sz + sizeof(indx_t);
6193 /** Calculate the size of a branch node.
6194 * The size should depend on the environment's page size but since
6195 * we currently don't support spilling large keys onto overflow
6196 * pages, it's simply the size of the #MDB_node header plus the
6197 * size of the key. Sizes are always rounded up to an even number
6198 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6199 * @param[in] env The environment handle.
6200 * @param[in] key The key for the node.
6201 * @return The number of bytes needed to store the node.
6204 mdb_branch_size(MDB_env *env, MDB_val *key)
6209 if (sz >= env->me_nodemax) {
6210 /* put on overflow page */
6211 /* not implemented */
6212 /* sz -= key->size - sizeof(pgno_t); */
6215 return sz + sizeof(indx_t);
6218 /** Add a node to the page pointed to by the cursor.
6219 * @param[in] mc The cursor for this operation.
6220 * @param[in] indx The index on the page where the new node should be added.
6221 * @param[in] key The key for the new node.
6222 * @param[in] data The data for the new node, if any.
6223 * @param[in] pgno The page number, if adding a branch node.
6224 * @param[in] flags Flags for the node.
6225 * @return 0 on success, non-zero on failure. Possible errors are:
6227 * <li>ENOMEM - failed to allocate overflow pages for the node.
6228 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6229 * should never happen since all callers already calculate the
6230 * page's free space before calling this function.
6234 mdb_node_add(MDB_cursor *mc, indx_t indx,
6235 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6238 size_t node_size = NODESIZE;
6242 MDB_page *mp = mc->mc_pg[mc->mc_top];
6243 MDB_page *ofp = NULL; /* overflow page */
6246 assert(mp->mp_upper >= mp->mp_lower);
6248 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6249 IS_LEAF(mp) ? "leaf" : "branch",
6250 IS_SUBP(mp) ? "sub-" : "",
6251 mp->mp_pgno, indx, data ? data->mv_size : 0,
6252 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6255 /* Move higher keys up one slot. */
6256 int ksize = mc->mc_db->md_pad, dif;
6257 char *ptr = LEAF2KEY(mp, indx, ksize);
6258 dif = NUMKEYS(mp) - indx;
6260 memmove(ptr+ksize, ptr, dif*ksize);
6261 /* insert new key */
6262 memcpy(ptr, key->mv_data, ksize);
6264 /* Just using these for counting */
6265 mp->mp_lower += sizeof(indx_t);
6266 mp->mp_upper -= ksize - sizeof(indx_t);
6270 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6272 node_size += key->mv_size;
6275 if (F_ISSET(flags, F_BIGDATA)) {
6276 /* Data already on overflow page. */
6277 node_size += sizeof(pgno_t);
6278 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6279 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6281 /* Put data on overflow page. */
6282 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6283 data->mv_size, node_size+data->mv_size));
6284 node_size += sizeof(pgno_t) + (node_size & 1);
6285 if ((ssize_t)node_size > room)
6287 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6289 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6293 node_size += data->mv_size;
6296 node_size += node_size & 1;
6297 if ((ssize_t)node_size > room)
6301 /* Move higher pointers up one slot. */
6302 for (i = NUMKEYS(mp); i > indx; i--)
6303 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6305 /* Adjust free space offsets. */
6306 ofs = mp->mp_upper - node_size;
6307 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6308 mp->mp_ptrs[indx] = ofs;
6310 mp->mp_lower += sizeof(indx_t);
6312 /* Write the node data. */
6313 node = NODEPTR(mp, indx);
6314 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6315 node->mn_flags = flags;
6317 SETDSZ(node,data->mv_size);
6322 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6327 if (F_ISSET(flags, F_BIGDATA))
6328 memcpy(node->mn_data + key->mv_size, data->mv_data,
6330 else if (F_ISSET(flags, MDB_RESERVE))
6331 data->mv_data = node->mn_data + key->mv_size;
6333 memcpy(node->mn_data + key->mv_size, data->mv_data,
6336 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6338 if (F_ISSET(flags, MDB_RESERVE))
6339 data->mv_data = METADATA(ofp);
6341 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6348 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6349 mp->mp_pgno, NUMKEYS(mp)));
6350 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6351 DPRINTF(("node size = %"Z"u", node_size));
6352 return MDB_PAGE_FULL;
6355 /** Delete the specified node from a page.
6356 * @param[in] mp The page to operate on.
6357 * @param[in] indx The index of the node to delete.
6358 * @param[in] ksize The size of a node. Only used if the page is
6359 * part of a #MDB_DUPFIXED database.
6362 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6365 indx_t i, j, numkeys, ptr;
6372 COPY_PGNO(pgno, mp->mp_pgno);
6373 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6374 IS_LEAF(mp) ? "leaf" : "branch", pgno));
6377 assert(indx < NUMKEYS(mp));
6380 int x = NUMKEYS(mp) - 1 - indx;
6381 base = LEAF2KEY(mp, indx, ksize);
6383 memmove(base, base + ksize, x * ksize);
6384 mp->mp_lower -= sizeof(indx_t);
6385 mp->mp_upper += ksize - sizeof(indx_t);
6389 node = NODEPTR(mp, indx);
6390 sz = NODESIZE + node->mn_ksize;
6392 if (F_ISSET(node->mn_flags, F_BIGDATA))
6393 sz += sizeof(pgno_t);
6395 sz += NODEDSZ(node);
6399 ptr = mp->mp_ptrs[indx];
6400 numkeys = NUMKEYS(mp);
6401 for (i = j = 0; i < numkeys; i++) {
6403 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6404 if (mp->mp_ptrs[i] < ptr)
6405 mp->mp_ptrs[j] += sz;
6410 base = (char *)mp + mp->mp_upper;
6411 memmove(base + sz, base, ptr - mp->mp_upper);
6413 mp->mp_lower -= sizeof(indx_t);
6417 /** Compact the main page after deleting a node on a subpage.
6418 * @param[in] mp The main page to operate on.
6419 * @param[in] indx The index of the subpage on the main page.
6422 mdb_node_shrink(MDB_page *mp, indx_t indx)
6429 indx_t i, numkeys, ptr;
6431 node = NODEPTR(mp, indx);
6432 sp = (MDB_page *)NODEDATA(node);
6433 osize = NODEDSZ(node);
6435 delta = sp->mp_upper - sp->mp_lower;
6436 SETDSZ(node, osize - delta);
6437 xp = (MDB_page *)((char *)sp + delta);
6439 /* shift subpage upward */
6441 nsize = NUMKEYS(sp) * sp->mp_pad;
6442 memmove(METADATA(xp), METADATA(sp), nsize);
6445 nsize = osize - sp->mp_upper;
6446 numkeys = NUMKEYS(sp);
6447 for (i=numkeys-1; i>=0; i--)
6448 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6450 xp->mp_upper = sp->mp_lower;
6451 xp->mp_lower = sp->mp_lower;
6452 xp->mp_flags = sp->mp_flags;
6453 xp->mp_pad = sp->mp_pad;
6454 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6456 /* shift lower nodes upward */
6457 ptr = mp->mp_ptrs[indx];
6458 numkeys = NUMKEYS(mp);
6459 for (i = 0; i < numkeys; i++) {
6460 if (mp->mp_ptrs[i] <= ptr)
6461 mp->mp_ptrs[i] += delta;
6464 base = (char *)mp + mp->mp_upper;
6465 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6466 mp->mp_upper += delta;
6469 /** Initial setup of a sorted-dups cursor.
6470 * Sorted duplicates are implemented as a sub-database for the given key.
6471 * The duplicate data items are actually keys of the sub-database.
6472 * Operations on the duplicate data items are performed using a sub-cursor
6473 * initialized when the sub-database is first accessed. This function does
6474 * the preliminary setup of the sub-cursor, filling in the fields that
6475 * depend only on the parent DB.
6476 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6479 mdb_xcursor_init0(MDB_cursor *mc)
6481 MDB_xcursor *mx = mc->mc_xcursor;
6483 mx->mx_cursor.mc_xcursor = NULL;
6484 mx->mx_cursor.mc_txn = mc->mc_txn;
6485 mx->mx_cursor.mc_db = &mx->mx_db;
6486 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6487 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6488 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6489 mx->mx_cursor.mc_snum = 0;
6490 mx->mx_cursor.mc_top = 0;
6491 mx->mx_cursor.mc_flags = C_SUB;
6492 mx->mx_dbx.md_name.mv_size = 0;
6493 mx->mx_dbx.md_name.mv_data = NULL;
6494 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6495 mx->mx_dbx.md_dcmp = NULL;
6496 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6499 /** Final setup of a sorted-dups cursor.
6500 * Sets up the fields that depend on the data from the main cursor.
6501 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6502 * @param[in] node The data containing the #MDB_db record for the
6503 * sorted-dup database.
6506 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6508 MDB_xcursor *mx = mc->mc_xcursor;
6510 if (node->mn_flags & F_SUBDATA) {
6511 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6512 mx->mx_cursor.mc_pg[0] = 0;
6513 mx->mx_cursor.mc_snum = 0;
6514 mx->mx_cursor.mc_top = 0;
6515 mx->mx_cursor.mc_flags = C_SUB;
6517 MDB_page *fp = NODEDATA(node);
6518 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6519 mx->mx_db.md_flags = 0;
6520 mx->mx_db.md_depth = 1;
6521 mx->mx_db.md_branch_pages = 0;
6522 mx->mx_db.md_leaf_pages = 1;
6523 mx->mx_db.md_overflow_pages = 0;
6524 mx->mx_db.md_entries = NUMKEYS(fp);
6525 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6526 mx->mx_cursor.mc_snum = 1;
6527 mx->mx_cursor.mc_top = 0;
6528 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6529 mx->mx_cursor.mc_pg[0] = fp;
6530 mx->mx_cursor.mc_ki[0] = 0;
6531 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6532 mx->mx_db.md_flags = MDB_DUPFIXED;
6533 mx->mx_db.md_pad = fp->mp_pad;
6534 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6535 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6538 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6539 mx->mx_db.md_root));
6540 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6541 #if UINT_MAX < SIZE_MAX
6542 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6543 #ifdef MISALIGNED_OK
6544 mx->mx_dbx.md_cmp = mdb_cmp_long;
6546 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6551 /** Initialize a cursor for a given transaction and database. */
6553 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6556 mc->mc_backup = NULL;
6559 mc->mc_db = &txn->mt_dbs[dbi];
6560 mc->mc_dbx = &txn->mt_dbxs[dbi];
6561 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6566 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6568 mc->mc_xcursor = mx;
6569 mdb_xcursor_init0(mc);
6571 mc->mc_xcursor = NULL;
6573 if (*mc->mc_dbflag & DB_STALE) {
6574 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6579 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6582 size_t size = sizeof(MDB_cursor);
6584 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6587 if (txn->mt_flags & MDB_TXN_ERROR)
6590 /* Allow read access to the freelist */
6591 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6594 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6595 size += sizeof(MDB_xcursor);
6597 if ((mc = malloc(size)) != NULL) {
6598 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6599 if (txn->mt_cursors) {
6600 mc->mc_next = txn->mt_cursors[dbi];
6601 txn->mt_cursors[dbi] = mc;
6602 mc->mc_flags |= C_UNTRACK;
6614 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6616 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6619 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6622 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6626 /* Return the count of duplicate data items for the current key */
6628 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6632 if (mc == NULL || countp == NULL)
6635 if (mc->mc_xcursor == NULL)
6636 return MDB_INCOMPATIBLE;
6638 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6639 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6642 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6645 *countp = mc->mc_xcursor->mx_db.md_entries;
6651 mdb_cursor_close(MDB_cursor *mc)
6653 if (mc && !mc->mc_backup) {
6654 /* remove from txn, if tracked */
6655 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6656 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6657 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6659 *prev = mc->mc_next;
6666 mdb_cursor_txn(MDB_cursor *mc)
6668 if (!mc) return NULL;
6673 mdb_cursor_dbi(MDB_cursor *mc)
6679 /** Replace the key for a node with a new key.
6680 * @param[in] mc Cursor pointing to the node to operate on.
6681 * @param[in] key The new key to use.
6682 * @return 0 on success, non-zero on failure.
6685 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6692 indx_t ptr, i, numkeys, indx;
6695 indx = mc->mc_ki[mc->mc_top];
6696 mp = mc->mc_pg[mc->mc_top];
6697 node = NODEPTR(mp, indx);
6698 ptr = mp->mp_ptrs[indx];
6702 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6703 k2.mv_data = NODEKEY(node);
6704 k2.mv_size = node->mn_ksize;
6705 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6707 mdb_dkey(&k2, kbuf2),
6713 delta0 = delta = key->mv_size - node->mn_ksize;
6715 /* Must be 2-byte aligned. If new key is
6716 * shorter by 1, the shift will be skipped.
6718 delta += (delta & 1);
6720 if (delta > 0 && SIZELEFT(mp) < delta) {
6722 /* not enough space left, do a delete and split */
6723 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6724 pgno = NODEPGNO(node);
6725 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6726 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6729 numkeys = NUMKEYS(mp);
6730 for (i = 0; i < numkeys; i++) {
6731 if (mp->mp_ptrs[i] <= ptr)
6732 mp->mp_ptrs[i] -= delta;
6735 base = (char *)mp + mp->mp_upper;
6736 len = ptr - mp->mp_upper + NODESIZE;
6737 memmove(base - delta, base, len);
6738 mp->mp_upper -= delta;
6740 node = NODEPTR(mp, indx);
6743 /* But even if no shift was needed, update ksize */
6745 node->mn_ksize = key->mv_size;
6748 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6754 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6756 /** Move a node from csrc to cdst.
6759 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6766 unsigned short flags;
6770 /* Mark src and dst as dirty. */
6771 if ((rc = mdb_page_touch(csrc)) ||
6772 (rc = mdb_page_touch(cdst)))
6775 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6776 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6777 key.mv_size = csrc->mc_db->md_pad;
6778 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6780 data.mv_data = NULL;
6784 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6785 assert(!((long)srcnode&1));
6786 srcpg = NODEPGNO(srcnode);
6787 flags = srcnode->mn_flags;
6788 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6789 unsigned int snum = csrc->mc_snum;
6791 /* must find the lowest key below src */
6792 mdb_page_search_lowest(csrc);
6793 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6794 key.mv_size = csrc->mc_db->md_pad;
6795 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6797 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6798 key.mv_size = NODEKSZ(s2);
6799 key.mv_data = NODEKEY(s2);
6801 csrc->mc_snum = snum--;
6802 csrc->mc_top = snum;
6804 key.mv_size = NODEKSZ(srcnode);
6805 key.mv_data = NODEKEY(srcnode);
6807 data.mv_size = NODEDSZ(srcnode);
6808 data.mv_data = NODEDATA(srcnode);
6810 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6811 unsigned int snum = cdst->mc_snum;
6814 /* must find the lowest key below dst */
6815 mdb_page_search_lowest(cdst);
6816 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6817 bkey.mv_size = cdst->mc_db->md_pad;
6818 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6820 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6821 bkey.mv_size = NODEKSZ(s2);
6822 bkey.mv_data = NODEKEY(s2);
6824 cdst->mc_snum = snum--;
6825 cdst->mc_top = snum;
6826 mdb_cursor_copy(cdst, &mn);
6828 rc = mdb_update_key(&mn, &bkey);
6833 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6834 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6835 csrc->mc_ki[csrc->mc_top],
6837 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6838 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6840 /* Add the node to the destination page.
6842 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6843 if (rc != MDB_SUCCESS)
6846 /* Delete the node from the source page.
6848 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6851 /* Adjust other cursors pointing to mp */
6852 MDB_cursor *m2, *m3;
6853 MDB_dbi dbi = csrc->mc_dbi;
6854 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6856 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6857 if (csrc->mc_flags & C_SUB)
6858 m3 = &m2->mc_xcursor->mx_cursor;
6861 if (m3 == csrc) continue;
6862 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6863 csrc->mc_ki[csrc->mc_top]) {
6864 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6865 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6870 /* Update the parent separators.
6872 if (csrc->mc_ki[csrc->mc_top] == 0) {
6873 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6874 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6875 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6877 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6878 key.mv_size = NODEKSZ(srcnode);
6879 key.mv_data = NODEKEY(srcnode);
6881 DPRINTF(("update separator for source page %"Z"u to [%s]",
6882 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6883 mdb_cursor_copy(csrc, &mn);
6886 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6889 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6891 indx_t ix = csrc->mc_ki[csrc->mc_top];
6892 nullkey.mv_size = 0;
6893 csrc->mc_ki[csrc->mc_top] = 0;
6894 rc = mdb_update_key(csrc, &nullkey);
6895 csrc->mc_ki[csrc->mc_top] = ix;
6896 assert(rc == MDB_SUCCESS);
6900 if (cdst->mc_ki[cdst->mc_top] == 0) {
6901 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6902 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6903 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6905 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6906 key.mv_size = NODEKSZ(srcnode);
6907 key.mv_data = NODEKEY(srcnode);
6909 DPRINTF(("update separator for destination page %"Z"u to [%s]",
6910 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
6911 mdb_cursor_copy(cdst, &mn);
6914 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6917 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6919 indx_t ix = cdst->mc_ki[cdst->mc_top];
6920 nullkey.mv_size = 0;
6921 cdst->mc_ki[cdst->mc_top] = 0;
6922 rc = mdb_update_key(cdst, &nullkey);
6923 cdst->mc_ki[cdst->mc_top] = ix;
6924 assert(rc == MDB_SUCCESS);
6931 /** Merge one page into another.
6932 * The nodes from the page pointed to by \b csrc will
6933 * be copied to the page pointed to by \b cdst and then
6934 * the \b csrc page will be freed.
6935 * @param[in] csrc Cursor pointing to the source page.
6936 * @param[in] cdst Cursor pointing to the destination page.
6939 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6947 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6948 cdst->mc_pg[cdst->mc_top]->mp_pgno));
6950 assert(csrc->mc_snum > 1); /* can't merge root page */
6951 assert(cdst->mc_snum > 1);
6953 /* Mark dst as dirty. */
6954 if ((rc = mdb_page_touch(cdst)))
6957 /* Move all nodes from src to dst.
6959 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6960 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6961 key.mv_size = csrc->mc_db->md_pad;
6962 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6963 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6964 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6965 if (rc != MDB_SUCCESS)
6967 key.mv_data = (char *)key.mv_data + key.mv_size;
6970 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6971 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6972 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6973 unsigned int snum = csrc->mc_snum;
6975 /* must find the lowest key below src */
6976 mdb_page_search_lowest(csrc);
6977 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6978 key.mv_size = csrc->mc_db->md_pad;
6979 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6981 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6982 key.mv_size = NODEKSZ(s2);
6983 key.mv_data = NODEKEY(s2);
6985 csrc->mc_snum = snum--;
6986 csrc->mc_top = snum;
6988 key.mv_size = srcnode->mn_ksize;
6989 key.mv_data = NODEKEY(srcnode);
6992 data.mv_size = NODEDSZ(srcnode);
6993 data.mv_data = NODEDATA(srcnode);
6994 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6995 if (rc != MDB_SUCCESS)
7000 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7001 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7002 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7004 /* Unlink the src page from parent and add to free list.
7006 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7007 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7010 rc = mdb_update_key(csrc, &key);
7016 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7017 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7020 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7021 csrc->mc_db->md_leaf_pages--;
7023 csrc->mc_db->md_branch_pages--;
7025 /* Adjust other cursors pointing to mp */
7026 MDB_cursor *m2, *m3;
7027 MDB_dbi dbi = csrc->mc_dbi;
7028 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7030 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7031 if (csrc->mc_flags & C_SUB)
7032 m3 = &m2->mc_xcursor->mx_cursor;
7035 if (m3 == csrc) continue;
7036 if (m3->mc_snum < csrc->mc_snum) continue;
7037 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7038 m3->mc_pg[csrc->mc_top] = mp;
7039 m3->mc_ki[csrc->mc_top] += nkeys;
7043 mdb_cursor_pop(csrc);
7045 return mdb_rebalance(csrc);
7048 /** Copy the contents of a cursor.
7049 * @param[in] csrc The cursor to copy from.
7050 * @param[out] cdst The cursor to copy to.
7053 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7057 cdst->mc_txn = csrc->mc_txn;
7058 cdst->mc_dbi = csrc->mc_dbi;
7059 cdst->mc_db = csrc->mc_db;
7060 cdst->mc_dbx = csrc->mc_dbx;
7061 cdst->mc_snum = csrc->mc_snum;
7062 cdst->mc_top = csrc->mc_top;
7063 cdst->mc_flags = csrc->mc_flags;
7065 for (i=0; i<csrc->mc_snum; i++) {
7066 cdst->mc_pg[i] = csrc->mc_pg[i];
7067 cdst->mc_ki[i] = csrc->mc_ki[i];
7071 /** Rebalance the tree after a delete operation.
7072 * @param[in] mc Cursor pointing to the page where rebalancing
7074 * @return 0 on success, non-zero on failure.
7077 mdb_rebalance(MDB_cursor *mc)
7081 unsigned int ptop, minkeys;
7084 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7088 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7089 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7090 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7091 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
7092 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7096 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7097 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7100 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7101 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7107 if (mc->mc_snum < 2) {
7108 MDB_page *mp = mc->mc_pg[0];
7110 DPUTS("Can't rebalance a subpage, ignoring");
7113 if (NUMKEYS(mp) == 0) {
7114 DPUTS("tree is completely empty");
7115 mc->mc_db->md_root = P_INVALID;
7116 mc->mc_db->md_depth = 0;
7117 mc->mc_db->md_leaf_pages = 0;
7118 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7121 /* Adjust cursors pointing to mp */
7124 mc->mc_flags &= ~C_INITIALIZED;
7126 MDB_cursor *m2, *m3;
7127 MDB_dbi dbi = mc->mc_dbi;
7129 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7130 if (mc->mc_flags & C_SUB)
7131 m3 = &m2->mc_xcursor->mx_cursor;
7134 if (m3->mc_snum < mc->mc_snum) continue;
7135 if (m3->mc_pg[0] == mp) {
7138 m3->mc_flags &= ~C_INITIALIZED;
7142 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7143 DPUTS("collapsing root page!");
7144 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7147 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7148 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7151 mc->mc_db->md_depth--;
7152 mc->mc_db->md_branch_pages--;
7153 mc->mc_ki[0] = mc->mc_ki[1];
7155 /* Adjust other cursors pointing to mp */
7156 MDB_cursor *m2, *m3;
7157 MDB_dbi dbi = mc->mc_dbi;
7159 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7160 if (mc->mc_flags & C_SUB)
7161 m3 = &m2->mc_xcursor->mx_cursor;
7164 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7165 if (m3->mc_pg[0] == mp) {
7169 for (i=0; i<m3->mc_snum; i++) {
7170 m3->mc_pg[i] = m3->mc_pg[i+1];
7171 m3->mc_ki[i] = m3->mc_ki[i+1];
7177 DPUTS("root page doesn't need rebalancing");
7181 /* The parent (branch page) must have at least 2 pointers,
7182 * otherwise the tree is invalid.
7184 ptop = mc->mc_top-1;
7185 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7187 /* Leaf page fill factor is below the threshold.
7188 * Try to move keys from left or right neighbor, or
7189 * merge with a neighbor page.
7194 mdb_cursor_copy(mc, &mn);
7195 mn.mc_xcursor = NULL;
7197 if (mc->mc_ki[ptop] == 0) {
7198 /* We're the leftmost leaf in our parent.
7200 DPUTS("reading right neighbor");
7202 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7203 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7206 mn.mc_ki[mn.mc_top] = 0;
7207 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7209 /* There is at least one neighbor to the left.
7211 DPUTS("reading left neighbor");
7213 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7214 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7217 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7218 mc->mc_ki[mc->mc_top] = 0;
7221 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7222 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7223 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7225 /* If the neighbor page is above threshold and has enough keys,
7226 * move one key from it. Otherwise we should try to merge them.
7227 * (A branch page must never have less than 2 keys.)
7229 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7230 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7231 return mdb_node_move(&mn, mc);
7233 if (mc->mc_ki[ptop] == 0)
7234 rc = mdb_page_merge(&mn, mc);
7236 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7237 rc = mdb_page_merge(mc, &mn);
7238 mdb_cursor_copy(&mn, mc);
7240 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7245 /** Complete a delete operation started by #mdb_cursor_del(). */
7247 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7254 mp = mc->mc_pg[mc->mc_top];
7255 ki = mc->mc_ki[mc->mc_top];
7257 /* add overflow pages to free list */
7258 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7262 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7263 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7264 (rc = mdb_ovpage_free(mc, omp)))
7267 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7268 mc->mc_db->md_entries--;
7269 rc = mdb_rebalance(mc);
7270 if (rc != MDB_SUCCESS)
7271 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7274 MDB_dbi dbi = mc->mc_dbi;
7276 mp = mc->mc_pg[mc->mc_top];
7277 nkeys = NUMKEYS(mp);
7279 /* if mc points past last node in page, find next sibling */
7280 if (mc->mc_ki[mc->mc_top] >= nkeys)
7281 mdb_cursor_sibling(mc, 1);
7283 /* Adjust other cursors pointing to mp */
7284 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7287 if (!(m2->mc_flags & C_INITIALIZED))
7289 if (m2->mc_pg[mc->mc_top] == mp) {
7290 if (m2->mc_ki[mc->mc_top] >= ki) {
7291 m2->mc_flags |= C_DEL;
7292 if (m2->mc_ki[mc->mc_top] > ki)
7293 m2->mc_ki[mc->mc_top]--;
7295 if (m2->mc_ki[mc->mc_top] >= nkeys)
7296 mdb_cursor_sibling(m2, 1);
7299 mc->mc_flags |= C_DEL;
7306 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7307 MDB_val *key, MDB_val *data)
7312 MDB_val rdata, *xdata;
7316 assert(key != NULL);
7318 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7320 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7323 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7324 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7326 if (key->mv_size > MDB_MAXKEYSIZE) {
7327 return MDB_BAD_VALSIZE;
7330 mdb_cursor_init(&mc, txn, dbi, &mx);
7333 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7334 /* must ignore any data */
7345 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7347 /* let mdb_page_split know about this cursor if needed:
7348 * delete will trigger a rebalance; if it needs to move
7349 * a node from one page to another, it will have to
7350 * update the parent's separator key(s). If the new sepkey
7351 * is larger than the current one, the parent page may
7352 * run out of space, triggering a split. We need this
7353 * cursor to be consistent until the end of the rebalance.
7355 mc.mc_flags |= C_UNTRACK;
7356 mc.mc_next = txn->mt_cursors[dbi];
7357 txn->mt_cursors[dbi] = &mc;
7358 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7359 txn->mt_cursors[dbi] = mc.mc_next;
7364 /** Split a page and insert a new node.
7365 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7366 * The cursor will be updated to point to the actual page and index where
7367 * the node got inserted after the split.
7368 * @param[in] newkey The key for the newly inserted node.
7369 * @param[in] newdata The data for the newly inserted node.
7370 * @param[in] newpgno The page number, if the new node is a branch node.
7371 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7372 * @return 0 on success, non-zero on failure.
7375 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7376 unsigned int nflags)
7379 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7382 int i, j, split_indx, nkeys, pmax;
7383 MDB_env *env = mc->mc_txn->mt_env;
7385 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7386 MDB_page *copy = NULL;
7387 MDB_page *mp, *rp, *pp;
7392 mp = mc->mc_pg[mc->mc_top];
7393 newindx = mc->mc_ki[mc->mc_top];
7394 nkeys = NUMKEYS(mp);
7396 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7397 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7398 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7400 /* Create a right sibling. */
7401 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7403 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7405 if (mc->mc_snum < 2) {
7406 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7408 /* shift current top to make room for new parent */
7409 mc->mc_pg[1] = mc->mc_pg[0];
7410 mc->mc_ki[1] = mc->mc_ki[0];
7413 mc->mc_db->md_root = pp->mp_pgno;
7414 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7415 mc->mc_db->md_depth++;
7418 /* Add left (implicit) pointer. */
7419 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7420 /* undo the pre-push */
7421 mc->mc_pg[0] = mc->mc_pg[1];
7422 mc->mc_ki[0] = mc->mc_ki[1];
7423 mc->mc_db->md_root = mp->mp_pgno;
7424 mc->mc_db->md_depth--;
7431 ptop = mc->mc_top-1;
7432 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7435 mc->mc_flags |= C_SPLITTING;
7436 mdb_cursor_copy(mc, &mn);
7437 mn.mc_pg[mn.mc_top] = rp;
7438 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7440 if (nflags & MDB_APPEND) {
7441 mn.mc_ki[mn.mc_top] = 0;
7443 split_indx = newindx;
7447 split_indx = (nkeys+1) / 2;
7452 unsigned int lsize, rsize, ksize;
7453 /* Move half of the keys to the right sibling */
7455 x = mc->mc_ki[mc->mc_top] - split_indx;
7456 ksize = mc->mc_db->md_pad;
7457 split = LEAF2KEY(mp, split_indx, ksize);
7458 rsize = (nkeys - split_indx) * ksize;
7459 lsize = (nkeys - split_indx) * sizeof(indx_t);
7460 mp->mp_lower -= lsize;
7461 rp->mp_lower += lsize;
7462 mp->mp_upper += rsize - lsize;
7463 rp->mp_upper -= rsize - lsize;
7464 sepkey.mv_size = ksize;
7465 if (newindx == split_indx) {
7466 sepkey.mv_data = newkey->mv_data;
7468 sepkey.mv_data = split;
7471 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7472 memcpy(rp->mp_ptrs, split, rsize);
7473 sepkey.mv_data = rp->mp_ptrs;
7474 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7475 memcpy(ins, newkey->mv_data, ksize);
7476 mp->mp_lower += sizeof(indx_t);
7477 mp->mp_upper -= ksize - sizeof(indx_t);
7480 memcpy(rp->mp_ptrs, split, x * ksize);
7481 ins = LEAF2KEY(rp, x, ksize);
7482 memcpy(ins, newkey->mv_data, ksize);
7483 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7484 rp->mp_lower += sizeof(indx_t);
7485 rp->mp_upper -= ksize - sizeof(indx_t);
7486 mc->mc_ki[mc->mc_top] = x;
7487 mc->mc_pg[mc->mc_top] = rp;
7490 int psize, nsize, k;
7491 /* Maximum free space in an empty page */
7492 pmax = env->me_psize - PAGEHDRSZ;
7494 nsize = mdb_leaf_size(env, newkey, newdata);
7496 nsize = mdb_branch_size(env, newkey);
7499 /* grab a page to hold a temporary copy */
7500 copy = mdb_page_malloc(mc->mc_txn, 1);
7503 copy->mp_pgno = mp->mp_pgno;
7504 copy->mp_flags = mp->mp_flags;
7505 copy->mp_lower = PAGEHDRSZ;
7506 copy->mp_upper = env->me_psize;
7508 /* prepare to insert */
7509 for (i=0, j=0; i<nkeys; i++) {
7511 copy->mp_ptrs[j++] = 0;
7513 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7516 /* When items are relatively large the split point needs
7517 * to be checked, because being off-by-one will make the
7518 * difference between success or failure in mdb_node_add.
7520 * It's also relevant if a page happens to be laid out
7521 * such that one half of its nodes are all "small" and
7522 * the other half of its nodes are "large." If the new
7523 * item is also "large" and falls on the half with
7524 * "large" nodes, it also may not fit.
7526 * As a final tweak, if the new item goes on the last
7527 * spot on the page (and thus, onto the new page), bias
7528 * the split so the new page is emptier than the old page.
7529 * This yields better packing during sequential inserts.
7531 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7532 /* Find split point */
7534 if (newindx <= split_indx || newindx >= nkeys) {
7536 k = newindx >= nkeys ? nkeys : split_indx+1;
7541 for (; i!=k; i+=j) {
7546 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7547 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7549 if (F_ISSET(node->mn_flags, F_BIGDATA))
7550 psize += sizeof(pgno_t);
7552 psize += NODEDSZ(node);
7557 split_indx = i + (j<0);
7561 /* special case: when the new node was on the last
7562 * slot we may not have tripped the break inside the loop.
7563 * In all other cases we either hit the break condition,
7564 * or the original split_indx was already safe.
7566 if (newindx >= nkeys && i == k)
7567 split_indx = nkeys-1;
7569 if (split_indx == newindx) {
7570 sepkey.mv_size = newkey->mv_size;
7571 sepkey.mv_data = newkey->mv_data;
7573 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7574 sepkey.mv_size = node->mn_ksize;
7575 sepkey.mv_data = NODEKEY(node);
7580 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7582 /* Copy separator key to the parent.
7584 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7588 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7591 if (mn.mc_snum == mc->mc_snum) {
7592 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7593 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7594 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7595 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7600 /* Right page might now have changed parent.
7601 * Check if left page also changed parent.
7603 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7604 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7605 for (i=0; i<ptop; i++) {
7606 mc->mc_pg[i] = mn.mc_pg[i];
7607 mc->mc_ki[i] = mn.mc_ki[i];
7609 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7610 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7614 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7617 mc->mc_flags ^= C_SPLITTING;
7618 if (rc != MDB_SUCCESS) {
7621 if (nflags & MDB_APPEND) {
7622 mc->mc_pg[mc->mc_top] = rp;
7623 mc->mc_ki[mc->mc_top] = 0;
7624 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7627 for (i=0; i<mc->mc_top; i++)
7628 mc->mc_ki[i] = mn.mc_ki[i];
7629 } else if (!IS_LEAF2(mp)) {
7631 mc->mc_pg[mc->mc_top] = rp;
7636 rkey.mv_data = newkey->mv_data;
7637 rkey.mv_size = newkey->mv_size;
7643 /* Update index for the new key. */
7644 mc->mc_ki[mc->mc_top] = j;
7646 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7647 rkey.mv_data = NODEKEY(node);
7648 rkey.mv_size = node->mn_ksize;
7650 xdata.mv_data = NODEDATA(node);
7651 xdata.mv_size = NODEDSZ(node);
7654 pgno = NODEPGNO(node);
7655 flags = node->mn_flags;
7658 if (!IS_LEAF(mp) && j == 0) {
7659 /* First branch index doesn't need key data. */
7663 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7665 /* return tmp page to freelist */
7666 mdb_page_free(env, copy);
7672 mc->mc_pg[mc->mc_top] = copy;
7677 } while (i != split_indx);
7679 nkeys = NUMKEYS(copy);
7680 for (i=0; i<nkeys; i++)
7681 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7682 mp->mp_lower = copy->mp_lower;
7683 mp->mp_upper = copy->mp_upper;
7684 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7685 env->me_psize - copy->mp_upper);
7687 /* reset back to original page */
7688 if (newindx < split_indx) {
7689 mc->mc_pg[mc->mc_top] = mp;
7690 if (nflags & MDB_RESERVE) {
7691 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7692 if (!(node->mn_flags & F_BIGDATA))
7693 newdata->mv_data = NODEDATA(node);
7696 mc->mc_pg[mc->mc_top] = rp;
7698 /* Make sure mc_ki is still valid.
7700 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7701 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7702 for (i=0; i<ptop; i++) {
7703 mc->mc_pg[i] = mn.mc_pg[i];
7704 mc->mc_ki[i] = mn.mc_ki[i];
7706 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7707 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7710 /* return tmp page to freelist */
7711 mdb_page_free(env, copy);
7715 /* Adjust other cursors pointing to mp */
7716 MDB_cursor *m2, *m3;
7717 MDB_dbi dbi = mc->mc_dbi;
7718 int fixup = NUMKEYS(mp);
7720 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7721 if (mc->mc_flags & C_SUB)
7722 m3 = &m2->mc_xcursor->mx_cursor;
7727 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7729 if (m3->mc_flags & C_SPLITTING)
7734 for (k=m3->mc_top; k>=0; k--) {
7735 m3->mc_ki[k+1] = m3->mc_ki[k];
7736 m3->mc_pg[k+1] = m3->mc_pg[k];
7738 if (m3->mc_ki[0] >= split_indx) {
7743 m3->mc_pg[0] = mc->mc_pg[0];
7747 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7748 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7749 m3->mc_ki[mc->mc_top]++;
7750 if (m3->mc_ki[mc->mc_top] >= fixup) {
7751 m3->mc_pg[mc->mc_top] = rp;
7752 m3->mc_ki[mc->mc_top] -= fixup;
7753 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7755 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7756 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7761 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7766 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7767 MDB_val *key, MDB_val *data, unsigned int flags)
7772 assert(key != NULL);
7773 assert(data != NULL);
7775 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7778 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7781 mdb_cursor_init(&mc, txn, dbi, &mx);
7782 return mdb_cursor_put(&mc, key, data, flags);
7786 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7788 if ((flag & CHANGEABLE) != flag)
7791 env->me_flags |= flag;
7793 env->me_flags &= ~flag;
7798 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7803 *arg = env->me_flags;
7808 mdb_env_get_path(MDB_env *env, const char **arg)
7813 *arg = env->me_path;
7817 /** Common code for #mdb_stat() and #mdb_env_stat().
7818 * @param[in] env the environment to operate in.
7819 * @param[in] db the #MDB_db record containing the stats to return.
7820 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7821 * @return 0, this function always succeeds.
7824 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7826 arg->ms_psize = env->me_psize;
7827 arg->ms_depth = db->md_depth;
7828 arg->ms_branch_pages = db->md_branch_pages;
7829 arg->ms_leaf_pages = db->md_leaf_pages;
7830 arg->ms_overflow_pages = db->md_overflow_pages;
7831 arg->ms_entries = db->md_entries;
7836 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7840 if (env == NULL || arg == NULL)
7843 toggle = mdb_env_pick_meta(env);
7845 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7849 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7853 if (env == NULL || arg == NULL)
7856 toggle = mdb_env_pick_meta(env);
7857 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7858 arg->me_mapsize = env->me_mapsize;
7859 arg->me_maxreaders = env->me_maxreaders;
7861 /* me_numreaders may be zero if this process never used any readers. Use
7862 * the shared numreader count if it exists.
7864 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7866 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7867 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7871 /** Set the default comparison functions for a database.
7872 * Called immediately after a database is opened to set the defaults.
7873 * The user can then override them with #mdb_set_compare() or
7874 * #mdb_set_dupsort().
7875 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7876 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7879 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7881 uint16_t f = txn->mt_dbs[dbi].md_flags;
7883 txn->mt_dbxs[dbi].md_cmp =
7884 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7885 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7887 txn->mt_dbxs[dbi].md_dcmp =
7888 !(f & MDB_DUPSORT) ? 0 :
7889 ((f & MDB_INTEGERDUP)
7890 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7891 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7894 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7899 int rc, dbflag, exact;
7900 unsigned int unused = 0;
7903 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7904 mdb_default_cmp(txn, FREE_DBI);
7907 if ((flags & VALID_FLAGS) != flags)
7909 if (txn->mt_flags & MDB_TXN_ERROR)
7915 if (flags & PERSISTENT_FLAGS) {
7916 uint16_t f2 = flags & PERSISTENT_FLAGS;
7917 /* make sure flag changes get committed */
7918 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7919 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7920 txn->mt_flags |= MDB_TXN_DIRTY;
7923 mdb_default_cmp(txn, MAIN_DBI);
7927 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7928 mdb_default_cmp(txn, MAIN_DBI);
7931 /* Is the DB already open? */
7933 for (i=2; i<txn->mt_numdbs; i++) {
7934 if (!txn->mt_dbxs[i].md_name.mv_size) {
7935 /* Remember this free slot */
7936 if (!unused) unused = i;
7939 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7940 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7946 /* If no free slot and max hit, fail */
7947 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7948 return MDB_DBS_FULL;
7950 /* Cannot mix named databases with some mainDB flags */
7951 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7952 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7954 /* Find the DB info */
7955 dbflag = DB_NEW|DB_VALID;
7958 key.mv_data = (void *)name;
7959 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7960 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7961 if (rc == MDB_SUCCESS) {
7962 /* make sure this is actually a DB */
7963 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7964 if (!(node->mn_flags & F_SUBDATA))
7965 return MDB_INCOMPATIBLE;
7966 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7967 /* Create if requested */
7969 data.mv_size = sizeof(MDB_db);
7970 data.mv_data = &dummy;
7971 memset(&dummy, 0, sizeof(dummy));
7972 dummy.md_root = P_INVALID;
7973 dummy.md_flags = flags & PERSISTENT_FLAGS;
7974 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7978 /* OK, got info, add to table */
7979 if (rc == MDB_SUCCESS) {
7980 unsigned int slot = unused ? unused : txn->mt_numdbs;
7981 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7982 txn->mt_dbxs[slot].md_name.mv_size = len;
7983 txn->mt_dbxs[slot].md_rel = NULL;
7984 txn->mt_dbflags[slot] = dbflag;
7985 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7987 mdb_default_cmp(txn, slot);
7996 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7998 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8001 if (txn->mt_dbflags[dbi] & DB_STALE) {
8004 /* Stale, must read the DB's root. cursor_init does it for us. */
8005 mdb_cursor_init(&mc, txn, dbi, &mx);
8007 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8010 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8013 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8015 ptr = env->me_dbxs[dbi].md_name.mv_data;
8016 env->me_dbxs[dbi].md_name.mv_data = NULL;
8017 env->me_dbxs[dbi].md_name.mv_size = 0;
8018 env->me_dbflags[dbi] = 0;
8022 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8024 /* We could return the flags for the FREE_DBI too but what's the point? */
8025 if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8027 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8031 /** Add all the DB's pages to the free list.
8032 * @param[in] mc Cursor on the DB to free.
8033 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8034 * @return 0 on success, non-zero on failure.
8037 mdb_drop0(MDB_cursor *mc, int subs)
8041 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8042 if (rc == MDB_SUCCESS) {
8043 MDB_txn *txn = mc->mc_txn;
8048 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8049 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8052 mdb_cursor_copy(mc, &mx);
8053 while (mc->mc_snum > 0) {
8054 MDB_page *mp = mc->mc_pg[mc->mc_top];
8055 unsigned n = NUMKEYS(mp);
8057 for (i=0; i<n; i++) {
8058 ni = NODEPTR(mp, i);
8059 if (ni->mn_flags & F_BIGDATA) {
8062 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8063 rc = mdb_page_get(txn, pg, &omp, NULL);
8066 assert(IS_OVERFLOW(omp));
8067 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8071 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8072 mdb_xcursor_init1(mc, ni);
8073 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8079 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8081 for (i=0; i<n; i++) {
8083 ni = NODEPTR(mp, i);
8086 mdb_midl_xappend(txn->mt_free_pgs, pg);
8091 mc->mc_ki[mc->mc_top] = i;
8092 rc = mdb_cursor_sibling(mc, 1);
8094 /* no more siblings, go back to beginning
8095 * of previous level.
8099 for (i=1; i<mc->mc_snum; i++) {
8101 mc->mc_pg[i] = mx.mc_pg[i];
8106 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8107 } else if (rc == MDB_NOTFOUND) {
8113 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8115 MDB_cursor *mc, *m2;
8118 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8121 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8124 rc = mdb_cursor_open(txn, dbi, &mc);
8128 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8129 /* Invalidate the dropped DB's cursors */
8130 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8131 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8135 /* Can't delete the main DB */
8136 if (del && dbi > MAIN_DBI) {
8137 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8139 txn->mt_dbflags[dbi] = DB_STALE;
8140 mdb_dbi_close(txn->mt_env, dbi);
8143 /* reset the DB record, mark it dirty */
8144 txn->mt_dbflags[dbi] |= DB_DIRTY;
8145 txn->mt_dbs[dbi].md_depth = 0;
8146 txn->mt_dbs[dbi].md_branch_pages = 0;
8147 txn->mt_dbs[dbi].md_leaf_pages = 0;
8148 txn->mt_dbs[dbi].md_overflow_pages = 0;
8149 txn->mt_dbs[dbi].md_entries = 0;
8150 txn->mt_dbs[dbi].md_root = P_INVALID;
8152 txn->mt_flags |= MDB_TXN_DIRTY;
8155 mdb_cursor_close(mc);
8159 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8161 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8164 txn->mt_dbxs[dbi].md_cmp = cmp;
8168 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8170 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8173 txn->mt_dbxs[dbi].md_dcmp = cmp;
8177 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8179 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8182 txn->mt_dbxs[dbi].md_rel = rel;
8186 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8188 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8191 txn->mt_dbxs[dbi].md_relctx = ctx;
8195 int mdb_env_get_maxkeysize(MDB_env *env)
8197 return MDB_MAXKEYSIZE;
8200 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8202 unsigned int i, rdrs;
8209 if (!env->me_txns) {
8210 return func("(no reader locks)\n", ctx);
8212 rdrs = env->me_txns->mti_numreaders;
8213 mr = env->me_txns->mti_readers;
8214 for (i=0; i<rdrs; i++) {
8219 if (mr[i].mr_txnid == (txnid_t)-1) {
8220 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8222 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8226 func(" pid thread txnid\n", ctx);
8228 rc = func(buf, ctx);
8234 func("(no active readers)\n", ctx);
8239 /** Insert pid into list if not already present.
8240 * return -1 if already present.
8242 static int mdb_pid_insert(pid_t *ids, pid_t pid)
8244 /* binary search of pid in list */
8246 unsigned cursor = 1;
8248 unsigned n = ids[0];
8251 unsigned pivot = n >> 1;
8252 cursor = base + pivot + 1;
8253 val = pid - ids[cursor];
8258 } else if ( val > 0 ) {
8263 /* found, so it's a duplicate */
8272 for (n = ids[0]; n > cursor; n--)
8278 int mdb_reader_check(MDB_env *env, int *dead)
8280 unsigned int i, j, rdrs;
8291 rdrs = env->me_txns->mti_numreaders;
8292 pids = malloc((rdrs+1) * sizeof(pid_t));
8296 mr = env->me_txns->mti_readers;
8298 for (i=0; i<rdrs; i++) {
8299 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8301 if (mdb_pid_insert(pids, pid) == 0) {
8302 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8304 /* Recheck, a new process may have reused pid */
8305 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8306 for (j=i; j<rdrs; j++)
8307 if (mr[j].mr_pid == pid) {
8308 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8309 (unsigned) pid, mr[j].mr_txnid));
8314 UNLOCK_MUTEX_R(env);