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
66 /** @defgroup internal MDB Internals
69 /** @defgroup compat Windows Compatibility Macros
70 * A bunch of macros to minimize the amount of platform-specific ifdefs
71 * needed throughout the rest of the code. When the features this library
72 * needs are similar enough to POSIX to be hidden in a one-or-two line
73 * replacement, this macro approach is used.
77 #define pthread_t DWORD
78 #define pthread_mutex_t HANDLE
79 #define pthread_key_t DWORD
80 #define pthread_self() GetCurrentThreadId()
81 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
82 #define pthread_key_delete(x) TlsFree(x)
83 #define pthread_getspecific(x) TlsGetValue(x)
84 #define pthread_setspecific(x,y) TlsSetValue(x,y)
85 #define pthread_mutex_unlock(x) ReleaseMutex(x)
86 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
87 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
88 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
89 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
90 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
91 #define getpid() GetCurrentProcessId()
92 #define fdatasync(fd) (!FlushFileBuffers(fd))
93 #define ErrCode() GetLastError()
94 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
95 #define close(fd) CloseHandle(fd)
96 #define munmap(ptr,len) UnmapViewOfFile(ptr)
98 /** Lock the reader mutex.
100 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
101 /** Unlock the reader mutex.
103 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
105 /** Lock the writer mutex.
106 * Only a single write transaction is allowed at a time. Other writers
107 * will block waiting for this mutex.
109 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
110 /** Unlock the writer mutex.
112 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
114 /** Get the error code for the last failed system function.
116 #define ErrCode() errno
118 /** An abstraction for a file handle.
119 * On POSIX systems file handles are small integers. On Windows
120 * they're opaque pointers.
124 /** A value for an invalid file handle.
125 * Mainly used to initialize file variables and signify that they are
128 #define INVALID_HANDLE_VALUE (-1)
130 /** Get the size of a memory page for the system.
131 * This is the basic size that the platform's memory manager uses, and is
132 * fundamental to the use of memory-mapped files.
134 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
140 /** A flag for opening a file and requesting synchronous data writes.
141 * This is only used when writing a meta page. It's not strictly needed;
142 * we could just do a normal write and then immediately perform a flush.
143 * But if this flag is available it saves us an extra system call.
145 * @note If O_DSYNC is undefined but exists in /usr/include,
146 * preferably set some compiler flag to get the definition.
147 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
150 # define MDB_DSYNC O_DSYNC
154 /** A page number in the database.
155 * Note that 64 bit page numbers are overkill, since pages themselves
156 * already represent 12-13 bits of addressable memory, and the OS will
157 * always limit applications to a maximum of 63 bits of address space.
159 * @note In the #MDB_node structure, we only store 48 bits of this value,
160 * which thus limits us to only 60 bits of addressable data.
162 typedef ULONG pgno_t;
164 /** @defgroup debug Debug Macros
168 /** Enable debug output.
169 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
170 * read from and written to the database (used for free space management).
175 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
176 # define DPRINTF (void) /* Vararg macros may be unsupported */
178 /** Print a debug message with printf formatting. */
179 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
180 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
182 # define DPRINTF(fmt, ...) ((void) 0)
184 /** Print a debug string.
185 * The string is printed literally, with no format processing.
187 #define DPUTS(arg) DPRINTF("%s", arg)
190 /** A default memory page size.
191 * The actual size is platform-dependent, but we use this for
192 * boot-strapping. We probably should not be using this any more.
193 * The #GET_PAGESIZE() macro is used to get the actual size.
195 * Note that we don't currently support Huge pages. On Linux,
196 * regular data files cannot use Huge pages, and in general
197 * Huge pages aren't actually pageable. We rely on the OS
198 * demand-pager to read our data and page it out when memory
199 * pressure from other processes is high. So until OSs have
200 * actual paging support for Huge pages, they're not viable.
202 #define PAGESIZE 4096
204 /** The minimum number of keys required in a database page.
205 * Setting this to a larger value will place a smaller bound on the
206 * maximum size of a data item. Data items larger than this size will
207 * be pushed into overflow pages instead of being stored directly in
208 * the B-tree node. This value used to default to 4. With a page size
209 * of 4096 bytes that meant that any item larger than 1024 bytes would
210 * go into an overflow page. That also meant that on average 2-3KB of
211 * each overflow page was wasted space. The value cannot be lower than
212 * 2 because then there would no longer be a tree structure. With this
213 * value, items larger than 2KB will go into overflow pages, and on
214 * average only 1KB will be wasted.
216 #define MDB_MINKEYS 2
218 /** A stamp that identifies a file as an MDB file.
219 * There's nothing special about this value other than that it is easily
220 * recognizable, and it will reflect any byte order mismatches.
222 #define MDB_MAGIC 0xBEEFC0DE
224 /** The version number for a database's file format. */
225 #define MDB_VERSION 1
227 /** The maximum size of a key in the database.
228 * While data items have essentially unbounded size, we require that
229 * keys all fit onto a regular page. This limit could be raised a bit
230 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
232 #define MAXKEYSIZE 511
237 * This is used for printing a hex dump of a key's contents.
239 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
240 /** Display a key in hex.
242 * Invoke a function to display a key in hex.
244 #define DKEY(x) mdb_dkey(x, kbuf)
246 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
250 /** @defgroup lazylock Lazy Locking
251 * Macros for locks that are't actually needed.
252 * The DB view is always consistent because all writes are wrapped in
253 * the wmutex. Finer-grained locks aren't necessary.
257 /** Use lazy locking. I.e., don't lock these accesses at all. */
261 /** Grab the reader lock */
262 #define LAZY_MUTEX_LOCK(x)
263 /** Release the reader lock */
264 #define LAZY_MUTEX_UNLOCK(x)
265 /** Release the DB table reader/writer lock */
266 #define LAZY_RWLOCK_UNLOCK(x)
267 /** Grab the DB table write lock */
268 #define LAZY_RWLOCK_WRLOCK(x)
269 /** Grab the DB table read lock */
270 #define LAZY_RWLOCK_RDLOCK(x)
271 /** Declare the DB table rwlock. Should not be followed by ';'. */
272 #define LAZY_RWLOCK_DEF(x)
273 /** Initialize the DB table rwlock */
274 #define LAZY_RWLOCK_INIT(x,y)
275 /** Destroy the DB table rwlock */
276 #define LAZY_RWLOCK_DESTROY(x)
278 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
279 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
280 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
281 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
282 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
283 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
284 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
285 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
289 /** An invalid page number.
290 * Mainly used to denote an empty tree.
292 #define P_INVALID (~0UL)
294 /** Test if a flag \b f is set in a flag word \b w. */
295 #define F_ISSET(w, f) (((w) & (f)) == (f))
297 /** Used for offsets within a single page.
298 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
301 typedef uint16_t indx_t;
303 /** Default size of memory map.
304 * This is certainly too small for any actual applications. Apps should always set
305 * the size explicitly using #mdb_env_set_mapsize().
307 #define DEFAULT_MAPSIZE 1048576
309 /** @defgroup readers Reader Lock Table
310 * Readers don't acquire any locks for their data access. Instead, they
311 * simply record their transaction ID in the reader table. The reader
312 * mutex is needed just to find an empty slot in the reader table. The
313 * slot's address is saved in thread-specific data so that subsequent read
314 * transactions started by the same thread need no further locking to proceed.
316 * Since the database uses multi-version concurrency control, readers don't
317 * actually need any locking. This table is used to keep track of which
318 * readers are using data from which old transactions, so that we'll know
319 * when a particular old transaction is no longer in use. Old transactions
320 * that have discarded any data pages can then have those pages reclaimed
321 * for use by a later write transaction.
323 * The lock table is constructed such that reader slots are aligned with the
324 * processor's cache line size. Any slot is only ever used by one thread.
325 * This alignment guarantees that there will be no contention or cache
326 * thrashing as threads update their own slot info, and also eliminates
327 * any need for locking when accessing a slot.
329 * A writer thread will scan every slot in the table to determine the oldest
330 * outstanding reader transaction. Any freed pages older than this will be
331 * reclaimed by the writer. The writer doesn't use any locks when scanning
332 * this table. This means that there's no guarantee that the writer will
333 * see the most up-to-date reader info, but that's not required for correct
334 * operation - all we need is to know the upper bound on the oldest reader,
335 * we don't care at all about the newest reader. So the only consequence of
336 * reading stale information here is that old pages might hang around a
337 * while longer before being reclaimed. That's actually good anyway, because
338 * the longer we delay reclaiming old pages, the more likely it is that a
339 * string of contiguous pages can be found after coalescing old pages from
340 * many old transactions together.
342 * @todo We don't actually do such coalescing yet, we grab pages from one
343 * old transaction at a time.
346 /** Number of slots in the reader table.
347 * This value was chosen somewhat arbitrarily. 126 readers plus a
348 * couple mutexes fit exactly into 8KB on my development machine.
349 * Applications should set the table size using #mdb_env_set_maxreaders().
351 #define DEFAULT_READERS 126
353 /** The size of a CPU cache line in bytes. We want our lock structures
354 * aligned to this size to avoid false cache line sharing in the
356 * This value works for most CPUs. For Itanium this should be 128.
362 /** The information we store in a single slot of the reader table.
363 * In addition to a transaction ID, we also record the process and
364 * thread ID that owns a slot, so that we can detect stale information,
365 * e.g. threads or processes that went away without cleaning up.
366 * @note We currently don't check for stale records. We simply re-init
367 * the table when we know that we're the only process opening the
370 typedef struct MDB_rxbody {
371 /** The current Transaction ID when this transaction began.
372 * Multiple readers that start at the same time will probably have the
373 * same ID here. Again, it's not important to exclude them from
374 * anything; all we need to know is which version of the DB they
375 * started from so we can avoid overwriting any data used in that
376 * particular version.
379 /** The process ID of the process owning this reader txn. */
381 /** The thread ID of the thread owning this txn. */
385 /** The actual reader record, with cacheline padding. */
386 typedef struct MDB_reader {
389 /** shorthand for mrb_txnid */
390 #define mr_txnid mru.mrx.mrb_txnid
391 #define mr_pid mru.mrx.mrb_pid
392 #define mr_tid mru.mrx.mrb_tid
393 /** cache line alignment */
394 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
398 /** The header for the reader table.
399 * The table resides in a memory-mapped file. (This is a different file
400 * than is used for the main database.)
402 * For POSIX the actual mutexes reside in the shared memory of this
403 * mapped file. On Windows, mutexes are named objects allocated by the
404 * kernel; we store the mutex names in this mapped file so that other
405 * processes can grab them. This same approach will also be used on
406 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
407 * process-shared POSIX mutexes.
409 typedef struct MDB_txbody {
410 /** Stamp identifying this as an MDB lock file. It must be set
413 /** Version number of this lock file. Must be set to #MDB_VERSION. */
414 uint32_t mtb_version;
418 /** Mutex protecting access to this table.
419 * This is the reader lock that #LOCK_MUTEX_R acquires.
421 pthread_mutex_t mtb_mutex;
423 /** The ID of the last transaction committed to the database.
424 * This is recorded here only for convenience; the value can always
425 * be determined by reading the main database meta pages.
428 /** The number of slots that have been used in the reader table.
429 * This always records the maximum count, it is not decremented
430 * when readers release their slots.
432 uint32_t mtb_numreaders;
433 /** The ID of the most recent meta page in the database.
434 * This is recorded here only for convenience; the value can always
435 * be determined by reading the main database meta pages.
437 uint32_t mtb_me_toggle;
440 /** The actual reader table definition. */
441 typedef struct MDB_txninfo {
444 #define mti_magic mt1.mtb.mtb_magic
445 #define mti_version mt1.mtb.mtb_version
446 #define mti_mutex mt1.mtb.mtb_mutex
447 #define mti_rmname mt1.mtb.mtb_rmname
448 #define mti_txnid mt1.mtb.mtb_txnid
449 #define mti_numreaders mt1.mtb.mtb_numreaders
450 #define mti_me_toggle mt1.mtb.mtb_me_toggle
451 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
456 #define mti_wmname mt2.mt2_wmname
458 pthread_mutex_t mt2_wmutex;
459 #define mti_wmutex mt2.mt2_wmutex
461 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
463 MDB_reader mti_readers[1];
467 /** Common header for all page types.
468 * Overflow pages occupy a number of contiguous pages with no
469 * headers on any page after the first.
471 typedef struct MDB_page {
472 #define mp_pgno mp_p.p_pgno
473 #define mp_next mp_p.p_next
475 pgno_t p_pgno; /**< page number */
476 void * p_next; /**< for in-memory list of freed structs */
478 #define P_BRANCH 0x01 /**< branch page */
479 #define P_LEAF 0x02 /**< leaf page */
480 #define P_OVERFLOW 0x04 /**< overflow page */
481 #define P_META 0x08 /**< meta page */
482 #define P_DIRTY 0x10 /**< dirty page */
483 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
485 #define mp_lower mp_pb.pb.pb_lower
486 #define mp_upper mp_pb.pb.pb_upper
487 #define mp_pages mp_pb.pb_pages
490 indx_t pb_lower; /**< lower bound of free space */
491 indx_t pb_upper; /**< upper bound of free space */
493 uint32_t pb_pages; /**< number of overflow pages */
495 indx_t mp_ptrs[1]; /**< dynamic size */
498 /** Size of the page header, excluding dynamic data at the end */
499 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
501 /** Address of first usable data byte in a page, after the header */
502 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
504 /** Number of nodes on a page */
505 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
507 /** The amount of space remaining in the page */
508 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
510 /** The percentage of space used in the page, in tenths of a percent. */
511 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
512 ((env)->me_psize - PAGEHDRSZ))
513 /** The minimum page fill factor, in tenths of a percent.
514 * Pages emptier than this are candidates for merging.
516 #define FILL_THRESHOLD 250
518 /** Test if a page is a leaf page */
519 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
520 /** Test if a page is a LEAF2 page */
521 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
522 /** Test if a page is a branch page */
523 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
524 /** Test if a page is an overflow page */
525 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
527 /** The number of overflow pages needed to store the given size. */
528 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
530 /** Header for a single key/data pair within a page.
531 * We guarantee 2-byte alignment for nodes.
533 typedef struct MDB_node {
534 /** lo and hi are used for data size on leaf nodes and for
535 * child pgno on branch nodes. On 64 bit platforms, flags
536 * is also used for pgno. (Branch nodes have no flags).
537 * They are in in host byte order in case that lets some
538 * accesses be optimized into a 32-bit word access.
540 #define mn_lo mn_offset[__BYTE_ORDER!=__LITTLE_ENDIAN]
541 #define mn_hi mn_offset[__BYTE_ORDER==__LITTLE_ENDIAN] /**< part of dsize or pgno */
542 unsigned short mn_offset[2];
543 unsigned short mn_flags; /**< flags for special node types */
544 #define F_BIGDATA 0x01 /**< data put on overflow page */
545 #define F_SUBDATA 0x02 /**< data is a sub-database */
546 #define F_DUPDATA 0x04 /**< data has duplicates */
547 unsigned short mn_ksize; /**< key size */
548 char mn_data[1]; /**< key and data are appended here */
551 /** Size of the node header, excluding dynamic data at the end */
552 #define NODESIZE offsetof(MDB_node, mn_data)
554 /** Size of a node in a branch page with a given key.
555 * This is just the node header plus the key, there is no data.
557 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
559 /** Size of a node in a leaf page with a given key and data.
560 * This is node header plus key plus data size.
562 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
564 /** Address of node \b i in page \b p */
565 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
567 /** Address of the key for the node */
568 #define NODEKEY(node) (void *)((node)->mn_data)
570 /** Address of the data for a node */
571 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
573 /** Get the page number pointed to by a branch node */
574 #if LONG_MAX == 0x7fffffff
575 #define NODEPGNO(node) ((node)->mn_lo | ((node)->mn_hi << 16))
576 /** Set the page number in a branch node */
577 #define SETPGNO(node,pgno) do { \
578 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16;} while(0)
580 #define NODEPGNO(node) ((node)->mn_lo | ((node)->mn_hi << 16) | ((unsigned long)(node)->mn_flags << 32))
581 /** Set the page number in a branch node */
582 #define SETPGNO(node,pgno) do { \
583 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
584 (node)->mn_flags = (pgno) >> 32; } while(0)
587 /** Get the size of the data in a leaf node */
588 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
589 /** Set the size of the data for a leaf node */
590 #define SETDSZ(node,size) do { \
591 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
592 /** The size of a key in a node */
593 #define NODEKSZ(node) ((node)->mn_ksize)
595 /** The address of a key in a LEAF2 page.
596 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
597 * There are no node headers, keys are stored contiguously.
599 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
601 /** Set the \b node's key into \b key, if requested. */
602 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
603 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
605 /** Information about a single database in the environment. */
606 typedef struct MDB_db {
607 uint32_t md_pad; /**< also ksize for LEAF2 pages */
608 uint16_t md_flags; /**< @ref mdb_open */
609 uint16_t md_depth; /**< depth of this tree */
610 ULONG md_branch_pages; /**< number of internal pages */
611 ULONG md_leaf_pages; /**< number of leaf pages */
612 ULONG md_overflow_pages; /**< number of overflow pages */
613 ULONG md_entries; /**< number of data items */
614 pgno_t md_root; /**< the root page of this tree */
617 /** Handle for the DB used to track free pages. */
619 /** Handle for the default DB. */
622 /** Meta page content. */
623 typedef struct MDB_meta {
624 /** Stamp identifying this as an MDB data file. It must be set
627 /** Version number of this lock file. Must be set to #MDB_VERSION. */
629 void *mm_address; /**< address for fixed mapping */
630 size_t mm_mapsize; /**< size of mmap region */
631 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
632 /** The size of pages used in this DB */
633 #define mm_psize mm_dbs[0].md_pad
634 /** Any persistent environment flags. @ref mdb_env */
635 #define mm_flags mm_dbs[0].md_flags
636 pgno_t mm_last_pg; /**< last used page in file */
637 ULONG mm_txnid; /**< txnid that committed this page */
640 /** Auxiliary DB info.
641 * The information here is mostly static/read-only. There is
642 * only a single copy of this record in the environment.
643 * The \b md_dirty flag is not read-only, but only a write
644 * transaction can ever update it, and only write transactions
645 * need to worry about it.
647 typedef struct MDB_dbx {
648 MDB_val md_name; /**< name of the database */
649 MDB_cmp_func *md_cmp; /**< function for comparing keys */
650 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
651 MDB_rel_func *md_rel; /**< user relocate function */
652 MDB_dbi md_parent; /**< parent DB of a sub-DB */
653 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
656 /** A database transaction.
657 * Every operation requires a transaction handle.
660 pgno_t mt_next_pgno; /**< next unallocated page */
661 /** The ID of this transaction. IDs are integers incrementing from 1.
662 * Only committed write transactions increment the ID. If a transaction
663 * aborts, the ID may be re-used by the next writer.
666 MDB_env *mt_env; /**< the DB environment */
667 /** The list of pages that became unused during this transaction.
672 ID2L dirty_list; /**< modified pages */
673 MDB_reader *reader; /**< this thread's slot in the reader table */
675 /** Array of records for each DB known in the environment. */
677 /** Array of MDB_db records for each known DB */
679 /** Number of DB records in use. This number only ever increments;
680 * we don't decrement it when individual DB handles are closed.
682 unsigned int mt_numdbs;
684 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
685 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
686 unsigned int mt_flags;
687 /** Tracks which of the two meta pages was used at the start
688 * of this transaction.
690 unsigned int mt_toggle;
693 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
694 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
695 * raise this on a 64 bit machine.
697 #define CURSOR_STACK 32
701 /** Cursors are used for all DB operations */
703 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
704 struct MDB_xcursor *mc_xcursor;
705 /** The transaction that owns this cursor */
707 /** The database handle this cursor operates on */
709 unsigned short mc_snum; /**< number of pushed pages */
710 unsigned short mc_top; /**< index of top page, mc_snum-1 */
711 unsigned int mc_flags;
712 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
713 #define C_EOF 0x02 /**< No more data */
714 #define C_XDIRTY 0x04 /**< @deprecated mc_xcursor needs to be flushed */
715 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
716 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
719 /** Context for sorted-dup records.
720 * We could have gone to a fully recursive design, with arbitrarily
721 * deep nesting of sub-databases. But for now we only handle these
722 * levels - main DB, optional sub-DB, sorted-duplicate DB.
724 typedef struct MDB_xcursor {
725 /** A sub-cursor for traversing the Dup DB */
726 MDB_cursor mx_cursor;
727 /** A fake transaction struct for pointing to our own table
731 /** Our private DB information tables. Slots 0 and 1 are always
732 * copies of the corresponding slots in the main transaction. These
733 * hold the FREEDB and MAINDB, respectively. If the main cursor is
734 * on a sub-database, that will be copied to slot 2, and the duplicate
735 * database info will be in slot 3. If the main cursor is on the MAINDB
736 * then the duplicate DB info will be in slot 2 and slot 3 will be unused.
743 /** A set of pages freed by an earlier transaction. */
744 typedef struct MDB_oldpages {
745 /** Usually we only read one record from the FREEDB at a time, but
746 * in case we read more, this will chain them together.
748 struct MDB_oldpages *mo_next;
749 /** The ID of the transaction in which these pages were freed. */
751 /** An #IDL of the pages */
752 pgno_t mo_pages[1]; /* dynamic */
755 /** The database environment. */
757 HANDLE me_fd; /**< The main data file */
758 HANDLE me_lfd; /**< The lock file */
759 HANDLE me_mfd; /**< just for writing the meta pages */
760 /** Failed to update the meta page. Probably an I/O error. */
761 #define MDB_FATAL_ERROR 0x80000000U
763 uint32_t me_extrapad; /**< unused for now */
764 unsigned int me_maxreaders; /**< size of the reader table */
765 unsigned int me_numdbs; /**< number of DBs opened */
766 unsigned int me_maxdbs; /**< size of the DB table */
767 char *me_path; /**< path to the DB files */
768 char *me_map; /**< the memory map of the data file */
769 MDB_txninfo *me_txns; /**< the memory map of the lock file */
770 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
771 MDB_txn *me_txn; /**< current write transaction */
772 size_t me_mapsize; /**< size of the data memory map */
773 off_t me_size; /**< current file size */
774 pgno_t me_maxpg; /**< me_mapsize / me_psize */
775 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
776 unsigned int me_db_toggle; /**< which DB table is current */
777 MDB_dbx *me_dbxs; /**< array of static DB info */
778 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
779 MDB_oldpages *me_pghead; /**< list of old page records */
780 pthread_key_t me_txkey; /**< thread-key for readers */
781 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
782 /** IDL of pages that became unused in a write txn */
783 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
784 /** ID2L of pages that were written during a write txn */
785 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
786 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
787 LAZY_RWLOCK_DEF(me_dblock)
789 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
793 /** max number of pages to commit in one writev() call */
794 #define MDB_COMMIT_PAGES 64
796 static MDB_page *mdb_alloc_page(MDB_cursor *mc, int num);
797 static int mdb_touch(MDB_cursor *mc);
799 static int mdb_search_page_root(MDB_cursor *mc,
800 MDB_val *key, int modify);
801 static int mdb_search_page(MDB_cursor *mc,
802 MDB_val *key, int modify);
804 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
805 static int mdb_env_read_meta(MDB_env *env, int *which);
806 static int mdb_env_write_meta(MDB_txn *txn);
807 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
809 static MDB_node *mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp);
810 static int mdb_add_node(MDB_cursor *mc, indx_t indx,
811 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
812 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
813 static int mdb_del0(MDB_cursor *mc, MDB_node *leaf);
814 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
816 static int mdb_rebalance(MDB_cursor *mc);
817 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
818 static int mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst);
819 static int mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst);
820 static int mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
822 static MDB_page *mdb_new_page(MDB_cursor *mc, uint32_t flags, int num);
824 static void cursor_pop_page(MDB_cursor *mc);
825 static int cursor_push_page(MDB_cursor *mc, MDB_page *mp);
827 static int mdb_sibling(MDB_cursor *mc, int move_right);
828 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
829 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
830 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
832 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
833 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
835 static void mdb_xcursor_init0(MDB_cursor *mc);
836 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
837 static void mdb_xcursor_init2(MDB_cursor *mc);
838 static void mdb_xcursor_fini(MDB_cursor *mc);
840 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
841 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
843 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
846 static MDB_cmp_func memncmp, memnrcmp, intcmp, cintcmp;
850 static SECURITY_DESCRIPTOR mdb_null_sd;
851 static SECURITY_ATTRIBUTES mdb_all_sa;
852 static int mdb_sec_inited;
855 /** Return the library version info. */
857 mdb_version(int *major, int *minor, int *patch)
859 if (major) *major = MDB_VERSION_MAJOR;
860 if (minor) *minor = MDB_VERSION_MINOR;
861 if (patch) *patch = MDB_VERSION_PATCH;
862 return MDB_VERSION_STRING;
865 /** Table of descriptions for MDB @ref errors */
866 static char *const mdb_errstr[] = {
867 "MDB_KEYEXIST: Key/data pair already exists",
868 "MDB_NOTFOUND: No matching key/data pair found",
869 "MDB_PAGE_NOTFOUND: Requested page not found",
870 "MDB_CORRUPTED: Located page was wrong type",
871 "MDB_PANIC: Update of meta page failed",
872 "MDB_VERSION_MISMATCH: Database environment version mismatch"
876 mdb_strerror(int err)
879 return ("Successful return: 0");
881 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
882 return mdb_errstr[err - MDB_KEYEXIST];
884 return strerror(err);
888 /** Display a key in hexadecimal and return the address of the result.
889 * @param[in] key the key to display
890 * @param[in] buf the buffer to write into. Should always be #DKBUF.
891 * @return The key in hexadecimal form.
894 mdb_dkey(MDB_val *key, char *buf)
897 unsigned char *c = key->mv_data;
899 if (key->mv_size > MAXKEYSIZE)
901 /* may want to make this a dynamic check: if the key is mostly
902 * printable characters, print it as-is instead of converting to hex.
905 for (i=0; i<key->mv_size; i++)
906 ptr += sprintf(ptr, "%02x", *c++);
908 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
915 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
917 return txn->mt_dbxs[dbi].md_cmp(a, b);
920 /** Compare two data items according to a particular database.
921 * This returns a comparison as if the two items were data items of
922 * a sorted duplicates #MDB_DUPSORT database.
923 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
924 * @param[in] dbi A database handle returned by #mdb_open()
925 * @param[in] a The first item to compare
926 * @param[in] b The second item to compare
927 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
930 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
932 if (txn->mt_dbxs[dbi].md_dcmp)
933 return txn->mt_dbxs[dbi].md_dcmp(a, b);
935 return EINVAL; /* too bad you can't distinguish this from a valid result */
938 /** Allocate pages for writing.
939 * If there are free pages available from older transactions, they
940 * will be re-used first. Otherwise a new page will be allocated.
941 * @param[in] mc cursor A cursor handle identifying the transaction and
942 * database for which we are allocating.
943 * @param[in] num the number of pages to allocate.
944 * @return Address of the allocated page(s). Requests for multiple pages
945 * will always be satisfied by a single contiguous chunk of memory.
948 mdb_alloc_page(MDB_cursor *mc, int num)
950 MDB_txn *txn = mc->mc_txn;
952 pgno_t pgno = P_INVALID;
955 if (txn->mt_txnid > 2) {
957 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
958 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
959 /* See if there's anything in the free DB */
965 m2.mc_dbi = FREE_DBI;
968 mdb_search_page(&m2, NULL, 0);
969 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
970 kptr = (ULONG *)NODEKEY(leaf);
974 oldest = txn->mt_txnid - 1;
975 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
976 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
977 if (mr && mr < oldest)
982 if (oldest > *kptr) {
983 /* It's usable, grab it.
989 mdb_read_data(txn, leaf, &data);
990 idl = (ULONG *)data.mv_data;
991 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
992 mop->mo_next = txn->mt_env->me_pghead;
993 mop->mo_txnid = *kptr;
994 txn->mt_env->me_pghead = mop;
995 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1000 DPRINTF("IDL read txn %lu root %lu num %lu",
1001 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1002 for (i=0; i<idl[0]; i++) {
1003 DPRINTF("IDL %lu", idl[i+1]);
1007 /* drop this IDL from the DB */
1008 m2.mc_ki[m2.mc_top] = 0;
1009 m2.mc_flags = C_INITIALIZED;
1010 mdb_cursor_del(&m2, 0);
1013 if (txn->mt_env->me_pghead) {
1014 MDB_oldpages *mop = txn->mt_env->me_pghead;
1016 /* FIXME: For now, always use fresh pages. We
1017 * really ought to search the free list for a
1022 /* peel pages off tail, so we only have to truncate the list */
1023 pgno = MDB_IDL_LAST(mop->mo_pages);
1024 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1026 if (mop->mo_pages[2] > mop->mo_pages[1])
1027 mop->mo_pages[0] = 0;
1031 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1032 txn->mt_env->me_pghead = mop->mo_next;
1039 if (pgno == P_INVALID) {
1040 /* DB size is maxed out */
1041 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
1044 if (txn->mt_env->me_dpages && num == 1) {
1045 np = txn->mt_env->me_dpages;
1046 txn->mt_env->me_dpages = np->mp_next;
1048 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1051 if (pgno == P_INVALID) {
1052 np->mp_pgno = txn->mt_next_pgno;
1053 txn->mt_next_pgno += num;
1057 mid.mid = np->mp_pgno;
1059 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1064 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1065 * @param[in] mc cursor pointing to the page to be touched
1066 * @return 0 on success, non-zero on failure.
1069 mdb_touch(MDB_cursor *mc)
1071 MDB_page *mp = mc->mc_pg[mc->mc_top];
1074 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1076 if ((np = mdb_alloc_page(mc, 1)) == NULL)
1078 DPRINTF("touched db %u page %lu -> %lu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1079 assert(mp->mp_pgno != np->mp_pgno);
1080 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1082 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1085 mp->mp_flags |= P_DIRTY;
1087 mc->mc_pg[mc->mc_top] = mp;
1088 /** If this page has a parent, update the parent to point to
1092 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1098 mdb_env_sync(MDB_env *env, int force)
1101 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1102 if (fdatasync(env->me_fd))
1109 mdb_txn_reset0(MDB_txn *txn);
1111 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1112 * @param[in] txn the transaction handle to initialize
1113 * @return 0 on success, non-zero on failure. This can only
1114 * fail for read-only transactions, and then only if the
1115 * reader table is full.
1118 mdb_txn_renew0(MDB_txn *txn)
1120 MDB_env *env = txn->mt_env;
1122 if (txn->mt_flags & MDB_TXN_RDONLY) {
1123 MDB_reader *r = pthread_getspecific(env->me_txkey);
1126 pid_t pid = getpid();
1127 pthread_t tid = pthread_self();
1130 for (i=0; i<env->me_txns->mti_numreaders; i++)
1131 if (env->me_txns->mti_readers[i].mr_pid == 0)
1133 if (i == env->me_maxreaders) {
1134 UNLOCK_MUTEX_R(env);
1137 env->me_txns->mti_readers[i].mr_pid = pid;
1138 env->me_txns->mti_readers[i].mr_tid = tid;
1139 if (i >= env->me_txns->mti_numreaders)
1140 env->me_txns->mti_numreaders = i+1;
1141 UNLOCK_MUTEX_R(env);
1142 r = &env->me_txns->mti_readers[i];
1143 pthread_setspecific(env->me_txkey, r);
1145 txn->mt_txnid = env->me_txns->mti_txnid;
1146 txn->mt_toggle = env->me_txns->mti_me_toggle;
1147 r->mr_txnid = txn->mt_txnid;
1148 txn->mt_u.reader = r;
1152 txn->mt_txnid = env->me_txns->mti_txnid+1;
1153 txn->mt_toggle = env->me_txns->mti_me_toggle;
1154 txn->mt_u.dirty_list = env->me_dirty_list;
1155 txn->mt_u.dirty_list[0].mid = 0;
1156 txn->mt_free_pgs = env->me_free_pgs;
1157 txn->mt_free_pgs[0] = 0;
1158 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1162 /* Copy the DB arrays */
1163 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1164 txn->mt_numdbs = env->me_numdbs;
1165 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1166 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1167 if (txn->mt_numdbs > 2)
1168 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1169 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1170 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1176 mdb_txn_renew(MDB_txn *txn)
1183 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1184 DPUTS("environment had fatal error, must shutdown!");
1188 rc = mdb_txn_renew0(txn);
1189 if (rc == MDB_SUCCESS) {
1190 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
1191 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1192 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1198 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1203 if (env->me_flags & MDB_FATAL_ERROR) {
1204 DPUTS("environment had fatal error, must shutdown!");
1207 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1208 DPRINTF("calloc: %s", strerror(ErrCode()));
1211 txn->mt_dbs = (MDB_db *)(txn+1);
1212 if (flags & MDB_RDONLY) {
1213 txn->mt_flags |= MDB_TXN_RDONLY;
1217 rc = mdb_txn_renew0(txn);
1222 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
1223 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1224 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1230 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1231 * @param[in] txn the transaction handle to reset
1234 mdb_txn_reset0(MDB_txn *txn)
1236 MDB_env *env = txn->mt_env;
1238 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1239 txn->mt_u.reader->mr_txnid = 0;
1245 /* return all dirty pages to dpage list */
1246 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1247 dp = txn->mt_u.dirty_list[i].mptr;
1248 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1249 dp->mp_next = txn->mt_env->me_dpages;
1250 txn->mt_env->me_dpages = dp;
1252 /* large pages just get freed directly */
1257 while ((mop = txn->mt_env->me_pghead)) {
1258 txn->mt_env->me_pghead = mop->mo_next;
1263 for (i=2; i<env->me_numdbs; i++)
1264 env->me_dbxs[i].md_dirty = 0;
1265 /* The writer mutex was locked in mdb_txn_begin. */
1266 UNLOCK_MUTEX_W(env);
1271 mdb_txn_reset(MDB_txn *txn)
1276 DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
1277 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1278 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1280 mdb_txn_reset0(txn);
1284 mdb_txn_abort(MDB_txn *txn)
1289 DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
1290 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1291 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1293 mdb_txn_reset0(txn);
1298 mdb_txn_commit(MDB_txn *txn)
1309 assert(txn != NULL);
1310 assert(txn->mt_env != NULL);
1314 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1319 if (txn != env->me_txn) {
1320 DPUTS("attempt to commit unknown transaction");
1325 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1326 DPUTS("error flag is set, can't commit");
1331 if (!txn->mt_u.dirty_list[0].mid)
1334 DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
1335 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1338 mc.mc_dbi = FREE_DBI;
1341 /* should only be one record now */
1342 if (env->me_pghead) {
1343 /* make sure first page of freeDB is touched and on freelist */
1344 mdb_search_page(&mc, NULL, 1);
1346 /* save to free list */
1347 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1351 /* make sure last page of freeDB is touched and on freelist */
1352 key.mv_size = MAXKEYSIZE+1;
1354 mdb_search_page(&mc, &key, 1);
1356 mdb_midl_sort(txn->mt_free_pgs);
1360 ULONG *idl = txn->mt_free_pgs;
1361 DPRINTF("IDL write txn %lu root %lu num %lu",
1362 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1363 for (i=0; i<idl[0]; i++) {
1364 DPRINTF("IDL %lu", idl[i+1]);
1368 /* write to last page of freeDB */
1369 key.mv_size = sizeof(pgno_t);
1370 key.mv_data = (char *)&txn->mt_txnid;
1371 data.mv_data = txn->mt_free_pgs;
1372 /* The free list can still grow during this call,
1373 * despite the pre-emptive touches above. So check
1374 * and make sure the entire thing got written.
1377 i = txn->mt_free_pgs[0];
1378 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1379 rc = mdb_cursor_put(&mc, &key, &data, 0);
1384 } while (i != txn->mt_free_pgs[0]);
1386 /* should only be one record now */
1387 if (env->me_pghead) {
1391 mop = env->me_pghead;
1392 key.mv_size = sizeof(pgno_t);
1393 key.mv_data = (char *)&mop->mo_txnid;
1394 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1395 data.mv_data = mop->mo_pages;
1396 mdb_cursor_put(&mc, &key, &data, 0);
1397 free(env->me_pghead);
1398 env->me_pghead = NULL;
1401 /* Update DB root pointers. Their pages have already been
1402 * touched so this is all in-place and cannot fail.
1406 data.mv_size = sizeof(MDB_db);
1408 mc.mc_dbi = MAIN_DBI;
1410 for (i = 2; i < txn->mt_numdbs; i++) {
1411 if (txn->mt_dbxs[i].md_dirty) {
1412 data.mv_data = &txn->mt_dbs[i];
1413 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1418 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1424 /* Windows actually supports scatter/gather I/O, but only on
1425 * unbuffered file handles. Since we're relying on the OS page
1426 * cache for all our data, that's self-defeating. So we just
1427 * write pages one at a time. We use the ov structure to set
1428 * the write offset, to at least save the overhead of a Seek
1432 memset(&ov, 0, sizeof(ov));
1433 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1435 dp = txn->mt_u.dirty_list[i].mptr;
1436 DPRINTF("committing page %lu", dp->mp_pgno);
1437 size = dp->mp_pgno * env->me_psize;
1438 ov.Offset = size & 0xffffffff;
1439 ov.OffsetHigh = size >> 16;
1440 ov.OffsetHigh >>= 16;
1441 /* clear dirty flag */
1442 dp->mp_flags &= ~P_DIRTY;
1443 wsize = env->me_psize;
1444 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1445 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1448 DPRINTF("WriteFile: %d", n);
1455 struct iovec iov[MDB_COMMIT_PAGES];
1459 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1460 dp = txn->mt_u.dirty_list[i].mptr;
1461 if (dp->mp_pgno != next) {
1463 DPRINTF("committing %u dirty pages", n);
1464 rc = writev(env->me_fd, iov, n);
1468 DPUTS("short write, filesystem full?");
1470 DPRINTF("writev: %s", strerror(n));
1477 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1480 DPRINTF("committing page %lu", dp->mp_pgno);
1481 iov[n].iov_len = env->me_psize;
1482 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1483 iov[n].iov_base = dp;
1484 size += iov[n].iov_len;
1485 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1486 /* clear dirty flag */
1487 dp->mp_flags &= ~P_DIRTY;
1488 if (++n >= MDB_COMMIT_PAGES) {
1498 DPRINTF("committing %u dirty pages", n);
1499 rc = writev(env->me_fd, iov, n);
1503 DPUTS("short write, filesystem full?");
1505 DPRINTF("writev: %s", strerror(n));
1512 /* Drop the dirty pages.
1514 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1515 dp = txn->mt_u.dirty_list[i].mptr;
1516 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1517 dp->mp_next = txn->mt_env->me_dpages;
1518 txn->mt_env->me_dpages = dp;
1522 txn->mt_u.dirty_list[i].mid = 0;
1524 txn->mt_u.dirty_list[0].mid = 0;
1526 if ((n = mdb_env_sync(env, 0)) != 0 ||
1527 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1534 /* update the DB tables */
1536 int toggle = !env->me_db_toggle;
1539 ip = &env->me_dbs[toggle][2];
1540 jp = &txn->mt_dbs[2];
1541 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1542 for (i = 2; i < txn->mt_numdbs; i++) {
1543 if (ip->md_root != jp->md_root)
1548 for (i = 2; i < txn->mt_numdbs; i++) {
1549 if (txn->mt_dbxs[i].md_dirty)
1550 txn->mt_dbxs[i].md_dirty = 0;
1552 env->me_db_toggle = toggle;
1553 env->me_numdbs = txn->mt_numdbs;
1554 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1557 UNLOCK_MUTEX_W(env);
1563 /** Read the environment parameters of a DB environment before
1564 * mapping it into memory.
1565 * @param[in] env the environment handle
1566 * @param[out] meta address of where to store the meta information
1567 * @return 0 on success, non-zero on failure.
1570 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1572 char page[PAGESIZE];
1577 /* We don't know the page size yet, so use a minimum value.
1581 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1583 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1588 else if (rc != PAGESIZE) {
1592 DPRINTF("read: %s", strerror(err));
1596 p = (MDB_page *)page;
1598 if (!F_ISSET(p->mp_flags, P_META)) {
1599 DPRINTF("page %lu not a meta page", p->mp_pgno);
1604 if (m->mm_magic != MDB_MAGIC) {
1605 DPUTS("meta has invalid magic");
1609 if (m->mm_version != MDB_VERSION) {
1610 DPRINTF("database is version %u, expected version %u",
1611 m->mm_version, MDB_VERSION);
1612 return MDB_VERSION_MISMATCH;
1615 memcpy(meta, m, sizeof(*m));
1619 /** Write the environment parameters of a freshly created DB environment.
1620 * @param[in] env the environment handle
1621 * @param[out] meta address of where to store the meta information
1622 * @return 0 on success, non-zero on failure.
1625 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1632 DPUTS("writing new meta page");
1634 GET_PAGESIZE(psize);
1636 meta->mm_magic = MDB_MAGIC;
1637 meta->mm_version = MDB_VERSION;
1638 meta->mm_psize = psize;
1639 meta->mm_last_pg = 1;
1640 meta->mm_flags = env->me_flags & 0xffff;
1641 meta->mm_flags |= MDB_INTEGERKEY;
1642 meta->mm_dbs[0].md_root = P_INVALID;
1643 meta->mm_dbs[1].md_root = P_INVALID;
1645 p = calloc(2, psize);
1647 p->mp_flags = P_META;
1650 memcpy(m, meta, sizeof(*meta));
1652 q = (MDB_page *)((char *)p + psize);
1655 q->mp_flags = P_META;
1658 memcpy(m, meta, sizeof(*meta));
1663 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1664 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1667 rc = write(env->me_fd, p, psize * 2);
1668 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1674 /** Update the environment info to commit a transaction.
1675 * @param[in] txn the transaction that's being committed
1676 * @return 0 on success, non-zero on failure.
1679 mdb_env_write_meta(MDB_txn *txn)
1682 MDB_meta meta, metab;
1684 int rc, len, toggle;
1690 assert(txn != NULL);
1691 assert(txn->mt_env != NULL);
1693 toggle = !txn->mt_toggle;
1694 DPRINTF("writing meta page %d for root page %lu",
1695 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1699 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1700 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1702 ptr = (char *)&meta;
1703 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1704 len = sizeof(MDB_meta) - off;
1707 meta.mm_dbs[0] = txn->mt_dbs[0];
1708 meta.mm_dbs[1] = txn->mt_dbs[1];
1709 meta.mm_last_pg = txn->mt_next_pgno - 1;
1710 meta.mm_txnid = txn->mt_txnid;
1713 off += env->me_psize;
1716 /* Write to the SYNC fd */
1719 memset(&ov, 0, sizeof(ov));
1721 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1724 rc = pwrite(env->me_mfd, ptr, len, off);
1729 DPUTS("write failed, disk error?");
1730 /* On a failure, the pagecache still contains the new data.
1731 * Write some old data back, to prevent it from being used.
1732 * Use the non-SYNC fd; we know it will fail anyway.
1734 meta.mm_last_pg = metab.mm_last_pg;
1735 meta.mm_txnid = metab.mm_txnid;
1737 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1739 r2 = pwrite(env->me_fd, ptr, len, off);
1741 env->me_flags |= MDB_FATAL_ERROR;
1744 /* Memory ordering issues are irrelevant; since the entire writer
1745 * is wrapped by wmutex, all of these changes will become visible
1746 * after the wmutex is unlocked. Since the DB is multi-version,
1747 * readers will get consistent data regardless of how fresh or
1748 * how stale their view of these values is.
1750 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1751 txn->mt_env->me_txns->mti_me_toggle = toggle;
1752 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1753 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1758 /** Check both meta pages to see which one is newer.
1759 * @param[in] env the environment handle
1760 * @param[out] which address of where to store the meta toggle ID
1761 * @return 0 on success, non-zero on failure.
1764 mdb_env_read_meta(MDB_env *env, int *which)
1768 assert(env != NULL);
1770 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1773 DPRINTF("Using meta page %d", toggle);
1780 mdb_env_create(MDB_env **env)
1784 e = calloc(1, sizeof(MDB_env));
1785 if (!e) return ENOMEM;
1787 e->me_maxreaders = DEFAULT_READERS;
1789 e->me_fd = INVALID_HANDLE_VALUE;
1790 e->me_lfd = INVALID_HANDLE_VALUE;
1791 e->me_mfd = INVALID_HANDLE_VALUE;
1797 mdb_env_set_mapsize(MDB_env *env, size_t size)
1801 env->me_mapsize = size;
1806 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1810 env->me_maxdbs = dbs;
1815 mdb_env_set_maxreaders(MDB_env *env, int readers)
1819 env->me_maxreaders = readers;
1824 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1826 if (!env || !readers)
1828 *readers = env->me_maxreaders;
1832 /** Further setup required for opening an MDB environment
1835 mdb_env_open2(MDB_env *env, unsigned int flags)
1837 int i, newenv = 0, toggle;
1841 env->me_flags = flags;
1843 memset(&meta, 0, sizeof(meta));
1845 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1848 DPUTS("new mdbenv");
1852 if (!env->me_mapsize) {
1853 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1859 LONG sizelo, sizehi;
1860 sizelo = env->me_mapsize & 0xffffffff;
1861 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1863 /* Windows won't create mappings for zero length files.
1864 * Just allocate the maxsize right now.
1867 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1868 if (!SetEndOfFile(env->me_fd))
1870 SetFilePointer(env->me_fd, 0, NULL, 0);
1872 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1873 sizehi, sizelo, NULL);
1876 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1884 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1886 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1888 if (env->me_map == MAP_FAILED)
1893 meta.mm_mapsize = env->me_mapsize;
1894 if (flags & MDB_FIXEDMAP)
1895 meta.mm_address = env->me_map;
1896 i = mdb_env_init_meta(env, &meta);
1897 if (i != MDB_SUCCESS) {
1898 munmap(env->me_map, env->me_mapsize);
1902 env->me_psize = meta.mm_psize;
1904 env->me_maxpg = env->me_mapsize / env->me_psize;
1906 p = (MDB_page *)env->me_map;
1907 env->me_metas[0] = METADATA(p);
1908 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1910 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1913 DPRINTF("opened database version %u, pagesize %u",
1914 env->me_metas[toggle]->mm_version, env->me_psize);
1915 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1916 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1917 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1918 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1919 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1920 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1926 /* Windows doesn't support destructor callbacks for thread-specific storage */
1928 mdb_env_reader_dest(void *ptr)
1930 MDB_reader *reader = ptr;
1932 reader->mr_txnid = 0;
1938 /* downgrade the exclusive lock on the region back to shared */
1940 mdb_env_share_locks(MDB_env *env)
1944 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1946 env->me_txns->mti_me_toggle = toggle;
1947 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1952 /* First acquire a shared lock. The Unlock will
1953 * then release the existing exclusive lock.
1955 memset(&ov, 0, sizeof(ov));
1956 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1957 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1961 struct flock lock_info;
1962 /* The shared lock replaces the existing lock */
1963 memset((void *)&lock_info, 0, sizeof(lock_info));
1964 lock_info.l_type = F_RDLCK;
1965 lock_info.l_whence = SEEK_SET;
1966 lock_info.l_start = 0;
1967 lock_info.l_len = 1;
1968 fcntl(env->me_lfd, F_SETLK, &lock_info);
1974 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1982 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1983 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1984 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1988 /* Try to get exclusive lock. If we succeed, then
1989 * nobody is using the lock region and we should initialize it.
1992 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1996 memset(&ov, 0, sizeof(ov));
1997 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2003 size = GetFileSize(env->me_lfd, NULL);
2005 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2009 /* Try to get exclusive lock. If we succeed, then
2010 * nobody is using the lock region and we should initialize it.
2013 struct flock lock_info;
2014 memset((void *)&lock_info, 0, sizeof(lock_info));
2015 lock_info.l_type = F_WRLCK;
2016 lock_info.l_whence = SEEK_SET;
2017 lock_info.l_start = 0;
2018 lock_info.l_len = 1;
2019 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2023 lock_info.l_type = F_RDLCK;
2024 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2031 size = lseek(env->me_lfd, 0, SEEK_END);
2033 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2034 if (size < rsize && *excl) {
2036 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2037 if (!SetEndOfFile(env->me_lfd)) {
2042 if (ftruncate(env->me_lfd, rsize) != 0) {
2049 size = rsize - sizeof(MDB_txninfo);
2050 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2055 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2061 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2063 if (!env->me_txns) {
2069 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2071 if (env->me_txns == MAP_FAILED) {
2079 if (!mdb_sec_inited) {
2080 InitializeSecurityDescriptor(&mdb_null_sd,
2081 SECURITY_DESCRIPTOR_REVISION);
2082 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2083 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2084 mdb_all_sa.bInheritHandle = FALSE;
2085 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2088 /* FIXME: only using up to 20 characters of the env path here,
2089 * probably not enough to assure uniqueness...
2091 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
2092 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
2093 while ((ptr = strchr(ptr, '\\')))
2095 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2096 if (!env->me_rmutex) {
2100 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
2101 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
2102 while ((ptr = strchr(ptr, '\\')))
2104 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2105 if (!env->me_wmutex) {
2110 pthread_mutexattr_t mattr;
2112 pthread_mutexattr_init(&mattr);
2113 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2117 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2118 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2120 env->me_txns->mti_version = MDB_VERSION;
2121 env->me_txns->mti_magic = MDB_MAGIC;
2122 env->me_txns->mti_txnid = 0;
2123 env->me_txns->mti_numreaders = 0;
2124 env->me_txns->mti_me_toggle = 0;
2127 if (env->me_txns->mti_magic != MDB_MAGIC) {
2128 DPUTS("lock region has invalid magic");
2132 if (env->me_txns->mti_version != MDB_VERSION) {
2133 DPRINTF("lock region is version %u, expected version %u",
2134 env->me_txns->mti_version, MDB_VERSION);
2135 rc = MDB_VERSION_MISMATCH;
2139 if (rc != EACCES && rc != EAGAIN) {
2143 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2144 if (!env->me_rmutex) {
2148 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2149 if (!env->me_wmutex) {
2159 env->me_lfd = INVALID_HANDLE_VALUE;
2164 /** The name of the lock file in the DB environment */
2165 #define LOCKNAME "/lock.mdb"
2166 /** The name of the data file in the DB environment */
2167 #define DATANAME "/data.mdb"
2169 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2171 int oflags, rc, len, excl;
2172 char *lpath, *dpath;
2175 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2178 dpath = lpath + len + sizeof(LOCKNAME);
2179 sprintf(lpath, "%s" LOCKNAME, path);
2180 sprintf(dpath, "%s" DATANAME, path);
2182 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2187 if (F_ISSET(flags, MDB_RDONLY)) {
2188 oflags = GENERIC_READ;
2189 len = OPEN_EXISTING;
2191 oflags = GENERIC_READ|GENERIC_WRITE;
2194 mode = FILE_ATTRIBUTE_NORMAL;
2195 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2196 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2201 if (F_ISSET(flags, MDB_RDONLY))
2204 oflags = O_RDWR | O_CREAT;
2206 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2212 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2213 /* synchronous fd for meta writes */
2215 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2216 mode |= FILE_FLAG_WRITE_THROUGH;
2217 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2218 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2223 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2224 oflags |= MDB_DSYNC;
2225 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2230 env->me_path = strdup(path);
2231 DPRINTF("opened dbenv %p", (void *) env);
2232 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2233 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2235 mdb_env_share_locks(env);
2236 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2237 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2238 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2244 if (env->me_fd != INVALID_HANDLE_VALUE) {
2246 env->me_fd = INVALID_HANDLE_VALUE;
2248 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2250 env->me_lfd = INVALID_HANDLE_VALUE;
2258 mdb_env_close(MDB_env *env)
2265 while (env->me_dpages) {
2266 dp = env->me_dpages;
2267 env->me_dpages = dp->mp_next;
2271 free(env->me_dbs[1]);
2272 free(env->me_dbs[0]);
2276 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2277 pthread_key_delete(env->me_txkey);
2280 munmap(env->me_map, env->me_mapsize);
2285 pid_t pid = getpid();
2287 for (i=0; i<env->me_txns->mti_numreaders; i++)
2288 if (env->me_txns->mti_readers[i].mr_pid == pid)
2289 env->me_txns->mti_readers[i].mr_pid = 0;
2290 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2296 /* only for aligned ints */
2298 intcmp(const MDB_val *a, const MDB_val *b)
2300 if (a->mv_size == sizeof(long))
2302 unsigned long *la, *lb;
2307 unsigned int *ia, *ib;
2314 /* ints must always be the same size */
2316 cintcmp(const MDB_val *a, const MDB_val *b)
2318 #if __BYTE_ORDER == __LITTLE_ENDIAN
2319 unsigned short *u, *c;
2322 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2323 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2326 } while(!x && u > (unsigned short *)a->mv_data);
2329 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2334 memncmp(const MDB_val *a, const MDB_val *b)
2340 len_diff = a->mv_size - b->mv_size;
2343 diff = memcmp(a->mv_data, b->mv_data, len);
2344 return diff ? diff : len_diff;
2348 memnrcmp(const MDB_val *a, const MDB_val *b)
2350 const unsigned char *p1, *p2, *p1_lim;
2353 if (b->mv_size == 0)
2354 return a->mv_size != 0;
2355 if (a->mv_size == 0)
2358 p1 = (const unsigned char *)a->mv_data + a->mv_size - 1;
2359 p2 = (const unsigned char *)b->mv_data + b->mv_size - 1;
2361 len_diff = a->mv_size - b->mv_size;
2363 p1_lim = p1 - a->mv_size;
2365 p1_lim = p1 - b->mv_size;
2367 while (p1 > p1_lim) {
2377 /* Search for key within a leaf page, using binary search.
2378 * Returns the smallest entry larger or equal to the key.
2379 * If exactp is non-null, stores whether the found entry was an exact match
2380 * in *exactp (1 or 0).
2381 * If kip is non-null, stores the index of the found entry in *kip.
2382 * If no entry larger or equal to the key is found, returns NULL.
2385 mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp)
2387 unsigned int i = 0, nkeys;
2390 MDB_page *mp = mc->mc_pg[mc->mc_top];
2391 MDB_node *node = NULL;
2396 nkeys = NUMKEYS(mp);
2398 DPRINTF("searching %u keys in %s page %lu",
2399 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2404 low = IS_LEAF(mp) ? 0 : 1;
2406 cmp = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp;
2408 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2409 node = NODEPTR(mp, 0); /* fake */
2411 while (low <= high) {
2412 i = (low + high) >> 1;
2415 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2417 node = NODEPTR(mp, i);
2419 nodekey.mv_size = node->mn_ksize;
2420 nodekey.mv_data = NODEKEY(node);
2423 rc = cmp(key, &nodekey);
2427 DPRINTF("found leaf index %u [%s], rc = %i",
2428 i, DKEY(&nodekey), rc);
2430 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2431 i, DKEY(&nodekey), NODEPGNO(node), rc);
2442 if (rc > 0) { /* Found entry is less than the key. */
2443 i++; /* Skip to get the smallest entry larger than key. */
2445 node = NODEPTR(mp, i);
2448 *exactp = (rc == 0);
2449 /* store the key index */
2450 mc->mc_ki[mc->mc_top] = i;
2452 /* There is no entry larger or equal to the key. */
2455 /* nodeptr is fake for LEAF2 */
2460 cursor_pop_page(MDB_cursor *mc)
2465 top = mc->mc_pg[mc->mc_top];
2470 DPRINTF("popped page %lu off db %u cursor %p", top->mp_pgno,
2471 mc->mc_dbi, (void *) mc);
2476 cursor_push_page(MDB_cursor *mc, MDB_page *mp)
2478 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2479 mc->mc_dbi, (void *) mc);
2481 if (mc->mc_snum >= CURSOR_STACK)
2484 mc->mc_top = mc->mc_snum++;
2485 mc->mc_pg[mc->mc_top] = mp;
2486 mc->mc_ki[mc->mc_top] = 0;
2492 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2496 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2498 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2499 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2500 p = txn->mt_u.dirty_list[x].mptr;
2504 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2505 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2509 DPRINTF("page %lu not found", pgno);
2512 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2516 mdb_search_page_root(MDB_cursor *mc, MDB_val *key, int modify)
2518 MDB_page *mp = mc->mc_pg[mc->mc_top];
2523 while (IS_BRANCH(mp)) {
2526 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2527 assert(NUMKEYS(mp) > 1);
2528 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2530 if (key == NULL) /* Initialize cursor to first page. */
2531 mc->mc_ki[mc->mc_top] = 0;
2532 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2533 /* cursor to last page */
2534 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
2537 node = mdb_search_node(mc, key, &exact);
2539 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2541 assert(mc->mc_ki[mc->mc_top] > 0);
2542 mc->mc_ki[mc->mc_top]--;
2547 DPRINTF("following index %u for key [%s]",
2548 mc->mc_ki[mc->mc_top], DKEY(key));
2549 assert(mc->mc_ki[mc->mc_top] < NUMKEYS(mp));
2550 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2552 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mp)))
2555 if ((rc = cursor_push_page(mc, mp)))
2559 if ((rc = mdb_touch(mc)) != 0)
2561 mp = mc->mc_pg[mc->mc_top];
2566 DPRINTF("internal error, index points to a %02X page!?",
2568 return MDB_CORRUPTED;
2571 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2572 key ? DKEY(key) : NULL);
2577 /* Search for the page a given key should be in.
2578 * Pushes parent pages on the cursor stack.
2579 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2580 * If modify is true, visited pages are updated with new page numbers.
2583 mdb_search_page(MDB_cursor *mc, MDB_val *key, int modify)
2588 /* Make sure the txn is still viable, then find the root from
2589 * the txn's db table.
2591 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2592 DPUTS("transaction has failed, must abort");
2595 root = mc->mc_txn->mt_dbs[mc->mc_dbi].md_root;
2597 if (root == P_INVALID) { /* Tree is empty. */
2598 DPUTS("tree is empty");
2599 return MDB_NOTFOUND;
2602 if ((rc = mdb_get_page(mc->mc_txn, root, &mc->mc_pg[0])))
2608 DPRINTF("db %u root page %lu has flags 0x%X",
2609 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2612 /* For sub-databases, update main root first */
2613 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2615 mc2.mc_txn = mc->mc_txn;
2616 mc2.mc_dbi = MAIN_DBI;
2617 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
2620 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2622 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2623 if ((rc = mdb_touch(mc)))
2625 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mc->mc_pg[0]->mp_pgno;
2629 return mdb_search_page_root(mc, key, modify);
2633 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2635 MDB_page *omp; /* overflow mpage */
2639 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2640 data->mv_size = NODEDSZ(leaf);
2641 data->mv_data = NODEDATA(leaf);
2645 /* Read overflow data.
2647 data->mv_size = NODEDSZ(leaf);
2648 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2649 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2650 DPRINTF("read overflow page %lu failed", pgno);
2653 data->mv_data = METADATA(omp);
2659 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2660 MDB_val *key, MDB_val *data)
2669 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2671 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2674 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2681 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2682 mc.mc_xcursor = &mx;
2683 mdb_xcursor_init0(&mc);
2685 mc.mc_xcursor = NULL;
2687 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2691 mdb_sibling(MDB_cursor *mc, int move_right)
2698 if (mc->mc_snum < 2) {
2699 return MDB_NOTFOUND; /* root has no siblings */
2701 ptop = mc->mc_top-1;
2703 DPRINTF("parent page is page %lu, index %u",
2704 mc->mc_pg[ptop]->mp_pgno, mc->mc_ki[ptop]);
2706 cursor_pop_page(mc);
2707 if (move_right ? (mc->mc_ki[ptop] + 1u >= NUMKEYS(mc->mc_pg[ptop]))
2708 : (mc->mc_ki[ptop] == 0)) {
2709 DPRINTF("no more keys left, moving to %s sibling",
2710 move_right ? "right" : "left");
2711 if ((rc = mdb_sibling(mc, move_right)) != MDB_SUCCESS)
2718 DPRINTF("just moving to %s index key %u",
2719 move_right ? "right" : "left", mc->mc_ki[ptop]);
2721 assert(IS_BRANCH(mc->mc_pg[ptop]));
2723 indx = NODEPTR(mc->mc_pg[ptop], mc->mc_ki[ptop]);
2724 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(indx), &mp)))
2727 cursor_push_page(mc, mp);
2733 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2739 if (mc->mc_flags & C_EOF) {
2740 return MDB_NOTFOUND;
2743 assert(mc->mc_flags & C_INITIALIZED);
2745 mp = mc->mc_pg[mc->mc_top];
2747 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2748 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2749 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2750 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2751 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2752 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2756 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2757 if (op == MDB_NEXT_DUP)
2758 return MDB_NOTFOUND;
2762 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) mc);
2764 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2765 DPUTS("=====> move to next sibling page");
2766 if (mdb_sibling(mc, 1) != MDB_SUCCESS) {
2767 mc->mc_flags |= C_EOF;
2768 return MDB_NOTFOUND;
2770 mp = mc->mc_pg[mc->mc_top];
2771 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2773 mc->mc_ki[mc->mc_top]++;
2775 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2776 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2779 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2780 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2784 assert(IS_LEAF(mp));
2785 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2787 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2788 mdb_xcursor_init1(mc, leaf);
2791 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2794 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2795 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2796 if (rc != MDB_SUCCESS)
2801 MDB_SET_KEY(leaf, key);
2806 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2812 assert(mc->mc_flags & C_INITIALIZED);
2814 mp = mc->mc_pg[mc->mc_top];
2816 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2817 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2818 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2819 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2820 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2821 if (op != MDB_PREV || rc == MDB_SUCCESS)
2824 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2825 if (op == MDB_PREV_DUP)
2826 return MDB_NOTFOUND;
2831 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) mc);
2833 if (mc->mc_ki[mc->mc_top] == 0) {
2834 DPUTS("=====> move to prev sibling page");
2835 if (mdb_sibling(mc, 0) != MDB_SUCCESS) {
2836 mc->mc_flags &= ~C_INITIALIZED;
2837 return MDB_NOTFOUND;
2839 mp = mc->mc_pg[mc->mc_top];
2840 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2841 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2843 mc->mc_ki[mc->mc_top]--;
2845 mc->mc_flags &= ~C_EOF;
2847 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2848 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2851 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2852 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2856 assert(IS_LEAF(mp));
2857 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2859 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2860 mdb_xcursor_init1(mc, leaf);
2863 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2866 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2867 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
2868 if (rc != MDB_SUCCESS)
2873 MDB_SET_KEY(leaf, key);
2878 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2879 MDB_cursor_op op, int *exactp)
2887 assert(key->mv_size > 0);
2889 /* See if we're already on the right page */
2890 if (mc->mc_flags & C_INITIALIZED) {
2893 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2894 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2895 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, nodekey.mv_size);
2897 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2898 MDB_SET_KEY(leaf, &nodekey);
2900 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2902 /* Probably happens rarely, but first node on the page
2903 * was the one we wanted.
2905 mc->mc_ki[mc->mc_top] = 0;
2909 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2914 if (NUMKEYS(mc->mc_pg[mc->mc_top]) > 1) {
2915 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2916 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top],
2917 NUMKEYS(mc->mc_pg[mc->mc_top])-1, nodekey.mv_size);
2919 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
2920 MDB_SET_KEY(leaf, &nodekey);
2922 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2924 /* last node was the one we wanted */
2925 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top])-1;
2929 /* This is definitely the right page, skip search_page */
2934 /* If any parents have right-sibs, search.
2935 * Otherwise, there's nothing further.
2937 for (i=0; i<mc->mc_top; i++)
2939 NUMKEYS(mc->mc_pg[i])-1)
2941 if (i == mc->mc_top) {
2942 /* There are no other pages */
2943 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
2944 return MDB_NOTFOUND;
2949 rc = mdb_search_page(mc, key, 0);
2950 if (rc != MDB_SUCCESS)
2953 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2956 leaf = mdb_search_node(mc, key, exactp);
2957 if (exactp != NULL && !*exactp) {
2958 /* MDB_SET specified and not an exact match. */
2959 return MDB_NOTFOUND;
2963 DPUTS("===> inexact leaf not found, goto sibling");
2964 if ((rc = mdb_sibling(mc, 1)) != MDB_SUCCESS)
2965 return rc; /* no entries matched */
2966 mc->mc_ki[mc->mc_top] = 0;
2967 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2968 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2972 mc->mc_flags |= C_INITIALIZED;
2973 mc->mc_flags &= ~C_EOF;
2975 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
2976 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2977 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
2981 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2982 mdb_xcursor_init1(mc, leaf);
2985 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2986 if (op == MDB_SET || op == MDB_SET_RANGE) {
2987 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2990 if (op == MDB_GET_BOTH) {
2996 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2997 if (rc != MDB_SUCCESS)
3000 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3002 if ((rc = mdb_read_data(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3004 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dcmp(data, &d2);
3006 if (op == MDB_GET_BOTH || rc > 0)
3007 return MDB_NOTFOUND;
3011 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3016 /* The key already matches in all other cases */
3017 if (op == MDB_SET_RANGE)
3018 MDB_SET_KEY(leaf, key);
3019 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3025 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3030 rc = mdb_search_page(mc, NULL, 0);
3031 if (rc != MDB_SUCCESS)
3033 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3035 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3036 mc->mc_flags |= C_INITIALIZED;
3037 mc->mc_flags &= ~C_EOF;
3039 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3040 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3041 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3046 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3047 mdb_xcursor_init1(mc, leaf);
3048 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3053 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3054 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3058 MDB_SET_KEY(leaf, key);
3063 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3069 lkey.mv_size = MAXKEYSIZE+1;
3070 lkey.mv_data = NULL;
3072 rc = mdb_search_page(mc, &lkey, 0);
3073 if (rc != MDB_SUCCESS)
3075 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3077 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3078 mc->mc_flags |= C_INITIALIZED;
3079 mc->mc_flags &= ~C_EOF;
3081 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3083 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3084 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3085 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3090 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3091 mdb_xcursor_init1(mc, leaf);
3092 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3096 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3101 MDB_SET_KEY(leaf, key);
3106 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3116 case MDB_GET_BOTH_RANGE:
3117 if (data == NULL || mc->mc_xcursor == NULL) {
3124 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3126 } else if (op == MDB_SET_RANGE)
3127 rc = mdb_cursor_set(mc, key, data, op, NULL);
3129 rc = mdb_cursor_set(mc, key, data, op, &exact);
3131 case MDB_GET_MULTIPLE:
3133 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) ||
3134 !(mc->mc_flags & C_INITIALIZED)) {
3139 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3140 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3143 case MDB_NEXT_MULTIPLE:
3145 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED)) {
3149 if (!(mc->mc_flags & C_INITIALIZED))
3150 rc = mdb_cursor_first(mc, key, data);
3152 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3153 if (rc == MDB_SUCCESS) {
3154 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3157 mx = &mc->mc_xcursor->mx_cursor;
3158 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3159 mx->mc_txn->mt_dbs[mx->mc_dbi].md_pad;
3160 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3161 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3169 case MDB_NEXT_NODUP:
3170 if (!(mc->mc_flags & C_INITIALIZED))
3171 rc = mdb_cursor_first(mc, key, data);
3173 rc = mdb_cursor_next(mc, key, data, op);
3177 case MDB_PREV_NODUP:
3178 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3179 rc = mdb_cursor_last(mc, key, data);
3181 rc = mdb_cursor_prev(mc, key, data, op);
3184 rc = mdb_cursor_first(mc, key, data);
3188 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3189 !(mc->mc_flags & C_INITIALIZED) ||
3190 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3194 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3197 rc = mdb_cursor_last(mc, key, data);
3201 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3202 !(mc->mc_flags & C_INITIALIZED) ||
3203 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3207 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3210 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3219 mdb_cursor_touch(MDB_cursor *mc)
3223 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
3225 mc2.mc_txn = mc->mc_txn;
3226 mc2.mc_dbi = MAIN_DBI;
3227 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
3229 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3231 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3232 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3236 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root =
3237 mc->mc_pg[mc->mc_top]->mp_pgno;
3241 mc->mc_top = mc->mc_snum-1;
3246 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3250 MDB_val xdata, *rdata, dkey;
3252 char dbuf[PAGESIZE];
3258 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3261 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3262 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3266 if (flags == MDB_CURRENT) {
3267 if (!(mc->mc_flags & C_INITIALIZED))
3270 } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
3272 /* new database, write a root leaf page */
3273 DPUTS("allocating new root leaf page");
3274 if ((np = mdb_new_page(mc, P_LEAF, 1)) == NULL) {
3278 cursor_push_page(mc, np);
3279 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = np->mp_pgno;
3280 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
3281 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3282 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3284 np->mp_flags |= P_LEAF2;
3285 mc->mc_flags |= C_INITIALIZED;
3291 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3292 if (flags == MDB_NOOVERWRITE && rc == 0) {
3293 DPRINTF("duplicate key [%s]", DKEY(key));
3295 return MDB_KEYEXIST;
3297 if (rc && rc != MDB_NOTFOUND)
3301 /* Cursor is positioned, now make sure all pages are writable */
3302 rc2 = mdb_cursor_touch(mc);
3303 if (rc2) return rc2;
3306 /* The key already exists */
3307 if (rc == MDB_SUCCESS) {
3308 /* there's only a key anyway, so this is a no-op */
3309 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3310 unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3311 if (key->mv_size != ksize)
3313 if (flags == MDB_CURRENT) {
3314 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3315 memcpy(ptr, key->mv_data, ksize);
3320 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3323 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
3324 /* Was a single item before, must convert now */
3325 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3326 dkey.mv_size = NODEDSZ(leaf);
3327 dkey.mv_data = dbuf;
3328 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3329 /* data matches, ignore it */
3330 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
3331 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3332 memset(&dummy, 0, sizeof(dummy));
3333 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
3334 dummy.md_pad = data->mv_size;
3335 dummy.md_flags = MDB_DUPFIXED;
3336 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
3337 dummy.md_flags |= MDB_INTEGERKEY;
3339 dummy.md_root = P_INVALID;
3340 if (dkey.mv_size == sizeof(MDB_db)) {
3341 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3344 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3347 xdata.mv_size = sizeof(MDB_db);
3348 xdata.mv_data = &dummy;
3349 /* new sub-DB, must fully init xcursor */
3350 if (flags == MDB_CURRENT)
3356 /* same size, just replace it */
3357 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3358 NODEDSZ(leaf) == data->mv_size) {
3359 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3362 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3364 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3370 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3371 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3372 rc = mdb_split(mc, key, rdata, P_INVALID);
3374 /* There is room already in this leaf page. */
3375 rc = mdb_add_node(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3378 if (rc != MDB_SUCCESS)
3379 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3381 /* Remember if we just added a subdatabase */
3382 if (flags & F_SUBDATA) {
3383 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3384 leaf->mn_flags |= F_SUBDATA;
3387 /* Now store the actual data in the child DB. Note that we're
3388 * storing the user data in the keys field, so there are strict
3389 * size limits on dupdata. The actual data fields of the child
3390 * DB are all zero size.
3393 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3395 if (flags == MDB_CURRENT)
3396 mdb_xcursor_init2(mc);
3398 mdb_xcursor_init1(mc, leaf);
3401 if (flags == MDB_NODUPDATA)
3402 flags = MDB_NOOVERWRITE;
3403 /* converted, write the original data first */
3405 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3407 leaf->mn_flags |= F_DUPDATA;
3409 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3410 mdb_xcursor_fini(mc);
3411 memcpy(NODEDATA(leaf),
3412 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3415 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3422 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3427 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3430 if (!mc->mc_flags & C_INITIALIZED)
3433 rc = mdb_cursor_touch(mc);
3436 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3438 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3439 if (flags != MDB_NODUPDATA) {
3440 mdb_xcursor_init2(mc);
3441 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3442 mdb_xcursor_fini(mc);
3443 /* If sub-DB still has entries, we're done */
3444 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3446 memcpy(NODEDATA(leaf),
3447 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3449 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3452 /* otherwise fall thru and delete the sub-DB */
3455 /* add all the child DB's pages to the free list */
3456 rc = mdb_search_page(&mc->mc_xcursor->mx_cursor, NULL, 0);
3457 if (rc == MDB_SUCCESS) {
3462 mx = &mc->mc_xcursor->mx_cursor;
3463 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3464 mx->mc_txn->mt_dbs[mx->mc_dbi].md_entries;
3466 cursor_pop_page(mx);
3468 while (mx->mc_snum > 1) {
3469 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3471 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3474 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3476 rc = mdb_sibling(mx, 1);
3481 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3482 mx->mc_txn->mt_dbs[mx->mc_dbi].md_root);
3486 return mdb_del0(mc, leaf);
3489 /* Allocate a page and initialize it
3492 mdb_new_page(MDB_cursor *mc, uint32_t flags, int num)
3496 if ((np = mdb_alloc_page(mc, num)) == NULL)
3498 DPRINTF("allocated new mpage %lu, page size %u",
3499 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3500 np->mp_flags = flags | P_DIRTY;
3501 np->mp_lower = PAGEHDRSZ;
3502 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3505 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages++;
3506 else if (IS_LEAF(np))
3507 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages++;
3508 else if (IS_OVERFLOW(np)) {
3509 mc->mc_txn->mt_dbs[mc->mc_dbi].md_overflow_pages += num;
3517 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3521 sz = LEAFSIZE(key, data);
3522 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3523 /* put on overflow page */
3524 sz -= data->mv_size - sizeof(pgno_t);
3528 return sz + sizeof(indx_t);
3532 mdb_branch_size(MDB_env *env, MDB_val *key)
3537 if (sz >= env->me_psize / MDB_MINKEYS) {
3538 /* put on overflow page */
3539 /* not implemented */
3540 /* sz -= key->size - sizeof(pgno_t); */
3543 return sz + sizeof(indx_t);
3547 mdb_add_node(MDB_cursor *mc, indx_t indx,
3548 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3551 size_t node_size = NODESIZE;
3554 MDB_page *mp = mc->mc_pg[mc->mc_top];
3555 MDB_page *ofp = NULL; /* overflow page */
3558 assert(mp->mp_upper >= mp->mp_lower);
3560 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
3561 IS_LEAF(mp) ? "leaf" : "branch",
3562 mp->mp_pgno, indx, data ? data->mv_size : 0,
3563 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3566 /* Move higher keys up one slot. */
3567 int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad, dif;
3568 char *ptr = LEAF2KEY(mp, indx, ksize);
3569 dif = NUMKEYS(mp) - indx;
3571 memmove(ptr+ksize, ptr, dif*ksize);
3572 /* insert new key */
3573 memcpy(ptr, key->mv_data, ksize);
3575 /* Just using these for counting */
3576 mp->mp_lower += sizeof(indx_t);
3577 mp->mp_upper -= ksize - sizeof(indx_t);
3582 node_size += key->mv_size;
3586 if (F_ISSET(flags, F_BIGDATA)) {
3587 /* Data already on overflow page. */
3588 node_size += sizeof(pgno_t);
3589 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3590 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3591 /* Put data on overflow page. */
3592 DPRINTF("data size is %zu, put on overflow page",
3594 node_size += sizeof(pgno_t);
3595 if ((ofp = mdb_new_page(mc, P_OVERFLOW, ovpages)) == NULL)
3597 DPRINTF("allocated overflow page %lu", ofp->mp_pgno);
3600 node_size += data->mv_size;
3603 node_size += node_size & 1;
3605 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3606 DPRINTF("not enough room in page %lu, got %u ptrs",
3607 mp->mp_pgno, NUMKEYS(mp));
3608 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3609 mp->mp_upper - mp->mp_lower);
3610 DPRINTF("node size = %zu", node_size);
3614 /* Move higher pointers up one slot. */
3615 for (i = NUMKEYS(mp); i > indx; i--)
3616 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3618 /* Adjust free space offsets. */
3619 ofs = mp->mp_upper - node_size;
3620 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3621 mp->mp_ptrs[indx] = ofs;
3623 mp->mp_lower += sizeof(indx_t);
3625 /* Write the node data. */
3626 node = NODEPTR(mp, indx);
3627 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3628 node->mn_flags = flags;
3630 SETDSZ(node,data->mv_size);
3635 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3640 if (F_ISSET(flags, F_BIGDATA))
3641 memcpy(node->mn_data + key->mv_size, data->mv_data,
3644 memcpy(node->mn_data + key->mv_size, data->mv_data,
3647 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3649 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3657 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3660 indx_t i, j, numkeys, ptr;
3664 DPRINTF("delete node %u on %s page %lu", indx,
3665 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3666 assert(indx < NUMKEYS(mp));
3669 int x = NUMKEYS(mp) - 1 - indx;
3670 base = LEAF2KEY(mp, indx, ksize);
3672 memmove(base, base + ksize, x * ksize);
3673 mp->mp_lower -= sizeof(indx_t);
3674 mp->mp_upper += ksize - sizeof(indx_t);
3678 node = NODEPTR(mp, indx);
3679 sz = NODESIZE + node->mn_ksize;
3681 if (F_ISSET(node->mn_flags, F_BIGDATA))
3682 sz += sizeof(pgno_t);
3684 sz += NODEDSZ(node);
3688 ptr = mp->mp_ptrs[indx];
3689 numkeys = NUMKEYS(mp);
3690 for (i = j = 0; i < numkeys; i++) {
3692 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3693 if (mp->mp_ptrs[i] < ptr)
3694 mp->mp_ptrs[j] += sz;
3699 base = (char *)mp + mp->mp_upper;
3700 memmove(base + sz, base, ptr - mp->mp_upper);
3702 mp->mp_lower -= sizeof(indx_t);
3707 mdb_xcursor_init0(MDB_cursor *mc)
3709 MDB_xcursor *mx = mc->mc_xcursor;
3712 mx->mx_txn = *mc->mc_txn;
3713 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3714 mx->mx_txn.mt_dbs = mx->mx_dbs;
3715 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3716 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3717 if (mc->mc_dbi > 1) {
3718 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3723 mx->mx_dbxs[dbn+1].md_parent = dbn;
3724 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3725 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3726 mx->mx_dbxs[dbn+1].md_dirty = 0;
3727 mx->mx_txn.mt_numdbs = dbn+2;
3728 mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3730 mx->mx_cursor.mc_xcursor = NULL;
3731 mx->mx_cursor.mc_txn = &mx->mx_txn;
3732 mx->mx_cursor.mc_dbi = dbn+1;
3736 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
3738 MDB_db *db = NODEDATA(node);
3739 MDB_xcursor *mx = mc->mc_xcursor;
3741 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3742 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3743 if (mc->mc_dbi > 1) {
3744 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3745 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3750 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi, db->md_root);
3751 mx->mx_dbs[dbn] = *db;
3752 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
3753 mx->mx_dbxs[dbn].md_dirty = 1;
3754 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3755 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3756 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3757 mx->mx_cursor.mc_snum = 0;
3758 mx->mx_cursor.mc_flags = 0;
3762 mdb_xcursor_init2(MDB_cursor *mc)
3764 MDB_xcursor *mx = mc->mc_xcursor;
3766 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3767 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3768 if (mc->mc_dbi > 1) {
3769 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3770 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3775 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi,
3776 mx->mx_dbs[dbn].md_root);
3777 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3781 mdb_xcursor_fini(MDB_cursor *mc)
3783 MDB_xcursor *mx = mc->mc_xcursor;
3784 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3785 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3786 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3787 if (mc->mc_dbi > 1) {
3788 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3789 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3794 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3797 size_t size = sizeof(MDB_cursor);
3799 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3802 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3803 size += sizeof(MDB_xcursor);
3805 if ((mc = calloc(1, size)) != NULL) {
3808 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3809 MDB_xcursor *mx = (MDB_xcursor *)(mc + 1);
3810 mc->mc_xcursor = mx;
3811 mdb_xcursor_init0(mc);
3822 /* Return the count of duplicate data items for the current key */
3824 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3828 if (mc == NULL || countp == NULL)
3831 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3834 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3835 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3838 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3841 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3847 mdb_cursor_close(MDB_cursor *mc)
3855 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3857 indx_t ptr, i, numkeys;
3864 node = NODEPTR(mp, indx);
3865 ptr = mp->mp_ptrs[indx];
3866 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3868 (int)node->mn_ksize, (char *)NODEKEY(node),
3872 delta = key->mv_size - node->mn_ksize;
3874 if (delta > 0 && SIZELEFT(mp) < delta) {
3875 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3879 numkeys = NUMKEYS(mp);
3880 for (i = 0; i < numkeys; i++) {
3881 if (mp->mp_ptrs[i] <= ptr)
3882 mp->mp_ptrs[i] -= delta;
3885 base = (char *)mp + mp->mp_upper;
3886 len = ptr - mp->mp_upper + NODESIZE;
3887 memmove(base - delta, base, len);
3888 mp->mp_upper -= delta;
3890 node = NODEPTR(mp, indx);
3891 node->mn_ksize = key->mv_size;
3894 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3899 /* Move a node from csrc to cdst.
3902 mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst)
3909 /* Mark src and dst as dirty. */
3910 if ((rc = mdb_touch(csrc)) ||
3911 (rc = mdb_touch(cdst)))
3914 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3915 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
3916 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
3917 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3919 data.mv_data = NULL;
3921 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3922 unsigned int snum = csrc->mc_snum;
3923 /* must find the lowest key below src */
3924 mdb_search_page_root(csrc, NULL, 0);
3925 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
3926 csrc->mc_snum = snum--;
3927 csrc->mc_top = snum;
3929 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3931 key.mv_size = NODEKSZ(srcnode);
3932 key.mv_data = NODEKEY(srcnode);
3933 data.mv_size = NODEDSZ(srcnode);
3934 data.mv_data = NODEDATA(srcnode);
3936 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3937 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
3938 csrc->mc_ki[csrc->mc_top],
3940 csrc->mc_pg[csrc->mc_top]->mp_pgno,
3941 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
3943 /* Add the node to the destination page.
3945 rc = mdb_add_node(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
3947 if (rc != MDB_SUCCESS)
3950 /* Delete the node from the source page.
3952 mdb_del_node(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3954 /* Update the parent separators.
3956 if (csrc->mc_ki[csrc->mc_top] == 0) {
3957 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
3958 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3959 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3961 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3962 key.mv_size = NODEKSZ(srcnode);
3963 key.mv_data = NODEKEY(srcnode);
3965 DPRINTF("update separator for source page %lu to [%s]",
3966 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
3967 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
3968 &key)) != MDB_SUCCESS)
3971 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3973 nullkey.mv_size = 0;
3974 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
3978 if (cdst->mc_ki[cdst->mc_top] == 0) {
3979 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
3980 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3981 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
3983 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
3984 key.mv_size = NODEKSZ(srcnode);
3985 key.mv_data = NODEKEY(srcnode);
3987 DPRINTF("update separator for destination page %lu to [%s]",
3988 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
3989 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
3990 &key)) != MDB_SUCCESS)
3993 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
3995 nullkey.mv_size = 0;
3996 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4004 mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4011 DPRINTF("merging page %lu into %lu", csrc->mc_pg[csrc->mc_top]->mp_pgno, cdst->mc_pg[cdst->mc_top]->mp_pgno);
4013 assert(csrc->mc_snum > 1); /* can't merge root page */
4014 assert(cdst->mc_snum > 1);
4016 /* Mark dst as dirty. */
4017 if ((rc = mdb_touch(cdst)))
4020 /* Move all nodes from src to dst.
4022 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4023 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4024 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
4025 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4026 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4027 rc = mdb_add_node(cdst, j, &key, NULL, 0, 0);
4028 if (rc != MDB_SUCCESS)
4030 key.mv_data = (char *)key.mv_data + key.mv_size;
4033 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4034 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4036 key.mv_size = srcnode->mn_ksize;
4037 key.mv_data = NODEKEY(srcnode);
4038 data.mv_size = NODEDSZ(srcnode);
4039 data.mv_data = NODEDATA(srcnode);
4040 rc = mdb_add_node(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4041 if (rc != MDB_SUCCESS)
4046 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
4047 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);
4049 /* Unlink the src page from parent and add to free list.
4051 mdb_del_node(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4052 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4054 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4058 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4059 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4060 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_leaf_pages--;
4062 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_branch_pages--;
4063 cursor_pop_page(csrc);
4065 return mdb_rebalance(csrc);
4069 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4073 cdst->mc_txn = csrc->mc_txn;
4074 cdst->mc_dbi = csrc->mc_dbi;
4075 cdst->mc_snum = csrc->mc_snum;
4076 cdst->mc_top = csrc->mc_top;
4077 cdst->mc_flags = csrc->mc_flags;
4079 for (i=0; i<csrc->mc_snum; i++) {
4080 cdst->mc_pg[i] = csrc->mc_pg[i];
4081 cdst->mc_ki[i] = csrc->mc_ki[i];
4086 mdb_rebalance(MDB_cursor *mc)
4094 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
4095 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4096 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);
4098 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4099 DPRINTF("no need to rebalance page %lu, above fill threshold",
4100 mc->mc_pg[mc->mc_top]->mp_pgno);
4104 if (mc->mc_snum < 2) {
4105 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4106 DPUTS("tree is completely empty");
4107 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = P_INVALID;
4108 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth = 0;
4109 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages = 0;
4110 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4111 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4112 DPUTS("collapsing root page!");
4113 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4114 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4115 if ((rc = mdb_get_page(mc->mc_txn, mc->mc_txn->mt_dbs[mc->mc_dbi].md_root, &root)))
4117 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4118 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages--;
4120 DPUTS("root page doesn't need rebalancing");
4124 /* The parent (branch page) must have at least 2 pointers,
4125 * otherwise the tree is invalid.
4127 ptop = mc->mc_top-1;
4128 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4130 /* Leaf page fill factor is below the threshold.
4131 * Try to move keys from left or right neighbor, or
4132 * merge with a neighbor page.
4137 mdb_cursor_copy(mc, &mn);
4138 mn.mc_xcursor = NULL;
4140 if (mc->mc_ki[ptop] == 0) {
4141 /* We're the leftmost leaf in our parent.
4143 DPUTS("reading right neighbor");
4145 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4146 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4148 mn.mc_ki[mn.mc_top] = 0;
4149 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4151 /* There is at least one neighbor to the left.
4153 DPUTS("reading left 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] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4159 mc->mc_ki[mc->mc_top] = 0;
4162 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
4163 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);
4165 /* If the neighbor page is above threshold and has at least two
4166 * keys, move one key from it.
4168 * Otherwise we should try to merge them.
4170 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4171 return mdb_move_node(&mn, mc);
4172 else { /* FIXME: if (has_enough_room()) */
4173 if (mc->mc_ki[ptop] == 0)
4174 return mdb_merge(&mn, mc);
4176 return mdb_merge(mc, &mn);
4181 mdb_del0(MDB_cursor *mc, MDB_node *leaf)
4185 /* add overflow pages to free list */
4186 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4190 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4191 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4192 for (i=0; i<ovpages; i++) {
4193 DPRINTF("freed ov page %lu", pg);
4194 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4198 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);
4199 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
4200 rc = mdb_rebalance(mc);
4201 if (rc != MDB_SUCCESS)
4202 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4208 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4209 MDB_val *key, MDB_val *data)
4214 MDB_val rdata, *xdata;
4218 assert(key != NULL);
4220 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4222 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4225 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4229 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4236 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4237 mc.mc_xcursor = &mx;
4238 mdb_xcursor_init0(&mc);
4240 mc.mc_xcursor = NULL;
4252 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4254 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4258 /* Split page <mc->top>, and insert <key,(data|newpgno)> in either left or
4259 * right sibling, at index <mc->ki> (as if unsplit). Updates mc->top and
4260 * mc->ki with the actual values after split, ie if mc->top and mc->ki
4261 * refer to a node in the new right sibling page.
4264 mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4267 int rc = MDB_SUCCESS, ins_new = 0;
4270 unsigned int i, j, split_indx, nkeys, pmax;
4272 MDB_val sepkey, rkey, rdata;
4274 MDB_page *mp, *rp, *pp;
4279 mp = mc->mc_pg[mc->mc_top];
4280 newindx = mc->mc_ki[mc->mc_top];
4282 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
4283 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4284 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4286 if (mc->mc_snum < 2) {
4287 if ((pp = mdb_new_page(mc, P_BRANCH, 1)) == NULL)
4289 /* shift current top to make room for new parent */
4290 mc->mc_pg[1] = mc->mc_pg[0];
4291 mc->mc_ki[1] = mc->mc_ki[0];
4294 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = pp->mp_pgno;
4295 DPRINTF("root split! new root = %lu", pp->mp_pgno);
4296 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
4298 /* Add left (implicit) pointer. */
4299 if ((rc = mdb_add_node(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4300 /* undo the pre-push */
4301 mc->mc_pg[0] = mc->mc_pg[1];
4302 mc->mc_ki[0] = mc->mc_ki[1];
4303 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mp->mp_pgno;
4304 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4311 ptop = mc->mc_top-1;
4312 DPRINTF("parent branch page is %lu", mc->mc_pg[ptop]->mp_pgno);
4315 /* Create a right sibling. */
4316 if ((rp = mdb_new_page(mc, mp->mp_flags, 1)) == NULL)
4318 mdb_cursor_copy(mc, &mn);
4319 mn.mc_pg[mn.mc_top] = rp;
4320 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4321 DPRINTF("new right sibling: page %lu", rp->mp_pgno);
4323 nkeys = NUMKEYS(mp);
4324 split_indx = nkeys / 2 + 1;
4329 unsigned int lsize, rsize, ksize;
4330 /* Move half of the keys to the right sibling */
4332 x = mc->mc_ki[mc->mc_top] - split_indx;
4333 ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
4334 split = LEAF2KEY(mp, split_indx, ksize);
4335 rsize = (nkeys - split_indx) * ksize;
4336 lsize = (nkeys - split_indx) * sizeof(indx_t);
4337 mp->mp_lower -= lsize;
4338 rp->mp_lower += lsize;
4339 mp->mp_upper += rsize - lsize;
4340 rp->mp_upper -= rsize - lsize;
4341 sepkey.mv_size = ksize;
4342 if (newindx == split_indx) {
4343 sepkey.mv_data = newkey->mv_data;
4345 sepkey.mv_data = split;
4348 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4349 memcpy(rp->mp_ptrs, split, rsize);
4350 sepkey.mv_data = rp->mp_ptrs;
4351 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4352 memcpy(ins, newkey->mv_data, ksize);
4353 mp->mp_lower += sizeof(indx_t);
4354 mp->mp_upper -= ksize - sizeof(indx_t);
4357 memcpy(rp->mp_ptrs, split, x * ksize);
4358 ins = LEAF2KEY(rp, x, ksize);
4359 memcpy(ins, newkey->mv_data, ksize);
4360 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4361 rp->mp_lower += sizeof(indx_t);
4362 rp->mp_upper -= ksize - sizeof(indx_t);
4363 mc->mc_ki[mc->mc_top] = x;
4364 mc->mc_pg[mc->mc_top] = rp;
4369 /* For leaf pages, check the split point based on what
4370 * fits where, since otherwise add_node can fail.
4373 unsigned int psize, nsize;
4374 /* Maximum free space in an empty page */
4375 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4376 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4377 if (newindx < split_indx) {
4379 for (i=0; i<split_indx; i++) {
4380 node = NODEPTR(mp, i);
4381 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4382 if (F_ISSET(node->mn_flags, F_BIGDATA))
4383 psize += sizeof(pgno_t);
4385 psize += NODEDSZ(node);
4394 for (i=nkeys-1; i>=split_indx; i--) {
4395 node = NODEPTR(mp, i);
4396 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4397 if (F_ISSET(node->mn_flags, F_BIGDATA))
4398 psize += sizeof(pgno_t);
4400 psize += NODEDSZ(node);
4410 /* First find the separating key between the split pages.
4412 if (newindx == split_indx) {
4413 sepkey.mv_size = newkey->mv_size;
4414 sepkey.mv_data = newkey->mv_data;
4416 node = NODEPTR(mp, split_indx);
4417 sepkey.mv_size = node->mn_ksize;
4418 sepkey.mv_data = NODEKEY(node);
4422 DPRINTF("separator is [%s]", DKEY(&sepkey));
4424 /* Copy separator key to the parent.
4426 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4429 rc = mdb_split(&mn, &sepkey, NULL, rp->mp_pgno);
4431 /* Right page might now have changed parent.
4432 * Check if left page also changed parent.
4434 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4435 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4436 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4437 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4441 rc = mdb_add_node(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4447 if (rc != MDB_SUCCESS) {
4451 /* Move half of the keys to the right sibling. */
4453 /* grab a page to hold a temporary copy */
4454 if (mc->mc_txn->mt_env->me_dpages) {
4455 copy = mc->mc_txn->mt_env->me_dpages;
4456 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4458 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4462 copy->mp_pgno = mp->mp_pgno;
4463 copy->mp_flags = mp->mp_flags;
4464 copy->mp_lower = PAGEHDRSZ;
4465 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4466 mc->mc_pg[mc->mc_top] = copy;
4467 for (i = j = 0; i <= nkeys; j++) {
4468 if (i == split_indx) {
4469 /* Insert in right sibling. */
4470 /* Reset insert index for right sibling. */
4471 j = (i == newindx && ins_new);
4472 mc->mc_pg[mc->mc_top] = rp;
4475 if (i == newindx && !ins_new) {
4476 /* Insert the original entry that caused the split. */
4477 rkey.mv_data = newkey->mv_data;
4478 rkey.mv_size = newkey->mv_size;
4480 rdata.mv_data = newdata->mv_data;
4481 rdata.mv_size = newdata->mv_size;
4488 /* Update page and index for the new key. */
4489 mc->mc_ki[mc->mc_top] = j;
4490 } else if (i == nkeys) {
4493 node = NODEPTR(mp, i);
4494 rkey.mv_data = NODEKEY(node);
4495 rkey.mv_size = node->mn_ksize;
4497 rdata.mv_data = NODEDATA(node);
4498 rdata.mv_size = NODEDSZ(node);
4500 pgno = NODEPGNO(node);
4501 flags = node->mn_flags;
4506 if (!IS_LEAF(mp) && j == 0) {
4507 /* First branch index doesn't need key data. */
4511 rc = mdb_add_node(mc, j, &rkey, &rdata, pgno, flags);
4514 /* reset back to original page */
4515 if (newindx < split_indx)
4516 mc->mc_pg[mc->mc_top] = mp;
4518 nkeys = NUMKEYS(copy);
4519 for (i=0; i<nkeys; i++)
4520 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4521 mp->mp_lower = copy->mp_lower;
4522 mp->mp_upper = copy->mp_upper;
4523 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4524 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4526 /* return tmp page to freelist */
4527 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4528 mc->mc_txn->mt_env->me_dpages = copy;
4533 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4534 MDB_val *key, MDB_val *data, unsigned int flags)
4539 assert(key != NULL);
4540 assert(data != NULL);
4542 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4545 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4549 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4553 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4560 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4561 mc.mc_xcursor = &mx;
4562 mdb_xcursor_init0(&mc);
4564 mc.mc_xcursor = NULL;
4566 return mdb_cursor_put(&mc, key, data, flags);
4570 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4572 /** Only a subset of the @ref mdb_env flags can be changed
4573 * at runtime. Changing other flags requires closing the environment
4574 * and re-opening it with the new flags.
4576 #define CHANGEABLE (MDB_NOSYNC)
4577 if ((flag & CHANGEABLE) != flag)
4580 env->me_flags |= flag;
4582 env->me_flags &= ~flag;
4587 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4592 *arg = env->me_flags;
4597 mdb_env_get_path(MDB_env *env, const char **arg)
4602 *arg = env->me_path;
4607 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4609 arg->ms_psize = env->me_psize;
4610 arg->ms_depth = db->md_depth;
4611 arg->ms_branch_pages = db->md_branch_pages;
4612 arg->ms_leaf_pages = db->md_leaf_pages;
4613 arg->ms_overflow_pages = db->md_overflow_pages;
4614 arg->ms_entries = db->md_entries;
4619 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4623 if (env == NULL || arg == NULL)
4626 mdb_env_read_meta(env, &toggle);
4628 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4632 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4634 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4635 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4636 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4637 txn->mt_dbxs[dbi].md_cmp = cintcmp;
4639 txn->mt_dbxs[dbi].md_cmp = memncmp;
4641 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4642 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4643 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4644 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4646 txn->mt_dbxs[dbi].md_dcmp = cintcmp;
4647 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4648 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4650 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4653 txn->mt_dbxs[dbi].md_dcmp = NULL;
4657 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4664 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4665 mdb_default_cmp(txn, FREE_DBI);
4671 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4672 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4673 mdb_default_cmp(txn, MAIN_DBI);
4677 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4678 mdb_default_cmp(txn, MAIN_DBI);
4681 /* Is the DB already open? */
4683 for (i=2; i<txn->mt_numdbs; i++) {
4684 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4685 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4691 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4694 /* Find the DB info */
4696 key.mv_data = (void *)name;
4697 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4699 /* Create if requested */
4700 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4703 data.mv_size = sizeof(MDB_db);
4704 data.mv_data = &dummy;
4705 memset(&dummy, 0, sizeof(dummy));
4706 dummy.md_root = P_INVALID;
4707 dummy.md_flags = flags & 0xffff;
4709 mc.mc_dbi = MAIN_DBI;
4711 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4715 /* OK, got info, add to table */
4716 if (rc == MDB_SUCCESS) {
4717 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4718 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4719 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4720 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4721 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4722 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4723 *dbi = txn->mt_numdbs;
4724 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4725 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4726 mdb_default_cmp(txn, txn->mt_numdbs);
4733 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4735 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4738 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4741 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4744 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4746 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4747 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4748 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4752 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4754 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4757 txn->mt_dbxs[dbi].md_cmp = cmp;
4761 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4763 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4766 txn->mt_dbxs[dbi].md_dcmp = cmp;
4770 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4772 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4775 txn->mt_dbxs[dbi].md_rel = rel;