1 /* mdb.c - memory-mapped database library */
3 * Copyright 2011 Howard Chu, Symas Corp.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted only as authorized by the OpenLDAP
10 * A copy of this license is available in the file LICENSE in the
11 * top-level directory of the distribution or, alternatively, at
12 * <http://www.OpenLDAP.org/license.html>.
14 * This code is derived from btree.c written by Martin Hedenfalk.
16 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
18 * Permission to use, copy, modify, and distribute this software for any
19 * purpose with or without fee is hereby granted, provided that the above
20 * copyright notice and this permission notice appear in all copies.
22 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
23 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
24 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
25 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
27 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
28 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
30 #include <sys/types.h>
32 #include <sys/param.h>
35 #ifdef HAVE_SYS_FILE_H
53 #define ULONG unsigned long
58 /* Note: If O_DSYNC is undefined but exists in /usr/include,
59 * preferably set some compiler flag to get the definition.
60 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
63 # define MDB_DSYNC O_DSYNC
70 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
71 # define DPRINTF (void) /* Vararg macros may be unsupported */
73 # define DPRINTF(fmt, ...) /* Requires 2 or more args */ \
74 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
76 # define DPRINTF(fmt, ...) ((void) 0)
78 #define DPUTS(arg) DPRINTF("%s", arg)
82 #define MDB_MAGIC 0xBEEFC0DE
84 #define MAXKEYSIZE 511
86 #define KBUF (MAXKEYSIZE*2+1)
87 #define DKBUF char kbuf[KBUF]
88 #define DKEY(x) mdb_dkey(x, kbuf)
94 #define P_INVALID (~0UL)
96 #define F_ISSET(w, f) (((w) & (f)) == (f))
98 typedef uint16_t indx_t;
100 #define DEFAULT_READERS 126
101 #define DEFAULT_MAPSIZE 1048576
103 /* Lock descriptor stuff */
105 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
108 typedef struct MDB_rxbody {
114 typedef struct MDB_reader {
117 #define mr_txnid mru.mrx.mrb_txnid
118 #define mr_pid mru.mrx.mrb_pid
119 #define mr_tid mru.mrx.mrb_tid
120 /* cache line alignment */
121 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
125 typedef struct MDB_txbody {
127 uint32_t mtb_version;
128 pthread_mutex_t mtb_mutex;
130 uint32_t mtb_numreaders;
131 uint32_t mtb_me_toggle;
134 typedef struct MDB_txninfo {
137 #define mti_magic mt1.mtb.mtb_magic
138 #define mti_version mt1.mtb.mtb_version
139 #define mti_mutex mt1.mtb.mtb_mutex
140 #define mti_txnid mt1.mtb.mtb_txnid
141 #define mti_numreaders mt1.mtb.mtb_numreaders
142 #define mti_me_toggle mt1.mtb.mtb_me_toggle
143 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
146 pthread_mutex_t mt2_wmutex;
147 #define mti_wmutex mt2.mt2_wmutex
148 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
150 MDB_reader mti_readers[1];
153 /* Common header for all page types. Overflow pages
154 * occupy a number of contiguous pages with no
155 * headers on any page after the first.
157 typedef struct MDB_page { /* represents a page of storage */
158 #define mp_pgno mp_p.p_pgno
160 pgno_t p_pgno; /* page number */
161 void * p_align; /* for IL32P64 */
163 #define P_BRANCH 0x01 /* branch page */
164 #define P_LEAF 0x02 /* leaf page */
165 #define P_OVERFLOW 0x04 /* overflow page */
166 #define P_META 0x08 /* meta page */
167 #define P_DIRTY 0x10 /* dirty page */
168 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
170 #define mp_lower mp_pb.pb.pb_lower
171 #define mp_upper mp_pb.pb.pb_upper
172 #define mp_pages mp_pb.pb_pages
175 indx_t pb_lower; /* lower bound of free space */
176 indx_t pb_upper; /* upper bound of free space */
178 uint32_t pb_pages; /* number of overflow pages */
180 indx_t mp_ptrs[1]; /* dynamic size */
183 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
185 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
186 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
187 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
188 ((env)->me_psize - PAGEHDRSZ))
189 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
190 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
191 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
192 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
194 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
196 typedef struct MDB_db {
197 uint32_t md_pad; /* also ksize for LEAF2 pages */
200 ULONG md_branch_pages;
202 ULONG md_overflow_pages;
210 typedef struct MDB_meta { /* meta (footer) page content */
213 void *mm_address; /* address for fixed mapping */
214 size_t mm_mapsize; /* size of mmap region */
215 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
216 #define mm_psize mm_dbs[0].md_pad
217 #define mm_flags mm_dbs[0].md_flags
218 pgno_t mm_last_pg; /* last used page in file */
219 ULONG mm_txnid; /* txnid that committed this page */
222 typedef struct MDB_dhead { /* a dirty page */
224 unsigned md_pi; /* parent index */
228 typedef struct MDB_dpage {
233 typedef struct MDB_oldpages {
234 struct MDB_oldpages *mo_next;
236 pgno_t mo_pages[1]; /* dynamic */
239 typedef struct MDB_pageparent {
245 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
246 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
248 typedef struct MDB_ppage { /* ordered list of pages */
250 unsigned int mp_ki; /* cursor index on page */
253 #define CURSOR_TOP(c) (&(c)->mc_stack[(c)->mc_snum-1])
254 #define CURSOR_PARENT(c) (&(c)->mc_stack[(c)->mc_snum-2])
255 #define CURSOR_STACK 32
261 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
262 unsigned int mc_snum; /* number of pushed pages */
264 short mc_initialized; /* 1 if initialized */
265 short mc_eof; /* 1 if end is reached */
266 struct MDB_xcursor *mc_xcursor;
269 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
271 typedef struct MDB_node {
272 #define mn_pgno mn_p.np_pgno
273 #define mn_dsize mn_p.np_dsize
275 pgno_t np_pgno; /* child page number */
276 uint32_t np_dsize; /* leaf data size */
278 unsigned int mn_flags:4;
279 unsigned int mn_ksize:12; /* key size */
280 #define F_BIGDATA 0x01 /* data put on overflow page */
281 #define F_SUBDATA 0x02 /* data is a sub-database */
282 #define F_DUPDATA 0x04 /* data has duplicates */
286 typedef struct MDB_dbx {
288 MDB_cmp_func *md_cmp; /* user compare function */
289 MDB_cmp_func *md_dcmp; /* user dupsort function */
290 MDB_rel_func *md_rel; /* user relocate function */
292 unsigned int md_dirty;
296 pgno_t mt_next_pgno; /* next unallocated page */
300 pgno_t *mt_free_pgs; /* this is an IDL */
302 MIDL2 *dirty_list; /* modified pages */
305 MDB_dbx *mt_dbxs; /* array */
307 unsigned int mt_numdbs;
309 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
310 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
311 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
312 unsigned int mt_flags;
315 /* Context for sorted-dup records */
316 typedef struct MDB_xcursor {
317 MDB_cursor mx_cursor;
326 int me_mfd; /* just for writing the meta pages */
327 #define MDB_FATAL_ERROR 0x80000000U
329 uint32_t me_extrapad; /* unused for now */
330 unsigned int me_maxreaders;
331 unsigned int me_numdbs;
332 unsigned int me_maxdbs;
335 MDB_txninfo *me_txns;
336 MDB_meta *me_metas[2];
338 MDB_txn *me_txn; /* current write transaction */
340 off_t me_size; /* current file size */
341 pgno_t me_maxpg; /* me_mapsize / me_psize */
342 unsigned int me_psize;
343 unsigned int me_db_toggle;
344 MDB_dbx *me_dbxs; /* array */
346 MDB_oldpages *me_pghead;
347 pthread_key_t me_txkey; /* thread-key for readers */
348 MDB_dpage *me_dpages;
349 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
350 MIDL2 me_dirty_list[MDB_IDL_DB_SIZE];
353 #define NODESIZE offsetof(MDB_node, mn_data)
355 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
356 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
357 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
358 #define NODEKEY(node) (void *)((node)->mn_data)
359 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
360 #define NODEPGNO(node) ((node)->mn_pgno)
361 #define NODEDSZ(node) ((node)->mn_dsize)
362 #define NODEKSZ(node) ((node)->mn_ksize)
363 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
365 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
367 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
369 static int mdb_search_page_root(MDB_txn *txn,
370 MDB_dbi dbi, MDB_val *key,
371 MDB_cursor *cursor, int modify,
372 MDB_pageparent *mpp);
373 static int mdb_search_page(MDB_txn *txn,
374 MDB_dbi dbi, MDB_val *key,
375 MDB_cursor *cursor, int modify,
376 MDB_pageparent *mpp);
378 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
379 static int mdb_env_read_meta(MDB_env *env, int *which);
380 static int mdb_env_write_meta(MDB_txn *txn);
381 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
383 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
384 MDB_val *key, int *exactp, unsigned int *kip);
385 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
386 indx_t indx, MDB_val *key, MDB_val *data,
387 pgno_t pgno, uint8_t flags);
388 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
389 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
390 MDB_pageparent *mpp, MDB_node *leaf);
391 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
392 MDB_val *key, MDB_val *data, unsigned int flags);
393 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
395 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
396 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
397 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
398 MDB_pageparent *src, indx_t srcindx,
399 MDB_pageparent *dst, indx_t dstindx);
400 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
401 MDB_pageparent *dst);
402 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
403 unsigned int *newindxp, MDB_val *newkey,
404 MDB_val *newdata, pgno_t newpgno);
405 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
407 static void cursor_pop_page(MDB_cursor *cursor);
408 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
411 static int mdb_sibling(MDB_cursor *cursor, int move_right);
412 static int mdb_cursor_next(MDB_cursor *cursor,
413 MDB_val *key, MDB_val *data, MDB_cursor_op op);
414 static int mdb_cursor_prev(MDB_cursor *cursor,
415 MDB_val *key, MDB_val *data, MDB_cursor_op op);
416 static int mdb_cursor_set(MDB_cursor *cursor,
417 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
418 static int mdb_cursor_first(MDB_cursor *cursor,
419 MDB_val *key, MDB_val *data);
420 static int mdb_cursor_last(MDB_cursor *cursor,
421 MDB_val *key, MDB_val *data);
423 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
424 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx,
425 MDB_page *mp, MDB_node *node);
426 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
428 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
430 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
432 static int memncmp(const void *s1, size_t n1,
433 const void *s2, size_t n2);
434 static int memnrcmp(const void *s1, size_t n1,
435 const void *s2, size_t n2);
438 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
440 int diff, len_diff = -1;
443 len_diff = (n1 > n2);
446 diff = memcmp(s1, s2, n1);
447 return diff ? diff : len_diff;
451 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
453 const unsigned char *p1, *p2, *p1_lim;
460 p1 = (const unsigned char *)s1 + n1 - 1;
461 p2 = (const unsigned char *)s2 + n2 - 1;
463 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
465 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
471 mdb_version(int *maj, int *min, int *pat)
473 *maj = MDB_VERSION_MAJOR;
474 *min = MDB_VERSION_MINOR;
475 *pat = MDB_VERSION_PATCH;
476 return MDB_VERSION_STRING;
479 static char *const errstr[] = {
480 "MDB_KEYEXIST: Key/data pair already exists",
481 "MDB_NOTFOUND: No matching key/data pair found",
482 "MDB_PAGE_NOTFOUND: Requested page not found",
483 "MDB_CORRUPTED: Located page was wrong type",
484 "MDB_PANIC: Update of meta page failed",
485 "MDB_VERSION_MISMATCH: Database environment version mismatch"
489 mdb_strerror(int err)
492 return ("Successful return: 0");
494 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
495 return errstr[err - MDB_KEYEXIST];
497 return strerror(err);
501 mdb_dkey(MDB_val *key, char *buf)
504 unsigned char *c = key->mv_data;
506 if (key->mv_size > MAXKEYSIZE)
508 for (i=0; i<key->mv_size; i++)
509 ptr += sprintf(ptr, "%02x", *c++);
514 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
516 if (txn->mt_dbxs[dbi].md_cmp)
517 return txn->mt_dbxs[dbi].md_cmp(a, b);
519 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
520 #if __BYTE_ORDER == __LITTLE_ENDIAN
524 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
526 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
530 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
532 if (txn->mt_dbxs[dbi].md_dcmp)
533 return txn->mt_dbxs[dbi].md_dcmp(a, b);
535 if (txn->mt_dbs[dbi].md_flags & (0
536 #if __BYTE_ORDER == __LITTLE_ENDIAN
540 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
542 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
545 /* Allocate new page(s) for writing */
547 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
550 pgno_t pgno = P_INVALID;
554 if (txn->mt_txnid > 2) {
556 oldest = txn->mt_txnid - 2;
557 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
558 /* See if there's anything in the free DB */
563 mpp.mp_parent = NULL;
565 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
566 leaf = NODEPTR(mpp.mp_page, 0);
567 kptr = (ULONG *)NODEKEY(leaf);
569 /* It's potentially usable, unless there are still
570 * older readers outstanding. Grab it.
572 if (oldest > *kptr) {
577 mdb_read_data(txn, leaf, &data);
578 idl = (ULONG *)data.mv_data;
579 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
580 mop->mo_next = txn->mt_env->me_pghead;
581 mop->mo_txnid = *kptr;
582 txn->mt_env->me_pghead = mop;
583 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
588 DPRINTF("IDL read txn %lu root %lu num %lu",
589 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
590 for (i=0; i<idl[0]; i++) {
591 DPRINTF("IDL %lu", idl[i+1]);
595 /* drop this IDL from the DB */
596 mpp.mp_parent = NULL;
598 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
599 leaf = NODEPTR(mpp.mp_page, 0);
600 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
603 if (txn->mt_env->me_pghead) {
605 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
606 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
609 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
611 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
612 MDB_oldpages *mop = txn->mt_env->me_pghead;
613 txn->mt_oldest = oldest;
615 /* FIXME: For now, always use fresh pages. We
616 * really ought to search the free list for a
621 /* peel pages off tail, so we only have to truncate the list */
622 pgno = MDB_IDL_LAST(mop->mo_pages);
623 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
625 if (mop->mo_pages[2] > mop->mo_pages[1])
626 mop->mo_pages[0] = 0;
630 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
631 txn->mt_env->me_pghead = mop->mo_next;
639 if (pgno == P_INVALID) {
640 /* DB size is maxed out */
641 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
644 if (txn->mt_env->me_dpages && num == 1) {
645 dp = txn->mt_env->me_dpages;
646 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
648 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
652 dp->h.md_parent = parent;
653 dp->h.md_pi = parent_idx;
654 if (pgno == P_INVALID) {
655 dp->p.mp_pgno = txn->mt_next_pgno;
656 txn->mt_next_pgno += num;
658 dp->p.mp_pgno = pgno;
660 mid.mid = dp->p.mp_pgno;
662 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
667 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
670 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
672 MDB_page *mp = pp->mp_page;
677 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
679 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
681 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
682 assert(mp->mp_pgno != dp->p.mp_pgno);
683 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
684 pgno = dp->p.mp_pgno;
685 memcpy(&dp->p, mp, txn->mt_env->me_psize);
688 mp->mp_flags |= P_DIRTY;
690 /* Update the page number to new touched page. */
691 if (pp->mp_parent != NULL)
692 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
699 mdb_env_sync(MDB_env *env, int force)
702 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
703 if (fdatasync(env->me_fd))
710 mdb_txn_reset0(MDB_txn *txn);
713 mdb_txn_renew0(MDB_txn *txn)
715 MDB_env *env = txn->mt_env;
719 if (env->me_flags & MDB_FATAL_ERROR) {
720 DPUTS("mdb_txn_begin: environment had fatal error, must shutdown!");
724 if (txn->mt_flags & MDB_TXN_RDONLY) {
725 MDB_reader *r = pthread_getspecific(env->me_txkey);
728 pthread_mutex_lock(&env->me_txns->mti_mutex);
729 for (i=0; i<env->me_txns->mti_numreaders; i++)
730 if (env->me_txns->mti_readers[i].mr_pid == 0)
732 if (i == env->me_maxreaders) {
733 pthread_mutex_unlock(&env->me_txns->mti_mutex);
736 env->me_txns->mti_readers[i].mr_pid = getpid();
737 env->me_txns->mti_readers[i].mr_tid = pthread_self();
738 r = &env->me_txns->mti_readers[i];
739 pthread_setspecific(env->me_txkey, r);
740 if (i >= env->me_txns->mti_numreaders)
741 env->me_txns->mti_numreaders = i+1;
742 pthread_mutex_unlock(&env->me_txns->mti_mutex);
744 txn->mt_txnid = env->me_txns->mti_txnid;
745 r->mr_txnid = txn->mt_txnid;
746 txn->mt_u.reader = r;
748 pthread_mutex_lock(&env->me_txns->mti_wmutex);
750 txn->mt_txnid = env->me_txns->mti_txnid+1;
751 txn->mt_u.dirty_list = env->me_dirty_list;
752 txn->mt_u.dirty_list[0].mid = 0;
753 txn->mt_free_pgs = env->me_free_pgs;
754 txn->mt_free_pgs[0] = 0;
758 toggle = env->me_txns->mti_me_toggle;
759 if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
764 /* Copy the DB arrays */
765 txn->mt_numdbs = env->me_numdbs;
766 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
767 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
768 if (txn->mt_numdbs > 2)
769 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
770 (txn->mt_numdbs - 2) * sizeof(MDB_db));
772 if (!(txn->mt_flags & MDB_TXN_RDONLY)) {
774 txn->mt_flags |= MDB_TXN_METOGGLE;
775 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
778 DPRINTF("begin txn %p %lu%c on mdbenv %p, root page %lu", txn,
779 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
780 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
786 mdb_txn_renew(MDB_txn *txn)
793 rc = mdb_txn_renew0(txn);
794 if (rc == MDB_SUCCESS) {
795 DPRINTF("reset txn %p %lu%c on mdbenv %p, root page %lu", txn,
796 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
797 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
803 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
808 if (env->me_flags & MDB_FATAL_ERROR) {
809 DPUTS("mdb_txn_begin: environment had fatal error, must shutdown!");
812 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
813 DPRINTF("calloc: %s", strerror(errno));
816 txn->mt_dbs = (MDB_db *)(txn+1);
818 txn->mt_flags |= MDB_TXN_RDONLY;
822 rc = mdb_txn_renew0(txn);
827 DPRINTF("begin txn %p %lu%c on mdbenv %p, root page %lu", txn,
828 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
829 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
836 mdb_txn_reset0(MDB_txn *txn)
838 MDB_env *env = txn->mt_env;
840 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
841 txn->mt_u.reader->mr_txnid = 0;
847 /* return all dirty pages to dpage list */
848 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
849 dp = txn->mt_u.dirty_list[i].mptr;
850 if (dp->h.md_num == 1) {
851 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
852 txn->mt_env->me_dpages = dp;
854 /* large pages just get freed directly */
859 while ((mop = txn->mt_env->me_pghead)) {
860 txn->mt_env->me_pghead = mop->mo_next;
865 for (i=2; i<env->me_numdbs; i++)
866 env->me_dbxs[i].md_dirty = 0;
867 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
872 mdb_txn_reset(MDB_txn *txn)
877 DPRINTF("reset txn %p %lu%c on mdbenv %p, root page %lu", txn,
878 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
879 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
885 mdb_txn_abort(MDB_txn *txn)
890 DPRINTF("abort txn %p %lu%c on mdbenv %p, root page %lu", txn,
891 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
892 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
899 mdb_txn_commit(MDB_txn *txn)
908 struct iovec iov[MDB_COMMIT_PAGES];
911 assert(txn->mt_env != NULL);
915 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
920 if (txn != env->me_txn) {
921 DPUTS("attempt to commit unknown transaction");
926 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
927 DPUTS("error flag is set, can't commit");
932 if (!txn->mt_u.dirty_list[0].mid)
935 DPRINTF("committing txn %p %lu on mdbenv %p, root page %lu", txn,
936 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
938 /* should only be one record now */
939 if (env->me_pghead) {
943 mop = env->me_pghead;
944 key.mv_size = sizeof(pgno_t);
945 key.mv_data = (char *)&mop->mo_txnid;
946 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
947 data.mv_data = mop->mo_pages;
948 mdb_put0(txn, FREE_DBI, &key, &data, 0);
949 free(env->me_pghead);
950 env->me_pghead = NULL;
952 /* save to free list */
953 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
957 /* make sure last page of freeDB is touched and on freelist */
958 key.mv_size = MAXKEYSIZE+1;
960 mpp.mp_parent = NULL;
962 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
967 ULONG *idl = txn->mt_free_pgs;
968 DPRINTF("IDL write txn %lu root %lu num %lu",
969 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
970 for (i=0; i<idl[0]; i++) {
971 DPRINTF("IDL %lu", idl[i+1]);
975 /* write to last page of freeDB */
976 key.mv_size = sizeof(pgno_t);
977 key.mv_data = (char *)&txn->mt_txnid;
978 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
979 data.mv_data = txn->mt_free_pgs;
980 mdb_put0(txn, FREE_DBI, &key, &data, 0);
983 /* Update DB root pointers. Their pages have already been
984 * touched so this is all in-place and cannot fail.
988 data.mv_size = sizeof(MDB_db);
990 for (i = 2; i < txn->mt_numdbs; i++) {
991 if (txn->mt_dbxs[i].md_dirty) {
992 data.mv_data = &txn->mt_dbs[i];
993 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
998 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1006 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1007 dp = txn->mt_u.dirty_list[i].mptr;
1008 if (dp->p.mp_pgno != next) {
1010 DPRINTF("committing %u dirty pages", n);
1011 rc = writev(env->me_fd, iov, n);
1015 DPUTS("short write, filesystem full?");
1017 DPRINTF("writev: %s", strerror(errno));
1024 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1025 next = dp->p.mp_pgno;
1027 DPRINTF("committing page %lu", dp->p.mp_pgno);
1028 iov[n].iov_len = env->me_psize * dp->h.md_num;
1029 iov[n].iov_base = &dp->p;
1030 size += iov[n].iov_len;
1031 next = dp->p.mp_pgno + dp->h.md_num;
1032 /* clear dirty flag */
1033 dp->p.mp_flags &= ~P_DIRTY;
1034 if (++n >= MDB_COMMIT_PAGES) {
1044 DPRINTF("committing %u dirty pages", n);
1045 rc = writev(env->me_fd, iov, n);
1049 DPUTS("short write, filesystem full?");
1051 DPRINTF("writev: %s", strerror(errno));
1058 /* Drop the dirty pages.
1060 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1061 dp = txn->mt_u.dirty_list[i].mptr;
1062 if (dp->h.md_num == 1) {
1063 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1064 txn->mt_env->me_dpages = dp;
1068 txn->mt_u.dirty_list[i].mid = 0;
1070 txn->mt_u.dirty_list[0].mid = 0;
1072 if ((n = mdb_env_sync(env, 0)) != 0 ||
1073 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1078 env->me_txns->mti_txnid = txn->mt_txnid;
1082 /* update the DB tables */
1084 int toggle = !env->me_db_toggle;
1086 for (i = 2; i < env->me_numdbs; i++) {
1087 if (txn->mt_dbxs[i].md_dirty) {
1088 env->me_dbs[toggle][i] = txn->mt_dbs[i];
1089 txn->mt_dbxs[i].md_dirty = 0;
1092 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1093 txn->mt_dbxs[i].md_dirty = 0;
1094 env->me_dbxs[i] = txn->mt_dbxs[i];
1095 env->me_dbs[toggle][i] = txn->mt_dbs[i];
1097 env->me_db_toggle = toggle;
1098 env->me_numdbs = txn->mt_numdbs;
1101 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
1108 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1110 char page[PAGESIZE];
1115 assert(env != NULL);
1117 /* We don't know the page size yet, so use a minimum value.
1120 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
1122 } else if (rc != PAGESIZE) {
1125 DPRINTF("read: %s", strerror(errno));
1129 p = (MDB_page *)page;
1131 if (!F_ISSET(p->mp_flags, P_META)) {
1132 DPRINTF("page %lu not a meta page", p->mp_pgno);
1137 if (m->mm_magic != MDB_MAGIC) {
1138 DPUTS("meta has invalid magic");
1142 if (m->mm_version != MDB_VERSION) {
1143 DPRINTF("database is version %u, expected version %u",
1144 m->mm_version, MDB_VERSION);
1145 return MDB_VERSION_MISMATCH;
1148 memcpy(meta, m, sizeof(*m));
1153 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1160 DPUTS("writing new meta page");
1161 psize = sysconf(_SC_PAGE_SIZE);
1163 meta->mm_magic = MDB_MAGIC;
1164 meta->mm_version = MDB_VERSION;
1165 meta->mm_psize = psize;
1166 meta->mm_last_pg = 1;
1167 meta->mm_flags = env->me_flags & 0xffff;
1168 meta->mm_flags |= MDB_INTEGERKEY;
1169 meta->mm_dbs[0].md_root = P_INVALID;
1170 meta->mm_dbs[1].md_root = P_INVALID;
1172 p = calloc(2, psize);
1174 p->mp_flags = P_META;
1177 memcpy(m, meta, sizeof(*meta));
1179 q = (MDB_page *)((char *)p + psize);
1182 q->mp_flags = P_META;
1185 memcpy(m, meta, sizeof(*meta));
1187 rc = write(env->me_fd, p, psize * 2);
1189 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1193 mdb_env_write_meta(MDB_txn *txn)
1196 MDB_meta meta, metab;
1198 int rc, len, toggle;
1201 assert(txn != NULL);
1202 assert(txn->mt_env != NULL);
1204 toggle = !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE);
1205 DPRINTF("writing meta page %d for root page %lu",
1206 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1210 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1211 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1213 ptr = (char *)&meta;
1214 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1215 len = sizeof(MDB_meta) - off;
1218 meta.mm_dbs[0] = txn->mt_dbs[0];
1219 meta.mm_dbs[1] = txn->mt_dbs[1];
1220 meta.mm_last_pg = txn->mt_next_pgno - 1;
1221 meta.mm_txnid = txn->mt_txnid;
1224 off += env->me_psize;
1227 /* Write to the SYNC fd */
1228 rc = pwrite(env->me_mfd, ptr, len, off);
1232 DPUTS("write failed, disk error?");
1233 /* On a failure, the pagecache still contains the new data.
1234 * Write some old data back, to prevent it from being used.
1235 * Use the non-SYNC fd; we know it will fail anyway.
1237 meta.mm_last_pg = metab.mm_last_pg;
1238 meta.mm_txnid = metab.mm_txnid;
1239 r2 = pwrite(env->me_fd, ptr, len, off);
1240 env->me_flags |= MDB_FATAL_ERROR;
1243 txn->mt_env->me_txns->mti_me_toggle = toggle;
1249 mdb_env_read_meta(MDB_env *env, int *which)
1253 assert(env != NULL);
1257 else if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1260 if (env->me_meta != env->me_metas[toggle])
1261 env->me_meta = env->me_metas[toggle];
1263 DPRINTF("Using meta page %d", toggle);
1269 mdb_env_create(MDB_env **env)
1273 e = calloc(1, sizeof(MDB_env));
1274 if (!e) return ENOMEM;
1276 e->me_maxreaders = DEFAULT_READERS;
1286 mdb_env_set_mapsize(MDB_env *env, size_t size)
1290 env->me_mapsize = size;
1295 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1297 env->me_maxdbs = dbs;
1302 mdb_env_set_maxreaders(MDB_env *env, int readers)
1304 env->me_maxreaders = readers;
1309 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1311 if (!env || !readers)
1313 *readers = env->me_maxreaders;
1318 mdb_env_open2(MDB_env *env, unsigned int flags)
1324 env->me_flags = flags;
1326 memset(&meta, 0, sizeof(meta));
1328 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1331 DPUTS("new mdbenv");
1335 if (!env->me_mapsize) {
1336 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1340 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1342 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1344 if (env->me_map == MAP_FAILED)
1348 meta.mm_mapsize = env->me_mapsize;
1349 if (flags & MDB_FIXEDMAP)
1350 meta.mm_address = env->me_map;
1351 i = mdb_env_init_meta(env, &meta);
1352 if (i != MDB_SUCCESS) {
1353 munmap(env->me_map, env->me_mapsize);
1357 env->me_psize = meta.mm_psize;
1359 env->me_maxpg = env->me_mapsize / env->me_psize;
1361 p = (MDB_page *)env->me_map;
1362 env->me_metas[0] = METADATA(p);
1363 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1365 if ((i = mdb_env_read_meta(env, NULL)) != 0)
1368 DPRINTF("opened database version %u, pagesize %u",
1369 env->me_meta->mm_version, env->me_psize);
1370 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1371 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1372 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1373 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1374 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1375 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1381 mdb_env_reader_dest(void *ptr)
1383 MDB_reader *reader = ptr;
1385 reader->mr_txnid = 0;
1390 /* downgrade the exclusive lock on the region back to shared */
1392 mdb_env_share_locks(MDB_env *env)
1394 struct flock lock_info;
1396 env->me_txns->mti_txnid = env->me_meta->mm_txnid;
1397 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1398 env->me_txns->mti_me_toggle = 1;
1400 memset((void *)&lock_info, 0, sizeof(lock_info));
1401 lock_info.l_type = F_RDLCK;
1402 lock_info.l_whence = SEEK_SET;
1403 lock_info.l_start = 0;
1404 lock_info.l_len = 1;
1405 fcntl(env->me_lfd, F_SETLK, &lock_info);
1409 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1413 struct flock lock_info;
1417 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1421 /* Try to get exclusive lock. If we succeed, then
1422 * nobody is using the lock region and we should initialize it.
1424 memset((void *)&lock_info, 0, sizeof(lock_info));
1425 lock_info.l_type = F_WRLCK;
1426 lock_info.l_whence = SEEK_SET;
1427 lock_info.l_start = 0;
1428 lock_info.l_len = 1;
1429 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1433 lock_info.l_type = F_RDLCK;
1434 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1440 size = lseek(env->me_lfd, 0, SEEK_END);
1441 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1442 if (size < rsize && *excl) {
1443 if (ftruncate(env->me_lfd, rsize) != 0) {
1449 size = rsize - sizeof(MDB_txninfo);
1450 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1452 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1454 if (env->me_txns == MAP_FAILED) {
1459 pthread_mutexattr_t mattr;
1461 pthread_mutexattr_init(&mattr);
1462 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1466 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1467 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1468 env->me_txns->mti_version = MDB_VERSION;
1469 env->me_txns->mti_magic = MDB_MAGIC;
1470 env->me_txns->mti_txnid = 0;
1471 env->me_txns->mti_numreaders = 0;
1472 env->me_txns->mti_me_toggle = 0;
1475 if (env->me_txns->mti_magic != MDB_MAGIC) {
1476 DPUTS("lock region has invalid magic");
1480 if (env->me_txns->mti_version != MDB_VERSION) {
1481 DPRINTF("lock region is version %u, expected version %u",
1482 env->me_txns->mti_version, MDB_VERSION);
1483 rc = MDB_VERSION_MISMATCH;
1486 if (errno != EACCES && errno != EAGAIN) {
1500 #define LOCKNAME "/lock.mdb"
1501 #define DATANAME "/data.mdb"
1503 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1505 int oflags, rc, len, excl;
1506 char *lpath, *dpath;
1509 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1512 dpath = lpath + len + sizeof(LOCKNAME);
1513 sprintf(lpath, "%s" LOCKNAME, path);
1514 sprintf(dpath, "%s" DATANAME, path);
1516 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1520 if (F_ISSET(flags, MDB_RDONLY))
1523 oflags = O_RDWR | O_CREAT;
1525 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1530 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1531 /* synchronous fd for meta writes */
1532 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1533 oflags |= MDB_DSYNC;
1534 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1539 env->me_path = strdup(path);
1540 DPRINTF("opened dbenv %p", (void *) env);
1541 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1543 mdb_env_share_locks(env);
1544 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1545 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1546 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1552 if (env->me_fd >= 0) {
1556 if (env->me_lfd >= 0) {
1566 mdb_env_close(MDB_env *env)
1573 while (env->me_dpages) {
1574 dp = env->me_dpages;
1575 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1579 free(env->me_dbs[1]);
1580 free(env->me_dbs[0]);
1584 pthread_key_delete(env->me_txkey);
1587 munmap(env->me_map, env->me_mapsize);
1592 pid_t pid = getpid();
1593 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1595 for (i=0; i<env->me_txns->mti_numreaders; i++)
1596 if (env->me_txns->mti_readers[i].mr_pid == pid)
1597 env->me_txns->mti_readers[i].mr_pid = 0;
1598 munmap(env->me_txns, size);
1604 /* Search for key within a leaf page, using binary search.
1605 * Returns the smallest entry larger or equal to the key.
1606 * If exactp is non-null, stores whether the found entry was an exact match
1607 * in *exactp (1 or 0).
1608 * If kip is non-null, stores the index of the found entry in *kip.
1609 * If no entry larger or equal to the key is found, returns NULL.
1612 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1613 int *exactp, unsigned int *kip)
1618 MDB_node *node = NULL;
1622 DPRINTF("searching %u keys in %s page %lu",
1624 IS_LEAF(mp) ? "leaf" : "branch",
1627 assert(NUMKEYS(mp) > 0);
1629 memset(&nodekey, 0, sizeof(nodekey));
1631 low = IS_LEAF(mp) ? 0 : 1;
1632 high = NUMKEYS(mp) - 1;
1633 while (low <= high) {
1634 i = (low + high) >> 1;
1637 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
1638 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
1640 node = NODEPTR(mp, i);
1642 nodekey.mv_size = node->mn_ksize;
1643 nodekey.mv_data = NODEKEY(node);
1646 rc = mdb_cmp(txn, dbi, key, &nodekey);
1649 DPRINTF("found leaf index %u [%s], rc = %i",
1650 i, DKEY(&nodekey), rc);
1652 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
1653 i, DKEY(&nodekey), NODEPGNO(node), rc);
1663 if (rc > 0) { /* Found entry is less than the key. */
1664 i++; /* Skip to get the smallest entry larger than key. */
1665 if (i >= NUMKEYS(mp))
1666 /* There is no entry larger or equal to the key. */
1670 *exactp = (rc == 0);
1671 if (kip) /* Store the key index if requested. */
1674 /* nodeptr is fake for LEAF2 */
1675 return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
1679 cursor_pop_page(MDB_cursor *cursor)
1683 if (cursor->mc_snum) {
1684 top = CURSOR_TOP(cursor);
1687 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
1688 cursor->mc_dbi, (void *) cursor);
1693 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1697 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
1698 cursor->mc_dbi, (void *) cursor);
1700 assert(cursor->mc_snum < CURSOR_STACK);
1702 ppage = &cursor->mc_stack[cursor->mc_snum++];
1703 ppage->mp_page = mp;
1709 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
1713 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1718 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1719 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1720 dp = txn->mt_u.dirty_list[x].mptr;
1725 if (pgno <= txn->mt_env->me_meta->mm_last_pg)
1726 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1730 DPRINTF("page %lu not found", pgno);
1733 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
1737 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1738 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1740 MDB_page *mp = mpp->mp_page;
1744 if (cursor && cursor_push_page(cursor, mp) == NULL)
1747 while (IS_BRANCH(mp)) {
1751 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1752 assert(NUMKEYS(mp) > 1);
1753 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1755 if (key == NULL) /* Initialize cursor to first page. */
1757 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1758 /* cursor to last page */
1762 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1764 i = NUMKEYS(mp) - 1;
1772 DPRINTF("following index %u for key [%s]",
1774 assert(i < NUMKEYS(mp));
1775 node = NODEPTR(mp, i);
1778 CURSOR_TOP(cursor)->mp_ki = i;
1780 mpp->mp_parent = mp;
1781 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
1786 if (cursor && cursor_push_page(cursor, mp) == NULL)
1790 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1791 if ((rc = mdb_touch(txn, mpp)) != 0)
1793 dh = ((MDB_dhead *)mpp->mp_page)-1;
1794 dh->md_parent = mpp->mp_parent;
1795 dh->md_pi = mpp->mp_pi;
1802 DPRINTF("internal error, index points to a %02X page!?",
1804 return MDB_CORRUPTED;
1807 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
1808 key ? DKEY(key) : NULL);
1813 /* Search for the page a given key should be in.
1814 * Stores a pointer to the found page in *mpp.
1815 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1816 * If cursor is non-null, pushes parent pages on the cursor stack.
1817 * If modify is true, visited pages are updated with new page numbers.
1820 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1821 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1826 /* Choose which root page to start with. If a transaction is given
1827 * use the root page from the transaction, otherwise read the last
1828 * committed root page.
1830 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1831 DPUTS("transaction has failed, must abort");
1834 root = txn->mt_dbs[dbi].md_root;
1836 if (root == P_INVALID) { /* Tree is empty. */
1837 DPUTS("tree is empty");
1838 return MDB_NOTFOUND;
1841 if (rc = mdb_get_page(txn, root, &mpp->mp_page))
1844 DPRINTF("db %u root page %lu has flags 0x%X",
1845 dbi, root, mpp->mp_page->mp_flags);
1848 /* For sub-databases, update main root first */
1849 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1851 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1855 txn->mt_dbxs[dbi].md_dirty = 1;
1857 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1858 mpp->mp_parent = NULL;
1860 if ((rc = mdb_touch(txn, mpp)))
1862 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1866 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1870 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1872 MDB_page *omp; /* overflow mpage */
1876 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1877 data->mv_size = leaf->mn_dsize;
1878 data->mv_data = NODEDATA(leaf);
1882 /* Read overflow data.
1884 data->mv_size = leaf->mn_dsize;
1885 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1886 if (rc = mdb_get_page(txn, pgno, &omp)) {
1887 DPRINTF("read overflow page %lu failed", pgno);
1890 data->mv_data = METADATA(omp);
1896 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1897 MDB_val *key, MDB_val *data)
1906 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
1908 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1911 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1915 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1918 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1919 if (leaf && exact) {
1920 /* Return first duplicate data item */
1921 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
1924 mdb_xcursor_init0(txn, dbi, &mx);
1925 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
1926 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1927 if (rc != MDB_SUCCESS)
1929 if (IS_LEAF2(mpp.mp_page)) {
1930 data->mv_size = txn->mt_dbs[dbi].md_pad;
1931 data->mv_data = LEAF2KEY(mpp.mp_page, 0, data->mv_size);
1933 leaf = NODEPTR(mpp.mp_page, 0);
1934 data->mv_size = NODEKSZ(leaf);
1935 data->mv_data = NODEKEY(leaf);
1938 rc = mdb_read_data(txn, leaf, data);
1948 mdb_sibling(MDB_cursor *cursor, int move_right)
1955 if (cursor->mc_snum < 2) {
1956 return MDB_NOTFOUND; /* root has no siblings */
1958 parent = CURSOR_PARENT(cursor);
1960 DPRINTF("parent page is page %lu, index %u",
1961 parent->mp_page->mp_pgno, parent->mp_ki);
1963 cursor_pop_page(cursor);
1964 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1965 : (parent->mp_ki == 0)) {
1966 DPRINTF("no more keys left, moving to %s sibling",
1967 move_right ? "right" : "left");
1968 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1970 parent = CURSOR_TOP(cursor);
1976 DPRINTF("just moving to %s index key %u",
1977 move_right ? "right" : "left", parent->mp_ki);
1979 assert(IS_BRANCH(parent->mp_page));
1981 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1982 if (rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp))
1985 mp->parent = parent->mp_page;
1986 mp->parent_index = parent->mp_ki;
1989 cursor_push_page(cursor, mp);
1995 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2002 if (cursor->mc_eof) {
2003 return MDB_NOTFOUND;
2006 assert(cursor->mc_initialized);
2008 top = CURSOR_TOP(cursor);
2011 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2012 leaf = NODEPTR(mp, top->mp_ki);
2013 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2014 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2015 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2016 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2020 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2021 if (op == MDB_NEXT_DUP)
2022 return MDB_NOTFOUND;
2026 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2028 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2029 DPUTS("=====> move to next sibling page");
2030 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2032 return MDB_NOTFOUND;
2034 top = CURSOR_TOP(cursor);
2036 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2040 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2041 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2044 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2045 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2049 assert(IS_LEAF(mp));
2050 leaf = NODEPTR(mp, top->mp_ki);
2052 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2053 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2056 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2059 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2060 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2061 if (rc != MDB_SUCCESS)
2066 MDB_SET_KEY(leaf, key);
2071 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2078 assert(cursor->mc_initialized);
2080 top = CURSOR_TOP(cursor);
2083 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2084 leaf = NODEPTR(mp, top->mp_ki);
2085 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2086 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2087 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2088 if (op != MDB_PREV || rc == MDB_SUCCESS)
2091 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2092 if (op == MDB_PREV_DUP)
2093 return MDB_NOTFOUND;
2098 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2100 if (top->mp_ki == 0) {
2101 DPUTS("=====> move to prev sibling page");
2102 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2103 cursor->mc_initialized = 0;
2104 return MDB_NOTFOUND;
2106 top = CURSOR_TOP(cursor);
2108 top->mp_ki = NUMKEYS(mp) - 1;
2109 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2115 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2116 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2119 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2120 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2124 assert(IS_LEAF(mp));
2125 leaf = NODEPTR(mp, top->mp_ki);
2127 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2128 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2131 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2134 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2135 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2136 if (rc != MDB_SUCCESS)
2141 MDB_SET_KEY(leaf, key);
2146 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2147 MDB_cursor_op op, int *exactp)
2157 assert(key->mv_size > 0);
2159 /* See if we're already on the right page */
2160 if (cursor->mc_initialized) {
2162 top = CURSOR_TOP(cursor);
2163 /* Don't try this for LEAF2 pages. Maybe support that later. */
2164 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2165 leaf = NODEPTR(top->mp_page, 0);
2166 MDB_SET_KEY(leaf, &nodekey);
2167 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2169 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2170 MDB_SET_KEY(leaf, &nodekey);
2171 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2173 /* we're already on the right page */
2174 mpp.mp_page = top->mp_page;
2181 cursor->mc_snum = 0;
2183 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2184 if (rc != MDB_SUCCESS)
2187 assert(IS_LEAF(mpp.mp_page));
2189 top = CURSOR_TOP(cursor);
2191 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2192 if (exactp != NULL && !*exactp) {
2193 /* MDB_SET specified and not an exact match. */
2194 return MDB_NOTFOUND;
2198 DPUTS("===> inexact leaf not found, goto sibling");
2199 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2200 return rc; /* no entries matched */
2201 top = CURSOR_TOP(cursor);
2203 mpp.mp_page = top->mp_page;
2204 assert(IS_LEAF(mpp.mp_page));
2205 leaf = NODEPTR(mpp.mp_page, 0);
2208 cursor->mc_initialized = 1;
2211 if (IS_LEAF2(mpp.mp_page)) {
2212 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2213 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2217 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2218 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2221 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2222 if (op == MDB_SET || op == MDB_SET_RANGE) {
2223 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2226 if (op == MDB_GET_BOTH) {
2231 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2232 if (rc != MDB_SUCCESS)
2235 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2237 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2239 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2241 if (op == MDB_GET_BOTH || rc > 0)
2242 return MDB_NOTFOUND;
2246 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2251 /* The key already matches in all other cases */
2252 if (op == MDB_SET_RANGE)
2253 MDB_SET_KEY(leaf, key);
2254 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2260 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2266 cursor->mc_snum = 0;
2268 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2269 if (rc != MDB_SUCCESS)
2271 assert(IS_LEAF(mpp.mp_page));
2273 leaf = NODEPTR(mpp.mp_page, 0);
2274 cursor->mc_initialized = 1;
2277 if (IS_LEAF2(mpp.mp_page)) {
2278 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2279 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2284 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2285 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2286 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2290 if (cursor->mc_xcursor)
2291 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2292 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2296 MDB_SET_KEY(leaf, key);
2301 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2309 cursor->mc_snum = 0;
2311 lkey.mv_size = MAXKEYSIZE+1;
2312 lkey.mv_data = NULL;
2314 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2315 if (rc != MDB_SUCCESS)
2317 assert(IS_LEAF(mpp.mp_page));
2319 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2320 cursor->mc_initialized = 1;
2323 top = CURSOR_TOP(cursor);
2324 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2326 if (IS_LEAF2(mpp.mp_page)) {
2327 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2328 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2333 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2334 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2335 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2339 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2344 MDB_SET_KEY(leaf, key);
2349 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2359 case MDB_GET_BOTH_RANGE:
2360 if (data == NULL || cursor->mc_xcursor == NULL) {
2367 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2369 } else if (op == MDB_SET_RANGE)
2370 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2372 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2374 case MDB_GET_MULTIPLE:
2376 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2377 !cursor->mc_initialized) {
2382 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2385 case MDB_NEXT_MULTIPLE:
2387 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2391 if (!cursor->mc_initialized)
2392 rc = mdb_cursor_first(cursor, key, data);
2394 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2395 if (rc == MDB_SUCCESS) {
2396 if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2399 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2400 data->mv_size = NUMKEYS(top->mp_page) *
2401 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2402 data->mv_data = METADATA(top->mp_page);
2403 top->mp_ki = NUMKEYS(top->mp_page)-1;
2411 case MDB_NEXT_NODUP:
2412 if (!cursor->mc_initialized)
2413 rc = mdb_cursor_first(cursor, key, data);
2415 rc = mdb_cursor_next(cursor, key, data, op);
2419 case MDB_PREV_NODUP:
2420 if (!cursor->mc_initialized || cursor->mc_eof)
2421 rc = mdb_cursor_last(cursor, key, data);
2423 rc = mdb_cursor_prev(cursor, key, data, op);
2426 rc = mdb_cursor_first(cursor, key, data);
2429 rc = mdb_cursor_last(cursor, key, data);
2432 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2440 /* Allocate a page and initialize it
2443 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2447 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2449 DPRINTF("allocated new mpage %lu, page size %u",
2450 dp->p.mp_pgno, txn->mt_env->me_psize);
2451 dp->p.mp_flags = flags | P_DIRTY;
2452 dp->p.mp_lower = PAGEHDRSZ;
2453 dp->p.mp_upper = txn->mt_env->me_psize;
2455 if (IS_BRANCH(&dp->p))
2456 txn->mt_dbs[dbi].md_branch_pages++;
2457 else if (IS_LEAF(&dp->p))
2458 txn->mt_dbs[dbi].md_leaf_pages++;
2459 else if (IS_OVERFLOW(&dp->p)) {
2460 txn->mt_dbs[dbi].md_overflow_pages += num;
2461 dp->p.mp_pages = num;
2468 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2472 sz = LEAFSIZE(key, data);
2473 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2474 /* put on overflow page */
2475 sz -= data->mv_size - sizeof(pgno_t);
2478 return sz + sizeof(indx_t);
2482 mdb_branch_size(MDB_env *env, MDB_val *key)
2487 if (sz >= env->me_psize / MDB_MINKEYS) {
2488 /* put on overflow page */
2489 /* not implemented */
2490 /* sz -= key->size - sizeof(pgno_t); */
2493 return sz + sizeof(indx_t);
2497 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2498 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2501 size_t node_size = NODESIZE;
2504 MDB_dpage *ofp = NULL; /* overflow page */
2507 assert(mp->mp_upper >= mp->mp_lower);
2509 DPRINTF("add node [%s] to %s page %lu at index %i, key size %zu",
2510 key ? DKEY(key) : NULL,
2511 IS_LEAF(mp) ? "leaf" : "branch",
2512 mp->mp_pgno, indx, key ? key->mv_size : 0);
2515 /* Move higher keys up one slot. */
2516 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2517 char *ptr = LEAF2KEY(mp, indx, ksize);
2518 dif = NUMKEYS(mp) - indx;
2520 memmove(ptr+ksize, ptr, dif*ksize);
2521 /* insert new key */
2522 memcpy(ptr, key->mv_data, ksize);
2524 /* Just using these for counting */
2525 mp->mp_lower += sizeof(indx_t);
2526 mp->mp_upper -= ksize - sizeof(indx_t);
2531 node_size += key->mv_size;
2535 if (F_ISSET(flags, F_BIGDATA)) {
2536 /* Data already on overflow page. */
2537 node_size += sizeof(pgno_t);
2538 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2539 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2540 /* Put data on overflow page. */
2541 DPRINTF("data size is %zu, put on overflow page",
2543 node_size += sizeof(pgno_t);
2544 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2546 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2549 node_size += data->mv_size;
2553 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2554 DPRINTF("not enough room in page %lu, got %u ptrs",
2555 mp->mp_pgno, NUMKEYS(mp));
2556 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2557 mp->mp_upper - mp->mp_lower);
2558 DPRINTF("node size = %zu", node_size);
2562 /* Move higher pointers up one slot. */
2563 for (i = NUMKEYS(mp); i > indx; i--)
2564 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2566 /* Adjust free space offsets. */
2567 ofs = mp->mp_upper - node_size;
2568 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2569 mp->mp_ptrs[indx] = ofs;
2571 mp->mp_lower += sizeof(indx_t);
2573 /* Write the node data. */
2574 node = NODEPTR(mp, indx);
2575 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2576 node->mn_flags = flags;
2578 node->mn_dsize = data->mv_size;
2580 NODEPGNO(node) = pgno;
2583 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2588 if (F_ISSET(flags, F_BIGDATA))
2589 memcpy(node->mn_data + key->mv_size, data->mv_data,
2592 memcpy(node->mn_data + key->mv_size, data->mv_data,
2595 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2597 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2605 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2608 indx_t i, j, numkeys, ptr;
2612 DPRINTF("delete node %u on %s page %lu", indx,
2613 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2614 assert(indx < NUMKEYS(mp));
2617 int x = NUMKEYS(mp) - 1 - indx;
2618 base = LEAF2KEY(mp, indx, ksize);
2620 memmove(base, base + ksize, x * ksize);
2621 mp->mp_lower -= sizeof(indx_t);
2622 mp->mp_upper += ksize - sizeof(indx_t);
2626 node = NODEPTR(mp, indx);
2627 sz = NODESIZE + node->mn_ksize;
2629 if (F_ISSET(node->mn_flags, F_BIGDATA))
2630 sz += sizeof(pgno_t);
2632 sz += NODEDSZ(node);
2635 ptr = mp->mp_ptrs[indx];
2636 numkeys = NUMKEYS(mp);
2637 for (i = j = 0; i < numkeys; i++) {
2639 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2640 if (mp->mp_ptrs[i] < ptr)
2641 mp->mp_ptrs[j] += sz;
2646 base = (char *)mp + mp->mp_upper;
2647 memmove(base + sz, base, ptr - mp->mp_upper);
2649 mp->mp_lower -= sizeof(indx_t);
2654 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2659 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2660 mx->mx_txn.mt_dbs = mx->mx_dbs;
2661 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2662 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2664 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2669 mx->mx_dbxs[dbn+1].md_parent = dbn;
2670 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2671 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2672 mx->mx_dbxs[dbn+1].md_dirty = 0;
2673 mx->mx_txn.mt_numdbs = dbn+2;
2675 mx->mx_cursor.mc_snum = 0;
2676 mx->mx_cursor.mc_txn = &mx->mx_txn;
2677 mx->mx_cursor.mc_dbi = dbn+1;
2681 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
2683 MDB_db *db = NODEDATA(node);
2685 mx->mx_dbs[0] = txn->mt_dbs[0];
2686 mx->mx_dbs[1] = txn->mt_dbs[1];
2688 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2693 DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
2694 mx->mx_dbs[dbn] = *db;
2695 if (F_ISSET(mp->mp_flags, P_DIRTY))
2696 mx->mx_dbxs[dbn].md_dirty = 1;
2697 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2698 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2699 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2700 mx->mx_txn.mt_oldest = txn->mt_oldest;
2701 mx->mx_txn.mt_u = txn->mt_u;
2702 mx->mx_cursor.mc_initialized = 0;
2703 mx->mx_cursor.mc_eof = 0;
2707 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2709 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2710 txn->mt_oldest = mx->mx_txn.mt_oldest;
2711 txn->mt_u = mx->mx_txn.mt_u;
2712 txn->mt_dbs[0] = mx->mx_dbs[0];
2713 txn->mt_dbs[1] = mx->mx_dbs[1];
2714 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2715 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2717 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2718 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2723 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2726 size_t size = sizeof(MDB_cursor);
2728 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2731 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2732 size += sizeof(MDB_xcursor);
2734 if ((cursor = calloc(1, size)) != NULL) {
2735 cursor->mc_dbi = dbi;
2736 cursor->mc_txn = txn;
2737 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2738 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2739 cursor->mc_xcursor = mx;
2740 mdb_xcursor_init0(txn, dbi, mx);
2751 /* Return the count of duplicate data items for the current key */
2753 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2758 if (mc == NULL || countp == NULL)
2761 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2764 top = CURSOR_TOP(mc);
2765 leaf = NODEPTR(top->mp_page, top->mp_ki);
2766 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2769 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2772 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2778 mdb_cursor_close(MDB_cursor *cursor)
2780 if (cursor != NULL) {
2786 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2788 indx_t ptr, i, numkeys;
2795 node = NODEPTR(mp, indx);
2796 ptr = mp->mp_ptrs[indx];
2797 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
2799 (int)node->mn_ksize, (char *)NODEKEY(node),
2803 delta = key->mv_size - node->mn_ksize;
2805 if (delta > 0 && SIZELEFT(mp) < delta) {
2806 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2810 numkeys = NUMKEYS(mp);
2811 for (i = 0; i < numkeys; i++) {
2812 if (mp->mp_ptrs[i] <= ptr)
2813 mp->mp_ptrs[i] -= delta;
2816 base = (char *)mp + mp->mp_upper;
2817 len = ptr - mp->mp_upper + NODESIZE;
2818 memmove(base - delta, base, len);
2819 mp->mp_upper -= delta;
2821 node = NODEPTR(mp, indx);
2822 node->mn_ksize = key->mv_size;
2825 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2830 /* Move a node from src to dst.
2833 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2834 MDB_pageparent *dst, indx_t dstindx)
2841 /* Mark src and dst as dirty. */
2842 if ((rc = mdb_touch(txn, src)) ||
2843 (rc = mdb_touch(txn, dst)))
2846 if (IS_LEAF2(src->mp_page)) {
2847 srcnode = NODEPTR(src->mp_page, 0); /* fake */
2848 key.mv_size = txn->mt_dbs[dbi].md_pad;
2849 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
2851 data.mv_data = NULL;
2853 srcnode = NODEPTR(src->mp_page, srcindx);
2854 key.mv_size = NODEKSZ(srcnode);
2855 key.mv_data = NODEKEY(srcnode);
2856 data.mv_size = NODEDSZ(srcnode);
2857 data.mv_data = NODEDATA(srcnode);
2859 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
2860 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2863 src->mp_page->mp_pgno,
2864 dstindx, dst->mp_page->mp_pgno);
2866 /* Add the node to the destination page.
2868 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2870 if (rc != MDB_SUCCESS)
2873 /* Delete the node from the source page.
2875 mdb_del_node(src->mp_page, srcindx, key.mv_size);
2877 /* The key value just changed due to del_node, find it again.
2879 if (!IS_LEAF2(src->mp_page)) {
2880 srcnode = NODEPTR(src->mp_page, srcindx);
2881 key.mv_data = NODEKEY(srcnode);
2884 /* Update the parent separators.
2887 if (src->mp_pi != 0) {
2888 DPRINTF("update separator for source page %lu to [%s]",
2889 src->mp_page->mp_pgno, DKEY(&key));
2890 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2891 &key)) != MDB_SUCCESS)
2894 if (IS_BRANCH(src->mp_page)) {
2896 nullkey.mv_size = 0;
2897 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2902 if (dst->mp_pi != 0) {
2903 DPRINTF("update separator for destination page %lu to [%s]",
2904 dst->mp_page->mp_pgno, DKEY(&key));
2905 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2906 &key)) != MDB_SUCCESS)
2909 if (IS_BRANCH(dst->mp_page)) {
2911 nullkey.mv_size = 0;
2912 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2920 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2929 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2931 assert(txn != NULL);
2932 assert(src->mp_parent); /* can't merge root page */
2933 assert(dst->mp_parent);
2935 /* Mark src and dst as dirty. */
2936 if ((rc = mdb_touch(txn, src)) ||
2937 (rc = mdb_touch(txn, dst)))
2940 /* Move all nodes from src to dst.
2942 if (IS_LEAF2(src->mp_page)) {
2943 key.mv_size = txn->mt_dbs[dbi].md_pad;
2944 key.mv_data = METADATA(src->mp_page);
2945 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2946 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2948 if (rc != MDB_SUCCESS)
2950 key.mv_data = (char *)key.mv_data + key.mv_size;
2953 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2954 srcnode = NODEPTR(src->mp_page, i);
2956 key.mv_size = srcnode->mn_ksize;
2957 key.mv_data = NODEKEY(srcnode);
2958 data.mv_size = NODEDSZ(srcnode);
2959 data.mv_data = NODEDATA(srcnode);
2960 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2961 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2962 if (rc != MDB_SUCCESS)
2967 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2968 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2970 /* Unlink the src page from parent.
2972 mdb_del_node(src->mp_parent, src->mp_pi, 0);
2973 if (src->mp_pi == 0) {
2975 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2979 if (IS_LEAF(src->mp_page))
2980 txn->mt_dbs[dbi].md_leaf_pages--;
2982 txn->mt_dbs[dbi].md_branch_pages--;
2984 mpp.mp_page = src->mp_parent;
2985 dh = (MDB_dhead *)src->mp_parent;
2987 mpp.mp_parent = dh->md_parent;
2988 mpp.mp_pi = dh->md_pi;
2990 return mdb_rebalance(txn, dbi, &mpp);
2993 #define FILL_THRESHOLD 250
2996 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3001 indx_t si = 0, di = 0;
3004 assert(txn != NULL);
3005 assert(mpp != NULL);
3007 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3008 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3009 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3011 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3012 DPRINTF("no need to rebalance page %lu, above fill threshold",
3013 mpp->mp_page->mp_pgno);
3017 if (mpp->mp_parent == NULL) {
3018 if (NUMKEYS(mpp->mp_page) == 0) {
3019 DPUTS("tree is completely empty");
3020 txn->mt_dbs[dbi].md_root = P_INVALID;
3021 txn->mt_dbs[dbi].md_depth = 0;
3022 txn->mt_dbs[dbi].md_leaf_pages = 0;
3023 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3024 DPUTS("collapsing root page!");
3025 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3026 if (rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root))
3028 txn->mt_dbs[dbi].md_depth--;
3029 txn->mt_dbs[dbi].md_branch_pages--;
3031 DPUTS("root page doesn't need rebalancing");
3035 /* The parent (branch page) must have at least 2 pointers,
3036 * otherwise the tree is invalid.
3038 assert(NUMKEYS(mpp->mp_parent) > 1);
3040 /* Leaf page fill factor is below the threshold.
3041 * Try to move keys from left or right neighbor, or
3042 * merge with a neighbor page.
3047 if (mpp->mp_pi == 0) {
3048 /* We're the leftmost leaf in our parent.
3050 DPUTS("reading right neighbor");
3051 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3052 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3054 npp.mp_pi = mpp->mp_pi + 1;
3056 di = NUMKEYS(mpp->mp_page);
3058 /* There is at least one neighbor to the left.
3060 DPUTS("reading left neighbor");
3061 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3062 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3064 npp.mp_pi = mpp->mp_pi - 1;
3065 si = NUMKEYS(npp.mp_page) - 1;
3068 npp.mp_parent = mpp->mp_parent;
3070 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3071 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3073 /* If the neighbor page is above threshold and has at least two
3074 * keys, move one key from it.
3076 * Otherwise we should try to merge them.
3078 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3079 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3080 else { /* FIXME: if (has_enough_room()) */
3081 if (mpp->mp_pi == 0)
3082 return mdb_merge(txn, dbi, &npp, mpp);
3084 return mdb_merge(txn, dbi, mpp, &npp);
3089 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3093 /* add overflow pages to free list */
3094 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3098 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3099 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3100 for (i=0; i<ovpages; i++) {
3101 DPRINTF("freed ov page %lu", pg);
3102 mdb_midl_insert(txn->mt_free_pgs, pg);
3106 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3107 txn->mt_dbs[dbi].md_entries--;
3108 rc = mdb_rebalance(txn, dbi, mpp);
3109 if (rc != MDB_SUCCESS)
3110 txn->mt_flags |= MDB_TXN_ERROR;
3116 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3117 MDB_val *key, MDB_val *data,
3126 assert(key != NULL);
3128 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3130 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3133 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3137 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3141 mpp.mp_parent = NULL;
3143 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3146 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3147 if (leaf == NULL || !exact) {
3148 return MDB_NOTFOUND;
3151 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3155 mdb_xcursor_init0(txn, dbi, &mx);
3156 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3157 if (flags == MDB_DEL_DUP) {
3158 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
3159 mdb_xcursor_fini(txn, dbi, &mx);
3160 /* If sub-DB still has entries, we're done */
3161 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3162 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3164 txn->mt_dbs[dbi].md_entries--;
3167 /* otherwise fall thru and delete the sub-DB */
3169 /* add all the child DB's pages to the free list */
3170 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3171 NULL, &mx.mx_cursor, 0, &mp2);
3172 if (rc == MDB_SUCCESS) {
3173 MDB_ppage *top, *parent;
3177 cursor_pop_page(&mx.mx_cursor);
3178 if (mx.mx_cursor.mc_snum) {
3179 top = CURSOR_TOP(&mx.mx_cursor);
3180 while (mx.mx_cursor.mc_snum > 1) {
3181 parent = CURSOR_PARENT(&mx.mx_cursor);
3182 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3183 ni = NODEPTR(top->mp_page, i);
3184 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3187 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3188 cursor_pop_page(&mx.mx_cursor);
3191 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3192 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3196 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3201 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
3204 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3207 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3208 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3209 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3210 * refer to a node in the new right sibling page.
3213 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3214 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3217 int rc = MDB_SUCCESS, ins_new = 0;
3220 unsigned int i, j, split_indx;
3222 MDB_val sepkey, rkey, rdata;
3224 MDB_dpage *mdp, *rdp, *pdp;
3228 assert(txn != NULL);
3230 dh = ((MDB_dhead *)*mpp) - 1;
3231 mdp = (MDB_dpage *)dh;
3232 newindx = *newindxp;
3234 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3235 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3236 DKEY(newkey), *newindxp);
3238 if (mdp->h.md_parent == NULL) {
3239 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3242 mdp->h.md_parent = &pdp->p;
3243 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3244 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3245 txn->mt_dbs[dbi].md_depth++;
3247 /* Add left (implicit) pointer. */
3248 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3249 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3252 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3255 /* Create a right sibling. */
3256 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3258 rdp->h.md_parent = mdp->h.md_parent;
3259 rdp->h.md_pi = mdp->h.md_pi + 1;
3260 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3262 split_indx = NUMKEYS(&mdp->p) / 2 + 1;
3264 if (IS_LEAF2(&rdp->p)) {
3267 unsigned int nkeys = NUMKEYS(&mdp->p), lsize, rsize, ksize;
3268 /* Move half of the keys to the right sibling */
3270 x = *newindxp - split_indx;
3271 ksize = txn->mt_dbs[dbi].md_pad;
3272 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3273 rsize = (nkeys - split_indx) * ksize;
3274 lsize = (nkeys - split_indx) * sizeof(indx_t);
3275 mdp->p.mp_lower -= lsize;
3276 rdp->p.mp_lower += lsize;
3277 mdp->p.mp_upper += rsize - lsize;
3278 rdp->p.mp_upper -= rsize - lsize;
3279 sepkey.mv_size = ksize;
3280 if (newindx == split_indx) {
3281 sepkey.mv_data = newkey->mv_data;
3283 sepkey.mv_data = split;
3286 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3287 memcpy(&rdp->p.mp_ptrs, split, rsize);
3288 sepkey.mv_data = &rdp->p.mp_ptrs;
3289 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3290 memcpy(ins, newkey->mv_data, ksize);
3291 mdp->p.mp_lower += sizeof(indx_t);
3292 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3295 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3296 ins = LEAF2KEY(&rdp->p, x, ksize);
3297 memcpy(ins, newkey->mv_data, ksize);
3298 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3299 rdp->p.mp_lower += sizeof(indx_t);
3300 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3307 /* Move half of the keys to the right sibling. */
3308 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3310 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
3311 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
3312 mdp->p.mp_lower = PAGEHDRSZ;
3313 mdp->p.mp_upper = txn->mt_env->me_psize;
3315 /* First find the separating key between the split pages.
3317 memset(&sepkey, 0, sizeof(sepkey));
3318 if (newindx == split_indx) {
3319 sepkey.mv_size = newkey->mv_size;
3320 sepkey.mv_data = newkey->mv_data;
3322 node = NODEPTR(copy, split_indx);
3323 sepkey.mv_size = node->mn_ksize;
3324 sepkey.mv_data = NODEKEY(node);
3328 DPRINTF("separator is [%s]", DKEY(&sepkey));
3330 /* Copy separator key to the parent.
3332 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3333 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3334 &sepkey, NULL, rdp->p.mp_pgno);
3336 /* Right page might now have changed parent.
3337 * Check if left page also changed parent.
3339 if (rdp->h.md_parent != mdp->h.md_parent &&
3340 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3341 mdp->h.md_parent = rdp->h.md_parent;
3342 mdp->h.md_pi = rdp->h.md_pi - 1;
3345 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3346 &sepkey, NULL, rdp->p.mp_pgno, 0);
3348 if (IS_LEAF2(&rdp->p)) {
3351 if (rc != MDB_SUCCESS) {
3356 for (i = j = 0; i <= NUMKEYS(copy); j++) {
3357 if (i < split_indx) {
3358 /* Re-insert in left sibling. */
3361 /* Insert in right sibling. */
3362 if (i == split_indx)
3363 /* Reset insert index for right sibling. */
3364 j = (i == newindx && ins_new);
3368 if (i == newindx && !ins_new) {
3369 /* Insert the original entry that caused the split. */
3370 rkey.mv_data = newkey->mv_data;
3371 rkey.mv_size = newkey->mv_size;
3372 if (IS_LEAF(&mdp->p)) {
3373 rdata.mv_data = newdata->mv_data;
3374 rdata.mv_size = newdata->mv_size;
3381 /* Update page and index for the new key. */
3384 } else if (i == NUMKEYS(copy)) {
3387 node = NODEPTR(copy, i);
3388 rkey.mv_data = NODEKEY(node);
3389 rkey.mv_size = node->mn_ksize;
3390 if (IS_LEAF(&mdp->p)) {
3391 rdata.mv_data = NODEDATA(node);
3392 rdata.mv_size = node->mn_dsize;
3394 pgno = NODEPGNO(node);
3395 flags = node->mn_flags;
3400 if (!IS_LEAF(&mdp->p) && j == 0) {
3401 /* First branch index doesn't need key data. */
3405 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
3413 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3414 MDB_val *key, MDB_val *data, unsigned int flags)
3416 int rc = MDB_SUCCESS, exact;
3420 MDB_val xdata, *rdata, dkey;
3422 char dbuf[PAGESIZE];
3427 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3428 dbi, DKEY(key), key->mv_size, data->mv_size);
3431 mpp.mp_parent = NULL;
3433 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3434 if (rc == MDB_SUCCESS) {
3435 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3436 if (leaf && exact) {
3437 if (flags == MDB_NOOVERWRITE) {
3438 DPRINTF("duplicate key [%s]", DKEY(key));
3439 return MDB_KEYEXIST;
3441 /* there's only a key anyway, so this is a no-op */
3442 if (IS_LEAF2(mpp.mp_page))
3445 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3446 /* Was a single item before, must convert now */
3447 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3448 dkey.mv_size = NODEDSZ(leaf);
3449 dkey.mv_data = dbuf;
3450 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3451 /* data matches, ignore it */
3452 if (!mdb_dcmp(txn, dbi, data, &dkey))
3453 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3454 memset(&dummy, 0, sizeof(dummy));
3455 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3456 dummy.md_pad = data->mv_size;
3457 dummy.md_flags = MDB_DUPFIXED;
3458 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3459 dummy.md_flags |= MDB_INTEGERKEY;
3461 dummy.md_root = P_INVALID;
3462 if (dkey.mv_size == sizeof(MDB_db)) {
3463 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3466 mdb_del_node(mpp.mp_page, ki, 0);
3469 xdata.mv_size = sizeof(MDB_db);
3470 xdata.mv_data = &dummy;
3475 /* same size, just replace it */
3476 if (NODEDSZ(leaf) == data->mv_size) {
3477 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3480 mdb_del_node(mpp.mp_page, ki, 0);
3482 if (leaf == NULL) { /* append if not found */
3483 ki = NUMKEYS(mpp.mp_page);
3484 DPRINTF("appending key at index %i", ki);
3486 } else if (rc == MDB_NOTFOUND) {
3488 /* new file, just write a root leaf page */
3489 DPUTS("allocating new root leaf page");
3490 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3493 mpp.mp_page = &dp->p;
3494 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3495 txn->mt_dbs[dbi].md_depth++;
3496 txn->mt_dbxs[dbi].md_dirty = 1;
3497 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3498 mpp.mp_page->mp_flags |= P_LEAF2;
3504 assert(IS_LEAF(mpp.mp_page));
3505 DPRINTF("there are %u keys, should insert new key at index %i",
3506 NUMKEYS(mpp.mp_page), ki);
3511 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3512 if (SIZELEFT(mpp.mp_page) < nsize) {
3513 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3515 /* There is room already in this leaf page. */
3516 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3519 if (rc != MDB_SUCCESS)
3520 txn->mt_flags |= MDB_TXN_ERROR;
3522 /* Remember if we just added a subdatabase */
3523 if (flags & F_SUBDATA) {
3524 leaf = NODEPTR(mpp.mp_page, ki);
3525 leaf->mn_flags |= F_SUBDATA;
3528 /* Now store the actual data in the child DB. Note that we're
3529 * storing the user data in the keys field, so there are strict
3530 * size limits on dupdata. The actual data fields of the child
3531 * DB are all zero size.
3536 leaf = NODEPTR(mpp.mp_page, ki);
3538 mdb_xcursor_init0(txn, dbi, &mx);
3539 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3542 if (flags == MDB_NODUPDATA)
3543 flags = MDB_NOOVERWRITE;
3544 /* converted, write the original data first */
3546 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3548 leaf->mn_flags |= F_DUPDATA;
3550 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3551 mdb_xcursor_fini(txn, dbi, &mx);
3552 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3555 txn->mt_dbs[dbi].md_entries++;
3563 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3564 MDB_val *key, MDB_val *data, unsigned int flags)
3566 assert(key != NULL);
3567 assert(data != NULL);
3569 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3572 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3576 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3580 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3583 return mdb_put0(txn, dbi, key, data, flags);
3587 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3589 #define CHANGEABLE (MDB_NOSYNC)
3590 if ((flag & CHANGEABLE) != flag)
3593 env->me_flags |= flag;
3595 env->me_flags &= ~flag;
3600 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3605 *arg = env->me_flags;
3610 mdb_env_get_path(MDB_env *env, const char **arg)
3615 *arg = env->me_path;
3620 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3622 arg->ms_psize = env->me_psize;
3623 arg->ms_depth = db->md_depth;
3624 arg->ms_branch_pages = db->md_branch_pages;
3625 arg->ms_leaf_pages = db->md_leaf_pages;
3626 arg->ms_overflow_pages = db->md_overflow_pages;
3627 arg->ms_entries = db->md_entries;
3632 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3634 if (env == NULL || arg == NULL)
3637 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3640 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3650 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3651 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3655 /* Is the DB already open? */
3657 for (i=2; i<txn->mt_numdbs; i++) {
3658 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3659 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3665 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3668 /* Find the DB info */
3670 key.mv_data = (void *)name;
3671 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3673 /* Create if requested */
3674 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3676 data.mv_size = sizeof(MDB_db);
3677 data.mv_data = &dummy;
3678 memset(&dummy, 0, sizeof(dummy));
3679 dummy.md_root = P_INVALID;
3680 dummy.md_flags = flags & 0xffff;
3681 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3685 /* OK, got info, add to table */
3686 if (rc == MDB_SUCCESS) {
3687 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3688 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3689 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3690 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3691 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3692 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3693 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3694 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3695 *dbi = txn->mt_numdbs;
3696 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3697 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3704 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3706 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3709 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3712 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3715 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3717 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3718 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3719 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3723 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3725 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3728 txn->mt_dbxs[dbi].md_cmp = cmp;
3732 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3734 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3737 txn->mt_dbxs[dbi].md_dcmp = cmp;
3741 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3743 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3746 txn->mt_dbxs[dbi].md_rel = rel;