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-2012 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.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
60 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
61 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
67 #include <semaphore.h>
72 #include <valgrind/memcheck.h>
73 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
74 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
75 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
76 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
77 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
79 #define VGMEMP_CREATE(h,r,z)
80 #define VGMEMP_ALLOC(h,a,s)
81 #define VGMEMP_FREE(h,a)
82 #define VGMEMP_DESTROY(h)
83 #define VGMEMP_DEFINED(a,s)
87 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
88 /* Solaris just defines one or the other */
89 # define LITTLE_ENDIAN 1234
90 # define BIG_ENDIAN 4321
91 # ifdef _LITTLE_ENDIAN
92 # define BYTE_ORDER LITTLE_ENDIAN
94 # define BYTE_ORDER BIG_ENDIAN
97 # define BYTE_ORDER __BYTE_ORDER
101 #ifndef LITTLE_ENDIAN
102 #define LITTLE_ENDIAN __LITTLE_ENDIAN
105 #define BIG_ENDIAN __BIG_ENDIAN
108 #if defined(__i386) || defined(__x86_64)
109 #define MISALIGNED_OK 1
115 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
116 # error "Unknown or unsupported endianness (BYTE_ORDER)"
117 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
118 # error "Two's complement, reasonably sized integer types, please"
121 /** @defgroup internal MDB Internals
124 /** @defgroup compat Windows Compatibility Macros
125 * A bunch of macros to minimize the amount of platform-specific ifdefs
126 * needed throughout the rest of the code. When the features this library
127 * needs are similar enough to POSIX to be hidden in a one-or-two line
128 * replacement, this macro approach is used.
132 #define pthread_t DWORD
133 #define pthread_mutex_t HANDLE
134 #define pthread_key_t DWORD
135 #define pthread_self() GetCurrentThreadId()
136 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
137 #define pthread_key_delete(x) TlsFree(x)
138 #define pthread_getspecific(x) TlsGetValue(x)
139 #define pthread_setspecific(x,y) TlsSetValue(x,y)
140 #define pthread_mutex_unlock(x) ReleaseMutex(x)
141 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
142 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
143 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
144 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
145 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
146 #define getpid() GetCurrentProcessId()
147 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
148 #define ErrCode() GetLastError()
149 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
150 #define close(fd) CloseHandle(fd)
151 #define munmap(ptr,len) UnmapViewOfFile(ptr)
154 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
158 #define MDB_FDATASYNC(fd) fsync(fd)
161 #define MDB_FDATASYNC(fd) fsync(fd)
163 /** Lock the reader mutex.
165 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
166 /** Unlock the reader mutex.
168 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
170 /** Lock the writer mutex.
171 * Only a single write transaction is allowed at a time. Other writers
172 * will block waiting for this mutex.
174 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
175 /** Unlock the writer mutex.
177 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
178 #endif /* __APPLE__ */
180 /** Get the error code for the last failed system function.
182 #define ErrCode() errno
184 /** An abstraction for a file handle.
185 * On POSIX systems file handles are small integers. On Windows
186 * they're opaque pointers.
190 /** A value for an invalid file handle.
191 * Mainly used to initialize file variables and signify that they are
194 #define INVALID_HANDLE_VALUE (-1)
196 /** Get the size of a memory page for the system.
197 * This is the basic size that the platform's memory manager uses, and is
198 * fundamental to the use of memory-mapped files.
200 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
203 #if defined(_WIN32) || defined(__APPLE__)
206 #define MNAME_LEN (sizeof(pthread_mutex_t))
212 /** A flag for opening a file and requesting synchronous data writes.
213 * This is only used when writing a meta page. It's not strictly needed;
214 * we could just do a normal write and then immediately perform a flush.
215 * But if this flag is available it saves us an extra system call.
217 * @note If O_DSYNC is undefined but exists in /usr/include,
218 * preferably set some compiler flag to get the definition.
219 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
222 # define MDB_DSYNC O_DSYNC
226 /** Function for flushing the data of a file. Define this to fsync
227 * if fdatasync() is not supported.
229 #ifndef MDB_FDATASYNC
230 # define MDB_FDATASYNC fdatasync
233 /** A page number in the database.
234 * Note that 64 bit page numbers are overkill, since pages themselves
235 * already represent 12-13 bits of addressable memory, and the OS will
236 * always limit applications to a maximum of 63 bits of address space.
238 * @note In the #MDB_node structure, we only store 48 bits of this value,
239 * which thus limits us to only 60 bits of addressable data.
241 typedef MDB_ID pgno_t;
243 /** A transaction ID.
244 * See struct MDB_txn.mt_txnid for details.
246 typedef MDB_ID txnid_t;
248 /** @defgroup debug Debug Macros
252 /** Enable debug output.
253 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
254 * read from and written to the database (used for free space management).
259 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
260 # define DPRINTF (void) /* Vararg macros may be unsupported */
262 static int mdb_debug;
263 static txnid_t mdb_debug_start;
265 /** Print a debug message with printf formatting. */
266 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
267 ((void) ((mdb_debug) && \
268 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
270 # define DPRINTF(fmt, ...) ((void) 0)
272 /** Print a debug string.
273 * The string is printed literally, with no format processing.
275 #define DPUTS(arg) DPRINTF("%s", arg)
278 /** A default memory page size.
279 * The actual size is platform-dependent, but we use this for
280 * boot-strapping. We probably should not be using this any more.
281 * The #GET_PAGESIZE() macro is used to get the actual size.
283 * Note that we don't currently support Huge pages. On Linux,
284 * regular data files cannot use Huge pages, and in general
285 * Huge pages aren't actually pageable. We rely on the OS
286 * demand-pager to read our data and page it out when memory
287 * pressure from other processes is high. So until OSs have
288 * actual paging support for Huge pages, they're not viable.
290 #define MDB_PAGESIZE 4096
292 /** The minimum number of keys required in a database page.
293 * Setting this to a larger value will place a smaller bound on the
294 * maximum size of a data item. Data items larger than this size will
295 * be pushed into overflow pages instead of being stored directly in
296 * the B-tree node. This value used to default to 4. With a page size
297 * of 4096 bytes that meant that any item larger than 1024 bytes would
298 * go into an overflow page. That also meant that on average 2-3KB of
299 * each overflow page was wasted space. The value cannot be lower than
300 * 2 because then there would no longer be a tree structure. With this
301 * value, items larger than 2KB will go into overflow pages, and on
302 * average only 1KB will be wasted.
304 #define MDB_MINKEYS 2
306 /** A stamp that identifies a file as an MDB file.
307 * There's nothing special about this value other than that it is easily
308 * recognizable, and it will reflect any byte order mismatches.
310 #define MDB_MAGIC 0xBEEFC0DE
312 /** The version number for a database's file format. */
313 #define MDB_VERSION 1
315 /** The maximum size of a key in the database.
316 * While data items have essentially unbounded size, we require that
317 * keys all fit onto a regular page. This limit could be raised a bit
318 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
320 #define MAXKEYSIZE 511
325 * This is used for printing a hex dump of a key's contents.
327 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
328 /** Display a key in hex.
330 * Invoke a function to display a key in hex.
332 #define DKEY(x) mdb_dkey(x, kbuf)
334 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
338 /** An invalid page number.
339 * Mainly used to denote an empty tree.
341 #define P_INVALID (~0UL)
343 /** Test if a flag \b f is set in a flag word \b w. */
344 #define F_ISSET(w, f) (((w) & (f)) == (f))
346 /** Used for offsets within a single page.
347 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
350 typedef uint16_t indx_t;
352 /** Default size of memory map.
353 * This is certainly too small for any actual applications. Apps should always set
354 * the size explicitly using #mdb_env_set_mapsize().
356 #define DEFAULT_MAPSIZE 1048576
358 /** @defgroup readers Reader Lock Table
359 * Readers don't acquire any locks for their data access. Instead, they
360 * simply record their transaction ID in the reader table. The reader
361 * mutex is needed just to find an empty slot in the reader table. The
362 * slot's address is saved in thread-specific data so that subsequent read
363 * transactions started by the same thread need no further locking to proceed.
365 * Since the database uses multi-version concurrency control, readers don't
366 * actually need any locking. This table is used to keep track of which
367 * readers are using data from which old transactions, so that we'll know
368 * when a particular old transaction is no longer in use. Old transactions
369 * that have discarded any data pages can then have those pages reclaimed
370 * for use by a later write transaction.
372 * The lock table is constructed such that reader slots are aligned with the
373 * processor's cache line size. Any slot is only ever used by one thread.
374 * This alignment guarantees that there will be no contention or cache
375 * thrashing as threads update their own slot info, and also eliminates
376 * any need for locking when accessing a slot.
378 * A writer thread will scan every slot in the table to determine the oldest
379 * outstanding reader transaction. Any freed pages older than this will be
380 * reclaimed by the writer. The writer doesn't use any locks when scanning
381 * this table. This means that there's no guarantee that the writer will
382 * see the most up-to-date reader info, but that's not required for correct
383 * operation - all we need is to know the upper bound on the oldest reader,
384 * we don't care at all about the newest reader. So the only consequence of
385 * reading stale information here is that old pages might hang around a
386 * while longer before being reclaimed. That's actually good anyway, because
387 * the longer we delay reclaiming old pages, the more likely it is that a
388 * string of contiguous pages can be found after coalescing old pages from
389 * many old transactions together.
391 * @todo We don't actually do such coalescing yet, we grab pages from one
392 * old transaction at a time.
395 /** Number of slots in the reader table.
396 * This value was chosen somewhat arbitrarily. 126 readers plus a
397 * couple mutexes fit exactly into 8KB on my development machine.
398 * Applications should set the table size using #mdb_env_set_maxreaders().
400 #define DEFAULT_READERS 126
402 /** The size of a CPU cache line in bytes. We want our lock structures
403 * aligned to this size to avoid false cache line sharing in the
405 * This value works for most CPUs. For Itanium this should be 128.
411 /** The information we store in a single slot of the reader table.
412 * In addition to a transaction ID, we also record the process and
413 * thread ID that owns a slot, so that we can detect stale information,
414 * e.g. threads or processes that went away without cleaning up.
415 * @note We currently don't check for stale records. We simply re-init
416 * the table when we know that we're the only process opening the
419 typedef struct MDB_rxbody {
420 /** The current Transaction ID when this transaction began.
421 * Multiple readers that start at the same time will probably have the
422 * same ID here. Again, it's not important to exclude them from
423 * anything; all we need to know is which version of the DB they
424 * started from so we can avoid overwriting any data used in that
425 * particular version.
428 /** The process ID of the process owning this reader txn. */
430 /** The thread ID of the thread owning this txn. */
434 /** The actual reader record, with cacheline padding. */
435 typedef struct MDB_reader {
438 /** shorthand for mrb_txnid */
439 #define mr_txnid mru.mrx.mrb_txnid
440 #define mr_pid mru.mrx.mrb_pid
441 #define mr_tid mru.mrx.mrb_tid
442 /** cache line alignment */
443 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
447 /** The header for the reader table.
448 * The table resides in a memory-mapped file. (This is a different file
449 * than is used for the main database.)
451 * For POSIX the actual mutexes reside in the shared memory of this
452 * mapped file. On Windows, mutexes are named objects allocated by the
453 * kernel; we store the mutex names in this mapped file so that other
454 * processes can grab them. This same approach is also used on
455 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
456 * process-shared POSIX mutexes. For these cases where a named object
457 * is used, the object name is derived from a 64 bit FNV hash of the
458 * environment pathname. As such, naming collisions are extremely
459 * unlikely. If a collision occurs, the results are unpredictable.
461 typedef struct MDB_txbody {
462 /** Stamp identifying this as an MDB file. It must be set
465 /** Version number of this lock file. Must be set to #MDB_VERSION. */
466 uint32_t mtb_version;
467 #if defined(_WIN32) || defined(__APPLE__)
468 char mtb_rmname[MNAME_LEN];
470 /** Mutex protecting access to this table.
471 * This is the reader lock that #LOCK_MUTEX_R acquires.
473 pthread_mutex_t mtb_mutex;
475 /** The ID of the last transaction committed to the database.
476 * This is recorded here only for convenience; the value can always
477 * be determined by reading the main database meta pages.
480 /** The number of slots that have been used in the reader table.
481 * This always records the maximum count, it is not decremented
482 * when readers release their slots.
484 unsigned mtb_numreaders;
487 /** The actual reader table definition. */
488 typedef struct MDB_txninfo {
491 #define mti_magic mt1.mtb.mtb_magic
492 #define mti_version mt1.mtb.mtb_version
493 #define mti_mutex mt1.mtb.mtb_mutex
494 #define mti_rmname mt1.mtb.mtb_rmname
495 #define mti_txnid mt1.mtb.mtb_txnid
496 #define mti_numreaders mt1.mtb.mtb_numreaders
497 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
500 #if defined(_WIN32) || defined(__APPLE__)
501 char mt2_wmname[MNAME_LEN];
502 #define mti_wmname mt2.mt2_wmname
504 pthread_mutex_t mt2_wmutex;
505 #define mti_wmutex mt2.mt2_wmutex
507 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
509 MDB_reader mti_readers[1];
513 /** Common header for all page types.
514 * Overflow records occupy a number of contiguous pages with no
515 * headers on any page after the first.
517 typedef struct MDB_page {
518 #define mp_pgno mp_p.p_pgno
519 #define mp_next mp_p.p_next
521 pgno_t p_pgno; /**< page number */
522 void * p_next; /**< for in-memory list of freed structs */
525 /** @defgroup mdb_page Page Flags
527 * Flags for the page headers.
530 #define P_BRANCH 0x01 /**< branch page */
531 #define P_LEAF 0x02 /**< leaf page */
532 #define P_OVERFLOW 0x04 /**< overflow page */
533 #define P_META 0x08 /**< meta page */
534 #define P_DIRTY 0x10 /**< dirty page */
535 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
536 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
538 uint16_t mp_flags; /**< @ref mdb_page */
539 #define mp_lower mp_pb.pb.pb_lower
540 #define mp_upper mp_pb.pb.pb_upper
541 #define mp_pages mp_pb.pb_pages
544 indx_t pb_lower; /**< lower bound of free space */
545 indx_t pb_upper; /**< upper bound of free space */
547 uint32_t pb_pages; /**< number of overflow pages */
549 indx_t mp_ptrs[1]; /**< dynamic size */
552 /** Size of the page header, excluding dynamic data at the end */
553 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
555 /** Address of first usable data byte in a page, after the header */
556 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
558 /** Number of nodes on a page */
559 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
561 /** The amount of space remaining in the page */
562 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
564 /** The percentage of space used in the page, in tenths of a percent. */
565 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
566 ((env)->me_psize - PAGEHDRSZ))
567 /** The minimum page fill factor, in tenths of a percent.
568 * Pages emptier than this are candidates for merging.
570 #define FILL_THRESHOLD 250
572 /** Test if a page is a leaf page */
573 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
574 /** Test if a page is a LEAF2 page */
575 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
576 /** Test if a page is a branch page */
577 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
578 /** Test if a page is an overflow page */
579 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
580 /** Test if a page is a sub page */
581 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
583 /** The number of overflow pages needed to store the given size. */
584 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
586 /** Header for a single key/data pair within a page.
587 * We guarantee 2-byte alignment for nodes.
589 typedef struct MDB_node {
590 /** lo and hi are used for data size on leaf nodes and for
591 * child pgno on branch nodes. On 64 bit platforms, flags
592 * is also used for pgno. (Branch nodes have no flags).
593 * They are in host byte order in case that lets some
594 * accesses be optimized into a 32-bit word access.
596 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
597 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
598 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
599 /** @defgroup mdb_node Node Flags
601 * Flags for node headers.
604 #define F_BIGDATA 0x01 /**< data put on overflow page */
605 #define F_SUBDATA 0x02 /**< data is a sub-database */
606 #define F_DUPDATA 0x04 /**< data has duplicates */
608 /** valid flags for #mdb_node_add() */
609 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
612 unsigned short mn_flags; /**< @ref mdb_node */
613 unsigned short mn_ksize; /**< key size */
614 char mn_data[1]; /**< key and data are appended here */
617 /** Size of the node header, excluding dynamic data at the end */
618 #define NODESIZE offsetof(MDB_node, mn_data)
620 /** Bit position of top word in page number, for shifting mn_flags */
621 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
623 /** Size of a node in a branch page with a given key.
624 * This is just the node header plus the key, there is no data.
626 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
628 /** Size of a node in a leaf page with a given key and data.
629 * This is node header plus key plus data size.
631 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
633 /** Address of node \b i in page \b p */
634 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
636 /** Address of the key for the node */
637 #define NODEKEY(node) (void *)((node)->mn_data)
639 /** Address of the data for a node */
640 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
642 /** Get the page number pointed to by a branch node */
643 #define NODEPGNO(node) \
644 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
645 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
646 /** Set the page number in a branch node */
647 #define SETPGNO(node,pgno) do { \
648 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
649 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
651 /** Get the size of the data in a leaf node */
652 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
653 /** Set the size of the data for a leaf node */
654 #define SETDSZ(node,size) do { \
655 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
656 /** The size of a key in a node */
657 #define NODEKSZ(node) ((node)->mn_ksize)
659 /** Copy a page number from src to dst */
661 #define COPY_PGNO(dst,src) dst = src
663 #if SIZE_MAX > 4294967295UL
664 #define COPY_PGNO(dst,src) do { \
665 unsigned short *s, *d; \
666 s = (unsigned short *)&(src); \
667 d = (unsigned short *)&(dst); \
674 #define COPY_PGNO(dst,src) do { \
675 unsigned short *s, *d; \
676 s = (unsigned short *)&(src); \
677 d = (unsigned short *)&(dst); \
683 /** The address of a key in a LEAF2 page.
684 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
685 * There are no node headers, keys are stored contiguously.
687 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
689 /** Set the \b node's key into \b key, if requested. */
690 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
691 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
693 /** Information about a single database in the environment. */
694 typedef struct MDB_db {
695 uint32_t md_pad; /**< also ksize for LEAF2 pages */
696 uint16_t md_flags; /**< @ref mdb_open */
697 uint16_t md_depth; /**< depth of this tree */
698 pgno_t md_branch_pages; /**< number of internal pages */
699 pgno_t md_leaf_pages; /**< number of leaf pages */
700 pgno_t md_overflow_pages; /**< number of overflow pages */
701 size_t md_entries; /**< number of data items */
702 pgno_t md_root; /**< the root page of this tree */
705 /** Handle for the DB used to track free pages. */
707 /** Handle for the default DB. */
710 /** Meta page content. */
711 typedef struct MDB_meta {
712 /** Stamp identifying this as an MDB file. It must be set
715 /** Version number of this lock file. Must be set to #MDB_VERSION. */
717 void *mm_address; /**< address for fixed mapping */
718 size_t mm_mapsize; /**< size of mmap region */
719 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
720 /** The size of pages used in this DB */
721 #define mm_psize mm_dbs[0].md_pad
722 /** Any persistent environment flags. @ref mdb_env */
723 #define mm_flags mm_dbs[0].md_flags
724 pgno_t mm_last_pg; /**< last used page in file */
725 txnid_t mm_txnid; /**< txnid that committed this page */
728 /** Buffer for a stack-allocated dirty page.
729 * The members define size and alignment, and silence type
730 * aliasing warnings. They are not used directly; that could
731 * mean incorrectly using several union members in parallel.
733 typedef union MDB_pagebuf {
734 char mb_raw[MDB_PAGESIZE];
737 char mm_pad[PAGEHDRSZ];
742 /** Auxiliary DB info.
743 * The information here is mostly static/read-only. There is
744 * only a single copy of this record in the environment.
746 typedef struct MDB_dbx {
747 MDB_val md_name; /**< name of the database */
748 MDB_cmp_func *md_cmp; /**< function for comparing keys */
749 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
750 MDB_rel_func *md_rel; /**< user relocate function */
751 void *md_relctx; /**< user-provided context for md_rel */
754 /** A database transaction.
755 * Every operation requires a transaction handle.
758 MDB_txn *mt_parent; /**< parent of a nested txn */
759 MDB_txn *mt_child; /**< nested txn under this txn */
760 pgno_t mt_next_pgno; /**< next unallocated page */
761 /** The ID of this transaction. IDs are integers incrementing from 1.
762 * Only committed write transactions increment the ID. If a transaction
763 * aborts, the ID may be re-used by the next writer.
766 MDB_env *mt_env; /**< the DB environment */
767 /** The list of pages that became unused during this transaction.
771 MDB_ID2L dirty_list; /**< modified pages */
772 MDB_reader *reader; /**< this thread's slot in the reader table */
774 /** Array of records for each DB known in the environment. */
776 /** Array of MDB_db records for each known DB */
778 /** @defgroup mt_dbflag Transaction DB Flags
782 #define DB_DIRTY 0x01 /**< DB was written in this txn */
783 #define DB_STALE 0x02 /**< DB record is older than txnID */
785 /** Array of cursors for each DB */
786 MDB_cursor **mt_cursors;
787 /** Array of flags for each DB */
788 unsigned char *mt_dbflags;
789 /** Number of DB records in use. This number only ever increments;
790 * we don't decrement it when individual DB handles are closed.
794 /** @defgroup mdb_txn Transaction Flags
798 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
799 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
801 unsigned int mt_flags; /**< @ref mdb_txn */
802 /** Tracks which of the two meta pages was used at the start
803 * of this transaction.
805 unsigned int mt_toggle;
808 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
809 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
810 * raise this on a 64 bit machine.
812 #define CURSOR_STACK 32
816 /** Cursors are used for all DB operations */
818 /** Next cursor on this DB in this txn */
820 /** Original cursor if this is a shadow */
822 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
823 struct MDB_xcursor *mc_xcursor;
824 /** The transaction that owns this cursor */
826 /** The database handle this cursor operates on */
828 /** The database record for this cursor */
830 /** The database auxiliary record for this cursor */
832 /** The @ref mt_dbflag for this database */
833 unsigned char *mc_dbflag;
834 unsigned short mc_snum; /**< number of pushed pages */
835 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
836 /** @defgroup mdb_cursor Cursor Flags
838 * Cursor state flags.
841 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
842 #define C_EOF 0x02 /**< No more data */
843 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
844 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
845 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
846 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
848 unsigned int mc_flags; /**< @ref mdb_cursor */
849 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
850 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
853 /** Context for sorted-dup records.
854 * We could have gone to a fully recursive design, with arbitrarily
855 * deep nesting of sub-databases. But for now we only handle these
856 * levels - main DB, optional sub-DB, sorted-duplicate DB.
858 typedef struct MDB_xcursor {
859 /** A sub-cursor for traversing the Dup DB */
860 MDB_cursor mx_cursor;
861 /** The database record for this Dup DB */
863 /** The auxiliary DB record for this Dup DB */
865 /** The @ref mt_dbflag for this Dup DB */
866 unsigned char mx_dbflag;
869 /** A set of pages freed by an earlier transaction. */
870 typedef struct MDB_oldpages {
871 /** Usually we only read one record from the FREEDB at a time, but
872 * in case we read more, this will chain them together.
874 struct MDB_oldpages *mo_next;
875 /** The ID of the transaction in which these pages were freed. */
877 /** An #MDB_IDL of the pages */
878 pgno_t mo_pages[1]; /* dynamic */
881 /** The database environment. */
883 HANDLE me_fd; /**< The main data file */
884 HANDLE me_lfd; /**< The lock file */
885 HANDLE me_mfd; /**< just for writing the meta pages */
886 /** Failed to update the meta page. Probably an I/O error. */
887 #define MDB_FATAL_ERROR 0x80000000U
888 uint32_t me_flags; /**< @ref mdb_env */
889 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
890 unsigned int me_maxreaders; /**< size of the reader table */
891 MDB_dbi me_numdbs; /**< number of DBs opened */
892 MDB_dbi me_maxdbs; /**< size of the DB table */
893 char *me_path; /**< path to the DB files */
894 char *me_map; /**< the memory map of the data file */
895 MDB_txninfo *me_txns; /**< the memory map of the lock file */
896 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
897 MDB_txn *me_txn; /**< current write transaction */
898 size_t me_mapsize; /**< size of the data memory map */
899 off_t me_size; /**< current file size */
900 pgno_t me_maxpg; /**< me_mapsize / me_psize */
901 txnid_t me_pgfirst; /**< ID of first old page record we used */
902 txnid_t me_pglast; /**< ID of last old page record we used */
903 MDB_dbx *me_dbxs; /**< array of static DB info */
904 uint16_t *me_dbflags; /**< array of DB flags */
905 MDB_oldpages *me_pghead; /**< list of old page records */
906 MDB_oldpages *me_pgfree; /**< list of page records to free */
907 pthread_key_t me_txkey; /**< thread-key for readers */
908 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
909 /** IDL of pages that became unused in a write txn */
911 /** ID2L of pages that were written during a write txn */
912 MDB_ID2 me_dirty_list[MDB_IDL_UM_SIZE];
914 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
918 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
922 /** max number of pages to commit in one writev() call */
923 #define MDB_COMMIT_PAGES 64
924 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
925 #undef MDB_COMMIT_PAGES
926 #define MDB_COMMIT_PAGES IOV_MAX
929 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
930 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
931 static int mdb_page_touch(MDB_cursor *mc);
933 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
934 static int mdb_page_search_root(MDB_cursor *mc,
935 MDB_val *key, int modify);
936 #define MDB_PS_MODIFY 1
937 #define MDB_PS_ROOTONLY 2
938 static int mdb_page_search(MDB_cursor *mc,
939 MDB_val *key, int flags);
940 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
942 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
943 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
944 pgno_t newpgno, unsigned int nflags);
946 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
947 static int mdb_env_pick_meta(const MDB_env *env);
948 static int mdb_env_write_meta(MDB_txn *txn);
950 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
951 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
952 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
953 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
954 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
955 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
956 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
957 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
958 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
960 static int mdb_rebalance(MDB_cursor *mc);
961 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
963 static void mdb_cursor_pop(MDB_cursor *mc);
964 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
966 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
967 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
968 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
969 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
970 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
972 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
973 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
975 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
976 static void mdb_xcursor_init0(MDB_cursor *mc);
977 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
979 static int mdb_drop0(MDB_cursor *mc, int subs);
980 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
983 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
987 static SECURITY_DESCRIPTOR mdb_null_sd;
988 static SECURITY_ATTRIBUTES mdb_all_sa;
989 static int mdb_sec_inited;
992 /** Return the library version info. */
994 mdb_version(int *major, int *minor, int *patch)
996 if (major) *major = MDB_VERSION_MAJOR;
997 if (minor) *minor = MDB_VERSION_MINOR;
998 if (patch) *patch = MDB_VERSION_PATCH;
999 return MDB_VERSION_STRING;
1002 /** Table of descriptions for MDB @ref errors */
1003 static char *const mdb_errstr[] = {
1004 "MDB_KEYEXIST: Key/data pair already exists",
1005 "MDB_NOTFOUND: No matching key/data pair found",
1006 "MDB_PAGE_NOTFOUND: Requested page not found",
1007 "MDB_CORRUPTED: Located page was wrong type",
1008 "MDB_PANIC: Update of meta page failed",
1009 "MDB_VERSION_MISMATCH: Database environment version mismatch"
1013 mdb_strerror(int err)
1016 return ("Successful return: 0");
1018 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1019 return mdb_errstr[err - MDB_KEYEXIST];
1021 return strerror(err);
1025 /** Display a key in hexadecimal and return the address of the result.
1026 * @param[in] key the key to display
1027 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1028 * @return The key in hexadecimal form.
1031 mdb_dkey(MDB_val *key, char *buf)
1034 unsigned char *c = key->mv_data;
1036 if (key->mv_size > MAXKEYSIZE)
1037 return "MAXKEYSIZE";
1038 /* may want to make this a dynamic check: if the key is mostly
1039 * printable characters, print it as-is instead of converting to hex.
1043 for (i=0; i<key->mv_size; i++)
1044 ptr += sprintf(ptr, "%02x", *c++);
1046 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1051 /** Display all the keys in the page. */
1053 mdb_page_keys(MDB_page *mp)
1056 unsigned int i, nkeys;
1060 nkeys = NUMKEYS(mp);
1061 fprintf(stderr, "numkeys %d\n", nkeys);
1062 for (i=0; i<nkeys; i++) {
1063 node = NODEPTR(mp, i);
1064 key.mv_size = node->mn_ksize;
1065 key.mv_data = node->mn_data;
1066 fprintf(stderr, "key %d: %s\n", i, DKEY(&key));
1071 mdb_cursor_chk(MDB_cursor *mc)
1077 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1078 for (i=0; i<mc->mc_top; i++) {
1080 node = NODEPTR(mp, mc->mc_ki[i]);
1081 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1084 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1090 /** Count all the pages in each DB and in the freelist
1091 * and make sure it matches the actual number of pages
1094 static void mdb_audit(MDB_txn *txn)
1098 MDB_ID freecount, count;
1103 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1104 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1105 freecount += *(MDB_ID *)data.mv_data;
1106 freecount += txn->mt_dbs[0].md_branch_pages + txn->mt_dbs[0].md_leaf_pages +
1107 txn->mt_dbs[0].md_overflow_pages;
1110 for (i = 0; i<txn->mt_numdbs; i++) {
1111 count += txn->mt_dbs[i].md_branch_pages +
1112 txn->mt_dbs[i].md_leaf_pages +
1113 txn->mt_dbs[i].md_overflow_pages;
1114 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1116 mdb_cursor_init(&mc, txn, i, &mx);
1117 mdb_page_search(&mc, NULL, 0);
1121 mp = mc.mc_pg[mc.mc_top];
1122 for (j=0; j<NUMKEYS(mp); j++) {
1123 MDB_node *leaf = NODEPTR(mp, j);
1124 if (leaf->mn_flags & F_SUBDATA) {
1126 memcpy(&db, NODEDATA(leaf), sizeof(db));
1127 count += db.md_branch_pages + db.md_leaf_pages +
1128 db.md_overflow_pages;
1132 while (mdb_cursor_sibling(&mc, 1) == 0);
1135 assert(freecount + count + 2 >= txn->mt_next_pgno - 1);
1140 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1142 return txn->mt_dbxs[dbi].md_cmp(a, b);
1146 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1148 if (txn->mt_dbxs[dbi].md_dcmp)
1149 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1151 return EINVAL; /* too bad you can't distinguish this from a valid result */
1154 /** Allocate a single page.
1155 * Re-use old malloc'd pages first, otherwise just malloc.
1158 mdb_page_malloc(MDB_cursor *mc) {
1160 size_t sz = mc->mc_txn->mt_env->me_psize;
1161 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1162 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1163 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1164 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1165 } else if ((ret = malloc(sz)) != NULL) {
1166 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1171 /** Allocate pages for writing.
1172 * If there are free pages available from older transactions, they
1173 * will be re-used first. Otherwise a new page will be allocated.
1174 * @param[in] mc cursor A cursor handle identifying the transaction and
1175 * database for which we are allocating.
1176 * @param[in] num the number of pages to allocate.
1177 * @return Address of the allocated page(s). Requests for multiple pages
1178 * will always be satisfied by a single contiguous chunk of memory.
1181 mdb_page_alloc(MDB_cursor *mc, int num)
1183 MDB_txn *txn = mc->mc_txn;
1185 pgno_t pgno = P_INVALID;
1188 /* The free list won't have any content at all until txn 2 has
1189 * committed. The pages freed by txn 2 will be unreferenced
1190 * after txn 3 commits, and so will be safe to re-use in txn 4.
1192 if (txn->mt_txnid > 3) {
1194 if (!txn->mt_env->me_pghead &&
1195 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1196 /* See if there's anything in the free DB */
1200 txnid_t *kptr, oldest, last;
1202 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1203 if (!txn->mt_env->me_pgfirst) {
1204 mdb_page_search(&m2, NULL, 0);
1205 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1206 kptr = (txnid_t *)NODEKEY(leaf);
1213 last = txn->mt_env->me_pglast + 1;
1215 key.mv_data = &last;
1216 key.mv_size = sizeof(last);
1217 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1220 last = *(txnid_t *)key.mv_data;
1225 oldest = txn->mt_txnid - 1;
1226 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1227 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1228 if (mr && mr < oldest)
1233 if (oldest > last) {
1234 /* It's usable, grab it.
1239 if (!txn->mt_env->me_pgfirst) {
1240 mdb_node_read(txn, leaf, &data);
1242 txn->mt_env->me_pglast = last;
1243 if (!txn->mt_env->me_pgfirst)
1244 txn->mt_env->me_pgfirst = last;
1245 idl = (MDB_ID *) data.mv_data;
1246 /* We might have a zero-length IDL due to freelist growth
1247 * during a prior commit
1249 if (!idl[0]) goto again;
1250 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1251 mop->mo_next = txn->mt_env->me_pghead;
1252 mop->mo_txnid = last;
1253 txn->mt_env->me_pghead = mop;
1254 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1259 DPRINTF("IDL read txn %zu root %zu num %zu",
1260 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1261 for (i=0; i<idl[0]; i++) {
1262 DPRINTF("IDL %zu", idl[i+1]);
1269 if (txn->mt_env->me_pghead) {
1270 MDB_oldpages *mop = txn->mt_env->me_pghead;
1272 /* FIXME: For now, always use fresh pages. We
1273 * really ought to search the free list for a
1278 /* peel pages off tail, so we only have to truncate the list */
1279 pgno = MDB_IDL_LAST(mop->mo_pages);
1280 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1282 if (mop->mo_pages[2] > mop->mo_pages[1])
1283 mop->mo_pages[0] = 0;
1287 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1288 txn->mt_env->me_pghead = mop->mo_next;
1289 if (mc->mc_dbi == FREE_DBI) {
1290 mop->mo_next = txn->mt_env->me_pgfree;
1291 txn->mt_env->me_pgfree = mop;
1300 if (pgno == P_INVALID) {
1301 /* DB size is maxed out */
1302 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1303 DPUTS("DB size maxed out");
1307 if (txn->mt_env->me_dpages && num == 1) {
1308 np = txn->mt_env->me_dpages;
1309 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1310 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1311 txn->mt_env->me_dpages = np->mp_next;
1313 size_t sz = txn->mt_env->me_psize * num;
1314 if ((np = malloc(sz)) == NULL)
1316 VGMEMP_ALLOC(txn->mt_env, np, sz);
1318 if (pgno == P_INVALID) {
1319 np->mp_pgno = txn->mt_next_pgno;
1320 txn->mt_next_pgno += num;
1324 mid.mid = np->mp_pgno;
1326 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1331 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1332 * @param[in] mc cursor pointing to the page to be touched
1333 * @return 0 on success, non-zero on failure.
1336 mdb_page_touch(MDB_cursor *mc)
1338 MDB_page *mp = mc->mc_pg[mc->mc_top];
1341 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1343 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1345 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1346 assert(mp->mp_pgno != np->mp_pgno);
1347 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1349 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1352 mp->mp_flags |= P_DIRTY;
1355 /* Adjust other cursors pointing to mp */
1356 if (mc->mc_flags & C_SUB) {
1357 MDB_cursor *m2, *m3;
1358 MDB_dbi dbi = mc->mc_dbi-1;
1360 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1361 if (m2 == mc) continue;
1362 m3 = &m2->mc_xcursor->mx_cursor;
1363 if (m3->mc_snum < mc->mc_snum) continue;
1364 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1365 m3->mc_pg[mc->mc_top] = mp;
1371 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1372 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1373 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1374 m2->mc_pg[mc->mc_top] = mp;
1378 mc->mc_pg[mc->mc_top] = mp;
1379 /** If this page has a parent, update the parent to point to
1383 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1385 mc->mc_db->md_root = mp->mp_pgno;
1386 } else if (mc->mc_txn->mt_parent) {
1389 /* If txn has a parent, make sure the page is in our
1392 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1393 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1394 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1395 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1396 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1397 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1398 mc->mc_pg[mc->mc_top] = mp;
1404 np = mdb_page_malloc(mc);
1405 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1406 mid.mid = np->mp_pgno;
1408 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1416 mdb_env_sync(MDB_env *env, int force)
1419 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1420 if (MDB_FDATASYNC(env->me_fd))
1426 /** Make shadow copies of all of parent txn's cursors */
1428 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1430 MDB_cursor *mc, *m2;
1431 unsigned int i, j, size;
1433 for (i=0;i<src->mt_numdbs; i++) {
1434 if (src->mt_cursors[i]) {
1435 size = sizeof(MDB_cursor);
1436 if (src->mt_cursors[i]->mc_xcursor)
1437 size += sizeof(MDB_xcursor);
1438 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1445 mc->mc_db = &dst->mt_dbs[i];
1446 mc->mc_dbx = m2->mc_dbx;
1447 mc->mc_dbflag = &dst->mt_dbflags[i];
1448 mc->mc_snum = m2->mc_snum;
1449 mc->mc_top = m2->mc_top;
1450 mc->mc_flags = m2->mc_flags | C_SHADOW;
1451 for (j=0; j<mc->mc_snum; j++) {
1452 mc->mc_pg[j] = m2->mc_pg[j];
1453 mc->mc_ki[j] = m2->mc_ki[j];
1455 if (m2->mc_xcursor) {
1456 MDB_xcursor *mx, *mx2;
1457 mx = (MDB_xcursor *)(mc+1);
1458 mc->mc_xcursor = mx;
1459 mx2 = m2->mc_xcursor;
1460 mx->mx_db = mx2->mx_db;
1461 mx->mx_dbx = mx2->mx_dbx;
1462 mx->mx_dbflag = mx2->mx_dbflag;
1463 mx->mx_cursor.mc_txn = dst;
1464 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1465 mx->mx_cursor.mc_db = &mx->mx_db;
1466 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1467 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1468 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1469 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1470 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1471 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1472 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1473 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1476 mc->mc_xcursor = NULL;
1478 mc->mc_next = dst->mt_cursors[i];
1479 dst->mt_cursors[i] = mc;
1486 /** Merge shadow cursors back into parent's */
1488 mdb_cursor_merge(MDB_txn *txn)
1491 for (i=0; i<txn->mt_numdbs; i++) {
1492 if (txn->mt_cursors[i]) {
1494 while ((mc = txn->mt_cursors[i])) {
1495 txn->mt_cursors[i] = mc->mc_next;
1496 if (mc->mc_flags & C_SHADOW) {
1497 MDB_cursor *m2 = mc->mc_orig;
1499 m2->mc_snum = mc->mc_snum;
1500 m2->mc_top = mc->mc_top;
1501 for (j=0; j<mc->mc_snum; j++) {
1502 m2->mc_pg[j] = mc->mc_pg[j];
1503 m2->mc_ki[j] = mc->mc_ki[j];
1506 if (mc->mc_flags & C_ALLOCD)
1514 mdb_txn_reset0(MDB_txn *txn);
1516 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1517 * @param[in] txn the transaction handle to initialize
1518 * @return 0 on success, non-zero on failure. This can only
1519 * fail for read-only transactions, and then only if the
1520 * reader table is full.
1523 mdb_txn_renew0(MDB_txn *txn)
1525 MDB_env *env = txn->mt_env;
1529 txn->mt_numdbs = env->me_numdbs;
1530 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1532 if (txn->mt_flags & MDB_TXN_RDONLY) {
1533 MDB_reader *r = pthread_getspecific(env->me_txkey);
1535 pid_t pid = getpid();
1536 pthread_t tid = pthread_self();
1539 for (i=0; i<env->me_txns->mti_numreaders; i++)
1540 if (env->me_txns->mti_readers[i].mr_pid == 0)
1542 if (i == env->me_maxreaders) {
1543 UNLOCK_MUTEX_R(env);
1546 env->me_txns->mti_readers[i].mr_pid = pid;
1547 env->me_txns->mti_readers[i].mr_tid = tid;
1548 if (i >= env->me_txns->mti_numreaders)
1549 env->me_txns->mti_numreaders = i+1;
1550 UNLOCK_MUTEX_R(env);
1551 r = &env->me_txns->mti_readers[i];
1552 pthread_setspecific(env->me_txkey, r);
1554 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1555 txn->mt_toggle = txn->mt_txnid & 1;
1556 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1557 txn->mt_u.reader = r;
1561 txn->mt_txnid = env->me_txns->mti_txnid;
1562 txn->mt_toggle = txn->mt_txnid & 1;
1563 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1566 if (txn->mt_txnid == mdb_debug_start)
1569 txn->mt_u.dirty_list = env->me_dirty_list;
1570 txn->mt_u.dirty_list[0].mid = 0;
1571 txn->mt_free_pgs = env->me_free_pgs;
1572 txn->mt_free_pgs[0] = 0;
1576 /* Copy the DB info and flags */
1577 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1578 for (i=2; i<txn->mt_numdbs; i++)
1579 txn->mt_dbs[i].md_flags = env->me_dbflags[i];
1580 txn->mt_dbflags[0] = txn->mt_dbflags[1] = 0;
1581 memset(txn->mt_dbflags+2, DB_STALE, env->me_numdbs-2);
1587 mdb_txn_renew(MDB_txn *txn)
1594 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1595 DPUTS("environment had fatal error, must shutdown!");
1599 rc = mdb_txn_renew0(txn);
1600 if (rc == MDB_SUCCESS) {
1601 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1602 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1603 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1609 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1614 if (env->me_flags & MDB_FATAL_ERROR) {
1615 DPUTS("environment had fatal error, must shutdown!");
1619 /* parent already has an active child txn */
1620 if (parent->mt_child) {
1624 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1625 if (!(flags & MDB_RDONLY))
1626 size += env->me_maxdbs * sizeof(MDB_cursor *);
1628 if ((txn = calloc(1, size)) == NULL) {
1629 DPRINTF("calloc: %s", strerror(ErrCode()));
1632 txn->mt_dbs = (MDB_db *)(txn+1);
1633 if (flags & MDB_RDONLY) {
1634 txn->mt_flags |= MDB_TXN_RDONLY;
1635 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1637 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1638 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1643 txn->mt_free_pgs = mdb_midl_alloc();
1644 if (!txn->mt_free_pgs) {
1648 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1649 if (!txn->mt_u.dirty_list) {
1650 free(txn->mt_free_pgs);
1654 txn->mt_txnid = parent->mt_txnid;
1655 txn->mt_toggle = parent->mt_toggle;
1656 txn->mt_u.dirty_list[0].mid = 0;
1657 txn->mt_free_pgs[0] = 0;
1658 txn->mt_next_pgno = parent->mt_next_pgno;
1659 parent->mt_child = txn;
1660 txn->mt_parent = parent;
1661 txn->mt_numdbs = parent->mt_numdbs;
1662 txn->mt_dbxs = parent->mt_dbxs;
1663 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1664 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1665 mdb_cursor_shadow(parent, txn);
1668 rc = mdb_txn_renew0(txn);
1674 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1675 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1676 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1682 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1683 * @param[in] txn the transaction handle to reset
1686 mdb_txn_reset0(MDB_txn *txn)
1688 MDB_env *env = txn->mt_env;
1690 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1691 txn->mt_u.reader->mr_txnid = 0;
1697 /* close(free) all cursors */
1698 for (i=0; i<txn->mt_numdbs; i++) {
1699 if (txn->mt_cursors[i]) {
1701 while ((mc = txn->mt_cursors[i])) {
1702 txn->mt_cursors[i] = mc->mc_next;
1703 if (mc->mc_flags & C_ALLOCD)
1709 /* return all dirty pages to dpage list */
1710 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1711 dp = txn->mt_u.dirty_list[i].mptr;
1712 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1713 dp->mp_next = txn->mt_env->me_dpages;
1714 VGMEMP_FREE(txn->mt_env, dp);
1715 txn->mt_env->me_dpages = dp;
1717 /* large pages just get freed directly */
1718 VGMEMP_FREE(txn->mt_env, dp);
1723 if (txn->mt_parent) {
1724 txn->mt_parent->mt_child = NULL;
1725 free(txn->mt_free_pgs);
1726 free(txn->mt_u.dirty_list);
1729 if (mdb_midl_shrink(&txn->mt_free_pgs))
1730 env->me_free_pgs = txn->mt_free_pgs;
1733 while ((mop = txn->mt_env->me_pghead)) {
1734 txn->mt_env->me_pghead = mop->mo_next;
1737 txn->mt_env->me_pgfirst = 0;
1738 txn->mt_env->me_pglast = 0;
1741 /* The writer mutex was locked in mdb_txn_begin. */
1742 UNLOCK_MUTEX_W(env);
1747 mdb_txn_reset(MDB_txn *txn)
1752 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1753 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1754 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1756 mdb_txn_reset0(txn);
1760 mdb_txn_abort(MDB_txn *txn)
1765 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1766 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1767 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1770 mdb_txn_abort(txn->mt_child);
1772 mdb_txn_reset0(txn);
1777 mdb_txn_commit(MDB_txn *txn)
1785 pgno_t next, freecnt;
1788 assert(txn != NULL);
1789 assert(txn->mt_env != NULL);
1791 if (txn->mt_child) {
1792 mdb_txn_commit(txn->mt_child);
1793 txn->mt_child = NULL;
1798 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1799 if (txn->mt_numdbs > env->me_numdbs) {
1800 /* update the DB flags */
1802 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
1803 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
1810 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1811 DPUTS("error flag is set, can't commit");
1813 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1818 /* Merge (and close) our cursors with parent's */
1819 mdb_cursor_merge(txn);
1821 if (txn->mt_parent) {
1827 /* Update parent's DB table */
1828 ip = &txn->mt_parent->mt_dbs[2];
1829 jp = &txn->mt_dbs[2];
1830 for (i = 2; i < txn->mt_numdbs; i++) {
1831 if (ip->md_root != jp->md_root)
1835 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1837 /* Append our free list to parent's */
1838 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1840 mdb_midl_free(txn->mt_free_pgs);
1842 /* Merge our dirty list with parent's */
1843 dst = txn->mt_parent->mt_u.dirty_list;
1844 src = txn->mt_u.dirty_list;
1845 x = mdb_mid2l_search(dst, src[1].mid);
1846 for (y=1; y<=src[0].mid; y++) {
1847 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1851 dst[x].mptr = src[y].mptr;
1854 for (; y<=src[0].mid; y++) {
1855 if (++x >= MDB_IDL_UM_MAX) {
1862 free(txn->mt_u.dirty_list);
1863 txn->mt_parent->mt_child = NULL;
1868 if (txn != env->me_txn) {
1869 DPUTS("attempt to commit unknown transaction");
1874 if (!txn->mt_u.dirty_list[0].mid)
1877 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1878 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1880 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1882 /* should only be one record now */
1883 if (env->me_pghead) {
1884 /* make sure first page of freeDB is touched and on freelist */
1885 mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
1888 /* Delete IDLs we used from the free list */
1889 if (env->me_pgfirst) {
1894 key.mv_size = sizeof(cur);
1895 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1898 mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1899 mdb_cursor_del(&mc, 0);
1901 env->me_pgfirst = 0;
1905 /* save to free list */
1907 freecnt = txn->mt_free_pgs[0];
1908 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1911 /* make sure last page of freeDB is touched and on freelist */
1912 key.mv_size = MAXKEYSIZE+1;
1914 mdb_page_search(&mc, &key, MDB_PS_MODIFY);
1916 mdb_midl_sort(txn->mt_free_pgs);
1920 MDB_IDL idl = txn->mt_free_pgs;
1921 DPRINTF("IDL write txn %zu root %zu num %zu",
1922 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1923 for (i=0; i<idl[0]; i++) {
1924 DPRINTF("IDL %zu", idl[i+1]);
1928 /* write to last page of freeDB */
1929 key.mv_size = sizeof(pgno_t);
1930 key.mv_data = &txn->mt_txnid;
1931 data.mv_data = txn->mt_free_pgs;
1932 /* The free list can still grow during this call,
1933 * despite the pre-emptive touches above. So check
1934 * and make sure the entire thing got written.
1937 freecnt = txn->mt_free_pgs[0];
1938 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1939 rc = mdb_cursor_put(&mc, &key, &data, 0);
1944 } while (freecnt != txn->mt_free_pgs[0]);
1946 /* should only be one record now */
1948 if (env->me_pghead) {
1954 mop = env->me_pghead;
1956 key.mv_size = sizeof(id);
1958 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1959 data.mv_data = mop->mo_pages;
1960 orig = mop->mo_pages[0];
1961 /* These steps may grow the freelist again
1962 * due to freed overflow pages...
1964 mdb_cursor_put(&mc, &key, &data, 0);
1965 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
1966 /* could have been used again here */
1967 if (mop->mo_pages[0] != orig) {
1968 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1969 data.mv_data = mop->mo_pages;
1971 mdb_cursor_put(&mc, &key, &data, 0);
1973 env->me_pghead = NULL;
1976 /* was completely used up */
1977 mdb_cursor_del(&mc, 0);
1981 env->me_pgfirst = 0;
1985 while (env->me_pgfree) {
1986 MDB_oldpages *mop = env->me_pgfree;
1987 env->me_pgfree = mop->mo_next;
1991 /* Check for growth of freelist again */
1992 if (freecnt != txn->mt_free_pgs[0])
1995 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1996 if (mdb_midl_shrink(&txn->mt_free_pgs))
1997 env->me_free_pgs = txn->mt_free_pgs;
2000 /* Update DB root pointers. Their pages have already been
2001 * touched so this is all in-place and cannot fail.
2006 data.mv_size = sizeof(MDB_db);
2008 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2009 for (i = 2; i < txn->mt_numdbs; i++) {
2010 if (txn->mt_dbflags[i] & DB_DIRTY) {
2011 data.mv_data = &txn->mt_dbs[i];
2012 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2020 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2026 /* Windows actually supports scatter/gather I/O, but only on
2027 * unbuffered file handles. Since we're relying on the OS page
2028 * cache for all our data, that's self-defeating. So we just
2029 * write pages one at a time. We use the ov structure to set
2030 * the write offset, to at least save the overhead of a Seek
2034 memset(&ov, 0, sizeof(ov));
2035 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2037 dp = txn->mt_u.dirty_list[i].mptr;
2038 DPRINTF("committing page %zu", dp->mp_pgno);
2039 size = dp->mp_pgno * env->me_psize;
2040 ov.Offset = size & 0xffffffff;
2041 ov.OffsetHigh = size >> 16;
2042 ov.OffsetHigh >>= 16;
2043 /* clear dirty flag */
2044 dp->mp_flags &= ~P_DIRTY;
2045 wsize = env->me_psize;
2046 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2047 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2050 DPRINTF("WriteFile: %d", n);
2057 struct iovec iov[MDB_COMMIT_PAGES];
2061 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2062 dp = txn->mt_u.dirty_list[i].mptr;
2063 if (dp->mp_pgno != next) {
2065 rc = writev(env->me_fd, iov, n);
2069 DPUTS("short write, filesystem full?");
2071 DPRINTF("writev: %s", strerror(n));
2078 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2081 DPRINTF("committing page %zu", dp->mp_pgno);
2082 iov[n].iov_len = env->me_psize;
2083 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2084 iov[n].iov_base = (char *)dp;
2085 size += iov[n].iov_len;
2086 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2087 /* clear dirty flag */
2088 dp->mp_flags &= ~P_DIRTY;
2089 if (++n >= MDB_COMMIT_PAGES) {
2099 rc = writev(env->me_fd, iov, n);
2103 DPUTS("short write, filesystem full?");
2105 DPRINTF("writev: %s", strerror(n));
2112 /* Drop the dirty pages.
2114 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2115 dp = txn->mt_u.dirty_list[i].mptr;
2116 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2117 dp->mp_next = txn->mt_env->me_dpages;
2118 VGMEMP_FREE(txn->mt_env, dp);
2119 txn->mt_env->me_dpages = dp;
2121 VGMEMP_FREE(txn->mt_env, dp);
2124 txn->mt_u.dirty_list[i].mid = 0;
2126 txn->mt_u.dirty_list[0].mid = 0;
2128 if ((n = mdb_env_sync(env, 0)) != 0 ||
2129 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2136 if (txn->mt_numdbs > env->me_numdbs) {
2137 /* update the DB flags */
2139 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2140 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2144 UNLOCK_MUTEX_W(env);
2150 /** Read the environment parameters of a DB environment before
2151 * mapping it into memory.
2152 * @param[in] env the environment handle
2153 * @param[out] meta address of where to store the meta information
2154 * @return 0 on success, non-zero on failure.
2157 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2164 /* We don't know the page size yet, so use a minimum value.
2168 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2170 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2175 else if (rc != MDB_PAGESIZE) {
2179 DPRINTF("read: %s", strerror(err));
2183 p = (MDB_page *)&pbuf;
2185 if (!F_ISSET(p->mp_flags, P_META)) {
2186 DPRINTF("page %zu not a meta page", p->mp_pgno);
2191 if (m->mm_magic != MDB_MAGIC) {
2192 DPUTS("meta has invalid magic");
2196 if (m->mm_version != MDB_VERSION) {
2197 DPRINTF("database is version %u, expected version %u",
2198 m->mm_version, MDB_VERSION);
2199 return MDB_VERSION_MISMATCH;
2202 memcpy(meta, m, sizeof(*m));
2206 /** Write the environment parameters of a freshly created DB environment.
2207 * @param[in] env the environment handle
2208 * @param[out] meta address of where to store the meta information
2209 * @return 0 on success, non-zero on failure.
2212 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2219 DPUTS("writing new meta page");
2221 GET_PAGESIZE(psize);
2223 meta->mm_magic = MDB_MAGIC;
2224 meta->mm_version = MDB_VERSION;
2225 meta->mm_psize = psize;
2226 meta->mm_last_pg = 1;
2227 meta->mm_flags = env->me_flags & 0xffff;
2228 meta->mm_flags |= MDB_INTEGERKEY;
2229 meta->mm_dbs[0].md_root = P_INVALID;
2230 meta->mm_dbs[1].md_root = P_INVALID;
2232 p = calloc(2, psize);
2234 p->mp_flags = P_META;
2237 memcpy(m, meta, sizeof(*meta));
2239 q = (MDB_page *)((char *)p + psize);
2242 q->mp_flags = P_META;
2245 memcpy(m, meta, sizeof(*meta));
2250 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2251 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2254 rc = write(env->me_fd, p, psize * 2);
2255 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2261 /** Update the environment info to commit a transaction.
2262 * @param[in] txn the transaction that's being committed
2263 * @return 0 on success, non-zero on failure.
2266 mdb_env_write_meta(MDB_txn *txn)
2269 MDB_meta meta, metab;
2271 int rc, len, toggle;
2277 assert(txn != NULL);
2278 assert(txn->mt_env != NULL);
2280 toggle = !txn->mt_toggle;
2281 DPRINTF("writing meta page %d for root page %zu",
2282 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2286 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2287 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2289 ptr = (char *)&meta;
2290 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2291 len = sizeof(MDB_meta) - off;
2294 meta.mm_dbs[0] = txn->mt_dbs[0];
2295 meta.mm_dbs[1] = txn->mt_dbs[1];
2296 meta.mm_last_pg = txn->mt_next_pgno - 1;
2297 meta.mm_txnid = txn->mt_txnid;
2300 off += env->me_psize;
2303 /* Write to the SYNC fd */
2306 memset(&ov, 0, sizeof(ov));
2308 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2311 rc = pwrite(env->me_mfd, ptr, len, off);
2316 DPUTS("write failed, disk error?");
2317 /* On a failure, the pagecache still contains the new data.
2318 * Write some old data back, to prevent it from being used.
2319 * Use the non-SYNC fd; we know it will fail anyway.
2321 meta.mm_last_pg = metab.mm_last_pg;
2322 meta.mm_txnid = metab.mm_txnid;
2324 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2326 r2 = pwrite(env->me_fd, ptr, len, off);
2328 env->me_flags |= MDB_FATAL_ERROR;
2331 /* Memory ordering issues are irrelevant; since the entire writer
2332 * is wrapped by wmutex, all of these changes will become visible
2333 * after the wmutex is unlocked. Since the DB is multi-version,
2334 * readers will get consistent data regardless of how fresh or
2335 * how stale their view of these values is.
2337 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2342 /** Check both meta pages to see which one is newer.
2343 * @param[in] env the environment handle
2344 * @return meta toggle (0 or 1).
2347 mdb_env_pick_meta(const MDB_env *env)
2349 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2353 mdb_env_create(MDB_env **env)
2357 e = calloc(1, sizeof(MDB_env));
2361 e->me_free_pgs = mdb_midl_alloc();
2362 if (!e->me_free_pgs) {
2366 e->me_maxreaders = DEFAULT_READERS;
2368 e->me_fd = INVALID_HANDLE_VALUE;
2369 e->me_lfd = INVALID_HANDLE_VALUE;
2370 e->me_mfd = INVALID_HANDLE_VALUE;
2371 VGMEMP_CREATE(e,0,0);
2377 mdb_env_set_mapsize(MDB_env *env, size_t size)
2381 env->me_mapsize = size;
2383 env->me_maxpg = env->me_mapsize / env->me_psize;
2388 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2392 env->me_maxdbs = dbs;
2397 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2399 if (env->me_map || readers < 1)
2401 env->me_maxreaders = readers;
2406 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2408 if (!env || !readers)
2410 *readers = env->me_maxreaders;
2414 /** Further setup required for opening an MDB environment
2417 mdb_env_open2(MDB_env *env, unsigned int flags)
2423 env->me_flags = flags;
2425 memset(&meta, 0, sizeof(meta));
2427 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2430 DPUTS("new mdbenv");
2434 if (!env->me_mapsize) {
2435 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2441 LONG sizelo, sizehi;
2442 sizelo = env->me_mapsize & 0xffffffff;
2443 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2445 /* Windows won't create mappings for zero length files.
2446 * Just allocate the maxsize right now.
2449 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2450 if (!SetEndOfFile(env->me_fd))
2452 SetFilePointer(env->me_fd, 0, NULL, 0);
2454 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2455 sizehi, sizelo, NULL);
2458 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2466 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2468 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2470 if (env->me_map == MAP_FAILED) {
2477 meta.mm_mapsize = env->me_mapsize;
2478 if (flags & MDB_FIXEDMAP)
2479 meta.mm_address = env->me_map;
2480 i = mdb_env_init_meta(env, &meta);
2481 if (i != MDB_SUCCESS) {
2482 munmap(env->me_map, env->me_mapsize);
2486 env->me_psize = meta.mm_psize;
2488 env->me_maxpg = env->me_mapsize / env->me_psize;
2490 p = (MDB_page *)env->me_map;
2491 env->me_metas[0] = METADATA(p);
2492 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2496 int toggle = mdb_env_pick_meta(env);
2497 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2499 DPRINTF("opened database version %u, pagesize %u",
2500 env->me_metas[0]->mm_version, env->me_psize);
2501 DPRINTF("using meta page %d", toggle);
2502 DPRINTF("depth: %u", db->md_depth);
2503 DPRINTF("entries: %zu", db->md_entries);
2504 DPRINTF("branch pages: %zu", db->md_branch_pages);
2505 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2506 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2507 DPRINTF("root: %zu", db->md_root);
2515 /** Release a reader thread's slot in the reader lock table.
2516 * This function is called automatically when a thread exits.
2517 * @param[in] ptr This points to the slot in the reader lock table.
2520 mdb_env_reader_dest(void *ptr)
2522 MDB_reader *reader = ptr;
2524 reader->mr_txnid = 0;
2530 /** Junk for arranging thread-specific callbacks on Windows. This is
2531 * necessarily platform and compiler-specific. Windows supports up
2532 * to 1088 keys. Let's assume nobody opens more than 64 environments
2533 * in a single process, for now. They can override this if needed.
2535 #ifndef MAX_TLS_KEYS
2536 #define MAX_TLS_KEYS 64
2538 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2539 static int mdb_tls_nkeys;
2541 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2545 case DLL_PROCESS_ATTACH: break;
2546 case DLL_THREAD_ATTACH: break;
2547 case DLL_THREAD_DETACH:
2548 for (i=0; i<mdb_tls_nkeys; i++) {
2549 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
2550 mdb_env_reader_dest(r);
2553 case DLL_PROCESS_DETACH: break;
2558 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2560 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2564 /* Force some symbol references.
2565 * _tls_used forces the linker to create the TLS directory if not already done
2566 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
2568 #pragma comment(linker, "/INCLUDE:_tls_used")
2569 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
2570 #pragma const_seg(".CRT$XLB")
2571 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
2572 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2575 #pragma comment(linker, "/INCLUDE:__tls_used")
2576 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
2577 #pragma data_seg(".CRT$XLB")
2578 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2580 #endif /* WIN 32/64 */
2581 #endif /* !__GNUC__ */
2584 /** Downgrade the exclusive lock on the region back to shared */
2586 mdb_env_share_locks(MDB_env *env)
2588 int toggle = mdb_env_pick_meta(env);
2590 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2595 /* First acquire a shared lock. The Unlock will
2596 * then release the existing exclusive lock.
2598 memset(&ov, 0, sizeof(ov));
2599 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2600 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2604 struct flock lock_info;
2605 /* The shared lock replaces the existing lock */
2606 memset((void *)&lock_info, 0, sizeof(lock_info));
2607 lock_info.l_type = F_RDLCK;
2608 lock_info.l_whence = SEEK_SET;
2609 lock_info.l_start = 0;
2610 lock_info.l_len = 1;
2611 fcntl(env->me_lfd, F_SETLK, &lock_info);
2615 #if defined(_WIN32) || defined(__APPLE__)
2617 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2619 * @(#) $Revision: 5.1 $
2620 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2621 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2623 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2627 * Please do not copyright this code. This code is in the public domain.
2629 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2630 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2631 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2632 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2633 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2634 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2635 * PERFORMANCE OF THIS SOFTWARE.
2638 * chongo <Landon Curt Noll> /\oo/\
2639 * http://www.isthe.com/chongo/
2641 * Share and Enjoy! :-)
2644 typedef unsigned long long mdb_hash_t;
2645 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2647 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2648 * @param[in] str string to hash
2649 * @param[in] hval initial value for hash
2650 * @return 64 bit hash
2652 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2653 * hval arg on the first call.
2656 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
2658 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
2659 unsigned char *end = s + val->mv_size;
2661 * FNV-1a hash each octet of the string
2664 /* xor the bottom with the current octet */
2665 hval ^= (mdb_hash_t)*s++;
2667 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2668 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2669 (hval << 7) + (hval << 8) + (hval << 40);
2671 /* return our new hash value */
2675 /** Hash the string and output the hash in hex.
2676 * @param[in] str string to hash
2677 * @param[out] hexbuf an array of 17 chars to hold the hash
2680 mdb_hash_hex(MDB_val *val, char *hexbuf)
2683 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
2684 for (i=0; i<8; i++) {
2685 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2691 /** Open and/or initialize the lock region for the environment.
2692 * @param[in] env The MDB environment.
2693 * @param[in] lpath The pathname of the file used for the lock region.
2694 * @param[in] mode The Unix permissions for the file, if we create it.
2695 * @param[out] excl Set to true if we got an exclusive lock on the region.
2696 * @return 0 on success, non-zero on failure.
2699 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2707 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2708 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2709 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2713 /* Try to get exclusive lock. If we succeed, then
2714 * nobody is using the lock region and we should initialize it.
2717 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2721 memset(&ov, 0, sizeof(ov));
2722 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2728 size = GetFileSize(env->me_lfd, NULL);
2734 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1)
2736 /* Lose record locks when exec*() */
2737 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
2738 fcntl(env->me_lfd, F_SETFD, fdflags);
2740 #else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
2741 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1)
2745 /* Try to get exclusive lock. If we succeed, then
2746 * nobody is using the lock region and we should initialize it.
2749 struct flock lock_info;
2750 memset((void *)&lock_info, 0, sizeof(lock_info));
2751 lock_info.l_type = F_WRLCK;
2752 lock_info.l_whence = SEEK_SET;
2753 lock_info.l_start = 0;
2754 lock_info.l_len = 1;
2755 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2759 lock_info.l_type = F_RDLCK;
2760 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2767 size = lseek(env->me_lfd, 0, SEEK_END);
2769 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2770 if (size < rsize && *excl) {
2772 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2773 if (!SetEndOfFile(env->me_lfd)) {
2778 if (ftruncate(env->me_lfd, rsize) != 0) {
2785 size = rsize - sizeof(MDB_txninfo);
2786 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2791 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2797 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2799 if (!env->me_txns) {
2804 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2806 if (m == MAP_FAILED) {
2807 env->me_txns = NULL;
2816 BY_HANDLE_FILE_INFORMATION stbuf;
2825 if (!mdb_sec_inited) {
2826 InitializeSecurityDescriptor(&mdb_null_sd,
2827 SECURITY_DESCRIPTOR_REVISION);
2828 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2829 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2830 mdb_all_sa.bInheritHandle = FALSE;
2831 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2834 GetFileInformationByHandle(env->me_lfd, &stbuf);
2835 idbuf.volume = stbuf.dwVolumeSerialNumber;
2836 idbuf.nhigh = stbuf.nFileIndexHigh;
2837 idbuf.nlow = stbuf.nFileIndexLow;
2838 val.mv_data = &idbuf;
2839 val.mv_size = sizeof(idbuf);
2840 mdb_hash_hex(&val, hexbuf);
2841 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2842 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2843 if (!env->me_rmutex) {
2847 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2848 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2849 if (!env->me_wmutex) {
2863 fstat(env->me_lfd, &stbuf);
2864 idbuf.dev = stbuf.st_dev;
2865 idbuf.ino = stbuf.st_ino;
2866 val.mv_data = &idbuf;
2867 val.mv_size = sizeof(idbuf);
2868 mdb_hash_hex(&val, hexbuf);
2869 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
2870 if (sem_unlink(env->me_txns->mti_rmname)) {
2872 if (rc != ENOENT && rc != EINVAL)
2875 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2876 if (!env->me_rmutex) {
2880 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
2881 if (sem_unlink(env->me_txns->mti_wmname)) {
2883 if (rc != ENOENT && rc != EINVAL)
2886 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2887 if (!env->me_wmutex) {
2891 #else /* __APPLE__ */
2892 pthread_mutexattr_t mattr;
2894 pthread_mutexattr_init(&mattr);
2895 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2899 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2900 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2901 #endif /* __APPLE__ */
2903 env->me_txns->mti_version = MDB_VERSION;
2904 env->me_txns->mti_magic = MDB_MAGIC;
2905 env->me_txns->mti_txnid = 0;
2906 env->me_txns->mti_numreaders = 0;
2909 if (env->me_txns->mti_magic != MDB_MAGIC) {
2910 DPUTS("lock region has invalid magic");
2914 if (env->me_txns->mti_version != MDB_VERSION) {
2915 DPRINTF("lock region is version %u, expected version %u",
2916 env->me_txns->mti_version, MDB_VERSION);
2917 rc = MDB_VERSION_MISMATCH;
2921 if (rc != EACCES && rc != EAGAIN) {
2925 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2926 if (!env->me_rmutex) {
2930 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2931 if (!env->me_wmutex) {
2937 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2938 if (!env->me_rmutex) {
2942 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2943 if (!env->me_wmutex) {
2953 env->me_lfd = INVALID_HANDLE_VALUE;
2958 /** The name of the lock file in the DB environment */
2959 #define LOCKNAME "/lock.mdb"
2960 /** The name of the data file in the DB environment */
2961 #define DATANAME "/data.mdb"
2962 /** The suffix of the lock file when no subdir is used */
2963 #define LOCKSUFF "-lock"
2966 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2968 int oflags, rc, len, excl;
2969 char *lpath, *dpath;
2972 if (flags & MDB_NOSUBDIR) {
2973 rc = len + sizeof(LOCKSUFF) + len + 1;
2975 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2980 if (flags & MDB_NOSUBDIR) {
2981 dpath = lpath + len + sizeof(LOCKSUFF);
2982 sprintf(lpath, "%s" LOCKSUFF, path);
2983 strcpy(dpath, path);
2985 dpath = lpath + len + sizeof(LOCKNAME);
2986 sprintf(lpath, "%s" LOCKNAME, path);
2987 sprintf(dpath, "%s" DATANAME, path);
2990 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2995 if (F_ISSET(flags, MDB_RDONLY)) {
2996 oflags = GENERIC_READ;
2997 len = OPEN_EXISTING;
2999 oflags = GENERIC_READ|GENERIC_WRITE;
3002 mode = FILE_ATTRIBUTE_NORMAL;
3003 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3004 NULL, len, mode, NULL);
3006 if (F_ISSET(flags, MDB_RDONLY))
3009 oflags = O_RDWR | O_CREAT;
3011 env->me_fd = open(dpath, oflags, mode);
3013 if (env->me_fd == INVALID_HANDLE_VALUE) {
3018 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
3019 if (flags & (MDB_RDONLY|MDB_NOSYNC|MDB_NOMETASYNC)) {
3020 env->me_mfd = env->me_fd;
3022 /* synchronous fd for meta writes */
3024 env->me_mfd = CreateFile(dpath, oflags,
3025 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3026 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3028 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3030 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3035 env->me_path = strdup(path);
3036 DPRINTF("opened dbenv %p", (void *) env);
3037 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3039 /* Windows TLS callbacks need help finding their TLS info. */
3040 if (mdb_tls_nkeys < MAX_TLS_KEYS)
3041 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3048 mdb_env_share_locks(env);
3050 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3051 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3052 if (!env->me_dbxs || !env->me_dbflags)
3058 if (env->me_fd != INVALID_HANDLE_VALUE) {
3060 env->me_fd = INVALID_HANDLE_VALUE;
3062 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3064 env->me_lfd = INVALID_HANDLE_VALUE;
3072 mdb_env_close(MDB_env *env)
3079 VGMEMP_DESTROY(env);
3080 while (env->me_dpages) {
3081 dp = env->me_dpages;
3082 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3083 env->me_dpages = dp->mp_next;
3087 free(env->me_dbflags);
3091 pthread_key_delete(env->me_txkey);
3093 /* Delete our key from the global list */
3095 for (i=0; i<mdb_tls_nkeys; i++)
3096 if (mdb_tls_keys[i] == env->me_txkey) {
3097 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3105 munmap(env->me_map, env->me_mapsize);
3107 if (env->me_mfd != env->me_fd)
3111 pid_t pid = getpid();
3113 for (i=0; i<env->me_txns->mti_numreaders; i++)
3114 if (env->me_txns->mti_readers[i].mr_pid == pid)
3115 env->me_txns->mti_readers[i].mr_pid = 0;
3116 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3119 mdb_midl_free(env->me_free_pgs);
3123 /** Compare two items pointing at aligned size_t's */
3125 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3127 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3128 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3131 /** Compare two items pointing at aligned int's */
3133 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3135 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3136 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3139 /** Compare two items pointing at ints of unknown alignment.
3140 * Nodes and keys are guaranteed to be 2-byte aligned.
3143 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3145 #if BYTE_ORDER == LITTLE_ENDIAN
3146 unsigned short *u, *c;
3149 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3150 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3153 } while(!x && u > (unsigned short *)a->mv_data);
3156 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3160 /** Compare two items lexically */
3162 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3169 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3175 diff = memcmp(a->mv_data, b->mv_data, len);
3176 return diff ? diff : len_diff<0 ? -1 : len_diff;
3179 /** Compare two items in reverse byte order */
3181 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3183 const unsigned char *p1, *p2, *p1_lim;
3187 p1_lim = (const unsigned char *)a->mv_data;
3188 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3189 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3191 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3197 while (p1 > p1_lim) {
3198 diff = *--p1 - *--p2;
3202 return len_diff<0 ? -1 : len_diff;
3205 /** Search for key within a page, using binary search.
3206 * Returns the smallest entry larger or equal to the key.
3207 * If exactp is non-null, stores whether the found entry was an exact match
3208 * in *exactp (1 or 0).
3209 * Updates the cursor index with the index of the found entry.
3210 * If no entry larger or equal to the key is found, returns NULL.
3213 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3215 unsigned int i = 0, nkeys;
3218 MDB_page *mp = mc->mc_pg[mc->mc_top];
3219 MDB_node *node = NULL;
3224 nkeys = NUMKEYS(mp);
3229 COPY_PGNO(pgno, mp->mp_pgno);
3230 DPRINTF("searching %u keys in %s %spage %zu",
3231 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3238 low = IS_LEAF(mp) ? 0 : 1;
3240 cmp = mc->mc_dbx->md_cmp;
3242 /* Branch pages have no data, so if using integer keys,
3243 * alignment is guaranteed. Use faster mdb_cmp_int.
3245 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3246 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3253 nodekey.mv_size = mc->mc_db->md_pad;
3254 node = NODEPTR(mp, 0); /* fake */
3255 while (low <= high) {
3256 i = (low + high) >> 1;
3257 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3258 rc = cmp(key, &nodekey);
3259 DPRINTF("found leaf index %u [%s], rc = %i",
3260 i, DKEY(&nodekey), rc);
3269 while (low <= high) {
3270 i = (low + high) >> 1;
3272 node = NODEPTR(mp, i);
3273 nodekey.mv_size = NODEKSZ(node);
3274 nodekey.mv_data = NODEKEY(node);
3276 rc = cmp(key, &nodekey);
3279 DPRINTF("found leaf index %u [%s], rc = %i",
3280 i, DKEY(&nodekey), rc);
3282 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3283 i, DKEY(&nodekey), NODEPGNO(node), rc);
3294 if (rc > 0) { /* Found entry is less than the key. */
3295 i++; /* Skip to get the smallest entry larger than key. */
3297 node = NODEPTR(mp, i);
3300 *exactp = (rc == 0);
3301 /* store the key index */
3302 mc->mc_ki[mc->mc_top] = i;
3304 /* There is no entry larger or equal to the key. */
3307 /* nodeptr is fake for LEAF2 */
3313 mdb_cursor_adjust(MDB_cursor *mc, func)
3317 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3318 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3325 /** Pop a page off the top of the cursor's stack. */
3327 mdb_cursor_pop(MDB_cursor *mc)
3332 top = mc->mc_pg[mc->mc_top];
3337 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3338 mc->mc_dbi, (void *) mc);
3342 /** Push a page onto the top of the cursor's stack. */
3344 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3346 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3347 mc->mc_dbi, (void *) mc);
3349 if (mc->mc_snum >= CURSOR_STACK) {
3350 assert(mc->mc_snum < CURSOR_STACK);
3354 mc->mc_top = mc->mc_snum++;
3355 mc->mc_pg[mc->mc_top] = mp;
3356 mc->mc_ki[mc->mc_top] = 0;
3361 /** Find the address of the page corresponding to a given page number.
3362 * @param[in] txn the transaction for this access.
3363 * @param[in] pgno the page number for the page to retrieve.
3364 * @param[out] ret address of a pointer where the page's address will be stored.
3365 * @return 0 on success, non-zero on failure.
3368 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3372 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3374 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3375 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3376 p = txn->mt_u.dirty_list[x].mptr;
3380 if (pgno < txn->mt_next_pgno)
3381 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3385 DPRINTF("page %zu not found", pgno);
3388 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3391 /** Search for the page a given key should be in.
3392 * Pushes parent pages on the cursor stack. This function continues a
3393 * search on a cursor that has already been initialized. (Usually by
3394 * #mdb_page_search() but also by #mdb_node_move().)
3395 * @param[in,out] mc the cursor for this operation.
3396 * @param[in] key the key to search for. If NULL, search for the lowest
3397 * page. (This is used by #mdb_cursor_first().)
3398 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
3399 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
3400 * @return 0 on success, non-zero on failure.
3403 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3405 MDB_page *mp = mc->mc_pg[mc->mc_top];
3410 while (IS_BRANCH(mp)) {
3414 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3415 assert(NUMKEYS(mp) > 1);
3416 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3418 if (key == NULL) /* Initialize cursor to first page. */
3420 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3421 /* cursor to last page */
3425 node = mdb_node_search(mc, key, &exact);
3427 i = NUMKEYS(mp) - 1;
3429 i = mc->mc_ki[mc->mc_top];
3438 DPRINTF("following index %u for key [%s]",
3440 assert(i < NUMKEYS(mp));
3441 node = NODEPTR(mp, i);
3443 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3446 mc->mc_ki[mc->mc_top] = i;
3447 if ((rc = mdb_cursor_push(mc, mp)))
3451 if ((rc = mdb_page_touch(mc)) != 0)
3453 mp = mc->mc_pg[mc->mc_top];
3458 DPRINTF("internal error, index points to a %02X page!?",
3460 return MDB_CORRUPTED;
3463 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3464 key ? DKEY(key) : NULL);
3469 /** Search for the page a given key should be in.
3470 * Pushes parent pages on the cursor stack. This function just sets up
3471 * the search; it finds the root page for \b mc's database and sets this
3472 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3473 * called to complete the search.
3474 * @param[in,out] mc the cursor for this operation.
3475 * @param[in] key the key to search for. If NULL, search for the lowest
3476 * page. (This is used by #mdb_cursor_first().)
3477 * @param[in] modify If true, visited pages are updated with new page numbers.
3478 * @return 0 on success, non-zero on failure.
3481 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
3486 /* Make sure the txn is still viable, then find the root from
3487 * the txn's db table.
3489 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3490 DPUTS("transaction has failed, must abort");
3493 /* Make sure we're using an up-to-date root */
3494 if (mc->mc_dbi > MAIN_DBI) {
3495 if ((*mc->mc_dbflag & DB_STALE) ||
3496 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
3498 unsigned char dbflag = 0;
3499 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3500 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
3503 if (*mc->mc_dbflag & DB_STALE) {
3506 MDB_node *leaf = mdb_node_search(&mc2,
3507 &mc->mc_dbx->md_name, &exact);
3509 return MDB_NOTFOUND;
3510 mdb_node_read(mc->mc_txn, leaf, &data);
3511 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3513 if (flags & MDB_PS_MODIFY)
3515 *mc->mc_dbflag = dbflag;
3518 root = mc->mc_db->md_root;
3520 if (root == P_INVALID) { /* Tree is empty. */
3521 DPUTS("tree is empty");
3522 return MDB_NOTFOUND;
3527 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
3528 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3534 DPRINTF("db %u root page %zu has flags 0x%X",
3535 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3537 if (flags & MDB_PS_MODIFY) {
3538 if ((rc = mdb_page_touch(mc)))
3542 if (flags & MDB_PS_ROOTONLY)
3545 return mdb_page_search_root(mc, key, flags);
3548 /** Return the data associated with a given node.
3549 * @param[in] txn The transaction for this operation.
3550 * @param[in] leaf The node being read.
3551 * @param[out] data Updated to point to the node's data.
3552 * @return 0 on success, non-zero on failure.
3555 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3557 MDB_page *omp; /* overflow page */
3561 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3562 data->mv_size = NODEDSZ(leaf);
3563 data->mv_data = NODEDATA(leaf);
3567 /* Read overflow data.
3569 data->mv_size = NODEDSZ(leaf);
3570 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3571 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3572 DPRINTF("read overflow page %zu failed", pgno);
3575 data->mv_data = METADATA(omp);
3581 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3582 MDB_val *key, MDB_val *data)
3591 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3593 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3596 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3600 mdb_cursor_init(&mc, txn, dbi, &mx);
3601 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3604 /** Find a sibling for a page.
3605 * Replaces the page at the top of the cursor's stack with the
3606 * specified sibling, if one exists.
3607 * @param[in] mc The cursor for this operation.
3608 * @param[in] move_right Non-zero if the right sibling is requested,
3609 * otherwise the left sibling.
3610 * @return 0 on success, non-zero on failure.
3613 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3619 if (mc->mc_snum < 2) {
3620 return MDB_NOTFOUND; /* root has no siblings */
3624 DPRINTF("parent page is page %zu, index %u",
3625 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3627 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3628 : (mc->mc_ki[mc->mc_top] == 0)) {
3629 DPRINTF("no more keys left, moving to %s sibling",
3630 move_right ? "right" : "left");
3631 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3635 mc->mc_ki[mc->mc_top]++;
3637 mc->mc_ki[mc->mc_top]--;
3638 DPRINTF("just moving to %s index key %u",
3639 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3641 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3643 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3644 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3647 mdb_cursor_push(mc, mp);
3652 /** Move the cursor to the next data item. */
3654 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3660 if (mc->mc_flags & C_EOF) {
3661 return MDB_NOTFOUND;
3664 assert(mc->mc_flags & C_INITIALIZED);
3666 mp = mc->mc_pg[mc->mc_top];
3668 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3669 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3670 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3671 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3672 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3673 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3677 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3678 if (op == MDB_NEXT_DUP)
3679 return MDB_NOTFOUND;
3683 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3685 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3686 DPUTS("=====> move to next sibling page");
3687 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3688 mc->mc_flags |= C_EOF;
3689 mc->mc_flags &= ~C_INITIALIZED;
3690 return MDB_NOTFOUND;
3692 mp = mc->mc_pg[mc->mc_top];
3693 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3695 mc->mc_ki[mc->mc_top]++;
3697 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3698 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3701 key->mv_size = mc->mc_db->md_pad;
3702 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3706 assert(IS_LEAF(mp));
3707 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3709 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3710 mdb_xcursor_init1(mc, leaf);
3713 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3716 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3717 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3718 if (rc != MDB_SUCCESS)
3723 MDB_SET_KEY(leaf, key);
3727 /** Move the cursor to the previous data item. */
3729 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3735 assert(mc->mc_flags & C_INITIALIZED);
3737 mp = mc->mc_pg[mc->mc_top];
3739 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3740 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3741 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3742 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3743 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3744 if (op != MDB_PREV || rc == MDB_SUCCESS)
3747 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3748 if (op == MDB_PREV_DUP)
3749 return MDB_NOTFOUND;
3754 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3756 if (mc->mc_ki[mc->mc_top] == 0) {
3757 DPUTS("=====> move to prev sibling page");
3758 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3759 mc->mc_flags &= ~C_INITIALIZED;
3760 return MDB_NOTFOUND;
3762 mp = mc->mc_pg[mc->mc_top];
3763 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3764 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3766 mc->mc_ki[mc->mc_top]--;
3768 mc->mc_flags &= ~C_EOF;
3770 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3771 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3774 key->mv_size = mc->mc_db->md_pad;
3775 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3779 assert(IS_LEAF(mp));
3780 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3782 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3783 mdb_xcursor_init1(mc, leaf);
3786 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3789 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3790 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3791 if (rc != MDB_SUCCESS)
3796 MDB_SET_KEY(leaf, key);
3800 /** Set the cursor on a specific data item. */
3802 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3803 MDB_cursor_op op, int *exactp)
3812 assert(key->mv_size > 0);
3814 /* See if we're already on the right page */
3815 if (mc->mc_flags & C_INITIALIZED) {
3818 mp = mc->mc_pg[mc->mc_top];
3820 mc->mc_ki[mc->mc_top] = 0;
3821 return MDB_NOTFOUND;
3823 if (mp->mp_flags & P_LEAF2) {
3824 nodekey.mv_size = mc->mc_db->md_pad;
3825 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3827 leaf = NODEPTR(mp, 0);
3828 MDB_SET_KEY(leaf, &nodekey);
3830 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3832 /* Probably happens rarely, but first node on the page
3833 * was the one we wanted.
3835 mc->mc_ki[mc->mc_top] = 0;
3842 unsigned int nkeys = NUMKEYS(mp);
3844 if (mp->mp_flags & P_LEAF2) {
3845 nodekey.mv_data = LEAF2KEY(mp,
3846 nkeys-1, nodekey.mv_size);
3848 leaf = NODEPTR(mp, nkeys-1);
3849 MDB_SET_KEY(leaf, &nodekey);
3851 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3853 /* last node was the one we wanted */
3854 mc->mc_ki[mc->mc_top] = nkeys-1;
3860 /* This is definitely the right page, skip search_page */
3861 if (mp->mp_flags & P_LEAF2) {
3862 nodekey.mv_data = LEAF2KEY(mp,
3863 mc->mc_ki[mc->mc_top], nodekey.mv_size);
3865 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3866 MDB_SET_KEY(leaf, &nodekey);
3868 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3870 /* current node was the one we wanted */
3879 /* If any parents have right-sibs, search.
3880 * Otherwise, there's nothing further.
3882 for (i=0; i<mc->mc_top; i++)
3884 NUMKEYS(mc->mc_pg[i])-1)
3886 if (i == mc->mc_top) {
3887 /* There are no other pages */
3888 mc->mc_ki[mc->mc_top] = nkeys;
3889 return MDB_NOTFOUND;
3893 /* There are no other pages */
3894 mc->mc_ki[mc->mc_top] = 0;
3895 return MDB_NOTFOUND;
3899 rc = mdb_page_search(mc, key, 0);
3900 if (rc != MDB_SUCCESS)
3903 mp = mc->mc_pg[mc->mc_top];
3904 assert(IS_LEAF(mp));
3907 leaf = mdb_node_search(mc, key, exactp);
3908 if (exactp != NULL && !*exactp) {
3909 /* MDB_SET specified and not an exact match. */
3910 return MDB_NOTFOUND;
3914 DPUTS("===> inexact leaf not found, goto sibling");
3915 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3916 return rc; /* no entries matched */
3917 mp = mc->mc_pg[mc->mc_top];
3918 assert(IS_LEAF(mp));
3919 leaf = NODEPTR(mp, 0);
3923 mc->mc_flags |= C_INITIALIZED;
3924 mc->mc_flags &= ~C_EOF;
3927 key->mv_size = mc->mc_db->md_pad;
3928 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3932 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3933 mdb_xcursor_init1(mc, leaf);
3936 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3937 if (op == MDB_SET || op == MDB_SET_RANGE) {
3938 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3941 if (op == MDB_GET_BOTH) {
3947 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3948 if (rc != MDB_SUCCESS)
3951 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3953 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3955 rc = mc->mc_dbx->md_dcmp(data, &d2);
3957 if (op == MDB_GET_BOTH || rc > 0)
3958 return MDB_NOTFOUND;
3963 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3964 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3969 /* The key already matches in all other cases */
3970 if (op == MDB_SET_RANGE)
3971 MDB_SET_KEY(leaf, key);
3972 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3977 /** Move the cursor to the first item in the database. */
3979 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3984 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3985 rc = mdb_page_search(mc, NULL, 0);
3986 if (rc != MDB_SUCCESS)
3989 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3991 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3992 mc->mc_flags |= C_INITIALIZED;
3993 mc->mc_flags &= ~C_EOF;
3995 mc->mc_ki[mc->mc_top] = 0;
3997 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3998 key->mv_size = mc->mc_db->md_pad;
3999 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4004 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4005 mdb_xcursor_init1(mc, leaf);
4006 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4011 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4012 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4016 MDB_SET_KEY(leaf, key);
4020 /** Move the cursor to the last item in the database. */
4022 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4027 if (!(mc->mc_flags & C_EOF)) {
4029 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4032 lkey.mv_size = MAXKEYSIZE+1;
4033 lkey.mv_data = NULL;
4034 rc = mdb_page_search(mc, &lkey, 0);
4035 if (rc != MDB_SUCCESS)
4038 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4040 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4041 mc->mc_flags |= C_INITIALIZED|C_EOF;
4043 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4045 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4046 key->mv_size = mc->mc_db->md_pad;
4047 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4052 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4053 mdb_xcursor_init1(mc, leaf);
4054 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4059 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4060 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4065 MDB_SET_KEY(leaf, key);
4070 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4080 case MDB_GET_BOTH_RANGE:
4081 if (data == NULL || mc->mc_xcursor == NULL) {
4088 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4090 } else if (op == MDB_SET_RANGE)
4091 rc = mdb_cursor_set(mc, key, data, op, NULL);
4093 rc = mdb_cursor_set(mc, key, data, op, &exact);
4095 case MDB_GET_MULTIPLE:
4097 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4098 !(mc->mc_flags & C_INITIALIZED)) {
4103 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4104 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4107 case MDB_NEXT_MULTIPLE:
4109 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4113 if (!(mc->mc_flags & C_INITIALIZED))
4114 rc = mdb_cursor_first(mc, key, data);
4116 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4117 if (rc == MDB_SUCCESS) {
4118 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4121 mx = &mc->mc_xcursor->mx_cursor;
4122 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4124 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4125 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4133 case MDB_NEXT_NODUP:
4134 if (!(mc->mc_flags & C_INITIALIZED))
4135 rc = mdb_cursor_first(mc, key, data);
4137 rc = mdb_cursor_next(mc, key, data, op);
4141 case MDB_PREV_NODUP:
4142 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF)) {
4143 rc = mdb_cursor_last(mc, key, data);
4144 mc->mc_flags &= ~C_EOF;
4146 rc = mdb_cursor_prev(mc, key, data, op);
4149 rc = mdb_cursor_first(mc, key, data);
4153 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4154 !(mc->mc_flags & C_INITIALIZED) ||
4155 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4159 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4162 rc = mdb_cursor_last(mc, key, data);
4166 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4167 !(mc->mc_flags & C_INITIALIZED) ||
4168 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4172 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4175 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4183 /** Touch all the pages in the cursor stack.
4184 * Makes sure all the pages are writable, before attempting a write operation.
4185 * @param[in] mc The cursor to operate on.
4188 mdb_cursor_touch(MDB_cursor *mc)
4192 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4194 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4195 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4198 *mc->mc_dbflag = DB_DIRTY;
4200 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4201 rc = mdb_page_touch(mc);
4205 mc->mc_top = mc->mc_snum-1;
4210 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4213 MDB_node *leaf = NULL;
4214 MDB_val xdata, *rdata, dkey;
4217 int do_sub = 0, insert = 0;
4218 unsigned int mcount = 0;
4222 char dbuf[MAXKEYSIZE+1];
4223 unsigned int nflags;
4226 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4229 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4230 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4234 if (flags == MDB_CURRENT) {
4235 if (!(mc->mc_flags & C_INITIALIZED))
4238 } else if (mc->mc_db->md_root == P_INVALID) {
4240 /* new database, write a root leaf page */
4241 DPUTS("allocating new root leaf page");
4242 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4246 mdb_cursor_push(mc, np);
4247 mc->mc_db->md_root = np->mp_pgno;
4248 mc->mc_db->md_depth++;
4249 *mc->mc_dbflag = DB_DIRTY;
4250 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4252 np->mp_flags |= P_LEAF2;
4253 mc->mc_flags |= C_INITIALIZED;
4259 if (flags & MDB_APPEND) {
4261 rc = mdb_cursor_last(mc, &k2, &d2);
4263 rc = mc->mc_dbx->md_cmp(key, &k2);
4266 mc->mc_ki[mc->mc_top]++;
4270 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4272 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4273 DPRINTF("duplicate key [%s]", DKEY(key));
4275 return MDB_KEYEXIST;
4277 if (rc && rc != MDB_NOTFOUND)
4281 /* Cursor is positioned, now make sure all pages are writable */
4282 rc2 = mdb_cursor_touch(mc);
4287 /* The key already exists */
4288 if (rc == MDB_SUCCESS) {
4289 /* there's only a key anyway, so this is a no-op */
4290 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4291 unsigned int ksize = mc->mc_db->md_pad;
4292 if (key->mv_size != ksize)
4294 if (flags == MDB_CURRENT) {
4295 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4296 memcpy(ptr, key->mv_data, ksize);
4301 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4304 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4305 /* Was a single item before, must convert now */
4307 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4308 /* Just overwrite the current item */
4309 if (flags == MDB_CURRENT)
4312 dkey.mv_size = NODEDSZ(leaf);
4313 dkey.mv_data = NODEDATA(leaf);
4314 #if UINT_MAX < SIZE_MAX
4315 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4316 #ifdef MISALIGNED_OK
4317 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4319 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4322 /* if data matches, ignore it */
4323 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4324 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4326 /* create a fake page for the dup items */
4327 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4328 dkey.mv_data = dbuf;
4329 fp = (MDB_page *)&pbuf;
4330 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4331 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4332 fp->mp_lower = PAGEHDRSZ;
4333 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4334 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4335 fp->mp_flags |= P_LEAF2;
4336 fp->mp_pad = data->mv_size;
4337 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
4339 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4340 (dkey.mv_size & 1) + (data->mv_size & 1);
4342 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4345 xdata.mv_size = fp->mp_upper;
4350 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4351 /* See if we need to convert from fake page to subDB */
4353 unsigned int offset;
4356 fp = NODEDATA(leaf);
4357 if (flags == MDB_CURRENT) {
4359 fp->mp_flags |= P_DIRTY;
4360 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4361 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4365 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4366 offset = fp->mp_pad;
4367 if (SIZELEFT(fp) >= offset)
4369 offset *= 4; /* space for 4 more */
4371 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4373 offset += offset & 1;
4374 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4375 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4377 /* yes, convert it */
4379 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4380 dummy.md_pad = fp->mp_pad;
4381 dummy.md_flags = MDB_DUPFIXED;
4382 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4383 dummy.md_flags |= MDB_INTEGERKEY;
4386 dummy.md_branch_pages = 0;
4387 dummy.md_leaf_pages = 1;
4388 dummy.md_overflow_pages = 0;
4389 dummy.md_entries = NUMKEYS(fp);
4391 xdata.mv_size = sizeof(MDB_db);
4392 xdata.mv_data = &dummy;
4393 mp = mdb_page_alloc(mc, 1);
4396 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4397 flags |= F_DUPDATA|F_SUBDATA;
4398 dummy.md_root = mp->mp_pgno;
4400 /* no, just grow it */
4402 xdata.mv_size = NODEDSZ(leaf) + offset;
4403 xdata.mv_data = &pbuf;
4404 mp = (MDB_page *)&pbuf;
4405 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4408 mp->mp_flags = fp->mp_flags | P_DIRTY;
4409 mp->mp_pad = fp->mp_pad;
4410 mp->mp_lower = fp->mp_lower;
4411 mp->mp_upper = fp->mp_upper + offset;
4413 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4415 nsize = NODEDSZ(leaf) - fp->mp_upper;
4416 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4417 for (i=0; i<NUMKEYS(fp); i++)
4418 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4420 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4424 /* data is on sub-DB, just store it */
4425 flags |= F_DUPDATA|F_SUBDATA;
4429 /* overflow page overwrites need special handling */
4430 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4433 int ovpages, dpages;
4435 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4436 dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4437 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4438 mdb_page_get(mc->mc_txn, pg, &omp);
4439 /* Is the ov page writable and large enough? */
4440 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
4441 /* yes, overwrite it. Note in this case we don't
4442 * bother to try shrinking the node if the new data
4443 * is smaller than the overflow threshold.
4445 if (F_ISSET(flags, MDB_RESERVE))
4446 data->mv_data = METADATA(omp);
4448 memcpy(METADATA(omp), data->mv_data, data->mv_size);
4451 /* no, free ovpages */
4453 mc->mc_db->md_overflow_pages -= ovpages;
4454 for (i=0; i<ovpages; i++) {
4455 DPRINTF("freed ov page %zu", pg);
4456 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4460 } else if (NODEDSZ(leaf) == data->mv_size) {
4461 /* same size, just replace it. Note that we could
4462 * also reuse this node if the new data is smaller,
4463 * but instead we opt to shrink the node in that case.
4465 if (F_ISSET(flags, MDB_RESERVE))
4466 data->mv_data = NODEDATA(leaf);
4468 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4471 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4472 mc->mc_db->md_entries--;
4474 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4481 nflags = flags & NODE_ADD_FLAGS;
4482 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4483 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4484 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4485 nflags &= ~MDB_APPEND;
4487 nflags |= MDB_SPLIT_REPLACE;
4488 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4490 /* There is room already in this leaf page. */
4491 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4492 if (rc == 0 && !do_sub && insert) {
4493 /* Adjust other cursors pointing to mp */
4494 MDB_cursor *m2, *m3;
4495 MDB_dbi dbi = mc->mc_dbi;
4496 unsigned i = mc->mc_top;
4497 MDB_page *mp = mc->mc_pg[i];
4499 if (mc->mc_flags & C_SUB)
4502 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4503 if (mc->mc_flags & C_SUB)
4504 m3 = &m2->mc_xcursor->mx_cursor;
4507 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4508 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4515 if (rc != MDB_SUCCESS)
4516 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4518 /* Now store the actual data in the child DB. Note that we're
4519 * storing the user data in the keys field, so there are strict
4520 * size limits on dupdata. The actual data fields of the child
4521 * DB are all zero size.
4528 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4529 if (flags & MDB_CURRENT) {
4530 xflags = MDB_CURRENT;
4532 mdb_xcursor_init1(mc, leaf);
4533 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4535 /* converted, write the original data first */
4537 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4541 /* Adjust other cursors pointing to mp */
4543 unsigned i = mc->mc_top;
4544 MDB_page *mp = mc->mc_pg[i];
4546 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4547 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4548 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4549 mdb_xcursor_init1(m2, leaf);
4554 if (flags & MDB_APPENDDUP)
4555 xflags |= MDB_APPEND;
4556 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4557 if (flags & F_SUBDATA) {
4558 void *db = NODEDATA(leaf);
4559 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4562 /* sub-writes might have failed so check rc again.
4563 * Don't increment count if we just replaced an existing item.
4565 if (!rc && !(flags & MDB_CURRENT))
4566 mc->mc_db->md_entries++;
4567 if (flags & MDB_MULTIPLE) {
4569 if (mcount < data[1].mv_size) {
4570 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4571 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4581 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4586 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4589 if (!mc->mc_flags & C_INITIALIZED)
4592 rc = mdb_cursor_touch(mc);
4596 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4598 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4599 if (flags != MDB_NODUPDATA) {
4600 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4601 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4603 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4604 /* If sub-DB still has entries, we're done */
4605 if (mc->mc_xcursor->mx_db.md_entries) {
4606 if (leaf->mn_flags & F_SUBDATA) {
4607 /* update subDB info */
4608 void *db = NODEDATA(leaf);
4609 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4611 /* shrink fake page */
4612 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4614 mc->mc_db->md_entries--;
4617 /* otherwise fall thru and delete the sub-DB */
4620 if (leaf->mn_flags & F_SUBDATA) {
4621 /* add all the child DB's pages to the free list */
4622 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4623 if (rc == MDB_SUCCESS) {
4624 mc->mc_db->md_entries -=
4625 mc->mc_xcursor->mx_db.md_entries;
4630 return mdb_cursor_del0(mc, leaf);
4633 /** Allocate and initialize new pages for a database.
4634 * @param[in] mc a cursor on the database being added to.
4635 * @param[in] flags flags defining what type of page is being allocated.
4636 * @param[in] num the number of pages to allocate. This is usually 1,
4637 * unless allocating overflow pages for a large record.
4638 * @return Address of a page, or NULL on failure.
4641 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4645 if ((np = mdb_page_alloc(mc, num)) == NULL)
4647 DPRINTF("allocated new mpage %zu, page size %u",
4648 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4649 np->mp_flags = flags | P_DIRTY;
4650 np->mp_lower = PAGEHDRSZ;
4651 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4654 mc->mc_db->md_branch_pages++;
4655 else if (IS_LEAF(np))
4656 mc->mc_db->md_leaf_pages++;
4657 else if (IS_OVERFLOW(np)) {
4658 mc->mc_db->md_overflow_pages += num;
4665 /** Calculate the size of a leaf node.
4666 * The size depends on the environment's page size; if a data item
4667 * is too large it will be put onto an overflow page and the node
4668 * size will only include the key and not the data. Sizes are always
4669 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4670 * of the #MDB_node headers.
4671 * @param[in] env The environment handle.
4672 * @param[in] key The key for the node.
4673 * @param[in] data The data for the node.
4674 * @return The number of bytes needed to store the node.
4677 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4681 sz = LEAFSIZE(key, data);
4682 if (sz >= env->me_psize / MDB_MINKEYS) {
4683 /* put on overflow page */
4684 sz -= data->mv_size - sizeof(pgno_t);
4688 return sz + sizeof(indx_t);
4691 /** Calculate the size of a branch node.
4692 * The size should depend on the environment's page size but since
4693 * we currently don't support spilling large keys onto overflow
4694 * pages, it's simply the size of the #MDB_node header plus the
4695 * size of the key. Sizes are always rounded up to an even number
4696 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4697 * @param[in] env The environment handle.
4698 * @param[in] key The key for the node.
4699 * @return The number of bytes needed to store the node.
4702 mdb_branch_size(MDB_env *env, MDB_val *key)
4707 if (sz >= env->me_psize / MDB_MINKEYS) {
4708 /* put on overflow page */
4709 /* not implemented */
4710 /* sz -= key->size - sizeof(pgno_t); */
4713 return sz + sizeof(indx_t);
4716 /** Add a node to the page pointed to by the cursor.
4717 * @param[in] mc The cursor for this operation.
4718 * @param[in] indx The index on the page where the new node should be added.
4719 * @param[in] key The key for the new node.
4720 * @param[in] data The data for the new node, if any.
4721 * @param[in] pgno The page number, if adding a branch node.
4722 * @param[in] flags Flags for the node.
4723 * @return 0 on success, non-zero on failure. Possible errors are:
4725 * <li>ENOMEM - failed to allocate overflow pages for the node.
4726 * <li>ENOSPC - there is insufficient room in the page. This error
4727 * should never happen since all callers already calculate the
4728 * page's free space before calling this function.
4732 mdb_node_add(MDB_cursor *mc, indx_t indx,
4733 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4736 size_t node_size = NODESIZE;
4739 MDB_page *mp = mc->mc_pg[mc->mc_top];
4740 MDB_page *ofp = NULL; /* overflow page */
4743 assert(mp->mp_upper >= mp->mp_lower);
4745 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4746 IS_LEAF(mp) ? "leaf" : "branch",
4747 IS_SUBP(mp) ? "sub-" : "",
4748 mp->mp_pgno, indx, data ? data->mv_size : 0,
4749 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4752 /* Move higher keys up one slot. */
4753 int ksize = mc->mc_db->md_pad, dif;
4754 char *ptr = LEAF2KEY(mp, indx, ksize);
4755 dif = NUMKEYS(mp) - indx;
4757 memmove(ptr+ksize, ptr, dif*ksize);
4758 /* insert new key */
4759 memcpy(ptr, key->mv_data, ksize);
4761 /* Just using these for counting */
4762 mp->mp_lower += sizeof(indx_t);
4763 mp->mp_upper -= ksize - sizeof(indx_t);
4768 node_size += key->mv_size;
4772 if (F_ISSET(flags, F_BIGDATA)) {
4773 /* Data already on overflow page. */
4774 node_size += sizeof(pgno_t);
4775 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4776 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4777 /* Put data on overflow page. */
4778 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4779 data->mv_size, node_size+data->mv_size);
4780 node_size += sizeof(pgno_t);
4781 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4783 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4786 node_size += data->mv_size;
4789 node_size += node_size & 1;
4791 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4792 DPRINTF("not enough room in page %zu, got %u ptrs",
4793 mp->mp_pgno, NUMKEYS(mp));
4794 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4795 mp->mp_upper - mp->mp_lower);
4796 DPRINTF("node size = %zu", node_size);
4800 /* Move higher pointers up one slot. */
4801 for (i = NUMKEYS(mp); i > indx; i--)
4802 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4804 /* Adjust free space offsets. */
4805 ofs = mp->mp_upper - node_size;
4806 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4807 mp->mp_ptrs[indx] = ofs;
4809 mp->mp_lower += sizeof(indx_t);
4811 /* Write the node data. */
4812 node = NODEPTR(mp, indx);
4813 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4814 node->mn_flags = flags;
4816 SETDSZ(node,data->mv_size);
4821 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4826 if (F_ISSET(flags, F_BIGDATA))
4827 memcpy(node->mn_data + key->mv_size, data->mv_data,
4829 else if (F_ISSET(flags, MDB_RESERVE))
4830 data->mv_data = node->mn_data + key->mv_size;
4832 memcpy(node->mn_data + key->mv_size, data->mv_data,
4835 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4837 if (F_ISSET(flags, MDB_RESERVE))
4838 data->mv_data = METADATA(ofp);
4840 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4847 /** Delete the specified node from a page.
4848 * @param[in] mp The page to operate on.
4849 * @param[in] indx The index of the node to delete.
4850 * @param[in] ksize The size of a node. Only used if the page is
4851 * part of a #MDB_DUPFIXED database.
4854 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4857 indx_t i, j, numkeys, ptr;
4864 COPY_PGNO(pgno, mp->mp_pgno);
4865 DPRINTF("delete node %u on %s page %zu", indx,
4866 IS_LEAF(mp) ? "leaf" : "branch", pgno);
4869 assert(indx < NUMKEYS(mp));
4872 int x = NUMKEYS(mp) - 1 - indx;
4873 base = LEAF2KEY(mp, indx, ksize);
4875 memmove(base, base + ksize, x * ksize);
4876 mp->mp_lower -= sizeof(indx_t);
4877 mp->mp_upper += ksize - sizeof(indx_t);
4881 node = NODEPTR(mp, indx);
4882 sz = NODESIZE + node->mn_ksize;
4884 if (F_ISSET(node->mn_flags, F_BIGDATA))
4885 sz += sizeof(pgno_t);
4887 sz += NODEDSZ(node);
4891 ptr = mp->mp_ptrs[indx];
4892 numkeys = NUMKEYS(mp);
4893 for (i = j = 0; i < numkeys; i++) {
4895 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4896 if (mp->mp_ptrs[i] < ptr)
4897 mp->mp_ptrs[j] += sz;
4902 base = (char *)mp + mp->mp_upper;
4903 memmove(base + sz, base, ptr - mp->mp_upper);
4905 mp->mp_lower -= sizeof(indx_t);
4909 /** Compact the main page after deleting a node on a subpage.
4910 * @param[in] mp The main page to operate on.
4911 * @param[in] indx The index of the subpage on the main page.
4914 mdb_node_shrink(MDB_page *mp, indx_t indx)
4921 indx_t i, numkeys, ptr;
4923 node = NODEPTR(mp, indx);
4924 sp = (MDB_page *)NODEDATA(node);
4925 osize = NODEDSZ(node);
4927 delta = sp->mp_upper - sp->mp_lower;
4928 SETDSZ(node, osize - delta);
4929 xp = (MDB_page *)((char *)sp + delta);
4931 /* shift subpage upward */
4933 nsize = NUMKEYS(sp) * sp->mp_pad;
4934 memmove(METADATA(xp), METADATA(sp), nsize);
4937 nsize = osize - sp->mp_upper;
4938 numkeys = NUMKEYS(sp);
4939 for (i=numkeys-1; i>=0; i--)
4940 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4942 xp->mp_upper = sp->mp_lower;
4943 xp->mp_lower = sp->mp_lower;
4944 xp->mp_flags = sp->mp_flags;
4945 xp->mp_pad = sp->mp_pad;
4946 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4948 /* shift lower nodes upward */
4949 ptr = mp->mp_ptrs[indx];
4950 numkeys = NUMKEYS(mp);
4951 for (i = 0; i < numkeys; i++) {
4952 if (mp->mp_ptrs[i] <= ptr)
4953 mp->mp_ptrs[i] += delta;
4956 base = (char *)mp + mp->mp_upper;
4957 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4958 mp->mp_upper += delta;
4961 /** Initial setup of a sorted-dups cursor.
4962 * Sorted duplicates are implemented as a sub-database for the given key.
4963 * The duplicate data items are actually keys of the sub-database.
4964 * Operations on the duplicate data items are performed using a sub-cursor
4965 * initialized when the sub-database is first accessed. This function does
4966 * the preliminary setup of the sub-cursor, filling in the fields that
4967 * depend only on the parent DB.
4968 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4971 mdb_xcursor_init0(MDB_cursor *mc)
4973 MDB_xcursor *mx = mc->mc_xcursor;
4975 mx->mx_cursor.mc_xcursor = NULL;
4976 mx->mx_cursor.mc_txn = mc->mc_txn;
4977 mx->mx_cursor.mc_db = &mx->mx_db;
4978 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4979 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4980 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4981 mx->mx_cursor.mc_snum = 0;
4982 mx->mx_cursor.mc_top = 0;
4983 mx->mx_cursor.mc_flags = C_SUB;
4984 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4985 mx->mx_dbx.md_dcmp = NULL;
4986 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4989 /** Final setup of a sorted-dups cursor.
4990 * Sets up the fields that depend on the data from the main cursor.
4991 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4992 * @param[in] node The data containing the #MDB_db record for the
4993 * sorted-dup database.
4996 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4998 MDB_xcursor *mx = mc->mc_xcursor;
5000 if (node->mn_flags & F_SUBDATA) {
5001 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5002 mx->mx_cursor.mc_pg[0] = 0;
5003 mx->mx_cursor.mc_snum = 0;
5004 mx->mx_cursor.mc_flags = C_SUB;
5006 MDB_page *fp = NODEDATA(node);
5007 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5008 mx->mx_db.md_flags = 0;
5009 mx->mx_db.md_depth = 1;
5010 mx->mx_db.md_branch_pages = 0;
5011 mx->mx_db.md_leaf_pages = 1;
5012 mx->mx_db.md_overflow_pages = 0;
5013 mx->mx_db.md_entries = NUMKEYS(fp);
5014 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5015 mx->mx_cursor.mc_snum = 1;
5016 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5017 mx->mx_cursor.mc_top = 0;
5018 mx->mx_cursor.mc_pg[0] = fp;
5019 mx->mx_cursor.mc_ki[0] = 0;
5020 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5021 mx->mx_db.md_flags = MDB_DUPFIXED;
5022 mx->mx_db.md_pad = fp->mp_pad;
5023 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5024 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5027 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5029 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
5031 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5032 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5033 #if UINT_MAX < SIZE_MAX
5034 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5035 #ifdef MISALIGNED_OK
5036 mx->mx_dbx.md_cmp = mdb_cmp_long;
5038 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5043 /** Initialize a cursor for a given transaction and database. */
5045 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5050 mc->mc_db = &txn->mt_dbs[dbi];
5051 mc->mc_dbx = &txn->mt_dbxs[dbi];
5052 mc->mc_dbflag = &txn->mt_dbflags[dbi];
5057 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5059 mc->mc_xcursor = mx;
5060 mdb_xcursor_init0(mc);
5062 mc->mc_xcursor = NULL;
5064 if (*mc->mc_dbflag & DB_STALE) {
5065 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5070 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5073 MDB_xcursor *mx = NULL;
5074 size_t size = sizeof(MDB_cursor);
5076 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
5079 /* Allow read access to the freelist */
5080 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5083 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5084 size += sizeof(MDB_xcursor);
5086 if ((mc = malloc(size)) != NULL) {
5087 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5088 mx = (MDB_xcursor *)(mc + 1);
5090 mdb_cursor_init(mc, txn, dbi, mx);
5091 if (txn->mt_cursors) {
5092 mc->mc_next = txn->mt_cursors[dbi];
5093 txn->mt_cursors[dbi] = mc;
5095 mc->mc_flags |= C_ALLOCD;
5105 /* Return the count of duplicate data items for the current key */
5107 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5111 if (mc == NULL || countp == NULL)
5114 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5117 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5118 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5121 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5124 *countp = mc->mc_xcursor->mx_db.md_entries;
5130 mdb_cursor_close(MDB_cursor *mc)
5133 /* remove from txn, if tracked */
5134 if (mc->mc_txn->mt_cursors) {
5135 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5136 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5138 *prev = mc->mc_next;
5140 if (mc->mc_flags & C_ALLOCD)
5146 mdb_cursor_txn(MDB_cursor *mc)
5148 if (!mc) return NULL;
5153 mdb_cursor_dbi(MDB_cursor *mc)
5159 /** Replace the key for a node with a new key.
5160 * @param[in] mp The page containing the node to operate on.
5161 * @param[in] indx The index of the node to operate on.
5162 * @param[in] key The new key to use.
5163 * @return 0 on success, non-zero on failure.
5166 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5172 indx_t ptr, i, numkeys;
5175 node = NODEPTR(mp, indx);
5176 ptr = mp->mp_ptrs[indx];
5180 char kbuf2[(MAXKEYSIZE*2+1)];
5181 k2.mv_data = NODEKEY(node);
5182 k2.mv_size = node->mn_ksize;
5183 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5185 mdb_dkey(&k2, kbuf2),
5191 delta0 = delta = key->mv_size - node->mn_ksize;
5193 /* Must be 2-byte aligned. If new key is
5194 * shorter by 1, the shift will be skipped.
5196 delta += (delta & 1);
5198 if (delta > 0 && SIZELEFT(mp) < delta) {
5199 DPRINTF("OUCH! Not enough room, delta = %d", delta);
5203 numkeys = NUMKEYS(mp);
5204 for (i = 0; i < numkeys; i++) {
5205 if (mp->mp_ptrs[i] <= ptr)
5206 mp->mp_ptrs[i] -= delta;
5209 base = (char *)mp + mp->mp_upper;
5210 len = ptr - mp->mp_upper + NODESIZE;
5211 memmove(base - delta, base, len);
5212 mp->mp_upper -= delta;
5214 node = NODEPTR(mp, indx);
5217 /* But even if no shift was needed, update ksize */
5219 node->mn_ksize = key->mv_size;
5222 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5227 /** Move a node from csrc to cdst.
5230 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5236 unsigned short flags;
5240 /* Mark src and dst as dirty. */
5241 if ((rc = mdb_page_touch(csrc)) ||
5242 (rc = mdb_page_touch(cdst)))
5245 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5246 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5247 key.mv_size = csrc->mc_db->md_pad;
5248 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5250 data.mv_data = NULL;
5254 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5255 assert(!((long)srcnode&1));
5256 srcpg = NODEPGNO(srcnode);
5257 flags = srcnode->mn_flags;
5258 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5259 unsigned int snum = csrc->mc_snum;
5261 /* must find the lowest key below src */
5262 mdb_page_search_root(csrc, NULL, 0);
5263 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5264 key.mv_size = csrc->mc_db->md_pad;
5265 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5267 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5268 key.mv_size = NODEKSZ(s2);
5269 key.mv_data = NODEKEY(s2);
5271 csrc->mc_snum = snum--;
5272 csrc->mc_top = snum;
5274 key.mv_size = NODEKSZ(srcnode);
5275 key.mv_data = NODEKEY(srcnode);
5277 data.mv_size = NODEDSZ(srcnode);
5278 data.mv_data = NODEDATA(srcnode);
5280 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5281 unsigned int snum = cdst->mc_snum;
5284 /* must find the lowest key below dst */
5285 mdb_page_search_root(cdst, NULL, 0);
5286 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
5287 bkey.mv_size = cdst->mc_db->md_pad;
5288 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
5290 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5291 bkey.mv_size = NODEKSZ(s2);
5292 bkey.mv_data = NODEKEY(s2);
5294 cdst->mc_snum = snum--;
5295 cdst->mc_top = snum;
5296 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5299 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5300 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5301 csrc->mc_ki[csrc->mc_top],
5303 csrc->mc_pg[csrc->mc_top]->mp_pgno,
5304 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5306 /* Add the node to the destination page.
5308 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5309 if (rc != MDB_SUCCESS)
5312 /* Delete the node from the source page.
5314 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5317 /* Adjust other cursors pointing to mp */
5318 MDB_cursor *m2, *m3;
5319 MDB_dbi dbi = csrc->mc_dbi;
5320 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5322 if (csrc->mc_flags & C_SUB)
5325 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5326 if (m2 == csrc) continue;
5327 if (csrc->mc_flags & C_SUB)
5328 m3 = &m2->mc_xcursor->mx_cursor;
5331 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5332 csrc->mc_ki[csrc->mc_top]) {
5333 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5334 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5339 /* Update the parent separators.
5341 if (csrc->mc_ki[csrc->mc_top] == 0) {
5342 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5343 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5344 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5346 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5347 key.mv_size = NODEKSZ(srcnode);
5348 key.mv_data = NODEKEY(srcnode);
5350 DPRINTF("update separator for source page %zu to [%s]",
5351 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5352 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5353 &key)) != MDB_SUCCESS)
5356 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5358 nullkey.mv_size = 0;
5359 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5360 assert(rc == MDB_SUCCESS);
5364 if (cdst->mc_ki[cdst->mc_top] == 0) {
5365 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5366 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5367 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5369 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5370 key.mv_size = NODEKSZ(srcnode);
5371 key.mv_data = NODEKEY(srcnode);
5373 DPRINTF("update separator for destination page %zu to [%s]",
5374 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5375 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5376 &key)) != MDB_SUCCESS)
5379 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5381 nullkey.mv_size = 0;
5382 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5383 assert(rc == MDB_SUCCESS);
5390 /** Merge one page into another.
5391 * The nodes from the page pointed to by \b csrc will
5392 * be copied to the page pointed to by \b cdst and then
5393 * the \b csrc page will be freed.
5394 * @param[in] csrc Cursor pointing to the source page.
5395 * @param[in] cdst Cursor pointing to the destination page.
5398 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5406 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5407 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5409 assert(csrc->mc_snum > 1); /* can't merge root page */
5410 assert(cdst->mc_snum > 1);
5412 /* Mark dst as dirty. */
5413 if ((rc = mdb_page_touch(cdst)))
5416 /* Move all nodes from src to dst.
5418 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5419 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5420 key.mv_size = csrc->mc_db->md_pad;
5421 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5422 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5423 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5424 if (rc != MDB_SUCCESS)
5426 key.mv_data = (char *)key.mv_data + key.mv_size;
5429 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5430 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5431 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5432 unsigned int snum = csrc->mc_snum;
5434 /* must find the lowest key below src */
5435 mdb_page_search_root(csrc, NULL, 0);
5436 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5437 key.mv_size = csrc->mc_db->md_pad;
5438 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5440 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5441 key.mv_size = NODEKSZ(s2);
5442 key.mv_data = NODEKEY(s2);
5444 csrc->mc_snum = snum--;
5445 csrc->mc_top = snum;
5447 key.mv_size = srcnode->mn_ksize;
5448 key.mv_data = NODEKEY(srcnode);
5451 data.mv_size = NODEDSZ(srcnode);
5452 data.mv_data = NODEDATA(srcnode);
5453 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5454 if (rc != MDB_SUCCESS)
5459 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5460 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]), (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10);
5462 /* Unlink the src page from parent and add to free list.
5464 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5465 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5467 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5471 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5472 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5473 csrc->mc_db->md_leaf_pages--;
5475 csrc->mc_db->md_branch_pages--;
5477 /* Adjust other cursors pointing to mp */
5478 MDB_cursor *m2, *m3;
5479 MDB_dbi dbi = csrc->mc_dbi;
5480 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5482 if (csrc->mc_flags & C_SUB)
5485 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5486 if (csrc->mc_flags & C_SUB)
5487 m3 = &m2->mc_xcursor->mx_cursor;
5490 if (m3 == csrc) continue;
5491 if (m3->mc_snum < csrc->mc_snum) continue;
5492 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5493 m3->mc_pg[csrc->mc_top] = mp;
5494 m3->mc_ki[csrc->mc_top] += nkeys;
5498 mdb_cursor_pop(csrc);
5500 return mdb_rebalance(csrc);
5503 /** Copy the contents of a cursor.
5504 * @param[in] csrc The cursor to copy from.
5505 * @param[out] cdst The cursor to copy to.
5508 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5512 cdst->mc_txn = csrc->mc_txn;
5513 cdst->mc_dbi = csrc->mc_dbi;
5514 cdst->mc_db = csrc->mc_db;
5515 cdst->mc_dbx = csrc->mc_dbx;
5516 cdst->mc_snum = csrc->mc_snum;
5517 cdst->mc_top = csrc->mc_top;
5518 cdst->mc_flags = csrc->mc_flags;
5520 for (i=0; i<csrc->mc_snum; i++) {
5521 cdst->mc_pg[i] = csrc->mc_pg[i];
5522 cdst->mc_ki[i] = csrc->mc_ki[i];
5526 /** Rebalance the tree after a delete operation.
5527 * @param[in] mc Cursor pointing to the page where rebalancing
5529 * @return 0 on success, non-zero on failure.
5532 mdb_rebalance(MDB_cursor *mc)
5542 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5543 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5544 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5545 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5549 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5552 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5553 DPRINTF("no need to rebalance page %zu, above fill threshold",
5559 if (mc->mc_snum < 2) {
5560 MDB_page *mp = mc->mc_pg[0];
5561 if (NUMKEYS(mp) == 0) {
5562 DPUTS("tree is completely empty");
5563 mc->mc_db->md_root = P_INVALID;
5564 mc->mc_db->md_depth = 0;
5565 mc->mc_db->md_leaf_pages = 0;
5566 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5570 /* Adjust other cursors pointing to mp */
5571 MDB_cursor *m2, *m3;
5572 MDB_dbi dbi = mc->mc_dbi;
5574 if (mc->mc_flags & C_SUB)
5577 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5578 if (m2 == mc) continue;
5579 if (mc->mc_flags & C_SUB)
5580 m3 = &m2->mc_xcursor->mx_cursor;
5583 if (m3->mc_snum < mc->mc_snum) continue;
5584 if (m3->mc_pg[0] == mp) {
5590 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5591 DPUTS("collapsing root page!");
5592 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5593 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5594 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5597 mc->mc_db->md_depth--;
5598 mc->mc_db->md_branch_pages--;
5600 /* Adjust other cursors pointing to mp */
5601 MDB_cursor *m2, *m3;
5602 MDB_dbi dbi = mc->mc_dbi;
5604 if (mc->mc_flags & C_SUB)
5607 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5608 if (m2 == mc) continue;
5609 if (mc->mc_flags & C_SUB)
5610 m3 = &m2->mc_xcursor->mx_cursor;
5613 if (m3->mc_snum < mc->mc_snum) continue;
5614 if (m3->mc_pg[0] == mp) {
5615 m3->mc_pg[0] = mc->mc_pg[0];
5620 DPUTS("root page doesn't need rebalancing");
5624 /* The parent (branch page) must have at least 2 pointers,
5625 * otherwise the tree is invalid.
5627 ptop = mc->mc_top-1;
5628 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5630 /* Leaf page fill factor is below the threshold.
5631 * Try to move keys from left or right neighbor, or
5632 * merge with a neighbor page.
5637 mdb_cursor_copy(mc, &mn);
5638 mn.mc_xcursor = NULL;
5640 if (mc->mc_ki[ptop] == 0) {
5641 /* We're the leftmost leaf in our parent.
5643 DPUTS("reading right neighbor");
5645 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5646 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5648 mn.mc_ki[mn.mc_top] = 0;
5649 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5651 /* There is at least one neighbor to the left.
5653 DPUTS("reading left neighbor");
5655 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5656 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5658 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5659 mc->mc_ki[mc->mc_top] = 0;
5662 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5663 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10);
5665 /* If the neighbor page is above threshold and has at least two
5666 * keys, move one key from it.
5668 * Otherwise we should try to merge them.
5670 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5671 return mdb_node_move(&mn, mc);
5672 else { /* FIXME: if (has_enough_room()) */
5673 mc->mc_flags &= ~C_INITIALIZED;
5674 if (mc->mc_ki[ptop] == 0)
5675 return mdb_page_merge(&mn, mc);
5677 return mdb_page_merge(mc, &mn);
5681 /** Complete a delete operation started by #mdb_cursor_del(). */
5683 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5687 /* add overflow pages to free list */
5688 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5692 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5693 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5694 mc->mc_db->md_overflow_pages -= ovpages;
5695 for (i=0; i<ovpages; i++) {
5696 DPRINTF("freed ov page %zu", pg);
5697 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5701 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5702 mc->mc_db->md_entries--;
5703 rc = mdb_rebalance(mc);
5704 if (rc != MDB_SUCCESS)
5705 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5711 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5712 MDB_val *key, MDB_val *data)
5717 MDB_val rdata, *xdata;
5721 assert(key != NULL);
5723 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5725 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5728 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5732 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5736 mdb_cursor_init(&mc, txn, dbi, &mx);
5747 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5749 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5753 /** Split a page and insert a new node.
5754 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5755 * The cursor will be updated to point to the actual page and index where
5756 * the node got inserted after the split.
5757 * @param[in] newkey The key for the newly inserted node.
5758 * @param[in] newdata The data for the newly inserted node.
5759 * @param[in] newpgno The page number, if the new node is a branch node.
5760 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
5761 * @return 0 on success, non-zero on failure.
5764 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5765 unsigned int nflags)
5768 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
5771 unsigned int i, j, split_indx, nkeys, pmax;
5773 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5775 MDB_page *mp, *rp, *pp;
5780 mp = mc->mc_pg[mc->mc_top];
5781 newindx = mc->mc_ki[mc->mc_top];
5783 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5784 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5785 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5787 /* Create a right sibling. */
5788 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5790 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5792 if (mc->mc_snum < 2) {
5793 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5795 /* shift current top to make room for new parent */
5796 mc->mc_pg[1] = mc->mc_pg[0];
5797 mc->mc_ki[1] = mc->mc_ki[0];
5800 mc->mc_db->md_root = pp->mp_pgno;
5801 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5802 mc->mc_db->md_depth++;
5805 /* Add left (implicit) pointer. */
5806 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5807 /* undo the pre-push */
5808 mc->mc_pg[0] = mc->mc_pg[1];
5809 mc->mc_ki[0] = mc->mc_ki[1];
5810 mc->mc_db->md_root = mp->mp_pgno;
5811 mc->mc_db->md_depth--;
5818 ptop = mc->mc_top-1;
5819 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5822 mc->mc_flags |= C_SPLITTING;
5823 mdb_cursor_copy(mc, &mn);
5824 mn.mc_pg[mn.mc_top] = rp;
5825 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5827 if (nflags & MDB_APPEND) {
5828 mn.mc_ki[mn.mc_top] = 0;
5830 split_indx = newindx;
5835 nkeys = NUMKEYS(mp);
5836 split_indx = (nkeys + 1) / 2;
5837 if (newindx < split_indx)
5843 unsigned int lsize, rsize, ksize;
5844 /* Move half of the keys to the right sibling */
5846 x = mc->mc_ki[mc->mc_top] - split_indx;
5847 ksize = mc->mc_db->md_pad;
5848 split = LEAF2KEY(mp, split_indx, ksize);
5849 rsize = (nkeys - split_indx) * ksize;
5850 lsize = (nkeys - split_indx) * sizeof(indx_t);
5851 mp->mp_lower -= lsize;
5852 rp->mp_lower += lsize;
5853 mp->mp_upper += rsize - lsize;
5854 rp->mp_upper -= rsize - lsize;
5855 sepkey.mv_size = ksize;
5856 if (newindx == split_indx) {
5857 sepkey.mv_data = newkey->mv_data;
5859 sepkey.mv_data = split;
5862 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5863 memcpy(rp->mp_ptrs, split, rsize);
5864 sepkey.mv_data = rp->mp_ptrs;
5865 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5866 memcpy(ins, newkey->mv_data, ksize);
5867 mp->mp_lower += sizeof(indx_t);
5868 mp->mp_upper -= ksize - sizeof(indx_t);
5871 memcpy(rp->mp_ptrs, split, x * ksize);
5872 ins = LEAF2KEY(rp, x, ksize);
5873 memcpy(ins, newkey->mv_data, ksize);
5874 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5875 rp->mp_lower += sizeof(indx_t);
5876 rp->mp_upper -= ksize - sizeof(indx_t);
5877 mc->mc_ki[mc->mc_top] = x;
5878 mc->mc_pg[mc->mc_top] = rp;
5883 /* For leaf pages, check the split point based on what
5884 * fits where, since otherwise mdb_node_add can fail.
5886 * This check is only needed when the data items are
5887 * relatively large, such that being off by one will
5888 * make the difference between success or failure.
5889 * When the size of the data items is much smaller than
5890 * one-half of a page, this check is irrelevant.
5893 unsigned int psize, nsize;
5894 /* Maximum free space in an empty page */
5895 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5896 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5897 if ((nkeys < 20) || (nsize > pmax/4)) {
5898 if (newindx <= split_indx) {
5901 for (i=0; i<split_indx; i++) {
5902 node = NODEPTR(mp, i);
5903 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5904 if (F_ISSET(node->mn_flags, F_BIGDATA))
5905 psize += sizeof(pgno_t);
5907 psize += NODEDSZ(node);
5910 if (i == split_indx - 1 && newindx == split_indx)
5919 for (i=nkeys-1; i>=split_indx; i--) {
5920 node = NODEPTR(mp, i);
5921 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5922 if (F_ISSET(node->mn_flags, F_BIGDATA))
5923 psize += sizeof(pgno_t);
5925 psize += NODEDSZ(node);
5936 /* First find the separating key between the split pages.
5937 * The case where newindx == split_indx is ambiguous; the
5938 * new item could go to the new page or stay on the original
5939 * page. If newpos == 1 it goes to the new page.
5941 if (newindx == split_indx && newpos) {
5942 sepkey.mv_size = newkey->mv_size;
5943 sepkey.mv_data = newkey->mv_data;
5945 node = NODEPTR(mp, split_indx);
5946 sepkey.mv_size = node->mn_ksize;
5947 sepkey.mv_data = NODEKEY(node);
5951 DPRINTF("separator is [%s]", DKEY(&sepkey));
5953 /* Copy separator key to the parent.
5955 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5959 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5962 if (mn.mc_snum == mc->mc_snum) {
5963 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
5964 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
5965 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
5966 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
5971 /* Right page might now have changed parent.
5972 * Check if left page also changed parent.
5974 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5975 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5976 for (i=0; i<ptop; i++) {
5977 mc->mc_pg[i] = mn.mc_pg[i];
5978 mc->mc_ki[i] = mn.mc_ki[i];
5980 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5981 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5985 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5988 mc->mc_flags ^= C_SPLITTING;
5989 if (rc != MDB_SUCCESS) {
5992 if (nflags & MDB_APPEND) {
5993 mc->mc_pg[mc->mc_top] = rp;
5994 mc->mc_ki[mc->mc_top] = 0;
5995 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5998 for (i=0; i<mc->mc_top; i++)
5999 mc->mc_ki[i] = mn.mc_ki[i];
6006 /* Move half of the keys to the right sibling. */
6008 /* grab a page to hold a temporary copy */
6009 copy = mdb_page_malloc(mc);
6013 copy->mp_pgno = mp->mp_pgno;
6014 copy->mp_flags = mp->mp_flags;
6015 copy->mp_lower = PAGEHDRSZ;
6016 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6017 mc->mc_pg[mc->mc_top] = copy;
6018 for (i = j = 0; i <= nkeys; j++) {
6019 if (i == split_indx) {
6020 /* Insert in right sibling. */
6021 /* Reset insert index for right sibling. */
6022 if (i != newindx || (newpos ^ ins_new)) {
6024 mc->mc_pg[mc->mc_top] = rp;
6028 if (i == newindx && !ins_new) {
6029 /* Insert the original entry that caused the split. */
6030 rkey.mv_data = newkey->mv_data;
6031 rkey.mv_size = newkey->mv_size;
6040 /* Update index for the new key. */
6041 mc->mc_ki[mc->mc_top] = j;
6042 } else if (i == nkeys) {
6045 node = NODEPTR(mp, i);
6046 rkey.mv_data = NODEKEY(node);
6047 rkey.mv_size = node->mn_ksize;
6049 xdata.mv_data = NODEDATA(node);
6050 xdata.mv_size = NODEDSZ(node);
6053 pgno = NODEPGNO(node);
6054 flags = node->mn_flags;
6059 if (!IS_LEAF(mp) && j == 0) {
6060 /* First branch index doesn't need key data. */
6064 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6068 nkeys = NUMKEYS(copy);
6069 for (i=0; i<nkeys; i++)
6070 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6071 mp->mp_lower = copy->mp_lower;
6072 mp->mp_upper = copy->mp_upper;
6073 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6074 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6076 /* reset back to original page */
6077 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6078 mc->mc_pg[mc->mc_top] = mp;
6079 if (nflags & MDB_RESERVE) {
6080 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6081 if (!(node->mn_flags & F_BIGDATA))
6082 newdata->mv_data = NODEDATA(node);
6088 /* return tmp page to freelist */
6089 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
6090 VGMEMP_FREE(mc->mc_txn->mt_env, copy);
6091 mc->mc_txn->mt_env->me_dpages = copy;
6094 /* Adjust other cursors pointing to mp */
6095 MDB_cursor *m2, *m3;
6096 MDB_dbi dbi = mc->mc_dbi;
6097 int fixup = NUMKEYS(mp);
6099 if (mc->mc_flags & C_SUB)
6102 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6103 if (m2 == mc) continue;
6104 if (mc->mc_flags & C_SUB)
6105 m3 = &m2->mc_xcursor->mx_cursor;
6108 if (!(m3->mc_flags & C_INITIALIZED))
6110 if (m3->mc_flags & C_SPLITTING)
6115 for (k=m3->mc_top; k>=0; k--) {
6116 m3->mc_ki[k+1] = m3->mc_ki[k];
6117 m3->mc_pg[k+1] = m3->mc_pg[k];
6119 if (m3->mc_ki[0] >= split_indx) {
6124 m3->mc_pg[0] = mc->mc_pg[0];
6128 if (m3->mc_pg[mc->mc_top] == mp) {
6129 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
6130 m3->mc_ki[mc->mc_top]++;
6131 if (m3->mc_ki[mc->mc_top] >= fixup) {
6132 m3->mc_pg[mc->mc_top] = rp;
6133 m3->mc_ki[mc->mc_top] -= fixup;
6134 m3->mc_ki[ptop] = mn.mc_ki[ptop];
6136 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
6137 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
6146 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6147 MDB_val *key, MDB_val *data, unsigned int flags)
6152 assert(key != NULL);
6153 assert(data != NULL);
6155 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6158 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6162 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
6166 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6169 mdb_cursor_init(&mc, txn, dbi, &mx);
6170 return mdb_cursor_put(&mc, key, data, flags);
6173 /** Only a subset of the @ref mdb_env flags can be changed
6174 * at runtime. Changing other flags requires closing the environment
6175 * and re-opening it with the new flags.
6177 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC)
6179 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6181 if ((flag & CHANGEABLE) != flag)
6184 env->me_flags |= flag;
6186 env->me_flags &= ~flag;
6191 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6196 *arg = env->me_flags;
6201 mdb_env_get_path(MDB_env *env, const char **arg)
6206 *arg = env->me_path;
6210 /** Common code for #mdb_stat() and #mdb_env_stat().
6211 * @param[in] env the environment to operate in.
6212 * @param[in] db the #MDB_db record containing the stats to return.
6213 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6214 * @return 0, this function always succeeds.
6217 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6219 arg->ms_psize = env->me_psize;
6220 arg->ms_depth = db->md_depth;
6221 arg->ms_branch_pages = db->md_branch_pages;
6222 arg->ms_leaf_pages = db->md_leaf_pages;
6223 arg->ms_overflow_pages = db->md_overflow_pages;
6224 arg->ms_entries = db->md_entries;
6229 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6233 if (env == NULL || arg == NULL)
6236 toggle = mdb_env_pick_meta(env);
6238 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6241 /** Set the default comparison functions for a database.
6242 * Called immediately after a database is opened to set the defaults.
6243 * The user can then override them with #mdb_set_compare() or
6244 * #mdb_set_dupsort().
6245 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6246 * @param[in] dbi A database handle returned by #mdb_open()
6249 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6251 uint16_t f = txn->mt_dbs[dbi].md_flags;
6253 txn->mt_dbxs[dbi].md_cmp =
6254 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
6255 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
6257 txn->mt_dbxs[dbi].md_dcmp =
6258 !(f & MDB_DUPSORT) ? 0 :
6259 ((f & MDB_INTEGERDUP)
6260 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
6261 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
6264 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6269 int rc, dbflag, exact;
6270 unsigned int unused = 0;
6273 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6274 mdb_default_cmp(txn, FREE_DBI);
6280 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6281 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6282 mdb_default_cmp(txn, MAIN_DBI);
6286 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6287 mdb_default_cmp(txn, MAIN_DBI);
6290 /* Is the DB already open? */
6292 for (i=2; i<txn->mt_numdbs; i++) {
6293 if (!txn->mt_dbxs[i].md_name.mv_size) {
6294 /* Remember this free slot */
6295 if (!unused) unused = i;
6298 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6299 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6305 /* If no free slot and max hit, fail */
6306 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6309 /* Find the DB info */
6313 key.mv_data = (void *)name;
6314 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6315 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6316 if (rc == MDB_SUCCESS) {
6317 /* make sure this is actually a DB */
6318 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6319 if (!(node->mn_flags & F_SUBDATA))
6321 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6322 /* Create if requested */
6324 data.mv_size = sizeof(MDB_db);
6325 data.mv_data = &dummy;
6326 memset(&dummy, 0, sizeof(dummy));
6327 dummy.md_root = P_INVALID;
6328 dummy.md_flags = flags & 0xffff;
6329 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6333 /* OK, got info, add to table */
6334 if (rc == MDB_SUCCESS) {
6335 unsigned int slot = unused ? unused : txn->mt_numdbs;
6336 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
6337 txn->mt_dbxs[slot].md_name.mv_size = len;
6338 txn->mt_dbxs[slot].md_rel = NULL;
6339 txn->mt_dbflags[slot] = dbflag;
6340 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
6342 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
6343 mdb_default_cmp(txn, slot);
6346 txn->mt_env->me_numdbs++;
6353 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6355 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6358 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6361 void mdb_close(MDB_env *env, MDB_dbi dbi)
6364 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6366 ptr = env->me_dbxs[dbi].md_name.mv_data;
6367 env->me_dbxs[dbi].md_name.mv_data = NULL;
6368 env->me_dbxs[dbi].md_name.mv_size = 0;
6372 /** Add all the DB's pages to the free list.
6373 * @param[in] mc Cursor on the DB to free.
6374 * @param[in] subs non-Zero to check for sub-DBs in this DB.
6375 * @return 0 on success, non-zero on failure.
6378 mdb_drop0(MDB_cursor *mc, int subs)
6382 rc = mdb_page_search(mc, NULL, 0);
6383 if (rc == MDB_SUCCESS) {
6388 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6389 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6392 mdb_cursor_copy(mc, &mx);
6393 while (mc->mc_snum > 0) {
6394 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6395 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6396 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6397 if (ni->mn_flags & F_SUBDATA) {
6398 mdb_xcursor_init1(mc, ni);
6399 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6405 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6407 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6410 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6415 rc = mdb_cursor_sibling(mc, 1);
6417 /* no more siblings, go back to beginning
6418 * of previous level. (stack was already popped
6419 * by mdb_cursor_sibling)
6421 for (i=1; i<mc->mc_top; i++)
6422 mc->mc_pg[i] = mx.mc_pg[i];
6426 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6427 mc->mc_db->md_root);
6432 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6437 if (!txn || !dbi || dbi >= txn->mt_numdbs)
6440 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6443 rc = mdb_cursor_open(txn, dbi, &mc);
6447 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6451 /* Can't delete the main DB */
6452 if (del && dbi > MAIN_DBI) {
6453 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6455 mdb_close(txn->mt_env, dbi);
6457 txn->mt_dbflags[dbi] |= DB_DIRTY;
6458 txn->mt_dbs[dbi].md_depth = 0;
6459 txn->mt_dbs[dbi].md_branch_pages = 0;
6460 txn->mt_dbs[dbi].md_leaf_pages = 0;
6461 txn->mt_dbs[dbi].md_overflow_pages = 0;
6462 txn->mt_dbs[dbi].md_entries = 0;
6463 txn->mt_dbs[dbi].md_root = P_INVALID;
6466 mdb_cursor_close(mc);
6470 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6472 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6475 txn->mt_dbxs[dbi].md_cmp = cmp;
6479 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6481 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6484 txn->mt_dbxs[dbi].md_dcmp = cmp;
6488 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6490 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6493 txn->mt_dbxs[dbi].md_rel = rel;
6497 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6499 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6502 txn->mt_dbxs[dbi].md_relctx = ctx;