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: " fmt "\n", __func__, __LINE__, __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])
260 MDB_ppage mc_stack[32]; /* stack of parent pages */
261 unsigned int mc_snum; /* number of pushed pages */
263 short mc_initialized; /* 1 if initialized */
264 short mc_eof; /* 1 if end is reached */
265 struct MDB_xcursor *mc_xcursor;
268 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
270 typedef struct MDB_node {
271 #define mn_pgno mn_p.np_pgno
272 #define mn_dsize mn_p.np_dsize
274 pgno_t np_pgno; /* child page number */
275 uint32_t np_dsize; /* leaf data size */
277 unsigned int mn_flags:4;
278 unsigned int mn_ksize:12; /* key size */
279 #define F_BIGDATA 0x01 /* data put on overflow page */
280 #define F_SUBDATA 0x02 /* data is a sub-database */
281 #define F_DUPDATA 0x04 /* data has duplicates */
285 typedef struct MDB_dbx {
287 MDB_cmp_func *md_cmp; /* user compare function */
288 MDB_cmp_func *md_dcmp; /* user dupsort function */
289 MDB_rel_func *md_rel; /* user relocate function */
291 unsigned int md_dirty;
295 pgno_t mt_next_pgno; /* next unallocated page */
299 pgno_t *mt_free_pgs; /* this is an IDL */
301 MIDL2 *dirty_list; /* modified pages */
304 MDB_dbx *mt_dbxs; /* array */
306 unsigned int mt_numdbs;
308 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
309 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
310 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
311 unsigned int mt_flags;
314 /* Context for sorted-dup records */
315 typedef struct MDB_xcursor {
316 MDB_cursor mx_cursor;
325 int me_mfd; /* just for writing the meta pages */
326 #define MDB_FATAL_ERROR 0x80000000U
328 uint32_t me_extrapad; /* unused for now */
329 unsigned int me_maxreaders;
330 unsigned int me_numdbs;
331 unsigned int me_maxdbs;
334 MDB_txninfo *me_txns;
335 MDB_meta *me_metas[2];
337 MDB_txn *me_txn; /* current write transaction */
339 off_t me_size; /* current file size */
340 pgno_t me_maxpg; /* me_mapsize / me_psize */
341 unsigned int me_psize;
342 unsigned int me_db_toggle;
343 MDB_dbx *me_dbxs; /* array */
345 MDB_oldpages *me_pghead;
346 pthread_key_t me_txkey; /* thread-key for readers */
347 MDB_dpage *me_dpages;
348 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
349 MIDL2 me_dirty_list[MDB_IDL_DB_SIZE];
352 #define NODESIZE offsetof(MDB_node, mn_data)
354 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
355 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
356 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
357 #define NODEKEY(node) (void *)((node)->mn_data)
358 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
359 #define NODEPGNO(node) ((node)->mn_pgno)
360 #define NODEDSZ(node) ((node)->mn_dsize)
361 #define NODEKSZ(node) ((node)->mn_ksize)
362 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
364 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
366 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
368 static int mdb_search_page_root(MDB_txn *txn,
369 MDB_dbi dbi, MDB_val *key,
370 MDB_cursor *cursor, int modify,
371 MDB_pageparent *mpp);
372 static int mdb_search_page(MDB_txn *txn,
373 MDB_dbi dbi, MDB_val *key,
374 MDB_cursor *cursor, int modify,
375 MDB_pageparent *mpp);
377 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
378 static int mdb_env_read_meta(MDB_env *env, int *which);
379 static int mdb_env_write_meta(MDB_txn *txn);
380 static MDB_page *mdb_get_page(MDB_txn *txn, pgno_t pgno);
382 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
383 MDB_val *key, int *exactp, unsigned int *kip);
384 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
385 indx_t indx, MDB_val *key, MDB_val *data,
386 pgno_t pgno, uint8_t flags);
387 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
388 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
389 MDB_pageparent *mpp, MDB_node *leaf);
390 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
391 MDB_val *key, MDB_val *data, unsigned int flags);
392 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
394 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
395 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
396 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
397 MDB_pageparent *src, indx_t srcindx,
398 MDB_pageparent *dst, indx_t dstindx);
399 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
400 MDB_pageparent *dst);
401 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
402 unsigned int *newindxp, MDB_val *newkey,
403 MDB_val *newdata, pgno_t newpgno);
404 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
406 static void cursor_pop_page(MDB_cursor *cursor);
407 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
410 static int mdb_sibling(MDB_cursor *cursor, int move_right);
411 static int mdb_cursor_next(MDB_cursor *cursor,
412 MDB_val *key, MDB_val *data, MDB_cursor_op op);
413 static int mdb_cursor_prev(MDB_cursor *cursor,
414 MDB_val *key, MDB_val *data, MDB_cursor_op op);
415 static int mdb_cursor_set(MDB_cursor *cursor,
416 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
417 static int mdb_cursor_first(MDB_cursor *cursor,
418 MDB_val *key, MDB_val *data);
419 static int mdb_cursor_last(MDB_cursor *cursor,
420 MDB_val *key, MDB_val *data);
422 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
423 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node);
424 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
426 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
428 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
430 static int memncmp(const void *s1, size_t n1,
431 const void *s2, size_t n2);
432 static int memnrcmp(const void *s1, size_t n1,
433 const void *s2, size_t n2);
436 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
438 int diff, len_diff = -1;
441 len_diff = (n1 > n2);
444 diff = memcmp(s1, s2, n1);
445 return diff ? diff : len_diff;
449 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
451 const unsigned char *p1, *p2, *p1_lim;
458 p1 = (const unsigned char *)s1 + n1 - 1;
459 p2 = (const unsigned char *)s2 + n2 - 1;
461 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
463 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
469 mdb_version(int *maj, int *min, int *pat)
471 *maj = MDB_VERSION_MAJOR;
472 *min = MDB_VERSION_MINOR;
473 *pat = MDB_VERSION_PATCH;
474 return MDB_VERSION_STRING;
477 static char *const errstr[] = {
478 "MDB_KEYEXIST: Key/data pair already exists",
479 "MDB_NOTFOUND: No matching key/data pair found",
480 "MDB_PAGE_NOTFOUND: Requested page not found",
481 "MDB_CORRUPTED: Located page was wrong type",
482 "MDB_PANIC: Update of meta page failed",
483 "MDB_VERSION_MISMATCH: Database environment version mismatch"
487 mdb_strerror(int err)
490 return ("Successful return: 0");
492 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
493 return errstr[err - MDB_KEYEXIST];
495 return strerror(err);
499 mdb_dkey(MDB_val *key, char *buf)
502 unsigned char *c = key->mv_data;
504 if (key->mv_size > MAXKEYSIZE)
506 for (i=0; i<key->mv_size; i++)
507 ptr += sprintf(ptr, "%02x", *c++);
512 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
514 if (txn->mt_dbxs[dbi].md_cmp)
515 return txn->mt_dbxs[dbi].md_cmp(a, b);
517 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
518 #if __BYTE_ORDER == __LITTLE_ENDIAN
522 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
524 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
528 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
530 if (txn->mt_dbxs[dbi].md_dcmp)
531 return txn->mt_dbxs[dbi].md_dcmp(a, b);
533 if (txn->mt_dbs[dbi].md_flags & (0
534 #if __BYTE_ORDER == __LITTLE_ENDIAN
538 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
540 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
543 /* Allocate new page(s) for writing */
545 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
548 pgno_t pgno = P_INVALID;
552 if (txn->mt_txnid > 2) {
554 oldest = txn->mt_txnid - 2;
555 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
556 /* See if there's anything in the free DB */
561 mpp.mp_parent = NULL;
563 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
564 leaf = NODEPTR(mpp.mp_page, 0);
565 kptr = (ULONG *)NODEKEY(leaf);
567 /* It's potentially usable, unless there are still
568 * older readers outstanding. Grab it.
570 if (oldest > *kptr) {
575 mdb_read_data(txn, leaf, &data);
576 idl = (ULONG *)data.mv_data;
577 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
578 mop->mo_next = txn->mt_env->me_pghead;
579 mop->mo_txnid = *kptr;
580 txn->mt_env->me_pghead = mop;
581 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
586 DPRINTF("IDL read txn %lu root %lu num %lu",
587 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
588 for (i=0; i<idl[0]; i++) {
589 DPRINTF("IDL %lu", idl[i+1]);
593 /* drop this IDL from the DB */
594 mpp.mp_parent = NULL;
596 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
597 leaf = NODEPTR(mpp.mp_page, 0);
598 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
601 if (txn->mt_env->me_pghead) {
603 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
604 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
607 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
609 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
610 MDB_oldpages *mop = txn->mt_env->me_pghead;
611 txn->mt_oldest = oldest;
613 /* FIXME: For now, always use fresh pages. We
614 * really ought to search the free list for a
619 /* peel pages off tail, so we only have to truncate the list */
620 pgno = MDB_IDL_LAST(mop->mo_pages);
621 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
623 if (mop->mo_pages[2] > mop->mo_pages[1])
624 mop->mo_pages[0] = 0;
628 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
629 txn->mt_env->me_pghead = mop->mo_next;
637 if (pgno == P_INVALID) {
638 /* DB size is maxed out */
639 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
642 if (txn->mt_env->me_dpages && num == 1) {
643 dp = txn->mt_env->me_dpages;
644 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
646 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
650 dp->h.md_parent = parent;
651 dp->h.md_pi = parent_idx;
652 if (pgno == P_INVALID) {
653 dp->p.mp_pgno = txn->mt_next_pgno;
654 txn->mt_next_pgno += num;
656 dp->p.mp_pgno = pgno;
658 mid.mid = dp->p.mp_pgno;
660 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
665 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
668 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
670 MDB_page *mp = pp->mp_page;
675 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
677 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
679 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
680 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
681 pgno = dp->p.mp_pgno;
682 memcpy(&dp->p, mp, txn->mt_env->me_psize);
685 mp->mp_flags |= P_DIRTY;
687 /* Update the page number to new touched page. */
688 if (pp->mp_parent != NULL)
689 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
696 mdb_env_sync(MDB_env *env, int force)
699 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
700 if (fdatasync(env->me_fd))
707 mdb_txn_reset0(MDB_txn *txn);
710 mdb_txn_renew0(MDB_txn *txn)
712 MDB_env *env = txn->mt_env;
716 if (env->me_flags & MDB_FATAL_ERROR) {
717 DPUTS("mdb_txn_begin: environment had fatal error, must shutdown!");
721 if (!(txn->mt_flags & MDB_TXN_RDONLY)) {
722 txn->mt_u.dirty_list = env->me_dirty_list;
723 txn->mt_u.dirty_list[0].mid = 0;
724 txn->mt_free_pgs = env->me_free_pgs;
725 txn->mt_free_pgs[0] = 0;
727 pthread_mutex_lock(&env->me_txns->mti_wmutex);
728 env->me_txns->mti_txnid++;
731 txn->mt_txnid = env->me_txns->mti_txnid;
733 if (txn->mt_flags & MDB_TXN_RDONLY) {
734 MDB_reader *r = pthread_getspecific(env->me_txkey);
737 pthread_mutex_lock(&env->me_txns->mti_mutex);
738 for (i=0; i<env->me_txns->mti_numreaders; i++)
739 if (env->me_txns->mti_readers[i].mr_pid == 0)
741 if (i == env->me_maxreaders) {
742 pthread_mutex_unlock(&env->me_txns->mti_mutex);
745 env->me_txns->mti_readers[i].mr_pid = getpid();
746 env->me_txns->mti_readers[i].mr_tid = pthread_self();
747 r = &env->me_txns->mti_readers[i];
748 pthread_setspecific(env->me_txkey, r);
749 if (i >= env->me_txns->mti_numreaders)
750 env->me_txns->mti_numreaders = i+1;
751 pthread_mutex_unlock(&env->me_txns->mti_mutex);
753 r->mr_txnid = txn->mt_txnid;
754 txn->mt_u.reader = r;
759 toggle = env->me_txns->mti_me_toggle;
760 if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
765 /* Copy the DB arrays */
766 txn->mt_numdbs = env->me_numdbs;
767 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
768 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
769 if (txn->mt_numdbs > 2)
770 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
771 (txn->mt_numdbs - 2) * sizeof(MDB_db));
773 if (!(txn->mt_flags & MDB_TXN_RDONLY)) {
775 txn->mt_flags |= MDB_TXN_METOGGLE;
776 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
779 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
780 txn->mt_txnid, (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 env->me_txns->mti_txnid--;
866 for (i=2; i<env->me_numdbs; i++)
867 env->me_dbxs[i].md_dirty = 0;
868 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
873 mdb_txn_reset(MDB_txn *txn)
878 DPRINTF("reset txn %p %lu%c on mdbenv %p, root page %lu", txn,
879 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
880 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
886 mdb_txn_abort(MDB_txn *txn)
891 DPRINTF("abort txn %p %lu%c on mdbenv %p, root page %lu", txn,
892 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
893 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
900 mdb_txn_commit(MDB_txn *txn)
909 struct iovec iov[MDB_COMMIT_PAGES];
912 assert(txn->mt_env != NULL);
916 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
921 if (txn != env->me_txn) {
922 DPUTS("attempt to commit unknown transaction");
927 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
928 DPUTS("error flag is set, can't commit");
933 if (!txn->mt_u.dirty_list[0].mid)
936 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
937 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
939 /* should only be one record now */
940 if (env->me_pghead) {
944 mop = env->me_pghead;
945 key.mv_size = sizeof(pgno_t);
946 key.mv_data = (char *)&mop->mo_txnid;
947 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
948 data.mv_data = mop->mo_pages;
949 mdb_put0(txn, FREE_DBI, &key, &data, 0);
950 free(env->me_pghead);
951 env->me_pghead = NULL;
953 /* save to free list */
954 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
958 /* make sure last page of freeDB is touched and on freelist */
959 key.mv_size = MAXKEYSIZE+1;
961 mpp.mp_parent = NULL;
963 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
968 ULONG *idl = txn->mt_free_pgs;
969 DPRINTF("IDL write txn %lu root %lu num %lu",
970 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
971 for (i=0; i<idl[0]; i++) {
972 DPRINTF("IDL %lu", idl[i+1]);
976 /* write to last page of freeDB */
977 key.mv_size = sizeof(pgno_t);
978 key.mv_data = (char *)&txn->mt_txnid;
979 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
980 data.mv_data = txn->mt_free_pgs;
981 mdb_put0(txn, FREE_DBI, &key, &data, 0);
984 /* Update DB root pointers. Their pages have already been
985 * touched so this is all in-place and cannot fail.
989 data.mv_size = sizeof(MDB_db);
991 for (i = 2; i < txn->mt_numdbs; i++) {
992 if (txn->mt_dbxs[i].md_dirty) {
993 data.mv_data = &txn->mt_dbs[i];
994 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
999 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1007 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1008 dp = txn->mt_u.dirty_list[i].mptr;
1009 if (dp->p.mp_pgno != next) {
1011 DPRINTF("committing %u dirty pages", n);
1012 rc = writev(env->me_fd, iov, n);
1016 DPUTS("short write, filesystem full?");
1018 DPRINTF("writev: %s", strerror(errno));
1025 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1026 next = dp->p.mp_pgno;
1028 DPRINTF("committing page %lu", dp->p.mp_pgno);
1029 iov[n].iov_len = env->me_psize * dp->h.md_num;
1030 iov[n].iov_base = &dp->p;
1031 size += iov[n].iov_len;
1032 next = dp->p.mp_pgno + dp->h.md_num;
1033 /* clear dirty flag */
1034 dp->p.mp_flags &= ~P_DIRTY;
1035 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;
1071 if ((n = mdb_env_sync(env, 0)) != 0 ||
1072 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1079 /* update the DB tables */
1081 int toggle = !env->me_db_toggle;
1083 for (i = 2; i < env->me_numdbs; i++) {
1084 if (txn->mt_dbxs[i].md_dirty) {
1085 env->me_dbs[toggle][i] = txn->mt_dbs[i];
1086 txn->mt_dbxs[i].md_dirty = 0;
1089 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1090 txn->mt_dbxs[i].md_dirty = 0;
1091 env->me_dbxs[i] = txn->mt_dbxs[i];
1092 env->me_dbs[toggle][i] = txn->mt_dbs[i];
1094 env->me_db_toggle = toggle;
1095 env->me_numdbs = txn->mt_numdbs;
1098 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
1105 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1107 char page[PAGESIZE];
1112 assert(env != NULL);
1114 /* We don't know the page size yet, so use a minimum value.
1117 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
1119 } else if (rc != PAGESIZE) {
1122 DPRINTF("read: %s", strerror(errno));
1126 p = (MDB_page *)page;
1128 if (!F_ISSET(p->mp_flags, P_META)) {
1129 DPRINTF("page %lu not a meta page", p->mp_pgno);
1134 if (m->mm_magic != MDB_MAGIC) {
1135 DPUTS("meta has invalid magic");
1139 if (m->mm_version != MDB_VERSION) {
1140 DPRINTF("database is version %u, expected version %u",
1141 m->mm_version, MDB_VERSION);
1142 return MDB_VERSION_MISMATCH;
1145 memcpy(meta, m, sizeof(*m));
1150 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1157 DPUTS("writing new meta page");
1158 psize = sysconf(_SC_PAGE_SIZE);
1160 meta->mm_magic = MDB_MAGIC;
1161 meta->mm_version = MDB_VERSION;
1162 meta->mm_psize = psize;
1163 meta->mm_last_pg = 1;
1164 meta->mm_flags = env->me_flags & 0xffff;
1165 meta->mm_flags |= MDB_INTEGERKEY;
1166 meta->mm_dbs[0].md_root = P_INVALID;
1167 meta->mm_dbs[1].md_root = P_INVALID;
1169 p = calloc(2, psize);
1171 p->mp_flags = P_META;
1174 memcpy(m, meta, sizeof(*meta));
1176 q = (MDB_page *)((char *)p + psize);
1179 q->mp_flags = P_META;
1182 memcpy(m, meta, sizeof(*meta));
1184 rc = write(env->me_fd, p, psize * 2);
1186 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1190 mdb_env_write_meta(MDB_txn *txn)
1193 MDB_meta meta, metab;
1195 int rc, len, toggle;
1198 assert(txn != NULL);
1199 assert(txn->mt_env != NULL);
1201 toggle = !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE);
1202 DPRINTF("writing meta page %d for root page %lu",
1203 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1207 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1208 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1210 ptr = (char *)&meta;
1211 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1212 len = sizeof(MDB_meta) - off;
1215 meta.mm_dbs[0] = txn->mt_dbs[0];
1216 meta.mm_dbs[1] = txn->mt_dbs[1];
1217 meta.mm_last_pg = txn->mt_next_pgno - 1;
1218 meta.mm_txnid = txn->mt_txnid;
1221 off += env->me_psize;
1224 /* Write to the SYNC fd */
1225 rc = pwrite(env->me_mfd, ptr, len, off);
1229 DPUTS("write failed, disk error?");
1230 /* On a failure, the pagecache still contains the new data.
1231 * Write some old data back, to prevent it from being used.
1232 * Use the non-SYNC fd; we know it will fail anyway.
1234 meta.mm_last_pg = metab.mm_last_pg;
1235 meta.mm_txnid = metab.mm_txnid;
1236 r2 = pwrite(env->me_fd, ptr, len, off);
1237 env->me_flags |= MDB_FATAL_ERROR;
1240 txn->mt_env->me_txns->mti_me_toggle = toggle;
1246 mdb_env_read_meta(MDB_env *env, int *which)
1250 assert(env != NULL);
1254 else if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1257 if (env->me_meta != env->me_metas[toggle])
1258 env->me_meta = env->me_metas[toggle];
1260 DPRINTF("Using meta page %d", toggle);
1266 mdb_env_create(MDB_env **env)
1270 e = calloc(1, sizeof(MDB_env));
1271 if (!e) return ENOMEM;
1273 e->me_maxreaders = DEFAULT_READERS;
1283 mdb_env_set_mapsize(MDB_env *env, size_t size)
1287 env->me_mapsize = size;
1292 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1294 env->me_maxdbs = dbs;
1299 mdb_env_set_maxreaders(MDB_env *env, int readers)
1301 env->me_maxreaders = readers;
1306 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1308 if (!env || !readers)
1310 *readers = env->me_maxreaders;
1315 mdb_env_open2(MDB_env *env, unsigned int flags)
1321 env->me_flags = flags;
1323 memset(&meta, 0, sizeof(meta));
1325 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1328 DPUTS("new mdbenv");
1332 if (!env->me_mapsize) {
1333 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1337 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1339 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1341 if (env->me_map == MAP_FAILED)
1345 meta.mm_mapsize = env->me_mapsize;
1346 if (flags & MDB_FIXEDMAP)
1347 meta.mm_address = env->me_map;
1348 i = mdb_env_init_meta(env, &meta);
1349 if (i != MDB_SUCCESS) {
1350 munmap(env->me_map, env->me_mapsize);
1354 env->me_psize = meta.mm_psize;
1356 env->me_maxpg = env->me_mapsize / env->me_psize;
1358 p = (MDB_page *)env->me_map;
1359 env->me_metas[0] = METADATA(p);
1360 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1362 if ((i = mdb_env_read_meta(env, NULL)) != 0)
1365 DPRINTF("opened database version %u, pagesize %u",
1366 env->me_meta->mm_version, env->me_psize);
1367 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1368 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1369 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1370 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1371 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1372 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1378 mdb_env_reader_dest(void *ptr)
1380 MDB_reader *reader = ptr;
1382 reader->mr_txnid = 0;
1387 /* downgrade the exclusive lock on the region back to shared */
1389 mdb_env_share_locks(MDB_env *env)
1391 struct flock lock_info;
1393 env->me_txns->mti_txnid = env->me_meta->mm_txnid;
1394 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1395 env->me_txns->mti_me_toggle = 1;
1397 memset((void *)&lock_info, 0, sizeof(lock_info));
1398 lock_info.l_type = F_RDLCK;
1399 lock_info.l_whence = SEEK_SET;
1400 lock_info.l_start = 0;
1401 lock_info.l_len = 1;
1402 fcntl(env->me_lfd, F_SETLK, &lock_info);
1406 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1410 struct flock lock_info;
1414 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1418 /* Try to get exclusive lock. If we succeed, then
1419 * nobody is using the lock region and we should initialize it.
1421 memset((void *)&lock_info, 0, sizeof(lock_info));
1422 lock_info.l_type = F_WRLCK;
1423 lock_info.l_whence = SEEK_SET;
1424 lock_info.l_start = 0;
1425 lock_info.l_len = 1;
1426 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1430 lock_info.l_type = F_RDLCK;
1431 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1437 size = lseek(env->me_lfd, 0, SEEK_END);
1438 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1439 if (size < rsize && *excl) {
1440 if (ftruncate(env->me_lfd, rsize) != 0) {
1446 size = rsize - sizeof(MDB_txninfo);
1447 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1449 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1451 if (env->me_txns == MAP_FAILED) {
1456 pthread_mutexattr_t mattr;
1458 pthread_mutexattr_init(&mattr);
1459 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1463 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1464 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1465 env->me_txns->mti_version = MDB_VERSION;
1466 env->me_txns->mti_magic = MDB_MAGIC;
1467 env->me_txns->mti_txnid = 0;
1468 env->me_txns->mti_numreaders = 0;
1469 env->me_txns->mti_me_toggle = 0;
1472 if (env->me_txns->mti_magic != MDB_MAGIC) {
1473 DPUTS("lock region has invalid magic");
1477 if (env->me_txns->mti_version != MDB_VERSION) {
1478 DPRINTF("lock region is version %u, expected version %u",
1479 env->me_txns->mti_version, MDB_VERSION);
1480 rc = MDB_VERSION_MISMATCH;
1483 if (errno != EACCES && errno != EAGAIN) {
1497 #define LOCKNAME "/lock.mdb"
1498 #define DATANAME "/data.mdb"
1500 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1502 int oflags, rc, len, excl;
1503 char *lpath, *dpath;
1506 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1509 dpath = lpath + len + sizeof(LOCKNAME);
1510 sprintf(lpath, "%s" LOCKNAME, path);
1511 sprintf(dpath, "%s" DATANAME, path);
1513 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1517 if (F_ISSET(flags, MDB_RDONLY))
1520 oflags = O_RDWR | O_CREAT;
1522 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1527 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1528 /* synchronous fd for meta writes */
1529 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1530 oflags |= MDB_DSYNC;
1531 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1536 env->me_path = strdup(path);
1537 DPRINTF("opened dbenv %p", (void *) env);
1538 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1540 mdb_env_share_locks(env);
1541 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1542 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1543 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1549 if (env->me_fd >= 0) {
1553 if (env->me_lfd >= 0) {
1563 mdb_env_close(MDB_env *env)
1570 while (env->me_dpages) {
1571 dp = env->me_dpages;
1572 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1576 free(env->me_dbs[1]);
1577 free(env->me_dbs[0]);
1581 pthread_key_delete(env->me_txkey);
1584 munmap(env->me_map, env->me_mapsize);
1589 pid_t pid = getpid();
1590 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1592 for (i=0; i<env->me_txns->mti_numreaders; i++)
1593 if (env->me_txns->mti_readers[i].mr_pid == pid)
1594 env->me_txns->mti_readers[i].mr_pid = 0;
1595 munmap(env->me_txns, size);
1601 /* Search for key within a leaf page, using binary search.
1602 * Returns the smallest entry larger or equal to the key.
1603 * If exactp is non-null, stores whether the found entry was an exact match
1604 * in *exactp (1 or 0).
1605 * If kip is non-null, stores the index of the found entry in *kip.
1606 * If no entry larger or equal to the key is found, returns NULL.
1609 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1610 int *exactp, unsigned int *kip)
1615 MDB_node *node = NULL;
1619 DPRINTF("searching %u keys in %s page %lu",
1621 IS_LEAF(mp) ? "leaf" : "branch",
1624 assert(NUMKEYS(mp) > 0);
1626 memset(&nodekey, 0, sizeof(nodekey));
1628 low = IS_LEAF(mp) ? 0 : 1;
1629 high = NUMKEYS(mp) - 1;
1630 while (low <= high) {
1631 i = (low + high) >> 1;
1634 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
1635 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
1637 node = NODEPTR(mp, i);
1639 nodekey.mv_size = node->mn_ksize;
1640 nodekey.mv_data = NODEKEY(node);
1643 rc = mdb_cmp(txn, dbi, key, &nodekey);
1646 DPRINTF("found leaf index %u [%s], rc = %i",
1647 i, DKEY(&nodekey), rc);
1649 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
1650 i, DKEY(&nodekey), NODEPGNO(node), rc);
1660 if (rc > 0) { /* Found entry is less than the key. */
1661 i++; /* Skip to get the smallest entry larger than key. */
1662 if (i >= NUMKEYS(mp))
1663 /* There is no entry larger or equal to the key. */
1667 *exactp = (rc == 0);
1668 if (kip) /* Store the key index if requested. */
1671 /* nodeptr is fake for LEAF2 */
1672 return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
1676 cursor_pop_page(MDB_cursor *cursor)
1680 if (cursor->mc_snum) {
1681 top = CURSOR_TOP(cursor);
1684 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
1685 cursor->mc_dbi, (void *) cursor);
1690 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1694 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
1695 cursor->mc_dbi, (void *) cursor);
1697 ppage = &cursor->mc_stack[cursor->mc_snum++];
1698 ppage->mp_page = mp;
1704 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1709 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1714 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1715 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1716 dp = txn->mt_u.dirty_list[x].mptr;
1722 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1724 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1730 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1731 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1733 MDB_page *mp = mpp->mp_page;
1737 if (cursor && cursor_push_page(cursor, mp) == NULL)
1740 while (IS_BRANCH(mp)) {
1744 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1745 assert(NUMKEYS(mp) > 1);
1746 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1748 if (key == NULL) /* Initialize cursor to first page. */
1750 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1751 /* cursor to last page */
1755 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1757 i = NUMKEYS(mp) - 1;
1765 DPRINTF("following index %u for key [%s]",
1767 assert(i < NUMKEYS(mp));
1768 node = NODEPTR(mp, i);
1771 CURSOR_TOP(cursor)->mp_ki = i;
1773 mpp->mp_parent = mp;
1774 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1775 return MDB_PAGE_NOTFOUND;
1779 if (cursor && cursor_push_page(cursor, mp) == NULL)
1783 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1784 if ((rc = mdb_touch(txn, mpp)) != 0)
1786 dh = ((MDB_dhead *)mpp->mp_page)-1;
1787 dh->md_parent = mpp->mp_parent;
1788 dh->md_pi = mpp->mp_pi;
1795 DPRINTF("internal error, index points to a %02X page!?",
1797 return MDB_CORRUPTED;
1800 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
1801 key ? DKEY(key) : NULL);
1806 /* Search for the page a given key should be in.
1807 * Stores a pointer to the found page in *mpp.
1808 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1809 * If cursor is non-null, pushes parent pages on the cursor stack.
1810 * If modify is true, visited pages are updated with new page numbers.
1813 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1814 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1819 /* Choose which root page to start with. If a transaction is given
1820 * use the root page from the transaction, otherwise read the last
1821 * committed root page.
1823 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1824 DPUTS("transaction has failed, must abort");
1827 root = txn->mt_dbs[dbi].md_root;
1829 if (root == P_INVALID) { /* Tree is empty. */
1830 DPUTS("tree is empty");
1831 return MDB_NOTFOUND;
1834 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1835 return MDB_PAGE_NOTFOUND;
1837 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1840 /* For sub-databases, update main root first */
1841 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1843 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1847 txn->mt_dbxs[dbi].md_dirty = 1;
1849 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1850 mpp->mp_parent = NULL;
1852 if ((rc = mdb_touch(txn, mpp)))
1854 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1858 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1862 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1864 MDB_page *omp; /* overflow mpage */
1867 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1868 data->mv_size = leaf->mn_dsize;
1869 data->mv_data = NODEDATA(leaf);
1873 /* Read overflow data.
1875 data->mv_size = leaf->mn_dsize;
1876 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1877 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1878 DPRINTF("read overflow page %lu failed", pgno);
1879 return MDB_PAGE_NOTFOUND;
1881 data->mv_data = METADATA(omp);
1887 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1888 MDB_val *key, MDB_val *data)
1897 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
1899 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1902 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1906 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1909 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1910 if (leaf && exact) {
1911 /* Return first duplicate data item */
1912 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
1915 mdb_xcursor_init0(txn, dbi, &mx);
1916 mdb_xcursor_init1(txn, dbi, &mx, leaf);
1917 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1918 if (rc != MDB_SUCCESS)
1920 if (IS_LEAF2(mpp.mp_page)) {
1921 data->mv_size = txn->mt_dbs[dbi].md_pad;
1922 data->mv_data = LEAF2KEY(mpp.mp_page, 0, data->mv_size);
1924 leaf = NODEPTR(mpp.mp_page, 0);
1925 data->mv_size = NODEKSZ(leaf);
1926 data->mv_data = NODEKEY(leaf);
1929 rc = mdb_read_data(txn, leaf, data);
1939 mdb_sibling(MDB_cursor *cursor, int move_right)
1946 if (cursor->mc_snum < 2) {
1947 return MDB_NOTFOUND; /* root has no siblings */
1949 parent = CURSOR_PARENT(cursor);
1951 DPRINTF("parent page is page %lu, index %u",
1952 parent->mp_page->mp_pgno, parent->mp_ki);
1954 cursor_pop_page(cursor);
1955 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1956 : (parent->mp_ki == 0)) {
1957 DPRINTF("no more keys left, moving to %s sibling",
1958 move_right ? "right" : "left");
1959 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1961 parent = CURSOR_TOP(cursor);
1967 DPRINTF("just moving to %s index key %u",
1968 move_right ? "right" : "left", parent->mp_ki);
1970 assert(IS_BRANCH(parent->mp_page));
1972 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1973 if ((mp = mdb_get_page(cursor->mc_txn, NODEPGNO(indx))) == NULL)
1974 return MDB_PAGE_NOTFOUND;
1976 mp->parent = parent->mp_page;
1977 mp->parent_index = parent->mp_ki;
1980 cursor_push_page(cursor, mp);
1986 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1993 if (cursor->mc_eof) {
1994 return MDB_NOTFOUND;
1997 assert(cursor->mc_initialized);
1999 top = CURSOR_TOP(cursor);
2002 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2003 leaf = NODEPTR(mp, top->mp_ki);
2004 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2005 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2006 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2007 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2011 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2012 if (op == MDB_NEXT_DUP)
2013 return MDB_NOTFOUND;
2017 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2019 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2020 DPUTS("=====> move to next sibling page");
2021 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2023 return MDB_NOTFOUND;
2025 top = CURSOR_TOP(cursor);
2027 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2031 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2032 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2035 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2036 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2040 assert(IS_LEAF(mp));
2041 leaf = NODEPTR(mp, top->mp_ki);
2043 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2044 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2047 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2050 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2051 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2052 if (rc != MDB_SUCCESS)
2057 MDB_SET_KEY(leaf, key);
2062 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2069 assert(cursor->mc_initialized);
2071 top = CURSOR_TOP(cursor);
2074 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2075 leaf = NODEPTR(mp, top->mp_ki);
2076 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2077 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2078 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2079 if (op != MDB_PREV || rc == MDB_SUCCESS)
2082 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2083 if (op == MDB_PREV_DUP)
2084 return MDB_NOTFOUND;
2089 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2091 if (top->mp_ki == 0) {
2092 DPUTS("=====> move to prev sibling page");
2093 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2094 cursor->mc_initialized = 0;
2095 return MDB_NOTFOUND;
2097 top = CURSOR_TOP(cursor);
2099 top->mp_ki = NUMKEYS(mp) - 1;
2100 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2106 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2107 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2110 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2111 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2115 assert(IS_LEAF(mp));
2116 leaf = NODEPTR(mp, top->mp_ki);
2118 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2119 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2122 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2125 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2126 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2127 if (rc != MDB_SUCCESS)
2132 MDB_SET_KEY(leaf, key);
2137 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2138 MDB_cursor_op op, int *exactp)
2148 assert(key->mv_size > 0);
2150 /* See if we're already on the right page */
2151 if (cursor->mc_initialized) {
2153 top = CURSOR_TOP(cursor);
2154 /* Don't try this for LEAF2 pages. Maybe support that later. */
2155 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2156 leaf = NODEPTR(top->mp_page, 0);
2157 MDB_SET_KEY(leaf, &nodekey);
2158 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2160 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2161 MDB_SET_KEY(leaf, &nodekey);
2162 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2164 /* we're already on the right page */
2165 mpp.mp_page = top->mp_page;
2172 cursor->mc_snum = 0;
2174 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2175 if (rc != MDB_SUCCESS)
2178 assert(IS_LEAF(mpp.mp_page));
2180 top = CURSOR_TOP(cursor);
2182 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2183 if (exactp != NULL && !*exactp) {
2184 /* MDB_SET specified and not an exact match. */
2185 return MDB_NOTFOUND;
2189 DPUTS("===> inexact leaf not found, goto sibling");
2190 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2191 return rc; /* no entries matched */
2192 top = CURSOR_TOP(cursor);
2194 mpp.mp_page = top->mp_page;
2195 assert(IS_LEAF(mpp.mp_page));
2196 leaf = NODEPTR(mpp.mp_page, 0);
2199 cursor->mc_initialized = 1;
2202 if (IS_LEAF2(mpp.mp_page)) {
2203 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2204 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2208 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2209 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2212 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2213 if (op == MDB_SET || op == MDB_SET_RANGE) {
2214 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2217 if (op == MDB_GET_BOTH) {
2222 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2223 if (rc != MDB_SUCCESS)
2226 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2228 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2230 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2232 if (op == MDB_GET_BOTH || rc > 0)
2233 return MDB_NOTFOUND;
2237 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2242 /* The key already matches in all other cases */
2243 if (op == MDB_SET_RANGE)
2244 MDB_SET_KEY(leaf, key);
2245 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2251 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2257 cursor->mc_snum = 0;
2259 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2260 if (rc != MDB_SUCCESS)
2262 assert(IS_LEAF(mpp.mp_page));
2264 leaf = NODEPTR(mpp.mp_page, 0);
2265 cursor->mc_initialized = 1;
2268 if (IS_LEAF2(mpp.mp_page)) {
2269 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2270 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2275 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2276 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2277 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2281 if (cursor->mc_xcursor)
2282 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2283 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2287 MDB_SET_KEY(leaf, key);
2292 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2300 cursor->mc_snum = 0;
2302 lkey.mv_size = MAXKEYSIZE+1;
2303 lkey.mv_data = NULL;
2305 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2306 if (rc != MDB_SUCCESS)
2308 assert(IS_LEAF(mpp.mp_page));
2310 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2311 cursor->mc_initialized = 1;
2314 top = CURSOR_TOP(cursor);
2315 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2317 if (IS_LEAF2(mpp.mp_page)) {
2318 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2319 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2324 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2325 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2326 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2330 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2335 MDB_SET_KEY(leaf, key);
2340 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2350 case MDB_GET_BOTH_RANGE:
2351 if (data == NULL || cursor->mc_xcursor == NULL) {
2358 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2360 } else if (op == MDB_SET_RANGE)
2361 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2363 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2365 case MDB_GET_MULTIPLE:
2367 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2368 !cursor->mc_initialized) {
2373 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2376 case MDB_NEXT_MULTIPLE:
2378 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2382 if (!cursor->mc_initialized)
2383 rc = mdb_cursor_first(cursor, key, data);
2385 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2386 if (rc == MDB_SUCCESS) {
2387 if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2390 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2391 data->mv_size = NUMKEYS(top->mp_page) *
2392 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2393 data->mv_data = METADATA(top->mp_page);
2394 top->mp_ki = NUMKEYS(top->mp_page)-1;
2402 case MDB_NEXT_NODUP:
2403 if (!cursor->mc_initialized)
2404 rc = mdb_cursor_first(cursor, key, data);
2406 rc = mdb_cursor_next(cursor, key, data, op);
2410 case MDB_PREV_NODUP:
2411 if (!cursor->mc_initialized || cursor->mc_eof)
2412 rc = mdb_cursor_last(cursor, key, data);
2414 rc = mdb_cursor_prev(cursor, key, data, op);
2417 rc = mdb_cursor_first(cursor, key, data);
2420 rc = mdb_cursor_last(cursor, key, data);
2423 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2431 /* Allocate a page and initialize it
2434 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2438 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2440 DPRINTF("allocated new mpage %lu, page size %u",
2441 dp->p.mp_pgno, txn->mt_env->me_psize);
2442 dp->p.mp_flags = flags | P_DIRTY;
2443 dp->p.mp_lower = PAGEHDRSZ;
2444 dp->p.mp_upper = txn->mt_env->me_psize;
2446 if (IS_BRANCH(&dp->p))
2447 txn->mt_dbs[dbi].md_branch_pages++;
2448 else if (IS_LEAF(&dp->p))
2449 txn->mt_dbs[dbi].md_leaf_pages++;
2450 else if (IS_OVERFLOW(&dp->p)) {
2451 txn->mt_dbs[dbi].md_overflow_pages += num;
2452 dp->p.mp_pages = num;
2459 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2463 sz = LEAFSIZE(key, data);
2464 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2465 /* put on overflow page */
2466 sz -= data->mv_size - sizeof(pgno_t);
2469 return sz + sizeof(indx_t);
2473 mdb_branch_size(MDB_env *env, MDB_val *key)
2478 if (sz >= env->me_psize / MDB_MINKEYS) {
2479 /* put on overflow page */
2480 /* not implemented */
2481 /* sz -= key->size - sizeof(pgno_t); */
2484 return sz + sizeof(indx_t);
2488 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2489 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2492 size_t node_size = NODESIZE;
2495 MDB_dpage *ofp = NULL; /* overflow page */
2498 assert(mp->mp_upper >= mp->mp_lower);
2500 DPRINTF("add node [%s] to %s page %lu at index %i, key size %zu",
2501 key ? DKEY(key) : NULL,
2502 IS_LEAF(mp) ? "leaf" : "branch",
2503 mp->mp_pgno, indx, key ? key->mv_size : 0);
2506 /* Move higher keys up one slot. */
2507 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2508 char *ptr = LEAF2KEY(mp, indx, ksize);
2509 dif = NUMKEYS(mp) - indx;
2511 memmove(ptr+ksize, ptr, dif*ksize);
2512 /* insert new key */
2513 memcpy(ptr, key->mv_data, ksize);
2515 /* Just using these for counting */
2516 mp->mp_lower += sizeof(indx_t);
2517 mp->mp_upper -= ksize - sizeof(indx_t);
2522 node_size += key->mv_size;
2526 if (F_ISSET(flags, F_BIGDATA)) {
2527 /* Data already on overflow page. */
2528 node_size += sizeof(pgno_t);
2529 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2530 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2531 /* Put data on overflow page. */
2532 DPRINTF("data size is %zu, put on overflow page",
2534 node_size += sizeof(pgno_t);
2535 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2537 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2540 node_size += data->mv_size;
2544 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2545 DPRINTF("not enough room in page %lu, got %u ptrs",
2546 mp->mp_pgno, NUMKEYS(mp));
2547 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2548 mp->mp_upper - mp->mp_lower);
2549 DPRINTF("node size = %zu", node_size);
2553 /* Move higher pointers up one slot. */
2554 for (i = NUMKEYS(mp); i > indx; i--)
2555 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2557 /* Adjust free space offsets. */
2558 ofs = mp->mp_upper - node_size;
2559 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2560 mp->mp_ptrs[indx] = ofs;
2562 mp->mp_lower += sizeof(indx_t);
2564 /* Write the node data. */
2565 node = NODEPTR(mp, indx);
2566 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2567 node->mn_flags = flags;
2569 node->mn_dsize = data->mv_size;
2571 NODEPGNO(node) = pgno;
2574 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2579 if (F_ISSET(flags, F_BIGDATA))
2580 memcpy(node->mn_data + key->mv_size, data->mv_data,
2583 memcpy(node->mn_data + key->mv_size, data->mv_data,
2586 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2588 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2596 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2599 indx_t i, j, numkeys, ptr;
2603 DPRINTF("delete node %u on %s page %lu", indx,
2604 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2605 assert(indx < NUMKEYS(mp));
2608 int x = NUMKEYS(mp) - 1 - indx;
2609 base = LEAF2KEY(mp, indx, ksize);
2611 memmove(base, base + ksize, x * ksize);
2612 mp->mp_lower -= sizeof(indx_t);
2613 mp->mp_upper += ksize - sizeof(indx_t);
2617 node = NODEPTR(mp, indx);
2618 sz = NODESIZE + node->mn_ksize;
2620 if (F_ISSET(node->mn_flags, F_BIGDATA))
2621 sz += sizeof(pgno_t);
2623 sz += NODEDSZ(node);
2626 ptr = mp->mp_ptrs[indx];
2627 numkeys = NUMKEYS(mp);
2628 for (i = j = 0; i < numkeys; i++) {
2630 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2631 if (mp->mp_ptrs[i] < ptr)
2632 mp->mp_ptrs[j] += sz;
2637 base = (char *)mp + mp->mp_upper;
2638 memmove(base + sz, base, ptr - mp->mp_upper);
2640 mp->mp_lower -= sizeof(indx_t);
2645 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2650 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2651 mx->mx_txn.mt_dbs = mx->mx_dbs;
2652 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2653 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2655 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2660 mx->mx_dbxs[dbn+1].md_parent = dbn;
2661 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2662 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2663 mx->mx_dbxs[dbn+1].md_dirty = 0;
2664 mx->mx_txn.mt_numdbs = dbn+2;
2666 mx->mx_cursor.mc_snum = 0;
2667 mx->mx_cursor.mc_txn = &mx->mx_txn;
2668 mx->mx_cursor.mc_dbi = dbn+1;
2672 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node)
2674 MDB_db *db = NODEDATA(node);
2676 mx->mx_dbs[0] = txn->mt_dbs[0];
2677 mx->mx_dbs[1] = txn->mt_dbs[1];
2679 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2684 mx->mx_dbs[dbn] = *db;
2685 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2686 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2687 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2688 mx->mx_txn.mt_oldest = txn->mt_oldest;
2689 mx->mx_txn.mt_u = txn->mt_u;
2690 mx->mx_cursor.mc_initialized = 0;
2691 mx->mx_cursor.mc_eof = 0;
2695 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2697 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2698 txn->mt_oldest = mx->mx_txn.mt_oldest;
2699 txn->mt_u = mx->mx_txn.mt_u;
2700 txn->mt_dbs[0] = mx->mx_dbs[0];
2701 txn->mt_dbs[1] = mx->mx_dbs[1];
2702 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2703 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2705 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2706 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2711 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2714 size_t size = sizeof(MDB_cursor);
2716 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2719 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2720 size += sizeof(MDB_xcursor);
2722 if ((cursor = calloc(1, size)) != NULL) {
2723 cursor->mc_dbi = dbi;
2724 cursor->mc_txn = txn;
2725 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2726 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2727 cursor->mc_xcursor = mx;
2728 mdb_xcursor_init0(txn, dbi, mx);
2739 /* Return the count of duplicate data items for the current key */
2741 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2746 if (mc == NULL || countp == NULL)
2749 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2752 top = CURSOR_TOP(mc);
2753 leaf = NODEPTR(top->mp_page, top->mp_ki);
2754 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2757 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2760 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2766 mdb_cursor_close(MDB_cursor *cursor)
2768 if (cursor != NULL) {
2774 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2776 indx_t ptr, i, numkeys;
2783 node = NODEPTR(mp, indx);
2784 ptr = mp->mp_ptrs[indx];
2785 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
2787 (int)node->mn_ksize, (char *)NODEKEY(node),
2791 delta = key->mv_size - node->mn_ksize;
2793 if (delta > 0 && SIZELEFT(mp) < delta) {
2794 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2798 numkeys = NUMKEYS(mp);
2799 for (i = 0; i < numkeys; i++) {
2800 if (mp->mp_ptrs[i] <= ptr)
2801 mp->mp_ptrs[i] -= delta;
2804 base = (char *)mp + mp->mp_upper;
2805 len = ptr - mp->mp_upper + NODESIZE;
2806 memmove(base - delta, base, len);
2807 mp->mp_upper -= delta;
2809 node = NODEPTR(mp, indx);
2810 node->mn_ksize = key->mv_size;
2813 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2818 /* Move a node from src to dst.
2821 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2822 MDB_pageparent *dst, indx_t dstindx)
2829 /* Mark src and dst as dirty. */
2830 if ((rc = mdb_touch(txn, src)) ||
2831 (rc = mdb_touch(txn, dst)))
2834 if (IS_LEAF2(src->mp_page)) {
2835 srcnode = NODEPTR(src->mp_page, 0); /* fake */
2836 key.mv_size = txn->mt_dbs[dbi].md_pad;
2837 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
2839 data.mv_data = NULL;
2841 srcnode = NODEPTR(src->mp_page, srcindx);
2842 key.mv_size = NODEKSZ(srcnode);
2843 key.mv_data = NODEKEY(srcnode);
2844 data.mv_size = NODEDSZ(srcnode);
2845 data.mv_data = NODEDATA(srcnode);
2847 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
2848 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2851 src->mp_page->mp_pgno,
2852 dstindx, dst->mp_page->mp_pgno);
2854 /* Add the node to the destination page.
2856 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2858 if (rc != MDB_SUCCESS)
2861 /* Delete the node from the source page.
2863 mdb_del_node(src->mp_page, srcindx, key.mv_size);
2865 /* The key value just changed due to del_node, find it again.
2867 if (!IS_LEAF2(src->mp_page)) {
2868 srcnode = NODEPTR(src->mp_page, srcindx);
2869 key.mv_data = NODEKEY(srcnode);
2872 /* Update the parent separators.
2875 if (src->mp_pi != 0) {
2876 DPRINTF("update separator for source page %lu to [%s]",
2877 src->mp_page->mp_pgno, DKEY(&key));
2878 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2879 &key)) != MDB_SUCCESS)
2882 if (IS_BRANCH(src->mp_page)) {
2884 nullkey.mv_size = 0;
2885 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2890 if (dst->mp_pi != 0) {
2891 DPRINTF("update separator for destination page %lu to [%s]",
2892 dst->mp_page->mp_pgno, DKEY(&key));
2893 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2894 &key)) != MDB_SUCCESS)
2897 if (IS_BRANCH(dst->mp_page)) {
2899 nullkey.mv_size = 0;
2900 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2908 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2917 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2919 assert(txn != NULL);
2920 assert(src->mp_parent); /* can't merge root page */
2921 assert(dst->mp_parent);
2923 /* Mark src and dst as dirty. */
2924 if ((rc = mdb_touch(txn, src)) ||
2925 (rc = mdb_touch(txn, dst)))
2928 /* Move all nodes from src to dst.
2930 if (IS_LEAF2(src->mp_page)) {
2931 key.mv_size = txn->mt_dbs[dbi].md_pad;
2932 key.mv_data = METADATA(src->mp_page);
2933 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2934 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2936 if (rc != MDB_SUCCESS)
2938 key.mv_data = (char *)key.mv_data + key.mv_size;
2941 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2942 srcnode = NODEPTR(src->mp_page, i);
2944 key.mv_size = srcnode->mn_ksize;
2945 key.mv_data = NODEKEY(srcnode);
2946 data.mv_size = NODEDSZ(srcnode);
2947 data.mv_data = NODEDATA(srcnode);
2948 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2949 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2950 if (rc != MDB_SUCCESS)
2955 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2956 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2958 /* Unlink the src page from parent.
2960 mdb_del_node(src->mp_parent, src->mp_pi, 0);
2961 if (src->mp_pi == 0) {
2963 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2967 if (IS_LEAF(src->mp_page))
2968 txn->mt_dbs[dbi].md_leaf_pages--;
2970 txn->mt_dbs[dbi].md_branch_pages--;
2972 mpp.mp_page = src->mp_parent;
2973 dh = (MDB_dhead *)src->mp_parent;
2975 mpp.mp_parent = dh->md_parent;
2976 mpp.mp_pi = dh->md_pi;
2978 return mdb_rebalance(txn, dbi, &mpp);
2981 #define FILL_THRESHOLD 250
2984 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2989 indx_t si = 0, di = 0;
2991 assert(txn != NULL);
2992 assert(mpp != NULL);
2994 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2995 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2996 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2998 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2999 DPRINTF("no need to rebalance page %lu, above fill threshold",
3000 mpp->mp_page->mp_pgno);
3004 if (mpp->mp_parent == NULL) {
3005 if (NUMKEYS(mpp->mp_page) == 0) {
3006 DPUTS("tree is completely empty");
3007 txn->mt_dbs[dbi].md_root = P_INVALID;
3008 txn->mt_dbs[dbi].md_depth = 0;
3009 txn->mt_dbs[dbi].md_leaf_pages = 0;
3010 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3011 DPUTS("collapsing root page!");
3012 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3013 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
3014 return MDB_PAGE_NOTFOUND;
3015 txn->mt_dbs[dbi].md_depth--;
3016 txn->mt_dbs[dbi].md_branch_pages--;
3018 DPUTS("root page doesn't need rebalancing");
3022 /* The parent (branch page) must have at least 2 pointers,
3023 * otherwise the tree is invalid.
3025 assert(NUMKEYS(mpp->mp_parent) > 1);
3027 /* Leaf page fill factor is below the threshold.
3028 * Try to move keys from left or right neighbor, or
3029 * merge with a neighbor page.
3034 if (mpp->mp_pi == 0) {
3035 /* We're the leftmost leaf in our parent.
3037 DPUTS("reading right neighbor");
3038 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3039 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
3040 return MDB_PAGE_NOTFOUND;
3041 npp.mp_pi = mpp->mp_pi + 1;
3043 di = NUMKEYS(mpp->mp_page);
3045 /* There is at least one neighbor to the left.
3047 DPUTS("reading left neighbor");
3048 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3049 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
3050 return MDB_PAGE_NOTFOUND;
3051 npp.mp_pi = mpp->mp_pi - 1;
3052 si = NUMKEYS(npp.mp_page) - 1;
3055 npp.mp_parent = mpp->mp_parent;
3057 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3058 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3060 /* If the neighbor page is above threshold and has at least two
3061 * keys, move one key from it.
3063 * Otherwise we should try to merge them.
3065 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3066 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3067 else { /* FIXME: if (has_enough_room()) */
3068 if (mpp->mp_pi == 0)
3069 return mdb_merge(txn, dbi, &npp, mpp);
3071 return mdb_merge(txn, dbi, mpp, &npp);
3076 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3080 /* add overflow pages to free list */
3081 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3085 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3086 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3087 for (i=0; i<ovpages; i++) {
3088 DPRINTF("freed ov page %lu", pg);
3089 mdb_midl_insert(txn->mt_free_pgs, pg);
3093 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3094 txn->mt_dbs[dbi].md_entries--;
3095 rc = mdb_rebalance(txn, dbi, mpp);
3096 if (rc != MDB_SUCCESS)
3097 txn->mt_flags |= MDB_TXN_ERROR;
3103 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3104 MDB_val *key, MDB_val *data,
3113 assert(key != NULL);
3115 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3117 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3120 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3124 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3128 mpp.mp_parent = NULL;
3130 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3133 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3134 if (leaf == NULL || !exact) {
3135 return MDB_NOTFOUND;
3138 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3142 mdb_xcursor_init0(txn, dbi, &mx);
3143 mdb_xcursor_init1(txn, dbi, &mx, leaf);
3144 if (flags == MDB_DEL_DUP) {
3145 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
3146 mdb_xcursor_fini(txn, dbi, &mx);
3147 if (rc != MDB_SUCCESS)
3149 /* If sub-DB still has entries, we're done */
3150 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3151 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3153 txn->mt_dbs[dbi].md_entries--;
3156 /* otherwise fall thru and delete the sub-DB */
3158 /* add all the child DB's pages to the free list */
3159 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3160 NULL, &mx.mx_cursor, 0, &mp2);
3161 if (rc == MDB_SUCCESS) {
3162 MDB_ppage *top, *parent;
3166 cursor_pop_page(&mx.mx_cursor);
3167 if (mx.mx_cursor.mc_snum) {
3168 top = CURSOR_TOP(&mx.mx_cursor);
3169 while (mx.mx_cursor.mc_snum > 1) {
3170 parent = CURSOR_PARENT(&mx.mx_cursor);
3171 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3172 ni = NODEPTR(top->mp_page, i);
3173 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3176 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3177 cursor_pop_page(&mx.mx_cursor);
3180 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3181 top->mp_page = mdb_get_page(&mx.mx_txn, NODEPGNO(ni));
3185 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3190 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
3193 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3196 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3197 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3198 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3199 * refer to a node in the new right sibling page.
3202 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3203 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3206 int rc = MDB_SUCCESS, ins_new = 0;
3209 unsigned int i, j, split_indx;
3211 MDB_val sepkey, rkey, rdata;
3213 MDB_dpage *mdp, *rdp, *pdp;
3217 assert(txn != NULL);
3219 dh = ((MDB_dhead *)*mpp) - 1;
3220 mdp = (MDB_dpage *)dh;
3221 newindx = *newindxp;
3223 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3224 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3225 DKEY(newkey), *newindxp);
3227 if (mdp->h.md_parent == NULL) {
3228 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3231 mdp->h.md_parent = &pdp->p;
3232 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3233 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3234 txn->mt_dbs[dbi].md_depth++;
3236 /* Add left (implicit) pointer. */
3237 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3238 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3241 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3244 /* Create a right sibling. */
3245 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3247 rdp->h.md_parent = mdp->h.md_parent;
3248 rdp->h.md_pi = mdp->h.md_pi + 1;
3249 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3251 split_indx = NUMKEYS(&mdp->p) / 2 + 1;
3253 if (IS_LEAF2(&rdp->p)) {
3256 unsigned int nkeys = NUMKEYS(&mdp->p), lsize, rsize, ksize;
3257 /* Move half of the keys to the right sibling */
3259 x = *newindxp - split_indx;
3260 ksize = txn->mt_dbs[dbi].md_pad;
3261 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3262 rsize = (nkeys - split_indx) * ksize;
3263 lsize = (nkeys - split_indx) * sizeof(indx_t);
3264 mdp->p.mp_lower -= lsize;
3265 rdp->p.mp_lower += lsize;
3266 mdp->p.mp_upper += rsize - lsize;
3267 rdp->p.mp_upper -= rsize - lsize;
3268 sepkey.mv_size = ksize;
3269 if (newindx == split_indx) {
3270 sepkey.mv_data = newkey->mv_data;
3272 sepkey.mv_data = split;
3275 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3276 memcpy(&rdp->p.mp_ptrs, split, rsize);
3277 sepkey.mv_data = &rdp->p.mp_ptrs;
3278 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3279 memcpy(ins, newkey->mv_data, ksize);
3280 mdp->p.mp_lower += sizeof(indx_t);
3281 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3284 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3285 ins = LEAF2KEY(&rdp->p, x, ksize);
3286 memcpy(ins, newkey->mv_data, ksize);
3287 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3288 rdp->p.mp_lower += sizeof(indx_t);
3289 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3296 /* Move half of the keys to the right sibling. */
3297 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3299 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
3300 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
3301 mdp->p.mp_lower = PAGEHDRSZ;
3302 mdp->p.mp_upper = txn->mt_env->me_psize;
3304 /* First find the separating key between the split pages.
3306 memset(&sepkey, 0, sizeof(sepkey));
3307 if (newindx == split_indx) {
3308 sepkey.mv_size = newkey->mv_size;
3309 sepkey.mv_data = newkey->mv_data;
3311 node = NODEPTR(copy, split_indx);
3312 sepkey.mv_size = node->mn_ksize;
3313 sepkey.mv_data = NODEKEY(node);
3317 DPRINTF("separator is [%s]", DKEY(&sepkey));
3319 /* Copy separator key to the parent.
3321 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3322 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3323 &sepkey, NULL, rdp->p.mp_pgno);
3325 /* Right page might now have changed parent.
3326 * Check if left page also changed parent.
3328 if (rdp->h.md_parent != mdp->h.md_parent &&
3329 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3330 mdp->h.md_parent = rdp->h.md_parent;
3331 mdp->h.md_pi = rdp->h.md_pi - 1;
3334 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3335 &sepkey, NULL, rdp->p.mp_pgno, 0);
3337 if (IS_LEAF2(&rdp->p)) {
3340 if (rc != MDB_SUCCESS) {
3345 for (i = j = 0; i <= NUMKEYS(copy); j++) {
3346 if (i < split_indx) {
3347 /* Re-insert in left sibling. */
3350 /* Insert in right sibling. */
3351 if (i == split_indx)
3352 /* Reset insert index for right sibling. */
3353 j = (i == newindx && ins_new);
3357 if (i == newindx && !ins_new) {
3358 /* Insert the original entry that caused the split. */
3359 rkey.mv_data = newkey->mv_data;
3360 rkey.mv_size = newkey->mv_size;
3361 if (IS_LEAF(&mdp->p)) {
3362 rdata.mv_data = newdata->mv_data;
3363 rdata.mv_size = newdata->mv_size;
3370 /* Update page and index for the new key. */
3373 } else if (i == NUMKEYS(copy)) {
3376 node = NODEPTR(copy, i);
3377 rkey.mv_data = NODEKEY(node);
3378 rkey.mv_size = node->mn_ksize;
3379 if (IS_LEAF(&mdp->p)) {
3380 rdata.mv_data = NODEDATA(node);
3381 rdata.mv_size = node->mn_dsize;
3383 pgno = NODEPGNO(node);
3384 flags = node->mn_flags;
3389 if (!IS_LEAF(&mdp->p) && j == 0) {
3390 /* First branch index doesn't need key data. */
3394 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
3402 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3403 MDB_val *key, MDB_val *data, unsigned int flags)
3405 int rc = MDB_SUCCESS, exact;
3409 MDB_val xdata, *rdata, dkey;
3411 char dbuf[PAGESIZE];
3416 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3417 dbi, DKEY(key), key->mv_size, data->mv_size);
3420 mpp.mp_parent = NULL;
3422 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3423 if (rc == MDB_SUCCESS) {
3424 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3425 if (leaf && exact) {
3426 if (flags == MDB_NOOVERWRITE) {
3427 DPRINTF("duplicate key [%s]", DKEY(key));
3428 return MDB_KEYEXIST;
3430 /* there's only a key anyway, so this is a no-op */
3431 if (IS_LEAF2(mpp.mp_page))
3434 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3435 /* Was a single item before, must convert now */
3436 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3437 dkey.mv_size = NODEDSZ(leaf);
3438 dkey.mv_data = dbuf;
3439 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3440 /* data matches, ignore it */
3441 if (!mdb_dcmp(txn, dbi, data, &dkey))
3442 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3443 memset(&dummy, 0, sizeof(dummy));
3444 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3445 dummy.md_pad = data->mv_size;
3446 dummy.md_flags = MDB_DUPFIXED;
3447 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3448 dummy.md_flags |= MDB_INTEGERKEY;
3450 dummy.md_root = P_INVALID;
3451 if (dkey.mv_size == sizeof(MDB_db)) {
3452 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3455 mdb_del_node(mpp.mp_page, ki, 0);
3458 xdata.mv_size = sizeof(MDB_db);
3459 xdata.mv_data = &dummy;
3464 /* same size, just replace it */
3465 if (NODEDSZ(leaf) == data->mv_size) {
3466 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3469 mdb_del_node(mpp.mp_page, ki, 0);
3471 if (leaf == NULL) { /* append if not found */
3472 ki = NUMKEYS(mpp.mp_page);
3473 DPRINTF("appending key at index %i", ki);
3475 } else if (rc == MDB_NOTFOUND) {
3477 /* new file, just write a root leaf page */
3478 DPUTS("allocating new root leaf page");
3479 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3482 mpp.mp_page = &dp->p;
3483 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3484 txn->mt_dbs[dbi].md_depth++;
3485 txn->mt_dbxs[dbi].md_dirty = 1;
3486 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3487 mpp.mp_page->mp_flags |= P_LEAF2;
3493 assert(IS_LEAF(mpp.mp_page));
3494 DPRINTF("there are %u keys, should insert new key at index %i",
3495 NUMKEYS(mpp.mp_page), ki);
3500 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3501 if (SIZELEFT(mpp.mp_page) < nsize) {
3502 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3504 /* There is room already in this leaf page. */
3505 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3508 if (rc != MDB_SUCCESS)
3509 txn->mt_flags |= MDB_TXN_ERROR;
3511 /* Remember if we just added a subdatabase */
3512 if (flags & F_SUBDATA) {
3513 leaf = NODEPTR(mpp.mp_page, ki);
3514 leaf->mn_flags |= F_SUBDATA;
3517 /* Now store the actual data in the child DB. Note that we're
3518 * storing the user data in the keys field, so there are strict
3519 * size limits on dupdata. The actual data fields of the child
3520 * DB are all zero size.
3525 leaf = NODEPTR(mpp.mp_page, ki);
3527 mdb_xcursor_init0(txn, dbi, &mx);
3528 mdb_xcursor_init1(txn, dbi, &mx, leaf);
3531 if (flags == MDB_NODUPDATA)
3532 flags = MDB_NOOVERWRITE;
3533 /* converted, write the original data first */
3535 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3537 leaf->mn_flags |= F_DUPDATA;
3539 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3540 mdb_xcursor_fini(txn, dbi, &mx);
3541 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3544 txn->mt_dbs[dbi].md_entries++;
3552 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3553 MDB_val *key, MDB_val *data, unsigned int flags)
3555 assert(key != NULL);
3556 assert(data != NULL);
3558 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3561 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3565 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3569 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3572 return mdb_put0(txn, dbi, key, data, flags);
3576 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3578 #define CHANGEABLE (MDB_NOSYNC)
3579 if ((flag & CHANGEABLE) != flag)
3582 env->me_flags |= flag;
3584 env->me_flags &= ~flag;
3589 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3594 *arg = env->me_flags;
3599 mdb_env_get_path(MDB_env *env, const char **arg)
3604 *arg = env->me_path;
3609 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3611 arg->ms_psize = env->me_psize;
3612 arg->ms_depth = db->md_depth;
3613 arg->ms_branch_pages = db->md_branch_pages;
3614 arg->ms_leaf_pages = db->md_leaf_pages;
3615 arg->ms_overflow_pages = db->md_overflow_pages;
3616 arg->ms_entries = db->md_entries;
3621 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3623 if (env == NULL || arg == NULL)
3626 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3629 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3639 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3640 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3644 /* Is the DB already open? */
3646 for (i=2; i<txn->mt_numdbs; i++) {
3647 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3648 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3654 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3657 /* Find the DB info */
3659 key.mv_data = (void *)name;
3660 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3662 /* Create if requested */
3663 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3665 data.mv_size = sizeof(MDB_db);
3666 data.mv_data = &dummy;
3667 memset(&dummy, 0, sizeof(dummy));
3668 dummy.md_root = P_INVALID;
3669 dummy.md_flags = flags & 0xffff;
3670 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3674 /* OK, got info, add to table */
3675 if (rc == MDB_SUCCESS) {
3676 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3677 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3678 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3679 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3680 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3681 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3682 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3683 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3684 *dbi = txn->mt_numdbs;
3685 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3686 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3693 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3695 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3698 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3701 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3704 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3706 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3707 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3708 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3712 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3714 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3717 txn->mt_dbxs[dbi].md_cmp = cmp;
3721 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3723 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3726 txn->mt_dbxs[dbi].md_dcmp = cmp;
3730 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3732 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3735 txn->mt_dbxs[dbi].md_rel = rel;