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 /* The DB view is always consistent because all writes are wrapped in
95 * the wmutex. Finer-grained locks aren't necessary.
101 #define LAZY_MUTEX_LOCK(x)
102 #define LAZY_MUTEX_UNLOCK(x)
103 #define LAZY_RWLOCK_UNLOCK(x)
104 #define LAZY_RWLOCK_WRLOCK(x)
105 #define LAZY_RWLOCK_RDLOCK(x)
106 #define LAZY_RWLOCK_DEF(x)
107 #define LAZY_RWLOCK_INIT(x,y)
108 #define LAZY_RWLOCK_DESTROY(x)
110 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
111 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
112 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
113 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
114 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
115 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
116 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
117 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
120 #define P_INVALID (~0UL)
122 #define F_ISSET(w, f) (((w) & (f)) == (f))
124 typedef uint16_t indx_t;
126 #define DEFAULT_READERS 126
127 #define DEFAULT_MAPSIZE 1048576
129 /* Lock descriptor stuff */
131 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
134 typedef struct MDB_rxbody {
140 typedef struct MDB_reader {
143 #define mr_txnid mru.mrx.mrb_txnid
144 #define mr_pid mru.mrx.mrb_pid
145 #define mr_tid mru.mrx.mrb_tid
146 /* cache line alignment */
147 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
151 typedef struct MDB_txbody {
153 uint32_t mtb_version;
154 pthread_mutex_t mtb_mutex;
156 uint32_t mtb_numreaders;
157 uint32_t mtb_me_toggle;
160 typedef struct MDB_txninfo {
163 #define mti_magic mt1.mtb.mtb_magic
164 #define mti_version mt1.mtb.mtb_version
165 #define mti_mutex mt1.mtb.mtb_mutex
166 #define mti_txnid mt1.mtb.mtb_txnid
167 #define mti_numreaders mt1.mtb.mtb_numreaders
168 #define mti_me_toggle mt1.mtb.mtb_me_toggle
169 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
172 pthread_mutex_t mt2_wmutex;
173 #define mti_wmutex mt2.mt2_wmutex
174 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
176 MDB_reader mti_readers[1];
179 /* Common header for all page types. Overflow pages
180 * occupy a number of contiguous pages with no
181 * headers on any page after the first.
183 typedef struct MDB_page { /* represents a page of storage */
184 #define mp_pgno mp_p.p_pgno
186 pgno_t p_pgno; /* page number */
187 void * p_align; /* for IL32P64 */
189 #define P_BRANCH 0x01 /* branch page */
190 #define P_LEAF 0x02 /* leaf page */
191 #define P_OVERFLOW 0x04 /* overflow page */
192 #define P_META 0x08 /* meta page */
193 #define P_DIRTY 0x10 /* dirty page */
194 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
196 #define mp_lower mp_pb.pb.pb_lower
197 #define mp_upper mp_pb.pb.pb_upper
198 #define mp_pages mp_pb.pb_pages
201 indx_t pb_lower; /* lower bound of free space */
202 indx_t pb_upper; /* upper bound of free space */
204 uint32_t pb_pages; /* number of overflow pages */
206 indx_t mp_ptrs[1]; /* dynamic size */
209 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
211 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
212 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
213 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
214 ((env)->me_psize - PAGEHDRSZ))
215 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
216 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
217 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
218 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
220 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
222 typedef struct MDB_db {
223 uint32_t md_pad; /* also ksize for LEAF2 pages */
226 ULONG md_branch_pages;
228 ULONG md_overflow_pages;
236 typedef struct MDB_meta { /* meta (footer) page content */
239 void *mm_address; /* address for fixed mapping */
240 size_t mm_mapsize; /* size of mmap region */
241 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
242 #define mm_psize mm_dbs[0].md_pad
243 #define mm_flags mm_dbs[0].md_flags
244 pgno_t mm_last_pg; /* last used page in file */
245 ULONG mm_txnid; /* txnid that committed this page */
248 typedef struct MDB_dhead { /* a dirty page */
250 unsigned md_pi; /* parent index */
254 typedef struct MDB_dpage {
259 typedef struct MDB_oldpages {
260 struct MDB_oldpages *mo_next;
262 pgno_t mo_pages[1]; /* dynamic */
265 typedef struct MDB_pageparent {
271 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num);
272 static int mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
274 typedef struct MDB_ppage { /* ordered list of pages */
276 unsigned int mp_ki; /* cursor index on page */
279 #define CURSOR_TOP(c) (&(c)->mc_stack[(c)->mc_snum-1])
280 #define CURSOR_PARENT(c) (&(c)->mc_stack[(c)->mc_snum-2])
281 #define CURSOR_STACK 32
287 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
288 unsigned int mc_snum; /* number of pushed pages */
290 short mc_initialized; /* 1 if initialized */
291 short mc_eof; /* 1 if end is reached */
292 struct MDB_xcursor *mc_xcursor;
295 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
297 typedef struct MDB_node {
298 #define mn_pgno mn_p.np_pgno
299 #define mn_dsize mn_p.np_dsize
301 pgno_t np_pgno; /* child page number */
302 uint32_t np_dsize; /* leaf data size */
304 unsigned int mn_flags:4;
305 unsigned int mn_ksize:12; /* key size */
306 #define F_BIGDATA 0x01 /* data put on overflow page */
307 #define F_SUBDATA 0x02 /* data is a sub-database */
308 #define F_DUPDATA 0x04 /* data has duplicates */
312 typedef struct MDB_dbx {
314 MDB_cmp_func *md_cmp; /* user compare function */
315 MDB_cmp_func *md_dcmp; /* user dupsort function */
316 MDB_rel_func *md_rel; /* user relocate function */
318 unsigned int md_dirty;
322 pgno_t mt_next_pgno; /* next unallocated page */
325 pgno_t *mt_free_pgs; /* this is an IDL */
327 MIDL2 *dirty_list; /* modified pages */
330 MDB_dbx *mt_dbxs; /* array */
332 unsigned int mt_numdbs;
334 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
335 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
336 unsigned int mt_flags;
337 unsigned int mt_toggle;
340 /* Context for sorted-dup records */
341 typedef struct MDB_xcursor {
342 MDB_cursor mx_cursor;
351 int me_mfd; /* just for writing the meta pages */
352 #define MDB_FATAL_ERROR 0x80000000U
354 uint32_t me_extrapad; /* unused for now */
355 unsigned int me_maxreaders;
356 unsigned int me_numdbs;
357 unsigned int me_maxdbs;
360 MDB_txninfo *me_txns;
361 MDB_meta *me_metas[2];
362 MDB_txn *me_txn; /* current write transaction */
364 off_t me_size; /* current file size */
365 pgno_t me_maxpg; /* me_mapsize / me_psize */
366 unsigned int me_psize;
367 unsigned int me_db_toggle;
368 MDB_dbx *me_dbxs; /* array */
370 MDB_oldpages *me_pghead;
371 pthread_key_t me_txkey; /* thread-key for readers */
372 MDB_dpage *me_dpages;
373 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
374 MIDL2 me_dirty_list[MDB_IDL_DB_SIZE];
375 LAZY_RWLOCK_DEF(me_dblock);
378 #define NODESIZE offsetof(MDB_node, mn_data)
380 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
381 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
382 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
383 #define NODEKEY(node) (void *)((node)->mn_data)
384 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
385 #define NODEPGNO(node) ((node)->mn_pgno)
386 #define NODEDSZ(node) ((node)->mn_dsize)
387 #define NODEKSZ(node) ((node)->mn_ksize)
388 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
390 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
392 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
394 static int mdb_search_page_root(MDB_txn *txn,
395 MDB_dbi dbi, MDB_val *key,
396 MDB_cursor *cursor, int modify,
397 MDB_pageparent *mpp);
398 static int mdb_search_page(MDB_txn *txn,
399 MDB_dbi dbi, MDB_val *key,
400 MDB_cursor *cursor, int modify,
401 MDB_pageparent *mpp);
403 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
404 static int mdb_env_read_meta(MDB_env *env, int *which);
405 static int mdb_env_write_meta(MDB_txn *txn);
406 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
408 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
409 MDB_val *key, int *exactp, unsigned int *kip);
410 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
411 indx_t indx, MDB_val *key, MDB_val *data,
412 pgno_t pgno, uint8_t flags);
413 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
414 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
415 MDB_pageparent *mpp, MDB_node *leaf);
416 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
417 MDB_val *key, MDB_val *data, unsigned int flags);
418 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
420 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
421 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
422 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
423 MDB_pageparent *src, indx_t srcindx,
424 MDB_pageparent *dst, indx_t dstindx);
425 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
426 MDB_pageparent *dst);
427 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
428 unsigned int *newindxp, MDB_val *newkey,
429 MDB_val *newdata, pgno_t newpgno);
430 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
432 static void cursor_pop_page(MDB_cursor *cursor);
433 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
436 static int mdb_sibling(MDB_cursor *cursor, int move_right);
437 static int mdb_cursor_next(MDB_cursor *cursor,
438 MDB_val *key, MDB_val *data, MDB_cursor_op op);
439 static int mdb_cursor_prev(MDB_cursor *cursor,
440 MDB_val *key, MDB_val *data, MDB_cursor_op op);
441 static int mdb_cursor_set(MDB_cursor *cursor,
442 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
443 static int mdb_cursor_first(MDB_cursor *cursor,
444 MDB_val *key, MDB_val *data);
445 static int mdb_cursor_last(MDB_cursor *cursor,
446 MDB_val *key, MDB_val *data);
448 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
449 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx,
450 MDB_page *mp, MDB_node *node);
451 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
453 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
455 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
457 static int memncmp(const void *s1, size_t n1,
458 const void *s2, size_t n2);
459 static int memnrcmp(const void *s1, size_t n1,
460 const void *s2, size_t n2);
463 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
465 int diff, len_diff = -1;
468 len_diff = (n1 > n2);
471 diff = memcmp(s1, s2, n1);
472 return diff ? diff : len_diff;
476 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
478 const unsigned char *p1, *p2, *p1_lim;
485 p1 = (const unsigned char *)s1 + n1 - 1;
486 p2 = (const unsigned char *)s2 + n2 - 1;
488 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
490 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
496 mdb_version(int *maj, int *min, int *pat)
498 *maj = MDB_VERSION_MAJOR;
499 *min = MDB_VERSION_MINOR;
500 *pat = MDB_VERSION_PATCH;
501 return MDB_VERSION_STRING;
504 static char *const errstr[] = {
505 "MDB_KEYEXIST: Key/data pair already exists",
506 "MDB_NOTFOUND: No matching key/data pair found",
507 "MDB_PAGE_NOTFOUND: Requested page not found",
508 "MDB_CORRUPTED: Located page was wrong type",
509 "MDB_PANIC: Update of meta page failed",
510 "MDB_VERSION_MISMATCH: Database environment version mismatch"
514 mdb_strerror(int err)
517 return ("Successful return: 0");
519 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
520 return errstr[err - MDB_KEYEXIST];
522 return strerror(err);
526 mdb_dkey(MDB_val *key, char *buf)
529 unsigned char *c = key->mv_data;
531 if (key->mv_size > MAXKEYSIZE)
533 for (i=0; i<key->mv_size; i++)
534 ptr += sprintf(ptr, "%02x", *c++);
539 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
541 if (txn->mt_dbxs[dbi].md_cmp)
542 return txn->mt_dbxs[dbi].md_cmp(a, b);
544 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
545 #if __BYTE_ORDER == __LITTLE_ENDIAN
549 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
551 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
555 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
557 if (txn->mt_dbxs[dbi].md_dcmp)
558 return txn->mt_dbxs[dbi].md_dcmp(a, b);
560 if (txn->mt_dbs[dbi].md_flags & (0
561 #if __BYTE_ORDER == __LITTLE_ENDIAN
565 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
567 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
570 /* Allocate new page(s) for writing */
572 mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num)
575 pgno_t pgno = P_INVALID;
578 if (txn->mt_txnid > 2) {
580 if (!txn->mt_env->me_pghead && dbi != FREE_DBI &&
581 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
582 /* See if there's anything in the free DB */
587 mpp.mp_parent = NULL;
589 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
590 leaf = NODEPTR(mpp.mp_page, 0);
591 kptr = (ULONG *)NODEKEY(leaf);
595 oldest = txn->mt_txnid - 1;
596 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
597 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
598 if (mr && mr < oldest)
603 if (oldest > *kptr) {
604 /* It's usable, grab it.
610 mdb_read_data(txn, leaf, &data);
611 idl = (ULONG *)data.mv_data;
612 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
613 mop->mo_next = txn->mt_env->me_pghead;
614 mop->mo_txnid = *kptr;
615 txn->mt_env->me_pghead = mop;
616 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
621 DPRINTF("IDL read txn %lu root %lu num %lu",
622 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
623 for (i=0; i<idl[0]; i++) {
624 DPRINTF("IDL %lu", idl[i+1]);
628 /* drop this IDL from the DB */
629 mpp.mp_parent = NULL;
631 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
632 leaf = NODEPTR(mpp.mp_page, 0);
633 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
636 if (txn->mt_env->me_pghead) {
637 MDB_oldpages *mop = txn->mt_env->me_pghead;
639 /* FIXME: For now, always use fresh pages. We
640 * really ought to search the free list for a
645 /* peel pages off tail, so we only have to truncate the list */
646 pgno = MDB_IDL_LAST(mop->mo_pages);
647 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
649 if (mop->mo_pages[2] > mop->mo_pages[1])
650 mop->mo_pages[0] = 0;
654 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
655 txn->mt_env->me_pghead = mop->mo_next;
662 if (pgno == P_INVALID) {
663 /* DB size is maxed out */
664 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
667 if (txn->mt_env->me_dpages && num == 1) {
668 dp = txn->mt_env->me_dpages;
669 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
671 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
675 dp->h.md_parent = parent;
676 dp->h.md_pi = parent_idx;
677 if (pgno == P_INVALID) {
678 dp->p.mp_pgno = txn->mt_next_pgno;
679 txn->mt_next_pgno += num;
681 dp->p.mp_pgno = pgno;
683 mid.mid = dp->p.mp_pgno;
685 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
690 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
693 mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *pp)
695 MDB_page *mp = pp->mp_page;
700 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
702 if ((dp = mdb_alloc_page(txn, dbi, pp->mp_parent, pp->mp_pi, 1)) == NULL)
704 DPRINTF("touched db %u page %lu -> %lu", dbi, mp->mp_pgno, dp->p.mp_pgno);
705 assert(mp->mp_pgno != dp->p.mp_pgno);
706 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
707 pgno = dp->p.mp_pgno;
708 memcpy(&dp->p, mp, txn->mt_env->me_psize);
711 mp->mp_flags |= P_DIRTY;
713 /* Update the page number to new touched page. */
714 if (pp->mp_parent != NULL)
715 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
722 mdb_env_sync(MDB_env *env, int force)
725 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
726 if (fdatasync(env->me_fd))
733 mdb_txn_reset0(MDB_txn *txn);
736 mdb_txn_renew0(MDB_txn *txn)
738 MDB_env *env = txn->mt_env;
740 if (txn->mt_flags & MDB_TXN_RDONLY) {
741 MDB_reader *r = pthread_getspecific(env->me_txkey);
744 pid_t pid = getpid();
745 pthread_t tid = pthread_self();
747 pthread_mutex_lock(&env->me_txns->mti_mutex);
748 for (i=0; i<env->me_txns->mti_numreaders; i++)
749 if (env->me_txns->mti_readers[i].mr_pid == 0)
751 if (i == env->me_maxreaders) {
752 pthread_mutex_unlock(&env->me_txns->mti_mutex);
755 env->me_txns->mti_readers[i].mr_pid = pid;
756 env->me_txns->mti_readers[i].mr_tid = tid;
757 if (i >= env->me_txns->mti_numreaders)
758 env->me_txns->mti_numreaders = i+1;
759 pthread_mutex_unlock(&env->me_txns->mti_mutex);
760 r = &env->me_txns->mti_readers[i];
761 pthread_setspecific(env->me_txkey, r);
763 txn->mt_txnid = env->me_txns->mti_txnid;
764 txn->mt_toggle = env->me_txns->mti_me_toggle;
765 r->mr_txnid = txn->mt_txnid;
766 txn->mt_u.reader = r;
768 pthread_mutex_lock(&env->me_txns->mti_wmutex);
770 txn->mt_txnid = env->me_txns->mti_txnid+1;
771 txn->mt_toggle = env->me_txns->mti_me_toggle;
772 txn->mt_u.dirty_list = env->me_dirty_list;
773 txn->mt_u.dirty_list[0].mid = 0;
774 txn->mt_free_pgs = env->me_free_pgs;
775 txn->mt_free_pgs[0] = 0;
776 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
780 /* Copy the DB arrays */
781 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
782 txn->mt_numdbs = env->me_numdbs;
783 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
784 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
785 if (txn->mt_numdbs > 2)
786 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
787 (txn->mt_numdbs - 2) * sizeof(MDB_db));
788 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
794 mdb_txn_renew(MDB_txn *txn)
801 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
802 DPUTS("environment had fatal error, must shutdown!");
806 rc = mdb_txn_renew0(txn);
807 if (rc == MDB_SUCCESS) {
808 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
809 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
810 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
816 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
821 if (env->me_flags & MDB_FATAL_ERROR) {
822 DPUTS("environment had fatal error, must shutdown!");
825 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
826 DPRINTF("calloc: %s", strerror(errno));
829 txn->mt_dbs = (MDB_db *)(txn+1);
831 txn->mt_flags |= MDB_TXN_RDONLY;
835 rc = mdb_txn_renew0(txn);
840 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
841 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
842 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
849 mdb_txn_reset0(MDB_txn *txn)
851 MDB_env *env = txn->mt_env;
853 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
854 txn->mt_u.reader->mr_txnid = 0;
860 /* return all dirty pages to dpage list */
861 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
862 dp = txn->mt_u.dirty_list[i].mptr;
863 if (dp->h.md_num == 1) {
864 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
865 txn->mt_env->me_dpages = dp;
867 /* large pages just get freed directly */
872 while ((mop = txn->mt_env->me_pghead)) {
873 txn->mt_env->me_pghead = mop->mo_next;
878 for (i=2; i<env->me_numdbs; i++)
879 env->me_dbxs[i].md_dirty = 0;
880 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
885 mdb_txn_reset(MDB_txn *txn)
890 DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
891 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
892 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
898 mdb_txn_abort(MDB_txn *txn)
903 DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
904 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
905 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
912 mdb_txn_commit(MDB_txn *txn)
921 struct iovec iov[MDB_COMMIT_PAGES];
924 assert(txn->mt_env != NULL);
928 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
933 if (txn != env->me_txn) {
934 DPUTS("attempt to commit unknown transaction");
939 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
940 DPUTS("error flag is set, can't commit");
945 if (!txn->mt_u.dirty_list[0].mid)
948 DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
949 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
951 /* should only be one record now */
952 if (env->me_pghead) {
955 /* make sure first page of freeDB is touched and on freelist */
956 mpp.mp_parent = NULL;
958 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
960 /* save to free list */
961 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
966 /* make sure last page of freeDB is touched and on freelist */
967 key.mv_size = MAXKEYSIZE+1;
969 mpp.mp_parent = NULL;
971 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
976 ULONG *idl = txn->mt_free_pgs;
977 DPRINTF("IDL write txn %lu root %lu num %lu",
978 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
979 for (i=0; i<idl[0]; i++) {
980 DPRINTF("IDL %lu", idl[i+1]);
984 /* write to last page of freeDB */
985 key.mv_size = sizeof(pgno_t);
986 key.mv_data = (char *)&txn->mt_txnid;
987 data.mv_data = txn->mt_free_pgs;
988 /* The free list can still grow during this call,
989 * despite the pre-emptive touches above. So check
990 * and make sure the entire thing got written.
993 i = txn->mt_free_pgs[0];
994 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
995 rc = mdb_put0(txn, FREE_DBI, &key, &data, 0);
1000 } while (i != txn->mt_free_pgs[0]);
1002 /* should only be one record now */
1003 if (env->me_pghead) {
1007 mop = env->me_pghead;
1008 key.mv_size = sizeof(pgno_t);
1009 key.mv_data = (char *)&mop->mo_txnid;
1010 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1011 data.mv_data = mop->mo_pages;
1012 mdb_put0(txn, FREE_DBI, &key, &data, 0);
1013 free(env->me_pghead);
1014 env->me_pghead = NULL;
1017 /* Update DB root pointers. Their pages have already been
1018 * touched so this is all in-place and cannot fail.
1022 data.mv_size = sizeof(MDB_db);
1024 for (i = 2; i < txn->mt_numdbs; i++) {
1025 if (txn->mt_dbxs[i].md_dirty) {
1026 data.mv_data = &txn->mt_dbs[i];
1027 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
1032 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1040 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1041 dp = txn->mt_u.dirty_list[i].mptr;
1042 if (dp->p.mp_pgno != next) {
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 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1059 next = dp->p.mp_pgno;
1061 DPRINTF("committing page %lu", dp->p.mp_pgno);
1062 iov[n].iov_len = env->me_psize * dp->h.md_num;
1063 iov[n].iov_base = &dp->p;
1064 size += iov[n].iov_len;
1065 next = dp->p.mp_pgno + dp->h.md_num;
1066 /* clear dirty flag */
1067 dp->p.mp_flags &= ~P_DIRTY;
1068 if (++n >= MDB_COMMIT_PAGES) {
1078 DPRINTF("committing %u dirty pages", n);
1079 rc = writev(env->me_fd, iov, n);
1083 DPUTS("short write, filesystem full?");
1085 DPRINTF("writev: %s", strerror(errno));
1092 /* Drop the dirty pages.
1094 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1095 dp = txn->mt_u.dirty_list[i].mptr;
1096 if (dp->h.md_num == 1) {
1097 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1098 txn->mt_env->me_dpages = dp;
1102 txn->mt_u.dirty_list[i].mid = 0;
1104 txn->mt_u.dirty_list[0].mid = 0;
1106 if ((n = mdb_env_sync(env, 0)) != 0 ||
1107 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1114 /* update the DB tables */
1116 int toggle = !env->me_db_toggle;
1119 ip = &env->me_dbs[toggle][2];
1120 jp = &txn->mt_dbs[2];
1121 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1122 for (i = 2; i < txn->mt_numdbs; i++) {
1123 if (ip->md_root != jp->md_root)
1128 for (i = 2; i < txn->mt_numdbs; i++) {
1129 if (txn->mt_dbxs[i].md_dirty)
1130 txn->mt_dbxs[i].md_dirty = 0;
1132 env->me_db_toggle = toggle;
1133 env->me_numdbs = txn->mt_numdbs;
1134 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1137 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
1144 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1146 char page[PAGESIZE];
1151 assert(env != NULL);
1153 /* We don't know the page size yet, so use a minimum value.
1156 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
1158 } else if (rc != PAGESIZE) {
1161 DPRINTF("read: %s", strerror(errno));
1165 p = (MDB_page *)page;
1167 if (!F_ISSET(p->mp_flags, P_META)) {
1168 DPRINTF("page %lu not a meta page", p->mp_pgno);
1173 if (m->mm_magic != MDB_MAGIC) {
1174 DPUTS("meta has invalid magic");
1178 if (m->mm_version != MDB_VERSION) {
1179 DPRINTF("database is version %u, expected version %u",
1180 m->mm_version, MDB_VERSION);
1181 return MDB_VERSION_MISMATCH;
1184 memcpy(meta, m, sizeof(*m));
1189 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1196 DPUTS("writing new meta page");
1197 psize = sysconf(_SC_PAGE_SIZE);
1199 meta->mm_magic = MDB_MAGIC;
1200 meta->mm_version = MDB_VERSION;
1201 meta->mm_psize = psize;
1202 meta->mm_last_pg = 1;
1203 meta->mm_flags = env->me_flags & 0xffff;
1204 meta->mm_flags |= MDB_INTEGERKEY;
1205 meta->mm_dbs[0].md_root = P_INVALID;
1206 meta->mm_dbs[1].md_root = P_INVALID;
1208 p = calloc(2, psize);
1210 p->mp_flags = P_META;
1213 memcpy(m, meta, sizeof(*meta));
1215 q = (MDB_page *)((char *)p + psize);
1218 q->mp_flags = P_META;
1221 memcpy(m, meta, sizeof(*meta));
1223 rc = write(env->me_fd, p, psize * 2);
1225 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1229 mdb_env_write_meta(MDB_txn *txn)
1232 MDB_meta meta, metab;
1234 int rc, len, toggle;
1237 assert(txn != NULL);
1238 assert(txn->mt_env != NULL);
1240 toggle = !txn->mt_toggle;
1241 DPRINTF("writing meta page %d for root page %lu",
1242 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1246 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1247 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1249 ptr = (char *)&meta;
1250 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1251 len = sizeof(MDB_meta) - off;
1254 meta.mm_dbs[0] = txn->mt_dbs[0];
1255 meta.mm_dbs[1] = txn->mt_dbs[1];
1256 meta.mm_last_pg = txn->mt_next_pgno - 1;
1257 meta.mm_txnid = txn->mt_txnid;
1260 off += env->me_psize;
1263 /* Write to the SYNC fd */
1264 rc = pwrite(env->me_mfd, ptr, len, off);
1268 DPUTS("write failed, disk error?");
1269 /* On a failure, the pagecache still contains the new data.
1270 * Write some old data back, to prevent it from being used.
1271 * Use the non-SYNC fd; we know it will fail anyway.
1273 meta.mm_last_pg = metab.mm_last_pg;
1274 meta.mm_txnid = metab.mm_txnid;
1275 r2 = pwrite(env->me_fd, ptr, len, off);
1276 env->me_flags |= MDB_FATAL_ERROR;
1279 /* Memory ordering issues are irrelevant; since the entire writer
1280 * is wrapped by wmutex, all of these changes will become visible
1281 * after the wmutex is unlocked. Since the DB is multi-version,
1282 * readers will get consistent data regardless of how fresh or
1283 * how stale their view of these values is.
1285 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1286 txn->mt_env->me_txns->mti_me_toggle = toggle;
1287 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1288 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1294 mdb_env_read_meta(MDB_env *env, int *which)
1298 assert(env != NULL);
1300 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1303 DPRINTF("Using meta page %d", toggle);
1310 mdb_env_create(MDB_env **env)
1314 e = calloc(1, sizeof(MDB_env));
1315 if (!e) return ENOMEM;
1317 e->me_maxreaders = DEFAULT_READERS;
1327 mdb_env_set_mapsize(MDB_env *env, size_t size)
1331 env->me_mapsize = size;
1336 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1338 env->me_maxdbs = dbs;
1343 mdb_env_set_maxreaders(MDB_env *env, int readers)
1345 env->me_maxreaders = readers;
1350 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1352 if (!env || !readers)
1354 *readers = env->me_maxreaders;
1359 mdb_env_open2(MDB_env *env, unsigned int flags)
1361 int i, newenv = 0, toggle;
1365 env->me_flags = flags;
1367 memset(&meta, 0, sizeof(meta));
1369 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1372 DPUTS("new mdbenv");
1376 if (!env->me_mapsize) {
1377 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1381 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1383 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1385 if (env->me_map == MAP_FAILED)
1389 meta.mm_mapsize = env->me_mapsize;
1390 if (flags & MDB_FIXEDMAP)
1391 meta.mm_address = env->me_map;
1392 i = mdb_env_init_meta(env, &meta);
1393 if (i != MDB_SUCCESS) {
1394 munmap(env->me_map, env->me_mapsize);
1398 env->me_psize = meta.mm_psize;
1400 env->me_maxpg = env->me_mapsize / env->me_psize;
1402 p = (MDB_page *)env->me_map;
1403 env->me_metas[0] = METADATA(p);
1404 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1406 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1409 DPRINTF("opened database version %u, pagesize %u",
1410 env->me_metas[toggle]->mm_version, env->me_psize);
1411 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1412 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1413 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1414 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1415 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1416 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1422 mdb_env_reader_dest(void *ptr)
1424 MDB_reader *reader = ptr;
1426 reader->mr_txnid = 0;
1431 /* downgrade the exclusive lock on the region back to shared */
1433 mdb_env_share_locks(MDB_env *env)
1435 struct flock lock_info;
1438 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1440 env->me_txns->mti_me_toggle = toggle;
1441 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1443 memset((void *)&lock_info, 0, sizeof(lock_info));
1444 lock_info.l_type = F_RDLCK;
1445 lock_info.l_whence = SEEK_SET;
1446 lock_info.l_start = 0;
1447 lock_info.l_len = 1;
1448 fcntl(env->me_lfd, F_SETLK, &lock_info);
1452 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1456 struct flock lock_info;
1460 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1464 /* Try to get exclusive lock. If we succeed, then
1465 * nobody is using the lock region and we should initialize it.
1467 memset((void *)&lock_info, 0, sizeof(lock_info));
1468 lock_info.l_type = F_WRLCK;
1469 lock_info.l_whence = SEEK_SET;
1470 lock_info.l_start = 0;
1471 lock_info.l_len = 1;
1472 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1476 lock_info.l_type = F_RDLCK;
1477 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1483 size = lseek(env->me_lfd, 0, SEEK_END);
1484 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1485 if (size < rsize && *excl) {
1486 if (ftruncate(env->me_lfd, rsize) != 0) {
1492 size = rsize - sizeof(MDB_txninfo);
1493 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1495 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1497 if (env->me_txns == MAP_FAILED) {
1502 pthread_mutexattr_t mattr;
1504 pthread_mutexattr_init(&mattr);
1505 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1509 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1510 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1511 env->me_txns->mti_version = MDB_VERSION;
1512 env->me_txns->mti_magic = MDB_MAGIC;
1513 env->me_txns->mti_txnid = 0;
1514 env->me_txns->mti_numreaders = 0;
1515 env->me_txns->mti_me_toggle = 0;
1518 if (env->me_txns->mti_magic != MDB_MAGIC) {
1519 DPUTS("lock region has invalid magic");
1523 if (env->me_txns->mti_version != MDB_VERSION) {
1524 DPRINTF("lock region is version %u, expected version %u",
1525 env->me_txns->mti_version, MDB_VERSION);
1526 rc = MDB_VERSION_MISMATCH;
1529 if (errno != EACCES && errno != EAGAIN) {
1543 #define LOCKNAME "/lock.mdb"
1544 #define DATANAME "/data.mdb"
1546 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1548 int oflags, rc, len, excl;
1549 char *lpath, *dpath;
1552 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1555 dpath = lpath + len + sizeof(LOCKNAME);
1556 sprintf(lpath, "%s" LOCKNAME, path);
1557 sprintf(dpath, "%s" DATANAME, path);
1559 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1563 if (F_ISSET(flags, MDB_RDONLY))
1566 oflags = O_RDWR | O_CREAT;
1568 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1573 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1574 /* synchronous fd for meta writes */
1575 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1576 oflags |= MDB_DSYNC;
1577 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1582 env->me_path = strdup(path);
1583 DPRINTF("opened dbenv %p", (void *) env);
1584 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1585 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1587 mdb_env_share_locks(env);
1588 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1589 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1590 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1596 if (env->me_fd >= 0) {
1600 if (env->me_lfd >= 0) {
1610 mdb_env_close(MDB_env *env)
1617 while (env->me_dpages) {
1618 dp = env->me_dpages;
1619 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1623 free(env->me_dbs[1]);
1624 free(env->me_dbs[0]);
1628 LAZY_RWLOCK_DESTROY(&env->me_dblock);
1629 pthread_key_delete(env->me_txkey);
1632 munmap(env->me_map, env->me_mapsize);
1637 pid_t pid = getpid();
1638 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1640 for (i=0; i<env->me_txns->mti_numreaders; i++)
1641 if (env->me_txns->mti_readers[i].mr_pid == pid)
1642 env->me_txns->mti_readers[i].mr_pid = 0;
1643 munmap(env->me_txns, size);
1649 /* Search for key within a leaf page, using binary search.
1650 * Returns the smallest entry larger or equal to the key.
1651 * If exactp is non-null, stores whether the found entry was an exact match
1652 * in *exactp (1 or 0).
1653 * If kip is non-null, stores the index of the found entry in *kip.
1654 * If no entry larger or equal to the key is found, returns NULL.
1657 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1658 int *exactp, unsigned int *kip)
1663 MDB_node *node = NULL;
1667 DPRINTF("searching %u keys in %s page %lu",
1669 IS_LEAF(mp) ? "leaf" : "branch",
1672 assert(NUMKEYS(mp) > 0);
1674 memset(&nodekey, 0, sizeof(nodekey));
1676 low = IS_LEAF(mp) ? 0 : 1;
1677 high = NUMKEYS(mp) - 1;
1678 while (low <= high) {
1679 i = (low + high) >> 1;
1682 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
1683 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
1685 node = NODEPTR(mp, i);
1687 nodekey.mv_size = node->mn_ksize;
1688 nodekey.mv_data = NODEKEY(node);
1691 rc = mdb_cmp(txn, dbi, key, &nodekey);
1694 DPRINTF("found leaf index %u [%s], rc = %i",
1695 i, DKEY(&nodekey), rc);
1697 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
1698 i, DKEY(&nodekey), NODEPGNO(node), rc);
1708 if (rc > 0) { /* Found entry is less than the key. */
1709 i++; /* Skip to get the smallest entry larger than key. */
1710 if (i >= NUMKEYS(mp))
1711 /* There is no entry larger or equal to the key. */
1715 *exactp = (rc == 0);
1716 if (kip) /* Store the key index if requested. */
1719 /* nodeptr is fake for LEAF2 */
1720 return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
1724 cursor_pop_page(MDB_cursor *cursor)
1728 if (cursor->mc_snum) {
1729 top = CURSOR_TOP(cursor);
1732 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
1733 cursor->mc_dbi, (void *) cursor);
1738 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1742 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
1743 cursor->mc_dbi, (void *) cursor);
1745 assert(cursor->mc_snum < CURSOR_STACK);
1747 ppage = &cursor->mc_stack[cursor->mc_snum++];
1748 ppage->mp_page = mp;
1754 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
1758 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1763 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1764 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1765 dp = txn->mt_u.dirty_list[x].mptr;
1770 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
1771 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1775 DPRINTF("page %lu not found", pgno);
1778 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
1782 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1783 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1785 MDB_page *mp = mpp->mp_page;
1789 if (cursor && cursor_push_page(cursor, mp) == NULL)
1792 while (IS_BRANCH(mp)) {
1796 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1797 assert(NUMKEYS(mp) > 1);
1798 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1800 if (key == NULL) /* Initialize cursor to first page. */
1802 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1803 /* cursor to last page */
1807 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1809 i = NUMKEYS(mp) - 1;
1817 DPRINTF("following index %u for key [%s]",
1819 assert(i < NUMKEYS(mp));
1820 node = NODEPTR(mp, i);
1823 CURSOR_TOP(cursor)->mp_ki = i;
1825 mpp->mp_parent = mp;
1826 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
1831 if (cursor && cursor_push_page(cursor, mp) == NULL)
1835 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1836 if ((rc = mdb_touch(txn, dbi, mpp)) != 0)
1838 dh = ((MDB_dhead *)mpp->mp_page)-1;
1839 dh->md_parent = mpp->mp_parent;
1840 dh->md_pi = mpp->mp_pi;
1847 DPRINTF("internal error, index points to a %02X page!?",
1849 return MDB_CORRUPTED;
1852 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
1853 key ? DKEY(key) : NULL);
1858 /* Search for the page a given key should be in.
1859 * Stores a pointer to the found page in *mpp.
1860 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1861 * If cursor is non-null, pushes parent pages on the cursor stack.
1862 * If modify is true, visited pages are updated with new page numbers.
1865 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1866 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1871 /* Choose which root page to start with. If a transaction is given
1872 * use the root page from the transaction, otherwise read the last
1873 * committed root page.
1875 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1876 DPUTS("transaction has failed, must abort");
1879 root = txn->mt_dbs[dbi].md_root;
1881 if (root == P_INVALID) { /* Tree is empty. */
1882 DPUTS("tree is empty");
1883 return MDB_NOTFOUND;
1886 if (rc = mdb_get_page(txn, root, &mpp->mp_page))
1889 DPRINTF("db %u root page %lu has flags 0x%X",
1890 dbi, root, mpp->mp_page->mp_flags);
1893 /* For sub-databases, update main root first */
1894 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1896 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1900 txn->mt_dbxs[dbi].md_dirty = 1;
1902 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1903 mpp->mp_parent = NULL;
1905 if ((rc = mdb_touch(txn, dbi, mpp)))
1907 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1911 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1915 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1917 MDB_page *omp; /* overflow mpage */
1921 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1922 data->mv_size = leaf->mn_dsize;
1923 data->mv_data = NODEDATA(leaf);
1927 /* Read overflow data.
1929 data->mv_size = leaf->mn_dsize;
1930 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1931 if (rc = mdb_get_page(txn, pgno, &omp)) {
1932 DPRINTF("read overflow page %lu failed", pgno);
1935 data->mv_data = METADATA(omp);
1941 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1942 MDB_val *key, MDB_val *data)
1951 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
1953 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1956 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1960 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1963 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1964 if (leaf && exact) {
1965 /* Return first duplicate data item */
1966 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
1969 mdb_xcursor_init0(txn, dbi, &mx);
1970 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
1971 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1972 if (rc != MDB_SUCCESS)
1974 if (IS_LEAF2(mpp.mp_page)) {
1975 data->mv_size = txn->mt_dbs[dbi].md_pad;
1976 data->mv_data = LEAF2KEY(mpp.mp_page, 0, data->mv_size);
1978 leaf = NODEPTR(mpp.mp_page, 0);
1979 data->mv_size = NODEKSZ(leaf);
1980 data->mv_data = NODEKEY(leaf);
1983 rc = mdb_read_data(txn, leaf, data);
1993 mdb_sibling(MDB_cursor *cursor, int move_right)
2000 if (cursor->mc_snum < 2) {
2001 return MDB_NOTFOUND; /* root has no siblings */
2003 parent = CURSOR_PARENT(cursor);
2005 DPRINTF("parent page is page %lu, index %u",
2006 parent->mp_page->mp_pgno, parent->mp_ki);
2008 cursor_pop_page(cursor);
2009 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
2010 : (parent->mp_ki == 0)) {
2011 DPRINTF("no more keys left, moving to %s sibling",
2012 move_right ? "right" : "left");
2013 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2015 parent = CURSOR_TOP(cursor);
2021 DPRINTF("just moving to %s index key %u",
2022 move_right ? "right" : "left", parent->mp_ki);
2024 assert(IS_BRANCH(parent->mp_page));
2026 indx = NODEPTR(parent->mp_page, parent->mp_ki);
2027 if (rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp))
2030 mp->parent = parent->mp_page;
2031 mp->parent_index = parent->mp_ki;
2034 cursor_push_page(cursor, mp);
2040 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2047 if (cursor->mc_eof) {
2048 return MDB_NOTFOUND;
2051 assert(cursor->mc_initialized);
2053 top = CURSOR_TOP(cursor);
2056 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2057 leaf = NODEPTR(mp, top->mp_ki);
2058 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2059 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2060 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2061 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2065 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2066 if (op == MDB_NEXT_DUP)
2067 return MDB_NOTFOUND;
2071 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2073 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2074 DPUTS("=====> move to next sibling page");
2075 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2077 return MDB_NOTFOUND;
2079 top = CURSOR_TOP(cursor);
2081 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2085 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2086 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2089 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2090 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2094 assert(IS_LEAF(mp));
2095 leaf = NODEPTR(mp, top->mp_ki);
2097 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2098 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2101 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2104 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2105 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2106 if (rc != MDB_SUCCESS)
2111 MDB_SET_KEY(leaf, key);
2116 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2123 assert(cursor->mc_initialized);
2125 top = CURSOR_TOP(cursor);
2128 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2129 leaf = NODEPTR(mp, top->mp_ki);
2130 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2131 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2132 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2133 if (op != MDB_PREV || rc == MDB_SUCCESS)
2136 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2137 if (op == MDB_PREV_DUP)
2138 return MDB_NOTFOUND;
2143 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2145 if (top->mp_ki == 0) {
2146 DPUTS("=====> move to prev sibling page");
2147 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2148 cursor->mc_initialized = 0;
2149 return MDB_NOTFOUND;
2151 top = CURSOR_TOP(cursor);
2153 top->mp_ki = NUMKEYS(mp) - 1;
2154 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2160 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2161 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2164 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2165 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2169 assert(IS_LEAF(mp));
2170 leaf = NODEPTR(mp, top->mp_ki);
2172 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2173 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2176 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2179 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2180 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2181 if (rc != MDB_SUCCESS)
2186 MDB_SET_KEY(leaf, key);
2191 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2192 MDB_cursor_op op, int *exactp)
2202 assert(key->mv_size > 0);
2204 /* See if we're already on the right page */
2205 if (cursor->mc_initialized) {
2207 top = CURSOR_TOP(cursor);
2208 /* Don't try this for LEAF2 pages. Maybe support that later. */
2209 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2210 leaf = NODEPTR(top->mp_page, 0);
2211 MDB_SET_KEY(leaf, &nodekey);
2212 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2214 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2215 MDB_SET_KEY(leaf, &nodekey);
2216 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2218 /* we're already on the right page */
2219 mpp.mp_page = top->mp_page;
2226 cursor->mc_snum = 0;
2228 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2229 if (rc != MDB_SUCCESS)
2232 assert(IS_LEAF(mpp.mp_page));
2234 top = CURSOR_TOP(cursor);
2236 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2237 if (exactp != NULL && !*exactp) {
2238 /* MDB_SET specified and not an exact match. */
2239 return MDB_NOTFOUND;
2243 DPUTS("===> inexact leaf not found, goto sibling");
2244 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2245 return rc; /* no entries matched */
2246 top = CURSOR_TOP(cursor);
2248 mpp.mp_page = top->mp_page;
2249 assert(IS_LEAF(mpp.mp_page));
2250 leaf = NODEPTR(mpp.mp_page, 0);
2253 cursor->mc_initialized = 1;
2256 if (IS_LEAF2(mpp.mp_page)) {
2257 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2258 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2262 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2263 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2266 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2267 if (op == MDB_SET || op == MDB_SET_RANGE) {
2268 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2271 if (op == MDB_GET_BOTH) {
2276 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2277 if (rc != MDB_SUCCESS)
2280 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2282 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2284 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2286 if (op == MDB_GET_BOTH || rc > 0)
2287 return MDB_NOTFOUND;
2291 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2296 /* The key already matches in all other cases */
2297 if (op == MDB_SET_RANGE)
2298 MDB_SET_KEY(leaf, key);
2299 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2305 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2311 cursor->mc_snum = 0;
2313 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2314 if (rc != MDB_SUCCESS)
2316 assert(IS_LEAF(mpp.mp_page));
2318 leaf = NODEPTR(mpp.mp_page, 0);
2319 cursor->mc_initialized = 1;
2322 if (IS_LEAF2(mpp.mp_page)) {
2323 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2324 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2329 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2330 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2331 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2335 if (cursor->mc_xcursor)
2336 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2337 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2341 MDB_SET_KEY(leaf, key);
2346 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2354 cursor->mc_snum = 0;
2356 lkey.mv_size = MAXKEYSIZE+1;
2357 lkey.mv_data = NULL;
2359 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2360 if (rc != MDB_SUCCESS)
2362 assert(IS_LEAF(mpp.mp_page));
2364 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2365 cursor->mc_initialized = 1;
2368 top = CURSOR_TOP(cursor);
2369 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2371 if (IS_LEAF2(mpp.mp_page)) {
2372 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2373 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2378 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2379 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2380 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2384 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2389 MDB_SET_KEY(leaf, key);
2394 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2404 case MDB_GET_BOTH_RANGE:
2405 if (data == NULL || cursor->mc_xcursor == NULL) {
2412 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2414 } else if (op == MDB_SET_RANGE)
2415 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2417 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2419 case MDB_GET_MULTIPLE:
2421 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2422 !cursor->mc_initialized) {
2427 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2430 case MDB_NEXT_MULTIPLE:
2432 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2436 if (!cursor->mc_initialized)
2437 rc = mdb_cursor_first(cursor, key, data);
2439 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2440 if (rc == MDB_SUCCESS) {
2441 if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2444 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2445 data->mv_size = NUMKEYS(top->mp_page) *
2446 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2447 data->mv_data = METADATA(top->mp_page);
2448 top->mp_ki = NUMKEYS(top->mp_page)-1;
2456 case MDB_NEXT_NODUP:
2457 if (!cursor->mc_initialized)
2458 rc = mdb_cursor_first(cursor, key, data);
2460 rc = mdb_cursor_next(cursor, key, data, op);
2464 case MDB_PREV_NODUP:
2465 if (!cursor->mc_initialized || cursor->mc_eof)
2466 rc = mdb_cursor_last(cursor, key, data);
2468 rc = mdb_cursor_prev(cursor, key, data, op);
2471 rc = mdb_cursor_first(cursor, key, data);
2474 rc = mdb_cursor_last(cursor, key, data);
2477 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2485 /* Allocate a page and initialize it
2488 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2492 if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
2494 DPRINTF("allocated new mpage %lu, page size %u",
2495 dp->p.mp_pgno, txn->mt_env->me_psize);
2496 dp->p.mp_flags = flags | P_DIRTY;
2497 dp->p.mp_lower = PAGEHDRSZ;
2498 dp->p.mp_upper = txn->mt_env->me_psize;
2500 if (IS_BRANCH(&dp->p))
2501 txn->mt_dbs[dbi].md_branch_pages++;
2502 else if (IS_LEAF(&dp->p))
2503 txn->mt_dbs[dbi].md_leaf_pages++;
2504 else if (IS_OVERFLOW(&dp->p)) {
2505 txn->mt_dbs[dbi].md_overflow_pages += num;
2506 dp->p.mp_pages = num;
2513 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2517 sz = LEAFSIZE(key, data);
2518 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2519 /* put on overflow page */
2520 sz -= data->mv_size - sizeof(pgno_t);
2523 return sz + sizeof(indx_t);
2527 mdb_branch_size(MDB_env *env, MDB_val *key)
2532 if (sz >= env->me_psize / MDB_MINKEYS) {
2533 /* put on overflow page */
2534 /* not implemented */
2535 /* sz -= key->size - sizeof(pgno_t); */
2538 return sz + sizeof(indx_t);
2542 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2543 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2546 size_t node_size = NODESIZE;
2549 MDB_dpage *ofp = NULL; /* overflow page */
2552 assert(mp->mp_upper >= mp->mp_lower);
2554 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
2555 IS_LEAF(mp) ? "leaf" : "branch",
2556 mp->mp_pgno, indx, data ? data->mv_size : 0,
2557 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
2560 /* Move higher keys up one slot. */
2561 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2562 char *ptr = LEAF2KEY(mp, indx, ksize);
2563 dif = NUMKEYS(mp) - indx;
2565 memmove(ptr+ksize, ptr, dif*ksize);
2566 /* insert new key */
2567 memcpy(ptr, key->mv_data, ksize);
2569 /* Just using these for counting */
2570 mp->mp_lower += sizeof(indx_t);
2571 mp->mp_upper -= ksize - sizeof(indx_t);
2576 node_size += key->mv_size;
2580 if (F_ISSET(flags, F_BIGDATA)) {
2581 /* Data already on overflow page. */
2582 node_size += sizeof(pgno_t);
2583 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2584 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2585 /* Put data on overflow page. */
2586 DPRINTF("data size is %zu, put on overflow page",
2588 node_size += sizeof(pgno_t);
2589 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2591 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2594 node_size += data->mv_size;
2598 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2599 DPRINTF("not enough room in page %lu, got %u ptrs",
2600 mp->mp_pgno, NUMKEYS(mp));
2601 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2602 mp->mp_upper - mp->mp_lower);
2603 DPRINTF("node size = %zu", node_size);
2607 /* Move higher pointers up one slot. */
2608 for (i = NUMKEYS(mp); i > indx; i--)
2609 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2611 /* Adjust free space offsets. */
2612 ofs = mp->mp_upper - node_size;
2613 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2614 mp->mp_ptrs[indx] = ofs;
2616 mp->mp_lower += sizeof(indx_t);
2618 /* Write the node data. */
2619 node = NODEPTR(mp, indx);
2620 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2621 node->mn_flags = flags;
2623 node->mn_dsize = data->mv_size;
2625 NODEPGNO(node) = pgno;
2628 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2633 if (F_ISSET(flags, F_BIGDATA))
2634 memcpy(node->mn_data + key->mv_size, data->mv_data,
2637 memcpy(node->mn_data + key->mv_size, data->mv_data,
2640 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2642 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2650 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2653 indx_t i, j, numkeys, ptr;
2657 DPRINTF("delete node %u on %s page %lu", indx,
2658 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2659 assert(indx < NUMKEYS(mp));
2662 int x = NUMKEYS(mp) - 1 - indx;
2663 base = LEAF2KEY(mp, indx, ksize);
2665 memmove(base, base + ksize, x * ksize);
2666 mp->mp_lower -= sizeof(indx_t);
2667 mp->mp_upper += ksize - sizeof(indx_t);
2671 node = NODEPTR(mp, indx);
2672 sz = NODESIZE + node->mn_ksize;
2674 if (F_ISSET(node->mn_flags, F_BIGDATA))
2675 sz += sizeof(pgno_t);
2677 sz += NODEDSZ(node);
2680 ptr = mp->mp_ptrs[indx];
2681 numkeys = NUMKEYS(mp);
2682 for (i = j = 0; i < numkeys; i++) {
2684 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2685 if (mp->mp_ptrs[i] < ptr)
2686 mp->mp_ptrs[j] += sz;
2691 base = (char *)mp + mp->mp_upper;
2692 memmove(base + sz, base, ptr - mp->mp_upper);
2694 mp->mp_lower -= sizeof(indx_t);
2699 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2704 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2705 mx->mx_txn.mt_dbs = mx->mx_dbs;
2706 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2707 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2709 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2714 mx->mx_dbxs[dbn+1].md_parent = dbn;
2715 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2716 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2717 mx->mx_dbxs[dbn+1].md_dirty = 0;
2718 mx->mx_txn.mt_numdbs = dbn+2;
2720 mx->mx_cursor.mc_snum = 0;
2721 mx->mx_cursor.mc_txn = &mx->mx_txn;
2722 mx->mx_cursor.mc_dbi = dbn+1;
2726 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
2728 MDB_db *db = NODEDATA(node);
2730 mx->mx_dbs[0] = txn->mt_dbs[0];
2731 mx->mx_dbs[1] = txn->mt_dbs[1];
2733 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2738 DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
2739 mx->mx_dbs[dbn] = *db;
2740 if (F_ISSET(mp->mp_flags, P_DIRTY))
2741 mx->mx_dbxs[dbn].md_dirty = 1;
2742 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2743 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2744 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2745 mx->mx_txn.mt_u = txn->mt_u;
2746 mx->mx_cursor.mc_initialized = 0;
2747 mx->mx_cursor.mc_eof = 0;
2751 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2753 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2754 txn->mt_u = mx->mx_txn.mt_u;
2755 txn->mt_dbs[0] = mx->mx_dbs[0];
2756 txn->mt_dbs[1] = mx->mx_dbs[1];
2757 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2758 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2760 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2761 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2766 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2769 size_t size = sizeof(MDB_cursor);
2771 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2774 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2775 size += sizeof(MDB_xcursor);
2777 if ((cursor = calloc(1, size)) != NULL) {
2778 cursor->mc_dbi = dbi;
2779 cursor->mc_txn = txn;
2780 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2781 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2782 cursor->mc_xcursor = mx;
2783 mdb_xcursor_init0(txn, dbi, mx);
2794 /* Return the count of duplicate data items for the current key */
2796 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2801 if (mc == NULL || countp == NULL)
2804 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2807 top = CURSOR_TOP(mc);
2808 leaf = NODEPTR(top->mp_page, top->mp_ki);
2809 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2812 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2815 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2821 mdb_cursor_close(MDB_cursor *cursor)
2823 if (cursor != NULL) {
2829 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2831 indx_t ptr, i, numkeys;
2838 node = NODEPTR(mp, indx);
2839 ptr = mp->mp_ptrs[indx];
2840 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
2842 (int)node->mn_ksize, (char *)NODEKEY(node),
2846 delta = key->mv_size - node->mn_ksize;
2848 if (delta > 0 && SIZELEFT(mp) < delta) {
2849 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2853 numkeys = NUMKEYS(mp);
2854 for (i = 0; i < numkeys; i++) {
2855 if (mp->mp_ptrs[i] <= ptr)
2856 mp->mp_ptrs[i] -= delta;
2859 base = (char *)mp + mp->mp_upper;
2860 len = ptr - mp->mp_upper + NODESIZE;
2861 memmove(base - delta, base, len);
2862 mp->mp_upper -= delta;
2864 node = NODEPTR(mp, indx);
2865 node->mn_ksize = key->mv_size;
2868 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2873 /* Move a node from src to dst.
2876 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2877 MDB_pageparent *dst, indx_t dstindx)
2884 /* Mark src and dst as dirty. */
2885 if ((rc = mdb_touch(txn, dbi, src)) ||
2886 (rc = mdb_touch(txn, dbi, dst)))
2889 if (IS_LEAF2(src->mp_page)) {
2890 srcnode = NODEPTR(src->mp_page, 0); /* fake */
2891 key.mv_size = txn->mt_dbs[dbi].md_pad;
2892 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
2894 data.mv_data = NULL;
2896 srcnode = NODEPTR(src->mp_page, srcindx);
2897 key.mv_size = NODEKSZ(srcnode);
2898 key.mv_data = NODEKEY(srcnode);
2899 data.mv_size = NODEDSZ(srcnode);
2900 data.mv_data = NODEDATA(srcnode);
2902 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
2903 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2906 src->mp_page->mp_pgno,
2907 dstindx, dst->mp_page->mp_pgno);
2909 /* Add the node to the destination page.
2911 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2913 if (rc != MDB_SUCCESS)
2916 /* Delete the node from the source page.
2918 mdb_del_node(src->mp_page, srcindx, key.mv_size);
2920 /* The key value just changed due to del_node, find it again.
2922 if (!IS_LEAF2(src->mp_page)) {
2923 srcnode = NODEPTR(src->mp_page, srcindx);
2924 key.mv_data = NODEKEY(srcnode);
2927 /* Update the parent separators.
2930 if (src->mp_pi != 0) {
2931 DPRINTF("update separator for source page %lu to [%s]",
2932 src->mp_page->mp_pgno, DKEY(&key));
2933 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2934 &key)) != MDB_SUCCESS)
2937 if (IS_BRANCH(src->mp_page)) {
2939 nullkey.mv_size = 0;
2940 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2945 if (dst->mp_pi != 0) {
2946 DPRINTF("update separator for destination page %lu to [%s]",
2947 dst->mp_page->mp_pgno, DKEY(&key));
2948 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2949 &key)) != MDB_SUCCESS)
2952 if (IS_BRANCH(dst->mp_page)) {
2954 nullkey.mv_size = 0;
2955 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2963 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2972 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2974 assert(txn != NULL);
2975 assert(src->mp_parent); /* can't merge root page */
2976 assert(dst->mp_parent);
2978 /* Mark src and dst as dirty. */
2979 if ((rc = mdb_touch(txn, dbi, src)) ||
2980 (rc = mdb_touch(txn, dbi, dst)))
2983 /* Move all nodes from src to dst.
2985 if (IS_LEAF2(src->mp_page)) {
2986 key.mv_size = txn->mt_dbs[dbi].md_pad;
2987 key.mv_data = METADATA(src->mp_page);
2988 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2989 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2991 if (rc != MDB_SUCCESS)
2993 key.mv_data = (char *)key.mv_data + key.mv_size;
2996 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2997 srcnode = NODEPTR(src->mp_page, i);
2999 key.mv_size = srcnode->mn_ksize;
3000 key.mv_data = NODEKEY(srcnode);
3001 data.mv_size = NODEDSZ(srcnode);
3002 data.mv_data = NODEDATA(srcnode);
3003 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3004 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3005 if (rc != MDB_SUCCESS)
3010 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3011 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3013 /* Unlink the src page from parent.
3015 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3016 if (src->mp_pi == 0) {
3018 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3022 if (IS_LEAF(src->mp_page))
3023 txn->mt_dbs[dbi].md_leaf_pages--;
3025 txn->mt_dbs[dbi].md_branch_pages--;
3027 mpp.mp_page = src->mp_parent;
3028 dh = (MDB_dhead *)src->mp_parent;
3030 mpp.mp_parent = dh->md_parent;
3031 mpp.mp_pi = dh->md_pi;
3033 return mdb_rebalance(txn, dbi, &mpp);
3036 #define FILL_THRESHOLD 250
3039 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3044 indx_t si = 0, di = 0;
3047 assert(txn != NULL);
3048 assert(mpp != NULL);
3050 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3051 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3052 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3054 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3055 DPRINTF("no need to rebalance page %lu, above fill threshold",
3056 mpp->mp_page->mp_pgno);
3060 if (mpp->mp_parent == NULL) {
3061 if (NUMKEYS(mpp->mp_page) == 0) {
3062 DPUTS("tree is completely empty");
3063 txn->mt_dbs[dbi].md_root = P_INVALID;
3064 txn->mt_dbs[dbi].md_depth = 0;
3065 txn->mt_dbs[dbi].md_leaf_pages = 0;
3066 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3067 DPUTS("collapsing root page!");
3068 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3069 if (rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root))
3071 txn->mt_dbs[dbi].md_depth--;
3072 txn->mt_dbs[dbi].md_branch_pages--;
3074 DPUTS("root page doesn't need rebalancing");
3078 /* The parent (branch page) must have at least 2 pointers,
3079 * otherwise the tree is invalid.
3081 assert(NUMKEYS(mpp->mp_parent) > 1);
3083 /* Leaf page fill factor is below the threshold.
3084 * Try to move keys from left or right neighbor, or
3085 * merge with a neighbor page.
3090 if (mpp->mp_pi == 0) {
3091 /* We're the leftmost leaf in our parent.
3093 DPUTS("reading right neighbor");
3094 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3095 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3097 npp.mp_pi = mpp->mp_pi + 1;
3099 di = NUMKEYS(mpp->mp_page);
3101 /* There is at least one neighbor to the left.
3103 DPUTS("reading left neighbor");
3104 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3105 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3107 npp.mp_pi = mpp->mp_pi - 1;
3108 si = NUMKEYS(npp.mp_page) - 1;
3111 npp.mp_parent = mpp->mp_parent;
3113 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3114 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3116 /* If the neighbor page is above threshold and has at least two
3117 * keys, move one key from it.
3119 * Otherwise we should try to merge them.
3121 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3122 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3123 else { /* FIXME: if (has_enough_room()) */
3124 if (mpp->mp_pi == 0)
3125 return mdb_merge(txn, dbi, &npp, mpp);
3127 return mdb_merge(txn, dbi, mpp, &npp);
3132 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3136 /* add overflow pages to free list */
3137 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3141 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3142 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3143 for (i=0; i<ovpages; i++) {
3144 DPRINTF("freed ov page %lu", pg);
3145 mdb_midl_insert(txn->mt_free_pgs, pg);
3149 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3150 txn->mt_dbs[dbi].md_entries--;
3151 rc = mdb_rebalance(txn, dbi, mpp);
3152 if (rc != MDB_SUCCESS)
3153 txn->mt_flags |= MDB_TXN_ERROR;
3159 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3160 MDB_val *key, MDB_val *data,
3169 assert(key != NULL);
3171 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3173 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3176 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3180 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3184 mpp.mp_parent = NULL;
3186 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3189 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3190 if (leaf == NULL || !exact) {
3191 return MDB_NOTFOUND;
3194 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3198 mdb_xcursor_init0(txn, dbi, &mx);
3199 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3200 if (flags == MDB_DEL_DUP) {
3201 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
3202 mdb_xcursor_fini(txn, dbi, &mx);
3203 /* If sub-DB still has entries, we're done */
3204 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3205 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3207 txn->mt_dbs[dbi].md_entries--;
3210 /* otherwise fall thru and delete the sub-DB */
3212 /* add all the child DB's pages to the free list */
3213 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3214 NULL, &mx.mx_cursor, 0, &mp2);
3215 if (rc == MDB_SUCCESS) {
3216 MDB_ppage *top, *parent;
3220 cursor_pop_page(&mx.mx_cursor);
3221 if (mx.mx_cursor.mc_snum) {
3222 top = CURSOR_TOP(&mx.mx_cursor);
3223 while (mx.mx_cursor.mc_snum > 1) {
3224 parent = CURSOR_PARENT(&mx.mx_cursor);
3225 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3226 ni = NODEPTR(top->mp_page, i);
3227 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3230 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3231 cursor_pop_page(&mx.mx_cursor);
3234 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3235 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3239 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3244 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
3247 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3250 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3251 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3252 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3253 * refer to a node in the new right sibling page.
3256 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3257 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3260 int rc = MDB_SUCCESS, ins_new = 0;
3263 unsigned int i, j, split_indx, nkeys, pmax;
3265 MDB_val sepkey, rkey, rdata;
3266 MDB_page *copy, *cptr;
3267 MDB_dpage *mdp, *rdp, *pdp;
3271 assert(txn != NULL);
3273 dh = ((MDB_dhead *)*mpp) - 1;
3274 mdp = (MDB_dpage *)dh;
3275 newindx = *newindxp;
3277 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3278 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3279 DKEY(newkey), *newindxp);
3281 if (mdp->h.md_parent == NULL) {
3282 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3285 mdp->h.md_parent = &pdp->p;
3286 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3287 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3288 txn->mt_dbs[dbi].md_depth++;
3290 /* Add left (implicit) pointer. */
3291 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3292 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3295 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3298 /* Create a right sibling. */
3299 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3301 rdp->h.md_parent = mdp->h.md_parent;
3302 rdp->h.md_pi = mdp->h.md_pi + 1;
3303 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3305 nkeys = NUMKEYS(&mdp->p);
3306 split_indx = nkeys / 2 + 1;
3308 if (IS_LEAF2(&rdp->p)) {
3311 unsigned int lsize, rsize, ksize;
3312 /* Move half of the keys to the right sibling */
3314 x = *newindxp - split_indx;
3315 ksize = txn->mt_dbs[dbi].md_pad;
3316 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3317 rsize = (nkeys - split_indx) * ksize;
3318 lsize = (nkeys - split_indx) * sizeof(indx_t);
3319 mdp->p.mp_lower -= lsize;
3320 rdp->p.mp_lower += lsize;
3321 mdp->p.mp_upper += rsize - lsize;
3322 rdp->p.mp_upper -= rsize - lsize;
3323 sepkey.mv_size = ksize;
3324 if (newindx == split_indx) {
3325 sepkey.mv_data = newkey->mv_data;
3327 sepkey.mv_data = split;
3330 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3331 memcpy(&rdp->p.mp_ptrs, split, rsize);
3332 sepkey.mv_data = &rdp->p.mp_ptrs;
3333 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3334 memcpy(ins, newkey->mv_data, ksize);
3335 mdp->p.mp_lower += sizeof(indx_t);
3336 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3339 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3340 ins = LEAF2KEY(&rdp->p, x, ksize);
3341 memcpy(ins, newkey->mv_data, ksize);
3342 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3343 rdp->p.mp_lower += sizeof(indx_t);
3344 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3351 /* For leaf pages, check the split point based on what
3352 * fits where, since otherwise add_node can fail.
3354 if (IS_LEAF(&mdp->p)) {
3355 unsigned int psize, nsize;
3356 /* Maximum free space in an empty page */
3357 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
3358 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
3359 if (newindx <= split_indx) {
3362 for (i=0; i<split_indx; i++) {
3363 node = NODEPTR(&mdp->p, i);
3364 psize += NODESIZE + NODEKSZ(node);
3365 if (F_ISSET(node->mn_flags, F_BIGDATA))
3366 psize += sizeof(pgno_t);
3368 psize += NODEDSZ(node);
3377 for (i=split_indx; i<nkeys; i++) {
3378 node = NODEPTR(&mdp->p, i);
3379 psize += NODESIZE + NODEKSZ(node);
3380 if (F_ISSET(node->mn_flags, F_BIGDATA))
3381 psize += sizeof(pgno_t);
3383 psize += NODEDSZ(node);
3392 /* First find the separating key between the split pages.
3394 memset(&sepkey, 0, sizeof(sepkey));
3395 if (newindx == split_indx) {
3396 sepkey.mv_size = newkey->mv_size;
3397 sepkey.mv_data = newkey->mv_data;
3399 node = NODEPTR(&mdp->p, split_indx);
3400 sepkey.mv_size = node->mn_ksize;
3401 sepkey.mv_data = NODEKEY(node);
3405 DPRINTF("separator is [%s]", DKEY(&sepkey));
3407 /* Copy separator key to the parent.
3409 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3410 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3411 &sepkey, NULL, rdp->p.mp_pgno);
3413 /* Right page might now have changed parent.
3414 * Check if left page also changed parent.
3416 if (rdp->h.md_parent != mdp->h.md_parent &&
3417 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3418 mdp->h.md_parent = rdp->h.md_parent;
3419 mdp->h.md_pi = rdp->h.md_pi - 1;
3422 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3423 &sepkey, NULL, rdp->p.mp_pgno, 0);
3425 if (IS_LEAF2(&rdp->p)) {
3428 if (rc != MDB_SUCCESS) {
3432 /* Move half of the keys to the right sibling. */
3433 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3436 copy->mp_pgno = mdp->p.mp_pgno;
3437 copy->mp_flags = mdp->p.mp_flags;
3438 copy->mp_lower = PAGEHDRSZ;
3439 copy->mp_upper = txn->mt_env->me_psize;
3441 for (i = j = 0; i <= nkeys; j++) {
3442 if (i == split_indx) {
3443 /* Insert in right sibling. */
3444 /* Reset insert index for right sibling. */
3445 j = (i == newindx && ins_new);
3449 if (i == newindx && !ins_new) {
3450 /* Insert the original entry that caused the split. */
3451 rkey.mv_data = newkey->mv_data;
3452 rkey.mv_size = newkey->mv_size;
3453 if (IS_LEAF(&mdp->p)) {
3454 rdata.mv_data = newdata->mv_data;
3455 rdata.mv_size = newdata->mv_size;
3462 /* Update page and index for the new key. */
3464 if (cptr == &rdp->p)
3466 } else if (i == nkeys) {
3469 node = NODEPTR(&mdp->p, i);
3470 rkey.mv_data = NODEKEY(node);
3471 rkey.mv_size = node->mn_ksize;
3472 if (IS_LEAF(&mdp->p)) {
3473 rdata.mv_data = NODEDATA(node);
3474 rdata.mv_size = node->mn_dsize;
3476 pgno = NODEPGNO(node);
3477 flags = node->mn_flags;
3482 if (!IS_LEAF(&mdp->p) && j == 0) {
3483 /* First branch index doesn't need key data. */
3487 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
3489 nkeys = NUMKEYS(copy);
3490 for (i=0; i<nkeys; i++)
3491 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
3492 mdp->p.mp_lower = copy->mp_lower;
3493 mdp->p.mp_upper = copy->mp_upper;
3494 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
3495 txn->mt_env->me_psize - copy->mp_upper);
3502 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3503 MDB_val *key, MDB_val *data, unsigned int flags)
3505 int rc = MDB_SUCCESS, exact;
3509 MDB_val xdata, *rdata, dkey;
3511 char dbuf[PAGESIZE];
3516 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3517 dbi, DKEY(key), key->mv_size, data->mv_size);
3520 mpp.mp_parent = NULL;
3522 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3523 if (rc == MDB_SUCCESS) {
3524 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3525 if (leaf && exact) {
3526 if (flags == MDB_NOOVERWRITE) {
3527 DPRINTF("duplicate key [%s]", DKEY(key));
3528 return MDB_KEYEXIST;
3530 /* there's only a key anyway, so this is a no-op */
3531 if (IS_LEAF2(mpp.mp_page))
3534 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3535 /* Was a single item before, must convert now */
3536 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3537 dkey.mv_size = NODEDSZ(leaf);
3538 dkey.mv_data = dbuf;
3539 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3540 /* data matches, ignore it */
3541 if (!mdb_dcmp(txn, dbi, data, &dkey))
3542 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3543 memset(&dummy, 0, sizeof(dummy));
3544 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3545 dummy.md_pad = data->mv_size;
3546 dummy.md_flags = MDB_DUPFIXED;
3547 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3548 dummy.md_flags |= MDB_INTEGERKEY;
3550 dummy.md_root = P_INVALID;
3551 if (dkey.mv_size == sizeof(MDB_db)) {
3552 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3555 mdb_del_node(mpp.mp_page, ki, 0);
3558 xdata.mv_size = sizeof(MDB_db);
3559 xdata.mv_data = &dummy;
3564 /* same size, just replace it */
3565 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3566 NODEDSZ(leaf) == data->mv_size) {
3567 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3570 mdb_del_node(mpp.mp_page, ki, 0);
3572 if (leaf == NULL) { /* append if not found */
3573 ki = NUMKEYS(mpp.mp_page);
3574 DPRINTF("appending key at index %i", ki);
3576 } else if (rc == MDB_NOTFOUND) {
3578 /* new file, just write a root leaf page */
3579 DPUTS("allocating new root leaf page");
3580 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3583 mpp.mp_page = &dp->p;
3584 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3585 txn->mt_dbs[dbi].md_depth++;
3586 txn->mt_dbxs[dbi].md_dirty = 1;
3587 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3588 mpp.mp_page->mp_flags |= P_LEAF2;
3594 assert(IS_LEAF(mpp.mp_page));
3595 DPRINTF("there are %u keys, should insert new key at index %i",
3596 NUMKEYS(mpp.mp_page), ki);
3601 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3602 if (SIZELEFT(mpp.mp_page) < nsize) {
3603 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3605 /* There is room already in this leaf page. */
3606 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3609 if (rc != MDB_SUCCESS)
3610 txn->mt_flags |= MDB_TXN_ERROR;
3612 /* Remember if we just added a subdatabase */
3613 if (flags & F_SUBDATA) {
3614 leaf = NODEPTR(mpp.mp_page, ki);
3615 leaf->mn_flags |= F_SUBDATA;
3618 /* Now store the actual data in the child DB. Note that we're
3619 * storing the user data in the keys field, so there are strict
3620 * size limits on dupdata. The actual data fields of the child
3621 * DB are all zero size.
3626 leaf = NODEPTR(mpp.mp_page, ki);
3628 mdb_xcursor_init0(txn, dbi, &mx);
3629 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3632 if (flags == MDB_NODUPDATA)
3633 flags = MDB_NOOVERWRITE;
3634 /* converted, write the original data first */
3636 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3638 leaf->mn_flags |= F_DUPDATA;
3640 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3641 mdb_xcursor_fini(txn, dbi, &mx);
3642 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3645 txn->mt_dbs[dbi].md_entries++;
3653 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3654 MDB_val *key, MDB_val *data, unsigned int flags)
3656 assert(key != NULL);
3657 assert(data != NULL);
3659 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3662 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3666 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3670 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3673 return mdb_put0(txn, dbi, key, data, flags);
3677 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3679 #define CHANGEABLE (MDB_NOSYNC)
3680 if ((flag & CHANGEABLE) != flag)
3683 env->me_flags |= flag;
3685 env->me_flags &= ~flag;
3690 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3695 *arg = env->me_flags;
3700 mdb_env_get_path(MDB_env *env, const char **arg)
3705 *arg = env->me_path;
3710 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3712 arg->ms_psize = env->me_psize;
3713 arg->ms_depth = db->md_depth;
3714 arg->ms_branch_pages = db->md_branch_pages;
3715 arg->ms_leaf_pages = db->md_leaf_pages;
3716 arg->ms_overflow_pages = db->md_overflow_pages;
3717 arg->ms_entries = db->md_entries;
3722 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3726 if (env == NULL || arg == NULL)
3729 mdb_env_read_meta(env, &toggle);
3731 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
3734 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3744 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3745 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3749 /* Is the DB already open? */
3751 for (i=2; i<txn->mt_numdbs; i++) {
3752 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3753 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3759 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3762 /* Find the DB info */
3764 key.mv_data = (void *)name;
3765 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3767 /* Create if requested */
3768 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3770 data.mv_size = sizeof(MDB_db);
3771 data.mv_data = &dummy;
3772 memset(&dummy, 0, sizeof(dummy));
3773 dummy.md_root = P_INVALID;
3774 dummy.md_flags = flags & 0xffff;
3775 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3779 /* OK, got info, add to table */
3780 if (rc == MDB_SUCCESS) {
3781 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3782 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3783 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3784 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3785 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3786 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3787 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3788 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3789 *dbi = txn->mt_numdbs;
3790 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3791 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3798 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3800 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3803 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3806 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3809 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3811 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3812 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3813 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3817 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3819 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3822 txn->mt_dbxs[dbi].md_cmp = cmp;
3826 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3828 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3831 txn->mt_dbxs[dbi].md_dcmp = cmp;
3835 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3837 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3840 txn->mt_dbxs[dbi].md_rel = rel;