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) {
2586 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2587 if (rc != MDB_SUCCESS)
2590 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2592 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2594 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2596 if (op == MDB_GET_BOTH || rc > 0)
2597 return MDB_NOTFOUND;
2601 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2606 /* The key already matches in all other cases */
2607 if (op == MDB_SET_RANGE)
2608 MDB_SET_KEY(leaf, key);
2609 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2615 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2621 cursor->mc_snum = 0;
2623 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2624 if (rc != MDB_SUCCESS)
2626 assert(IS_LEAF(mpp.mp_page));
2628 leaf = NODEPTR(mpp.mp_page, 0);
2629 cursor->mc_initialized = 1;
2632 if (IS_LEAF2(mpp.mp_page)) {
2633 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2634 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2639 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2640 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2641 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2645 if (cursor->mc_xcursor)
2646 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2647 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2651 MDB_SET_KEY(leaf, key);
2656 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2664 cursor->mc_snum = 0;
2666 lkey.mv_size = MAXKEYSIZE+1;
2667 lkey.mv_data = NULL;
2669 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2670 if (rc != MDB_SUCCESS)
2672 assert(IS_LEAF(mpp.mp_page));
2674 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2675 cursor->mc_initialized = 1;
2678 top = CURSOR_TOP(cursor);
2679 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2681 if (IS_LEAF2(mpp.mp_page)) {
2682 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2683 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2688 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2689 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2690 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2694 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2699 MDB_SET_KEY(leaf, key);
2704 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2714 case MDB_GET_BOTH_RANGE:
2715 if (data == NULL || cursor->mc_xcursor == NULL) {
2722 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2724 } else if (op == MDB_SET_RANGE)
2725 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2727 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2729 case MDB_GET_MULTIPLE:
2731 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2732 !cursor->mc_initialized) {
2737 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2740 case MDB_NEXT_MULTIPLE:
2742 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2746 if (!cursor->mc_initialized)
2747 rc = mdb_cursor_first(cursor, key, data);
2749 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2750 if (rc == MDB_SUCCESS) {
2751 if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2754 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2755 data->mv_size = NUMKEYS(top->mp_page) *
2756 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2757 data->mv_data = METADATA(top->mp_page);
2758 top->mp_ki = NUMKEYS(top->mp_page)-1;
2766 case MDB_NEXT_NODUP:
2767 if (!cursor->mc_initialized)
2768 rc = mdb_cursor_first(cursor, key, data);
2770 rc = mdb_cursor_next(cursor, key, data, op);
2774 case MDB_PREV_NODUP:
2775 if (!cursor->mc_initialized || cursor->mc_eof)
2776 rc = mdb_cursor_last(cursor, key, data);
2778 rc = mdb_cursor_prev(cursor, key, data, op);
2781 rc = mdb_cursor_first(cursor, key, data);
2784 rc = mdb_cursor_last(cursor, key, data);
2787 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2795 /* Allocate a page and initialize it
2798 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2802 if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
2804 DPRINTF("allocated new mpage %lu, page size %u",
2805 dp->p.mp_pgno, txn->mt_env->me_psize);
2806 dp->p.mp_flags = flags | P_DIRTY;
2807 dp->p.mp_lower = PAGEHDRSZ;
2808 dp->p.mp_upper = txn->mt_env->me_psize;
2810 if (IS_BRANCH(&dp->p))
2811 txn->mt_dbs[dbi].md_branch_pages++;
2812 else if (IS_LEAF(&dp->p))
2813 txn->mt_dbs[dbi].md_leaf_pages++;
2814 else if (IS_OVERFLOW(&dp->p)) {
2815 txn->mt_dbs[dbi].md_overflow_pages += num;
2816 dp->p.mp_pages = num;
2823 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2827 sz = LEAFSIZE(key, data);
2828 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2829 /* put on overflow page */
2830 sz -= data->mv_size - sizeof(pgno_t);
2833 return sz + sizeof(indx_t);
2837 mdb_branch_size(MDB_env *env, MDB_val *key)
2842 if (sz >= env->me_psize / MDB_MINKEYS) {
2843 /* put on overflow page */
2844 /* not implemented */
2845 /* sz -= key->size - sizeof(pgno_t); */
2848 return sz + sizeof(indx_t);
2852 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2853 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2856 size_t node_size = NODESIZE;
2859 MDB_dpage *ofp = NULL; /* overflow page */
2862 assert(mp->mp_upper >= mp->mp_lower);
2864 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
2865 IS_LEAF(mp) ? "leaf" : "branch",
2866 mp->mp_pgno, indx, data ? data->mv_size : 0,
2867 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
2870 /* Move higher keys up one slot. */
2871 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2872 char *ptr = LEAF2KEY(mp, indx, ksize);
2873 dif = NUMKEYS(mp) - indx;
2875 memmove(ptr+ksize, ptr, dif*ksize);
2876 /* insert new key */
2877 memcpy(ptr, key->mv_data, ksize);
2879 /* Just using these for counting */
2880 mp->mp_lower += sizeof(indx_t);
2881 mp->mp_upper -= ksize - sizeof(indx_t);
2886 node_size += key->mv_size;
2890 if (F_ISSET(flags, F_BIGDATA)) {
2891 /* Data already on overflow page. */
2892 node_size += sizeof(pgno_t);
2893 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2894 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2895 /* Put data on overflow page. */
2896 DPRINTF("data size is %zu, put on overflow page",
2898 node_size += sizeof(pgno_t);
2899 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2901 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2904 node_size += data->mv_size;
2908 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2909 DPRINTF("not enough room in page %lu, got %u ptrs",
2910 mp->mp_pgno, NUMKEYS(mp));
2911 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2912 mp->mp_upper - mp->mp_lower);
2913 DPRINTF("node size = %zu", node_size);
2917 /* Move higher pointers up one slot. */
2918 for (i = NUMKEYS(mp); i > indx; i--)
2919 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2921 /* Adjust free space offsets. */
2922 ofs = mp->mp_upper - node_size;
2923 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2924 mp->mp_ptrs[indx] = ofs;
2926 mp->mp_lower += sizeof(indx_t);
2928 /* Write the node data. */
2929 node = NODEPTR(mp, indx);
2930 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2931 node->mn_flags = flags;
2933 node->mn_dsize = data->mv_size;
2935 NODEPGNO(node) = pgno;
2938 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2943 if (F_ISSET(flags, F_BIGDATA))
2944 memcpy(node->mn_data + key->mv_size, data->mv_data,
2947 memcpy(node->mn_data + key->mv_size, data->mv_data,
2950 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2952 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2960 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2963 indx_t i, j, numkeys, ptr;
2967 DPRINTF("delete node %u on %s page %lu", indx,
2968 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2969 assert(indx < NUMKEYS(mp));
2972 int x = NUMKEYS(mp) - 1 - indx;
2973 base = LEAF2KEY(mp, indx, ksize);
2975 memmove(base, base + ksize, x * ksize);
2976 mp->mp_lower -= sizeof(indx_t);
2977 mp->mp_upper += ksize - sizeof(indx_t);
2981 node = NODEPTR(mp, indx);
2982 sz = NODESIZE + node->mn_ksize;
2984 if (F_ISSET(node->mn_flags, F_BIGDATA))
2985 sz += sizeof(pgno_t);
2987 sz += NODEDSZ(node);
2990 ptr = mp->mp_ptrs[indx];
2991 numkeys = NUMKEYS(mp);
2992 for (i = j = 0; i < numkeys; i++) {
2994 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2995 if (mp->mp_ptrs[i] < ptr)
2996 mp->mp_ptrs[j] += sz;
3001 base = (char *)mp + mp->mp_upper;
3002 memmove(base + sz, base, ptr - mp->mp_upper);
3004 mp->mp_lower -= sizeof(indx_t);
3009 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3014 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3015 mx->mx_txn.mt_dbs = mx->mx_dbs;
3016 mx->mx_dbxs[0] = txn->mt_dbxs[0];
3017 mx->mx_dbxs[1] = txn->mt_dbxs[1];
3019 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
3024 mx->mx_dbxs[dbn+1].md_parent = dbn;
3025 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3026 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3027 mx->mx_dbxs[dbn+1].md_dirty = 0;
3028 mx->mx_txn.mt_numdbs = dbn+2;
3030 mx->mx_cursor.mc_snum = 0;
3031 mx->mx_cursor.mc_txn = &mx->mx_txn;
3032 mx->mx_cursor.mc_dbi = dbn+1;
3036 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
3038 MDB_db *db = NODEDATA(node);
3040 mx->mx_dbs[0] = txn->mt_dbs[0];
3041 mx->mx_dbs[1] = txn->mt_dbs[1];
3043 mx->mx_dbs[2] = txn->mt_dbs[dbi];
3048 DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
3049 mx->mx_dbs[dbn] = *db;
3050 if (F_ISSET(mp->mp_flags, P_DIRTY))
3051 mx->mx_dbxs[dbn].md_dirty = 1;
3052 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3053 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3054 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
3055 mx->mx_txn.mt_u = txn->mt_u;
3056 mx->mx_cursor.mc_initialized = 0;
3057 mx->mx_cursor.mc_eof = 0;
3061 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3063 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3064 txn->mt_u = mx->mx_txn.mt_u;
3065 txn->mt_dbs[0] = mx->mx_dbs[0];
3066 txn->mt_dbs[1] = mx->mx_dbs[1];
3067 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
3068 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
3070 txn->mt_dbs[dbi] = mx->mx_dbs[2];
3071 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3076 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3079 size_t size = sizeof(MDB_cursor);
3081 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3084 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3085 size += sizeof(MDB_xcursor);
3087 if ((cursor = calloc(1, size)) != NULL) {
3088 cursor->mc_dbi = dbi;
3089 cursor->mc_txn = txn;
3090 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3091 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
3092 cursor->mc_xcursor = mx;
3093 mdb_xcursor_init0(txn, dbi, mx);
3104 /* Return the count of duplicate data items for the current key */
3106 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3111 if (mc == NULL || countp == NULL)
3114 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3117 top = CURSOR_TOP(mc);
3118 leaf = NODEPTR(top->mp_page, top->mp_ki);
3119 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3122 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
3125 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3131 mdb_cursor_close(MDB_cursor *cursor)
3133 if (cursor != NULL) {
3139 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3141 indx_t ptr, i, numkeys;
3148 node = NODEPTR(mp, indx);
3149 ptr = mp->mp_ptrs[indx];
3150 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3152 (int)node->mn_ksize, (char *)NODEKEY(node),
3156 delta = key->mv_size - node->mn_ksize;
3158 if (delta > 0 && SIZELEFT(mp) < delta) {
3159 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3163 numkeys = NUMKEYS(mp);
3164 for (i = 0; i < numkeys; i++) {
3165 if (mp->mp_ptrs[i] <= ptr)
3166 mp->mp_ptrs[i] -= delta;
3169 base = (char *)mp + mp->mp_upper;
3170 len = ptr - mp->mp_upper + NODESIZE;
3171 memmove(base - delta, base, len);
3172 mp->mp_upper -= delta;
3174 node = NODEPTR(mp, indx);
3175 node->mn_ksize = key->mv_size;
3178 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3183 /* Move a node from src to dst.
3186 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
3187 MDB_pageparent *dst, indx_t dstindx)
3194 /* Mark src and dst as dirty. */
3195 if ((rc = mdb_touch(txn, dbi, src)) ||
3196 (rc = mdb_touch(txn, dbi, dst)))
3199 if (IS_LEAF2(src->mp_page)) {
3200 srcnode = NODEPTR(src->mp_page, 0); /* fake */
3201 key.mv_size = txn->mt_dbs[dbi].md_pad;
3202 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3204 data.mv_data = NULL;
3206 srcnode = NODEPTR(src->mp_page, srcindx);
3207 key.mv_size = NODEKSZ(srcnode);
3208 key.mv_data = NODEKEY(srcnode);
3209 data.mv_size = NODEDSZ(srcnode);
3210 data.mv_data = NODEDATA(srcnode);
3212 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3213 IS_LEAF(src->mp_page) ? "leaf" : "branch",
3216 src->mp_page->mp_pgno,
3217 dstindx, dst->mp_page->mp_pgno);
3219 /* Add the node to the destination page.
3221 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
3223 if (rc != MDB_SUCCESS)
3226 /* Delete the node from the source page.
3228 mdb_del_node(src->mp_page, srcindx, key.mv_size);
3230 /* The key value just changed due to del_node, find it again.
3232 if (!IS_LEAF2(src->mp_page)) {
3233 srcnode = NODEPTR(src->mp_page, srcindx);
3234 key.mv_data = NODEKEY(srcnode);
3237 /* Update the parent separators.
3240 if (src->mp_pi != 0) {
3241 DPRINTF("update separator for source page %lu to [%s]",
3242 src->mp_page->mp_pgno, DKEY(&key));
3243 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
3244 &key)) != MDB_SUCCESS)
3247 if (IS_BRANCH(src->mp_page)) {
3249 nullkey.mv_size = 0;
3250 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
3255 if (dst->mp_pi != 0) {
3256 DPRINTF("update separator for destination page %lu to [%s]",
3257 dst->mp_page->mp_pgno, DKEY(&key));
3258 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
3259 &key)) != MDB_SUCCESS)
3262 if (IS_BRANCH(dst->mp_page)) {
3264 nullkey.mv_size = 0;
3265 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
3273 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
3282 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
3284 assert(txn != NULL);
3285 assert(src->mp_parent); /* can't merge root page */
3286 assert(dst->mp_parent);
3288 /* Mark src and dst as dirty. */
3289 if ((rc = mdb_touch(txn, dbi, src)) ||
3290 (rc = mdb_touch(txn, dbi, dst)))
3293 /* Move all nodes from src to dst.
3295 if (IS_LEAF2(src->mp_page)) {
3296 key.mv_size = txn->mt_dbs[dbi].md_pad;
3297 key.mv_data = METADATA(src->mp_page);
3298 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3299 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3301 if (rc != MDB_SUCCESS)
3303 key.mv_data = (char *)key.mv_data + key.mv_size;
3306 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3307 srcnode = NODEPTR(src->mp_page, i);
3309 key.mv_size = srcnode->mn_ksize;
3310 key.mv_data = NODEKEY(srcnode);
3311 data.mv_size = NODEDSZ(srcnode);
3312 data.mv_data = NODEDATA(srcnode);
3313 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3314 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3315 if (rc != MDB_SUCCESS)
3320 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3321 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3323 /* Unlink the src page from parent.
3325 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3326 if (src->mp_pi == 0) {
3328 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3332 if (IS_LEAF(src->mp_page))
3333 txn->mt_dbs[dbi].md_leaf_pages--;
3335 txn->mt_dbs[dbi].md_branch_pages--;
3337 mpp.mp_page = src->mp_parent;
3338 dh = (MDB_dhead *)src->mp_parent;
3340 mpp.mp_parent = dh->md_parent;
3341 mpp.mp_pi = dh->md_pi;
3343 return mdb_rebalance(txn, dbi, &mpp);
3346 #define FILL_THRESHOLD 250
3349 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3354 indx_t si = 0, di = 0;
3357 assert(txn != NULL);
3358 assert(mpp != NULL);
3360 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3361 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3362 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3364 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3365 DPRINTF("no need to rebalance page %lu, above fill threshold",
3366 mpp->mp_page->mp_pgno);
3370 if (mpp->mp_parent == NULL) {
3371 if (NUMKEYS(mpp->mp_page) == 0) {
3372 DPUTS("tree is completely empty");
3373 txn->mt_dbs[dbi].md_root = P_INVALID;
3374 txn->mt_dbs[dbi].md_depth = 0;
3375 txn->mt_dbs[dbi].md_leaf_pages = 0;
3376 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3377 DPUTS("collapsing root page!");
3378 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3379 if ((rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root)))
3381 txn->mt_dbs[dbi].md_depth--;
3382 txn->mt_dbs[dbi].md_branch_pages--;
3384 DPUTS("root page doesn't need rebalancing");
3388 /* The parent (branch page) must have at least 2 pointers,
3389 * otherwise the tree is invalid.
3391 assert(NUMKEYS(mpp->mp_parent) > 1);
3393 /* Leaf page fill factor is below the threshold.
3394 * Try to move keys from left or right neighbor, or
3395 * merge with a neighbor page.
3400 if (mpp->mp_pi == 0) {
3401 /* We're the leftmost leaf in our parent.
3403 DPUTS("reading right neighbor");
3404 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3405 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3407 npp.mp_pi = mpp->mp_pi + 1;
3409 di = NUMKEYS(mpp->mp_page);
3411 /* There is at least one neighbor to the left.
3413 DPUTS("reading left neighbor");
3414 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3415 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3417 npp.mp_pi = mpp->mp_pi - 1;
3418 si = NUMKEYS(npp.mp_page) - 1;
3421 npp.mp_parent = mpp->mp_parent;
3423 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3424 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3426 /* If the neighbor page is above threshold and has at least two
3427 * keys, move one key from it.
3429 * Otherwise we should try to merge them.
3431 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3432 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3433 else { /* FIXME: if (has_enough_room()) */
3434 if (mpp->mp_pi == 0)
3435 return mdb_merge(txn, dbi, &npp, mpp);
3437 return mdb_merge(txn, dbi, mpp, &npp);
3442 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3446 /* add overflow pages to free list */
3447 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3451 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3452 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3453 for (i=0; i<ovpages; i++) {
3454 DPRINTF("freed ov page %lu", pg);
3455 mdb_midl_insert(txn->mt_free_pgs, pg);
3459 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3460 txn->mt_dbs[dbi].md_entries--;
3461 rc = mdb_rebalance(txn, dbi, mpp);
3462 if (rc != MDB_SUCCESS)
3463 txn->mt_flags |= MDB_TXN_ERROR;
3469 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3470 MDB_val *key, MDB_val *data)
3478 assert(key != NULL);
3480 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3482 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3485 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3489 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3493 mpp.mp_parent = NULL;
3495 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3498 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3499 if (leaf == NULL || !exact) {
3500 return MDB_NOTFOUND;
3503 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3507 mdb_xcursor_init0(txn, dbi, &mx);
3508 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3510 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL);
3511 mdb_xcursor_fini(txn, dbi, &mx);
3512 /* If sub-DB still has entries, we're done */
3513 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3514 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3516 txn->mt_dbs[dbi].md_entries--;
3519 /* otherwise fall thru and delete the sub-DB */
3521 /* add all the child DB's pages to the free list */
3522 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3523 NULL, &mx.mx_cursor, 0, &mp2);
3524 if (rc == MDB_SUCCESS) {
3525 MDB_ppage *top, *parent;
3529 cursor_pop_page(&mx.mx_cursor);
3530 if (mx.mx_cursor.mc_snum) {
3531 top = CURSOR_TOP(&mx.mx_cursor);
3532 while (mx.mx_cursor.mc_snum > 1) {
3533 parent = CURSOR_PARENT(&mx.mx_cursor);
3534 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3535 ni = NODEPTR(top->mp_page, i);
3536 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3539 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3540 cursor_pop_page(&mx.mx_cursor);
3543 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3544 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3548 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3553 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3556 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3557 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3558 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3559 * refer to a node in the new right sibling page.
3562 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3563 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3566 int rc = MDB_SUCCESS, ins_new = 0;
3569 unsigned int i, j, split_indx, nkeys, pmax;
3571 MDB_val sepkey, rkey, rdata;
3572 MDB_page *copy, *cptr;
3573 MDB_dpage *mdp, *rdp, *pdp;
3577 assert(txn != NULL);
3579 dh = ((MDB_dhead *)*mpp) - 1;
3580 mdp = (MDB_dpage *)dh;
3581 newindx = *newindxp;
3583 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3584 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3585 DKEY(newkey), *newindxp);
3587 if (mdp->h.md_parent == NULL) {
3588 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3591 mdp->h.md_parent = &pdp->p;
3592 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3593 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3594 txn->mt_dbs[dbi].md_depth++;
3596 /* Add left (implicit) pointer. */
3597 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3598 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3601 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3604 /* Create a right sibling. */
3605 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3607 rdp->h.md_parent = mdp->h.md_parent;
3608 rdp->h.md_pi = mdp->h.md_pi + 1;
3609 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3611 nkeys = NUMKEYS(&mdp->p);
3612 split_indx = nkeys / 2 + 1;
3614 if (IS_LEAF2(&rdp->p)) {
3617 unsigned int lsize, rsize, ksize;
3618 /* Move half of the keys to the right sibling */
3620 x = *newindxp - split_indx;
3621 ksize = txn->mt_dbs[dbi].md_pad;
3622 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3623 rsize = (nkeys - split_indx) * ksize;
3624 lsize = (nkeys - split_indx) * sizeof(indx_t);
3625 mdp->p.mp_lower -= lsize;
3626 rdp->p.mp_lower += lsize;
3627 mdp->p.mp_upper += rsize - lsize;
3628 rdp->p.mp_upper -= rsize - lsize;
3629 sepkey.mv_size = ksize;
3630 if (newindx == split_indx) {
3631 sepkey.mv_data = newkey->mv_data;
3633 sepkey.mv_data = split;
3636 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3637 memcpy(&rdp->p.mp_ptrs, split, rsize);
3638 sepkey.mv_data = &rdp->p.mp_ptrs;
3639 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3640 memcpy(ins, newkey->mv_data, ksize);
3641 mdp->p.mp_lower += sizeof(indx_t);
3642 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3645 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3646 ins = LEAF2KEY(&rdp->p, x, ksize);
3647 memcpy(ins, newkey->mv_data, ksize);
3648 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3649 rdp->p.mp_lower += sizeof(indx_t);
3650 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3657 /* For leaf pages, check the split point based on what
3658 * fits where, since otherwise add_node can fail.
3660 if (IS_LEAF(&mdp->p)) {
3661 unsigned int psize, nsize;
3662 /* Maximum free space in an empty page */
3663 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
3664 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
3665 if (newindx <= split_indx) {
3668 for (i=0; i<split_indx; i++) {
3669 node = NODEPTR(&mdp->p, i);
3670 psize += NODESIZE + NODEKSZ(node);
3671 if (F_ISSET(node->mn_flags, F_BIGDATA))
3672 psize += sizeof(pgno_t);
3674 psize += NODEDSZ(node);
3683 for (i=split_indx; i<nkeys; i++) {
3684 node = NODEPTR(&mdp->p, i);
3685 psize += NODESIZE + NODEKSZ(node);
3686 if (F_ISSET(node->mn_flags, F_BIGDATA))
3687 psize += sizeof(pgno_t);
3689 psize += NODEDSZ(node);
3698 /* First find the separating key between the split pages.
3700 memset(&sepkey, 0, sizeof(sepkey));
3701 if (newindx == split_indx) {
3702 sepkey.mv_size = newkey->mv_size;
3703 sepkey.mv_data = newkey->mv_data;
3705 node = NODEPTR(&mdp->p, split_indx);
3706 sepkey.mv_size = node->mn_ksize;
3707 sepkey.mv_data = NODEKEY(node);
3711 DPRINTF("separator is [%s]", DKEY(&sepkey));
3713 /* Copy separator key to the parent.
3715 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3716 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3717 &sepkey, NULL, rdp->p.mp_pgno);
3719 /* Right page might now have changed parent.
3720 * Check if left page also changed parent.
3722 if (rdp->h.md_parent != mdp->h.md_parent &&
3723 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3724 mdp->h.md_parent = rdp->h.md_parent;
3725 mdp->h.md_pi = rdp->h.md_pi - 1;
3728 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3729 &sepkey, NULL, rdp->p.mp_pgno, 0);
3731 if (IS_LEAF2(&rdp->p)) {
3734 if (rc != MDB_SUCCESS) {
3738 /* Move half of the keys to the right sibling. */
3739 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3742 copy->mp_pgno = mdp->p.mp_pgno;
3743 copy->mp_flags = mdp->p.mp_flags;
3744 copy->mp_lower = PAGEHDRSZ;
3745 copy->mp_upper = txn->mt_env->me_psize;
3747 for (i = j = 0; i <= nkeys; j++) {
3748 if (i == split_indx) {
3749 /* Insert in right sibling. */
3750 /* Reset insert index for right sibling. */
3751 j = (i == newindx && ins_new);
3755 if (i == newindx && !ins_new) {
3756 /* Insert the original entry that caused the split. */
3757 rkey.mv_data = newkey->mv_data;
3758 rkey.mv_size = newkey->mv_size;
3759 if (IS_LEAF(&mdp->p)) {
3760 rdata.mv_data = newdata->mv_data;
3761 rdata.mv_size = newdata->mv_size;
3768 /* Update page and index for the new key. */
3770 if (cptr == &rdp->p)
3772 } else if (i == nkeys) {
3775 node = NODEPTR(&mdp->p, i);
3776 rkey.mv_data = NODEKEY(node);
3777 rkey.mv_size = node->mn_ksize;
3778 if (IS_LEAF(&mdp->p)) {
3779 rdata.mv_data = NODEDATA(node);
3780 rdata.mv_size = node->mn_dsize;
3782 pgno = NODEPGNO(node);
3783 flags = node->mn_flags;
3788 if (!IS_LEAF(&mdp->p) && j == 0) {
3789 /* First branch index doesn't need key data. */
3793 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
3795 nkeys = NUMKEYS(copy);
3796 for (i=0; i<nkeys; i++)
3797 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
3798 mdp->p.mp_lower = copy->mp_lower;
3799 mdp->p.mp_upper = copy->mp_upper;
3800 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
3801 txn->mt_env->me_psize - copy->mp_upper);
3808 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3809 MDB_val *key, MDB_val *data, unsigned int flags)
3811 int rc = MDB_SUCCESS, exact;
3815 MDB_val xdata, *rdata, dkey;
3817 char dbuf[PAGESIZE];
3822 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3823 dbi, DKEY(key), key->mv_size, data->mv_size);
3826 mpp.mp_parent = NULL;
3828 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3829 if (rc == MDB_SUCCESS) {
3830 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3831 if (leaf && exact) {
3832 if (flags == MDB_NOOVERWRITE) {
3833 DPRINTF("duplicate key [%s]", DKEY(key));
3834 return MDB_KEYEXIST;
3836 /* there's only a key anyway, so this is a no-op */
3837 if (IS_LEAF2(mpp.mp_page))
3840 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3841 /* Was a single item before, must convert now */
3842 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3843 dkey.mv_size = NODEDSZ(leaf);
3844 dkey.mv_data = dbuf;
3845 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3846 /* data matches, ignore it */
3847 if (!mdb_dcmp(txn, dbi, data, &dkey))
3848 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3849 memset(&dummy, 0, sizeof(dummy));
3850 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3851 dummy.md_pad = data->mv_size;
3852 dummy.md_flags = MDB_DUPFIXED;
3853 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3854 dummy.md_flags |= MDB_INTEGERKEY;
3856 dummy.md_root = P_INVALID;
3857 if (dkey.mv_size == sizeof(MDB_db)) {
3858 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3861 mdb_del_node(mpp.mp_page, ki, 0);
3864 xdata.mv_size = sizeof(MDB_db);
3865 xdata.mv_data = &dummy;
3870 /* same size, just replace it */
3871 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3872 NODEDSZ(leaf) == data->mv_size) {
3873 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3876 mdb_del_node(mpp.mp_page, ki, 0);
3878 if (leaf == NULL) { /* append if not found */
3879 ki = NUMKEYS(mpp.mp_page);
3880 DPRINTF("appending key at index %i", ki);
3882 } else if (rc == MDB_NOTFOUND) {
3884 /* new file, just write a root leaf page */
3885 DPUTS("allocating new root leaf page");
3886 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3889 mpp.mp_page = &dp->p;
3890 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3891 txn->mt_dbs[dbi].md_depth++;
3892 txn->mt_dbxs[dbi].md_dirty = 1;
3893 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3894 mpp.mp_page->mp_flags |= P_LEAF2;
3900 assert(IS_LEAF(mpp.mp_page));
3901 DPRINTF("there are %u keys, should insert new key at index %i",
3902 NUMKEYS(mpp.mp_page), ki);
3907 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3908 if (SIZELEFT(mpp.mp_page) < nsize) {
3909 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3911 /* There is room already in this leaf page. */
3912 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3915 if (rc != MDB_SUCCESS)
3916 txn->mt_flags |= MDB_TXN_ERROR;
3918 /* Remember if we just added a subdatabase */
3919 if (flags & F_SUBDATA) {
3920 leaf = NODEPTR(mpp.mp_page, ki);
3921 leaf->mn_flags |= F_SUBDATA;
3924 /* Now store the actual data in the child DB. Note that we're
3925 * storing the user data in the keys field, so there are strict
3926 * size limits on dupdata. The actual data fields of the child
3927 * DB are all zero size.
3932 leaf = NODEPTR(mpp.mp_page, ki);
3934 mdb_xcursor_init0(txn, dbi, &mx);
3935 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3938 if (flags == MDB_NODUPDATA)
3939 flags = MDB_NOOVERWRITE;
3940 /* converted, write the original data first */
3942 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3944 leaf->mn_flags |= F_DUPDATA;
3946 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3947 mdb_xcursor_fini(txn, dbi, &mx);
3948 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3951 txn->mt_dbs[dbi].md_entries++;
3959 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3960 MDB_val *key, MDB_val *data, unsigned int flags)
3962 assert(key != NULL);
3963 assert(data != NULL);
3965 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3968 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3972 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3976 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3979 return mdb_put0(txn, dbi, key, data, flags);
3983 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3985 #define CHANGEABLE (MDB_NOSYNC)
3986 if ((flag & CHANGEABLE) != flag)
3989 env->me_flags |= flag;
3991 env->me_flags &= ~flag;
3996 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4001 *arg = env->me_flags;
4006 mdb_env_get_path(MDB_env *env, const char **arg)
4011 *arg = env->me_path;
4016 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4018 arg->ms_psize = env->me_psize;
4019 arg->ms_depth = db->md_depth;
4020 arg->ms_branch_pages = db->md_branch_pages;
4021 arg->ms_leaf_pages = db->md_leaf_pages;
4022 arg->ms_overflow_pages = db->md_overflow_pages;
4023 arg->ms_entries = db->md_entries;
4028 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4032 if (env == NULL || arg == NULL)
4035 mdb_env_read_meta(env, &toggle);
4037 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4040 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4050 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4051 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4055 /* Is the DB already open? */
4057 for (i=2; i<txn->mt_numdbs; i++) {
4058 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4059 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4065 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4068 /* Find the DB info */
4070 key.mv_data = (void *)name;
4071 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4073 /* Create if requested */
4074 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4076 data.mv_size = sizeof(MDB_db);
4077 data.mv_data = &dummy;
4078 memset(&dummy, 0, sizeof(dummy));
4079 dummy.md_root = P_INVALID;
4080 dummy.md_flags = flags & 0xffff;
4081 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
4085 /* OK, got info, add to table */
4086 if (rc == MDB_SUCCESS) {
4087 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4088 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4089 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
4090 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
4091 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4092 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4093 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4094 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4095 *dbi = txn->mt_numdbs;
4096 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4097 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4104 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4106 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4109 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4112 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4115 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4117 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4118 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4119 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4123 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4125 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4128 txn->mt_dbxs[dbi].md_cmp = cmp;
4132 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4134 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4137 txn->mt_dbxs[dbi].md_dcmp = cmp;
4141 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4143 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4146 txn->mt_dbxs[dbi].md_rel = rel;