2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
67 #if (__BYTE_ORDER == __LITTLE_ENDIAN) == (__BYTE_ORDER == __BIG_ENDIAN)
68 # error "Unknown or unsupported endianness (__BYTE_ORDER)"
69 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
70 # error "Two's complement, reasonably sized integer types, please"
73 /** @defgroup internal MDB Internals
76 /** @defgroup compat Windows Compatibility Macros
77 * A bunch of macros to minimize the amount of platform-specific ifdefs
78 * needed throughout the rest of the code. When the features this library
79 * needs are similar enough to POSIX to be hidden in a one-or-two line
80 * replacement, this macro approach is used.
84 #define pthread_t DWORD
85 #define pthread_mutex_t HANDLE
86 #define pthread_key_t DWORD
87 #define pthread_self() GetCurrentThreadId()
88 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
89 #define pthread_key_delete(x) TlsFree(x)
90 #define pthread_getspecific(x) TlsGetValue(x)
91 #define pthread_setspecific(x,y) TlsSetValue(x,y)
92 #define pthread_mutex_unlock(x) ReleaseMutex(x)
93 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
94 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
95 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
96 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
97 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
98 #define getpid() GetCurrentProcessId()
99 #define fdatasync(fd) (!FlushFileBuffers(fd))
100 #define ErrCode() GetLastError()
101 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
102 #define close(fd) CloseHandle(fd)
103 #define munmap(ptr,len) UnmapViewOfFile(ptr)
105 /** Lock the reader mutex.
107 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
108 /** Unlock the reader mutex.
110 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
112 /** Lock the writer mutex.
113 * Only a single write transaction is allowed at a time. Other writers
114 * will block waiting for this mutex.
116 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
117 /** Unlock the writer mutex.
119 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
121 /** Get the error code for the last failed system function.
123 #define ErrCode() errno
125 /** An abstraction for a file handle.
126 * On POSIX systems file handles are small integers. On Windows
127 * they're opaque pointers.
131 /** A value for an invalid file handle.
132 * Mainly used to initialize file variables and signify that they are
135 #define INVALID_HANDLE_VALUE (-1)
137 /** Get the size of a memory page for the system.
138 * This is the basic size that the platform's memory manager uses, and is
139 * fundamental to the use of memory-mapped files.
141 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
147 /** A flag for opening a file and requesting synchronous data writes.
148 * This is only used when writing a meta page. It's not strictly needed;
149 * we could just do a normal write and then immediately perform a flush.
150 * But if this flag is available it saves us an extra system call.
152 * @note If O_DSYNC is undefined but exists in /usr/include,
153 * preferably set some compiler flag to get the definition.
154 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
157 # define MDB_DSYNC O_DSYNC
161 /** A page number in the database.
162 * Note that 64 bit page numbers are overkill, since pages themselves
163 * already represent 12-13 bits of addressable memory, and the OS will
164 * always limit applications to a maximum of 63 bits of address space.
166 * @note In the #MDB_node structure, we only store 48 bits of this value,
167 * which thus limits us to only 60 bits of addressable data.
169 typedef ULONG pgno_t;
171 /** @defgroup debug Debug Macros
175 /** Enable debug output.
176 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
177 * read from and written to the database (used for free space management).
182 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
183 # define DPRINTF (void) /* Vararg macros may be unsupported */
185 /** Print a debug message with printf formatting. */
186 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
187 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
189 # define DPRINTF(fmt, ...) ((void) 0)
191 /** Print a debug string.
192 * The string is printed literally, with no format processing.
194 #define DPUTS(arg) DPRINTF("%s", arg)
197 /** A default memory page size.
198 * The actual size is platform-dependent, but we use this for
199 * boot-strapping. We probably should not be using this any more.
200 * The #GET_PAGESIZE() macro is used to get the actual size.
202 * Note that we don't currently support Huge pages. On Linux,
203 * regular data files cannot use Huge pages, and in general
204 * Huge pages aren't actually pageable. We rely on the OS
205 * demand-pager to read our data and page it out when memory
206 * pressure from other processes is high. So until OSs have
207 * actual paging support for Huge pages, they're not viable.
209 #define PAGESIZE 4096
211 /** The minimum number of keys required in a database page.
212 * Setting this to a larger value will place a smaller bound on the
213 * maximum size of a data item. Data items larger than this size will
214 * be pushed into overflow pages instead of being stored directly in
215 * the B-tree node. This value used to default to 4. With a page size
216 * of 4096 bytes that meant that any item larger than 1024 bytes would
217 * go into an overflow page. That also meant that on average 2-3KB of
218 * each overflow page was wasted space. The value cannot be lower than
219 * 2 because then there would no longer be a tree structure. With this
220 * value, items larger than 2KB will go into overflow pages, and on
221 * average only 1KB will be wasted.
223 #define MDB_MINKEYS 2
225 /** A stamp that identifies a file as an MDB file.
226 * There's nothing special about this value other than that it is easily
227 * recognizable, and it will reflect any byte order mismatches.
229 #define MDB_MAGIC 0xBEEFC0DE
231 /** The version number for a database's file format. */
232 #define MDB_VERSION 1
234 /** The maximum size of a key in the database.
235 * While data items have essentially unbounded size, we require that
236 * keys all fit onto a regular page. This limit could be raised a bit
237 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
239 #define MAXKEYSIZE 511
244 * This is used for printing a hex dump of a key's contents.
246 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
247 /** Display a key in hex.
249 * Invoke a function to display a key in hex.
251 #define DKEY(x) mdb_dkey(x, kbuf)
253 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
257 /** @defgroup lazylock Lazy Locking
258 * Macros for locks that are't actually needed.
259 * The DB view is always consistent because all writes are wrapped in
260 * the wmutex. Finer-grained locks aren't necessary.
264 /** Use lazy locking. I.e., don't lock these accesses at all. */
268 /** Grab the reader lock */
269 #define LAZY_MUTEX_LOCK(x)
270 /** Release the reader lock */
271 #define LAZY_MUTEX_UNLOCK(x)
272 /** Release the DB table reader/writer lock */
273 #define LAZY_RWLOCK_UNLOCK(x)
274 /** Grab the DB table write lock */
275 #define LAZY_RWLOCK_WRLOCK(x)
276 /** Grab the DB table read lock */
277 #define LAZY_RWLOCK_RDLOCK(x)
278 /** Declare the DB table rwlock. Should not be followed by ';'. */
279 #define LAZY_RWLOCK_DEF(x)
280 /** Initialize the DB table rwlock */
281 #define LAZY_RWLOCK_INIT(x,y)
282 /** Destroy the DB table rwlock */
283 #define LAZY_RWLOCK_DESTROY(x)
285 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
286 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
287 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
288 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
289 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
290 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
291 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
292 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
296 /** An invalid page number.
297 * Mainly used to denote an empty tree.
299 #define P_INVALID (~0UL)
301 /** Test if a flag \b f is set in a flag word \b w. */
302 #define F_ISSET(w, f) (((w) & (f)) == (f))
304 /** Used for offsets within a single page.
305 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
308 typedef uint16_t indx_t;
310 /** Default size of memory map.
311 * This is certainly too small for any actual applications. Apps should always set
312 * the size explicitly using #mdb_env_set_mapsize().
314 #define DEFAULT_MAPSIZE 1048576
316 /** @defgroup readers Reader Lock Table
317 * Readers don't acquire any locks for their data access. Instead, they
318 * simply record their transaction ID in the reader table. The reader
319 * mutex is needed just to find an empty slot in the reader table. The
320 * slot's address is saved in thread-specific data so that subsequent read
321 * transactions started by the same thread need no further locking to proceed.
323 * Since the database uses multi-version concurrency control, readers don't
324 * actually need any locking. This table is used to keep track of which
325 * readers are using data from which old transactions, so that we'll know
326 * when a particular old transaction is no longer in use. Old transactions
327 * that have discarded any data pages can then have those pages reclaimed
328 * for use by a later write transaction.
330 * The lock table is constructed such that reader slots are aligned with the
331 * processor's cache line size. Any slot is only ever used by one thread.
332 * This alignment guarantees that there will be no contention or cache
333 * thrashing as threads update their own slot info, and also eliminates
334 * any need for locking when accessing a slot.
336 * A writer thread will scan every slot in the table to determine the oldest
337 * outstanding reader transaction. Any freed pages older than this will be
338 * reclaimed by the writer. The writer doesn't use any locks when scanning
339 * this table. This means that there's no guarantee that the writer will
340 * see the most up-to-date reader info, but that's not required for correct
341 * operation - all we need is to know the upper bound on the oldest reader,
342 * we don't care at all about the newest reader. So the only consequence of
343 * reading stale information here is that old pages might hang around a
344 * while longer before being reclaimed. That's actually good anyway, because
345 * the longer we delay reclaiming old pages, the more likely it is that a
346 * string of contiguous pages can be found after coalescing old pages from
347 * many old transactions together.
349 * @todo We don't actually do such coalescing yet, we grab pages from one
350 * old transaction at a time.
353 /** Number of slots in the reader table.
354 * This value was chosen somewhat arbitrarily. 126 readers plus a
355 * couple mutexes fit exactly into 8KB on my development machine.
356 * Applications should set the table size using #mdb_env_set_maxreaders().
358 #define DEFAULT_READERS 126
360 /** The size of a CPU cache line in bytes. We want our lock structures
361 * aligned to this size to avoid false cache line sharing in the
363 * This value works for most CPUs. For Itanium this should be 128.
369 /** The information we store in a single slot of the reader table.
370 * In addition to a transaction ID, we also record the process and
371 * thread ID that owns a slot, so that we can detect stale information,
372 * e.g. threads or processes that went away without cleaning up.
373 * @note We currently don't check for stale records. We simply re-init
374 * the table when we know that we're the only process opening the
377 typedef struct MDB_rxbody {
378 /** The current Transaction ID when this transaction began.
379 * Multiple readers that start at the same time will probably have the
380 * same ID here. Again, it's not important to exclude them from
381 * anything; all we need to know is which version of the DB they
382 * started from so we can avoid overwriting any data used in that
383 * particular version.
386 /** The process ID of the process owning this reader txn. */
388 /** The thread ID of the thread owning this txn. */
392 /** The actual reader record, with cacheline padding. */
393 typedef struct MDB_reader {
396 /** shorthand for mrb_txnid */
397 #define mr_txnid mru.mrx.mrb_txnid
398 #define mr_pid mru.mrx.mrb_pid
399 #define mr_tid mru.mrx.mrb_tid
400 /** cache line alignment */
401 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
405 /** The header for the reader table.
406 * The table resides in a memory-mapped file. (This is a different file
407 * than is used for the main database.)
409 * For POSIX the actual mutexes reside in the shared memory of this
410 * mapped file. On Windows, mutexes are named objects allocated by the
411 * kernel; we store the mutex names in this mapped file so that other
412 * processes can grab them. This same approach will also be used on
413 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
414 * process-shared POSIX mutexes.
416 typedef struct MDB_txbody {
417 /** Stamp identifying this as an MDB lock file. It must be set
420 /** Version number of this lock file. Must be set to #MDB_VERSION. */
421 uint32_t mtb_version;
425 /** Mutex protecting access to this table.
426 * This is the reader lock that #LOCK_MUTEX_R acquires.
428 pthread_mutex_t mtb_mutex;
430 /** The ID of the last transaction committed to the database.
431 * This is recorded here only for convenience; the value can always
432 * be determined by reading the main database meta pages.
435 /** The number of slots that have been used in the reader table.
436 * This always records the maximum count, it is not decremented
437 * when readers release their slots.
439 uint32_t mtb_numreaders;
440 /** The ID of the most recent meta page in the database.
441 * This is recorded here only for convenience; the value can always
442 * be determined by reading the main database meta pages.
444 uint32_t mtb_me_toggle;
447 /** The actual reader table definition. */
448 typedef struct MDB_txninfo {
451 #define mti_magic mt1.mtb.mtb_magic
452 #define mti_version mt1.mtb.mtb_version
453 #define mti_mutex mt1.mtb.mtb_mutex
454 #define mti_rmname mt1.mtb.mtb_rmname
455 #define mti_txnid mt1.mtb.mtb_txnid
456 #define mti_numreaders mt1.mtb.mtb_numreaders
457 #define mti_me_toggle mt1.mtb.mtb_me_toggle
458 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
463 #define mti_wmname mt2.mt2_wmname
465 pthread_mutex_t mt2_wmutex;
466 #define mti_wmutex mt2.mt2_wmutex
468 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
470 MDB_reader mti_readers[1];
474 /** Common header for all page types.
475 * Overflow pages occupy a number of contiguous pages with no
476 * headers on any page after the first.
478 typedef struct MDB_page {
479 #define mp_pgno mp_p.p_pgno
480 #define mp_next mp_p.p_next
482 pgno_t p_pgno; /**< page number */
483 void * p_next; /**< for in-memory list of freed structs */
485 #define P_BRANCH 0x01 /**< branch page */
486 #define P_LEAF 0x02 /**< leaf page */
487 #define P_OVERFLOW 0x04 /**< overflow page */
488 #define P_META 0x08 /**< meta page */
489 #define P_DIRTY 0x10 /**< dirty page */
490 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
492 #define mp_lower mp_pb.pb.pb_lower
493 #define mp_upper mp_pb.pb.pb_upper
494 #define mp_pages mp_pb.pb_pages
497 indx_t pb_lower; /**< lower bound of free space */
498 indx_t pb_upper; /**< upper bound of free space */
500 uint32_t pb_pages; /**< number of overflow pages */
502 indx_t mp_ptrs[1]; /**< dynamic size */
505 /** Size of the page header, excluding dynamic data at the end */
506 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
508 /** Address of first usable data byte in a page, after the header */
509 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
511 /** Number of nodes on a page */
512 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
514 /** The amount of space remaining in the page */
515 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
517 /** The percentage of space used in the page, in tenths of a percent. */
518 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
519 ((env)->me_psize - PAGEHDRSZ))
520 /** The minimum page fill factor, in tenths of a percent.
521 * Pages emptier than this are candidates for merging.
523 #define FILL_THRESHOLD 250
525 /** Test if a page is a leaf page */
526 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
527 /** Test if a page is a LEAF2 page */
528 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
529 /** Test if a page is a branch page */
530 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
531 /** Test if a page is an overflow page */
532 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
534 /** The number of overflow pages needed to store the given size. */
535 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
537 /** Header for a single key/data pair within a page.
538 * We guarantee 2-byte alignment for nodes.
540 typedef struct MDB_node {
541 /** lo and hi are used for data size on leaf nodes and for
542 * child pgno on branch nodes. On 64 bit platforms, flags
543 * is also used for pgno. (Branch nodes have no flags).
544 * They are in in host byte order in case that lets some
545 * accesses be optimized into a 32-bit word access.
547 #define mn_lo mn_offset[__BYTE_ORDER!=__LITTLE_ENDIAN]
548 #define mn_hi mn_offset[__BYTE_ORDER==__LITTLE_ENDIAN] /**< part of dsize or pgno */
549 unsigned short mn_offset[2];
550 unsigned short mn_flags; /**< flags for special node types */
551 #define F_BIGDATA 0x01 /**< data put on overflow page */
552 #define F_SUBDATA 0x02 /**< data is a sub-database */
553 #define F_DUPDATA 0x04 /**< data has duplicates */
554 unsigned short mn_ksize; /**< key size */
555 char mn_data[1]; /**< key and data are appended here */
558 /** Size of the node header, excluding dynamic data at the end */
559 #define NODESIZE offsetof(MDB_node, mn_data)
561 /** Size of a node in a branch page with a given key.
562 * This is just the node header plus the key, there is no data.
564 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
566 /** Size of a node in a leaf page with a given key and data.
567 * This is node header plus key plus data size.
569 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
571 /** Address of node \b i in page \b p */
572 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
574 /** Address of the key for the node */
575 #define NODEKEY(node) (void *)((node)->mn_data)
577 /** Address of the data for a node */
578 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
580 /** Get the page number pointed to by a branch node */
581 #if LONG_MAX == 0x7fffffff
582 #define NODEPGNO(node) ((node)->mn_lo | ((node)->mn_hi << 16))
583 /** Set the page number in a branch node */
584 #define SETPGNO(node,pgno) do { \
585 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16;} while(0)
587 #define NODEPGNO(node) ((node)->mn_lo | ((node)->mn_hi << 16) | ((unsigned long)(node)->mn_flags << 32))
588 /** Set the page number in a branch node */
589 #define SETPGNO(node,pgno) do { \
590 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
591 (node)->mn_flags = (pgno) >> 32; } while(0)
594 /** Get the size of the data in a leaf node */
595 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
596 /** Set the size of the data for a leaf node */
597 #define SETDSZ(node,size) do { \
598 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
599 /** The size of a key in a node */
600 #define NODEKSZ(node) ((node)->mn_ksize)
602 /** The address of a key in a LEAF2 page.
603 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
604 * There are no node headers, keys are stored contiguously.
606 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
608 /** Set the \b node's key into \b key, if requested. */
609 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
610 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
612 /** Information about a single database in the environment. */
613 typedef struct MDB_db {
614 uint32_t md_pad; /**< also ksize for LEAF2 pages */
615 uint16_t md_flags; /**< @ref mdb_open */
616 uint16_t md_depth; /**< depth of this tree */
617 ULONG md_branch_pages; /**< number of internal pages */
618 ULONG md_leaf_pages; /**< number of leaf pages */
619 ULONG md_overflow_pages; /**< number of overflow pages */
620 ULONG md_entries; /**< number of data items */
621 pgno_t md_root; /**< the root page of this tree */
624 /** Handle for the DB used to track free pages. */
626 /** Handle for the default DB. */
629 /** Meta page content. */
630 typedef struct MDB_meta {
631 /** Stamp identifying this as an MDB data file. It must be set
634 /** Version number of this lock file. Must be set to #MDB_VERSION. */
636 void *mm_address; /**< address for fixed mapping */
637 size_t mm_mapsize; /**< size of mmap region */
638 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
639 /** The size of pages used in this DB */
640 #define mm_psize mm_dbs[0].md_pad
641 /** Any persistent environment flags. @ref mdb_env */
642 #define mm_flags mm_dbs[0].md_flags
643 pgno_t mm_last_pg; /**< last used page in file */
644 ULONG mm_txnid; /**< txnid that committed this page */
647 /** Auxiliary DB info.
648 * The information here is mostly static/read-only. There is
649 * only a single copy of this record in the environment.
650 * The \b md_dirty flag is not read-only, but only a write
651 * transaction can ever update it, and only write transactions
652 * need to worry about it.
654 typedef struct MDB_dbx {
655 MDB_val md_name; /**< name of the database */
656 MDB_cmp_func *md_cmp; /**< function for comparing keys */
657 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
658 MDB_rel_func *md_rel; /**< user relocate function */
659 MDB_dbi md_parent; /**< parent DB of a sub-DB */
660 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
663 /** A database transaction.
664 * Every operation requires a transaction handle.
667 pgno_t mt_next_pgno; /**< next unallocated page */
668 /** The ID of this transaction. IDs are integers incrementing from 1.
669 * Only committed write transactions increment the ID. If a transaction
670 * aborts, the ID may be re-used by the next writer.
673 MDB_env *mt_env; /**< the DB environment */
674 /** The list of pages that became unused during this transaction.
679 ID2L dirty_list; /**< modified pages */
680 MDB_reader *reader; /**< this thread's slot in the reader table */
682 /** Array of records for each DB known in the environment. */
684 /** Array of MDB_db records for each known DB */
686 /** Number of DB records in use. This number only ever increments;
687 * we don't decrement it when individual DB handles are closed.
689 unsigned int mt_numdbs;
691 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
692 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
693 unsigned int mt_flags;
694 /** Tracks which of the two meta pages was used at the start
695 * of this transaction.
697 unsigned int mt_toggle;
700 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
701 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
702 * raise this on a 64 bit machine.
704 #define CURSOR_STACK 32
708 /** Cursors are used for all DB operations */
710 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
711 struct MDB_xcursor *mc_xcursor;
712 /** The transaction that owns this cursor */
714 /** The database handle this cursor operates on */
716 unsigned short mc_snum; /**< number of pushed pages */
717 unsigned short mc_top; /**< index of top page, mc_snum-1 */
718 unsigned int mc_flags;
719 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
720 #define C_EOF 0x02 /**< No more data */
721 #define C_XDIRTY 0x04 /**< @deprecated mc_xcursor needs to be flushed */
722 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
723 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
726 /** Context for sorted-dup records.
727 * We could have gone to a fully recursive design, with arbitrarily
728 * deep nesting of sub-databases. But for now we only handle these
729 * levels - main DB, optional sub-DB, sorted-duplicate DB.
731 typedef struct MDB_xcursor {
732 /** A sub-cursor for traversing the Dup DB */
733 MDB_cursor mx_cursor;
734 /** A fake transaction struct for pointing to our own table
738 /** Our private DB information tables. Slots 0 and 1 are always
739 * copies of the corresponding slots in the main transaction. These
740 * hold the FREEDB and MAINDB, respectively. If the main cursor is
741 * on a sub-database, that will be copied to slot 2, and the duplicate
742 * database info will be in slot 3. If the main cursor is on the MAINDB
743 * then the duplicate DB info will be in slot 2 and slot 3 will be unused.
750 /** A set of pages freed by an earlier transaction. */
751 typedef struct MDB_oldpages {
752 /** Usually we only read one record from the FREEDB at a time, but
753 * in case we read more, this will chain them together.
755 struct MDB_oldpages *mo_next;
756 /** The ID of the transaction in which these pages were freed. */
758 /** An #IDL of the pages */
759 pgno_t mo_pages[1]; /* dynamic */
762 /** The database environment. */
764 HANDLE me_fd; /**< The main data file */
765 HANDLE me_lfd; /**< The lock file */
766 HANDLE me_mfd; /**< just for writing the meta pages */
767 /** Failed to update the meta page. Probably an I/O error. */
768 #define MDB_FATAL_ERROR 0x80000000U
770 uint32_t me_extrapad; /**< unused for now */
771 unsigned int me_maxreaders; /**< size of the reader table */
772 unsigned int me_numdbs; /**< number of DBs opened */
773 unsigned int me_maxdbs; /**< size of the DB table */
774 char *me_path; /**< path to the DB files */
775 char *me_map; /**< the memory map of the data file */
776 MDB_txninfo *me_txns; /**< the memory map of the lock file */
777 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
778 MDB_txn *me_txn; /**< current write transaction */
779 size_t me_mapsize; /**< size of the data memory map */
780 off_t me_size; /**< current file size */
781 pgno_t me_maxpg; /**< me_mapsize / me_psize */
782 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
783 unsigned int me_db_toggle; /**< which DB table is current */
784 MDB_dbx *me_dbxs; /**< array of static DB info */
785 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
786 MDB_oldpages *me_pghead; /**< list of old page records */
787 pthread_key_t me_txkey; /**< thread-key for readers */
788 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
789 /** IDL of pages that became unused in a write txn */
790 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
791 /** ID2L of pages that were written during a write txn */
792 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
793 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
794 LAZY_RWLOCK_DEF(me_dblock)
796 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
800 /** max number of pages to commit in one writev() call */
801 #define MDB_COMMIT_PAGES 64
803 static MDB_page *mdb_alloc_page(MDB_cursor *mc, int num);
804 static int mdb_touch(MDB_cursor *mc);
806 static int mdb_search_page_root(MDB_cursor *mc,
807 MDB_val *key, int modify);
808 static int mdb_search_page(MDB_cursor *mc,
809 MDB_val *key, int modify);
811 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
812 static int mdb_env_read_meta(MDB_env *env, int *which);
813 static int mdb_env_write_meta(MDB_txn *txn);
814 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
816 static MDB_node *mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp);
817 static int mdb_add_node(MDB_cursor *mc, indx_t indx,
818 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
819 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
820 static int mdb_del0(MDB_cursor *mc, MDB_node *leaf);
821 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
823 static int mdb_rebalance(MDB_cursor *mc);
824 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
825 static int mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst);
826 static int mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst);
827 static int mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
829 static MDB_page *mdb_new_page(MDB_cursor *mc, uint32_t flags, int num);
831 static void cursor_pop_page(MDB_cursor *mc);
832 static int cursor_push_page(MDB_cursor *mc, MDB_page *mp);
834 static int mdb_sibling(MDB_cursor *mc, int move_right);
835 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
836 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
837 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
839 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
840 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
842 static void mdb_xcursor_init0(MDB_cursor *mc);
843 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
844 static void mdb_xcursor_init2(MDB_cursor *mc);
845 static void mdb_xcursor_fini(MDB_cursor *mc);
847 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
848 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
850 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
853 static MDB_cmp_func memncmp, memnrcmp, intcmp, cintcmp;
857 static SECURITY_DESCRIPTOR mdb_null_sd;
858 static SECURITY_ATTRIBUTES mdb_all_sa;
859 static int mdb_sec_inited;
862 /** Return the library version info. */
864 mdb_version(int *major, int *minor, int *patch)
866 if (major) *major = MDB_VERSION_MAJOR;
867 if (minor) *minor = MDB_VERSION_MINOR;
868 if (patch) *patch = MDB_VERSION_PATCH;
869 return MDB_VERSION_STRING;
872 /** Table of descriptions for MDB @ref errors */
873 static char *const mdb_errstr[] = {
874 "MDB_KEYEXIST: Key/data pair already exists",
875 "MDB_NOTFOUND: No matching key/data pair found",
876 "MDB_PAGE_NOTFOUND: Requested page not found",
877 "MDB_CORRUPTED: Located page was wrong type",
878 "MDB_PANIC: Update of meta page failed",
879 "MDB_VERSION_MISMATCH: Database environment version mismatch"
883 mdb_strerror(int err)
886 return ("Successful return: 0");
888 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
889 return mdb_errstr[err - MDB_KEYEXIST];
891 return strerror(err);
895 /** Display a key in hexadecimal and return the address of the result.
896 * @param[in] key the key to display
897 * @param[in] buf the buffer to write into. Should always be #DKBUF.
898 * @return The key in hexadecimal form.
901 mdb_dkey(MDB_val *key, char *buf)
904 unsigned char *c = key->mv_data;
906 if (key->mv_size > MAXKEYSIZE)
908 /* may want to make this a dynamic check: if the key is mostly
909 * printable characters, print it as-is instead of converting to hex.
912 for (i=0; i<key->mv_size; i++)
913 ptr += sprintf(ptr, "%02x", *c++);
915 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
922 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
924 return txn->mt_dbxs[dbi].md_cmp(a, b);
927 /** Compare two data items according to a particular database.
928 * This returns a comparison as if the two items were data items of
929 * a sorted duplicates #MDB_DUPSORT database.
930 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
931 * @param[in] dbi A database handle returned by #mdb_open()
932 * @param[in] a The first item to compare
933 * @param[in] b The second item to compare
934 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
937 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
939 if (txn->mt_dbxs[dbi].md_dcmp)
940 return txn->mt_dbxs[dbi].md_dcmp(a, b);
942 return EINVAL; /* too bad you can't distinguish this from a valid result */
945 /** Allocate pages for writing.
946 * If there are free pages available from older transactions, they
947 * will be re-used first. Otherwise a new page will be allocated.
948 * @param[in] mc cursor A cursor handle identifying the transaction and
949 * database for which we are allocating.
950 * @param[in] num the number of pages to allocate.
951 * @return Address of the allocated page(s). Requests for multiple pages
952 * will always be satisfied by a single contiguous chunk of memory.
955 mdb_alloc_page(MDB_cursor *mc, int num)
957 MDB_txn *txn = mc->mc_txn;
959 pgno_t pgno = P_INVALID;
962 if (txn->mt_txnid > 2) {
964 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
965 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
966 /* See if there's anything in the free DB */
972 m2.mc_dbi = FREE_DBI;
975 mdb_search_page(&m2, NULL, 0);
976 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
977 kptr = (ULONG *)NODEKEY(leaf);
981 oldest = txn->mt_txnid - 1;
982 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
983 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
984 if (mr && mr < oldest)
989 if (oldest > *kptr) {
990 /* It's usable, grab it.
996 mdb_read_data(txn, leaf, &data);
997 idl = (ULONG *)data.mv_data;
998 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
999 mop->mo_next = txn->mt_env->me_pghead;
1000 mop->mo_txnid = *kptr;
1001 txn->mt_env->me_pghead = mop;
1002 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1007 DPRINTF("IDL read txn %lu root %lu num %lu",
1008 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1009 for (i=0; i<idl[0]; i++) {
1010 DPRINTF("IDL %lu", idl[i+1]);
1014 /* drop this IDL from the DB */
1015 m2.mc_ki[m2.mc_top] = 0;
1016 m2.mc_flags = C_INITIALIZED;
1017 mdb_cursor_del(&m2, 0);
1020 if (txn->mt_env->me_pghead) {
1021 MDB_oldpages *mop = txn->mt_env->me_pghead;
1023 /* FIXME: For now, always use fresh pages. We
1024 * really ought to search the free list for a
1029 /* peel pages off tail, so we only have to truncate the list */
1030 pgno = MDB_IDL_LAST(mop->mo_pages);
1031 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1033 if (mop->mo_pages[2] > mop->mo_pages[1])
1034 mop->mo_pages[0] = 0;
1038 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1039 txn->mt_env->me_pghead = mop->mo_next;
1046 if (pgno == P_INVALID) {
1047 /* DB size is maxed out */
1048 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
1051 if (txn->mt_env->me_dpages && num == 1) {
1052 np = txn->mt_env->me_dpages;
1053 txn->mt_env->me_dpages = np->mp_next;
1055 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1058 if (pgno == P_INVALID) {
1059 np->mp_pgno = txn->mt_next_pgno;
1060 txn->mt_next_pgno += num;
1064 mid.mid = np->mp_pgno;
1066 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1071 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1072 * @param[in] mc cursor pointing to the page to be touched
1073 * @return 0 on success, non-zero on failure.
1076 mdb_touch(MDB_cursor *mc)
1078 MDB_page *mp = mc->mc_pg[mc->mc_top];
1081 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1083 if ((np = mdb_alloc_page(mc, 1)) == NULL)
1085 DPRINTF("touched db %u page %lu -> %lu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1086 assert(mp->mp_pgno != np->mp_pgno);
1087 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1089 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1092 mp->mp_flags |= P_DIRTY;
1094 mc->mc_pg[mc->mc_top] = mp;
1095 /** If this page has a parent, update the parent to point to
1099 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1105 mdb_env_sync(MDB_env *env, int force)
1108 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1109 if (fdatasync(env->me_fd))
1116 mdb_txn_reset0(MDB_txn *txn);
1118 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1119 * @param[in] txn the transaction handle to initialize
1120 * @return 0 on success, non-zero on failure. This can only
1121 * fail for read-only transactions, and then only if the
1122 * reader table is full.
1125 mdb_txn_renew0(MDB_txn *txn)
1127 MDB_env *env = txn->mt_env;
1129 if (txn->mt_flags & MDB_TXN_RDONLY) {
1130 MDB_reader *r = pthread_getspecific(env->me_txkey);
1133 pid_t pid = getpid();
1134 pthread_t tid = pthread_self();
1137 for (i=0; i<env->me_txns->mti_numreaders; i++)
1138 if (env->me_txns->mti_readers[i].mr_pid == 0)
1140 if (i == env->me_maxreaders) {
1141 UNLOCK_MUTEX_R(env);
1144 env->me_txns->mti_readers[i].mr_pid = pid;
1145 env->me_txns->mti_readers[i].mr_tid = tid;
1146 if (i >= env->me_txns->mti_numreaders)
1147 env->me_txns->mti_numreaders = i+1;
1148 UNLOCK_MUTEX_R(env);
1149 r = &env->me_txns->mti_readers[i];
1150 pthread_setspecific(env->me_txkey, r);
1152 txn->mt_txnid = env->me_txns->mti_txnid;
1153 txn->mt_toggle = env->me_txns->mti_me_toggle;
1154 r->mr_txnid = txn->mt_txnid;
1155 txn->mt_u.reader = r;
1159 txn->mt_txnid = env->me_txns->mti_txnid+1;
1160 txn->mt_toggle = env->me_txns->mti_me_toggle;
1161 txn->mt_u.dirty_list = env->me_dirty_list;
1162 txn->mt_u.dirty_list[0].mid = 0;
1163 txn->mt_free_pgs = env->me_free_pgs;
1164 txn->mt_free_pgs[0] = 0;
1165 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1169 /* Copy the DB arrays */
1170 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1171 txn->mt_numdbs = env->me_numdbs;
1172 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1173 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1174 if (txn->mt_numdbs > 2)
1175 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1176 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1177 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1183 mdb_txn_renew(MDB_txn *txn)
1190 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1191 DPUTS("environment had fatal error, must shutdown!");
1195 rc = mdb_txn_renew0(txn);
1196 if (rc == MDB_SUCCESS) {
1197 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
1198 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1199 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1205 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1210 if (env->me_flags & MDB_FATAL_ERROR) {
1211 DPUTS("environment had fatal error, must shutdown!");
1214 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1215 DPRINTF("calloc: %s", strerror(ErrCode()));
1218 txn->mt_dbs = (MDB_db *)(txn+1);
1219 if (flags & MDB_RDONLY) {
1220 txn->mt_flags |= MDB_TXN_RDONLY;
1224 rc = mdb_txn_renew0(txn);
1229 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
1230 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1231 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1237 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1238 * @param[in] txn the transaction handle to reset
1241 mdb_txn_reset0(MDB_txn *txn)
1243 MDB_env *env = txn->mt_env;
1245 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1246 txn->mt_u.reader->mr_txnid = 0;
1252 /* return all dirty pages to dpage list */
1253 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1254 dp = txn->mt_u.dirty_list[i].mptr;
1255 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1256 dp->mp_next = txn->mt_env->me_dpages;
1257 txn->mt_env->me_dpages = dp;
1259 /* large pages just get freed directly */
1264 while ((mop = txn->mt_env->me_pghead)) {
1265 txn->mt_env->me_pghead = mop->mo_next;
1270 for (i=2; i<env->me_numdbs; i++)
1271 env->me_dbxs[i].md_dirty = 0;
1272 /* The writer mutex was locked in mdb_txn_begin. */
1273 UNLOCK_MUTEX_W(env);
1278 mdb_txn_reset(MDB_txn *txn)
1283 DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
1284 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1285 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1287 mdb_txn_reset0(txn);
1291 mdb_txn_abort(MDB_txn *txn)
1296 DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
1297 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1298 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1300 mdb_txn_reset0(txn);
1305 mdb_txn_commit(MDB_txn *txn)
1316 assert(txn != NULL);
1317 assert(txn->mt_env != NULL);
1321 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1326 if (txn != env->me_txn) {
1327 DPUTS("attempt to commit unknown transaction");
1332 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1333 DPUTS("error flag is set, can't commit");
1338 if (!txn->mt_u.dirty_list[0].mid)
1341 DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
1342 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1345 mc.mc_dbi = FREE_DBI;
1348 /* should only be one record now */
1349 if (env->me_pghead) {
1350 /* make sure first page of freeDB is touched and on freelist */
1351 mdb_search_page(&mc, NULL, 1);
1353 /* save to free list */
1354 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1358 /* make sure last page of freeDB is touched and on freelist */
1359 key.mv_size = MAXKEYSIZE+1;
1361 mdb_search_page(&mc, &key, 1);
1363 mdb_midl_sort(txn->mt_free_pgs);
1367 ULONG *idl = txn->mt_free_pgs;
1368 DPRINTF("IDL write txn %lu root %lu num %lu",
1369 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1370 for (i=0; i<idl[0]; i++) {
1371 DPRINTF("IDL %lu", idl[i+1]);
1375 /* write to last page of freeDB */
1376 key.mv_size = sizeof(pgno_t);
1377 key.mv_data = (char *)&txn->mt_txnid;
1378 data.mv_data = txn->mt_free_pgs;
1379 /* The free list can still grow during this call,
1380 * despite the pre-emptive touches above. So check
1381 * and make sure the entire thing got written.
1384 i = txn->mt_free_pgs[0];
1385 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1386 rc = mdb_cursor_put(&mc, &key, &data, 0);
1391 } while (i != txn->mt_free_pgs[0]);
1393 /* should only be one record now */
1394 if (env->me_pghead) {
1398 mop = env->me_pghead;
1399 key.mv_size = sizeof(pgno_t);
1400 key.mv_data = (char *)&mop->mo_txnid;
1401 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1402 data.mv_data = mop->mo_pages;
1403 mdb_cursor_put(&mc, &key, &data, 0);
1404 free(env->me_pghead);
1405 env->me_pghead = NULL;
1408 /* Update DB root pointers. Their pages have already been
1409 * touched so this is all in-place and cannot fail.
1413 data.mv_size = sizeof(MDB_db);
1415 mc.mc_dbi = MAIN_DBI;
1417 for (i = 2; i < txn->mt_numdbs; i++) {
1418 if (txn->mt_dbxs[i].md_dirty) {
1419 data.mv_data = &txn->mt_dbs[i];
1420 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1425 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1431 /* Windows actually supports scatter/gather I/O, but only on
1432 * unbuffered file handles. Since we're relying on the OS page
1433 * cache for all our data, that's self-defeating. So we just
1434 * write pages one at a time. We use the ov structure to set
1435 * the write offset, to at least save the overhead of a Seek
1439 memset(&ov, 0, sizeof(ov));
1440 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1442 dp = txn->mt_u.dirty_list[i].mptr;
1443 DPRINTF("committing page %lu", dp->mp_pgno);
1444 size = dp->mp_pgno * env->me_psize;
1445 ov.Offset = size & 0xffffffff;
1446 ov.OffsetHigh = size >> 16;
1447 ov.OffsetHigh >>= 16;
1448 /* clear dirty flag */
1449 dp->mp_flags &= ~P_DIRTY;
1450 wsize = env->me_psize;
1451 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1452 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1455 DPRINTF("WriteFile: %d", n);
1462 struct iovec iov[MDB_COMMIT_PAGES];
1466 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1467 dp = txn->mt_u.dirty_list[i].mptr;
1468 if (dp->mp_pgno != next) {
1470 DPRINTF("committing %u dirty pages", n);
1471 rc = writev(env->me_fd, iov, n);
1475 DPUTS("short write, filesystem full?");
1477 DPRINTF("writev: %s", strerror(n));
1484 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1487 DPRINTF("committing page %lu", dp->mp_pgno);
1488 iov[n].iov_len = env->me_psize;
1489 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1490 iov[n].iov_base = dp;
1491 size += iov[n].iov_len;
1492 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1493 /* clear dirty flag */
1494 dp->mp_flags &= ~P_DIRTY;
1495 if (++n >= MDB_COMMIT_PAGES) {
1505 DPRINTF("committing %u dirty pages", n);
1506 rc = writev(env->me_fd, iov, n);
1510 DPUTS("short write, filesystem full?");
1512 DPRINTF("writev: %s", strerror(n));
1519 /* Drop the dirty pages.
1521 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1522 dp = txn->mt_u.dirty_list[i].mptr;
1523 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1524 dp->mp_next = txn->mt_env->me_dpages;
1525 txn->mt_env->me_dpages = dp;
1529 txn->mt_u.dirty_list[i].mid = 0;
1531 txn->mt_u.dirty_list[0].mid = 0;
1533 if ((n = mdb_env_sync(env, 0)) != 0 ||
1534 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1541 /* update the DB tables */
1543 int toggle = !env->me_db_toggle;
1546 ip = &env->me_dbs[toggle][2];
1547 jp = &txn->mt_dbs[2];
1548 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1549 for (i = 2; i < txn->mt_numdbs; i++) {
1550 if (ip->md_root != jp->md_root)
1555 for (i = 2; i < txn->mt_numdbs; i++) {
1556 if (txn->mt_dbxs[i].md_dirty)
1557 txn->mt_dbxs[i].md_dirty = 0;
1559 env->me_db_toggle = toggle;
1560 env->me_numdbs = txn->mt_numdbs;
1561 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1564 UNLOCK_MUTEX_W(env);
1570 /** Read the environment parameters of a DB environment before
1571 * mapping it into memory.
1572 * @param[in] env the environment handle
1573 * @param[out] meta address of where to store the meta information
1574 * @return 0 on success, non-zero on failure.
1577 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1579 char page[PAGESIZE];
1584 /* We don't know the page size yet, so use a minimum value.
1588 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1590 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1595 else if (rc != PAGESIZE) {
1599 DPRINTF("read: %s", strerror(err));
1603 p = (MDB_page *)page;
1605 if (!F_ISSET(p->mp_flags, P_META)) {
1606 DPRINTF("page %lu not a meta page", p->mp_pgno);
1611 if (m->mm_magic != MDB_MAGIC) {
1612 DPUTS("meta has invalid magic");
1616 if (m->mm_version != MDB_VERSION) {
1617 DPRINTF("database is version %u, expected version %u",
1618 m->mm_version, MDB_VERSION);
1619 return MDB_VERSION_MISMATCH;
1622 memcpy(meta, m, sizeof(*m));
1626 /** Write the environment parameters of a freshly created DB environment.
1627 * @param[in] env the environment handle
1628 * @param[out] meta address of where to store the meta information
1629 * @return 0 on success, non-zero on failure.
1632 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1639 DPUTS("writing new meta page");
1641 GET_PAGESIZE(psize);
1643 meta->mm_magic = MDB_MAGIC;
1644 meta->mm_version = MDB_VERSION;
1645 meta->mm_psize = psize;
1646 meta->mm_last_pg = 1;
1647 meta->mm_flags = env->me_flags & 0xffff;
1648 meta->mm_flags |= MDB_INTEGERKEY;
1649 meta->mm_dbs[0].md_root = P_INVALID;
1650 meta->mm_dbs[1].md_root = P_INVALID;
1652 p = calloc(2, psize);
1654 p->mp_flags = P_META;
1657 memcpy(m, meta, sizeof(*meta));
1659 q = (MDB_page *)((char *)p + psize);
1662 q->mp_flags = P_META;
1665 memcpy(m, meta, sizeof(*meta));
1670 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1671 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1674 rc = write(env->me_fd, p, psize * 2);
1675 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1681 /** Update the environment info to commit a transaction.
1682 * @param[in] txn the transaction that's being committed
1683 * @return 0 on success, non-zero on failure.
1686 mdb_env_write_meta(MDB_txn *txn)
1689 MDB_meta meta, metab;
1691 int rc, len, toggle;
1697 assert(txn != NULL);
1698 assert(txn->mt_env != NULL);
1700 toggle = !txn->mt_toggle;
1701 DPRINTF("writing meta page %d for root page %lu",
1702 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1706 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1707 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1709 ptr = (char *)&meta;
1710 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1711 len = sizeof(MDB_meta) - off;
1714 meta.mm_dbs[0] = txn->mt_dbs[0];
1715 meta.mm_dbs[1] = txn->mt_dbs[1];
1716 meta.mm_last_pg = txn->mt_next_pgno - 1;
1717 meta.mm_txnid = txn->mt_txnid;
1720 off += env->me_psize;
1723 /* Write to the SYNC fd */
1726 memset(&ov, 0, sizeof(ov));
1728 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1731 rc = pwrite(env->me_mfd, ptr, len, off);
1736 DPUTS("write failed, disk error?");
1737 /* On a failure, the pagecache still contains the new data.
1738 * Write some old data back, to prevent it from being used.
1739 * Use the non-SYNC fd; we know it will fail anyway.
1741 meta.mm_last_pg = metab.mm_last_pg;
1742 meta.mm_txnid = metab.mm_txnid;
1744 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1746 r2 = pwrite(env->me_fd, ptr, len, off);
1748 env->me_flags |= MDB_FATAL_ERROR;
1751 /* Memory ordering issues are irrelevant; since the entire writer
1752 * is wrapped by wmutex, all of these changes will become visible
1753 * after the wmutex is unlocked. Since the DB is multi-version,
1754 * readers will get consistent data regardless of how fresh or
1755 * how stale their view of these values is.
1757 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1758 txn->mt_env->me_txns->mti_me_toggle = toggle;
1759 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1760 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1765 /** Check both meta pages to see which one is newer.
1766 * @param[in] env the environment handle
1767 * @param[out] which address of where to store the meta toggle ID
1768 * @return 0 on success, non-zero on failure.
1771 mdb_env_read_meta(MDB_env *env, int *which)
1775 assert(env != NULL);
1777 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1780 DPRINTF("Using meta page %d", toggle);
1787 mdb_env_create(MDB_env **env)
1791 e = calloc(1, sizeof(MDB_env));
1792 if (!e) return ENOMEM;
1794 e->me_maxreaders = DEFAULT_READERS;
1796 e->me_fd = INVALID_HANDLE_VALUE;
1797 e->me_lfd = INVALID_HANDLE_VALUE;
1798 e->me_mfd = INVALID_HANDLE_VALUE;
1804 mdb_env_set_mapsize(MDB_env *env, size_t size)
1808 env->me_mapsize = size;
1813 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1817 env->me_maxdbs = dbs;
1822 mdb_env_set_maxreaders(MDB_env *env, int readers)
1826 env->me_maxreaders = readers;
1831 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1833 if (!env || !readers)
1835 *readers = env->me_maxreaders;
1839 /** Further setup required for opening an MDB environment
1842 mdb_env_open2(MDB_env *env, unsigned int flags)
1844 int i, newenv = 0, toggle;
1848 env->me_flags = flags;
1850 memset(&meta, 0, sizeof(meta));
1852 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1855 DPUTS("new mdbenv");
1859 if (!env->me_mapsize) {
1860 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1866 LONG sizelo, sizehi;
1867 sizelo = env->me_mapsize & 0xffffffff;
1868 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1870 /* Windows won't create mappings for zero length files.
1871 * Just allocate the maxsize right now.
1874 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1875 if (!SetEndOfFile(env->me_fd))
1877 SetFilePointer(env->me_fd, 0, NULL, 0);
1879 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1880 sizehi, sizelo, NULL);
1883 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1891 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1893 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1895 if (env->me_map == MAP_FAILED)
1900 meta.mm_mapsize = env->me_mapsize;
1901 if (flags & MDB_FIXEDMAP)
1902 meta.mm_address = env->me_map;
1903 i = mdb_env_init_meta(env, &meta);
1904 if (i != MDB_SUCCESS) {
1905 munmap(env->me_map, env->me_mapsize);
1909 env->me_psize = meta.mm_psize;
1911 env->me_maxpg = env->me_mapsize / env->me_psize;
1913 p = (MDB_page *)env->me_map;
1914 env->me_metas[0] = METADATA(p);
1915 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1917 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1920 DPRINTF("opened database version %u, pagesize %u",
1921 env->me_metas[toggle]->mm_version, env->me_psize);
1922 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1923 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1924 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1925 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1926 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1927 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1933 /* Windows doesn't support destructor callbacks for thread-specific storage */
1935 mdb_env_reader_dest(void *ptr)
1937 MDB_reader *reader = ptr;
1939 reader->mr_txnid = 0;
1945 /* downgrade the exclusive lock on the region back to shared */
1947 mdb_env_share_locks(MDB_env *env)
1951 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1953 env->me_txns->mti_me_toggle = toggle;
1954 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1959 /* First acquire a shared lock. The Unlock will
1960 * then release the existing exclusive lock.
1962 memset(&ov, 0, sizeof(ov));
1963 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1964 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1968 struct flock lock_info;
1969 /* The shared lock replaces the existing lock */
1970 memset((void *)&lock_info, 0, sizeof(lock_info));
1971 lock_info.l_type = F_RDLCK;
1972 lock_info.l_whence = SEEK_SET;
1973 lock_info.l_start = 0;
1974 lock_info.l_len = 1;
1975 fcntl(env->me_lfd, F_SETLK, &lock_info);
1981 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1989 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1990 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1991 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1995 /* Try to get exclusive lock. If we succeed, then
1996 * nobody is using the lock region and we should initialize it.
1999 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2003 memset(&ov, 0, sizeof(ov));
2004 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2010 size = GetFileSize(env->me_lfd, NULL);
2012 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2016 /* Try to get exclusive lock. If we succeed, then
2017 * nobody is using the lock region and we should initialize it.
2020 struct flock lock_info;
2021 memset((void *)&lock_info, 0, sizeof(lock_info));
2022 lock_info.l_type = F_WRLCK;
2023 lock_info.l_whence = SEEK_SET;
2024 lock_info.l_start = 0;
2025 lock_info.l_len = 1;
2026 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2030 lock_info.l_type = F_RDLCK;
2031 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2038 size = lseek(env->me_lfd, 0, SEEK_END);
2040 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2041 if (size < rsize && *excl) {
2043 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2044 if (!SetEndOfFile(env->me_lfd)) {
2049 if (ftruncate(env->me_lfd, rsize) != 0) {
2056 size = rsize - sizeof(MDB_txninfo);
2057 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2062 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2068 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2070 if (!env->me_txns) {
2076 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2078 if (env->me_txns == MAP_FAILED) {
2086 if (!mdb_sec_inited) {
2087 InitializeSecurityDescriptor(&mdb_null_sd,
2088 SECURITY_DESCRIPTOR_REVISION);
2089 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2090 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2091 mdb_all_sa.bInheritHandle = FALSE;
2092 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2095 /* FIXME: only using up to 20 characters of the env path here,
2096 * probably not enough to assure uniqueness...
2098 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
2099 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
2100 while ((ptr = strchr(ptr, '\\')))
2102 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2103 if (!env->me_rmutex) {
2107 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
2108 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
2109 while ((ptr = strchr(ptr, '\\')))
2111 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2112 if (!env->me_wmutex) {
2117 pthread_mutexattr_t mattr;
2119 pthread_mutexattr_init(&mattr);
2120 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2124 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2125 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2127 env->me_txns->mti_version = MDB_VERSION;
2128 env->me_txns->mti_magic = MDB_MAGIC;
2129 env->me_txns->mti_txnid = 0;
2130 env->me_txns->mti_numreaders = 0;
2131 env->me_txns->mti_me_toggle = 0;
2134 if (env->me_txns->mti_magic != MDB_MAGIC) {
2135 DPUTS("lock region has invalid magic");
2139 if (env->me_txns->mti_version != MDB_VERSION) {
2140 DPRINTF("lock region is version %u, expected version %u",
2141 env->me_txns->mti_version, MDB_VERSION);
2142 rc = MDB_VERSION_MISMATCH;
2146 if (rc != EACCES && rc != EAGAIN) {
2150 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2151 if (!env->me_rmutex) {
2155 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2156 if (!env->me_wmutex) {
2166 env->me_lfd = INVALID_HANDLE_VALUE;
2171 /** The name of the lock file in the DB environment */
2172 #define LOCKNAME "/lock.mdb"
2173 /** The name of the data file in the DB environment */
2174 #define DATANAME "/data.mdb"
2176 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2178 int oflags, rc, len, excl;
2179 char *lpath, *dpath;
2182 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2185 dpath = lpath + len + sizeof(LOCKNAME);
2186 sprintf(lpath, "%s" LOCKNAME, path);
2187 sprintf(dpath, "%s" DATANAME, path);
2189 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2194 if (F_ISSET(flags, MDB_RDONLY)) {
2195 oflags = GENERIC_READ;
2196 len = OPEN_EXISTING;
2198 oflags = GENERIC_READ|GENERIC_WRITE;
2201 mode = FILE_ATTRIBUTE_NORMAL;
2202 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2203 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2208 if (F_ISSET(flags, MDB_RDONLY))
2211 oflags = O_RDWR | O_CREAT;
2213 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2219 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2220 /* synchronous fd for meta writes */
2222 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2223 mode |= FILE_FLAG_WRITE_THROUGH;
2224 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2225 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2230 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2231 oflags |= MDB_DSYNC;
2232 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2237 env->me_path = strdup(path);
2238 DPRINTF("opened dbenv %p", (void *) env);
2239 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2240 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2242 mdb_env_share_locks(env);
2243 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2244 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2245 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2251 if (env->me_fd != INVALID_HANDLE_VALUE) {
2253 env->me_fd = INVALID_HANDLE_VALUE;
2255 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2257 env->me_lfd = INVALID_HANDLE_VALUE;
2265 mdb_env_close(MDB_env *env)
2272 while (env->me_dpages) {
2273 dp = env->me_dpages;
2274 env->me_dpages = dp->mp_next;
2278 free(env->me_dbs[1]);
2279 free(env->me_dbs[0]);
2283 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2284 pthread_key_delete(env->me_txkey);
2287 munmap(env->me_map, env->me_mapsize);
2292 pid_t pid = getpid();
2294 for (i=0; i<env->me_txns->mti_numreaders; i++)
2295 if (env->me_txns->mti_readers[i].mr_pid == pid)
2296 env->me_txns->mti_readers[i].mr_pid = 0;
2297 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2303 /* only for aligned ints */
2305 intcmp(const MDB_val *a, const MDB_val *b)
2307 if (a->mv_size == sizeof(long))
2309 unsigned long *la, *lb;
2314 unsigned int *ia, *ib;
2321 /* ints must always be the same size */
2323 cintcmp(const MDB_val *a, const MDB_val *b)
2325 #if __BYTE_ORDER == __LITTLE_ENDIAN
2326 unsigned short *u, *c;
2329 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2330 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2333 } while(!x && u > (unsigned short *)a->mv_data);
2336 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2341 memncmp(const MDB_val *a, const MDB_val *b)
2347 len_diff = a->mv_size - b->mv_size;
2350 diff = memcmp(a->mv_data, b->mv_data, len);
2351 return diff ? diff : len_diff;
2355 memnrcmp(const MDB_val *a, const MDB_val *b)
2357 const unsigned char *p1, *p2, *p1_lim;
2360 if (b->mv_size == 0)
2361 return a->mv_size != 0;
2362 if (a->mv_size == 0)
2365 p1 = (const unsigned char *)a->mv_data + a->mv_size - 1;
2366 p2 = (const unsigned char *)b->mv_data + b->mv_size - 1;
2368 len_diff = a->mv_size - b->mv_size;
2370 p1_lim = p1 - a->mv_size;
2372 p1_lim = p1 - b->mv_size;
2374 while (p1 > p1_lim) {
2384 /* Search for key within a leaf page, using binary search.
2385 * Returns the smallest entry larger or equal to the key.
2386 * If exactp is non-null, stores whether the found entry was an exact match
2387 * in *exactp (1 or 0).
2388 * If kip is non-null, stores the index of the found entry in *kip.
2389 * If no entry larger or equal to the key is found, returns NULL.
2392 mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp)
2394 unsigned int i = 0, nkeys;
2397 MDB_page *mp = mc->mc_pg[mc->mc_top];
2398 MDB_node *node = NULL;
2403 nkeys = NUMKEYS(mp);
2405 DPRINTF("searching %u keys in %s page %lu",
2406 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2411 low = IS_LEAF(mp) ? 0 : 1;
2413 cmp = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp;
2415 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2416 node = NODEPTR(mp, 0); /* fake */
2418 while (low <= high) {
2419 i = (low + high) >> 1;
2422 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2424 node = NODEPTR(mp, i);
2426 nodekey.mv_size = node->mn_ksize;
2427 nodekey.mv_data = NODEKEY(node);
2430 rc = cmp(key, &nodekey);
2434 DPRINTF("found leaf index %u [%s], rc = %i",
2435 i, DKEY(&nodekey), rc);
2437 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2438 i, DKEY(&nodekey), NODEPGNO(node), rc);
2449 if (rc > 0) { /* Found entry is less than the key. */
2450 i++; /* Skip to get the smallest entry larger than key. */
2452 node = NODEPTR(mp, i);
2455 *exactp = (rc == 0);
2456 /* store the key index */
2457 mc->mc_ki[mc->mc_top] = i;
2459 /* There is no entry larger or equal to the key. */
2462 /* nodeptr is fake for LEAF2 */
2467 cursor_pop_page(MDB_cursor *mc)
2472 top = mc->mc_pg[mc->mc_top];
2477 DPRINTF("popped page %lu off db %u cursor %p", top->mp_pgno,
2478 mc->mc_dbi, (void *) mc);
2483 cursor_push_page(MDB_cursor *mc, MDB_page *mp)
2485 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2486 mc->mc_dbi, (void *) mc);
2488 if (mc->mc_snum >= CURSOR_STACK)
2491 mc->mc_top = mc->mc_snum++;
2492 mc->mc_pg[mc->mc_top] = mp;
2493 mc->mc_ki[mc->mc_top] = 0;
2499 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2503 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2505 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2506 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2507 p = txn->mt_u.dirty_list[x].mptr;
2511 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2512 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2516 DPRINTF("page %lu not found", pgno);
2519 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2523 mdb_search_page_root(MDB_cursor *mc, MDB_val *key, int modify)
2525 MDB_page *mp = mc->mc_pg[mc->mc_top];
2530 while (IS_BRANCH(mp)) {
2533 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2534 assert(NUMKEYS(mp) > 1);
2535 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2537 if (key == NULL) /* Initialize cursor to first page. */
2538 mc->mc_ki[mc->mc_top] = 0;
2539 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2540 /* cursor to last page */
2541 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
2544 node = mdb_search_node(mc, key, &exact);
2546 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2548 assert(mc->mc_ki[mc->mc_top] > 0);
2549 mc->mc_ki[mc->mc_top]--;
2554 DPRINTF("following index %u for key [%s]",
2555 mc->mc_ki[mc->mc_top], DKEY(key));
2556 assert(mc->mc_ki[mc->mc_top] < NUMKEYS(mp));
2557 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2559 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mp)))
2562 if ((rc = cursor_push_page(mc, mp)))
2566 if ((rc = mdb_touch(mc)) != 0)
2568 mp = mc->mc_pg[mc->mc_top];
2573 DPRINTF("internal error, index points to a %02X page!?",
2575 return MDB_CORRUPTED;
2578 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2579 key ? DKEY(key) : NULL);
2584 /* Search for the page a given key should be in.
2585 * Pushes parent pages on the cursor stack.
2586 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2587 * If modify is true, visited pages are updated with new page numbers.
2590 mdb_search_page(MDB_cursor *mc, MDB_val *key, int modify)
2595 /* Make sure the txn is still viable, then find the root from
2596 * the txn's db table.
2598 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2599 DPUTS("transaction has failed, must abort");
2602 root = mc->mc_txn->mt_dbs[mc->mc_dbi].md_root;
2604 if (root == P_INVALID) { /* Tree is empty. */
2605 DPUTS("tree is empty");
2606 return MDB_NOTFOUND;
2609 if ((rc = mdb_get_page(mc->mc_txn, root, &mc->mc_pg[0])))
2615 DPRINTF("db %u root page %lu has flags 0x%X",
2616 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2619 /* For sub-databases, update main root first */
2620 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2622 mc2.mc_txn = mc->mc_txn;
2623 mc2.mc_dbi = MAIN_DBI;
2624 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
2627 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2629 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2630 if ((rc = mdb_touch(mc)))
2632 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mc->mc_pg[0]->mp_pgno;
2636 return mdb_search_page_root(mc, key, modify);
2640 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2642 MDB_page *omp; /* overflow mpage */
2646 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2647 data->mv_size = NODEDSZ(leaf);
2648 data->mv_data = NODEDATA(leaf);
2652 /* Read overflow data.
2654 data->mv_size = NODEDSZ(leaf);
2655 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2656 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2657 DPRINTF("read overflow page %lu failed", pgno);
2660 data->mv_data = METADATA(omp);
2666 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2667 MDB_val *key, MDB_val *data)
2676 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2678 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2681 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2688 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2689 mc.mc_xcursor = &mx;
2690 mdb_xcursor_init0(&mc);
2692 mc.mc_xcursor = NULL;
2694 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2698 mdb_sibling(MDB_cursor *mc, int move_right)
2705 if (mc->mc_snum < 2) {
2706 return MDB_NOTFOUND; /* root has no siblings */
2708 ptop = mc->mc_top-1;
2710 DPRINTF("parent page is page %lu, index %u",
2711 mc->mc_pg[ptop]->mp_pgno, mc->mc_ki[ptop]);
2713 cursor_pop_page(mc);
2714 if (move_right ? (mc->mc_ki[ptop] + 1u >= NUMKEYS(mc->mc_pg[ptop]))
2715 : (mc->mc_ki[ptop] == 0)) {
2716 DPRINTF("no more keys left, moving to %s sibling",
2717 move_right ? "right" : "left");
2718 if ((rc = mdb_sibling(mc, move_right)) != MDB_SUCCESS)
2725 DPRINTF("just moving to %s index key %u",
2726 move_right ? "right" : "left", mc->mc_ki[ptop]);
2728 assert(IS_BRANCH(mc->mc_pg[ptop]));
2730 indx = NODEPTR(mc->mc_pg[ptop], mc->mc_ki[ptop]);
2731 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(indx), &mp)))
2734 cursor_push_page(mc, mp);
2740 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2746 if (mc->mc_flags & C_EOF) {
2747 return MDB_NOTFOUND;
2750 assert(mc->mc_flags & C_INITIALIZED);
2752 mp = mc->mc_pg[mc->mc_top];
2754 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2755 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2756 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2757 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2758 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2759 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2763 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2764 if (op == MDB_NEXT_DUP)
2765 return MDB_NOTFOUND;
2769 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) mc);
2771 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2772 DPUTS("=====> move to next sibling page");
2773 if (mdb_sibling(mc, 1) != MDB_SUCCESS) {
2774 mc->mc_flags |= C_EOF;
2775 return MDB_NOTFOUND;
2777 mp = mc->mc_pg[mc->mc_top];
2778 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2780 mc->mc_ki[mc->mc_top]++;
2782 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2783 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2786 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2787 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2791 assert(IS_LEAF(mp));
2792 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2794 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2795 mdb_xcursor_init1(mc, leaf);
2798 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2801 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2802 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2803 if (rc != MDB_SUCCESS)
2808 MDB_SET_KEY(leaf, key);
2813 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2819 assert(mc->mc_flags & C_INITIALIZED);
2821 mp = mc->mc_pg[mc->mc_top];
2823 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2824 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2825 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2826 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2827 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2828 if (op != MDB_PREV || rc == MDB_SUCCESS)
2831 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2832 if (op == MDB_PREV_DUP)
2833 return MDB_NOTFOUND;
2838 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) mc);
2840 if (mc->mc_ki[mc->mc_top] == 0) {
2841 DPUTS("=====> move to prev sibling page");
2842 if (mdb_sibling(mc, 0) != MDB_SUCCESS) {
2843 mc->mc_flags &= ~C_INITIALIZED;
2844 return MDB_NOTFOUND;
2846 mp = mc->mc_pg[mc->mc_top];
2847 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2848 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2850 mc->mc_ki[mc->mc_top]--;
2852 mc->mc_flags &= ~C_EOF;
2854 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2855 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2858 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2859 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2863 assert(IS_LEAF(mp));
2864 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2866 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2867 mdb_xcursor_init1(mc, leaf);
2870 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2873 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2874 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
2875 if (rc != MDB_SUCCESS)
2880 MDB_SET_KEY(leaf, key);
2885 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2886 MDB_cursor_op op, int *exactp)
2894 assert(key->mv_size > 0);
2896 /* See if we're already on the right page */
2897 if (mc->mc_flags & C_INITIALIZED) {
2900 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2901 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2902 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, nodekey.mv_size);
2904 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2905 MDB_SET_KEY(leaf, &nodekey);
2907 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2909 /* Probably happens rarely, but first node on the page
2910 * was the one we wanted.
2912 mc->mc_ki[mc->mc_top] = 0;
2916 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2921 if (NUMKEYS(mc->mc_pg[mc->mc_top]) > 1) {
2922 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2923 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top],
2924 NUMKEYS(mc->mc_pg[mc->mc_top])-1, nodekey.mv_size);
2926 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
2927 MDB_SET_KEY(leaf, &nodekey);
2929 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2931 /* last node was the one we wanted */
2932 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top])-1;
2936 /* This is definitely the right page, skip search_page */
2941 /* If any parents have right-sibs, search.
2942 * Otherwise, there's nothing further.
2944 for (i=0; i<mc->mc_top; i++)
2946 NUMKEYS(mc->mc_pg[i])-1)
2948 if (i == mc->mc_top) {
2949 /* There are no other pages */
2950 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
2951 return MDB_NOTFOUND;
2956 rc = mdb_search_page(mc, key, 0);
2957 if (rc != MDB_SUCCESS)
2960 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2963 leaf = mdb_search_node(mc, key, exactp);
2964 if (exactp != NULL && !*exactp) {
2965 /* MDB_SET specified and not an exact match. */
2966 return MDB_NOTFOUND;
2970 DPUTS("===> inexact leaf not found, goto sibling");
2971 if ((rc = mdb_sibling(mc, 1)) != MDB_SUCCESS)
2972 return rc; /* no entries matched */
2973 mc->mc_ki[mc->mc_top] = 0;
2974 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2975 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2979 mc->mc_flags |= C_INITIALIZED;
2980 mc->mc_flags &= ~C_EOF;
2982 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
2983 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2984 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
2988 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2989 mdb_xcursor_init1(mc, leaf);
2992 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2993 if (op == MDB_SET || op == MDB_SET_RANGE) {
2994 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2997 if (op == MDB_GET_BOTH) {
3003 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3004 if (rc != MDB_SUCCESS)
3007 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3009 if ((rc = mdb_read_data(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3011 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dcmp(data, &d2);
3013 if (op == MDB_GET_BOTH || rc > 0)
3014 return MDB_NOTFOUND;
3018 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3023 /* The key already matches in all other cases */
3024 if (op == MDB_SET_RANGE)
3025 MDB_SET_KEY(leaf, key);
3026 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3032 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3037 rc = mdb_search_page(mc, NULL, 0);
3038 if (rc != MDB_SUCCESS)
3040 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3042 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3043 mc->mc_flags |= C_INITIALIZED;
3044 mc->mc_flags &= ~C_EOF;
3046 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3047 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3048 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3053 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3054 mdb_xcursor_init1(mc, leaf);
3055 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3060 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3061 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3065 MDB_SET_KEY(leaf, key);
3070 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3076 lkey.mv_size = MAXKEYSIZE+1;
3077 lkey.mv_data = NULL;
3079 rc = mdb_search_page(mc, &lkey, 0);
3080 if (rc != MDB_SUCCESS)
3082 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3084 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3085 mc->mc_flags |= C_INITIALIZED;
3086 mc->mc_flags &= ~C_EOF;
3088 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3090 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3091 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3092 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3097 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3098 mdb_xcursor_init1(mc, leaf);
3099 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3103 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3108 MDB_SET_KEY(leaf, key);
3113 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3123 case MDB_GET_BOTH_RANGE:
3124 if (data == NULL || mc->mc_xcursor == NULL) {
3131 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3133 } else if (op == MDB_SET_RANGE)
3134 rc = mdb_cursor_set(mc, key, data, op, NULL);
3136 rc = mdb_cursor_set(mc, key, data, op, &exact);
3138 case MDB_GET_MULTIPLE:
3140 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) ||
3141 !(mc->mc_flags & C_INITIALIZED)) {
3146 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3147 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3150 case MDB_NEXT_MULTIPLE:
3152 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED)) {
3156 if (!(mc->mc_flags & C_INITIALIZED))
3157 rc = mdb_cursor_first(mc, key, data);
3159 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3160 if (rc == MDB_SUCCESS) {
3161 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3164 mx = &mc->mc_xcursor->mx_cursor;
3165 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3166 mx->mc_txn->mt_dbs[mx->mc_dbi].md_pad;
3167 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3168 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3176 case MDB_NEXT_NODUP:
3177 if (!(mc->mc_flags & C_INITIALIZED))
3178 rc = mdb_cursor_first(mc, key, data);
3180 rc = mdb_cursor_next(mc, key, data, op);
3184 case MDB_PREV_NODUP:
3185 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3186 rc = mdb_cursor_last(mc, key, data);
3188 rc = mdb_cursor_prev(mc, key, data, op);
3191 rc = mdb_cursor_first(mc, key, data);
3195 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3196 !(mc->mc_flags & C_INITIALIZED) ||
3197 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3201 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3204 rc = mdb_cursor_last(mc, key, data);
3208 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3209 !(mc->mc_flags & C_INITIALIZED) ||
3210 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3214 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3217 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3226 mdb_cursor_touch(MDB_cursor *mc)
3230 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
3232 mc2.mc_txn = mc->mc_txn;
3233 mc2.mc_dbi = MAIN_DBI;
3234 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
3236 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3238 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3239 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3243 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root =
3244 mc->mc_pg[mc->mc_top]->mp_pgno;
3248 mc->mc_top = mc->mc_snum-1;
3253 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3257 MDB_val xdata, *rdata, dkey;
3259 char dbuf[PAGESIZE];
3265 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3268 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3269 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3273 if (flags == MDB_CURRENT) {
3274 if (!(mc->mc_flags & C_INITIALIZED))
3277 } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
3279 /* new database, write a root leaf page */
3280 DPUTS("allocating new root leaf page");
3281 if ((np = mdb_new_page(mc, P_LEAF, 1)) == NULL) {
3285 cursor_push_page(mc, np);
3286 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = np->mp_pgno;
3287 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
3288 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3289 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3291 np->mp_flags |= P_LEAF2;
3292 mc->mc_flags |= C_INITIALIZED;
3298 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3299 if (flags == MDB_NOOVERWRITE && rc == 0) {
3300 DPRINTF("duplicate key [%s]", DKEY(key));
3302 return MDB_KEYEXIST;
3304 if (rc && rc != MDB_NOTFOUND)
3308 /* Cursor is positioned, now make sure all pages are writable */
3309 rc2 = mdb_cursor_touch(mc);
3310 if (rc2) return rc2;
3313 /* The key already exists */
3314 if (rc == MDB_SUCCESS) {
3315 /* there's only a key anyway, so this is a no-op */
3316 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3317 unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3318 if (key->mv_size != ksize)
3320 if (flags == MDB_CURRENT) {
3321 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3322 memcpy(ptr, key->mv_data, ksize);
3327 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3330 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
3331 /* Was a single item before, must convert now */
3332 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3333 dkey.mv_size = NODEDSZ(leaf);
3334 dkey.mv_data = dbuf;
3335 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3336 /* data matches, ignore it */
3337 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
3338 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3339 memset(&dummy, 0, sizeof(dummy));
3340 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
3341 dummy.md_pad = data->mv_size;
3342 dummy.md_flags = MDB_DUPFIXED;
3343 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
3344 dummy.md_flags |= MDB_INTEGERKEY;
3346 dummy.md_root = P_INVALID;
3347 if (dkey.mv_size == sizeof(MDB_db)) {
3348 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3351 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3354 xdata.mv_size = sizeof(MDB_db);
3355 xdata.mv_data = &dummy;
3356 /* new sub-DB, must fully init xcursor */
3357 if (flags == MDB_CURRENT)
3363 /* same size, just replace it */
3364 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3365 NODEDSZ(leaf) == data->mv_size) {
3366 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3369 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3371 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3377 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3378 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3379 rc = mdb_split(mc, key, rdata, P_INVALID);
3381 /* There is room already in this leaf page. */
3382 rc = mdb_add_node(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3385 if (rc != MDB_SUCCESS)
3386 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3388 /* Remember if we just added a subdatabase */
3389 if (flags & F_SUBDATA) {
3390 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3391 leaf->mn_flags |= F_SUBDATA;
3394 /* Now store the actual data in the child DB. Note that we're
3395 * storing the user data in the keys field, so there are strict
3396 * size limits on dupdata. The actual data fields of the child
3397 * DB are all zero size.
3400 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3402 if (flags == MDB_CURRENT)
3403 mdb_xcursor_init2(mc);
3405 mdb_xcursor_init1(mc, leaf);
3408 if (flags == MDB_NODUPDATA)
3409 flags = MDB_NOOVERWRITE;
3410 /* converted, write the original data first */
3412 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3414 leaf->mn_flags |= F_DUPDATA;
3416 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3417 mdb_xcursor_fini(mc);
3418 memcpy(NODEDATA(leaf),
3419 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3422 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3429 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3434 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3437 if (!mc->mc_flags & C_INITIALIZED)
3440 rc = mdb_cursor_touch(mc);
3443 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3445 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3446 if (flags != MDB_NODUPDATA) {
3447 mdb_xcursor_init2(mc);
3448 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3449 mdb_xcursor_fini(mc);
3450 /* If sub-DB still has entries, we're done */
3451 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3453 memcpy(NODEDATA(leaf),
3454 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3456 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3459 /* otherwise fall thru and delete the sub-DB */
3462 /* add all the child DB's pages to the free list */
3463 rc = mdb_search_page(&mc->mc_xcursor->mx_cursor, NULL, 0);
3464 if (rc == MDB_SUCCESS) {
3469 mx = &mc->mc_xcursor->mx_cursor;
3470 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3471 mx->mc_txn->mt_dbs[mx->mc_dbi].md_entries;
3473 cursor_pop_page(mx);
3475 while (mx->mc_snum > 1) {
3476 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3478 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3481 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3483 rc = mdb_sibling(mx, 1);
3488 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3489 mx->mc_txn->mt_dbs[mx->mc_dbi].md_root);
3493 return mdb_del0(mc, leaf);
3496 /* Allocate a page and initialize it
3499 mdb_new_page(MDB_cursor *mc, uint32_t flags, int num)
3503 if ((np = mdb_alloc_page(mc, num)) == NULL)
3505 DPRINTF("allocated new mpage %lu, page size %u",
3506 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3507 np->mp_flags = flags | P_DIRTY;
3508 np->mp_lower = PAGEHDRSZ;
3509 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3512 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages++;
3513 else if (IS_LEAF(np))
3514 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages++;
3515 else if (IS_OVERFLOW(np)) {
3516 mc->mc_txn->mt_dbs[mc->mc_dbi].md_overflow_pages += num;
3524 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3528 sz = LEAFSIZE(key, data);
3529 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3530 /* put on overflow page */
3531 sz -= data->mv_size - sizeof(pgno_t);
3535 return sz + sizeof(indx_t);
3539 mdb_branch_size(MDB_env *env, MDB_val *key)
3544 if (sz >= env->me_psize / MDB_MINKEYS) {
3545 /* put on overflow page */
3546 /* not implemented */
3547 /* sz -= key->size - sizeof(pgno_t); */
3550 return sz + sizeof(indx_t);
3554 mdb_add_node(MDB_cursor *mc, indx_t indx,
3555 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3558 size_t node_size = NODESIZE;
3561 MDB_page *mp = mc->mc_pg[mc->mc_top];
3562 MDB_page *ofp = NULL; /* overflow page */
3565 assert(mp->mp_upper >= mp->mp_lower);
3567 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
3568 IS_LEAF(mp) ? "leaf" : "branch",
3569 mp->mp_pgno, indx, data ? data->mv_size : 0,
3570 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3573 /* Move higher keys up one slot. */
3574 int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad, dif;
3575 char *ptr = LEAF2KEY(mp, indx, ksize);
3576 dif = NUMKEYS(mp) - indx;
3578 memmove(ptr+ksize, ptr, dif*ksize);
3579 /* insert new key */
3580 memcpy(ptr, key->mv_data, ksize);
3582 /* Just using these for counting */
3583 mp->mp_lower += sizeof(indx_t);
3584 mp->mp_upper -= ksize - sizeof(indx_t);
3589 node_size += key->mv_size;
3593 if (F_ISSET(flags, F_BIGDATA)) {
3594 /* Data already on overflow page. */
3595 node_size += sizeof(pgno_t);
3596 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3597 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3598 /* Put data on overflow page. */
3599 DPRINTF("data size is %zu, put on overflow page",
3601 node_size += sizeof(pgno_t);
3602 if ((ofp = mdb_new_page(mc, P_OVERFLOW, ovpages)) == NULL)
3604 DPRINTF("allocated overflow page %lu", ofp->mp_pgno);
3607 node_size += data->mv_size;
3610 node_size += node_size & 1;
3612 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3613 DPRINTF("not enough room in page %lu, got %u ptrs",
3614 mp->mp_pgno, NUMKEYS(mp));
3615 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3616 mp->mp_upper - mp->mp_lower);
3617 DPRINTF("node size = %zu", node_size);
3621 /* Move higher pointers up one slot. */
3622 for (i = NUMKEYS(mp); i > indx; i--)
3623 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3625 /* Adjust free space offsets. */
3626 ofs = mp->mp_upper - node_size;
3627 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3628 mp->mp_ptrs[indx] = ofs;
3630 mp->mp_lower += sizeof(indx_t);
3632 /* Write the node data. */
3633 node = NODEPTR(mp, indx);
3634 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3635 node->mn_flags = flags;
3637 SETDSZ(node,data->mv_size);
3642 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3647 if (F_ISSET(flags, F_BIGDATA))
3648 memcpy(node->mn_data + key->mv_size, data->mv_data,
3651 memcpy(node->mn_data + key->mv_size, data->mv_data,
3654 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3656 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3664 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3667 indx_t i, j, numkeys, ptr;
3671 DPRINTF("delete node %u on %s page %lu", indx,
3672 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3673 assert(indx < NUMKEYS(mp));
3676 int x = NUMKEYS(mp) - 1 - indx;
3677 base = LEAF2KEY(mp, indx, ksize);
3679 memmove(base, base + ksize, x * ksize);
3680 mp->mp_lower -= sizeof(indx_t);
3681 mp->mp_upper += ksize - sizeof(indx_t);
3685 node = NODEPTR(mp, indx);
3686 sz = NODESIZE + node->mn_ksize;
3688 if (F_ISSET(node->mn_flags, F_BIGDATA))
3689 sz += sizeof(pgno_t);
3691 sz += NODEDSZ(node);
3695 ptr = mp->mp_ptrs[indx];
3696 numkeys = NUMKEYS(mp);
3697 for (i = j = 0; i < numkeys; i++) {
3699 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3700 if (mp->mp_ptrs[i] < ptr)
3701 mp->mp_ptrs[j] += sz;
3706 base = (char *)mp + mp->mp_upper;
3707 memmove(base + sz, base, ptr - mp->mp_upper);
3709 mp->mp_lower -= sizeof(indx_t);
3714 mdb_xcursor_init0(MDB_cursor *mc)
3716 MDB_xcursor *mx = mc->mc_xcursor;
3719 mx->mx_txn = *mc->mc_txn;
3720 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3721 mx->mx_txn.mt_dbs = mx->mx_dbs;
3722 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3723 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3724 if (mc->mc_dbi > 1) {
3725 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3730 mx->mx_dbxs[dbn+1].md_parent = dbn;
3731 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3732 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3733 mx->mx_dbxs[dbn+1].md_dirty = 0;
3734 mx->mx_txn.mt_numdbs = dbn+2;
3735 mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3737 mx->mx_cursor.mc_xcursor = NULL;
3738 mx->mx_cursor.mc_txn = &mx->mx_txn;
3739 mx->mx_cursor.mc_dbi = dbn+1;
3743 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
3745 MDB_db *db = NODEDATA(node);
3746 MDB_xcursor *mx = mc->mc_xcursor;
3748 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3749 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3750 if (mc->mc_dbi > 1) {
3751 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3752 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3757 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi, db->md_root);
3758 mx->mx_dbs[dbn] = *db;
3759 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
3760 mx->mx_dbxs[dbn].md_dirty = 1;
3761 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3762 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3763 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3764 mx->mx_cursor.mc_snum = 0;
3765 mx->mx_cursor.mc_flags = 0;
3769 mdb_xcursor_init2(MDB_cursor *mc)
3771 MDB_xcursor *mx = mc->mc_xcursor;
3773 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3774 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3775 if (mc->mc_dbi > 1) {
3776 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3777 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3782 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi,
3783 mx->mx_dbs[dbn].md_root);
3784 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3788 mdb_xcursor_fini(MDB_cursor *mc)
3790 MDB_xcursor *mx = mc->mc_xcursor;
3791 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3792 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3793 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3794 if (mc->mc_dbi > 1) {
3795 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3796 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3801 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3804 size_t size = sizeof(MDB_cursor);
3806 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3809 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3810 size += sizeof(MDB_xcursor);
3812 if ((mc = calloc(1, size)) != NULL) {
3815 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3816 MDB_xcursor *mx = (MDB_xcursor *)(mc + 1);
3817 mc->mc_xcursor = mx;
3818 mdb_xcursor_init0(mc);
3829 /* Return the count of duplicate data items for the current key */
3831 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3835 if (mc == NULL || countp == NULL)
3838 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3841 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3842 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3845 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3848 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3854 mdb_cursor_close(MDB_cursor *mc)
3862 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3864 indx_t ptr, i, numkeys;
3871 node = NODEPTR(mp, indx);
3872 ptr = mp->mp_ptrs[indx];
3873 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3875 (int)node->mn_ksize, (char *)NODEKEY(node),
3879 delta = key->mv_size - node->mn_ksize;
3881 if (delta > 0 && SIZELEFT(mp) < delta) {
3882 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3886 numkeys = NUMKEYS(mp);
3887 for (i = 0; i < numkeys; i++) {
3888 if (mp->mp_ptrs[i] <= ptr)
3889 mp->mp_ptrs[i] -= delta;
3892 base = (char *)mp + mp->mp_upper;
3893 len = ptr - mp->mp_upper + NODESIZE;
3894 memmove(base - delta, base, len);
3895 mp->mp_upper -= delta;
3897 node = NODEPTR(mp, indx);
3898 node->mn_ksize = key->mv_size;
3901 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3906 /* Move a node from csrc to cdst.
3909 mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst)
3916 /* Mark src and dst as dirty. */
3917 if ((rc = mdb_touch(csrc)) ||
3918 (rc = mdb_touch(cdst)))
3921 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3922 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
3923 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
3924 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3926 data.mv_data = NULL;
3928 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3929 unsigned int snum = csrc->mc_snum;
3930 /* must find the lowest key below src */
3931 mdb_search_page_root(csrc, NULL, 0);
3932 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
3933 csrc->mc_snum = snum--;
3934 csrc->mc_top = snum;
3936 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3938 key.mv_size = NODEKSZ(srcnode);
3939 key.mv_data = NODEKEY(srcnode);
3940 data.mv_size = NODEDSZ(srcnode);
3941 data.mv_data = NODEDATA(srcnode);
3943 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3944 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
3945 csrc->mc_ki[csrc->mc_top],
3947 csrc->mc_pg[csrc->mc_top]->mp_pgno,
3948 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
3950 /* Add the node to the destination page.
3952 rc = mdb_add_node(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
3954 if (rc != MDB_SUCCESS)
3957 /* Delete the node from the source page.
3959 mdb_del_node(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3961 /* Update the parent separators.
3963 if (csrc->mc_ki[csrc->mc_top] == 0) {
3964 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
3965 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3966 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3968 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3969 key.mv_size = NODEKSZ(srcnode);
3970 key.mv_data = NODEKEY(srcnode);
3972 DPRINTF("update separator for source page %lu to [%s]",
3973 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
3974 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
3975 &key)) != MDB_SUCCESS)
3978 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3980 nullkey.mv_size = 0;
3981 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
3985 if (cdst->mc_ki[cdst->mc_top] == 0) {
3986 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
3987 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3988 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
3990 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
3991 key.mv_size = NODEKSZ(srcnode);
3992 key.mv_data = NODEKEY(srcnode);
3994 DPRINTF("update separator for destination page %lu to [%s]",
3995 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
3996 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
3997 &key)) != MDB_SUCCESS)
4000 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4002 nullkey.mv_size = 0;
4003 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4011 mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4018 DPRINTF("merging page %lu into %lu", csrc->mc_pg[csrc->mc_top]->mp_pgno, cdst->mc_pg[cdst->mc_top]->mp_pgno);
4020 assert(csrc->mc_snum > 1); /* can't merge root page */
4021 assert(cdst->mc_snum > 1);
4023 /* Mark dst as dirty. */
4024 if ((rc = mdb_touch(cdst)))
4027 /* Move all nodes from src to dst.
4029 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4030 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4031 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
4032 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4033 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4034 rc = mdb_add_node(cdst, j, &key, NULL, 0, 0);
4035 if (rc != MDB_SUCCESS)
4037 key.mv_data = (char *)key.mv_data + key.mv_size;
4040 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4041 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4043 key.mv_size = srcnode->mn_ksize;
4044 key.mv_data = NODEKEY(srcnode);
4045 data.mv_size = NODEDSZ(srcnode);
4046 data.mv_data = NODEDATA(srcnode);
4047 rc = mdb_add_node(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4048 if (rc != MDB_SUCCESS)
4053 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
4054 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);
4056 /* Unlink the src page from parent and add to free list.
4058 mdb_del_node(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4059 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4061 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4065 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4066 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4067 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_leaf_pages--;
4069 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_branch_pages--;
4070 cursor_pop_page(csrc);
4072 return mdb_rebalance(csrc);
4076 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4080 cdst->mc_txn = csrc->mc_txn;
4081 cdst->mc_dbi = csrc->mc_dbi;
4082 cdst->mc_snum = csrc->mc_snum;
4083 cdst->mc_top = csrc->mc_top;
4084 cdst->mc_flags = csrc->mc_flags;
4086 for (i=0; i<csrc->mc_snum; i++) {
4087 cdst->mc_pg[i] = csrc->mc_pg[i];
4088 cdst->mc_ki[i] = csrc->mc_ki[i];
4093 mdb_rebalance(MDB_cursor *mc)
4101 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
4102 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4103 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);
4105 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4106 DPRINTF("no need to rebalance page %lu, above fill threshold",
4107 mc->mc_pg[mc->mc_top]->mp_pgno);
4111 if (mc->mc_snum < 2) {
4112 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4113 DPUTS("tree is completely empty");
4114 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = P_INVALID;
4115 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth = 0;
4116 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages = 0;
4117 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4118 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4119 DPUTS("collapsing root page!");
4120 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4121 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4122 if ((rc = mdb_get_page(mc->mc_txn, mc->mc_txn->mt_dbs[mc->mc_dbi].md_root, &root)))
4124 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4125 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages--;
4127 DPUTS("root page doesn't need rebalancing");
4131 /* The parent (branch page) must have at least 2 pointers,
4132 * otherwise the tree is invalid.
4134 ptop = mc->mc_top-1;
4135 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4137 /* Leaf page fill factor is below the threshold.
4138 * Try to move keys from left or right neighbor, or
4139 * merge with a neighbor page.
4144 mdb_cursor_copy(mc, &mn);
4145 mn.mc_xcursor = NULL;
4147 if (mc->mc_ki[ptop] == 0) {
4148 /* We're the leftmost leaf in our parent.
4150 DPUTS("reading right neighbor");
4152 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4153 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4155 mn.mc_ki[mn.mc_top] = 0;
4156 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4158 /* There is at least one neighbor to the left.
4160 DPUTS("reading left neighbor");
4162 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4163 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4165 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4166 mc->mc_ki[mc->mc_top] = 0;
4169 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
4170 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);
4172 /* If the neighbor page is above threshold and has at least two
4173 * keys, move one key from it.
4175 * Otherwise we should try to merge them.
4177 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4178 return mdb_move_node(&mn, mc);
4179 else { /* FIXME: if (has_enough_room()) */
4180 if (mc->mc_ki[ptop] == 0)
4181 return mdb_merge(&mn, mc);
4183 return mdb_merge(mc, &mn);
4188 mdb_del0(MDB_cursor *mc, MDB_node *leaf)
4192 /* add overflow pages to free list */
4193 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4197 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4198 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4199 for (i=0; i<ovpages; i++) {
4200 DPRINTF("freed ov page %lu", pg);
4201 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4205 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);
4206 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
4207 rc = mdb_rebalance(mc);
4208 if (rc != MDB_SUCCESS)
4209 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4215 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4216 MDB_val *key, MDB_val *data)
4221 MDB_val rdata, *xdata;
4225 assert(key != NULL);
4227 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4229 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4232 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4236 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4243 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4244 mc.mc_xcursor = &mx;
4245 mdb_xcursor_init0(&mc);
4247 mc.mc_xcursor = NULL;
4259 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4261 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4265 /* Split page <mc->top>, and insert <key,(data|newpgno)> in either left or
4266 * right sibling, at index <mc->ki> (as if unsplit). Updates mc->top and
4267 * mc->ki with the actual values after split, ie if mc->top and mc->ki
4268 * refer to a node in the new right sibling page.
4271 mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4274 int rc = MDB_SUCCESS, ins_new = 0;
4277 unsigned int i, j, split_indx, nkeys, pmax;
4279 MDB_val sepkey, rkey, rdata;
4281 MDB_page *mp, *rp, *pp;
4286 mp = mc->mc_pg[mc->mc_top];
4287 newindx = mc->mc_ki[mc->mc_top];
4289 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
4290 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4291 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4293 if (mc->mc_snum < 2) {
4294 if ((pp = mdb_new_page(mc, P_BRANCH, 1)) == NULL)
4296 /* shift current top to make room for new parent */
4297 mc->mc_pg[1] = mc->mc_pg[0];
4298 mc->mc_ki[1] = mc->mc_ki[0];
4301 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = pp->mp_pgno;
4302 DPRINTF("root split! new root = %lu", pp->mp_pgno);
4303 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
4305 /* Add left (implicit) pointer. */
4306 if ((rc = mdb_add_node(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4307 /* undo the pre-push */
4308 mc->mc_pg[0] = mc->mc_pg[1];
4309 mc->mc_ki[0] = mc->mc_ki[1];
4310 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mp->mp_pgno;
4311 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4318 ptop = mc->mc_top-1;
4319 DPRINTF("parent branch page is %lu", mc->mc_pg[ptop]->mp_pgno);
4322 /* Create a right sibling. */
4323 if ((rp = mdb_new_page(mc, mp->mp_flags, 1)) == NULL)
4325 mdb_cursor_copy(mc, &mn);
4326 mn.mc_pg[mn.mc_top] = rp;
4327 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4328 DPRINTF("new right sibling: page %lu", rp->mp_pgno);
4330 nkeys = NUMKEYS(mp);
4331 split_indx = nkeys / 2 + 1;
4336 unsigned int lsize, rsize, ksize;
4337 /* Move half of the keys to the right sibling */
4339 x = mc->mc_ki[mc->mc_top] - split_indx;
4340 ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
4341 split = LEAF2KEY(mp, split_indx, ksize);
4342 rsize = (nkeys - split_indx) * ksize;
4343 lsize = (nkeys - split_indx) * sizeof(indx_t);
4344 mp->mp_lower -= lsize;
4345 rp->mp_lower += lsize;
4346 mp->mp_upper += rsize - lsize;
4347 rp->mp_upper -= rsize - lsize;
4348 sepkey.mv_size = ksize;
4349 if (newindx == split_indx) {
4350 sepkey.mv_data = newkey->mv_data;
4352 sepkey.mv_data = split;
4355 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4356 memcpy(rp->mp_ptrs, split, rsize);
4357 sepkey.mv_data = rp->mp_ptrs;
4358 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4359 memcpy(ins, newkey->mv_data, ksize);
4360 mp->mp_lower += sizeof(indx_t);
4361 mp->mp_upper -= ksize - sizeof(indx_t);
4364 memcpy(rp->mp_ptrs, split, x * ksize);
4365 ins = LEAF2KEY(rp, x, ksize);
4366 memcpy(ins, newkey->mv_data, ksize);
4367 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4368 rp->mp_lower += sizeof(indx_t);
4369 rp->mp_upper -= ksize - sizeof(indx_t);
4370 mc->mc_ki[mc->mc_top] = x;
4371 mc->mc_pg[mc->mc_top] = rp;
4376 /* For leaf pages, check the split point based on what
4377 * fits where, since otherwise add_node can fail.
4380 unsigned int psize, nsize;
4381 /* Maximum free space in an empty page */
4382 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4383 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4384 if (newindx < split_indx) {
4386 for (i=0; i<split_indx; i++) {
4387 node = NODEPTR(mp, i);
4388 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4389 if (F_ISSET(node->mn_flags, F_BIGDATA))
4390 psize += sizeof(pgno_t);
4392 psize += NODEDSZ(node);
4401 for (i=nkeys-1; i>=split_indx; i--) {
4402 node = NODEPTR(mp, i);
4403 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4404 if (F_ISSET(node->mn_flags, F_BIGDATA))
4405 psize += sizeof(pgno_t);
4407 psize += NODEDSZ(node);
4417 /* First find the separating key between the split pages.
4419 if (newindx == split_indx) {
4420 sepkey.mv_size = newkey->mv_size;
4421 sepkey.mv_data = newkey->mv_data;
4423 node = NODEPTR(mp, split_indx);
4424 sepkey.mv_size = node->mn_ksize;
4425 sepkey.mv_data = NODEKEY(node);
4429 DPRINTF("separator is [%s]", DKEY(&sepkey));
4431 /* Copy separator key to the parent.
4433 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4436 rc = mdb_split(&mn, &sepkey, NULL, rp->mp_pgno);
4438 /* Right page might now have changed parent.
4439 * Check if left page also changed parent.
4441 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4442 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4443 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4444 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4448 rc = mdb_add_node(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4454 if (rc != MDB_SUCCESS) {
4458 /* Move half of the keys to the right sibling. */
4460 /* grab a page to hold a temporary copy */
4461 if (mc->mc_txn->mt_env->me_dpages) {
4462 copy = mc->mc_txn->mt_env->me_dpages;
4463 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4465 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4469 copy->mp_pgno = mp->mp_pgno;
4470 copy->mp_flags = mp->mp_flags;
4471 copy->mp_lower = PAGEHDRSZ;
4472 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4473 mc->mc_pg[mc->mc_top] = copy;
4474 for (i = j = 0; i <= nkeys; j++) {
4475 if (i == split_indx) {
4476 /* Insert in right sibling. */
4477 /* Reset insert index for right sibling. */
4478 j = (i == newindx && ins_new);
4479 mc->mc_pg[mc->mc_top] = rp;
4482 if (i == newindx && !ins_new) {
4483 /* Insert the original entry that caused the split. */
4484 rkey.mv_data = newkey->mv_data;
4485 rkey.mv_size = newkey->mv_size;
4487 rdata.mv_data = newdata->mv_data;
4488 rdata.mv_size = newdata->mv_size;
4495 /* Update page and index for the new key. */
4496 mc->mc_ki[mc->mc_top] = j;
4497 } else if (i == nkeys) {
4500 node = NODEPTR(mp, i);
4501 rkey.mv_data = NODEKEY(node);
4502 rkey.mv_size = node->mn_ksize;
4504 rdata.mv_data = NODEDATA(node);
4505 rdata.mv_size = NODEDSZ(node);
4507 pgno = NODEPGNO(node);
4508 flags = node->mn_flags;
4513 if (!IS_LEAF(mp) && j == 0) {
4514 /* First branch index doesn't need key data. */
4518 rc = mdb_add_node(mc, j, &rkey, &rdata, pgno, flags);
4521 /* reset back to original page */
4522 if (newindx < split_indx)
4523 mc->mc_pg[mc->mc_top] = mp;
4525 nkeys = NUMKEYS(copy);
4526 for (i=0; i<nkeys; i++)
4527 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4528 mp->mp_lower = copy->mp_lower;
4529 mp->mp_upper = copy->mp_upper;
4530 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4531 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4533 /* return tmp page to freelist */
4534 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4535 mc->mc_txn->mt_env->me_dpages = copy;
4540 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4541 MDB_val *key, MDB_val *data, unsigned int flags)
4546 assert(key != NULL);
4547 assert(data != NULL);
4549 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4552 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4556 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4560 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4567 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4568 mc.mc_xcursor = &mx;
4569 mdb_xcursor_init0(&mc);
4571 mc.mc_xcursor = NULL;
4573 return mdb_cursor_put(&mc, key, data, flags);
4577 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4579 /** Only a subset of the @ref mdb_env flags can be changed
4580 * at runtime. Changing other flags requires closing the environment
4581 * and re-opening it with the new flags.
4583 #define CHANGEABLE (MDB_NOSYNC)
4584 if ((flag & CHANGEABLE) != flag)
4587 env->me_flags |= flag;
4589 env->me_flags &= ~flag;
4594 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4599 *arg = env->me_flags;
4604 mdb_env_get_path(MDB_env *env, const char **arg)
4609 *arg = env->me_path;
4614 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4616 arg->ms_psize = env->me_psize;
4617 arg->ms_depth = db->md_depth;
4618 arg->ms_branch_pages = db->md_branch_pages;
4619 arg->ms_leaf_pages = db->md_leaf_pages;
4620 arg->ms_overflow_pages = db->md_overflow_pages;
4621 arg->ms_entries = db->md_entries;
4626 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4630 if (env == NULL || arg == NULL)
4633 mdb_env_read_meta(env, &toggle);
4635 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4639 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4641 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4642 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4643 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4644 txn->mt_dbxs[dbi].md_cmp = cintcmp;
4646 txn->mt_dbxs[dbi].md_cmp = memncmp;
4648 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4649 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4650 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4651 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4653 txn->mt_dbxs[dbi].md_dcmp = cintcmp;
4654 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4655 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4657 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4660 txn->mt_dbxs[dbi].md_dcmp = NULL;
4664 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4671 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4672 mdb_default_cmp(txn, FREE_DBI);
4678 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4679 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4680 mdb_default_cmp(txn, MAIN_DBI);
4684 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4685 mdb_default_cmp(txn, MAIN_DBI);
4688 /* Is the DB already open? */
4690 for (i=2; i<txn->mt_numdbs; i++) {
4691 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4692 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4698 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4701 /* Find the DB info */
4703 key.mv_data = (void *)name;
4704 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4706 /* Create if requested */
4707 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4710 data.mv_size = sizeof(MDB_db);
4711 data.mv_data = &dummy;
4712 memset(&dummy, 0, sizeof(dummy));
4713 dummy.md_root = P_INVALID;
4714 dummy.md_flags = flags & 0xffff;
4716 mc.mc_dbi = MAIN_DBI;
4718 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4722 /* OK, got info, add to table */
4723 if (rc == MDB_SUCCESS) {
4724 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4725 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4726 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4727 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4728 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4729 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4730 *dbi = txn->mt_numdbs;
4731 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4732 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4733 mdb_default_cmp(txn, txn->mt_numdbs);
4740 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4742 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4745 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4748 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4751 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4753 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4754 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4755 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4759 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4761 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4764 txn->mt_dbxs[dbi].md_cmp = cmp;
4768 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4770 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4773 txn->mt_dbxs[dbi].md_dcmp = cmp;
4777 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4779 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4782 txn->mt_dbxs[dbi].md_rel = rel;