2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
66 /** @defgroup internal MDB Internals
69 /** @defgroup compat Windows Compatibility Macros
73 #define pthread_t DWORD
74 #define pthread_mutex_t HANDLE
75 #define pthread_key_t DWORD
76 #define pthread_self() GetCurrentThreadId()
77 #define pthread_key_create(x,y) *(x) = TlsAlloc()
78 #define pthread_key_delete(x) TlsFree(x)
79 #define pthread_getspecific(x) TlsGetValue(x)
80 #define pthread_setspecific(x,y) TlsSetValue(x,y)
81 #define pthread_mutex_unlock(x) ReleaseMutex(x)
82 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
83 #define LOCK_MUTEX_R(env) pthread_mutex_lock(env->me_rmutex)
84 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(env->me_rmutex)
85 #define LOCK_MUTEX_W(env) pthread_mutex_lock(env->me_wmutex)
86 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(env->me_wmutex)
87 #define getpid() GetCurrentProcessId()
88 #define fdatasync(fd) !FlushFileBuffers(fd)
89 #define ErrCode() GetLastError()
90 #define GetPageSize(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
91 #define close(fd) CloseHandle(fd)
92 #define munmap(ptr,len) UnmapViewOfFile(ptr)
94 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&env->me_txns->mti_mutex)
95 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&env->me_txns->mti_mutex)
96 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&env->me_txns->mti_wmutex)
97 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&env->me_txns->mti_wmutex)
98 #define ErrCode() errno
100 #define INVALID_HANDLE_VALUE -1
101 #define GetPageSize(x) (x) = sysconf(_SC_PAGE_SIZE)
107 /* Note: If O_DSYNC is undefined but exists in /usr/include,
108 * preferably set some compiler flag to get the definition.
109 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
112 # define MDB_DSYNC O_DSYNC
116 #define ULONG unsigned long
117 typedef ULONG pgno_t;
123 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
124 # define DPRINTF (void) /* Vararg macros may be unsupported */
126 # define DPRINTF(fmt, ...) /* Requires 2 or more args */ \
127 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
129 # define DPRINTF(fmt, ...) ((void) 0)
131 #define DPUTS(arg) DPRINTF("%s", arg)
133 #define PAGESIZE 4096
134 #define MDB_MINKEYS 2
135 #define MDB_MAGIC 0xBEEFC0DE
136 #define MDB_VERSION 1
137 #define MAXKEYSIZE 511
139 #define KBUF (MAXKEYSIZE*2+1)
140 #define DKBUF char kbuf[KBUF]
141 #define DKEY(x) mdb_dkey(x, kbuf)
147 /* The DB view is always consistent because all writes are wrapped in
148 * the wmutex. Finer-grained locks aren't necessary.
154 #define LAZY_MUTEX_LOCK(x)
155 #define LAZY_MUTEX_UNLOCK(x)
156 #define LAZY_RWLOCK_UNLOCK(x)
157 #define LAZY_RWLOCK_WRLOCK(x)
158 #define LAZY_RWLOCK_RDLOCK(x)
159 #define LAZY_RWLOCK_DEF(x)
160 #define LAZY_RWLOCK_INIT(x,y)
161 #define LAZY_RWLOCK_DESTROY(x)
163 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
164 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
165 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
166 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
167 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
168 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
169 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
170 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
173 #define P_INVALID (~0UL)
175 #define F_ISSET(w, f) (((w) & (f)) == (f))
177 typedef uint16_t indx_t;
179 #define DEFAULT_READERS 126
180 #define DEFAULT_MAPSIZE 1048576
182 /* Lock descriptor stuff */
184 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
187 typedef struct MDB_rxbody {
193 typedef struct MDB_reader {
196 #define mr_txnid mru.mrx.mrb_txnid
197 #define mr_pid mru.mrx.mrb_pid
198 #define mr_tid mru.mrx.mrb_tid
199 /* cache line alignment */
200 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
204 typedef struct MDB_txbody {
206 uint32_t mtb_version;
207 /* For POSIX the actual mutexes reside in shared memory.
208 * On Windows, mutexes are allocated by the kernel; we store
209 * the name in shared memory so that other processes can
215 pthread_mutex_t mtb_mutex;
218 uint32_t mtb_numreaders;
219 uint32_t mtb_me_toggle;
222 typedef struct MDB_txninfo {
225 #define mti_magic mt1.mtb.mtb_magic
226 #define mti_version mt1.mtb.mtb_version
227 #define mti_mutex mt1.mtb.mtb_mutex
228 #define mti_rmname mt1.mtb.mtb_rmname
229 #define mti_txnid mt1.mtb.mtb_txnid
230 #define mti_numreaders mt1.mtb.mtb_numreaders
231 #define mti_me_toggle mt1.mtb.mtb_me_toggle
232 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
237 #define mti_wmname mt2.mt2_wmname
239 pthread_mutex_t mt2_wmutex;
240 #define mti_wmutex mt2.mt2_wmutex
242 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
244 MDB_reader mti_readers[1];
247 /* Common header for all page types. Overflow pages
248 * occupy a number of contiguous pages with no
249 * headers on any page after the first.
251 typedef struct MDB_page { /* represents a page of storage */
252 #define mp_pgno mp_p.p_pgno
254 pgno_t p_pgno; /* page number */
255 void * p_align; /* for IL32P64 */
257 #define P_BRANCH 0x01 /* branch page */
258 #define P_LEAF 0x02 /* leaf page */
259 #define P_OVERFLOW 0x04 /* overflow page */
260 #define P_META 0x08 /* meta page */
261 #define P_DIRTY 0x10 /* dirty page */
262 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
264 #define mp_lower mp_pb.pb.pb_lower
265 #define mp_upper mp_pb.pb.pb_upper
266 #define mp_pages mp_pb.pb_pages
269 indx_t pb_lower; /* lower bound of free space */
270 indx_t pb_upper; /* upper bound of free space */
272 uint32_t pb_pages; /* number of overflow pages */
274 indx_t mp_ptrs[1]; /* dynamic size */
277 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
279 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
280 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
281 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
282 ((env)->me_psize - PAGEHDRSZ))
283 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
284 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
285 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
286 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
288 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
290 typedef struct MDB_db {
291 uint32_t md_pad; /* also ksize for LEAF2 pages */
294 ULONG md_branch_pages;
296 ULONG md_overflow_pages;
304 typedef struct MDB_meta { /* meta (footer) page content */
307 void *mm_address; /* address for fixed mapping */
308 size_t mm_mapsize; /* size of mmap region */
309 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
310 #define mm_psize mm_dbs[0].md_pad
311 #define mm_flags mm_dbs[0].md_flags
312 pgno_t mm_last_pg; /* last used page in file */
313 ULONG mm_txnid; /* txnid that committed this page */
316 typedef struct MDB_dhead { /* a dirty page */
318 unsigned md_pi; /* parent index */
322 typedef struct MDB_dpage {
327 typedef struct MDB_oldpages {
328 struct MDB_oldpages *mo_next;
330 pgno_t mo_pages[1]; /* dynamic */
333 typedef struct MDB_pageparent {
339 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num);
340 static int mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
342 typedef struct MDB_ppage { /* ordered list of pages */
344 unsigned int mp_ki; /* cursor index on page */
347 #define CURSOR_TOP(c) (&(c)->mc_stack[(c)->mc_snum-1])
348 #define CURSOR_PARENT(c) (&(c)->mc_stack[(c)->mc_snum-2])
349 #define CURSOR_STACK 32
355 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
356 unsigned int mc_snum; /* number of pushed pages */
358 short mc_initialized; /* 1 if initialized */
359 short mc_eof; /* 1 if end is reached */
360 struct MDB_xcursor *mc_xcursor;
363 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
365 typedef struct MDB_node {
366 #define mn_pgno mn_p.np_pgno
367 #define mn_dsize mn_p.np_dsize
369 pgno_t np_pgno; /* child page number */
370 uint32_t np_dsize; /* leaf data size */
372 unsigned int mn_flags:4;
373 unsigned int mn_ksize:12; /* key size */
374 #define F_BIGDATA 0x01 /* data put on overflow page */
375 #define F_SUBDATA 0x02 /* data is a sub-database */
376 #define F_DUPDATA 0x04 /* data has duplicates */
380 typedef struct MDB_dbx {
382 MDB_cmp_func *md_cmp; /* user compare function */
383 MDB_cmp_func *md_dcmp; /* user dupsort function */
384 MDB_rel_func *md_rel; /* user relocate function */
386 unsigned int md_dirty;
390 pgno_t mt_next_pgno; /* next unallocated page */
393 pgno_t *mt_free_pgs; /* this is an IDL */
395 ID2L dirty_list; /* modified pages */
398 MDB_dbx *mt_dbxs; /* array */
400 unsigned int mt_numdbs;
402 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
403 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
404 unsigned int mt_flags;
405 unsigned int mt_toggle;
408 /* Context for sorted-dup records */
409 typedef struct MDB_xcursor {
410 MDB_cursor mx_cursor;
419 HANDLE me_mfd; /* just for writing the meta pages */
420 #define MDB_FATAL_ERROR 0x80000000U
422 uint32_t me_extrapad; /* unused for now */
423 unsigned int me_maxreaders;
424 unsigned int me_numdbs;
425 unsigned int me_maxdbs;
428 MDB_txninfo *me_txns;
429 MDB_meta *me_metas[2];
430 MDB_txn *me_txn; /* current write transaction */
432 off_t me_size; /* current file size */
433 pgno_t me_maxpg; /* me_mapsize / me_psize */
434 unsigned int me_psize;
435 unsigned int me_db_toggle;
436 MDB_dbx *me_dbxs; /* array */
438 MDB_oldpages *me_pghead;
439 pthread_key_t me_txkey; /* thread-key for readers */
440 MDB_dpage *me_dpages;
441 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
442 ID2 me_dirty_list[MDB_IDL_DB_SIZE];
443 LAZY_RWLOCK_DEF(me_dblock);
445 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
450 #define NODESIZE offsetof(MDB_node, mn_data)
452 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
453 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
454 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
455 #define NODEKEY(node) (void *)((node)->mn_data)
456 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
457 #define NODEPGNO(node) ((node)->mn_pgno)
458 #define NODEDSZ(node) ((node)->mn_dsize)
459 #define NODEKSZ(node) ((node)->mn_ksize)
460 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
462 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
464 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
466 static int mdb_search_page_root(MDB_txn *txn,
467 MDB_dbi dbi, MDB_val *key,
468 MDB_cursor *cursor, int modify,
469 MDB_pageparent *mpp);
470 static int mdb_search_page(MDB_txn *txn,
471 MDB_dbi dbi, MDB_val *key,
472 MDB_cursor *cursor, int modify,
473 MDB_pageparent *mpp);
475 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
476 static int mdb_env_read_meta(MDB_env *env, int *which);
477 static int mdb_env_write_meta(MDB_txn *txn);
478 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
480 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
481 MDB_val *key, int *exactp, unsigned int *kip);
482 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
483 indx_t indx, MDB_val *key, MDB_val *data,
484 pgno_t pgno, uint8_t flags);
485 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
486 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
487 MDB_pageparent *mpp, MDB_node *leaf);
488 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
489 MDB_val *key, MDB_val *data, unsigned int flags);
490 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
492 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
493 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
494 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
495 MDB_pageparent *src, indx_t srcindx,
496 MDB_pageparent *dst, indx_t dstindx);
497 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
498 MDB_pageparent *dst);
499 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
500 unsigned int *newindxp, MDB_val *newkey,
501 MDB_val *newdata, pgno_t newpgno);
502 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
504 static void cursor_pop_page(MDB_cursor *cursor);
505 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
508 static int mdb_sibling(MDB_cursor *cursor, int move_right);
509 static int mdb_cursor_next(MDB_cursor *cursor,
510 MDB_val *key, MDB_val *data, MDB_cursor_op op);
511 static int mdb_cursor_prev(MDB_cursor *cursor,
512 MDB_val *key, MDB_val *data, MDB_cursor_op op);
513 static int mdb_cursor_set(MDB_cursor *cursor,
514 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
515 static int mdb_cursor_first(MDB_cursor *cursor,
516 MDB_val *key, MDB_val *data);
517 static int mdb_cursor_last(MDB_cursor *cursor,
518 MDB_val *key, MDB_val *data);
520 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
521 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx,
522 MDB_page *mp, MDB_node *node);
523 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
525 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
527 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
529 static int memncmp(const void *s1, size_t n1,
530 const void *s2, size_t n2);
531 static int memnrcmp(const void *s1, size_t n1,
532 const void *s2, size_t n2);
535 static SECURITY_DESCRIPTOR mdb_null_sd;
536 static SECURITY_ATTRIBUTES mdb_all_sa;
537 static int mdb_sec_inited;
541 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
543 int diff, len_diff = -1;
546 len_diff = (n1 > n2);
549 diff = memcmp(s1, s2, n1);
550 return diff ? diff : len_diff;
554 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
556 const unsigned char *p1, *p2, *p1_lim;
563 p1 = (const unsigned char *)s1 + n1 - 1;
564 p2 = (const unsigned char *)s2 + n2 - 1;
566 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
568 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
574 mdb_version(int *maj, int *min, int *pat)
576 if (maj) *maj = MDB_VERSION_MAJOR;
577 if (min) *min = MDB_VERSION_MINOR;
578 if (pat) *pat = MDB_VERSION_PATCH;
579 return MDB_VERSION_STRING;
582 static char *const mdb_errstr[] = {
583 "MDB_KEYEXIST: Key/data pair already exists",
584 "MDB_NOTFOUND: No matching key/data pair found",
585 "MDB_PAGE_NOTFOUND: Requested page not found",
586 "MDB_CORRUPTED: Located page was wrong type",
587 "MDB_PANIC: Update of meta page failed",
588 "MDB_VERSION_MISMATCH: Database environment version mismatch"
592 mdb_strerror(int err)
595 return ("Successful return: 0");
597 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
598 return mdb_errstr[err - MDB_KEYEXIST];
600 return strerror(err);
605 mdb_dkey(MDB_val *key, char *buf)
608 unsigned char *c = key->mv_data;
610 if (key->mv_size > MAXKEYSIZE)
612 for (i=0; i<key->mv_size; i++)
613 ptr += sprintf(ptr, "%02x", *c++);
619 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
621 if (txn->mt_dbxs[dbi].md_cmp)
622 return txn->mt_dbxs[dbi].md_cmp(a, b);
624 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
625 #if __BYTE_ORDER == __LITTLE_ENDIAN
629 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
631 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
635 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
637 if (txn->mt_dbxs[dbi].md_dcmp)
638 return txn->mt_dbxs[dbi].md_dcmp(a, b);
640 if (txn->mt_dbs[dbi].md_flags & (0
641 #if __BYTE_ORDER == __LITTLE_ENDIAN
645 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
647 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
650 /* Allocate new page(s) for writing */
652 mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num)
655 pgno_t pgno = P_INVALID;
658 if (txn->mt_txnid > 2) {
660 if (!txn->mt_env->me_pghead && dbi != FREE_DBI &&
661 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
662 /* See if there's anything in the free DB */
667 mpp.mp_parent = NULL;
669 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
670 leaf = NODEPTR(mpp.mp_page, 0);
671 kptr = (ULONG *)NODEKEY(leaf);
675 oldest = txn->mt_txnid - 1;
676 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
677 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
678 if (mr && mr < oldest)
683 if (oldest > *kptr) {
684 /* It's usable, grab it.
690 mdb_read_data(txn, leaf, &data);
691 idl = (ULONG *)data.mv_data;
692 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
693 mop->mo_next = txn->mt_env->me_pghead;
694 mop->mo_txnid = *kptr;
695 txn->mt_env->me_pghead = mop;
696 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
701 DPRINTF("IDL read txn %lu root %lu num %lu",
702 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
703 for (i=0; i<idl[0]; i++) {
704 DPRINTF("IDL %lu", idl[i+1]);
708 /* drop this IDL from the DB */
709 mpp.mp_parent = NULL;
711 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
712 leaf = NODEPTR(mpp.mp_page, 0);
713 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
716 if (txn->mt_env->me_pghead) {
717 MDB_oldpages *mop = txn->mt_env->me_pghead;
719 /* FIXME: For now, always use fresh pages. We
720 * really ought to search the free list for a
725 /* peel pages off tail, so we only have to truncate the list */
726 pgno = MDB_IDL_LAST(mop->mo_pages);
727 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
729 if (mop->mo_pages[2] > mop->mo_pages[1])
730 mop->mo_pages[0] = 0;
734 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
735 txn->mt_env->me_pghead = mop->mo_next;
742 if (pgno == P_INVALID) {
743 /* DB size is maxed out */
744 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
747 if (txn->mt_env->me_dpages && num == 1) {
748 dp = txn->mt_env->me_dpages;
749 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
751 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
755 dp->h.md_parent = parent;
756 dp->h.md_pi = parent_idx;
757 if (pgno == P_INVALID) {
758 dp->p.mp_pgno = txn->mt_next_pgno;
759 txn->mt_next_pgno += num;
761 dp->p.mp_pgno = pgno;
763 mid.mid = dp->p.mp_pgno;
765 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
770 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
773 mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *pp)
775 MDB_page *mp = pp->mp_page;
780 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
782 if ((dp = mdb_alloc_page(txn, dbi, pp->mp_parent, pp->mp_pi, 1)) == NULL)
784 DPRINTF("touched db %u page %lu -> %lu", dbi, mp->mp_pgno, dp->p.mp_pgno);
785 assert(mp->mp_pgno != dp->p.mp_pgno);
786 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
787 pgno = dp->p.mp_pgno;
788 memcpy(&dp->p, mp, txn->mt_env->me_psize);
791 mp->mp_flags |= P_DIRTY;
793 /* Update the page number to new touched page. */
794 if (pp->mp_parent != NULL)
795 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
802 mdb_env_sync(MDB_env *env, int force)
805 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
806 if (fdatasync(env->me_fd))
813 mdb_txn_reset0(MDB_txn *txn);
816 mdb_txn_renew0(MDB_txn *txn)
818 MDB_env *env = txn->mt_env;
820 if (txn->mt_flags & MDB_TXN_RDONLY) {
821 MDB_reader *r = pthread_getspecific(env->me_txkey);
824 pid_t pid = getpid();
825 pthread_t tid = pthread_self();
828 for (i=0; i<env->me_txns->mti_numreaders; i++)
829 if (env->me_txns->mti_readers[i].mr_pid == 0)
831 if (i == env->me_maxreaders) {
835 env->me_txns->mti_readers[i].mr_pid = pid;
836 env->me_txns->mti_readers[i].mr_tid = tid;
837 if (i >= env->me_txns->mti_numreaders)
838 env->me_txns->mti_numreaders = i+1;
840 r = &env->me_txns->mti_readers[i];
841 pthread_setspecific(env->me_txkey, r);
843 txn->mt_txnid = env->me_txns->mti_txnid;
844 txn->mt_toggle = env->me_txns->mti_me_toggle;
845 r->mr_txnid = txn->mt_txnid;
846 txn->mt_u.reader = r;
850 txn->mt_txnid = env->me_txns->mti_txnid+1;
851 txn->mt_toggle = env->me_txns->mti_me_toggle;
852 txn->mt_u.dirty_list = env->me_dirty_list;
853 txn->mt_u.dirty_list[0].mid = 0;
854 txn->mt_free_pgs = env->me_free_pgs;
855 txn->mt_free_pgs[0] = 0;
856 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
860 /* Copy the DB arrays */
861 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
862 txn->mt_numdbs = env->me_numdbs;
863 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
864 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
865 if (txn->mt_numdbs > 2)
866 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
867 (txn->mt_numdbs - 2) * sizeof(MDB_db));
868 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
874 mdb_txn_renew(MDB_txn *txn)
881 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
882 DPUTS("environment had fatal error, must shutdown!");
886 rc = mdb_txn_renew0(txn);
887 if (rc == MDB_SUCCESS) {
888 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
889 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
890 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
896 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
901 if (env->me_flags & MDB_FATAL_ERROR) {
902 DPUTS("environment had fatal error, must shutdown!");
905 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
906 DPRINTF("calloc: %s", strerror(ErrCode()));
909 txn->mt_dbs = (MDB_db *)(txn+1);
910 if (flags & MDB_RDONLY) {
911 txn->mt_flags |= MDB_TXN_RDONLY;
915 rc = mdb_txn_renew0(txn);
920 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
921 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
922 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
929 mdb_txn_reset0(MDB_txn *txn)
931 MDB_env *env = txn->mt_env;
933 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
934 txn->mt_u.reader->mr_txnid = 0;
940 /* return all dirty pages to dpage list */
941 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
942 dp = txn->mt_u.dirty_list[i].mptr;
943 if (dp->h.md_num == 1) {
944 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
945 txn->mt_env->me_dpages = dp;
947 /* large pages just get freed directly */
952 while ((mop = txn->mt_env->me_pghead)) {
953 txn->mt_env->me_pghead = mop->mo_next;
958 for (i=2; i<env->me_numdbs; i++)
959 env->me_dbxs[i].md_dirty = 0;
965 mdb_txn_reset(MDB_txn *txn)
970 DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
971 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
972 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
978 mdb_txn_abort(MDB_txn *txn)
983 DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
984 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
985 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
992 mdb_txn_commit(MDB_txn *txn)
1002 assert(txn != NULL);
1003 assert(txn->mt_env != NULL);
1007 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1012 if (txn != env->me_txn) {
1013 DPUTS("attempt to commit unknown transaction");
1018 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1019 DPUTS("error flag is set, can't commit");
1024 if (!txn->mt_u.dirty_list[0].mid)
1027 DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
1028 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1030 /* should only be one record now */
1031 if (env->me_pghead) {
1034 /* make sure first page of freeDB is touched and on freelist */
1035 mpp.mp_parent = NULL;
1037 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
1039 /* save to free list */
1040 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1045 /* make sure last page of freeDB is touched and on freelist */
1046 key.mv_size = MAXKEYSIZE+1;
1048 mpp.mp_parent = NULL;
1050 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
1055 ULONG *idl = txn->mt_free_pgs;
1056 DPRINTF("IDL write txn %lu root %lu num %lu",
1057 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1058 for (i=0; i<idl[0]; i++) {
1059 DPRINTF("IDL %lu", idl[i+1]);
1063 /* write to last page of freeDB */
1064 key.mv_size = sizeof(pgno_t);
1065 key.mv_data = (char *)&txn->mt_txnid;
1066 data.mv_data = txn->mt_free_pgs;
1067 /* The free list can still grow during this call,
1068 * despite the pre-emptive touches above. So check
1069 * and make sure the entire thing got written.
1072 i = txn->mt_free_pgs[0];
1073 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1074 rc = mdb_put0(txn, FREE_DBI, &key, &data, 0);
1079 } while (i != txn->mt_free_pgs[0]);
1081 /* should only be one record now */
1082 if (env->me_pghead) {
1086 mop = env->me_pghead;
1087 key.mv_size = sizeof(pgno_t);
1088 key.mv_data = (char *)&mop->mo_txnid;
1089 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1090 data.mv_data = mop->mo_pages;
1091 mdb_put0(txn, FREE_DBI, &key, &data, 0);
1092 free(env->me_pghead);
1093 env->me_pghead = NULL;
1096 /* Update DB root pointers. Their pages have already been
1097 * touched so this is all in-place and cannot fail.
1101 data.mv_size = sizeof(MDB_db);
1103 for (i = 2; i < txn->mt_numdbs; i++) {
1104 if (txn->mt_dbxs[i].md_dirty) {
1105 data.mv_data = &txn->mt_dbs[i];
1106 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
1111 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1117 /* Windows actually supports scatter/gather I/O, but only on
1118 * unbuffered file handles. Since we're relying on the OS page
1119 * cache for all our data, that's self-defeating. So we just
1120 * write pages one at a time. We use the ov structure to set
1121 * the write offset, to at least save the overhead of a Seek
1125 memset(&ov, 0, sizeof(ov));
1126 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1127 dp = txn->mt_u.dirty_list[i].mptr;
1128 DPRINTF("committing page %lu", dp->p.mp_pgno);
1129 size = dp->p.mp_pgno * env->me_psize;
1130 ov.Offset = size & 0xffffffff;
1131 ov.OffsetHigh = size >> 16;
1132 ov.OffsetHigh >>= 16;
1133 /* clear dirty flag */
1134 dp->p.mp_flags &= ~P_DIRTY;
1135 rc = WriteFile(env->me_fd, &dp->p, env->me_psize * dp->h.md_num, NULL, &ov);
1138 DPRINTF("WriteFile: %d", n);
1145 struct iovec iov[MDB_COMMIT_PAGES];
1149 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1150 dp = txn->mt_u.dirty_list[i].mptr;
1151 if (dp->p.mp_pgno != next) {
1153 DPRINTF("committing %u dirty pages", n);
1154 rc = writev(env->me_fd, iov, n);
1158 DPUTS("short write, filesystem full?");
1160 DPRINTF("writev: %s", strerror(n));
1167 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1168 next = dp->p.mp_pgno;
1170 DPRINTF("committing page %lu", dp->p.mp_pgno);
1171 iov[n].iov_len = env->me_psize * dp->h.md_num;
1172 iov[n].iov_base = &dp->p;
1173 size += iov[n].iov_len;
1174 next = dp->p.mp_pgno + dp->h.md_num;
1175 /* clear dirty flag */
1176 dp->p.mp_flags &= ~P_DIRTY;
1177 if (++n >= MDB_COMMIT_PAGES) {
1187 DPRINTF("committing %u dirty pages", n);
1188 rc = writev(env->me_fd, iov, n);
1192 DPUTS("short write, filesystem full?");
1194 DPRINTF("writev: %s", strerror(n));
1201 /* Drop the dirty pages.
1203 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1204 dp = txn->mt_u.dirty_list[i].mptr;
1205 if (dp->h.md_num == 1) {
1206 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1207 txn->mt_env->me_dpages = dp;
1211 txn->mt_u.dirty_list[i].mid = 0;
1213 txn->mt_u.dirty_list[0].mid = 0;
1215 if ((n = mdb_env_sync(env, 0)) != 0 ||
1216 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1223 /* update the DB tables */
1225 int toggle = !env->me_db_toggle;
1228 ip = &env->me_dbs[toggle][2];
1229 jp = &txn->mt_dbs[2];
1230 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1231 for (i = 2; i < txn->mt_numdbs; i++) {
1232 if (ip->md_root != jp->md_root)
1237 for (i = 2; i < txn->mt_numdbs; i++) {
1238 if (txn->mt_dbxs[i].md_dirty)
1239 txn->mt_dbxs[i].md_dirty = 0;
1241 env->me_db_toggle = toggle;
1242 env->me_numdbs = txn->mt_numdbs;
1243 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1246 UNLOCK_MUTEX_W(env);
1253 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1255 char page[PAGESIZE];
1260 /* We don't know the page size yet, so use a minimum value.
1264 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1266 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1271 else if (rc != PAGESIZE) {
1275 DPRINTF("read: %s", strerror(err));
1279 p = (MDB_page *)page;
1281 if (!F_ISSET(p->mp_flags, P_META)) {
1282 DPRINTF("page %lu not a meta page", p->mp_pgno);
1287 if (m->mm_magic != MDB_MAGIC) {
1288 DPUTS("meta has invalid magic");
1292 if (m->mm_version != MDB_VERSION) {
1293 DPRINTF("database is version %u, expected version %u",
1294 m->mm_version, MDB_VERSION);
1295 return MDB_VERSION_MISMATCH;
1298 memcpy(meta, m, sizeof(*m));
1303 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1310 DPUTS("writing new meta page");
1314 meta->mm_magic = MDB_MAGIC;
1315 meta->mm_version = MDB_VERSION;
1316 meta->mm_psize = psize;
1317 meta->mm_last_pg = 1;
1318 meta->mm_flags = env->me_flags & 0xffff;
1319 meta->mm_flags |= MDB_INTEGERKEY;
1320 meta->mm_dbs[0].md_root = P_INVALID;
1321 meta->mm_dbs[1].md_root = P_INVALID;
1323 p = calloc(2, psize);
1325 p->mp_flags = P_META;
1328 memcpy(m, meta, sizeof(*meta));
1330 q = (MDB_page *)((char *)p + psize);
1333 q->mp_flags = P_META;
1336 memcpy(m, meta, sizeof(*meta));
1341 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1342 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1345 rc = write(env->me_fd, p, psize * 2);
1346 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1353 mdb_env_write_meta(MDB_txn *txn)
1356 MDB_meta meta, metab;
1358 int rc, len, toggle;
1364 assert(txn != NULL);
1365 assert(txn->mt_env != NULL);
1367 toggle = !txn->mt_toggle;
1368 DPRINTF("writing meta page %d for root page %lu",
1369 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1373 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1374 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1376 ptr = (char *)&meta;
1377 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1378 len = sizeof(MDB_meta) - off;
1381 meta.mm_dbs[0] = txn->mt_dbs[0];
1382 meta.mm_dbs[1] = txn->mt_dbs[1];
1383 meta.mm_last_pg = txn->mt_next_pgno - 1;
1384 meta.mm_txnid = txn->mt_txnid;
1387 off += env->me_psize;
1390 /* Write to the SYNC fd */
1393 memset(&ov, 0, sizeof(ov));
1395 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1398 rc = pwrite(env->me_mfd, ptr, len, off);
1403 DPUTS("write failed, disk error?");
1404 /* On a failure, the pagecache still contains the new data.
1405 * Write some old data back, to prevent it from being used.
1406 * Use the non-SYNC fd; we know it will fail anyway.
1408 meta.mm_last_pg = metab.mm_last_pg;
1409 meta.mm_txnid = metab.mm_txnid;
1411 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1413 r2 = pwrite(env->me_fd, ptr, len, off);
1415 env->me_flags |= MDB_FATAL_ERROR;
1418 /* Memory ordering issues are irrelevant; since the entire writer
1419 * is wrapped by wmutex, all of these changes will become visible
1420 * after the wmutex is unlocked. Since the DB is multi-version,
1421 * readers will get consistent data regardless of how fresh or
1422 * how stale their view of these values is.
1424 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1425 txn->mt_env->me_txns->mti_me_toggle = toggle;
1426 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1427 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1433 mdb_env_read_meta(MDB_env *env, int *which)
1437 assert(env != NULL);
1439 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1442 DPRINTF("Using meta page %d", toggle);
1449 mdb_env_create(MDB_env **env)
1453 e = calloc(1, sizeof(MDB_env));
1454 if (!e) return ENOMEM;
1456 e->me_maxreaders = DEFAULT_READERS;
1458 e->me_fd = INVALID_HANDLE_VALUE;
1459 e->me_lfd = INVALID_HANDLE_VALUE;
1460 e->me_mfd = INVALID_HANDLE_VALUE;
1466 mdb_env_set_mapsize(MDB_env *env, size_t size)
1470 env->me_mapsize = size;
1475 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1479 env->me_maxdbs = dbs;
1484 mdb_env_set_maxreaders(MDB_env *env, int readers)
1488 env->me_maxreaders = readers;
1493 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1495 if (!env || !readers)
1497 *readers = env->me_maxreaders;
1502 mdb_env_open2(MDB_env *env, unsigned int flags)
1504 int i, newenv = 0, toggle;
1508 env->me_flags = flags;
1510 memset(&meta, 0, sizeof(meta));
1512 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1515 DPUTS("new mdbenv");
1519 if (!env->me_mapsize) {
1520 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1526 LONG sizelo, sizehi;
1527 sizelo = env->me_mapsize & 0xffffffff;
1528 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1530 /* Windows won't create mappings for zero length files.
1531 * Just allocate the maxsize right now.
1534 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1535 if (!SetEndOfFile(env->me_fd))
1537 SetFilePointer(env->me_fd, 0, NULL, 0);
1539 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1540 sizehi, sizelo, NULL);
1543 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1551 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1553 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1555 if (env->me_map == MAP_FAILED)
1560 meta.mm_mapsize = env->me_mapsize;
1561 if (flags & MDB_FIXEDMAP)
1562 meta.mm_address = env->me_map;
1563 i = mdb_env_init_meta(env, &meta);
1564 if (i != MDB_SUCCESS) {
1565 munmap(env->me_map, env->me_mapsize);
1569 env->me_psize = meta.mm_psize;
1571 env->me_maxpg = env->me_mapsize / env->me_psize;
1573 p = (MDB_page *)env->me_map;
1574 env->me_metas[0] = METADATA(p);
1575 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1577 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1580 DPRINTF("opened database version %u, pagesize %u",
1581 env->me_metas[toggle]->mm_version, env->me_psize);
1582 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1583 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1584 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1585 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1586 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1587 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1593 /* Windows doesn't support destructor callbacks for thread-specific storage */
1595 mdb_env_reader_dest(void *ptr)
1597 MDB_reader *reader = ptr;
1599 reader->mr_txnid = 0;
1605 /* downgrade the exclusive lock on the region back to shared */
1607 mdb_env_share_locks(MDB_env *env)
1611 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1613 env->me_txns->mti_me_toggle = toggle;
1614 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1619 /* First acquire a shared lock. The Unlock will
1620 * then release the existing exclusive lock.
1622 memset(&ov, 0, sizeof(ov));
1623 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1624 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1628 struct flock lock_info;
1629 /* The shared lock replaces the existing lock */
1630 memset((void *)&lock_info, 0, sizeof(lock_info));
1631 lock_info.l_type = F_RDLCK;
1632 lock_info.l_whence = SEEK_SET;
1633 lock_info.l_start = 0;
1634 lock_info.l_len = 1;
1635 fcntl(env->me_lfd, F_SETLK, &lock_info);
1641 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1649 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1650 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1651 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1655 /* Try to get exclusive lock. If we succeed, then
1656 * nobody is using the lock region and we should initialize it.
1659 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1663 memset(&ov, 0, sizeof(ov));
1664 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
1670 size = GetFileSize(env->me_lfd, NULL);
1672 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1676 /* Try to get exclusive lock. If we succeed, then
1677 * nobody is using the lock region and we should initialize it.
1680 struct flock lock_info;
1681 memset((void *)&lock_info, 0, sizeof(lock_info));
1682 lock_info.l_type = F_WRLCK;
1683 lock_info.l_whence = SEEK_SET;
1684 lock_info.l_start = 0;
1685 lock_info.l_len = 1;
1686 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1690 lock_info.l_type = F_RDLCK;
1691 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
1698 size = lseek(env->me_lfd, 0, SEEK_END);
1700 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1701 if (size < rsize && *excl) {
1703 SetFilePointer(env->me_lfd, rsize, NULL, 0);
1704 if (!SetEndOfFile(env->me_lfd)) {
1709 if (ftruncate(env->me_lfd, rsize) != 0) {
1716 size = rsize - sizeof(MDB_txninfo);
1717 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1722 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
1728 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
1730 if (!env->me_txns) {
1736 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1738 if (env->me_txns == MAP_FAILED) {
1746 if (!mdb_sec_inited) {
1747 InitializeSecurityDescriptor(&mdb_null_sd,
1748 SECURITY_DESCRIPTOR_REVISION);
1749 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
1750 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1751 mdb_all_sa.bInheritHandle = FALSE;
1752 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
1755 /* FIXME: only using up to 20 characters of the env path here,
1756 * probably not enough to assure uniqueness...
1758 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
1759 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
1760 while ((ptr = strchr(ptr, '\\')))
1762 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1763 if (!env->me_rmutex) {
1767 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
1768 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
1769 while ((ptr = strchr(ptr, '\\')))
1771 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1772 if (!env->me_wmutex) {
1777 pthread_mutexattr_t mattr;
1779 pthread_mutexattr_init(&mattr);
1780 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1784 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1785 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1787 env->me_txns->mti_version = MDB_VERSION;
1788 env->me_txns->mti_magic = MDB_MAGIC;
1789 env->me_txns->mti_txnid = 0;
1790 env->me_txns->mti_numreaders = 0;
1791 env->me_txns->mti_me_toggle = 0;
1794 if (env->me_txns->mti_magic != MDB_MAGIC) {
1795 DPUTS("lock region has invalid magic");
1799 if (env->me_txns->mti_version != MDB_VERSION) {
1800 DPRINTF("lock region is version %u, expected version %u",
1801 env->me_txns->mti_version, MDB_VERSION);
1802 rc = MDB_VERSION_MISMATCH;
1806 if (rc != EACCES && rc != EAGAIN) {
1810 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
1811 if (!env->me_rmutex) {
1815 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
1816 if (!env->me_wmutex) {
1826 env->me_lfd = INVALID_HANDLE_VALUE;
1831 #define LOCKNAME "/lock.mdb"
1832 #define DATANAME "/data.mdb"
1834 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1836 int oflags, rc, len, excl;
1837 char *lpath, *dpath;
1840 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1843 dpath = lpath + len + sizeof(LOCKNAME);
1844 sprintf(lpath, "%s" LOCKNAME, path);
1845 sprintf(dpath, "%s" DATANAME, path);
1847 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1852 if (F_ISSET(flags, MDB_RDONLY)) {
1853 oflags = GENERIC_READ;
1854 len = OPEN_EXISTING;
1856 oflags = GENERIC_READ|GENERIC_WRITE;
1859 mode = FILE_ATTRIBUTE_NORMAL;
1860 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1861 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1866 if (F_ISSET(flags, MDB_RDONLY))
1869 oflags = O_RDWR | O_CREAT;
1871 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1877 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1878 /* synchronous fd for meta writes */
1880 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1881 mode |= FILE_FLAG_WRITE_THROUGH;
1882 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1883 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1888 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1889 oflags |= MDB_DSYNC;
1890 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1895 env->me_path = strdup(path);
1896 DPRINTF("opened dbenv %p", (void *) env);
1897 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1898 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1900 mdb_env_share_locks(env);
1901 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1902 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1903 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1909 if (env->me_fd != INVALID_HANDLE_VALUE) {
1911 env->me_fd = INVALID_HANDLE_VALUE;
1913 if (env->me_lfd != INVALID_HANDLE_VALUE) {
1915 env->me_lfd = INVALID_HANDLE_VALUE;
1923 mdb_env_close(MDB_env *env)
1930 while (env->me_dpages) {
1931 dp = env->me_dpages;
1932 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1936 free(env->me_dbs[1]);
1937 free(env->me_dbs[0]);
1941 LAZY_RWLOCK_DESTROY(&env->me_dblock);
1942 pthread_key_delete(env->me_txkey);
1945 munmap(env->me_map, env->me_mapsize);
1950 pid_t pid = getpid();
1952 for (i=0; i<env->me_txns->mti_numreaders; i++)
1953 if (env->me_txns->mti_readers[i].mr_pid == pid)
1954 env->me_txns->mti_readers[i].mr_pid = 0;
1955 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
1961 /* Search for key within a leaf page, using binary search.
1962 * Returns the smallest entry larger or equal to the key.
1963 * If exactp is non-null, stores whether the found entry was an exact match
1964 * in *exactp (1 or 0).
1965 * If kip is non-null, stores the index of the found entry in *kip.
1966 * If no entry larger or equal to the key is found, returns NULL.
1969 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1970 int *exactp, unsigned int *kip)
1975 MDB_node *node = NULL;
1979 DPRINTF("searching %u keys in %s page %lu",
1981 IS_LEAF(mp) ? "leaf" : "branch",
1984 assert(NUMKEYS(mp) > 0);
1986 memset(&nodekey, 0, sizeof(nodekey));
1988 low = IS_LEAF(mp) ? 0 : 1;
1989 high = NUMKEYS(mp) - 1;
1990 while (low <= high) {
1991 i = (low + high) >> 1;
1994 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
1995 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
1997 node = NODEPTR(mp, i);
1999 nodekey.mv_size = node->mn_ksize;
2000 nodekey.mv_data = NODEKEY(node);
2003 rc = mdb_cmp(txn, dbi, key, &nodekey);
2006 DPRINTF("found leaf index %u [%s], rc = %i",
2007 i, DKEY(&nodekey), rc);
2009 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2010 i, DKEY(&nodekey), NODEPGNO(node), rc);
2020 if (rc > 0) { /* Found entry is less than the key. */
2021 i++; /* Skip to get the smallest entry larger than key. */
2022 if (i >= NUMKEYS(mp))
2023 /* There is no entry larger or equal to the key. */
2027 *exactp = (rc == 0);
2028 if (kip) /* Store the key index if requested. */
2031 /* nodeptr is fake for LEAF2 */
2032 return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
2036 cursor_pop_page(MDB_cursor *cursor)
2040 if (cursor->mc_snum) {
2041 top = CURSOR_TOP(cursor);
2044 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
2045 cursor->mc_dbi, (void *) cursor);
2050 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
2054 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2055 cursor->mc_dbi, (void *) cursor);
2057 assert(cursor->mc_snum < CURSOR_STACK);
2059 ppage = &cursor->mc_stack[cursor->mc_snum++];
2060 ppage->mp_page = mp;
2066 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2070 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2073 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2074 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2075 dp = txn->mt_u.dirty_list[x].mptr;
2080 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2081 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2085 DPRINTF("page %lu not found", pgno);
2088 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2092 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2093 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2095 MDB_page *mp = mpp->mp_page;
2099 if (cursor && cursor_push_page(cursor, mp) == NULL)
2102 while (IS_BRANCH(mp)) {
2106 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2107 assert(NUMKEYS(mp) > 1);
2108 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2110 if (key == NULL) /* Initialize cursor to first page. */
2112 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2113 /* cursor to last page */
2117 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
2119 i = NUMKEYS(mp) - 1;
2127 DPRINTF("following index %u for key [%s]",
2129 assert(i < NUMKEYS(mp));
2130 node = NODEPTR(mp, i);
2133 CURSOR_TOP(cursor)->mp_ki = i;
2135 mpp->mp_parent = mp;
2136 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
2141 if (cursor && cursor_push_page(cursor, mp) == NULL)
2145 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
2146 if ((rc = mdb_touch(txn, dbi, mpp)) != 0)
2148 dh = ((MDB_dhead *)mpp->mp_page)-1;
2149 dh->md_parent = mpp->mp_parent;
2150 dh->md_pi = mpp->mp_pi;
2157 DPRINTF("internal error, index points to a %02X page!?",
2159 return MDB_CORRUPTED;
2162 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2163 key ? DKEY(key) : NULL);
2168 /* Search for the page a given key should be in.
2169 * Stores a pointer to the found page in *mpp.
2170 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2171 * If cursor is non-null, pushes parent pages on the cursor stack.
2172 * If modify is true, visited pages are updated with new page numbers.
2175 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2176 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2181 /* Choose which root page to start with. If a transaction is given
2182 * use the root page from the transaction, otherwise read the last
2183 * committed root page.
2185 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2186 DPUTS("transaction has failed, must abort");
2189 root = txn->mt_dbs[dbi].md_root;
2191 if (root == P_INVALID) { /* Tree is empty. */
2192 DPUTS("tree is empty");
2193 return MDB_NOTFOUND;
2196 if ((rc = mdb_get_page(txn, root, &mpp->mp_page)))
2199 DPRINTF("db %u root page %lu has flags 0x%X",
2200 dbi, root, mpp->mp_page->mp_flags);
2203 /* For sub-databases, update main root first */
2204 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
2206 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
2210 txn->mt_dbxs[dbi].md_dirty = 1;
2212 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
2213 mpp->mp_parent = NULL;
2215 if ((rc = mdb_touch(txn, dbi, mpp)))
2217 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
2221 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
2225 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2227 MDB_page *omp; /* overflow mpage */
2231 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2232 data->mv_size = leaf->mn_dsize;
2233 data->mv_data = NODEDATA(leaf);
2237 /* Read overflow data.
2239 data->mv_size = leaf->mn_dsize;
2240 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2241 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2242 DPRINTF("read overflow page %lu failed", pgno);
2245 data->mv_data = METADATA(omp);
2251 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2252 MDB_val *key, MDB_val *data)
2261 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2263 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2266 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2270 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
2273 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
2274 if (leaf && exact) {
2275 /* Return first duplicate data item */
2276 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2279 mdb_xcursor_init0(txn, dbi, &mx);
2280 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
2281 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
2282 if (rc != MDB_SUCCESS)
2284 if (IS_LEAF2(mpp.mp_page)) {
2285 data->mv_size = txn->mt_dbs[dbi].md_pad;
2286 data->mv_data = LEAF2KEY(mpp.mp_page, 0, data->mv_size);
2288 leaf = NODEPTR(mpp.mp_page, 0);
2289 data->mv_size = NODEKSZ(leaf);
2290 data->mv_data = NODEKEY(leaf);
2293 rc = mdb_read_data(txn, leaf, data);
2303 mdb_sibling(MDB_cursor *cursor, int move_right)
2310 if (cursor->mc_snum < 2) {
2311 return MDB_NOTFOUND; /* root has no siblings */
2313 parent = CURSOR_PARENT(cursor);
2315 DPRINTF("parent page is page %lu, index %u",
2316 parent->mp_page->mp_pgno, parent->mp_ki);
2318 cursor_pop_page(cursor);
2319 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
2320 : (parent->mp_ki == 0)) {
2321 DPRINTF("no more keys left, moving to %s sibling",
2322 move_right ? "right" : "left");
2323 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2325 parent = CURSOR_TOP(cursor);
2331 DPRINTF("just moving to %s index key %u",
2332 move_right ? "right" : "left", parent->mp_ki);
2334 assert(IS_BRANCH(parent->mp_page));
2336 indx = NODEPTR(parent->mp_page, parent->mp_ki);
2337 if ((rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp)))
2340 mp->parent = parent->mp_page;
2341 mp->parent_index = parent->mp_ki;
2344 cursor_push_page(cursor, mp);
2350 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2357 if (cursor->mc_eof) {
2358 return MDB_NOTFOUND;
2361 assert(cursor->mc_initialized);
2363 top = CURSOR_TOP(cursor);
2366 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2367 leaf = NODEPTR(mp, top->mp_ki);
2368 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2369 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2370 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2371 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2375 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2376 if (op == MDB_NEXT_DUP)
2377 return MDB_NOTFOUND;
2381 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2383 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2384 DPUTS("=====> move to next sibling page");
2385 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2387 return MDB_NOTFOUND;
2389 top = CURSOR_TOP(cursor);
2391 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2395 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2396 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2399 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2400 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2404 assert(IS_LEAF(mp));
2405 leaf = NODEPTR(mp, top->mp_ki);
2407 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2408 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2411 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2414 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2415 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2416 if (rc != MDB_SUCCESS)
2421 MDB_SET_KEY(leaf, key);
2426 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2433 assert(cursor->mc_initialized);
2435 top = CURSOR_TOP(cursor);
2438 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2439 leaf = NODEPTR(mp, top->mp_ki);
2440 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2441 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2442 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2443 if (op != MDB_PREV || rc == MDB_SUCCESS)
2446 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2447 if (op == MDB_PREV_DUP)
2448 return MDB_NOTFOUND;
2453 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2455 if (top->mp_ki == 0) {
2456 DPUTS("=====> move to prev sibling page");
2457 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2458 cursor->mc_initialized = 0;
2459 return MDB_NOTFOUND;
2461 top = CURSOR_TOP(cursor);
2463 top->mp_ki = NUMKEYS(mp) - 1;
2464 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2470 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2471 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2474 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2475 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2479 assert(IS_LEAF(mp));
2480 leaf = NODEPTR(mp, top->mp_ki);
2482 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2483 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2486 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2489 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2490 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2491 if (rc != MDB_SUCCESS)
2496 MDB_SET_KEY(leaf, key);
2501 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2502 MDB_cursor_op op, int *exactp)
2512 assert(key->mv_size > 0);
2514 /* See if we're already on the right page */
2515 if (cursor->mc_initialized) {
2517 top = CURSOR_TOP(cursor);
2518 /* Don't try this for LEAF2 pages. Maybe support that later. */
2519 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2520 leaf = NODEPTR(top->mp_page, 0);
2521 MDB_SET_KEY(leaf, &nodekey);
2522 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2524 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2525 MDB_SET_KEY(leaf, &nodekey);
2526 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2528 /* we're already on the right page */
2529 mpp.mp_page = top->mp_page;
2536 cursor->mc_snum = 0;
2538 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2539 if (rc != MDB_SUCCESS)
2542 assert(IS_LEAF(mpp.mp_page));
2544 top = CURSOR_TOP(cursor);
2546 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2547 if (exactp != NULL && !*exactp) {
2548 /* MDB_SET specified and not an exact match. */
2549 return MDB_NOTFOUND;
2553 DPUTS("===> inexact leaf not found, goto sibling");
2554 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2555 return rc; /* no entries matched */
2556 top = CURSOR_TOP(cursor);
2558 mpp.mp_page = top->mp_page;
2559 assert(IS_LEAF(mpp.mp_page));
2560 leaf = NODEPTR(mpp.mp_page, 0);
2563 cursor->mc_initialized = 1;
2566 if (IS_LEAF2(mpp.mp_page)) {
2567 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2568 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2572 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2573 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2576 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2577 if (op == MDB_SET || op == MDB_SET_RANGE) {
2578 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2581 if (op == MDB_GET_BOTH) {
2587 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2588 if (rc != MDB_SUCCESS)
2591 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2593 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2595 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2597 if (op == MDB_GET_BOTH || rc > 0)
2598 return MDB_NOTFOUND;
2602 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2607 /* The key already matches in all other cases */
2608 if (op == MDB_SET_RANGE)
2609 MDB_SET_KEY(leaf, key);
2610 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2616 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2622 cursor->mc_snum = 0;
2624 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2625 if (rc != MDB_SUCCESS)
2627 assert(IS_LEAF(mpp.mp_page));
2629 leaf = NODEPTR(mpp.mp_page, 0);
2630 cursor->mc_initialized = 1;
2633 if (IS_LEAF2(mpp.mp_page)) {
2634 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2635 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2640 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2641 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2642 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2646 if (cursor->mc_xcursor)
2647 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2648 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2652 MDB_SET_KEY(leaf, key);
2657 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2665 cursor->mc_snum = 0;
2667 lkey.mv_size = MAXKEYSIZE+1;
2668 lkey.mv_data = NULL;
2670 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2671 if (rc != MDB_SUCCESS)
2673 assert(IS_LEAF(mpp.mp_page));
2675 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2676 cursor->mc_initialized = 1;
2679 top = CURSOR_TOP(cursor);
2680 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2682 if (IS_LEAF2(mpp.mp_page)) {
2683 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2684 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2689 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2690 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2691 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2695 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2700 MDB_SET_KEY(leaf, key);
2705 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2715 case MDB_GET_BOTH_RANGE:
2716 if (data == NULL || cursor->mc_xcursor == NULL) {
2723 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2725 } else if (op == MDB_SET_RANGE)
2726 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2728 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2730 case MDB_GET_MULTIPLE:
2732 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2733 !cursor->mc_initialized) {
2738 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2741 case MDB_NEXT_MULTIPLE:
2743 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2747 if (!cursor->mc_initialized)
2748 rc = mdb_cursor_first(cursor, key, data);
2750 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2751 if (rc == MDB_SUCCESS) {
2752 if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2755 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2756 data->mv_size = NUMKEYS(top->mp_page) *
2757 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2758 data->mv_data = METADATA(top->mp_page);
2759 top->mp_ki = NUMKEYS(top->mp_page)-1;
2767 case MDB_NEXT_NODUP:
2768 if (!cursor->mc_initialized)
2769 rc = mdb_cursor_first(cursor, key, data);
2771 rc = mdb_cursor_next(cursor, key, data, op);
2775 case MDB_PREV_NODUP:
2776 if (!cursor->mc_initialized || cursor->mc_eof)
2777 rc = mdb_cursor_last(cursor, key, data);
2779 rc = mdb_cursor_prev(cursor, key, data, op);
2782 rc = mdb_cursor_first(cursor, key, data);
2785 rc = mdb_cursor_last(cursor, key, data);
2788 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2796 /* Allocate a page and initialize it
2799 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2803 if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
2805 DPRINTF("allocated new mpage %lu, page size %u",
2806 dp->p.mp_pgno, txn->mt_env->me_psize);
2807 dp->p.mp_flags = flags | P_DIRTY;
2808 dp->p.mp_lower = PAGEHDRSZ;
2809 dp->p.mp_upper = txn->mt_env->me_psize;
2811 if (IS_BRANCH(&dp->p))
2812 txn->mt_dbs[dbi].md_branch_pages++;
2813 else if (IS_LEAF(&dp->p))
2814 txn->mt_dbs[dbi].md_leaf_pages++;
2815 else if (IS_OVERFLOW(&dp->p)) {
2816 txn->mt_dbs[dbi].md_overflow_pages += num;
2817 dp->p.mp_pages = num;
2824 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2828 sz = LEAFSIZE(key, data);
2829 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2830 /* put on overflow page */
2831 sz -= data->mv_size - sizeof(pgno_t);
2834 return sz + sizeof(indx_t);
2838 mdb_branch_size(MDB_env *env, MDB_val *key)
2843 if (sz >= env->me_psize / MDB_MINKEYS) {
2844 /* put on overflow page */
2845 /* not implemented */
2846 /* sz -= key->size - sizeof(pgno_t); */
2849 return sz + sizeof(indx_t);
2853 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2854 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2857 size_t node_size = NODESIZE;
2860 MDB_dpage *ofp = NULL; /* overflow page */
2863 assert(mp->mp_upper >= mp->mp_lower);
2865 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
2866 IS_LEAF(mp) ? "leaf" : "branch",
2867 mp->mp_pgno, indx, data ? data->mv_size : 0,
2868 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
2871 /* Move higher keys up one slot. */
2872 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2873 char *ptr = LEAF2KEY(mp, indx, ksize);
2874 dif = NUMKEYS(mp) - indx;
2876 memmove(ptr+ksize, ptr, dif*ksize);
2877 /* insert new key */
2878 memcpy(ptr, key->mv_data, ksize);
2880 /* Just using these for counting */
2881 mp->mp_lower += sizeof(indx_t);
2882 mp->mp_upper -= ksize - sizeof(indx_t);
2887 node_size += key->mv_size;
2891 if (F_ISSET(flags, F_BIGDATA)) {
2892 /* Data already on overflow page. */
2893 node_size += sizeof(pgno_t);
2894 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2895 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2896 /* Put data on overflow page. */
2897 DPRINTF("data size is %zu, put on overflow page",
2899 node_size += sizeof(pgno_t);
2900 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2902 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2905 node_size += data->mv_size;
2909 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2910 DPRINTF("not enough room in page %lu, got %u ptrs",
2911 mp->mp_pgno, NUMKEYS(mp));
2912 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2913 mp->mp_upper - mp->mp_lower);
2914 DPRINTF("node size = %zu", node_size);
2918 /* Move higher pointers up one slot. */
2919 for (i = NUMKEYS(mp); i > indx; i--)
2920 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2922 /* Adjust free space offsets. */
2923 ofs = mp->mp_upper - node_size;
2924 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2925 mp->mp_ptrs[indx] = ofs;
2927 mp->mp_lower += sizeof(indx_t);
2929 /* Write the node data. */
2930 node = NODEPTR(mp, indx);
2931 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2932 node->mn_flags = flags;
2934 node->mn_dsize = data->mv_size;
2936 NODEPGNO(node) = pgno;
2939 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2944 if (F_ISSET(flags, F_BIGDATA))
2945 memcpy(node->mn_data + key->mv_size, data->mv_data,
2948 memcpy(node->mn_data + key->mv_size, data->mv_data,
2951 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2953 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2961 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2964 indx_t i, j, numkeys, ptr;
2968 DPRINTF("delete node %u on %s page %lu", indx,
2969 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2970 assert(indx < NUMKEYS(mp));
2973 int x = NUMKEYS(mp) - 1 - indx;
2974 base = LEAF2KEY(mp, indx, ksize);
2976 memmove(base, base + ksize, x * ksize);
2977 mp->mp_lower -= sizeof(indx_t);
2978 mp->mp_upper += ksize - sizeof(indx_t);
2982 node = NODEPTR(mp, indx);
2983 sz = NODESIZE + node->mn_ksize;
2985 if (F_ISSET(node->mn_flags, F_BIGDATA))
2986 sz += sizeof(pgno_t);
2988 sz += NODEDSZ(node);
2991 ptr = mp->mp_ptrs[indx];
2992 numkeys = NUMKEYS(mp);
2993 for (i = j = 0; i < numkeys; i++) {
2995 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2996 if (mp->mp_ptrs[i] < ptr)
2997 mp->mp_ptrs[j] += sz;
3002 base = (char *)mp + mp->mp_upper;
3003 memmove(base + sz, base, ptr - mp->mp_upper);
3005 mp->mp_lower -= sizeof(indx_t);
3010 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3015 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3016 mx->mx_txn.mt_dbs = mx->mx_dbs;
3017 mx->mx_dbxs[0] = txn->mt_dbxs[0];
3018 mx->mx_dbxs[1] = txn->mt_dbxs[1];
3020 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
3025 mx->mx_dbxs[dbn+1].md_parent = dbn;
3026 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3027 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3028 mx->mx_dbxs[dbn+1].md_dirty = 0;
3029 mx->mx_txn.mt_numdbs = dbn+2;
3031 mx->mx_cursor.mc_snum = 0;
3032 mx->mx_cursor.mc_txn = &mx->mx_txn;
3033 mx->mx_cursor.mc_dbi = dbn+1;
3037 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
3039 MDB_db *db = NODEDATA(node);
3041 mx->mx_dbs[0] = txn->mt_dbs[0];
3042 mx->mx_dbs[1] = txn->mt_dbs[1];
3044 mx->mx_dbs[2] = txn->mt_dbs[dbi];
3049 DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
3050 mx->mx_dbs[dbn] = *db;
3051 if (F_ISSET(mp->mp_flags, P_DIRTY))
3052 mx->mx_dbxs[dbn].md_dirty = 1;
3053 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3054 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3055 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
3056 mx->mx_txn.mt_u = txn->mt_u;
3057 mx->mx_cursor.mc_initialized = 0;
3058 mx->mx_cursor.mc_eof = 0;
3062 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3064 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3065 txn->mt_u = mx->mx_txn.mt_u;
3066 txn->mt_dbs[0] = mx->mx_dbs[0];
3067 txn->mt_dbs[1] = mx->mx_dbs[1];
3068 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
3069 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
3071 txn->mt_dbs[dbi] = mx->mx_dbs[2];
3072 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3077 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3080 size_t size = sizeof(MDB_cursor);
3082 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3085 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3086 size += sizeof(MDB_xcursor);
3088 if ((cursor = calloc(1, size)) != NULL) {
3089 cursor->mc_dbi = dbi;
3090 cursor->mc_txn = txn;
3091 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3092 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
3093 cursor->mc_xcursor = mx;
3094 mdb_xcursor_init0(txn, dbi, mx);
3105 /* Return the count of duplicate data items for the current key */
3107 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3112 if (mc == NULL || countp == NULL)
3115 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3118 top = CURSOR_TOP(mc);
3119 leaf = NODEPTR(top->mp_page, top->mp_ki);
3120 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3123 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
3126 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3132 mdb_cursor_close(MDB_cursor *cursor)
3134 if (cursor != NULL) {
3140 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3142 indx_t ptr, i, numkeys;
3149 node = NODEPTR(mp, indx);
3150 ptr = mp->mp_ptrs[indx];
3151 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3153 (int)node->mn_ksize, (char *)NODEKEY(node),
3157 delta = key->mv_size - node->mn_ksize;
3159 if (delta > 0 && SIZELEFT(mp) < delta) {
3160 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3164 numkeys = NUMKEYS(mp);
3165 for (i = 0; i < numkeys; i++) {
3166 if (mp->mp_ptrs[i] <= ptr)
3167 mp->mp_ptrs[i] -= delta;
3170 base = (char *)mp + mp->mp_upper;
3171 len = ptr - mp->mp_upper + NODESIZE;
3172 memmove(base - delta, base, len);
3173 mp->mp_upper -= delta;
3175 node = NODEPTR(mp, indx);
3176 node->mn_ksize = key->mv_size;
3179 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3184 /* Move a node from src to dst.
3187 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
3188 MDB_pageparent *dst, indx_t dstindx)
3195 /* Mark src and dst as dirty. */
3196 if ((rc = mdb_touch(txn, dbi, src)) ||
3197 (rc = mdb_touch(txn, dbi, dst)))
3200 if (IS_LEAF2(src->mp_page)) {
3201 srcnode = NODEPTR(src->mp_page, 0); /* fake */
3202 key.mv_size = txn->mt_dbs[dbi].md_pad;
3203 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3205 data.mv_data = NULL;
3207 srcnode = NODEPTR(src->mp_page, srcindx);
3208 key.mv_size = NODEKSZ(srcnode);
3209 key.mv_data = NODEKEY(srcnode);
3210 data.mv_size = NODEDSZ(srcnode);
3211 data.mv_data = NODEDATA(srcnode);
3213 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3214 IS_LEAF(src->mp_page) ? "leaf" : "branch",
3217 src->mp_page->mp_pgno,
3218 dstindx, dst->mp_page->mp_pgno);
3220 /* Add the node to the destination page.
3222 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
3224 if (rc != MDB_SUCCESS)
3227 /* Delete the node from the source page.
3229 mdb_del_node(src->mp_page, srcindx, key.mv_size);
3231 /* The key value just changed due to del_node, find it again.
3233 if (!IS_LEAF2(src->mp_page)) {
3234 srcnode = NODEPTR(src->mp_page, srcindx);
3235 key.mv_data = NODEKEY(srcnode);
3238 /* Update the parent separators.
3241 if (src->mp_pi != 0) {
3242 DPRINTF("update separator for source page %lu to [%s]",
3243 src->mp_page->mp_pgno, DKEY(&key));
3244 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
3245 &key)) != MDB_SUCCESS)
3248 if (IS_BRANCH(src->mp_page)) {
3250 nullkey.mv_size = 0;
3251 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
3256 if (dst->mp_pi != 0) {
3257 DPRINTF("update separator for destination page %lu to [%s]",
3258 dst->mp_page->mp_pgno, DKEY(&key));
3259 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
3260 &key)) != MDB_SUCCESS)
3263 if (IS_BRANCH(dst->mp_page)) {
3265 nullkey.mv_size = 0;
3266 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
3274 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
3283 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
3285 assert(txn != NULL);
3286 assert(src->mp_parent); /* can't merge root page */
3287 assert(dst->mp_parent);
3289 /* Mark src and dst as dirty. */
3290 if ((rc = mdb_touch(txn, dbi, src)) ||
3291 (rc = mdb_touch(txn, dbi, dst)))
3294 /* Move all nodes from src to dst.
3296 if (IS_LEAF2(src->mp_page)) {
3297 key.mv_size = txn->mt_dbs[dbi].md_pad;
3298 key.mv_data = METADATA(src->mp_page);
3299 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3300 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3302 if (rc != MDB_SUCCESS)
3304 key.mv_data = (char *)key.mv_data + key.mv_size;
3307 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3308 srcnode = NODEPTR(src->mp_page, i);
3310 key.mv_size = srcnode->mn_ksize;
3311 key.mv_data = NODEKEY(srcnode);
3312 data.mv_size = NODEDSZ(srcnode);
3313 data.mv_data = NODEDATA(srcnode);
3314 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3315 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3316 if (rc != MDB_SUCCESS)
3321 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3322 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3324 /* Unlink the src page from parent.
3326 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3327 if (src->mp_pi == 0) {
3329 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3333 if (IS_LEAF(src->mp_page))
3334 txn->mt_dbs[dbi].md_leaf_pages--;
3336 txn->mt_dbs[dbi].md_branch_pages--;
3338 mpp.mp_page = src->mp_parent;
3339 dh = (MDB_dhead *)src->mp_parent;
3341 mpp.mp_parent = dh->md_parent;
3342 mpp.mp_pi = dh->md_pi;
3344 return mdb_rebalance(txn, dbi, &mpp);
3347 #define FILL_THRESHOLD 250
3350 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3355 indx_t si = 0, di = 0;
3358 assert(txn != NULL);
3359 assert(mpp != NULL);
3361 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3362 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3363 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3365 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3366 DPRINTF("no need to rebalance page %lu, above fill threshold",
3367 mpp->mp_page->mp_pgno);
3371 if (mpp->mp_parent == NULL) {
3372 if (NUMKEYS(mpp->mp_page) == 0) {
3373 DPUTS("tree is completely empty");
3374 txn->mt_dbs[dbi].md_root = P_INVALID;
3375 txn->mt_dbs[dbi].md_depth = 0;
3376 txn->mt_dbs[dbi].md_leaf_pages = 0;
3377 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3378 DPUTS("collapsing root page!");
3379 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3380 if ((rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root)))
3382 txn->mt_dbs[dbi].md_depth--;
3383 txn->mt_dbs[dbi].md_branch_pages--;
3385 DPUTS("root page doesn't need rebalancing");
3389 /* The parent (branch page) must have at least 2 pointers,
3390 * otherwise the tree is invalid.
3392 assert(NUMKEYS(mpp->mp_parent) > 1);
3394 /* Leaf page fill factor is below the threshold.
3395 * Try to move keys from left or right neighbor, or
3396 * merge with a neighbor page.
3401 if (mpp->mp_pi == 0) {
3402 /* We're the leftmost leaf in our parent.
3404 DPUTS("reading right neighbor");
3405 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3406 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3408 npp.mp_pi = mpp->mp_pi + 1;
3410 di = NUMKEYS(mpp->mp_page);
3412 /* There is at least one neighbor to the left.
3414 DPUTS("reading left neighbor");
3415 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3416 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3418 npp.mp_pi = mpp->mp_pi - 1;
3419 si = NUMKEYS(npp.mp_page) - 1;
3422 npp.mp_parent = mpp->mp_parent;
3424 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3425 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3427 /* If the neighbor page is above threshold and has at least two
3428 * keys, move one key from it.
3430 * Otherwise we should try to merge them.
3432 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3433 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3434 else { /* FIXME: if (has_enough_room()) */
3435 if (mpp->mp_pi == 0)
3436 return mdb_merge(txn, dbi, &npp, mpp);
3438 return mdb_merge(txn, dbi, mpp, &npp);
3443 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3447 /* add overflow pages to free list */
3448 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3452 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3453 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3454 for (i=0; i<ovpages; i++) {
3455 DPRINTF("freed ov page %lu", pg);
3456 mdb_midl_insert(txn->mt_free_pgs, pg);
3460 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3461 txn->mt_dbs[dbi].md_entries--;
3462 rc = mdb_rebalance(txn, dbi, mpp);
3463 if (rc != MDB_SUCCESS)
3464 txn->mt_flags |= MDB_TXN_ERROR;
3470 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3471 MDB_val *key, MDB_val *data)
3479 assert(key != NULL);
3481 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3483 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3486 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3490 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3494 mpp.mp_parent = NULL;
3496 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3499 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3500 if (leaf == NULL || !exact) {
3501 return MDB_NOTFOUND;
3504 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3508 mdb_xcursor_init0(txn, dbi, &mx);
3509 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3511 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL);
3512 mdb_xcursor_fini(txn, dbi, &mx);
3513 /* If sub-DB still has entries, we're done */
3514 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3515 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3517 txn->mt_dbs[dbi].md_entries--;
3520 /* otherwise fall thru and delete the sub-DB */
3522 /* add all the child DB's pages to the free list */
3523 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3524 NULL, &mx.mx_cursor, 0, &mp2);
3525 if (rc == MDB_SUCCESS) {
3526 MDB_ppage *top, *parent;
3530 cursor_pop_page(&mx.mx_cursor);
3531 if (mx.mx_cursor.mc_snum) {
3532 top = CURSOR_TOP(&mx.mx_cursor);
3533 while (mx.mx_cursor.mc_snum > 1) {
3534 parent = CURSOR_PARENT(&mx.mx_cursor);
3535 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3536 ni = NODEPTR(top->mp_page, i);
3537 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3540 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3541 cursor_pop_page(&mx.mx_cursor);
3544 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3545 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3549 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3554 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3557 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3558 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3559 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3560 * refer to a node in the new right sibling page.
3563 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3564 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3567 int rc = MDB_SUCCESS, ins_new = 0;
3570 unsigned int i, j, split_indx, nkeys, pmax;
3572 MDB_val sepkey, rkey, rdata;
3573 MDB_page *copy, *cptr;
3574 MDB_dpage *mdp, *rdp, *pdp;
3578 assert(txn != NULL);
3580 dh = ((MDB_dhead *)*mpp) - 1;
3581 mdp = (MDB_dpage *)dh;
3582 newindx = *newindxp;
3584 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3585 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3586 DKEY(newkey), *newindxp);
3588 if (mdp->h.md_parent == NULL) {
3589 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3592 mdp->h.md_parent = &pdp->p;
3593 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3594 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3595 txn->mt_dbs[dbi].md_depth++;
3597 /* Add left (implicit) pointer. */
3598 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3599 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3602 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3605 /* Create a right sibling. */
3606 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3608 rdp->h.md_parent = mdp->h.md_parent;
3609 rdp->h.md_pi = mdp->h.md_pi + 1;
3610 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3612 nkeys = NUMKEYS(&mdp->p);
3613 split_indx = nkeys / 2 + 1;
3615 if (IS_LEAF2(&rdp->p)) {
3618 unsigned int lsize, rsize, ksize;
3619 /* Move half of the keys to the right sibling */
3621 x = *newindxp - split_indx;
3622 ksize = txn->mt_dbs[dbi].md_pad;
3623 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3624 rsize = (nkeys - split_indx) * ksize;
3625 lsize = (nkeys - split_indx) * sizeof(indx_t);
3626 mdp->p.mp_lower -= lsize;
3627 rdp->p.mp_lower += lsize;
3628 mdp->p.mp_upper += rsize - lsize;
3629 rdp->p.mp_upper -= rsize - lsize;
3630 sepkey.mv_size = ksize;
3631 if (newindx == split_indx) {
3632 sepkey.mv_data = newkey->mv_data;
3634 sepkey.mv_data = split;
3637 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3638 memcpy(&rdp->p.mp_ptrs, split, rsize);
3639 sepkey.mv_data = &rdp->p.mp_ptrs;
3640 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3641 memcpy(ins, newkey->mv_data, ksize);
3642 mdp->p.mp_lower += sizeof(indx_t);
3643 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3646 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3647 ins = LEAF2KEY(&rdp->p, x, ksize);
3648 memcpy(ins, newkey->mv_data, ksize);
3649 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3650 rdp->p.mp_lower += sizeof(indx_t);
3651 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3658 /* For leaf pages, check the split point based on what
3659 * fits where, since otherwise add_node can fail.
3661 if (IS_LEAF(&mdp->p)) {
3662 unsigned int psize, nsize;
3663 /* Maximum free space in an empty page */
3664 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
3665 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
3666 if (newindx < split_indx) {
3668 for (i=0; i<split_indx; i++) {
3669 node = NODEPTR(&mdp->p, i);
3670 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
3671 if (F_ISSET(node->mn_flags, F_BIGDATA))
3672 psize += sizeof(pgno_t);
3674 psize += NODEDSZ(node);
3682 for (i=nkeys-1; i>=split_indx; i--) {
3683 node = NODEPTR(&mdp->p, i);
3684 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
3685 if (F_ISSET(node->mn_flags, F_BIGDATA))
3686 psize += sizeof(pgno_t);
3688 psize += NODEDSZ(node);
3697 /* First find the separating key between the split pages.
3699 memset(&sepkey, 0, sizeof(sepkey));
3700 if (newindx == split_indx) {
3701 sepkey.mv_size = newkey->mv_size;
3702 sepkey.mv_data = newkey->mv_data;
3704 node = NODEPTR(&mdp->p, split_indx);
3705 sepkey.mv_size = node->mn_ksize;
3706 sepkey.mv_data = NODEKEY(node);
3710 DPRINTF("separator is [%s]", DKEY(&sepkey));
3712 /* Copy separator key to the parent.
3714 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3715 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3716 &sepkey, NULL, rdp->p.mp_pgno);
3718 /* Right page might now have changed parent.
3719 * Check if left page also changed parent.
3721 if (rdp->h.md_parent != mdp->h.md_parent &&
3722 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3723 mdp->h.md_parent = rdp->h.md_parent;
3724 mdp->h.md_pi = rdp->h.md_pi - 1;
3727 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3728 &sepkey, NULL, rdp->p.mp_pgno, 0);
3730 if (IS_LEAF2(&rdp->p)) {
3733 if (rc != MDB_SUCCESS) {
3737 /* Move half of the keys to the right sibling. */
3738 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3741 copy->mp_pgno = mdp->p.mp_pgno;
3742 copy->mp_flags = mdp->p.mp_flags;
3743 copy->mp_lower = PAGEHDRSZ;
3744 copy->mp_upper = txn->mt_env->me_psize;
3746 for (i = j = 0; i <= nkeys; j++) {
3747 if (i == split_indx) {
3748 /* Insert in right sibling. */
3749 /* Reset insert index for right sibling. */
3750 j = (i == newindx && ins_new);
3754 if (i == newindx && !ins_new) {
3755 /* Insert the original entry that caused the split. */
3756 rkey.mv_data = newkey->mv_data;
3757 rkey.mv_size = newkey->mv_size;
3758 if (IS_LEAF(&mdp->p)) {
3759 rdata.mv_data = newdata->mv_data;
3760 rdata.mv_size = newdata->mv_size;
3767 /* Update page and index for the new key. */
3769 if (cptr == &rdp->p)
3771 } else if (i == nkeys) {
3774 node = NODEPTR(&mdp->p, i);
3775 rkey.mv_data = NODEKEY(node);
3776 rkey.mv_size = node->mn_ksize;
3777 if (IS_LEAF(&mdp->p)) {
3778 rdata.mv_data = NODEDATA(node);
3779 rdata.mv_size = node->mn_dsize;
3781 pgno = NODEPGNO(node);
3782 flags = node->mn_flags;
3787 if (!IS_LEAF(&mdp->p) && j == 0) {
3788 /* First branch index doesn't need key data. */
3792 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
3794 nkeys = NUMKEYS(copy);
3795 for (i=0; i<nkeys; i++)
3796 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
3797 mdp->p.mp_lower = copy->mp_lower;
3798 mdp->p.mp_upper = copy->mp_upper;
3799 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
3800 txn->mt_env->me_psize - copy->mp_upper);
3807 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3808 MDB_val *key, MDB_val *data, unsigned int flags)
3810 int rc = MDB_SUCCESS, exact;
3814 MDB_val xdata, *rdata, dkey;
3816 char dbuf[PAGESIZE];
3821 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3822 dbi, DKEY(key), key->mv_size, data->mv_size);
3825 mpp.mp_parent = NULL;
3827 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3828 if (rc == MDB_SUCCESS) {
3829 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3830 if (leaf && exact) {
3831 if (flags == MDB_NOOVERWRITE) {
3832 DPRINTF("duplicate key [%s]", DKEY(key));
3833 return MDB_KEYEXIST;
3835 /* there's only a key anyway, so this is a no-op */
3836 if (IS_LEAF2(mpp.mp_page))
3839 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3840 /* Was a single item before, must convert now */
3841 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3842 dkey.mv_size = NODEDSZ(leaf);
3843 dkey.mv_data = dbuf;
3844 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3845 /* data matches, ignore it */
3846 if (!mdb_dcmp(txn, dbi, data, &dkey))
3847 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3848 memset(&dummy, 0, sizeof(dummy));
3849 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3850 dummy.md_pad = data->mv_size;
3851 dummy.md_flags = MDB_DUPFIXED;
3852 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3853 dummy.md_flags |= MDB_INTEGERKEY;
3855 dummy.md_root = P_INVALID;
3856 if (dkey.mv_size == sizeof(MDB_db)) {
3857 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3860 mdb_del_node(mpp.mp_page, ki, 0);
3863 xdata.mv_size = sizeof(MDB_db);
3864 xdata.mv_data = &dummy;
3869 /* same size, just replace it */
3870 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3871 NODEDSZ(leaf) == data->mv_size) {
3872 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3875 mdb_del_node(mpp.mp_page, ki, 0);
3877 if (leaf == NULL) { /* append if not found */
3878 ki = NUMKEYS(mpp.mp_page);
3879 DPRINTF("appending key at index %i", ki);
3881 } else if (rc == MDB_NOTFOUND) {
3883 /* new file, just write a root leaf page */
3884 DPUTS("allocating new root leaf page");
3885 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3888 mpp.mp_page = &dp->p;
3889 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3890 txn->mt_dbs[dbi].md_depth++;
3891 txn->mt_dbxs[dbi].md_dirty = 1;
3892 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3893 mpp.mp_page->mp_flags |= P_LEAF2;
3899 assert(IS_LEAF(mpp.mp_page));
3900 DPRINTF("there are %u keys, should insert new key at index %i",
3901 NUMKEYS(mpp.mp_page), ki);
3906 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3907 if (SIZELEFT(mpp.mp_page) < nsize) {
3908 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3910 /* There is room already in this leaf page. */
3911 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3914 if (rc != MDB_SUCCESS)
3915 txn->mt_flags |= MDB_TXN_ERROR;
3917 /* Remember if we just added a subdatabase */
3918 if (flags & F_SUBDATA) {
3919 leaf = NODEPTR(mpp.mp_page, ki);
3920 leaf->mn_flags |= F_SUBDATA;
3923 /* Now store the actual data in the child DB. Note that we're
3924 * storing the user data in the keys field, so there are strict
3925 * size limits on dupdata. The actual data fields of the child
3926 * DB are all zero size.
3931 leaf = NODEPTR(mpp.mp_page, ki);
3933 mdb_xcursor_init0(txn, dbi, &mx);
3934 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3937 if (flags == MDB_NODUPDATA)
3938 flags = MDB_NOOVERWRITE;
3939 /* converted, write the original data first */
3941 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3943 leaf->mn_flags |= F_DUPDATA;
3945 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3946 mdb_xcursor_fini(txn, dbi, &mx);
3947 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3950 txn->mt_dbs[dbi].md_entries++;
3958 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3959 MDB_val *key, MDB_val *data, unsigned int flags)
3961 assert(key != NULL);
3962 assert(data != NULL);
3964 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3967 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3971 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3975 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3978 return mdb_put0(txn, dbi, key, data, flags);
3982 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3984 #define CHANGEABLE (MDB_NOSYNC)
3985 if ((flag & CHANGEABLE) != flag)
3988 env->me_flags |= flag;
3990 env->me_flags &= ~flag;
3995 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4000 *arg = env->me_flags;
4005 mdb_env_get_path(MDB_env *env, const char **arg)
4010 *arg = env->me_path;
4015 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4017 arg->ms_psize = env->me_psize;
4018 arg->ms_depth = db->md_depth;
4019 arg->ms_branch_pages = db->md_branch_pages;
4020 arg->ms_leaf_pages = db->md_leaf_pages;
4021 arg->ms_overflow_pages = db->md_overflow_pages;
4022 arg->ms_entries = db->md_entries;
4027 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4031 if (env == NULL || arg == NULL)
4034 mdb_env_read_meta(env, &toggle);
4036 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4039 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4049 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4050 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4054 /* Is the DB already open? */
4056 for (i=2; i<txn->mt_numdbs; i++) {
4057 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4058 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4064 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4067 /* Find the DB info */
4069 key.mv_data = (void *)name;
4070 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4072 /* Create if requested */
4073 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4075 data.mv_size = sizeof(MDB_db);
4076 data.mv_data = &dummy;
4077 memset(&dummy, 0, sizeof(dummy));
4078 dummy.md_root = P_INVALID;
4079 dummy.md_flags = flags & 0xffff;
4080 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
4084 /* OK, got info, add to table */
4085 if (rc == MDB_SUCCESS) {
4086 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4087 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4088 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
4089 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
4090 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4091 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4092 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4093 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4094 *dbi = txn->mt_numdbs;
4095 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4096 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4103 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4105 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4108 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4111 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4114 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4116 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4117 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4118 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4122 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4124 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4127 txn->mt_dbxs[dbi].md_cmp = cmp;
4131 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4133 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4136 txn->mt_dbxs[dbi].md_dcmp = cmp;
4140 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4142 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4145 txn->mt_dbxs[dbi].md_rel = rel;