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 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
67 #if (__BYTE_ORDER == __LITTLE_ENDIAN) == (__BYTE_ORDER == __BIG_ENDIAN)
68 # error "Unknown or unsupported endianness (__BYTE_ORDER)"
69 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
70 # error "Two's complement, reasonably sized integer types, please"
73 /** @defgroup internal MDB Internals
76 /** @defgroup compat Windows Compatibility Macros
77 * A bunch of macros to minimize the amount of platform-specific ifdefs
78 * needed throughout the rest of the code. When the features this library
79 * needs are similar enough to POSIX to be hidden in a one-or-two line
80 * replacement, this macro approach is used.
84 #define pthread_t DWORD
85 #define pthread_mutex_t HANDLE
86 #define pthread_key_t DWORD
87 #define pthread_self() GetCurrentThreadId()
88 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
89 #define pthread_key_delete(x) TlsFree(x)
90 #define pthread_getspecific(x) TlsGetValue(x)
91 #define pthread_setspecific(x,y) TlsSetValue(x,y)
92 #define pthread_mutex_unlock(x) ReleaseMutex(x)
93 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
94 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
95 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
96 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
97 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
98 #define getpid() GetCurrentProcessId()
99 #define fdatasync(fd) (!FlushFileBuffers(fd))
100 #define ErrCode() GetLastError()
101 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
102 #define close(fd) CloseHandle(fd)
103 #define munmap(ptr,len) UnmapViewOfFile(ptr)
105 /** Lock the reader mutex.
107 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
108 /** Unlock the reader mutex.
110 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
112 /** Lock the writer mutex.
113 * Only a single write transaction is allowed at a time. Other writers
114 * will block waiting for this mutex.
116 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
117 /** Unlock the writer mutex.
119 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
121 /** Get the error code for the last failed system function.
123 #define ErrCode() errno
125 /** An abstraction for a file handle.
126 * On POSIX systems file handles are small integers. On Windows
127 * they're opaque pointers.
131 /** A value for an invalid file handle.
132 * Mainly used to initialize file variables and signify that they are
135 #define INVALID_HANDLE_VALUE (-1)
137 /** Get the size of a memory page for the system.
138 * This is the basic size that the platform's memory manager uses, and is
139 * fundamental to the use of memory-mapped files.
141 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
147 /** A flag for opening a file and requesting synchronous data writes.
148 * This is only used when writing a meta page. It's not strictly needed;
149 * we could just do a normal write and then immediately perform a flush.
150 * But if this flag is available it saves us an extra system call.
152 * @note If O_DSYNC is undefined but exists in /usr/include,
153 * preferably set some compiler flag to get the definition.
154 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
157 # define MDB_DSYNC O_DSYNC
161 /** A page number in the database.
162 * Note that 64 bit page numbers are overkill, since pages themselves
163 * already represent 12-13 bits of addressable memory, and the OS will
164 * always limit applications to a maximum of 63 bits of address space.
166 * @note In the #MDB_node structure, we only store 48 bits of this value,
167 * which thus limits us to only 60 bits of addressable data.
171 /** A transaction ID.
172 * See struct MDB_txn.mt_txnid for details.
176 /** @defgroup debug Debug Macros
180 /** Enable debug output.
181 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
182 * read from and written to the database (used for free space management).
187 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
188 # define DPRINTF (void) /* Vararg macros may be unsupported */
190 /** Print a debug message with printf formatting. */
191 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
192 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
194 # define DPRINTF(fmt, ...) ((void) 0)
196 /** Print a debug string.
197 * The string is printed literally, with no format processing.
199 #define DPUTS(arg) DPRINTF("%s", arg)
202 /** A default memory page size.
203 * The actual size is platform-dependent, but we use this for
204 * boot-strapping. We probably should not be using this any more.
205 * The #GET_PAGESIZE() macro is used to get the actual size.
207 * Note that we don't currently support Huge pages. On Linux,
208 * regular data files cannot use Huge pages, and in general
209 * Huge pages aren't actually pageable. We rely on the OS
210 * demand-pager to read our data and page it out when memory
211 * pressure from other processes is high. So until OSs have
212 * actual paging support for Huge pages, they're not viable.
214 #define PAGESIZE 4096
216 /** The minimum number of keys required in a database page.
217 * Setting this to a larger value will place a smaller bound on the
218 * maximum size of a data item. Data items larger than this size will
219 * be pushed into overflow pages instead of being stored directly in
220 * the B-tree node. This value used to default to 4. With a page size
221 * of 4096 bytes that meant that any item larger than 1024 bytes would
222 * go into an overflow page. That also meant that on average 2-3KB of
223 * each overflow page was wasted space. The value cannot be lower than
224 * 2 because then there would no longer be a tree structure. With this
225 * value, items larger than 2KB will go into overflow pages, and on
226 * average only 1KB will be wasted.
228 #define MDB_MINKEYS 2
230 /** A stamp that identifies a file as an MDB file.
231 * There's nothing special about this value other than that it is easily
232 * recognizable, and it will reflect any byte order mismatches.
234 #define MDB_MAGIC 0xBEEFC0DE
236 /** The version number for a database's file format. */
237 #define MDB_VERSION 1
239 /** The maximum size of a key in the database.
240 * While data items have essentially unbounded size, we require that
241 * keys all fit onto a regular page. This limit could be raised a bit
242 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
244 #define MAXKEYSIZE 511
249 * This is used for printing a hex dump of a key's contents.
251 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
252 /** Display a key in hex.
254 * Invoke a function to display a key in hex.
256 #define DKEY(x) mdb_dkey(x, kbuf)
258 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
262 /** @defgroup lazylock Lazy Locking
263 * Macros for locks that are't actually needed.
264 * The DB view is always consistent because all writes are wrapped in
265 * the wmutex. Finer-grained locks aren't necessary.
269 /** Use lazy locking. I.e., don't lock these accesses at all. */
273 /** Grab the reader lock */
274 #define LAZY_MUTEX_LOCK(x)
275 /** Release the reader lock */
276 #define LAZY_MUTEX_UNLOCK(x)
277 /** Release the DB table reader/writer lock */
278 #define LAZY_RWLOCK_UNLOCK(x)
279 /** Grab the DB table write lock */
280 #define LAZY_RWLOCK_WRLOCK(x)
281 /** Grab the DB table read lock */
282 #define LAZY_RWLOCK_RDLOCK(x)
283 /** Declare the DB table rwlock. Should not be followed by ';'. */
284 #define LAZY_RWLOCK_DEF(x)
285 /** Initialize the DB table rwlock */
286 #define LAZY_RWLOCK_INIT(x,y)
287 /** Destroy the DB table rwlock */
288 #define LAZY_RWLOCK_DESTROY(x)
290 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
291 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
292 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
293 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
294 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
295 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
296 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
297 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
301 /** An invalid page number.
302 * Mainly used to denote an empty tree.
304 #define P_INVALID (~0UL)
306 /** Test if a flag \b f is set in a flag word \b w. */
307 #define F_ISSET(w, f) (((w) & (f)) == (f))
309 /** Used for offsets within a single page.
310 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
313 typedef uint16_t indx_t;
315 /** Default size of memory map.
316 * This is certainly too small for any actual applications. Apps should always set
317 * the size explicitly using #mdb_env_set_mapsize().
319 #define DEFAULT_MAPSIZE 1048576
321 /** @defgroup readers Reader Lock Table
322 * Readers don't acquire any locks for their data access. Instead, they
323 * simply record their transaction ID in the reader table. The reader
324 * mutex is needed just to find an empty slot in the reader table. The
325 * slot's address is saved in thread-specific data so that subsequent read
326 * transactions started by the same thread need no further locking to proceed.
328 * Since the database uses multi-version concurrency control, readers don't
329 * actually need any locking. This table is used to keep track of which
330 * readers are using data from which old transactions, so that we'll know
331 * when a particular old transaction is no longer in use. Old transactions
332 * that have discarded any data pages can then have those pages reclaimed
333 * for use by a later write transaction.
335 * The lock table is constructed such that reader slots are aligned with the
336 * processor's cache line size. Any slot is only ever used by one thread.
337 * This alignment guarantees that there will be no contention or cache
338 * thrashing as threads update their own slot info, and also eliminates
339 * any need for locking when accessing a slot.
341 * A writer thread will scan every slot in the table to determine the oldest
342 * outstanding reader transaction. Any freed pages older than this will be
343 * reclaimed by the writer. The writer doesn't use any locks when scanning
344 * this table. This means that there's no guarantee that the writer will
345 * see the most up-to-date reader info, but that's not required for correct
346 * operation - all we need is to know the upper bound on the oldest reader,
347 * we don't care at all about the newest reader. So the only consequence of
348 * reading stale information here is that old pages might hang around a
349 * while longer before being reclaimed. That's actually good anyway, because
350 * the longer we delay reclaiming old pages, the more likely it is that a
351 * string of contiguous pages can be found after coalescing old pages from
352 * many old transactions together.
354 * @todo We don't actually do such coalescing yet, we grab pages from one
355 * old transaction at a time.
358 /** Number of slots in the reader table.
359 * This value was chosen somewhat arbitrarily. 126 readers plus a
360 * couple mutexes fit exactly into 8KB on my development machine.
361 * Applications should set the table size using #mdb_env_set_maxreaders().
363 #define DEFAULT_READERS 126
365 /** The size of a CPU cache line in bytes. We want our lock structures
366 * aligned to this size to avoid false cache line sharing in the
368 * This value works for most CPUs. For Itanium this should be 128.
374 /** The information we store in a single slot of the reader table.
375 * In addition to a transaction ID, we also record the process and
376 * thread ID that owns a slot, so that we can detect stale information,
377 * e.g. threads or processes that went away without cleaning up.
378 * @note We currently don't check for stale records. We simply re-init
379 * the table when we know that we're the only process opening the
382 typedef struct MDB_rxbody {
383 /** The current Transaction ID when this transaction began.
384 * Multiple readers that start at the same time will probably have the
385 * same ID here. Again, it's not important to exclude them from
386 * anything; all we need to know is which version of the DB they
387 * started from so we can avoid overwriting any data used in that
388 * particular version.
391 /** The process ID of the process owning this reader txn. */
393 /** The thread ID of the thread owning this txn. */
397 /** The actual reader record, with cacheline padding. */
398 typedef struct MDB_reader {
401 /** shorthand for mrb_txnid */
402 #define mr_txnid mru.mrx.mrb_txnid
403 #define mr_pid mru.mrx.mrb_pid
404 #define mr_tid mru.mrx.mrb_tid
405 /** cache line alignment */
406 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
410 /** The header for the reader table.
411 * The table resides in a memory-mapped file. (This is a different file
412 * than is used for the main database.)
414 * For POSIX the actual mutexes reside in the shared memory of this
415 * mapped file. On Windows, mutexes are named objects allocated by the
416 * kernel; we store the mutex names in this mapped file so that other
417 * processes can grab them. This same approach will also be used on
418 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
419 * process-shared POSIX mutexes.
421 typedef struct MDB_txbody {
422 /** Stamp identifying this as an MDB lock file. It must be set
425 /** Version number of this lock file. Must be set to #MDB_VERSION. */
426 uint32_t mtb_version;
430 /** Mutex protecting access to this table.
431 * This is the reader lock that #LOCK_MUTEX_R acquires.
433 pthread_mutex_t mtb_mutex;
435 /** The ID of the last transaction committed to the database.
436 * This is recorded here only for convenience; the value can always
437 * be determined by reading the main database meta pages.
440 /** The number of slots that have been used in the reader table.
441 * This always records the maximum count, it is not decremented
442 * when readers release their slots.
444 unsigned mtb_numreaders;
445 /** The ID of the most recent meta page in the database.
446 * This is recorded here only for convenience; the value can always
447 * be determined by reading the main database meta pages.
449 uint32_t mtb_me_toggle;
452 /** The actual reader table definition. */
453 typedef struct MDB_txninfo {
456 #define mti_magic mt1.mtb.mtb_magic
457 #define mti_version mt1.mtb.mtb_version
458 #define mti_mutex mt1.mtb.mtb_mutex
459 #define mti_rmname mt1.mtb.mtb_rmname
460 #define mti_txnid mt1.mtb.mtb_txnid
461 #define mti_numreaders mt1.mtb.mtb_numreaders
462 #define mti_me_toggle mt1.mtb.mtb_me_toggle
463 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
468 #define mti_wmname mt2.mt2_wmname
470 pthread_mutex_t mt2_wmutex;
471 #define mti_wmutex mt2.mt2_wmutex
473 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
475 MDB_reader mti_readers[1];
479 /** Common header for all page types.
480 * Overflow pages occupy a number of contiguous pages with no
481 * headers on any page after the first.
483 typedef struct MDB_page {
484 #define mp_pgno mp_p.p_pgno
485 #define mp_next mp_p.p_next
487 pgno_t p_pgno; /**< page number */
488 void * p_next; /**< for in-memory list of freed structs */
490 #define P_BRANCH 0x01 /**< branch page */
491 #define P_LEAF 0x02 /**< leaf page */
492 #define P_OVERFLOW 0x04 /**< overflow page */
493 #define P_META 0x08 /**< meta page */
494 #define P_DIRTY 0x10 /**< dirty page */
495 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
497 #define mp_lower mp_pb.pb.pb_lower
498 #define mp_upper mp_pb.pb.pb_upper
499 #define mp_pages mp_pb.pb_pages
502 indx_t pb_lower; /**< lower bound of free space */
503 indx_t pb_upper; /**< upper bound of free space */
505 uint32_t pb_pages; /**< number of overflow pages */
507 indx_t mp_ptrs[1]; /**< dynamic size */
510 /** Size of the page header, excluding dynamic data at the end */
511 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
513 /** Address of first usable data byte in a page, after the header */
514 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
516 /** Number of nodes on a page */
517 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
519 /** The amount of space remaining in the page */
520 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
522 /** The percentage of space used in the page, in tenths of a percent. */
523 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
524 ((env)->me_psize - PAGEHDRSZ))
525 /** The minimum page fill factor, in tenths of a percent.
526 * Pages emptier than this are candidates for merging.
528 #define FILL_THRESHOLD 250
530 /** Test if a page is a leaf page */
531 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
532 /** Test if a page is a LEAF2 page */
533 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
534 /** Test if a page is a branch page */
535 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
536 /** Test if a page is an overflow page */
537 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
539 /** The number of overflow pages needed to store the given size. */
540 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
542 /** Header for a single key/data pair within a page.
543 * We guarantee 2-byte alignment for nodes.
545 typedef struct MDB_node {
546 /** lo and hi are used for data size on leaf nodes and for
547 * child pgno on branch nodes. On 64 bit platforms, flags
548 * is also used for pgno. (Branch nodes have no flags).
549 * They are in in host byte order in case that lets some
550 * accesses be optimized into a 32-bit word access.
552 #define mn_lo mn_offset[__BYTE_ORDER!=__LITTLE_ENDIAN]
553 #define mn_hi mn_offset[__BYTE_ORDER==__LITTLE_ENDIAN] /**< part of dsize or pgno */
554 unsigned short mn_offset[2];
555 unsigned short mn_flags; /**< flags for special node types */
556 #define F_BIGDATA 0x01 /**< data put on overflow page */
557 #define F_SUBDATA 0x02 /**< data is a sub-database */
558 #define F_DUPDATA 0x04 /**< data has duplicates */
559 unsigned short mn_ksize; /**< key size */
560 char mn_data[1]; /**< key and data are appended here */
563 /** Size of the node header, excluding dynamic data at the end */
564 #define NODESIZE offsetof(MDB_node, mn_data)
566 /** Bit position of top word in page number, for shifting mn_flags */
567 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
569 /** Size of a node in a branch page with a given key.
570 * This is just the node header plus the key, there is no data.
572 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
574 /** Size of a node in a leaf page with a given key and data.
575 * This is node header plus key plus data size.
577 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
579 /** Address of node \b i in page \b p */
580 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
582 /** Address of the key for the node */
583 #define NODEKEY(node) (void *)((node)->mn_data)
585 /** Address of the data for a node */
586 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
588 /** Get the page number pointed to by a branch node */
589 #define NODEPGNO(node) \
590 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
591 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
592 /** Set the page number in a branch node */
593 #define SETPGNO(node,pgno) do { \
594 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
595 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
597 /** Get the size of the data in a leaf node */
598 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
599 /** Set the size of the data for a leaf node */
600 #define SETDSZ(node,size) do { \
601 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
602 /** The size of a key in a node */
603 #define NODEKSZ(node) ((node)->mn_ksize)
605 /** The address of a key in a LEAF2 page.
606 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
607 * There are no node headers, keys are stored contiguously.
609 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
611 /** Set the \b node's key into \b key, if requested. */
612 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
613 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
615 /** Information about a single database in the environment. */
616 typedef struct MDB_db {
617 uint32_t md_pad; /**< also ksize for LEAF2 pages */
618 uint16_t md_flags; /**< @ref mdb_open */
619 uint16_t md_depth; /**< depth of this tree */
620 pgno_t md_branch_pages; /**< number of internal pages */
621 pgno_t md_leaf_pages; /**< number of leaf pages */
622 pgno_t md_overflow_pages; /**< number of overflow pages */
623 size_t md_entries; /**< number of data items */
624 pgno_t md_root; /**< the root page of this tree */
627 /** Handle for the DB used to track free pages. */
629 /** Handle for the default DB. */
632 /** Meta page content. */
633 typedef struct MDB_meta {
634 /** Stamp identifying this as an MDB data file. It must be set
637 /** Version number of this lock file. Must be set to #MDB_VERSION. */
639 void *mm_address; /**< address for fixed mapping */
640 size_t mm_mapsize; /**< size of mmap region */
641 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
642 /** The size of pages used in this DB */
643 #define mm_psize mm_dbs[0].md_pad
644 /** Any persistent environment flags. @ref mdb_env */
645 #define mm_flags mm_dbs[0].md_flags
646 pgno_t mm_last_pg; /**< last used page in file */
647 txnid_t mm_txnid; /**< txnid that committed this page */
650 /** Auxiliary DB info.
651 * The information here is mostly static/read-only. There is
652 * only a single copy of this record in the environment.
653 * The \b md_dirty flag is not read-only, but only a write
654 * transaction can ever update it, and only write transactions
655 * need to worry about it.
657 typedef struct MDB_dbx {
658 MDB_val md_name; /**< name of the database */
659 MDB_cmp_func *md_cmp; /**< function for comparing keys */
660 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
661 MDB_rel_func *md_rel; /**< user relocate function */
662 MDB_dbi md_parent; /**< parent DB of a sub-DB */
663 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
666 /** A database transaction.
667 * Every operation requires a transaction handle.
670 pgno_t mt_next_pgno; /**< next unallocated page */
671 /** The ID of this transaction. IDs are integers incrementing from 1.
672 * Only committed write transactions increment the ID. If a transaction
673 * aborts, the ID may be re-used by the next writer.
676 MDB_env *mt_env; /**< the DB environment */
677 /** The list of pages that became unused during this transaction.
682 ID2L dirty_list; /**< modified pages */
683 MDB_reader *reader; /**< this thread's slot in the reader table */
685 /** Array of records for each DB known in the environment. */
687 /** Array of MDB_db records for each known DB */
689 /** Number of DB records in use. This number only ever increments;
690 * we don't decrement it when individual DB handles are closed.
692 unsigned int mt_numdbs;
694 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
695 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
696 unsigned int mt_flags;
697 /** Tracks which of the two meta pages was used at the start
698 * of this transaction.
700 unsigned int mt_toggle;
703 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
704 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
705 * raise this on a 64 bit machine.
707 #define CURSOR_STACK 32
711 /** Cursors are used for all DB operations */
713 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
714 struct MDB_xcursor *mc_xcursor;
715 /** The transaction that owns this cursor */
717 /** The database handle this cursor operates on */
719 unsigned short mc_snum; /**< number of pushed pages */
720 unsigned short mc_top; /**< index of top page, mc_snum-1 */
721 unsigned int mc_flags;
722 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
723 #define C_EOF 0x02 /**< No more data */
724 #define C_XDIRTY 0x04 /**< @deprecated mc_xcursor needs to be flushed */
725 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
726 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
729 /** Context for sorted-dup records.
730 * We could have gone to a fully recursive design, with arbitrarily
731 * deep nesting of sub-databases. But for now we only handle these
732 * levels - main DB, optional sub-DB, sorted-duplicate DB.
734 typedef struct MDB_xcursor {
735 /** A sub-cursor for traversing the Dup DB */
736 MDB_cursor mx_cursor;
737 /** A fake transaction struct for pointing to our own table
741 /** Our private DB information tables. Slots 0 and 1 are always
742 * copies of the corresponding slots in the main transaction. These
743 * hold the FREEDB and MAINDB, respectively. If the main cursor is
744 * on a sub-database, that will be copied to slot 2, and the duplicate
745 * database info will be in slot 3. If the main cursor is on the MAINDB
746 * then the duplicate DB info will be in slot 2 and slot 3 will be unused.
753 /** A set of pages freed by an earlier transaction. */
754 typedef struct MDB_oldpages {
755 /** Usually we only read one record from the FREEDB at a time, but
756 * in case we read more, this will chain them together.
758 struct MDB_oldpages *mo_next;
759 /** The ID of the transaction in which these pages were freed. */
761 /** An #IDL of the pages */
762 pgno_t mo_pages[1]; /* dynamic */
765 /** The database environment. */
767 HANDLE me_fd; /**< The main data file */
768 HANDLE me_lfd; /**< The lock file */
769 HANDLE me_mfd; /**< just for writing the meta pages */
770 /** Failed to update the meta page. Probably an I/O error. */
771 #define MDB_FATAL_ERROR 0x80000000U
773 uint32_t me_extrapad; /**< unused for now */
774 unsigned int me_maxreaders; /**< size of the reader table */
775 unsigned int me_numdbs; /**< number of DBs opened */
776 unsigned int me_maxdbs; /**< size of the DB table */
777 char *me_path; /**< path to the DB files */
778 char *me_map; /**< the memory map of the data file */
779 MDB_txninfo *me_txns; /**< the memory map of the lock file */
780 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
781 MDB_txn *me_txn; /**< current write transaction */
782 size_t me_mapsize; /**< size of the data memory map */
783 off_t me_size; /**< current file size */
784 pgno_t me_maxpg; /**< me_mapsize / me_psize */
785 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
786 unsigned int me_db_toggle; /**< which DB table is current */
787 MDB_dbx *me_dbxs; /**< array of static DB info */
788 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
789 MDB_oldpages *me_pghead; /**< list of old page records */
790 pthread_key_t me_txkey; /**< thread-key for readers */
791 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
792 /** IDL of pages that became unused in a write txn */
793 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
794 /** ID2L of pages that were written during a write txn */
795 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
796 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
797 LAZY_RWLOCK_DEF(me_dblock)
799 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
803 /** max number of pages to commit in one writev() call */
804 #define MDB_COMMIT_PAGES 64
806 static MDB_page *mdb_alloc_page(MDB_cursor *mc, int num);
807 static int mdb_touch(MDB_cursor *mc);
809 static int mdb_search_page_root(MDB_cursor *mc,
810 MDB_val *key, int modify);
811 static int mdb_search_page(MDB_cursor *mc,
812 MDB_val *key, int modify);
814 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
815 static int mdb_env_read_meta(MDB_env *env, int *which);
816 static int mdb_env_write_meta(MDB_txn *txn);
817 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
819 static MDB_node *mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp);
820 static int mdb_add_node(MDB_cursor *mc, indx_t indx,
821 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
822 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
823 static int mdb_del0(MDB_cursor *mc, MDB_node *leaf);
824 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
826 static int mdb_rebalance(MDB_cursor *mc);
827 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
828 static int mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst);
829 static int mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst);
830 static int mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
832 static MDB_page *mdb_new_page(MDB_cursor *mc, uint32_t flags, int num);
834 static void cursor_pop_page(MDB_cursor *mc);
835 static int cursor_push_page(MDB_cursor *mc, MDB_page *mp);
837 static int mdb_sibling(MDB_cursor *mc, int move_right);
838 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
839 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
840 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
842 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
843 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
845 static void mdb_xcursor_init0(MDB_cursor *mc);
846 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
847 static void mdb_xcursor_init2(MDB_cursor *mc);
848 static void mdb_xcursor_fini(MDB_cursor *mc);
850 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
851 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
853 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
856 static MDB_cmp_func memncmp, memnrcmp, intcmp, cintcmp;
860 static SECURITY_DESCRIPTOR mdb_null_sd;
861 static SECURITY_ATTRIBUTES mdb_all_sa;
862 static int mdb_sec_inited;
865 /** Return the library version info. */
867 mdb_version(int *major, int *minor, int *patch)
869 if (major) *major = MDB_VERSION_MAJOR;
870 if (minor) *minor = MDB_VERSION_MINOR;
871 if (patch) *patch = MDB_VERSION_PATCH;
872 return MDB_VERSION_STRING;
875 /** Table of descriptions for MDB @ref errors */
876 static char *const mdb_errstr[] = {
877 "MDB_KEYEXIST: Key/data pair already exists",
878 "MDB_NOTFOUND: No matching key/data pair found",
879 "MDB_PAGE_NOTFOUND: Requested page not found",
880 "MDB_CORRUPTED: Located page was wrong type",
881 "MDB_PANIC: Update of meta page failed",
882 "MDB_VERSION_MISMATCH: Database environment version mismatch"
886 mdb_strerror(int err)
889 return ("Successful return: 0");
891 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
892 return mdb_errstr[err - MDB_KEYEXIST];
894 return strerror(err);
898 /** Display a key in hexadecimal and return the address of the result.
899 * @param[in] key the key to display
900 * @param[in] buf the buffer to write into. Should always be #DKBUF.
901 * @return The key in hexadecimal form.
904 mdb_dkey(MDB_val *key, char *buf)
907 unsigned char *c = key->mv_data;
909 if (key->mv_size > MAXKEYSIZE)
911 /* may want to make this a dynamic check: if the key is mostly
912 * printable characters, print it as-is instead of converting to hex.
915 for (i=0; i<key->mv_size; i++)
916 ptr += sprintf(ptr, "%02x", *c++);
918 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
925 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
927 return txn->mt_dbxs[dbi].md_cmp(a, b);
930 /** Compare two data items according to a particular database.
931 * This returns a comparison as if the two items were data items of
932 * a sorted duplicates #MDB_DUPSORT database.
933 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
934 * @param[in] dbi A database handle returned by #mdb_open()
935 * @param[in] a The first item to compare
936 * @param[in] b The second item to compare
937 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
940 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
942 if (txn->mt_dbxs[dbi].md_dcmp)
943 return txn->mt_dbxs[dbi].md_dcmp(a, b);
945 return EINVAL; /* too bad you can't distinguish this from a valid result */
948 /** Allocate pages for writing.
949 * If there are free pages available from older transactions, they
950 * will be re-used first. Otherwise a new page will be allocated.
951 * @param[in] mc cursor A cursor handle identifying the transaction and
952 * database for which we are allocating.
953 * @param[in] num the number of pages to allocate.
954 * @return Address of the allocated page(s). Requests for multiple pages
955 * will always be satisfied by a single contiguous chunk of memory.
958 mdb_alloc_page(MDB_cursor *mc, int num)
960 MDB_txn *txn = mc->mc_txn;
962 pgno_t pgno = P_INVALID;
965 if (txn->mt_txnid > 2) {
967 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
968 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
969 /* See if there's anything in the free DB */
972 txnid_t *kptr, oldest;
975 m2.mc_dbi = FREE_DBI;
978 mdb_search_page(&m2, NULL, 0);
979 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
980 kptr = (txnid_t *)NODEKEY(leaf);
984 oldest = txn->mt_txnid - 1;
985 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
986 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
987 if (mr && mr < oldest)
992 if (oldest > *kptr) {
993 /* It's usable, grab it.
999 mdb_read_data(txn, leaf, &data);
1000 idl = (ID *) data.mv_data;
1001 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1002 mop->mo_next = txn->mt_env->me_pghead;
1003 mop->mo_txnid = *kptr;
1004 txn->mt_env->me_pghead = mop;
1005 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1010 DPRINTF("IDL read txn %zu root %zu num %zu",
1011 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1012 for (i=0; i<idl[0]; i++) {
1013 DPRINTF("IDL %zu", idl[i+1]);
1017 /* drop this IDL from the DB */
1018 m2.mc_ki[m2.mc_top] = 0;
1019 m2.mc_flags = C_INITIALIZED;
1020 mdb_cursor_del(&m2, 0);
1023 if (txn->mt_env->me_pghead) {
1024 MDB_oldpages *mop = txn->mt_env->me_pghead;
1026 /* FIXME: For now, always use fresh pages. We
1027 * really ought to search the free list for a
1032 /* peel pages off tail, so we only have to truncate the list */
1033 pgno = MDB_IDL_LAST(mop->mo_pages);
1034 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1036 if (mop->mo_pages[2] > mop->mo_pages[1])
1037 mop->mo_pages[0] = 0;
1041 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1042 txn->mt_env->me_pghead = mop->mo_next;
1049 if (pgno == P_INVALID) {
1050 /* DB size is maxed out */
1051 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
1054 if (txn->mt_env->me_dpages && num == 1) {
1055 np = txn->mt_env->me_dpages;
1056 txn->mt_env->me_dpages = np->mp_next;
1058 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1061 if (pgno == P_INVALID) {
1062 np->mp_pgno = txn->mt_next_pgno;
1063 txn->mt_next_pgno += num;
1067 mid.mid = np->mp_pgno;
1069 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1074 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1075 * @param[in] mc cursor pointing to the page to be touched
1076 * @return 0 on success, non-zero on failure.
1079 mdb_touch(MDB_cursor *mc)
1081 MDB_page *mp = mc->mc_pg[mc->mc_top];
1084 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1086 if ((np = mdb_alloc_page(mc, 1)) == NULL)
1088 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1089 assert(mp->mp_pgno != np->mp_pgno);
1090 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1092 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1095 mp->mp_flags |= P_DIRTY;
1097 mc->mc_pg[mc->mc_top] = mp;
1098 /** If this page has a parent, update the parent to point to
1102 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1108 mdb_env_sync(MDB_env *env, int force)
1111 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1112 if (fdatasync(env->me_fd))
1119 mdb_txn_reset0(MDB_txn *txn);
1121 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1122 * @param[in] txn the transaction handle to initialize
1123 * @return 0 on success, non-zero on failure. This can only
1124 * fail for read-only transactions, and then only if the
1125 * reader table is full.
1128 mdb_txn_renew0(MDB_txn *txn)
1130 MDB_env *env = txn->mt_env;
1132 if (txn->mt_flags & MDB_TXN_RDONLY) {
1133 MDB_reader *r = pthread_getspecific(env->me_txkey);
1136 pid_t pid = getpid();
1137 pthread_t tid = pthread_self();
1140 for (i=0; i<env->me_txns->mti_numreaders; i++)
1141 if (env->me_txns->mti_readers[i].mr_pid == 0)
1143 if (i == env->me_maxreaders) {
1144 UNLOCK_MUTEX_R(env);
1147 env->me_txns->mti_readers[i].mr_pid = pid;
1148 env->me_txns->mti_readers[i].mr_tid = tid;
1149 if (i >= env->me_txns->mti_numreaders)
1150 env->me_txns->mti_numreaders = i+1;
1151 UNLOCK_MUTEX_R(env);
1152 r = &env->me_txns->mti_readers[i];
1153 pthread_setspecific(env->me_txkey, r);
1155 txn->mt_txnid = env->me_txns->mti_txnid;
1156 txn->mt_toggle = env->me_txns->mti_me_toggle;
1157 r->mr_txnid = txn->mt_txnid;
1158 txn->mt_u.reader = r;
1162 txn->mt_txnid = env->me_txns->mti_txnid+1;
1163 txn->mt_toggle = env->me_txns->mti_me_toggle;
1164 txn->mt_u.dirty_list = env->me_dirty_list;
1165 txn->mt_u.dirty_list[0].mid = 0;
1166 txn->mt_free_pgs = env->me_free_pgs;
1167 txn->mt_free_pgs[0] = 0;
1168 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1172 /* Copy the DB arrays */
1173 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1174 txn->mt_numdbs = env->me_numdbs;
1175 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1176 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1177 if (txn->mt_numdbs > 2)
1178 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1179 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1180 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1186 mdb_txn_renew(MDB_txn *txn)
1193 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1194 DPUTS("environment had fatal error, must shutdown!");
1198 rc = mdb_txn_renew0(txn);
1199 if (rc == MDB_SUCCESS) {
1200 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1201 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1202 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1208 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1213 if (env->me_flags & MDB_FATAL_ERROR) {
1214 DPUTS("environment had fatal error, must shutdown!");
1217 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1218 DPRINTF("calloc: %s", strerror(ErrCode()));
1221 txn->mt_dbs = (MDB_db *)(txn+1);
1222 if (flags & MDB_RDONLY) {
1223 txn->mt_flags |= MDB_TXN_RDONLY;
1227 rc = mdb_txn_renew0(txn);
1232 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1233 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1234 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1240 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1241 * @param[in] txn the transaction handle to reset
1244 mdb_txn_reset0(MDB_txn *txn)
1246 MDB_env *env = txn->mt_env;
1248 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1249 txn->mt_u.reader->mr_txnid = 0;
1255 /* return all dirty pages to dpage list */
1256 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1257 dp = txn->mt_u.dirty_list[i].mptr;
1258 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1259 dp->mp_next = txn->mt_env->me_dpages;
1260 txn->mt_env->me_dpages = dp;
1262 /* large pages just get freed directly */
1267 while ((mop = txn->mt_env->me_pghead)) {
1268 txn->mt_env->me_pghead = mop->mo_next;
1273 for (i=2; i<env->me_numdbs; i++)
1274 env->me_dbxs[i].md_dirty = 0;
1275 /* The writer mutex was locked in mdb_txn_begin. */
1276 UNLOCK_MUTEX_W(env);
1281 mdb_txn_reset(MDB_txn *txn)
1286 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1287 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1288 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1290 mdb_txn_reset0(txn);
1294 mdb_txn_abort(MDB_txn *txn)
1299 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1300 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1301 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1303 mdb_txn_reset0(txn);
1308 mdb_txn_commit(MDB_txn *txn)
1319 assert(txn != NULL);
1320 assert(txn->mt_env != NULL);
1324 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1329 if (txn != env->me_txn) {
1330 DPUTS("attempt to commit unknown transaction");
1335 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1336 DPUTS("error flag is set, can't commit");
1341 if (!txn->mt_u.dirty_list[0].mid)
1344 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1345 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1348 mc.mc_dbi = FREE_DBI;
1351 /* should only be one record now */
1352 if (env->me_pghead) {
1353 /* make sure first page of freeDB is touched and on freelist */
1354 mdb_search_page(&mc, NULL, 1);
1356 /* save to free list */
1357 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1361 /* make sure last page of freeDB is touched and on freelist */
1362 key.mv_size = MAXKEYSIZE+1;
1364 mdb_search_page(&mc, &key, 1);
1366 mdb_midl_sort(txn->mt_free_pgs);
1370 ID *idl = txn->mt_free_pgs;
1371 DPRINTF("IDL write txn %zu root %zu num %zu",
1372 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1373 for (i=0; i<idl[0]; i++) {
1374 DPRINTF("IDL %zu", idl[i+1]);
1378 /* write to last page of freeDB */
1379 key.mv_size = sizeof(pgno_t);
1380 key.mv_data = &txn->mt_txnid;
1381 data.mv_data = txn->mt_free_pgs;
1382 /* The free list can still grow during this call,
1383 * despite the pre-emptive touches above. So check
1384 * and make sure the entire thing got written.
1387 i = txn->mt_free_pgs[0];
1388 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1389 rc = mdb_cursor_put(&mc, &key, &data, 0);
1394 } while (i != txn->mt_free_pgs[0]);
1396 /* should only be one record now */
1397 if (env->me_pghead) {
1401 mop = env->me_pghead;
1402 key.mv_size = sizeof(pgno_t);
1403 key.mv_data = &mop->mo_txnid;
1404 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1405 data.mv_data = mop->mo_pages;
1406 mdb_cursor_put(&mc, &key, &data, 0);
1407 free(env->me_pghead);
1408 env->me_pghead = NULL;
1411 /* Update DB root pointers. Their pages have already been
1412 * touched so this is all in-place and cannot fail.
1416 data.mv_size = sizeof(MDB_db);
1418 mc.mc_dbi = MAIN_DBI;
1420 for (i = 2; i < txn->mt_numdbs; i++) {
1421 if (txn->mt_dbxs[i].md_dirty) {
1422 data.mv_data = &txn->mt_dbs[i];
1423 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1428 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1434 /* Windows actually supports scatter/gather I/O, but only on
1435 * unbuffered file handles. Since we're relying on the OS page
1436 * cache for all our data, that's self-defeating. So we just
1437 * write pages one at a time. We use the ov structure to set
1438 * the write offset, to at least save the overhead of a Seek
1442 memset(&ov, 0, sizeof(ov));
1443 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1445 dp = txn->mt_u.dirty_list[i].mptr;
1446 DPRINTF("committing page %zu", dp->mp_pgno);
1447 size = dp->mp_pgno * env->me_psize;
1448 ov.Offset = size & 0xffffffff;
1449 ov.OffsetHigh = size >> 16;
1450 ov.OffsetHigh >>= 16;
1451 /* clear dirty flag */
1452 dp->mp_flags &= ~P_DIRTY;
1453 wsize = env->me_psize;
1454 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1455 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1458 DPRINTF("WriteFile: %d", n);
1465 struct iovec iov[MDB_COMMIT_PAGES];
1469 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1470 dp = txn->mt_u.dirty_list[i].mptr;
1471 if (dp->mp_pgno != next) {
1473 DPRINTF("committing %u dirty pages", n);
1474 rc = writev(env->me_fd, iov, n);
1478 DPUTS("short write, filesystem full?");
1480 DPRINTF("writev: %s", strerror(n));
1487 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1490 DPRINTF("committing page %zu", dp->mp_pgno);
1491 iov[n].iov_len = env->me_psize;
1492 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1493 iov[n].iov_base = dp;
1494 size += iov[n].iov_len;
1495 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1496 /* clear dirty flag */
1497 dp->mp_flags &= ~P_DIRTY;
1498 if (++n >= MDB_COMMIT_PAGES) {
1508 DPRINTF("committing %u dirty pages", n);
1509 rc = writev(env->me_fd, iov, n);
1513 DPUTS("short write, filesystem full?");
1515 DPRINTF("writev: %s", strerror(n));
1522 /* Drop the dirty pages.
1524 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1525 dp = txn->mt_u.dirty_list[i].mptr;
1526 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1527 dp->mp_next = txn->mt_env->me_dpages;
1528 txn->mt_env->me_dpages = dp;
1532 txn->mt_u.dirty_list[i].mid = 0;
1534 txn->mt_u.dirty_list[0].mid = 0;
1536 if ((n = mdb_env_sync(env, 0)) != 0 ||
1537 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1544 /* update the DB tables */
1546 int toggle = !env->me_db_toggle;
1549 ip = &env->me_dbs[toggle][2];
1550 jp = &txn->mt_dbs[2];
1551 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1552 for (i = 2; i < txn->mt_numdbs; i++) {
1553 if (ip->md_root != jp->md_root)
1558 for (i = 2; i < txn->mt_numdbs; i++) {
1559 if (txn->mt_dbxs[i].md_dirty)
1560 txn->mt_dbxs[i].md_dirty = 0;
1562 env->me_db_toggle = toggle;
1563 env->me_numdbs = txn->mt_numdbs;
1564 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1567 UNLOCK_MUTEX_W(env);
1573 /** Read the environment parameters of a DB environment before
1574 * mapping it into memory.
1575 * @param[in] env the environment handle
1576 * @param[out] meta address of where to store the meta information
1577 * @return 0 on success, non-zero on failure.
1580 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1582 char page[PAGESIZE];
1587 /* We don't know the page size yet, so use a minimum value.
1591 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1593 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1598 else if (rc != PAGESIZE) {
1602 DPRINTF("read: %s", strerror(err));
1606 p = (MDB_page *)page;
1608 if (!F_ISSET(p->mp_flags, P_META)) {
1609 DPRINTF("page %zu not a meta page", p->mp_pgno);
1614 if (m->mm_magic != MDB_MAGIC) {
1615 DPUTS("meta has invalid magic");
1619 if (m->mm_version != MDB_VERSION) {
1620 DPRINTF("database is version %u, expected version %u",
1621 m->mm_version, MDB_VERSION);
1622 return MDB_VERSION_MISMATCH;
1625 memcpy(meta, m, sizeof(*m));
1629 /** Write the environment parameters of a freshly created DB environment.
1630 * @param[in] env the environment handle
1631 * @param[out] meta address of where to store the meta information
1632 * @return 0 on success, non-zero on failure.
1635 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1642 DPUTS("writing new meta page");
1644 GET_PAGESIZE(psize);
1646 meta->mm_magic = MDB_MAGIC;
1647 meta->mm_version = MDB_VERSION;
1648 meta->mm_psize = psize;
1649 meta->mm_last_pg = 1;
1650 meta->mm_flags = env->me_flags & 0xffff;
1651 meta->mm_flags |= MDB_INTEGERKEY;
1652 meta->mm_dbs[0].md_root = P_INVALID;
1653 meta->mm_dbs[1].md_root = P_INVALID;
1655 p = calloc(2, psize);
1657 p->mp_flags = P_META;
1660 memcpy(m, meta, sizeof(*meta));
1662 q = (MDB_page *)((char *)p + psize);
1665 q->mp_flags = P_META;
1668 memcpy(m, meta, sizeof(*meta));
1673 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1674 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1677 rc = write(env->me_fd, p, psize * 2);
1678 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1684 /** Update the environment info to commit a transaction.
1685 * @param[in] txn the transaction that's being committed
1686 * @return 0 on success, non-zero on failure.
1689 mdb_env_write_meta(MDB_txn *txn)
1692 MDB_meta meta, metab;
1694 int rc, len, toggle;
1700 assert(txn != NULL);
1701 assert(txn->mt_env != NULL);
1703 toggle = !txn->mt_toggle;
1704 DPRINTF("writing meta page %d for root page %zu",
1705 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1709 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1710 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1712 ptr = (char *)&meta;
1713 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1714 len = sizeof(MDB_meta) - off;
1717 meta.mm_dbs[0] = txn->mt_dbs[0];
1718 meta.mm_dbs[1] = txn->mt_dbs[1];
1719 meta.mm_last_pg = txn->mt_next_pgno - 1;
1720 meta.mm_txnid = txn->mt_txnid;
1723 off += env->me_psize;
1726 /* Write to the SYNC fd */
1729 memset(&ov, 0, sizeof(ov));
1731 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1734 rc = pwrite(env->me_mfd, ptr, len, off);
1739 DPUTS("write failed, disk error?");
1740 /* On a failure, the pagecache still contains the new data.
1741 * Write some old data back, to prevent it from being used.
1742 * Use the non-SYNC fd; we know it will fail anyway.
1744 meta.mm_last_pg = metab.mm_last_pg;
1745 meta.mm_txnid = metab.mm_txnid;
1747 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1749 r2 = pwrite(env->me_fd, ptr, len, off);
1751 env->me_flags |= MDB_FATAL_ERROR;
1754 /* Memory ordering issues are irrelevant; since the entire writer
1755 * is wrapped by wmutex, all of these changes will become visible
1756 * after the wmutex is unlocked. Since the DB is multi-version,
1757 * readers will get consistent data regardless of how fresh or
1758 * how stale their view of these values is.
1760 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1761 txn->mt_env->me_txns->mti_me_toggle = toggle;
1762 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1763 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1768 /** Check both meta pages to see which one is newer.
1769 * @param[in] env the environment handle
1770 * @param[out] which address of where to store the meta toggle ID
1771 * @return 0 on success, non-zero on failure.
1774 mdb_env_read_meta(MDB_env *env, int *which)
1778 assert(env != NULL);
1780 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1783 DPRINTF("Using meta page %d", toggle);
1790 mdb_env_create(MDB_env **env)
1794 e = calloc(1, sizeof(MDB_env));
1795 if (!e) return ENOMEM;
1797 e->me_maxreaders = DEFAULT_READERS;
1799 e->me_fd = INVALID_HANDLE_VALUE;
1800 e->me_lfd = INVALID_HANDLE_VALUE;
1801 e->me_mfd = INVALID_HANDLE_VALUE;
1807 mdb_env_set_mapsize(MDB_env *env, size_t size)
1811 env->me_mapsize = size;
1816 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1820 env->me_maxdbs = dbs;
1825 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1827 if (env->me_map || readers < 1)
1829 env->me_maxreaders = readers;
1834 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1836 if (!env || !readers)
1838 *readers = env->me_maxreaders;
1842 /** Further setup required for opening an MDB environment
1845 mdb_env_open2(MDB_env *env, unsigned int flags)
1847 int i, newenv = 0, toggle;
1851 env->me_flags = flags;
1853 memset(&meta, 0, sizeof(meta));
1855 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1858 DPUTS("new mdbenv");
1862 if (!env->me_mapsize) {
1863 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1869 LONG sizelo, sizehi;
1870 sizelo = env->me_mapsize & 0xffffffff;
1871 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1873 /* Windows won't create mappings for zero length files.
1874 * Just allocate the maxsize right now.
1877 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1878 if (!SetEndOfFile(env->me_fd))
1880 SetFilePointer(env->me_fd, 0, NULL, 0);
1882 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1883 sizehi, sizelo, NULL);
1886 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1894 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1896 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1898 if (env->me_map == MAP_FAILED)
1903 meta.mm_mapsize = env->me_mapsize;
1904 if (flags & MDB_FIXEDMAP)
1905 meta.mm_address = env->me_map;
1906 i = mdb_env_init_meta(env, &meta);
1907 if (i != MDB_SUCCESS) {
1908 munmap(env->me_map, env->me_mapsize);
1912 env->me_psize = meta.mm_psize;
1914 env->me_maxpg = env->me_mapsize / env->me_psize;
1916 p = (MDB_page *)env->me_map;
1917 env->me_metas[0] = METADATA(p);
1918 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1920 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1923 DPRINTF("opened database version %u, pagesize %u",
1924 env->me_metas[toggle]->mm_version, env->me_psize);
1925 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1926 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1927 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1928 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1929 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1930 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1936 /* Windows doesn't support destructor callbacks for thread-specific storage */
1938 mdb_env_reader_dest(void *ptr)
1940 MDB_reader *reader = ptr;
1942 reader->mr_txnid = 0;
1948 /* downgrade the exclusive lock on the region back to shared */
1950 mdb_env_share_locks(MDB_env *env)
1954 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1956 env->me_txns->mti_me_toggle = toggle;
1957 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1962 /* First acquire a shared lock. The Unlock will
1963 * then release the existing exclusive lock.
1965 memset(&ov, 0, sizeof(ov));
1966 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1967 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1971 struct flock lock_info;
1972 /* The shared lock replaces the existing lock */
1973 memset((void *)&lock_info, 0, sizeof(lock_info));
1974 lock_info.l_type = F_RDLCK;
1975 lock_info.l_whence = SEEK_SET;
1976 lock_info.l_start = 0;
1977 lock_info.l_len = 1;
1978 fcntl(env->me_lfd, F_SETLK, &lock_info);
1984 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1992 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1993 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1994 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1998 /* Try to get exclusive lock. If we succeed, then
1999 * nobody is using the lock region and we should initialize it.
2002 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2006 memset(&ov, 0, sizeof(ov));
2007 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2013 size = GetFileSize(env->me_lfd, NULL);
2015 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2019 /* Try to get exclusive lock. If we succeed, then
2020 * nobody is using the lock region and we should initialize it.
2023 struct flock lock_info;
2024 memset((void *)&lock_info, 0, sizeof(lock_info));
2025 lock_info.l_type = F_WRLCK;
2026 lock_info.l_whence = SEEK_SET;
2027 lock_info.l_start = 0;
2028 lock_info.l_len = 1;
2029 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2033 lock_info.l_type = F_RDLCK;
2034 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2041 size = lseek(env->me_lfd, 0, SEEK_END);
2043 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2044 if (size < rsize && *excl) {
2046 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2047 if (!SetEndOfFile(env->me_lfd)) {
2052 if (ftruncate(env->me_lfd, rsize) != 0) {
2059 size = rsize - sizeof(MDB_txninfo);
2060 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2065 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2071 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2073 if (!env->me_txns) {
2079 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2081 if (env->me_txns == MAP_FAILED) {
2089 if (!mdb_sec_inited) {
2090 InitializeSecurityDescriptor(&mdb_null_sd,
2091 SECURITY_DESCRIPTOR_REVISION);
2092 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2093 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2094 mdb_all_sa.bInheritHandle = FALSE;
2095 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2098 /* FIXME: only using up to 20 characters of the env path here,
2099 * probably not enough to assure uniqueness...
2101 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
2102 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
2103 while ((ptr = strchr(ptr, '\\')))
2105 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2106 if (!env->me_rmutex) {
2110 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
2111 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
2112 while ((ptr = strchr(ptr, '\\')))
2114 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2115 if (!env->me_wmutex) {
2120 pthread_mutexattr_t mattr;
2122 pthread_mutexattr_init(&mattr);
2123 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2127 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2128 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2130 env->me_txns->mti_version = MDB_VERSION;
2131 env->me_txns->mti_magic = MDB_MAGIC;
2132 env->me_txns->mti_txnid = 0;
2133 env->me_txns->mti_numreaders = 0;
2134 env->me_txns->mti_me_toggle = 0;
2137 if (env->me_txns->mti_magic != MDB_MAGIC) {
2138 DPUTS("lock region has invalid magic");
2142 if (env->me_txns->mti_version != MDB_VERSION) {
2143 DPRINTF("lock region is version %u, expected version %u",
2144 env->me_txns->mti_version, MDB_VERSION);
2145 rc = MDB_VERSION_MISMATCH;
2149 if (rc != EACCES && rc != EAGAIN) {
2153 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2154 if (!env->me_rmutex) {
2158 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2159 if (!env->me_wmutex) {
2169 env->me_lfd = INVALID_HANDLE_VALUE;
2174 /** The name of the lock file in the DB environment */
2175 #define LOCKNAME "/lock.mdb"
2176 /** The name of the data file in the DB environment */
2177 #define DATANAME "/data.mdb"
2179 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2181 int oflags, rc, len, excl;
2182 char *lpath, *dpath;
2185 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2188 dpath = lpath + len + sizeof(LOCKNAME);
2189 sprintf(lpath, "%s" LOCKNAME, path);
2190 sprintf(dpath, "%s" DATANAME, path);
2192 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2197 if (F_ISSET(flags, MDB_RDONLY)) {
2198 oflags = GENERIC_READ;
2199 len = OPEN_EXISTING;
2201 oflags = GENERIC_READ|GENERIC_WRITE;
2204 mode = FILE_ATTRIBUTE_NORMAL;
2205 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2206 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2211 if (F_ISSET(flags, MDB_RDONLY))
2214 oflags = O_RDWR | O_CREAT;
2216 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2222 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2223 /* synchronous fd for meta writes */
2225 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2226 mode |= FILE_FLAG_WRITE_THROUGH;
2227 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2228 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2233 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2234 oflags |= MDB_DSYNC;
2235 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2240 env->me_path = strdup(path);
2241 DPRINTF("opened dbenv %p", (void *) env);
2242 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2243 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2245 mdb_env_share_locks(env);
2246 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2247 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2248 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2254 if (env->me_fd != INVALID_HANDLE_VALUE) {
2256 env->me_fd = INVALID_HANDLE_VALUE;
2258 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2260 env->me_lfd = INVALID_HANDLE_VALUE;
2268 mdb_env_close(MDB_env *env)
2275 while (env->me_dpages) {
2276 dp = env->me_dpages;
2277 env->me_dpages = dp->mp_next;
2281 free(env->me_dbs[1]);
2282 free(env->me_dbs[0]);
2286 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2287 pthread_key_delete(env->me_txkey);
2290 munmap(env->me_map, env->me_mapsize);
2295 pid_t pid = getpid();
2297 for (i=0; i<env->me_txns->mti_numreaders; i++)
2298 if (env->me_txns->mti_readers[i].mr_pid == pid)
2299 env->me_txns->mti_readers[i].mr_pid = 0;
2300 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2306 /* only for aligned ints */
2308 intcmp(const MDB_val *a, const MDB_val *b)
2310 if (a->mv_size == sizeof(long))
2312 unsigned long *la, *lb;
2317 unsigned int *ia, *ib;
2324 /* ints must always be the same size */
2326 cintcmp(const MDB_val *a, const MDB_val *b)
2328 #if __BYTE_ORDER == __LITTLE_ENDIAN
2329 unsigned short *u, *c;
2332 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2333 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2336 } while(!x && u > (unsigned short *)a->mv_data);
2339 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2344 memncmp(const MDB_val *a, const MDB_val *b)
2351 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2357 diff = memcmp(a->mv_data, b->mv_data, len);
2358 return diff ? diff : len_diff<0 ? -1 : len_diff;
2362 memnrcmp(const MDB_val *a, const MDB_val *b)
2364 const unsigned char *p1, *p2, *p1_lim;
2368 p1_lim = (const unsigned char *)a->mv_data;
2369 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2370 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2372 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2378 while (p1 > p1_lim) {
2379 diff = *--p1 - *--p2;
2383 return len_diff<0 ? -1 : len_diff;
2386 /* Search for key within a leaf page, using binary search.
2387 * Returns the smallest entry larger or equal to the key.
2388 * If exactp is non-null, stores whether the found entry was an exact match
2389 * in *exactp (1 or 0).
2390 * If kip is non-null, stores the index of the found entry in *kip.
2391 * If no entry larger or equal to the key is found, returns NULL.
2394 mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp)
2396 unsigned int i = 0, nkeys;
2399 MDB_page *mp = mc->mc_pg[mc->mc_top];
2400 MDB_node *node = NULL;
2405 nkeys = NUMKEYS(mp);
2407 DPRINTF("searching %u keys in %s page %zu",
2408 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2413 low = IS_LEAF(mp) ? 0 : 1;
2415 cmp = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp;
2417 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2418 node = NODEPTR(mp, 0); /* fake */
2420 while (low <= high) {
2421 i = (low + high) >> 1;
2424 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2426 node = NODEPTR(mp, i);
2428 nodekey.mv_size = node->mn_ksize;
2429 nodekey.mv_data = NODEKEY(node);
2432 rc = cmp(key, &nodekey);
2436 DPRINTF("found leaf index %u [%s], rc = %i",
2437 i, DKEY(&nodekey), rc);
2439 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2440 i, DKEY(&nodekey), NODEPGNO(node), rc);
2451 if (rc > 0) { /* Found entry is less than the key. */
2452 i++; /* Skip to get the smallest entry larger than key. */
2454 node = NODEPTR(mp, i);
2457 *exactp = (rc == 0);
2458 /* store the key index */
2459 mc->mc_ki[mc->mc_top] = i;
2461 /* There is no entry larger or equal to the key. */
2464 /* nodeptr is fake for LEAF2 */
2469 cursor_pop_page(MDB_cursor *mc)
2474 top = mc->mc_pg[mc->mc_top];
2479 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2480 mc->mc_dbi, (void *) mc);
2485 cursor_push_page(MDB_cursor *mc, MDB_page *mp)
2487 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2488 mc->mc_dbi, (void *) mc);
2490 if (mc->mc_snum >= CURSOR_STACK)
2493 mc->mc_top = mc->mc_snum++;
2494 mc->mc_pg[mc->mc_top] = mp;
2495 mc->mc_ki[mc->mc_top] = 0;
2501 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2505 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2507 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2508 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2509 p = txn->mt_u.dirty_list[x].mptr;
2513 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2514 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2518 DPRINTF("page %zu not found", pgno);
2521 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2525 mdb_search_page_root(MDB_cursor *mc, MDB_val *key, int modify)
2527 MDB_page *mp = mc->mc_pg[mc->mc_top];
2532 while (IS_BRANCH(mp)) {
2535 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2536 assert(NUMKEYS(mp) > 1);
2537 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2539 if (key == NULL) /* Initialize cursor to first page. */
2540 mc->mc_ki[mc->mc_top] = 0;
2541 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2542 /* cursor to last page */
2543 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
2546 node = mdb_search_node(mc, key, &exact);
2548 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2550 assert(mc->mc_ki[mc->mc_top] > 0);
2551 mc->mc_ki[mc->mc_top]--;
2556 DPRINTF("following index %u for key [%s]",
2557 mc->mc_ki[mc->mc_top], DKEY(key));
2558 assert(mc->mc_ki[mc->mc_top] < NUMKEYS(mp));
2559 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2561 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mp)))
2564 if ((rc = cursor_push_page(mc, mp)))
2568 if ((rc = mdb_touch(mc)) != 0)
2570 mp = mc->mc_pg[mc->mc_top];
2575 DPRINTF("internal error, index points to a %02X page!?",
2577 return MDB_CORRUPTED;
2580 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2581 key ? DKEY(key) : NULL);
2586 /* Search for the page a given key should be in.
2587 * Pushes parent pages on the cursor stack.
2588 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2589 * If modify is true, visited pages are updated with new page numbers.
2592 mdb_search_page(MDB_cursor *mc, MDB_val *key, int modify)
2597 /* Make sure the txn is still viable, then find the root from
2598 * the txn's db table.
2600 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2601 DPUTS("transaction has failed, must abort");
2604 root = mc->mc_txn->mt_dbs[mc->mc_dbi].md_root;
2606 if (root == P_INVALID) { /* Tree is empty. */
2607 DPUTS("tree is empty");
2608 return MDB_NOTFOUND;
2611 if ((rc = mdb_get_page(mc->mc_txn, root, &mc->mc_pg[0])))
2617 DPRINTF("db %u root page %zu has flags 0x%X",
2618 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2621 /* For sub-databases, update main root first */
2622 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2624 mc2.mc_txn = mc->mc_txn;
2625 mc2.mc_dbi = MAIN_DBI;
2626 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
2629 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2631 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2632 if ((rc = mdb_touch(mc)))
2634 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mc->mc_pg[0]->mp_pgno;
2638 return mdb_search_page_root(mc, key, modify);
2642 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2644 MDB_page *omp; /* overflow mpage */
2648 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2649 data->mv_size = NODEDSZ(leaf);
2650 data->mv_data = NODEDATA(leaf);
2654 /* Read overflow data.
2656 data->mv_size = NODEDSZ(leaf);
2657 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2658 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2659 DPRINTF("read overflow page %zu failed", pgno);
2662 data->mv_data = METADATA(omp);
2668 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2669 MDB_val *key, MDB_val *data)
2678 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2680 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2683 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2690 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2691 mc.mc_xcursor = &mx;
2692 mdb_xcursor_init0(&mc);
2694 mc.mc_xcursor = NULL;
2696 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2700 mdb_sibling(MDB_cursor *mc, int move_right)
2707 if (mc->mc_snum < 2) {
2708 return MDB_NOTFOUND; /* root has no siblings */
2710 ptop = mc->mc_top-1;
2712 DPRINTF("parent page is page %zu, index %u",
2713 mc->mc_pg[ptop]->mp_pgno, mc->mc_ki[ptop]);
2715 cursor_pop_page(mc);
2716 if (move_right ? (mc->mc_ki[ptop] + 1u >= NUMKEYS(mc->mc_pg[ptop]))
2717 : (mc->mc_ki[ptop] == 0)) {
2718 DPRINTF("no more keys left, moving to %s sibling",
2719 move_right ? "right" : "left");
2720 if ((rc = mdb_sibling(mc, move_right)) != MDB_SUCCESS)
2727 DPRINTF("just moving to %s index key %u",
2728 move_right ? "right" : "left", mc->mc_ki[ptop]);
2730 assert(IS_BRANCH(mc->mc_pg[ptop]));
2732 indx = NODEPTR(mc->mc_pg[ptop], mc->mc_ki[ptop]);
2733 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(indx), &mp)))
2736 cursor_push_page(mc, mp);
2742 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2748 if (mc->mc_flags & C_EOF) {
2749 return MDB_NOTFOUND;
2752 assert(mc->mc_flags & C_INITIALIZED);
2754 mp = mc->mc_pg[mc->mc_top];
2756 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2757 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2758 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2759 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2760 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2761 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2765 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2766 if (op == MDB_NEXT_DUP)
2767 return MDB_NOTFOUND;
2771 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2773 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2774 DPUTS("=====> move to next sibling page");
2775 if (mdb_sibling(mc, 1) != MDB_SUCCESS) {
2776 mc->mc_flags |= C_EOF;
2777 return MDB_NOTFOUND;
2779 mp = mc->mc_pg[mc->mc_top];
2780 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2782 mc->mc_ki[mc->mc_top]++;
2784 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2785 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2788 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2789 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2793 assert(IS_LEAF(mp));
2794 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2796 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2797 mdb_xcursor_init1(mc, leaf);
2800 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2803 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2804 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2805 if (rc != MDB_SUCCESS)
2810 MDB_SET_KEY(leaf, key);
2815 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2821 assert(mc->mc_flags & C_INITIALIZED);
2823 mp = mc->mc_pg[mc->mc_top];
2825 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2826 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2827 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2828 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2829 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2830 if (op != MDB_PREV || rc == MDB_SUCCESS)
2833 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2834 if (op == MDB_PREV_DUP)
2835 return MDB_NOTFOUND;
2840 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2842 if (mc->mc_ki[mc->mc_top] == 0) {
2843 DPUTS("=====> move to prev sibling page");
2844 if (mdb_sibling(mc, 0) != MDB_SUCCESS) {
2845 mc->mc_flags &= ~C_INITIALIZED;
2846 return MDB_NOTFOUND;
2848 mp = mc->mc_pg[mc->mc_top];
2849 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2850 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2852 mc->mc_ki[mc->mc_top]--;
2854 mc->mc_flags &= ~C_EOF;
2856 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2857 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2860 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2861 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2865 assert(IS_LEAF(mp));
2866 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2868 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2869 mdb_xcursor_init1(mc, leaf);
2872 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2875 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2876 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
2877 if (rc != MDB_SUCCESS)
2882 MDB_SET_KEY(leaf, key);
2887 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2888 MDB_cursor_op op, int *exactp)
2896 assert(key->mv_size > 0);
2898 /* See if we're already on the right page */
2899 if (mc->mc_flags & C_INITIALIZED) {
2902 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2903 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2904 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, nodekey.mv_size);
2906 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2907 MDB_SET_KEY(leaf, &nodekey);
2909 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2911 /* Probably happens rarely, but first node on the page
2912 * was the one we wanted.
2914 mc->mc_ki[mc->mc_top] = 0;
2918 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2923 if (NUMKEYS(mc->mc_pg[mc->mc_top]) > 1) {
2924 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2925 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top],
2926 NUMKEYS(mc->mc_pg[mc->mc_top])-1, nodekey.mv_size);
2928 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
2929 MDB_SET_KEY(leaf, &nodekey);
2931 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2933 /* last node was the one we wanted */
2934 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top])-1;
2938 /* This is definitely the right page, skip search_page */
2943 /* If any parents have right-sibs, search.
2944 * Otherwise, there's nothing further.
2946 for (i=0; i<mc->mc_top; i++)
2948 NUMKEYS(mc->mc_pg[i])-1)
2950 if (i == mc->mc_top) {
2951 /* There are no other pages */
2952 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
2953 return MDB_NOTFOUND;
2958 rc = mdb_search_page(mc, key, 0);
2959 if (rc != MDB_SUCCESS)
2962 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2965 leaf = mdb_search_node(mc, key, exactp);
2966 if (exactp != NULL && !*exactp) {
2967 /* MDB_SET specified and not an exact match. */
2968 return MDB_NOTFOUND;
2972 DPUTS("===> inexact leaf not found, goto sibling");
2973 if ((rc = mdb_sibling(mc, 1)) != MDB_SUCCESS)
2974 return rc; /* no entries matched */
2975 mc->mc_ki[mc->mc_top] = 0;
2976 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2977 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2981 mc->mc_flags |= C_INITIALIZED;
2982 mc->mc_flags &= ~C_EOF;
2984 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
2985 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2986 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
2990 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2991 mdb_xcursor_init1(mc, leaf);
2994 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2995 if (op == MDB_SET || op == MDB_SET_RANGE) {
2996 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2999 if (op == MDB_GET_BOTH) {
3005 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3006 if (rc != MDB_SUCCESS)
3009 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3011 if ((rc = mdb_read_data(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3013 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dcmp(data, &d2);
3015 if (op == MDB_GET_BOTH || rc > 0)
3016 return MDB_NOTFOUND;
3020 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3025 /* The key already matches in all other cases */
3026 if (op == MDB_SET_RANGE)
3027 MDB_SET_KEY(leaf, key);
3028 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3034 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3039 rc = mdb_search_page(mc, NULL, 0);
3040 if (rc != MDB_SUCCESS)
3042 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3044 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3045 mc->mc_flags |= C_INITIALIZED;
3046 mc->mc_flags &= ~C_EOF;
3048 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3049 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3050 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3055 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3056 mdb_xcursor_init1(mc, leaf);
3057 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3062 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3063 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3067 MDB_SET_KEY(leaf, key);
3072 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3078 lkey.mv_size = MAXKEYSIZE+1;
3079 lkey.mv_data = NULL;
3081 rc = mdb_search_page(mc, &lkey, 0);
3082 if (rc != MDB_SUCCESS)
3084 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3086 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3087 mc->mc_flags |= C_INITIALIZED;
3088 mc->mc_flags &= ~C_EOF;
3090 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3092 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3093 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3094 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3099 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3100 mdb_xcursor_init1(mc, leaf);
3101 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3105 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3110 MDB_SET_KEY(leaf, key);
3115 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3125 case MDB_GET_BOTH_RANGE:
3126 if (data == NULL || mc->mc_xcursor == NULL) {
3133 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3135 } else if (op == MDB_SET_RANGE)
3136 rc = mdb_cursor_set(mc, key, data, op, NULL);
3138 rc = mdb_cursor_set(mc, key, data, op, &exact);
3140 case MDB_GET_MULTIPLE:
3142 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) ||
3143 !(mc->mc_flags & C_INITIALIZED)) {
3148 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3149 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3152 case MDB_NEXT_MULTIPLE:
3154 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED)) {
3158 if (!(mc->mc_flags & C_INITIALIZED))
3159 rc = mdb_cursor_first(mc, key, data);
3161 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3162 if (rc == MDB_SUCCESS) {
3163 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3166 mx = &mc->mc_xcursor->mx_cursor;
3167 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3168 mx->mc_txn->mt_dbs[mx->mc_dbi].md_pad;
3169 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3170 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3178 case MDB_NEXT_NODUP:
3179 if (!(mc->mc_flags & C_INITIALIZED))
3180 rc = mdb_cursor_first(mc, key, data);
3182 rc = mdb_cursor_next(mc, key, data, op);
3186 case MDB_PREV_NODUP:
3187 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3188 rc = mdb_cursor_last(mc, key, data);
3190 rc = mdb_cursor_prev(mc, key, data, op);
3193 rc = mdb_cursor_first(mc, key, data);
3197 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3198 !(mc->mc_flags & C_INITIALIZED) ||
3199 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3203 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3206 rc = mdb_cursor_last(mc, key, data);
3210 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3211 !(mc->mc_flags & C_INITIALIZED) ||
3212 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3216 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3219 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3228 mdb_cursor_touch(MDB_cursor *mc)
3232 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
3234 mc2.mc_txn = mc->mc_txn;
3235 mc2.mc_dbi = MAIN_DBI;
3236 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
3238 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3240 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3241 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3245 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root =
3246 mc->mc_pg[mc->mc_top]->mp_pgno;
3250 mc->mc_top = mc->mc_snum-1;
3255 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3259 MDB_val xdata, *rdata, dkey;
3261 char dbuf[PAGESIZE];
3267 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3270 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3271 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3275 if (flags == MDB_CURRENT) {
3276 if (!(mc->mc_flags & C_INITIALIZED))
3279 } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
3281 /* new database, write a root leaf page */
3282 DPUTS("allocating new root leaf page");
3283 if ((np = mdb_new_page(mc, P_LEAF, 1)) == NULL) {
3287 cursor_push_page(mc, np);
3288 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = np->mp_pgno;
3289 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
3290 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3291 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3293 np->mp_flags |= P_LEAF2;
3294 mc->mc_flags |= C_INITIALIZED;
3300 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3301 if (flags == MDB_NOOVERWRITE && rc == 0) {
3302 DPRINTF("duplicate key [%s]", DKEY(key));
3304 return MDB_KEYEXIST;
3306 if (rc && rc != MDB_NOTFOUND)
3310 /* Cursor is positioned, now make sure all pages are writable */
3311 rc2 = mdb_cursor_touch(mc);
3312 if (rc2) return rc2;
3315 /* The key already exists */
3316 if (rc == MDB_SUCCESS) {
3317 /* there's only a key anyway, so this is a no-op */
3318 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3319 unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3320 if (key->mv_size != ksize)
3322 if (flags == MDB_CURRENT) {
3323 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3324 memcpy(ptr, key->mv_data, ksize);
3329 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3332 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
3333 /* Was a single item before, must convert now */
3334 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3335 dkey.mv_size = NODEDSZ(leaf);
3336 dkey.mv_data = dbuf;
3337 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3338 /* data matches, ignore it */
3339 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
3340 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3341 memset(&dummy, 0, sizeof(dummy));
3342 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
3343 dummy.md_pad = data->mv_size;
3344 dummy.md_flags = MDB_DUPFIXED;
3345 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
3346 dummy.md_flags |= MDB_INTEGERKEY;
3348 dummy.md_root = P_INVALID;
3349 if (dkey.mv_size == sizeof(MDB_db)) {
3350 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3353 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3356 xdata.mv_size = sizeof(MDB_db);
3357 xdata.mv_data = &dummy;
3358 /* new sub-DB, must fully init xcursor */
3359 if (flags == MDB_CURRENT)
3365 /* same size, just replace it */
3366 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3367 NODEDSZ(leaf) == data->mv_size) {
3368 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3371 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3373 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3379 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3380 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3381 rc = mdb_split(mc, key, rdata, P_INVALID);
3383 /* There is room already in this leaf page. */
3384 rc = mdb_add_node(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3387 if (rc != MDB_SUCCESS)
3388 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3390 /* Remember if we just added a subdatabase */
3391 if (flags & F_SUBDATA) {
3392 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3393 leaf->mn_flags |= F_SUBDATA;
3396 /* Now store the actual data in the child DB. Note that we're
3397 * storing the user data in the keys field, so there are strict
3398 * size limits on dupdata. The actual data fields of the child
3399 * DB are all zero size.
3402 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3404 if (flags == MDB_CURRENT)
3405 mdb_xcursor_init2(mc);
3407 mdb_xcursor_init1(mc, leaf);
3410 if (flags == MDB_NODUPDATA)
3411 flags = MDB_NOOVERWRITE;
3412 /* converted, write the original data first */
3414 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3416 leaf->mn_flags |= F_DUPDATA;
3418 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3419 mdb_xcursor_fini(mc);
3420 memcpy(NODEDATA(leaf),
3421 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3424 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3431 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3436 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3439 if (!mc->mc_flags & C_INITIALIZED)
3442 rc = mdb_cursor_touch(mc);
3445 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3447 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3448 if (flags != MDB_NODUPDATA) {
3449 mdb_xcursor_init2(mc);
3450 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3451 mdb_xcursor_fini(mc);
3452 /* If sub-DB still has entries, we're done */
3453 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3455 memcpy(NODEDATA(leaf),
3456 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3458 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3461 /* otherwise fall thru and delete the sub-DB */
3464 /* add all the child DB's pages to the free list */
3465 rc = mdb_search_page(&mc->mc_xcursor->mx_cursor, NULL, 0);
3466 if (rc == MDB_SUCCESS) {
3471 mx = &mc->mc_xcursor->mx_cursor;
3472 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3473 mx->mc_txn->mt_dbs[mx->mc_dbi].md_entries;
3475 cursor_pop_page(mx);
3477 while (mx->mc_snum > 1) {
3478 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3480 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3483 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3485 rc = mdb_sibling(mx, 1);
3490 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3491 mx->mc_txn->mt_dbs[mx->mc_dbi].md_root);
3495 return mdb_del0(mc, leaf);
3498 /* Allocate a page and initialize it
3501 mdb_new_page(MDB_cursor *mc, uint32_t flags, int num)
3505 if ((np = mdb_alloc_page(mc, num)) == NULL)
3507 DPRINTF("allocated new mpage %zu, page size %u",
3508 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3509 np->mp_flags = flags | P_DIRTY;
3510 np->mp_lower = PAGEHDRSZ;
3511 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3514 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages++;
3515 else if (IS_LEAF(np))
3516 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages++;
3517 else if (IS_OVERFLOW(np)) {
3518 mc->mc_txn->mt_dbs[mc->mc_dbi].md_overflow_pages += num;
3526 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3530 sz = LEAFSIZE(key, data);
3531 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3532 /* put on overflow page */
3533 sz -= data->mv_size - sizeof(pgno_t);
3537 return sz + sizeof(indx_t);
3541 mdb_branch_size(MDB_env *env, MDB_val *key)
3546 if (sz >= env->me_psize / MDB_MINKEYS) {
3547 /* put on overflow page */
3548 /* not implemented */
3549 /* sz -= key->size - sizeof(pgno_t); */
3552 return sz + sizeof(indx_t);
3556 mdb_add_node(MDB_cursor *mc, indx_t indx,
3557 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3560 size_t node_size = NODESIZE;
3563 MDB_page *mp = mc->mc_pg[mc->mc_top];
3564 MDB_page *ofp = NULL; /* overflow page */
3567 assert(mp->mp_upper >= mp->mp_lower);
3569 DPRINTF("add to %s page %zu index %i, data size %zu key size %zu [%s]",
3570 IS_LEAF(mp) ? "leaf" : "branch",
3571 mp->mp_pgno, indx, data ? data->mv_size : 0,
3572 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3575 /* Move higher keys up one slot. */
3576 int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad, dif;
3577 char *ptr = LEAF2KEY(mp, indx, ksize);
3578 dif = NUMKEYS(mp) - indx;
3580 memmove(ptr+ksize, ptr, dif*ksize);
3581 /* insert new key */
3582 memcpy(ptr, key->mv_data, ksize);
3584 /* Just using these for counting */
3585 mp->mp_lower += sizeof(indx_t);
3586 mp->mp_upper -= ksize - sizeof(indx_t);
3591 node_size += key->mv_size;
3595 if (F_ISSET(flags, F_BIGDATA)) {
3596 /* Data already on overflow page. */
3597 node_size += sizeof(pgno_t);
3598 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3599 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3600 /* Put data on overflow page. */
3601 DPRINTF("data size is %zu, put on overflow page",
3603 node_size += sizeof(pgno_t);
3604 if ((ofp = mdb_new_page(mc, P_OVERFLOW, ovpages)) == NULL)
3606 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
3609 node_size += data->mv_size;
3612 node_size += node_size & 1;
3614 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3615 DPRINTF("not enough room in page %zu, got %u ptrs",
3616 mp->mp_pgno, NUMKEYS(mp));
3617 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3618 mp->mp_upper - mp->mp_lower);
3619 DPRINTF("node size = %zu", node_size);
3623 /* Move higher pointers up one slot. */
3624 for (i = NUMKEYS(mp); i > indx; i--)
3625 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3627 /* Adjust free space offsets. */
3628 ofs = mp->mp_upper - node_size;
3629 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3630 mp->mp_ptrs[indx] = ofs;
3632 mp->mp_lower += sizeof(indx_t);
3634 /* Write the node data. */
3635 node = NODEPTR(mp, indx);
3636 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3637 node->mn_flags = flags;
3639 SETDSZ(node,data->mv_size);
3644 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3649 if (F_ISSET(flags, F_BIGDATA))
3650 memcpy(node->mn_data + key->mv_size, data->mv_data,
3653 memcpy(node->mn_data + key->mv_size, data->mv_data,
3656 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3658 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3666 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3669 indx_t i, j, numkeys, ptr;
3673 DPRINTF("delete node %u on %s page %zu", indx,
3674 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3675 assert(indx < NUMKEYS(mp));
3678 int x = NUMKEYS(mp) - 1 - indx;
3679 base = LEAF2KEY(mp, indx, ksize);
3681 memmove(base, base + ksize, x * ksize);
3682 mp->mp_lower -= sizeof(indx_t);
3683 mp->mp_upper += ksize - sizeof(indx_t);
3687 node = NODEPTR(mp, indx);
3688 sz = NODESIZE + node->mn_ksize;
3690 if (F_ISSET(node->mn_flags, F_BIGDATA))
3691 sz += sizeof(pgno_t);
3693 sz += NODEDSZ(node);
3697 ptr = mp->mp_ptrs[indx];
3698 numkeys = NUMKEYS(mp);
3699 for (i = j = 0; i < numkeys; i++) {
3701 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3702 if (mp->mp_ptrs[i] < ptr)
3703 mp->mp_ptrs[j] += sz;
3708 base = (char *)mp + mp->mp_upper;
3709 memmove(base + sz, base, ptr - mp->mp_upper);
3711 mp->mp_lower -= sizeof(indx_t);
3716 mdb_xcursor_init0(MDB_cursor *mc)
3718 MDB_xcursor *mx = mc->mc_xcursor;
3721 mx->mx_txn = *mc->mc_txn;
3722 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3723 mx->mx_txn.mt_dbs = mx->mx_dbs;
3724 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3725 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3726 if (mc->mc_dbi > 1) {
3727 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3732 mx->mx_dbxs[dbn+1].md_parent = dbn;
3733 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3734 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3735 mx->mx_dbxs[dbn+1].md_dirty = 0;
3736 mx->mx_txn.mt_numdbs = dbn+2;
3737 mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3739 mx->mx_cursor.mc_xcursor = NULL;
3740 mx->mx_cursor.mc_txn = &mx->mx_txn;
3741 mx->mx_cursor.mc_dbi = dbn+1;
3745 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
3747 MDB_db *db = NODEDATA(node);
3748 MDB_xcursor *mx = mc->mc_xcursor;
3750 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3751 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3752 if (mc->mc_dbi > 1) {
3753 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3754 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3759 DPRINTF("Sub-db %u for db %u root page %zu", dbn, mc->mc_dbi, db->md_root);
3760 mx->mx_dbs[dbn] = *db;
3761 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
3762 mx->mx_dbxs[dbn].md_dirty = 1;
3763 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3764 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3765 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3766 mx->mx_cursor.mc_snum = 0;
3767 mx->mx_cursor.mc_flags = 0;
3771 mdb_xcursor_init2(MDB_cursor *mc)
3773 MDB_xcursor *mx = mc->mc_xcursor;
3775 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3776 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3777 if (mc->mc_dbi > 1) {
3778 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3779 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3784 DPRINTF("Sub-db %u for db %u root page %zu", dbn, mc->mc_dbi,
3785 mx->mx_dbs[dbn].md_root);
3786 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3790 mdb_xcursor_fini(MDB_cursor *mc)
3792 MDB_xcursor *mx = mc->mc_xcursor;
3793 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3794 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3795 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3796 if (mc->mc_dbi > 1) {
3797 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3798 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3803 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3806 size_t size = sizeof(MDB_cursor);
3808 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3811 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3812 size += sizeof(MDB_xcursor);
3814 if ((mc = calloc(1, size)) != NULL) {
3817 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3818 MDB_xcursor *mx = (MDB_xcursor *)(mc + 1);
3819 mc->mc_xcursor = mx;
3820 mdb_xcursor_init0(mc);
3831 /* Return the count of duplicate data items for the current key */
3833 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
3837 if (mc == NULL || countp == NULL)
3840 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3843 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3844 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3847 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3850 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3856 mdb_cursor_close(MDB_cursor *mc)
3864 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3866 indx_t ptr, i, numkeys;
3873 node = NODEPTR(mp, indx);
3874 ptr = mp->mp_ptrs[indx];
3875 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
3877 (int)node->mn_ksize, (char *)NODEKEY(node),
3881 delta = key->mv_size - node->mn_ksize;
3883 if (delta > 0 && SIZELEFT(mp) < delta) {
3884 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3888 numkeys = NUMKEYS(mp);
3889 for (i = 0; i < numkeys; i++) {
3890 if (mp->mp_ptrs[i] <= ptr)
3891 mp->mp_ptrs[i] -= delta;
3894 base = (char *)mp + mp->mp_upper;
3895 len = ptr - mp->mp_upper + NODESIZE;
3896 memmove(base - delta, base, len);
3897 mp->mp_upper -= delta;
3899 node = NODEPTR(mp, indx);
3900 node->mn_ksize = key->mv_size;
3903 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3908 /* Move a node from csrc to cdst.
3911 mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst)
3918 /* Mark src and dst as dirty. */
3919 if ((rc = mdb_touch(csrc)) ||
3920 (rc = mdb_touch(cdst)))
3923 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3924 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
3925 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
3926 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3928 data.mv_data = NULL;
3930 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3931 unsigned int snum = csrc->mc_snum;
3932 /* must find the lowest key below src */
3933 mdb_search_page_root(csrc, NULL, 0);
3934 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
3935 csrc->mc_snum = snum--;
3936 csrc->mc_top = snum;
3938 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3940 key.mv_size = NODEKSZ(srcnode);
3941 key.mv_data = NODEKEY(srcnode);
3942 data.mv_size = NODEDSZ(srcnode);
3943 data.mv_data = NODEDATA(srcnode);
3945 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
3946 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
3947 csrc->mc_ki[csrc->mc_top],
3949 csrc->mc_pg[csrc->mc_top]->mp_pgno,
3950 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
3952 /* Add the node to the destination page.
3954 rc = mdb_add_node(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
3956 if (rc != MDB_SUCCESS)
3959 /* Delete the node from the source page.
3961 mdb_del_node(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3963 /* Update the parent separators.
3965 if (csrc->mc_ki[csrc->mc_top] == 0) {
3966 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
3967 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3968 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3970 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3971 key.mv_size = NODEKSZ(srcnode);
3972 key.mv_data = NODEKEY(srcnode);
3974 DPRINTF("update separator for source page %zu to [%s]",
3975 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
3976 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
3977 &key)) != MDB_SUCCESS)
3980 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3982 nullkey.mv_size = 0;
3983 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
3987 if (cdst->mc_ki[cdst->mc_top] == 0) {
3988 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
3989 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3990 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
3992 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
3993 key.mv_size = NODEKSZ(srcnode);
3994 key.mv_data = NODEKEY(srcnode);
3996 DPRINTF("update separator for destination page %zu to [%s]",
3997 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
3998 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
3999 &key)) != MDB_SUCCESS)
4002 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4004 nullkey.mv_size = 0;
4005 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4013 mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4020 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4021 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4023 assert(csrc->mc_snum > 1); /* can't merge root page */
4024 assert(cdst->mc_snum > 1);
4026 /* Mark dst as dirty. */
4027 if ((rc = mdb_touch(cdst)))
4030 /* Move all nodes from src to dst.
4032 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4033 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4034 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
4035 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4036 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4037 rc = mdb_add_node(cdst, j, &key, NULL, 0, 0);
4038 if (rc != MDB_SUCCESS)
4040 key.mv_data = (char *)key.mv_data + key.mv_size;
4043 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4044 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4046 key.mv_size = srcnode->mn_ksize;
4047 key.mv_data = NODEKEY(srcnode);
4048 data.mv_size = NODEDSZ(srcnode);
4049 data.mv_data = NODEDATA(srcnode);
4050 rc = mdb_add_node(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4051 if (rc != MDB_SUCCESS)
4056 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4057 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);
4059 /* Unlink the src page from parent and add to free list.
4061 mdb_del_node(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4062 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4064 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4068 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4069 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4070 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_leaf_pages--;
4072 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_branch_pages--;
4073 cursor_pop_page(csrc);
4075 return mdb_rebalance(csrc);
4079 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4083 cdst->mc_txn = csrc->mc_txn;
4084 cdst->mc_dbi = csrc->mc_dbi;
4085 cdst->mc_snum = csrc->mc_snum;
4086 cdst->mc_top = csrc->mc_top;
4087 cdst->mc_flags = csrc->mc_flags;
4089 for (i=0; i<csrc->mc_snum; i++) {
4090 cdst->mc_pg[i] = csrc->mc_pg[i];
4091 cdst->mc_ki[i] = csrc->mc_ki[i];
4096 mdb_rebalance(MDB_cursor *mc)
4104 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4105 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4106 mc->mc_pg[mc->mc_top]->mp_pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
4108 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4109 DPRINTF("no need to rebalance page %zu, above fill threshold",
4110 mc->mc_pg[mc->mc_top]->mp_pgno);
4114 if (mc->mc_snum < 2) {
4115 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4116 DPUTS("tree is completely empty");
4117 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = P_INVALID;
4118 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth = 0;
4119 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages = 0;
4120 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4121 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4122 DPUTS("collapsing root page!");
4123 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4124 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4125 if ((rc = mdb_get_page(mc->mc_txn, mc->mc_txn->mt_dbs[mc->mc_dbi].md_root, &root)))
4127 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4128 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages--;
4130 DPUTS("root page doesn't need rebalancing");
4134 /* The parent (branch page) must have at least 2 pointers,
4135 * otherwise the tree is invalid.
4137 ptop = mc->mc_top-1;
4138 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4140 /* Leaf page fill factor is below the threshold.
4141 * Try to move keys from left or right neighbor, or
4142 * merge with a neighbor page.
4147 mdb_cursor_copy(mc, &mn);
4148 mn.mc_xcursor = NULL;
4150 if (mc->mc_ki[ptop] == 0) {
4151 /* We're the leftmost leaf in our parent.
4153 DPUTS("reading right neighbor");
4155 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4156 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4158 mn.mc_ki[mn.mc_top] = 0;
4159 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4161 /* There is at least one neighbor to the left.
4163 DPUTS("reading left neighbor");
4165 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4166 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4168 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4169 mc->mc_ki[mc->mc_top] = 0;
4172 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4173 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);
4175 /* If the neighbor page is above threshold and has at least two
4176 * keys, move one key from it.
4178 * Otherwise we should try to merge them.
4180 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4181 return mdb_move_node(&mn, mc);
4182 else { /* FIXME: if (has_enough_room()) */
4183 if (mc->mc_ki[ptop] == 0)
4184 return mdb_merge(&mn, mc);
4186 return mdb_merge(mc, &mn);
4191 mdb_del0(MDB_cursor *mc, MDB_node *leaf)
4195 /* add overflow pages to free list */
4196 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4200 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4201 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4202 for (i=0; i<ovpages; i++) {
4203 DPRINTF("freed ov page %zu", pg);
4204 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4208 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad);
4209 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
4210 rc = mdb_rebalance(mc);
4211 if (rc != MDB_SUCCESS)
4212 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4218 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4219 MDB_val *key, MDB_val *data)
4224 MDB_val rdata, *xdata;
4228 assert(key != NULL);
4230 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4232 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4235 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4239 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4246 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4247 mc.mc_xcursor = &mx;
4248 mdb_xcursor_init0(&mc);
4250 mc.mc_xcursor = NULL;
4262 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4264 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4268 /* Split page <mc->top>, and insert <key,(data|newpgno)> in either left or
4269 * right sibling, at index <mc->ki> (as if unsplit). Updates mc->top and
4270 * mc->ki with the actual values after split, ie if mc->top and mc->ki
4271 * refer to a node in the new right sibling page.
4274 mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4277 int rc = MDB_SUCCESS, ins_new = 0;
4280 unsigned int i, j, split_indx, nkeys, pmax;
4282 MDB_val sepkey, rkey, rdata;
4284 MDB_page *mp, *rp, *pp;
4289 mp = mc->mc_pg[mc->mc_top];
4290 newindx = mc->mc_ki[mc->mc_top];
4292 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4293 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4294 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4296 if (mc->mc_snum < 2) {
4297 if ((pp = mdb_new_page(mc, P_BRANCH, 1)) == NULL)
4299 /* shift current top to make room for new parent */
4300 mc->mc_pg[1] = mc->mc_pg[0];
4301 mc->mc_ki[1] = mc->mc_ki[0];
4304 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = pp->mp_pgno;
4305 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4306 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
4308 /* Add left (implicit) pointer. */
4309 if ((rc = mdb_add_node(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4310 /* undo the pre-push */
4311 mc->mc_pg[0] = mc->mc_pg[1];
4312 mc->mc_ki[0] = mc->mc_ki[1];
4313 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mp->mp_pgno;
4314 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4321 ptop = mc->mc_top-1;
4322 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4325 /* Create a right sibling. */
4326 if ((rp = mdb_new_page(mc, mp->mp_flags, 1)) == NULL)
4328 mdb_cursor_copy(mc, &mn);
4329 mn.mc_pg[mn.mc_top] = rp;
4330 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4331 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4333 nkeys = NUMKEYS(mp);
4334 split_indx = nkeys / 2 + 1;
4339 unsigned int lsize, rsize, ksize;
4340 /* Move half of the keys to the right sibling */
4342 x = mc->mc_ki[mc->mc_top] - split_indx;
4343 ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
4344 split = LEAF2KEY(mp, split_indx, ksize);
4345 rsize = (nkeys - split_indx) * ksize;
4346 lsize = (nkeys - split_indx) * sizeof(indx_t);
4347 mp->mp_lower -= lsize;
4348 rp->mp_lower += lsize;
4349 mp->mp_upper += rsize - lsize;
4350 rp->mp_upper -= rsize - lsize;
4351 sepkey.mv_size = ksize;
4352 if (newindx == split_indx) {
4353 sepkey.mv_data = newkey->mv_data;
4355 sepkey.mv_data = split;
4358 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4359 memcpy(rp->mp_ptrs, split, rsize);
4360 sepkey.mv_data = rp->mp_ptrs;
4361 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4362 memcpy(ins, newkey->mv_data, ksize);
4363 mp->mp_lower += sizeof(indx_t);
4364 mp->mp_upper -= ksize - sizeof(indx_t);
4367 memcpy(rp->mp_ptrs, split, x * ksize);
4368 ins = LEAF2KEY(rp, x, ksize);
4369 memcpy(ins, newkey->mv_data, ksize);
4370 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4371 rp->mp_lower += sizeof(indx_t);
4372 rp->mp_upper -= ksize - sizeof(indx_t);
4373 mc->mc_ki[mc->mc_top] = x;
4374 mc->mc_pg[mc->mc_top] = rp;
4379 /* For leaf pages, check the split point based on what
4380 * fits where, since otherwise add_node can fail.
4383 unsigned int psize, nsize;
4384 /* Maximum free space in an empty page */
4385 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4386 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4387 if (newindx < split_indx) {
4389 for (i=0; i<split_indx; i++) {
4390 node = NODEPTR(mp, i);
4391 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4392 if (F_ISSET(node->mn_flags, F_BIGDATA))
4393 psize += sizeof(pgno_t);
4395 psize += NODEDSZ(node);
4404 for (i=nkeys-1; i>=split_indx; i--) {
4405 node = NODEPTR(mp, i);
4406 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4407 if (F_ISSET(node->mn_flags, F_BIGDATA))
4408 psize += sizeof(pgno_t);
4410 psize += NODEDSZ(node);
4420 /* First find the separating key between the split pages.
4422 if (newindx == split_indx) {
4423 sepkey.mv_size = newkey->mv_size;
4424 sepkey.mv_data = newkey->mv_data;
4426 node = NODEPTR(mp, split_indx);
4427 sepkey.mv_size = node->mn_ksize;
4428 sepkey.mv_data = NODEKEY(node);
4432 DPRINTF("separator is [%s]", DKEY(&sepkey));
4434 /* Copy separator key to the parent.
4436 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4439 rc = mdb_split(&mn, &sepkey, NULL, rp->mp_pgno);
4441 /* Right page might now have changed parent.
4442 * Check if left page also changed parent.
4444 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4445 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4446 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4447 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4451 rc = mdb_add_node(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4457 if (rc != MDB_SUCCESS) {
4461 /* Move half of the keys to the right sibling. */
4463 /* grab a page to hold a temporary copy */
4464 if (mc->mc_txn->mt_env->me_dpages) {
4465 copy = mc->mc_txn->mt_env->me_dpages;
4466 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4468 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4472 copy->mp_pgno = mp->mp_pgno;
4473 copy->mp_flags = mp->mp_flags;
4474 copy->mp_lower = PAGEHDRSZ;
4475 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4476 mc->mc_pg[mc->mc_top] = copy;
4477 for (i = j = 0; i <= nkeys; j++) {
4478 if (i == split_indx) {
4479 /* Insert in right sibling. */
4480 /* Reset insert index for right sibling. */
4481 j = (i == newindx && ins_new);
4482 mc->mc_pg[mc->mc_top] = rp;
4485 if (i == newindx && !ins_new) {
4486 /* Insert the original entry that caused the split. */
4487 rkey.mv_data = newkey->mv_data;
4488 rkey.mv_size = newkey->mv_size;
4490 rdata.mv_data = newdata->mv_data;
4491 rdata.mv_size = newdata->mv_size;
4498 /* Update page and index for the new key. */
4499 mc->mc_ki[mc->mc_top] = j;
4500 } else if (i == nkeys) {
4503 node = NODEPTR(mp, i);
4504 rkey.mv_data = NODEKEY(node);
4505 rkey.mv_size = node->mn_ksize;
4507 rdata.mv_data = NODEDATA(node);
4508 rdata.mv_size = NODEDSZ(node);
4510 pgno = NODEPGNO(node);
4511 flags = node->mn_flags;
4516 if (!IS_LEAF(mp) && j == 0) {
4517 /* First branch index doesn't need key data. */
4521 rc = mdb_add_node(mc, j, &rkey, &rdata, pgno, flags);
4524 /* reset back to original page */
4525 if (newindx < split_indx)
4526 mc->mc_pg[mc->mc_top] = mp;
4528 nkeys = NUMKEYS(copy);
4529 for (i=0; i<nkeys; i++)
4530 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4531 mp->mp_lower = copy->mp_lower;
4532 mp->mp_upper = copy->mp_upper;
4533 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4534 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4536 /* return tmp page to freelist */
4537 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4538 mc->mc_txn->mt_env->me_dpages = copy;
4543 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4544 MDB_val *key, MDB_val *data, unsigned int flags)
4549 assert(key != NULL);
4550 assert(data != NULL);
4552 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4555 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4559 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4563 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4570 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4571 mc.mc_xcursor = &mx;
4572 mdb_xcursor_init0(&mc);
4574 mc.mc_xcursor = NULL;
4576 return mdb_cursor_put(&mc, key, data, flags);
4580 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4582 /** Only a subset of the @ref mdb_env flags can be changed
4583 * at runtime. Changing other flags requires closing the environment
4584 * and re-opening it with the new flags.
4586 #define CHANGEABLE (MDB_NOSYNC)
4587 if ((flag & CHANGEABLE) != flag)
4590 env->me_flags |= flag;
4592 env->me_flags &= ~flag;
4597 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4602 *arg = env->me_flags;
4607 mdb_env_get_path(MDB_env *env, const char **arg)
4612 *arg = env->me_path;
4617 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4619 arg->ms_psize = env->me_psize;
4620 arg->ms_depth = db->md_depth;
4621 arg->ms_branch_pages = db->md_branch_pages;
4622 arg->ms_leaf_pages = db->md_leaf_pages;
4623 arg->ms_overflow_pages = db->md_overflow_pages;
4624 arg->ms_entries = db->md_entries;
4629 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4633 if (env == NULL || arg == NULL)
4636 mdb_env_read_meta(env, &toggle);
4638 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4642 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4644 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4645 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4646 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4647 txn->mt_dbxs[dbi].md_cmp = cintcmp;
4649 txn->mt_dbxs[dbi].md_cmp = memncmp;
4651 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4652 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4653 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4654 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4656 txn->mt_dbxs[dbi].md_dcmp = cintcmp;
4657 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4658 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4660 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4663 txn->mt_dbxs[dbi].md_dcmp = NULL;
4667 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4674 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4675 mdb_default_cmp(txn, FREE_DBI);
4681 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4682 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4683 mdb_default_cmp(txn, MAIN_DBI);
4687 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4688 mdb_default_cmp(txn, MAIN_DBI);
4691 /* Is the DB already open? */
4693 for (i=2; i<txn->mt_numdbs; i++) {
4694 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4695 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4701 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4704 /* Find the DB info */
4706 key.mv_data = (void *)name;
4707 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4709 /* Create if requested */
4710 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4713 data.mv_size = sizeof(MDB_db);
4714 data.mv_data = &dummy;
4715 memset(&dummy, 0, sizeof(dummy));
4716 dummy.md_root = P_INVALID;
4717 dummy.md_flags = flags & 0xffff;
4719 mc.mc_dbi = MAIN_DBI;
4721 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4725 /* OK, got info, add to table */
4726 if (rc == MDB_SUCCESS) {
4727 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4728 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4729 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4730 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4731 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4732 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4733 *dbi = txn->mt_numdbs;
4734 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4735 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4736 mdb_default_cmp(txn, txn->mt_numdbs);
4743 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4745 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4748 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4751 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4754 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4756 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4757 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4758 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4762 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4764 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4767 txn->mt_dbxs[dbi].md_cmp = cmp;
4771 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4773 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4776 txn->mt_dbxs[dbi].md_dcmp = cmp;
4780 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4782 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4785 txn->mt_dbxs[dbi].md_rel = rel;