2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
66 /** @defgroup internal MDB Internals
69 /** @defgroup compat Windows Compatibility Macros
73 #define pthread_t DWORD
74 #define pthread_mutex_t HANDLE
75 #define pthread_key_t DWORD
76 #define pthread_self() GetCurrentThreadId()
77 #define pthread_key_create(x,y) *(x) = TlsAlloc()
78 #define pthread_key_delete(x) TlsFree(x)
79 #define pthread_getspecific(x) TlsGetValue(x)
80 #define pthread_setspecific(x,y) TlsSetValue(x,y)
81 #define pthread_mutex_unlock(x) ReleaseMutex(x)
82 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
83 #define LOCK_MUTEX_R(env) pthread_mutex_lock(env->me_rmutex)
84 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(env->me_rmutex)
85 #define LOCK_MUTEX_W(env) pthread_mutex_lock(env->me_wmutex)
86 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(env->me_wmutex)
87 #define getpid() GetCurrentProcessId()
88 #define fdatasync(fd) !FlushFileBuffers(fd)
89 #define ErrCode() GetLastError()
90 #define GetPageSize(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
91 #define close(fd) CloseHandle(fd)
92 #define munmap(ptr,len) UnmapViewOfFile(ptr)
94 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&env->me_txns->mti_mutex)
95 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&env->me_txns->mti_mutex)
96 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&env->me_txns->mti_wmutex)
97 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&env->me_txns->mti_wmutex)
98 #define ErrCode() errno
100 #define INVALID_HANDLE_VALUE -1
101 #define GetPageSize(x) (x) = sysconf(_SC_PAGE_SIZE)
107 /* Note: If O_DSYNC is undefined but exists in /usr/include,
108 * preferably set some compiler flag to get the definition.
109 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
112 # define MDB_DSYNC O_DSYNC
116 typedef ULONG pgno_t;
122 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
123 # define DPRINTF (void) /* Vararg macros may be unsupported */
125 # define DPRINTF(fmt, ...) /* Requires 2 or more args */ \
126 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
128 # define DPRINTF(fmt, ...) ((void) 0)
130 #define DPUTS(arg) DPRINTF("%s", arg)
132 #define PAGESIZE 4096
133 #define MDB_MINKEYS 2
134 #define MDB_MAGIC 0xBEEFC0DE
135 #define MDB_VERSION 1
136 #define MAXKEYSIZE 511
138 #define KBUF (MAXKEYSIZE*2+1)
139 #define DKBUF char kbuf[KBUF]
140 #define DKEY(x) mdb_dkey(x, kbuf)
146 /* The DB view is always consistent because all writes are wrapped in
147 * the wmutex. Finer-grained locks aren't necessary.
153 #define LAZY_MUTEX_LOCK(x)
154 #define LAZY_MUTEX_UNLOCK(x)
155 #define LAZY_RWLOCK_UNLOCK(x)
156 #define LAZY_RWLOCK_WRLOCK(x)
157 #define LAZY_RWLOCK_RDLOCK(x)
158 #define LAZY_RWLOCK_DEF(x)
159 #define LAZY_RWLOCK_INIT(x,y)
160 #define LAZY_RWLOCK_DESTROY(x)
162 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
163 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
164 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
165 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
166 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
167 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
168 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
169 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
172 #define P_INVALID (~0UL)
174 #define F_ISSET(w, f) (((w) & (f)) == (f))
176 typedef uint16_t indx_t;
178 #define DEFAULT_READERS 126
179 #define DEFAULT_MAPSIZE 1048576
181 /* Lock descriptor stuff */
183 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
186 typedef struct MDB_rxbody {
192 typedef struct MDB_reader {
195 #define mr_txnid mru.mrx.mrb_txnid
196 #define mr_pid mru.mrx.mrb_pid
197 #define mr_tid mru.mrx.mrb_tid
198 /* cache line alignment */
199 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
203 typedef struct MDB_txbody {
205 uint32_t mtb_version;
206 /* For POSIX the actual mutexes reside in shared memory.
207 * On Windows, mutexes are allocated by the kernel; we store
208 * the name in shared memory so that other processes can
214 pthread_mutex_t mtb_mutex;
217 uint32_t mtb_numreaders;
218 uint32_t mtb_me_toggle;
221 typedef struct MDB_txninfo {
224 #define mti_magic mt1.mtb.mtb_magic
225 #define mti_version mt1.mtb.mtb_version
226 #define mti_mutex mt1.mtb.mtb_mutex
227 #define mti_rmname mt1.mtb.mtb_rmname
228 #define mti_txnid mt1.mtb.mtb_txnid
229 #define mti_numreaders mt1.mtb.mtb_numreaders
230 #define mti_me_toggle mt1.mtb.mtb_me_toggle
231 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
236 #define mti_wmname mt2.mt2_wmname
238 pthread_mutex_t mt2_wmutex;
239 #define mti_wmutex mt2.mt2_wmutex
241 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
243 MDB_reader mti_readers[1];
246 /* Common header for all page types. Overflow pages
247 * occupy a number of contiguous pages with no
248 * headers on any page after the first.
250 typedef struct MDB_page { /* represents a page of storage */
251 #define mp_pgno mp_p.p_pgno
253 pgno_t p_pgno; /* page number */
254 void * p_align; /* for IL32P64 */
256 #define P_BRANCH 0x01 /* branch page */
257 #define P_LEAF 0x02 /* leaf page */
258 #define P_OVERFLOW 0x04 /* overflow page */
259 #define P_META 0x08 /* meta page */
260 #define P_DIRTY 0x10 /* dirty page */
261 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
263 #define mp_lower mp_pb.pb.pb_lower
264 #define mp_upper mp_pb.pb.pb_upper
265 #define mp_pages mp_pb.pb_pages
268 indx_t pb_lower; /* lower bound of free space */
269 indx_t pb_upper; /* upper bound of free space */
271 uint32_t pb_pages; /* number of overflow pages */
273 indx_t mp_ptrs[1]; /* dynamic size */
276 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
278 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
279 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
280 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
281 ((env)->me_psize - PAGEHDRSZ))
282 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
283 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
284 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
285 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
287 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
289 typedef struct MDB_db {
290 uint32_t md_pad; /* also ksize for LEAF2 pages */
293 ULONG md_branch_pages;
295 ULONG md_overflow_pages;
303 typedef struct MDB_meta { /* meta (footer) page content */
306 void *mm_address; /* address for fixed mapping */
307 size_t mm_mapsize; /* size of mmap region */
308 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
309 #define mm_psize mm_dbs[0].md_pad
310 #define mm_flags mm_dbs[0].md_flags
311 pgno_t mm_last_pg; /* last used page in file */
312 ULONG mm_txnid; /* txnid that committed this page */
315 typedef struct MDB_dhead { /* a dirty page */
317 unsigned md_pi; /* parent index */
321 typedef struct MDB_dpage {
326 typedef struct MDB_oldpages {
327 struct MDB_oldpages *mo_next;
329 pgno_t mo_pages[1]; /* dynamic */
332 typedef struct MDB_pageparent {
338 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num);
339 static int mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
341 typedef struct MDB_ppage { /* ordered list of pages */
343 unsigned int mp_ki; /* cursor index on page */
346 #define CURSOR_TOP(c) (&(c)->mc_stack[(c)->mc_snum-1])
347 #define CURSOR_PARENT(c) (&(c)->mc_stack[(c)->mc_snum-2])
348 #define CURSOR_STACK 32
354 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
355 unsigned int mc_snum; /* number of pushed pages */
357 unsigned int mc_flags;
358 #define C_INITIALIZED 0x01
360 #define C_XDIRTY 0x04
361 struct MDB_xcursor *mc_xcursor;
364 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
366 typedef struct MDB_node {
367 #define mn_pgno mn_p.np_pgno
368 #define mn_dsize mn_p.np_dsize
370 pgno_t np_pgno; /* child page number */
371 uint32_t np_dsize; /* leaf data size */
373 unsigned int mn_flags:4;
374 unsigned int mn_ksize:12; /* key size */
375 #define F_BIGDATA 0x01 /* data put on overflow page */
376 #define F_SUBDATA 0x02 /* data is a sub-database */
377 #define F_DUPDATA 0x04 /* data has duplicates */
381 typedef struct MDB_dbx {
383 MDB_cmp_func *md_cmp; /* user compare function */
384 MDB_cmp_func *md_dcmp; /* user dupsort function */
385 MDB_rel_func *md_rel; /* user relocate function */
387 unsigned int md_dirty;
391 pgno_t mt_next_pgno; /* next unallocated page */
394 pgno_t *mt_free_pgs; /* this is an IDL */
396 ID2L dirty_list; /* modified pages */
399 MDB_dbx *mt_dbxs; /* array */
401 unsigned int mt_numdbs;
403 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
404 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
405 unsigned int mt_flags;
406 unsigned int mt_toggle;
409 /* Context for sorted-dup records */
410 typedef struct MDB_xcursor {
411 MDB_cursor mx_cursor;
420 HANDLE me_mfd; /* just for writing the meta pages */
421 #define MDB_FATAL_ERROR 0x80000000U
423 uint32_t me_extrapad; /* unused for now */
424 unsigned int me_maxreaders;
425 unsigned int me_numdbs;
426 unsigned int me_maxdbs;
429 MDB_txninfo *me_txns;
430 MDB_meta *me_metas[2];
431 MDB_txn *me_txn; /* current write transaction */
433 off_t me_size; /* current file size */
434 pgno_t me_maxpg; /* me_mapsize / me_psize */
435 unsigned int me_psize;
436 unsigned int me_db_toggle;
437 MDB_dbx *me_dbxs; /* array */
439 MDB_oldpages *me_pghead;
440 pthread_key_t me_txkey; /* thread-key for readers */
441 MDB_dpage *me_dpages;
442 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
443 ID2 me_dirty_list[MDB_IDL_DB_SIZE];
444 LAZY_RWLOCK_DEF(me_dblock);
446 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
451 #define NODESIZE offsetof(MDB_node, mn_data)
453 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
454 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
455 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
456 #define NODEKEY(node) (void *)((node)->mn_data)
457 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
458 #define NODEPGNO(node) ((node)->mn_pgno)
459 #define NODEDSZ(node) ((node)->mn_dsize)
460 #define NODEKSZ(node) ((node)->mn_ksize)
461 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
463 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
465 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
467 static int mdb_search_page_root(MDB_txn *txn,
468 MDB_dbi dbi, MDB_val *key,
469 MDB_cursor *cursor, int modify,
470 MDB_pageparent *mpp);
471 static int mdb_search_page(MDB_txn *txn,
472 MDB_dbi dbi, MDB_val *key,
473 MDB_cursor *cursor, int modify,
474 MDB_pageparent *mpp);
476 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
477 static int mdb_env_read_meta(MDB_env *env, int *which);
478 static int mdb_env_write_meta(MDB_txn *txn);
479 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
481 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
482 MDB_val *key, int *exactp, unsigned int *kip);
483 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
484 indx_t indx, MDB_val *key, MDB_val *data,
485 pgno_t pgno, uint8_t flags);
486 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
487 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
488 MDB_pageparent *mpp, MDB_node *leaf);
489 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
490 MDB_val *key, MDB_val *data, unsigned int flags);
491 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
493 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
494 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
495 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
496 MDB_pageparent *src, indx_t srcindx,
497 MDB_pageparent *dst, indx_t dstindx);
498 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
499 MDB_pageparent *dst);
500 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
501 unsigned int *newindxp, MDB_val *newkey,
502 MDB_val *newdata, pgno_t newpgno);
503 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
505 static void cursor_pop_page(MDB_cursor *cursor);
506 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
509 static int mdb_sibling(MDB_cursor *cursor, int move_right);
510 static int mdb_cursor_next(MDB_cursor *cursor,
511 MDB_val *key, MDB_val *data, MDB_cursor_op op);
512 static int mdb_cursor_prev(MDB_cursor *cursor,
513 MDB_val *key, MDB_val *data, MDB_cursor_op op);
514 static int mdb_cursor_set(MDB_cursor *cursor,
515 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
516 static int mdb_cursor_first(MDB_cursor *cursor,
517 MDB_val *key, MDB_val *data);
518 static int mdb_cursor_last(MDB_cursor *cursor,
519 MDB_val *key, MDB_val *data);
521 static void mdb_xcursor_init0(MDB_cursor *mc);
522 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx,
523 MDB_page *mp, MDB_node *node);
524 static void mdb_xcursor_fini(MDB_cursor *mc);
526 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
528 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
530 static int memncmp(const void *s1, size_t n1,
531 const void *s2, size_t n2);
532 static int memnrcmp(const void *s1, size_t n1,
533 const void *s2, size_t n2);
536 static SECURITY_DESCRIPTOR mdb_null_sd;
537 static SECURITY_ATTRIBUTES mdb_all_sa;
538 static int mdb_sec_inited;
542 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
544 int diff, len_diff = -1;
547 len_diff = (n1 > n2);
550 diff = memcmp(s1, s2, n1);
551 return diff ? diff : len_diff;
555 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
557 const unsigned char *p1, *p2, *p1_lim;
564 p1 = (const unsigned char *)s1 + n1 - 1;
565 p2 = (const unsigned char *)s2 + n2 - 1;
567 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
569 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
575 mdb_version(int *maj, int *min, int *pat)
577 if (maj) *maj = MDB_VERSION_MAJOR;
578 if (min) *min = MDB_VERSION_MINOR;
579 if (pat) *pat = MDB_VERSION_PATCH;
580 return MDB_VERSION_STRING;
583 static char *const mdb_errstr[] = {
584 "MDB_KEYEXIST: Key/data pair already exists",
585 "MDB_NOTFOUND: No matching key/data pair found",
586 "MDB_PAGE_NOTFOUND: Requested page not found",
587 "MDB_CORRUPTED: Located page was wrong type",
588 "MDB_PANIC: Update of meta page failed",
589 "MDB_VERSION_MISMATCH: Database environment version mismatch"
593 mdb_strerror(int err)
596 return ("Successful return: 0");
598 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
599 return mdb_errstr[err - MDB_KEYEXIST];
601 return strerror(err);
606 mdb_dkey(MDB_val *key, char *buf)
609 unsigned char *c = key->mv_data;
611 if (key->mv_size > MAXKEYSIZE)
613 for (i=0; i<key->mv_size; i++)
614 ptr += sprintf(ptr, "%02x", *c++);
620 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
622 if (txn->mt_dbxs[dbi].md_cmp)
623 return txn->mt_dbxs[dbi].md_cmp(a, b);
625 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
626 #if __BYTE_ORDER == __LITTLE_ENDIAN
630 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
632 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
636 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
638 if (txn->mt_dbxs[dbi].md_dcmp)
639 return txn->mt_dbxs[dbi].md_dcmp(a, b);
641 if (txn->mt_dbs[dbi].md_flags & (0
642 #if __BYTE_ORDER == __LITTLE_ENDIAN
646 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
648 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
651 /* Allocate new page(s) for writing */
653 mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num)
656 pgno_t pgno = P_INVALID;
659 if (txn->mt_txnid > 2) {
661 if (!txn->mt_env->me_pghead && dbi != FREE_DBI &&
662 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
663 /* See if there's anything in the free DB */
669 mpp.mp_parent = NULL;
675 mdb_search_page(txn, FREE_DBI, NULL, &mc, 0, &mpp);
676 leaf = NODEPTR(mpp.mp_page, 0);
677 kptr = (ULONG *)NODEKEY(leaf);
681 oldest = txn->mt_txnid - 1;
682 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
683 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
684 if (mr && mr < oldest)
689 if (oldest > *kptr) {
690 /* It's usable, grab it.
697 mdb_read_data(txn, leaf, &data);
698 idl = (ULONG *)data.mv_data;
699 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
700 mop->mo_next = txn->mt_env->me_pghead;
701 mop->mo_txnid = *kptr;
702 txn->mt_env->me_pghead = mop;
703 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
708 DPRINTF("IDL read txn %lu root %lu num %lu",
709 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
710 for (i=0; i<idl[0]; i++) {
711 DPRINTF("IDL %lu", idl[i+1]);
715 /* drop this IDL from the DB */
716 top = CURSOR_TOP(&mc);
718 mc.mc_flags = C_INITIALIZED;
719 mdb_cursor_del(&mc, 0);
722 if (txn->mt_env->me_pghead) {
723 MDB_oldpages *mop = txn->mt_env->me_pghead;
725 /* FIXME: For now, always use fresh pages. We
726 * really ought to search the free list for a
731 /* peel pages off tail, so we only have to truncate the list */
732 pgno = MDB_IDL_LAST(mop->mo_pages);
733 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
735 if (mop->mo_pages[2] > mop->mo_pages[1])
736 mop->mo_pages[0] = 0;
740 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
741 txn->mt_env->me_pghead = mop->mo_next;
748 if (pgno == P_INVALID) {
749 /* DB size is maxed out */
750 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
753 if (txn->mt_env->me_dpages && num == 1) {
754 dp = txn->mt_env->me_dpages;
755 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
757 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
761 dp->h.md_parent = parent;
762 dp->h.md_pi = parent_idx;
763 if (pgno == P_INVALID) {
764 dp->p.mp_pgno = txn->mt_next_pgno;
765 txn->mt_next_pgno += num;
767 dp->p.mp_pgno = pgno;
769 mid.mid = dp->p.mp_pgno;
771 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
776 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
779 mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *pp)
781 MDB_page *mp = pp->mp_page;
786 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
788 if ((dp = mdb_alloc_page(txn, dbi, pp->mp_parent, pp->mp_pi, 1)) == NULL)
790 DPRINTF("touched db %u page %lu -> %lu", dbi, mp->mp_pgno, dp->p.mp_pgno);
791 assert(mp->mp_pgno != dp->p.mp_pgno);
792 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
793 pgno = dp->p.mp_pgno;
794 memcpy(&dp->p, mp, txn->mt_env->me_psize);
797 mp->mp_flags |= P_DIRTY;
799 /* Update the page number to new touched page. */
800 if (pp->mp_parent != NULL)
801 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
808 mdb_env_sync(MDB_env *env, int force)
811 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
812 if (fdatasync(env->me_fd))
819 mdb_txn_reset0(MDB_txn *txn);
822 mdb_txn_renew0(MDB_txn *txn)
824 MDB_env *env = txn->mt_env;
826 if (txn->mt_flags & MDB_TXN_RDONLY) {
827 MDB_reader *r = pthread_getspecific(env->me_txkey);
830 pid_t pid = getpid();
831 pthread_t tid = pthread_self();
834 for (i=0; i<env->me_txns->mti_numreaders; i++)
835 if (env->me_txns->mti_readers[i].mr_pid == 0)
837 if (i == env->me_maxreaders) {
841 env->me_txns->mti_readers[i].mr_pid = pid;
842 env->me_txns->mti_readers[i].mr_tid = tid;
843 if (i >= env->me_txns->mti_numreaders)
844 env->me_txns->mti_numreaders = i+1;
846 r = &env->me_txns->mti_readers[i];
847 pthread_setspecific(env->me_txkey, r);
849 txn->mt_txnid = env->me_txns->mti_txnid;
850 txn->mt_toggle = env->me_txns->mti_me_toggle;
851 r->mr_txnid = txn->mt_txnid;
852 txn->mt_u.reader = r;
856 txn->mt_txnid = env->me_txns->mti_txnid+1;
857 txn->mt_toggle = env->me_txns->mti_me_toggle;
858 txn->mt_u.dirty_list = env->me_dirty_list;
859 txn->mt_u.dirty_list[0].mid = 0;
860 txn->mt_free_pgs = env->me_free_pgs;
861 txn->mt_free_pgs[0] = 0;
862 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
866 /* Copy the DB arrays */
867 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
868 txn->mt_numdbs = env->me_numdbs;
869 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
870 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
871 if (txn->mt_numdbs > 2)
872 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
873 (txn->mt_numdbs - 2) * sizeof(MDB_db));
874 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
880 mdb_txn_renew(MDB_txn *txn)
887 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
888 DPUTS("environment had fatal error, must shutdown!");
892 rc = mdb_txn_renew0(txn);
893 if (rc == MDB_SUCCESS) {
894 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
895 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
896 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
902 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
907 if (env->me_flags & MDB_FATAL_ERROR) {
908 DPUTS("environment had fatal error, must shutdown!");
911 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
912 DPRINTF("calloc: %s", strerror(ErrCode()));
915 txn->mt_dbs = (MDB_db *)(txn+1);
916 if (flags & MDB_RDONLY) {
917 txn->mt_flags |= MDB_TXN_RDONLY;
921 rc = mdb_txn_renew0(txn);
926 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
927 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
928 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
935 mdb_txn_reset0(MDB_txn *txn)
937 MDB_env *env = txn->mt_env;
939 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
940 txn->mt_u.reader->mr_txnid = 0;
946 /* return all dirty pages to dpage list */
947 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
948 dp = txn->mt_u.dirty_list[i].mptr;
949 if (dp->h.md_num == 1) {
950 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
951 txn->mt_env->me_dpages = dp;
953 /* large pages just get freed directly */
958 while ((mop = txn->mt_env->me_pghead)) {
959 txn->mt_env->me_pghead = mop->mo_next;
964 for (i=2; i<env->me_numdbs; i++)
965 env->me_dbxs[i].md_dirty = 0;
971 mdb_txn_reset(MDB_txn *txn)
976 DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
977 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
978 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
984 mdb_txn_abort(MDB_txn *txn)
989 DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
990 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
991 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
998 mdb_txn_commit(MDB_txn *txn)
1008 assert(txn != NULL);
1009 assert(txn->mt_env != NULL);
1013 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1018 if (txn != env->me_txn) {
1019 DPUTS("attempt to commit unknown transaction");
1024 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1025 DPUTS("error flag is set, can't commit");
1030 if (!txn->mt_u.dirty_list[0].mid)
1033 DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
1034 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1036 /* should only be one record now */
1037 if (env->me_pghead) {
1040 /* make sure first page of freeDB is touched and on freelist */
1041 mpp.mp_parent = NULL;
1043 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
1045 /* save to free list */
1046 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1051 /* make sure last page of freeDB is touched and on freelist */
1052 key.mv_size = MAXKEYSIZE+1;
1054 mpp.mp_parent = NULL;
1056 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
1061 ULONG *idl = txn->mt_free_pgs;
1062 DPRINTF("IDL write txn %lu root %lu num %lu",
1063 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1064 for (i=0; i<idl[0]; i++) {
1065 DPRINTF("IDL %lu", idl[i+1]);
1069 /* write to last page of freeDB */
1070 key.mv_size = sizeof(pgno_t);
1071 key.mv_data = (char *)&txn->mt_txnid;
1072 data.mv_data = txn->mt_free_pgs;
1073 /* The free list can still grow during this call,
1074 * despite the pre-emptive touches above. So check
1075 * and make sure the entire thing got written.
1078 i = txn->mt_free_pgs[0];
1079 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1080 rc = mdb_put0(txn, FREE_DBI, &key, &data, 0);
1085 } while (i != txn->mt_free_pgs[0]);
1087 /* should only be one record now */
1088 if (env->me_pghead) {
1092 mop = env->me_pghead;
1093 key.mv_size = sizeof(pgno_t);
1094 key.mv_data = (char *)&mop->mo_txnid;
1095 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1096 data.mv_data = mop->mo_pages;
1097 mdb_put0(txn, FREE_DBI, &key, &data, 0);
1098 free(env->me_pghead);
1099 env->me_pghead = NULL;
1102 /* Update DB root pointers. Their pages have already been
1103 * touched so this is all in-place and cannot fail.
1107 data.mv_size = sizeof(MDB_db);
1109 for (i = 2; i < txn->mt_numdbs; i++) {
1110 if (txn->mt_dbxs[i].md_dirty) {
1111 data.mv_data = &txn->mt_dbs[i];
1112 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
1117 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1123 /* Windows actually supports scatter/gather I/O, but only on
1124 * unbuffered file handles. Since we're relying on the OS page
1125 * cache for all our data, that's self-defeating. So we just
1126 * write pages one at a time. We use the ov structure to set
1127 * the write offset, to at least save the overhead of a Seek
1131 memset(&ov, 0, sizeof(ov));
1132 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1133 dp = txn->mt_u.dirty_list[i].mptr;
1134 DPRINTF("committing page %lu", dp->p.mp_pgno);
1135 size = dp->p.mp_pgno * env->me_psize;
1136 ov.Offset = size & 0xffffffff;
1137 ov.OffsetHigh = size >> 16;
1138 ov.OffsetHigh >>= 16;
1139 /* clear dirty flag */
1140 dp->p.mp_flags &= ~P_DIRTY;
1141 rc = WriteFile(env->me_fd, &dp->p, env->me_psize * dp->h.md_num, NULL, &ov);
1144 DPRINTF("WriteFile: %d", n);
1151 struct iovec iov[MDB_COMMIT_PAGES];
1155 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1156 dp = txn->mt_u.dirty_list[i].mptr;
1157 if (dp->p.mp_pgno != next) {
1159 DPRINTF("committing %u dirty pages", n);
1160 rc = writev(env->me_fd, iov, n);
1164 DPUTS("short write, filesystem full?");
1166 DPRINTF("writev: %s", strerror(n));
1173 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1174 next = dp->p.mp_pgno;
1176 DPRINTF("committing page %lu", dp->p.mp_pgno);
1177 iov[n].iov_len = env->me_psize * dp->h.md_num;
1178 iov[n].iov_base = &dp->p;
1179 size += iov[n].iov_len;
1180 next = dp->p.mp_pgno + dp->h.md_num;
1181 /* clear dirty flag */
1182 dp->p.mp_flags &= ~P_DIRTY;
1183 if (++n >= MDB_COMMIT_PAGES) {
1193 DPRINTF("committing %u dirty pages", n);
1194 rc = writev(env->me_fd, iov, n);
1198 DPUTS("short write, filesystem full?");
1200 DPRINTF("writev: %s", strerror(n));
1207 /* Drop the dirty pages.
1209 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1210 dp = txn->mt_u.dirty_list[i].mptr;
1211 if (dp->h.md_num == 1) {
1212 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1213 txn->mt_env->me_dpages = dp;
1217 txn->mt_u.dirty_list[i].mid = 0;
1219 txn->mt_u.dirty_list[0].mid = 0;
1221 if ((n = mdb_env_sync(env, 0)) != 0 ||
1222 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1229 /* update the DB tables */
1231 int toggle = !env->me_db_toggle;
1234 ip = &env->me_dbs[toggle][2];
1235 jp = &txn->mt_dbs[2];
1236 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1237 for (i = 2; i < txn->mt_numdbs; i++) {
1238 if (ip->md_root != jp->md_root)
1243 for (i = 2; i < txn->mt_numdbs; i++) {
1244 if (txn->mt_dbxs[i].md_dirty)
1245 txn->mt_dbxs[i].md_dirty = 0;
1247 env->me_db_toggle = toggle;
1248 env->me_numdbs = txn->mt_numdbs;
1249 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1252 UNLOCK_MUTEX_W(env);
1259 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1261 char page[PAGESIZE];
1266 /* We don't know the page size yet, so use a minimum value.
1270 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1272 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1277 else if (rc != PAGESIZE) {
1281 DPRINTF("read: %s", strerror(err));
1285 p = (MDB_page *)page;
1287 if (!F_ISSET(p->mp_flags, P_META)) {
1288 DPRINTF("page %lu not a meta page", p->mp_pgno);
1293 if (m->mm_magic != MDB_MAGIC) {
1294 DPUTS("meta has invalid magic");
1298 if (m->mm_version != MDB_VERSION) {
1299 DPRINTF("database is version %u, expected version %u",
1300 m->mm_version, MDB_VERSION);
1301 return MDB_VERSION_MISMATCH;
1304 memcpy(meta, m, sizeof(*m));
1309 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1316 DPUTS("writing new meta page");
1320 meta->mm_magic = MDB_MAGIC;
1321 meta->mm_version = MDB_VERSION;
1322 meta->mm_psize = psize;
1323 meta->mm_last_pg = 1;
1324 meta->mm_flags = env->me_flags & 0xffff;
1325 meta->mm_flags |= MDB_INTEGERKEY;
1326 meta->mm_dbs[0].md_root = P_INVALID;
1327 meta->mm_dbs[1].md_root = P_INVALID;
1329 p = calloc(2, psize);
1331 p->mp_flags = P_META;
1334 memcpy(m, meta, sizeof(*meta));
1336 q = (MDB_page *)((char *)p + psize);
1339 q->mp_flags = P_META;
1342 memcpy(m, meta, sizeof(*meta));
1347 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1348 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1351 rc = write(env->me_fd, p, psize * 2);
1352 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1359 mdb_env_write_meta(MDB_txn *txn)
1362 MDB_meta meta, metab;
1364 int rc, len, toggle;
1370 assert(txn != NULL);
1371 assert(txn->mt_env != NULL);
1373 toggle = !txn->mt_toggle;
1374 DPRINTF("writing meta page %d for root page %lu",
1375 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1379 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1380 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1382 ptr = (char *)&meta;
1383 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1384 len = sizeof(MDB_meta) - off;
1387 meta.mm_dbs[0] = txn->mt_dbs[0];
1388 meta.mm_dbs[1] = txn->mt_dbs[1];
1389 meta.mm_last_pg = txn->mt_next_pgno - 1;
1390 meta.mm_txnid = txn->mt_txnid;
1393 off += env->me_psize;
1396 /* Write to the SYNC fd */
1399 memset(&ov, 0, sizeof(ov));
1401 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1404 rc = pwrite(env->me_mfd, ptr, len, off);
1409 DPUTS("write failed, disk error?");
1410 /* On a failure, the pagecache still contains the new data.
1411 * Write some old data back, to prevent it from being used.
1412 * Use the non-SYNC fd; we know it will fail anyway.
1414 meta.mm_last_pg = metab.mm_last_pg;
1415 meta.mm_txnid = metab.mm_txnid;
1417 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1419 r2 = pwrite(env->me_fd, ptr, len, off);
1421 env->me_flags |= MDB_FATAL_ERROR;
1424 /* Memory ordering issues are irrelevant; since the entire writer
1425 * is wrapped by wmutex, all of these changes will become visible
1426 * after the wmutex is unlocked. Since the DB is multi-version,
1427 * readers will get consistent data regardless of how fresh or
1428 * how stale their view of these values is.
1430 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1431 txn->mt_env->me_txns->mti_me_toggle = toggle;
1432 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1433 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1439 mdb_env_read_meta(MDB_env *env, int *which)
1443 assert(env != NULL);
1445 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1448 DPRINTF("Using meta page %d", toggle);
1455 mdb_env_create(MDB_env **env)
1459 e = calloc(1, sizeof(MDB_env));
1460 if (!e) return ENOMEM;
1462 e->me_maxreaders = DEFAULT_READERS;
1464 e->me_fd = INVALID_HANDLE_VALUE;
1465 e->me_lfd = INVALID_HANDLE_VALUE;
1466 e->me_mfd = INVALID_HANDLE_VALUE;
1472 mdb_env_set_mapsize(MDB_env *env, size_t size)
1476 env->me_mapsize = size;
1481 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1485 env->me_maxdbs = dbs;
1490 mdb_env_set_maxreaders(MDB_env *env, int readers)
1494 env->me_maxreaders = readers;
1499 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1501 if (!env || !readers)
1503 *readers = env->me_maxreaders;
1508 mdb_env_open2(MDB_env *env, unsigned int flags)
1510 int i, newenv = 0, toggle;
1514 env->me_flags = flags;
1516 memset(&meta, 0, sizeof(meta));
1518 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1521 DPUTS("new mdbenv");
1525 if (!env->me_mapsize) {
1526 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1532 LONG sizelo, sizehi;
1533 sizelo = env->me_mapsize & 0xffffffff;
1534 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1536 /* Windows won't create mappings for zero length files.
1537 * Just allocate the maxsize right now.
1540 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1541 if (!SetEndOfFile(env->me_fd))
1543 SetFilePointer(env->me_fd, 0, NULL, 0);
1545 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1546 sizehi, sizelo, NULL);
1549 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1557 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1559 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1561 if (env->me_map == MAP_FAILED)
1566 meta.mm_mapsize = env->me_mapsize;
1567 if (flags & MDB_FIXEDMAP)
1568 meta.mm_address = env->me_map;
1569 i = mdb_env_init_meta(env, &meta);
1570 if (i != MDB_SUCCESS) {
1571 munmap(env->me_map, env->me_mapsize);
1575 env->me_psize = meta.mm_psize;
1577 env->me_maxpg = env->me_mapsize / env->me_psize;
1579 p = (MDB_page *)env->me_map;
1580 env->me_metas[0] = METADATA(p);
1581 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1583 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1586 DPRINTF("opened database version %u, pagesize %u",
1587 env->me_metas[toggle]->mm_version, env->me_psize);
1588 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1589 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1590 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1591 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1592 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1593 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1599 /* Windows doesn't support destructor callbacks for thread-specific storage */
1601 mdb_env_reader_dest(void *ptr)
1603 MDB_reader *reader = ptr;
1605 reader->mr_txnid = 0;
1611 /* downgrade the exclusive lock on the region back to shared */
1613 mdb_env_share_locks(MDB_env *env)
1617 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1619 env->me_txns->mti_me_toggle = toggle;
1620 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1625 /* First acquire a shared lock. The Unlock will
1626 * then release the existing exclusive lock.
1628 memset(&ov, 0, sizeof(ov));
1629 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1630 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1634 struct flock lock_info;
1635 /* The shared lock replaces the existing lock */
1636 memset((void *)&lock_info, 0, sizeof(lock_info));
1637 lock_info.l_type = F_RDLCK;
1638 lock_info.l_whence = SEEK_SET;
1639 lock_info.l_start = 0;
1640 lock_info.l_len = 1;
1641 fcntl(env->me_lfd, F_SETLK, &lock_info);
1647 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1655 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1656 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1657 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1661 /* Try to get exclusive lock. If we succeed, then
1662 * nobody is using the lock region and we should initialize it.
1665 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1669 memset(&ov, 0, sizeof(ov));
1670 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
1676 size = GetFileSize(env->me_lfd, NULL);
1678 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1682 /* Try to get exclusive lock. If we succeed, then
1683 * nobody is using the lock region and we should initialize it.
1686 struct flock lock_info;
1687 memset((void *)&lock_info, 0, sizeof(lock_info));
1688 lock_info.l_type = F_WRLCK;
1689 lock_info.l_whence = SEEK_SET;
1690 lock_info.l_start = 0;
1691 lock_info.l_len = 1;
1692 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1696 lock_info.l_type = F_RDLCK;
1697 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
1704 size = lseek(env->me_lfd, 0, SEEK_END);
1706 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1707 if (size < rsize && *excl) {
1709 SetFilePointer(env->me_lfd, rsize, NULL, 0);
1710 if (!SetEndOfFile(env->me_lfd)) {
1715 if (ftruncate(env->me_lfd, rsize) != 0) {
1722 size = rsize - sizeof(MDB_txninfo);
1723 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1728 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
1734 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
1736 if (!env->me_txns) {
1742 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1744 if (env->me_txns == MAP_FAILED) {
1752 if (!mdb_sec_inited) {
1753 InitializeSecurityDescriptor(&mdb_null_sd,
1754 SECURITY_DESCRIPTOR_REVISION);
1755 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
1756 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1757 mdb_all_sa.bInheritHandle = FALSE;
1758 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
1761 /* FIXME: only using up to 20 characters of the env path here,
1762 * probably not enough to assure uniqueness...
1764 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
1765 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
1766 while ((ptr = strchr(ptr, '\\')))
1768 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1769 if (!env->me_rmutex) {
1773 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
1774 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
1775 while ((ptr = strchr(ptr, '\\')))
1777 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1778 if (!env->me_wmutex) {
1783 pthread_mutexattr_t mattr;
1785 pthread_mutexattr_init(&mattr);
1786 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1790 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1791 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1793 env->me_txns->mti_version = MDB_VERSION;
1794 env->me_txns->mti_magic = MDB_MAGIC;
1795 env->me_txns->mti_txnid = 0;
1796 env->me_txns->mti_numreaders = 0;
1797 env->me_txns->mti_me_toggle = 0;
1800 if (env->me_txns->mti_magic != MDB_MAGIC) {
1801 DPUTS("lock region has invalid magic");
1805 if (env->me_txns->mti_version != MDB_VERSION) {
1806 DPRINTF("lock region is version %u, expected version %u",
1807 env->me_txns->mti_version, MDB_VERSION);
1808 rc = MDB_VERSION_MISMATCH;
1812 if (rc != EACCES && rc != EAGAIN) {
1816 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
1817 if (!env->me_rmutex) {
1821 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
1822 if (!env->me_wmutex) {
1832 env->me_lfd = INVALID_HANDLE_VALUE;
1837 #define LOCKNAME "/lock.mdb"
1838 #define DATANAME "/data.mdb"
1840 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1842 int oflags, rc, len, excl;
1843 char *lpath, *dpath;
1846 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1849 dpath = lpath + len + sizeof(LOCKNAME);
1850 sprintf(lpath, "%s" LOCKNAME, path);
1851 sprintf(dpath, "%s" DATANAME, path);
1853 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1858 if (F_ISSET(flags, MDB_RDONLY)) {
1859 oflags = GENERIC_READ;
1860 len = OPEN_EXISTING;
1862 oflags = GENERIC_READ|GENERIC_WRITE;
1865 mode = FILE_ATTRIBUTE_NORMAL;
1866 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1867 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1872 if (F_ISSET(flags, MDB_RDONLY))
1875 oflags = O_RDWR | O_CREAT;
1877 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1883 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1884 /* synchronous fd for meta writes */
1886 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1887 mode |= FILE_FLAG_WRITE_THROUGH;
1888 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1889 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1894 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1895 oflags |= MDB_DSYNC;
1896 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1901 env->me_path = strdup(path);
1902 DPRINTF("opened dbenv %p", (void *) env);
1903 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1904 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1906 mdb_env_share_locks(env);
1907 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1908 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1909 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1915 if (env->me_fd != INVALID_HANDLE_VALUE) {
1917 env->me_fd = INVALID_HANDLE_VALUE;
1919 if (env->me_lfd != INVALID_HANDLE_VALUE) {
1921 env->me_lfd = INVALID_HANDLE_VALUE;
1929 mdb_env_close(MDB_env *env)
1936 while (env->me_dpages) {
1937 dp = env->me_dpages;
1938 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1942 free(env->me_dbs[1]);
1943 free(env->me_dbs[0]);
1947 LAZY_RWLOCK_DESTROY(&env->me_dblock);
1948 pthread_key_delete(env->me_txkey);
1951 munmap(env->me_map, env->me_mapsize);
1956 pid_t pid = getpid();
1958 for (i=0; i<env->me_txns->mti_numreaders; i++)
1959 if (env->me_txns->mti_readers[i].mr_pid == pid)
1960 env->me_txns->mti_readers[i].mr_pid = 0;
1961 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
1967 /* Search for key within a leaf page, using binary search.
1968 * Returns the smallest entry larger or equal to the key.
1969 * If exactp is non-null, stores whether the found entry was an exact match
1970 * in *exactp (1 or 0).
1971 * If kip is non-null, stores the index of the found entry in *kip.
1972 * If no entry larger or equal to the key is found, returns NULL.
1975 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1976 int *exactp, unsigned int *kip)
1981 MDB_node *node = NULL;
1985 DPRINTF("searching %u keys in %s page %lu",
1987 IS_LEAF(mp) ? "leaf" : "branch",
1990 assert(NUMKEYS(mp) > 0);
1992 memset(&nodekey, 0, sizeof(nodekey));
1994 low = IS_LEAF(mp) ? 0 : 1;
1995 high = NUMKEYS(mp) - 1;
1996 while (low <= high) {
1997 i = (low + high) >> 1;
2000 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
2001 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2003 node = NODEPTR(mp, i);
2005 nodekey.mv_size = node->mn_ksize;
2006 nodekey.mv_data = NODEKEY(node);
2009 rc = mdb_cmp(txn, dbi, key, &nodekey);
2012 DPRINTF("found leaf index %u [%s], rc = %i",
2013 i, DKEY(&nodekey), rc);
2015 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2016 i, DKEY(&nodekey), NODEPGNO(node), rc);
2026 if (rc > 0) { /* Found entry is less than the key. */
2027 i++; /* Skip to get the smallest entry larger than key. */
2028 if (i >= NUMKEYS(mp))
2029 /* There is no entry larger or equal to the key. */
2033 *exactp = (rc == 0);
2034 if (kip) /* Store the key index if requested. */
2037 /* nodeptr is fake for LEAF2 */
2038 return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
2042 cursor_pop_page(MDB_cursor *cursor)
2046 if (cursor->mc_snum) {
2047 top = CURSOR_TOP(cursor);
2050 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
2051 cursor->mc_dbi, (void *) cursor);
2056 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
2060 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2061 cursor->mc_dbi, (void *) cursor);
2063 assert(cursor->mc_snum < CURSOR_STACK);
2065 ppage = &cursor->mc_stack[cursor->mc_snum++];
2066 ppage->mp_page = mp;
2072 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2076 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2079 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2080 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2081 dp = txn->mt_u.dirty_list[x].mptr;
2086 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2087 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2091 DPRINTF("page %lu not found", pgno);
2094 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2098 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2099 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2101 MDB_page *mp = mpp->mp_page;
2105 if (cursor && cursor_push_page(cursor, mp) == NULL)
2108 while (IS_BRANCH(mp)) {
2112 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2113 assert(NUMKEYS(mp) > 1);
2114 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2116 if (key == NULL) /* Initialize cursor to first page. */
2118 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2119 /* cursor to last page */
2123 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
2125 i = NUMKEYS(mp) - 1;
2133 DPRINTF("following index %u for key [%s]",
2135 assert(i < NUMKEYS(mp));
2136 node = NODEPTR(mp, i);
2139 CURSOR_TOP(cursor)->mp_ki = i;
2141 mpp->mp_parent = mp;
2142 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
2147 if (cursor && cursor_push_page(cursor, mp) == NULL)
2151 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
2152 if ((rc = mdb_touch(txn, dbi, mpp)) != 0)
2154 dh = ((MDB_dhead *)mpp->mp_page)-1;
2155 dh->md_parent = mpp->mp_parent;
2156 dh->md_pi = mpp->mp_pi;
2163 DPRINTF("internal error, index points to a %02X page!?",
2165 return MDB_CORRUPTED;
2168 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2169 key ? DKEY(key) : NULL);
2174 /* Search for the page a given key should be in.
2175 * Stores a pointer to the found page in *mpp.
2176 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2177 * If cursor is non-null, pushes parent pages on the cursor stack.
2178 * If modify is true, visited pages are updated with new page numbers.
2181 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2182 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2187 /* Choose which root page to start with. If a transaction is given
2188 * use the root page from the transaction, otherwise read the last
2189 * committed root page.
2191 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2192 DPUTS("transaction has failed, must abort");
2195 root = txn->mt_dbs[dbi].md_root;
2197 if (root == P_INVALID) { /* Tree is empty. */
2198 DPUTS("tree is empty");
2199 return MDB_NOTFOUND;
2202 if ((rc = mdb_get_page(txn, root, &mpp->mp_page)))
2205 DPRINTF("db %u root page %lu has flags 0x%X",
2206 dbi, root, mpp->mp_page->mp_flags);
2209 /* For sub-databases, update main root first */
2210 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
2212 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
2216 txn->mt_dbxs[dbi].md_dirty = 1;
2218 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
2219 mpp->mp_parent = NULL;
2221 if ((rc = mdb_touch(txn, dbi, mpp)))
2223 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
2227 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
2231 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2233 MDB_page *omp; /* overflow mpage */
2237 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2238 data->mv_size = leaf->mn_dsize;
2239 data->mv_data = NODEDATA(leaf);
2243 /* Read overflow data.
2245 data->mv_size = leaf->mn_dsize;
2246 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2247 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2248 DPRINTF("read overflow page %lu failed", pgno);
2251 data->mv_data = METADATA(omp);
2257 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2258 MDB_val *key, MDB_val *data)
2267 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2269 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2272 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2279 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2280 mc.mc_xcursor = &mx;
2281 mdb_xcursor_init0(&mc);
2283 mc.mc_xcursor = NULL;
2285 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2289 mdb_sibling(MDB_cursor *cursor, int move_right)
2296 if (cursor->mc_snum < 2) {
2297 return MDB_NOTFOUND; /* root has no siblings */
2299 parent = CURSOR_PARENT(cursor);
2301 DPRINTF("parent page is page %lu, index %u",
2302 parent->mp_page->mp_pgno, parent->mp_ki);
2304 cursor_pop_page(cursor);
2305 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
2306 : (parent->mp_ki == 0)) {
2307 DPRINTF("no more keys left, moving to %s sibling",
2308 move_right ? "right" : "left");
2309 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2311 parent = CURSOR_TOP(cursor);
2317 DPRINTF("just moving to %s index key %u",
2318 move_right ? "right" : "left", parent->mp_ki);
2320 assert(IS_BRANCH(parent->mp_page));
2322 indx = NODEPTR(parent->mp_page, parent->mp_ki);
2323 if ((rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp)))
2326 mp->parent = parent->mp_page;
2327 mp->parent_index = parent->mp_ki;
2330 cursor_push_page(cursor, mp);
2336 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2343 if (cursor->mc_flags & C_EOF) {
2344 return MDB_NOTFOUND;
2347 assert(cursor->mc_flags & C_INITIALIZED);
2349 top = CURSOR_TOP(cursor);
2352 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2353 leaf = NODEPTR(mp, top->mp_ki);
2354 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2355 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2356 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2357 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2361 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2362 if (op == MDB_NEXT_DUP)
2363 return MDB_NOTFOUND;
2367 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2369 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2370 DPUTS("=====> move to next sibling page");
2371 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2372 cursor->mc_flags |= C_EOF;
2373 return MDB_NOTFOUND;
2375 top = CURSOR_TOP(cursor);
2377 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2381 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2382 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2385 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2386 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2390 assert(IS_LEAF(mp));
2391 leaf = NODEPTR(mp, top->mp_ki);
2393 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2394 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2397 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2400 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2401 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2402 if (rc != MDB_SUCCESS)
2407 MDB_SET_KEY(leaf, key);
2412 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2419 assert(cursor->mc_flags & C_INITIALIZED);
2421 top = CURSOR_TOP(cursor);
2424 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2425 leaf = NODEPTR(mp, top->mp_ki);
2426 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2427 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2428 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2429 if (op != MDB_PREV || rc == MDB_SUCCESS)
2432 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2433 if (op == MDB_PREV_DUP)
2434 return MDB_NOTFOUND;
2439 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2441 if (top->mp_ki == 0) {
2442 DPUTS("=====> move to prev sibling page");
2443 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2444 cursor->mc_flags &= ~C_INITIALIZED;
2445 return MDB_NOTFOUND;
2447 top = CURSOR_TOP(cursor);
2449 top->mp_ki = NUMKEYS(mp) - 1;
2450 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2454 cursor->mc_flags &= ~C_EOF;
2456 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2457 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2460 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2461 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2465 assert(IS_LEAF(mp));
2466 leaf = NODEPTR(mp, top->mp_ki);
2468 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2469 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2472 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2475 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2476 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2477 if (rc != MDB_SUCCESS)
2482 MDB_SET_KEY(leaf, key);
2487 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2488 MDB_cursor_op op, int *exactp)
2498 assert(key->mv_size > 0);
2500 /* See if we're already on the right page */
2501 if (cursor->mc_flags & C_INITIALIZED) {
2503 top = CURSOR_TOP(cursor);
2504 /* Don't try this for LEAF2 pages. Maybe support that later. */
2505 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2506 leaf = NODEPTR(top->mp_page, 0);
2507 MDB_SET_KEY(leaf, &nodekey);
2508 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2510 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2511 MDB_SET_KEY(leaf, &nodekey);
2512 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2514 /* we're already on the right page */
2515 mpp.mp_page = top->mp_page;
2522 cursor->mc_snum = 0;
2524 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2525 if (rc != MDB_SUCCESS)
2528 assert(IS_LEAF(mpp.mp_page));
2530 top = CURSOR_TOP(cursor);
2532 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2533 if (exactp != NULL && !*exactp) {
2534 /* MDB_SET specified and not an exact match. */
2535 return MDB_NOTFOUND;
2539 DPUTS("===> inexact leaf not found, goto sibling");
2540 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2541 return rc; /* no entries matched */
2542 top = CURSOR_TOP(cursor);
2544 mpp.mp_page = top->mp_page;
2545 assert(IS_LEAF(mpp.mp_page));
2546 leaf = NODEPTR(mpp.mp_page, 0);
2549 cursor->mc_flags |= C_INITIALIZED;
2550 cursor->mc_flags &= ~C_EOF;
2552 if (IS_LEAF2(mpp.mp_page)) {
2553 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2554 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2558 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2559 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2562 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2563 if (op == MDB_SET || op == MDB_SET_RANGE) {
2564 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2567 if (op == MDB_GET_BOTH) {
2573 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2574 if (rc != MDB_SUCCESS)
2577 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2579 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2581 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2583 if (op == MDB_GET_BOTH || rc > 0)
2584 return MDB_NOTFOUND;
2588 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2593 /* The key already matches in all other cases */
2594 if (op == MDB_SET_RANGE)
2595 MDB_SET_KEY(leaf, key);
2596 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2602 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2608 cursor->mc_snum = 0;
2610 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2611 if (rc != MDB_SUCCESS)
2613 assert(IS_LEAF(mpp.mp_page));
2615 leaf = NODEPTR(mpp.mp_page, 0);
2616 cursor->mc_flags |= C_INITIALIZED;
2617 cursor->mc_flags &= ~C_EOF;
2619 if (IS_LEAF2(mpp.mp_page)) {
2620 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2621 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2626 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2627 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2628 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2632 if (cursor->mc_xcursor)
2633 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2634 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2638 MDB_SET_KEY(leaf, key);
2643 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2651 cursor->mc_snum = 0;
2653 lkey.mv_size = MAXKEYSIZE+1;
2654 lkey.mv_data = NULL;
2656 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2657 if (rc != MDB_SUCCESS)
2659 assert(IS_LEAF(mpp.mp_page));
2661 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2662 cursor->mc_flags |= C_INITIALIZED;
2663 cursor->mc_flags &= ~C_EOF;
2665 top = CURSOR_TOP(cursor);
2666 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2668 if (IS_LEAF2(mpp.mp_page)) {
2669 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2670 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2675 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2676 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2677 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2681 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2686 MDB_SET_KEY(leaf, key);
2691 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2701 case MDB_GET_BOTH_RANGE:
2702 if (data == NULL || cursor->mc_xcursor == NULL) {
2709 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2711 } else if (op == MDB_SET_RANGE)
2712 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2714 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2716 case MDB_GET_MULTIPLE:
2718 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2719 !(cursor->mc_flags & C_INITIALIZED)) {
2724 if (!(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
2725 (cursor->mc_xcursor->mx_cursor.mc_flags & C_EOF))
2728 case MDB_NEXT_MULTIPLE:
2730 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2734 if (!(cursor->mc_flags & C_INITIALIZED))
2735 rc = mdb_cursor_first(cursor, key, data);
2737 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2738 if (rc == MDB_SUCCESS) {
2739 if (cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
2742 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2743 data->mv_size = NUMKEYS(top->mp_page) *
2744 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2745 data->mv_data = METADATA(top->mp_page);
2746 top->mp_ki = NUMKEYS(top->mp_page)-1;
2754 case MDB_NEXT_NODUP:
2755 if (!(cursor->mc_flags & C_INITIALIZED))
2756 rc = mdb_cursor_first(cursor, key, data);
2758 rc = mdb_cursor_next(cursor, key, data, op);
2762 case MDB_PREV_NODUP:
2763 if (!(cursor->mc_flags & C_INITIALIZED) || (cursor->mc_flags & C_EOF))
2764 rc = mdb_cursor_last(cursor, key, data);
2766 rc = mdb_cursor_prev(cursor, key, data, op);
2769 rc = mdb_cursor_first(cursor, key, data);
2773 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2774 !(cursor->mc_flags & C_INITIALIZED) ||
2775 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2779 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2782 rc = mdb_cursor_last(cursor, key, data);
2786 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2787 !(cursor->mc_flags & C_INITIALIZED) ||
2788 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2792 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2795 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2804 mdb_cursor_touch(MDB_cursor *cursor)
2810 mpp.mp_parent = NULL;
2812 for(i=0; i<cursor->mc_snum; i++) {
2813 mpp.mp_page = cursor->mc_stack[i].mp_page;
2814 if (!F_ISSET(mpp.mp_page->mp_flags, P_DIRTY)) {
2815 rc = mdb_touch(cursor->mc_txn, cursor->mc_dbi, &mpp);
2817 cursor->mc_stack[i].mp_page = mpp.mp_page;
2819 mpp.mp_parent = mpp.mp_page;
2820 mpp.mp_pi = cursor->mc_stack[i].mp_ki;
2826 mdb_cursor_put(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2833 if (F_ISSET(cursor->mc_txn->mt_flags, MDB_TXN_RDONLY))
2836 if (flags == MDB_NODUPDATA) {
2837 rc = mdb_cursor_set(cursor, key, data, MDB_GET_BOTH, &exact);
2839 return MDB_KEYEXIST;
2840 if (rc != MDB_NOTFOUND)
2842 } else if (flags != MDB_CURRENT) {
2843 rc = mdb_cursor_set(cursor, key, NULL, MDB_SET, &exact);
2844 if (flags == MDB_NOOVERWRITE && rc == 0)
2845 return MDB_KEYEXIST;
2846 if (rc != MDB_NOTFOUND)
2848 } else if (!(cursor->mc_flags & C_INITIALIZED)) {
2851 /* Cursor is positioned, now make sure all pages are writable */
2852 rc = mdb_cursor_touch(cursor);
2854 if (cursor->mc_xcursor) {
2855 rc = mdb_cursor_touch(&cursor->mc_xcursor->mx_cursor);
2857 cursor->mc_flags |= C_XDIRTY;
2860 top = CURSOR_TOP(cursor);
2866 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
2873 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
2876 if (!mc->mc_flags & C_INITIALIZED)
2879 rc = mdb_cursor_touch(mc);
2881 if (mc->mc_xcursor) {
2882 rc = mdb_cursor_touch(&mc->mc_xcursor->mx_cursor);
2886 top = CURSOR_TOP(mc);
2887 leaf = NODEPTR(top->mp_page, top->mp_ki);
2889 if (!IS_LEAF2(top->mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2892 if (flags != MDB_NODUPDATA) {
2893 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
2894 mdb_xcursor_fini(mc);
2895 /* If sub-DB still has entries, we're done */
2896 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
2898 memcpy(NODEDATA(leaf),
2899 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
2901 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
2904 /* otherwise fall thru and delete the sub-DB */
2906 /* add all the child DB's pages to the free list */
2907 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2908 NULL, &mx.mx_cursor, 0, &mp2);
2909 if (rc == MDB_SUCCESS) {
2910 MDB_ppage *top, *parent;
2914 cursor_pop_page(&mx.mx_cursor);
2915 if (mx.mx_cursor.mc_snum) {
2916 top = CURSOR_TOP(&mx.mx_cursor);
2917 while (mx.mx_cursor.mc_snum > 1) {
2918 parent = CURSOR_PARENT(&mx.mx_cursor);
2919 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2920 ni = NODEPTR(top->mp_page, i);
2921 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
2924 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2925 cursor_pop_page(&mx.mx_cursor);
2928 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2929 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
2933 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2938 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2942 /* Allocate a page and initialize it
2945 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2949 if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
2951 DPRINTF("allocated new mpage %lu, page size %u",
2952 dp->p.mp_pgno, txn->mt_env->me_psize);
2953 dp->p.mp_flags = flags | P_DIRTY;
2954 dp->p.mp_lower = PAGEHDRSZ;
2955 dp->p.mp_upper = txn->mt_env->me_psize;
2957 if (IS_BRANCH(&dp->p))
2958 txn->mt_dbs[dbi].md_branch_pages++;
2959 else if (IS_LEAF(&dp->p))
2960 txn->mt_dbs[dbi].md_leaf_pages++;
2961 else if (IS_OVERFLOW(&dp->p)) {
2962 txn->mt_dbs[dbi].md_overflow_pages += num;
2963 dp->p.mp_pages = num;
2970 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2974 sz = LEAFSIZE(key, data);
2975 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2976 /* put on overflow page */
2977 sz -= data->mv_size - sizeof(pgno_t);
2980 return sz + sizeof(indx_t);
2984 mdb_branch_size(MDB_env *env, MDB_val *key)
2989 if (sz >= env->me_psize / MDB_MINKEYS) {
2990 /* put on overflow page */
2991 /* not implemented */
2992 /* sz -= key->size - sizeof(pgno_t); */
2995 return sz + sizeof(indx_t);
2999 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
3000 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3003 size_t node_size = NODESIZE;
3006 MDB_dpage *ofp = NULL; /* overflow page */
3009 assert(mp->mp_upper >= mp->mp_lower);
3011 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
3012 IS_LEAF(mp) ? "leaf" : "branch",
3013 mp->mp_pgno, indx, data ? data->mv_size : 0,
3014 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3017 /* Move higher keys up one slot. */
3018 int ksize = txn->mt_dbs[dbi].md_pad, dif;
3019 char *ptr = LEAF2KEY(mp, indx, ksize);
3020 dif = NUMKEYS(mp) - indx;
3022 memmove(ptr+ksize, ptr, dif*ksize);
3023 /* insert new key */
3024 memcpy(ptr, key->mv_data, ksize);
3026 /* Just using these for counting */
3027 mp->mp_lower += sizeof(indx_t);
3028 mp->mp_upper -= ksize - sizeof(indx_t);
3033 node_size += key->mv_size;
3037 if (F_ISSET(flags, F_BIGDATA)) {
3038 /* Data already on overflow page. */
3039 node_size += sizeof(pgno_t);
3040 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
3041 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
3042 /* Put data on overflow page. */
3043 DPRINTF("data size is %zu, put on overflow page",
3045 node_size += sizeof(pgno_t);
3046 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
3048 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
3051 node_size += data->mv_size;
3055 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3056 DPRINTF("not enough room in page %lu, got %u ptrs",
3057 mp->mp_pgno, NUMKEYS(mp));
3058 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3059 mp->mp_upper - mp->mp_lower);
3060 DPRINTF("node size = %zu", node_size);
3064 /* Move higher pointers up one slot. */
3065 for (i = NUMKEYS(mp); i > indx; i--)
3066 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3068 /* Adjust free space offsets. */
3069 ofs = mp->mp_upper - node_size;
3070 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3071 mp->mp_ptrs[indx] = ofs;
3073 mp->mp_lower += sizeof(indx_t);
3075 /* Write the node data. */
3076 node = NODEPTR(mp, indx);
3077 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3078 node->mn_flags = flags;
3080 node->mn_dsize = data->mv_size;
3082 NODEPGNO(node) = pgno;
3085 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3090 if (F_ISSET(flags, F_BIGDATA))
3091 memcpy(node->mn_data + key->mv_size, data->mv_data,
3094 memcpy(node->mn_data + key->mv_size, data->mv_data,
3097 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
3099 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
3107 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3110 indx_t i, j, numkeys, ptr;
3114 DPRINTF("delete node %u on %s page %lu", indx,
3115 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3116 assert(indx < NUMKEYS(mp));
3119 int x = NUMKEYS(mp) - 1 - indx;
3120 base = LEAF2KEY(mp, indx, ksize);
3122 memmove(base, base + ksize, x * ksize);
3123 mp->mp_lower -= sizeof(indx_t);
3124 mp->mp_upper += ksize - sizeof(indx_t);
3128 node = NODEPTR(mp, indx);
3129 sz = NODESIZE + node->mn_ksize;
3131 if (F_ISSET(node->mn_flags, F_BIGDATA))
3132 sz += sizeof(pgno_t);
3134 sz += NODEDSZ(node);
3137 ptr = mp->mp_ptrs[indx];
3138 numkeys = NUMKEYS(mp);
3139 for (i = j = 0; i < numkeys; i++) {
3141 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3142 if (mp->mp_ptrs[i] < ptr)
3143 mp->mp_ptrs[j] += sz;
3148 base = (char *)mp + mp->mp_upper;
3149 memmove(base + sz, base, ptr - mp->mp_upper);
3151 mp->mp_lower -= sizeof(indx_t);
3156 mdb_xcursor_init0(MDB_cursor *mc)
3158 MDB_xcursor *mx = mc->mc_xcursor;
3161 mx->mx_txn = *mc->mc_txn;
3162 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3163 mx->mx_txn.mt_dbs = mx->mx_dbs;
3164 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3165 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3166 if (mc->mc_dbi > 1) {
3167 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3172 mx->mx_dbxs[dbn+1].md_parent = dbn;
3173 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3174 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3175 mx->mx_dbxs[dbn+1].md_dirty = 0;
3176 mx->mx_txn.mt_numdbs = dbn+2;
3178 mx->mx_cursor.mc_snum = 0;
3179 mx->mx_cursor.mc_txn = &mx->mx_txn;
3180 mx->mx_cursor.mc_dbi = dbn+1;
3184 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
3186 MDB_db *db = NODEDATA(node);
3188 mx->mx_dbs[0] = txn->mt_dbs[0];
3189 mx->mx_dbs[1] = txn->mt_dbs[1];
3191 mx->mx_dbs[2] = txn->mt_dbs[dbi];
3196 DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
3197 mx->mx_dbs[dbn] = *db;
3198 if (F_ISSET(mp->mp_flags, P_DIRTY))
3199 mx->mx_dbxs[dbn].md_dirty = 1;
3200 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3201 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3202 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
3203 mx->mx_txn.mt_u = txn->mt_u;
3204 mx->mx_cursor.mc_flags = 0;
3208 mdb_xcursor_fini(MDB_cursor *mc)
3210 MDB_xcursor *mx = mc->mc_xcursor;
3211 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3212 mc->mc_txn->mt_u = mx->mx_txn.mt_u;
3213 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3214 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3215 mc->mc_txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
3216 mc->mc_txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
3217 if (mc->mc_dbi > 1) {
3218 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3219 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3224 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3227 size_t size = sizeof(MDB_cursor);
3229 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3232 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3233 size += sizeof(MDB_xcursor);
3235 if ((cursor = calloc(1, size)) != NULL) {
3236 cursor->mc_dbi = dbi;
3237 cursor->mc_txn = txn;
3238 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3239 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
3240 cursor->mc_xcursor = mx;
3241 mdb_xcursor_init0(cursor);
3252 /* Return the count of duplicate data items for the current key */
3254 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3259 if (mc == NULL || countp == NULL)
3262 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3265 top = CURSOR_TOP(mc);
3266 leaf = NODEPTR(top->mp_page, top->mp_ki);
3267 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3270 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3273 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3279 mdb_cursor_close(MDB_cursor *cursor)
3281 if (cursor != NULL) {
3287 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3289 indx_t ptr, i, numkeys;
3296 node = NODEPTR(mp, indx);
3297 ptr = mp->mp_ptrs[indx];
3298 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3300 (int)node->mn_ksize, (char *)NODEKEY(node),
3304 delta = key->mv_size - node->mn_ksize;
3306 if (delta > 0 && SIZELEFT(mp) < delta) {
3307 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3311 numkeys = NUMKEYS(mp);
3312 for (i = 0; i < numkeys; i++) {
3313 if (mp->mp_ptrs[i] <= ptr)
3314 mp->mp_ptrs[i] -= delta;
3317 base = (char *)mp + mp->mp_upper;
3318 len = ptr - mp->mp_upper + NODESIZE;
3319 memmove(base - delta, base, len);
3320 mp->mp_upper -= delta;
3322 node = NODEPTR(mp, indx);
3323 node->mn_ksize = key->mv_size;
3326 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3331 /* Move a node from src to dst.
3334 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
3335 MDB_pageparent *dst, indx_t dstindx)
3342 /* Mark src and dst as dirty. */
3343 if ((rc = mdb_touch(txn, dbi, src)) ||
3344 (rc = mdb_touch(txn, dbi, dst)))
3347 if (IS_LEAF2(src->mp_page)) {
3348 srcnode = NODEPTR(src->mp_page, 0); /* fake */
3349 key.mv_size = txn->mt_dbs[dbi].md_pad;
3350 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3352 data.mv_data = NULL;
3354 srcnode = NODEPTR(src->mp_page, srcindx);
3355 key.mv_size = NODEKSZ(srcnode);
3356 key.mv_data = NODEKEY(srcnode);
3357 data.mv_size = NODEDSZ(srcnode);
3358 data.mv_data = NODEDATA(srcnode);
3360 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3361 IS_LEAF(src->mp_page) ? "leaf" : "branch",
3364 src->mp_page->mp_pgno,
3365 dstindx, dst->mp_page->mp_pgno);
3367 /* Add the node to the destination page.
3369 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
3371 if (rc != MDB_SUCCESS)
3374 /* Delete the node from the source page.
3376 mdb_del_node(src->mp_page, srcindx, key.mv_size);
3378 /* The key value just changed due to del_node, find it again.
3380 if (!IS_LEAF2(src->mp_page)) {
3381 srcnode = NODEPTR(src->mp_page, srcindx);
3382 key.mv_data = NODEKEY(srcnode);
3385 /* Update the parent separators.
3388 if (src->mp_pi != 0) {
3389 DPRINTF("update separator for source page %lu to [%s]",
3390 src->mp_page->mp_pgno, DKEY(&key));
3391 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
3392 &key)) != MDB_SUCCESS)
3395 if (IS_BRANCH(src->mp_page)) {
3397 nullkey.mv_size = 0;
3398 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
3403 if (dst->mp_pi != 0) {
3404 DPRINTF("update separator for destination page %lu to [%s]",
3405 dst->mp_page->mp_pgno, DKEY(&key));
3406 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
3407 &key)) != MDB_SUCCESS)
3410 if (IS_BRANCH(dst->mp_page)) {
3412 nullkey.mv_size = 0;
3413 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
3421 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
3430 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
3432 assert(txn != NULL);
3433 assert(src->mp_parent); /* can't merge root page */
3434 assert(dst->mp_parent);
3436 /* Mark src and dst as dirty. */
3437 if ((rc = mdb_touch(txn, dbi, src)) ||
3438 (rc = mdb_touch(txn, dbi, dst)))
3441 /* Move all nodes from src to dst.
3443 if (IS_LEAF2(src->mp_page)) {
3444 key.mv_size = txn->mt_dbs[dbi].md_pad;
3445 key.mv_data = METADATA(src->mp_page);
3446 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3447 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3449 if (rc != MDB_SUCCESS)
3451 key.mv_data = (char *)key.mv_data + key.mv_size;
3454 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3455 srcnode = NODEPTR(src->mp_page, i);
3457 key.mv_size = srcnode->mn_ksize;
3458 key.mv_data = NODEKEY(srcnode);
3459 data.mv_size = NODEDSZ(srcnode);
3460 data.mv_data = NODEDATA(srcnode);
3461 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3462 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3463 if (rc != MDB_SUCCESS)
3468 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3469 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3471 /* Unlink the src page from parent.
3473 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3474 if (src->mp_pi == 0) {
3476 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3480 if (IS_LEAF(src->mp_page))
3481 txn->mt_dbs[dbi].md_leaf_pages--;
3483 txn->mt_dbs[dbi].md_branch_pages--;
3485 mpp.mp_page = src->mp_parent;
3486 dh = (MDB_dhead *)src->mp_parent;
3488 mpp.mp_parent = dh->md_parent;
3489 mpp.mp_pi = dh->md_pi;
3491 return mdb_rebalance(txn, dbi, &mpp);
3494 #define FILL_THRESHOLD 250
3497 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3502 indx_t si = 0, di = 0;
3505 assert(txn != NULL);
3506 assert(mpp != NULL);
3508 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3509 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3510 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3512 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3513 DPRINTF("no need to rebalance page %lu, above fill threshold",
3514 mpp->mp_page->mp_pgno);
3518 if (mpp->mp_parent == NULL) {
3519 if (NUMKEYS(mpp->mp_page) == 0) {
3520 DPUTS("tree is completely empty");
3521 txn->mt_dbs[dbi].md_root = P_INVALID;
3522 txn->mt_dbs[dbi].md_depth = 0;
3523 txn->mt_dbs[dbi].md_leaf_pages = 0;
3524 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3525 DPUTS("collapsing root page!");
3526 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3527 if ((rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root)))
3529 txn->mt_dbs[dbi].md_depth--;
3530 txn->mt_dbs[dbi].md_branch_pages--;
3532 DPUTS("root page doesn't need rebalancing");
3536 /* The parent (branch page) must have at least 2 pointers,
3537 * otherwise the tree is invalid.
3539 assert(NUMKEYS(mpp->mp_parent) > 1);
3541 /* Leaf page fill factor is below the threshold.
3542 * Try to move keys from left or right neighbor, or
3543 * merge with a neighbor page.
3548 if (mpp->mp_pi == 0) {
3549 /* We're the leftmost leaf in our parent.
3551 DPUTS("reading right neighbor");
3552 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3553 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3555 npp.mp_pi = mpp->mp_pi + 1;
3557 di = NUMKEYS(mpp->mp_page);
3559 /* There is at least one neighbor to the left.
3561 DPUTS("reading left neighbor");
3562 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3563 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3565 npp.mp_pi = mpp->mp_pi - 1;
3566 si = NUMKEYS(npp.mp_page) - 1;
3569 npp.mp_parent = mpp->mp_parent;
3571 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3572 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3574 /* If the neighbor page is above threshold and has at least two
3575 * keys, move one key from it.
3577 * Otherwise we should try to merge them.
3579 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3580 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3581 else { /* FIXME: if (has_enough_room()) */
3582 if (mpp->mp_pi == 0)
3583 return mdb_merge(txn, dbi, &npp, mpp);
3585 return mdb_merge(txn, dbi, mpp, &npp);
3590 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3594 /* add overflow pages to free list */
3595 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3599 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3600 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3601 for (i=0; i<ovpages; i++) {
3602 DPRINTF("freed ov page %lu", pg);
3603 mdb_midl_insert(txn->mt_free_pgs, pg);
3607 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3608 txn->mt_dbs[dbi].md_entries--;
3609 rc = mdb_rebalance(txn, dbi, mpp);
3610 if (rc != MDB_SUCCESS)
3611 txn->mt_flags |= MDB_TXN_ERROR;
3617 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3618 MDB_val *key, MDB_val *data)
3626 assert(key != NULL);
3628 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3630 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3633 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3637 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3641 mpp.mp_parent = NULL;
3643 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3646 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3647 if (leaf == NULL || !exact) {
3648 return MDB_NOTFOUND;
3651 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3659 mc.mc_xcursor = &mx;
3660 mdb_xcursor_init0(&mc);
3661 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3663 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL);
3664 mdb_xcursor_fini(&mc);
3665 /* If sub-DB still has entries, we're done */
3666 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3667 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3669 txn->mt_dbs[dbi].md_entries--;
3672 /* otherwise fall thru and delete the sub-DB */
3674 /* add all the child DB's pages to the free list */
3675 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3676 NULL, &mx.mx_cursor, 0, &mp2);
3677 if (rc == MDB_SUCCESS) {
3678 MDB_ppage *top, *parent;
3682 cursor_pop_page(&mx.mx_cursor);
3683 if (mx.mx_cursor.mc_snum) {
3684 top = CURSOR_TOP(&mx.mx_cursor);
3685 while (mx.mx_cursor.mc_snum > 1) {
3686 parent = CURSOR_PARENT(&mx.mx_cursor);
3687 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3688 ni = NODEPTR(top->mp_page, i);
3689 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3692 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3693 cursor_pop_page(&mx.mx_cursor);
3696 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3697 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3701 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3706 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3709 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3710 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3711 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3712 * refer to a node in the new right sibling page.
3715 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3716 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3719 int rc = MDB_SUCCESS, ins_new = 0;
3722 unsigned int i, j, split_indx, nkeys, pmax;
3724 MDB_val sepkey, rkey, rdata;
3725 MDB_page *copy, *cptr;
3726 MDB_dpage *mdp, *rdp, *pdp;
3730 assert(txn != NULL);
3732 dh = ((MDB_dhead *)*mpp) - 1;
3733 mdp = (MDB_dpage *)dh;
3734 newindx = *newindxp;
3736 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3737 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3738 DKEY(newkey), *newindxp);
3740 if (mdp->h.md_parent == NULL) {
3741 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3744 mdp->h.md_parent = &pdp->p;
3745 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3746 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3747 txn->mt_dbs[dbi].md_depth++;
3749 /* Add left (implicit) pointer. */
3750 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3751 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3754 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3757 /* Create a right sibling. */
3758 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3760 rdp->h.md_parent = mdp->h.md_parent;
3761 rdp->h.md_pi = mdp->h.md_pi + 1;
3762 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3764 nkeys = NUMKEYS(&mdp->p);
3765 split_indx = nkeys / 2 + 1;
3767 if (IS_LEAF2(&rdp->p)) {
3770 unsigned int lsize, rsize, ksize;
3771 /* Move half of the keys to the right sibling */
3773 x = *newindxp - split_indx;
3774 ksize = txn->mt_dbs[dbi].md_pad;
3775 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3776 rsize = (nkeys - split_indx) * ksize;
3777 lsize = (nkeys - split_indx) * sizeof(indx_t);
3778 mdp->p.mp_lower -= lsize;
3779 rdp->p.mp_lower += lsize;
3780 mdp->p.mp_upper += rsize - lsize;
3781 rdp->p.mp_upper -= rsize - lsize;
3782 sepkey.mv_size = ksize;
3783 if (newindx == split_indx) {
3784 sepkey.mv_data = newkey->mv_data;
3786 sepkey.mv_data = split;
3789 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3790 memcpy(&rdp->p.mp_ptrs, split, rsize);
3791 sepkey.mv_data = &rdp->p.mp_ptrs;
3792 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3793 memcpy(ins, newkey->mv_data, ksize);
3794 mdp->p.mp_lower += sizeof(indx_t);
3795 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3798 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3799 ins = LEAF2KEY(&rdp->p, x, ksize);
3800 memcpy(ins, newkey->mv_data, ksize);
3801 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3802 rdp->p.mp_lower += sizeof(indx_t);
3803 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3810 /* For leaf pages, check the split point based on what
3811 * fits where, since otherwise add_node can fail.
3813 if (IS_LEAF(&mdp->p)) {
3814 unsigned int psize, nsize;
3815 /* Maximum free space in an empty page */
3816 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
3817 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
3818 if (newindx < split_indx) {
3820 for (i=0; i<split_indx; i++) {
3821 node = NODEPTR(&mdp->p, i);
3822 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
3823 if (F_ISSET(node->mn_flags, F_BIGDATA))
3824 psize += sizeof(pgno_t);
3826 psize += NODEDSZ(node);
3834 for (i=nkeys-1; i>=split_indx; i--) {
3835 node = NODEPTR(&mdp->p, i);
3836 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
3837 if (F_ISSET(node->mn_flags, F_BIGDATA))
3838 psize += sizeof(pgno_t);
3840 psize += NODEDSZ(node);
3849 /* First find the separating key between the split pages.
3851 memset(&sepkey, 0, sizeof(sepkey));
3852 if (newindx == split_indx) {
3853 sepkey.mv_size = newkey->mv_size;
3854 sepkey.mv_data = newkey->mv_data;
3856 node = NODEPTR(&mdp->p, split_indx);
3857 sepkey.mv_size = node->mn_ksize;
3858 sepkey.mv_data = NODEKEY(node);
3862 DPRINTF("separator is [%s]", DKEY(&sepkey));
3864 /* Copy separator key to the parent.
3866 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3867 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3868 &sepkey, NULL, rdp->p.mp_pgno);
3870 /* Right page might now have changed parent.
3871 * Check if left page also changed parent.
3873 if (rdp->h.md_parent != mdp->h.md_parent &&
3874 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3875 mdp->h.md_parent = rdp->h.md_parent;
3876 mdp->h.md_pi = rdp->h.md_pi - 1;
3879 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3880 &sepkey, NULL, rdp->p.mp_pgno, 0);
3882 if (IS_LEAF2(&rdp->p)) {
3885 if (rc != MDB_SUCCESS) {
3889 /* Move half of the keys to the right sibling. */
3890 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3893 copy->mp_pgno = mdp->p.mp_pgno;
3894 copy->mp_flags = mdp->p.mp_flags;
3895 copy->mp_lower = PAGEHDRSZ;
3896 copy->mp_upper = txn->mt_env->me_psize;
3898 for (i = j = 0; i <= nkeys; j++) {
3899 if (i == split_indx) {
3900 /* Insert in right sibling. */
3901 /* Reset insert index for right sibling. */
3902 j = (i == newindx && ins_new);
3906 if (i == newindx && !ins_new) {
3907 /* Insert the original entry that caused the split. */
3908 rkey.mv_data = newkey->mv_data;
3909 rkey.mv_size = newkey->mv_size;
3910 if (IS_LEAF(&mdp->p)) {
3911 rdata.mv_data = newdata->mv_data;
3912 rdata.mv_size = newdata->mv_size;
3919 /* Update page and index for the new key. */
3921 if (cptr == &rdp->p)
3923 } else if (i == nkeys) {
3926 node = NODEPTR(&mdp->p, i);
3927 rkey.mv_data = NODEKEY(node);
3928 rkey.mv_size = node->mn_ksize;
3929 if (IS_LEAF(&mdp->p)) {
3930 rdata.mv_data = NODEDATA(node);
3931 rdata.mv_size = node->mn_dsize;
3933 pgno = NODEPGNO(node);
3934 flags = node->mn_flags;
3939 if (!IS_LEAF(&mdp->p) && j == 0) {
3940 /* First branch index doesn't need key data. */
3944 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
3946 nkeys = NUMKEYS(copy);
3947 for (i=0; i<nkeys; i++)
3948 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
3949 mdp->p.mp_lower = copy->mp_lower;
3950 mdp->p.mp_upper = copy->mp_upper;
3951 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
3952 txn->mt_env->me_psize - copy->mp_upper);
3959 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3960 MDB_val *key, MDB_val *data, unsigned int flags)
3962 int rc = MDB_SUCCESS, exact;
3966 MDB_val xdata, *rdata, dkey;
3968 char dbuf[PAGESIZE];
3973 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3974 dbi, DKEY(key), key->mv_size, data->mv_size);
3977 mpp.mp_parent = NULL;
3979 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3980 if (rc == MDB_SUCCESS) {
3981 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3982 if (leaf && exact) {
3983 if (flags == MDB_NOOVERWRITE) {
3984 DPRINTF("duplicate key [%s]", DKEY(key));
3985 return MDB_KEYEXIST;
3987 /* there's only a key anyway, so this is a no-op */
3988 if (IS_LEAF2(mpp.mp_page))
3991 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3992 /* Was a single item before, must convert now */
3993 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3994 dkey.mv_size = NODEDSZ(leaf);
3995 dkey.mv_data = dbuf;
3996 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3997 /* data matches, ignore it */
3998 if (!mdb_dcmp(txn, dbi, data, &dkey))
3999 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4000 memset(&dummy, 0, sizeof(dummy));
4001 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
4002 dummy.md_pad = data->mv_size;
4003 dummy.md_flags = MDB_DUPFIXED;
4004 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
4005 dummy.md_flags |= MDB_INTEGERKEY;
4007 dummy.md_root = P_INVALID;
4008 if (dkey.mv_size == sizeof(MDB_db)) {
4009 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
4012 mdb_del_node(mpp.mp_page, ki, 0);
4015 xdata.mv_size = sizeof(MDB_db);
4016 xdata.mv_data = &dummy;
4021 /* same size, just replace it */
4022 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4023 NODEDSZ(leaf) == data->mv_size) {
4024 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4027 mdb_del_node(mpp.mp_page, ki, 0);
4029 if (leaf == NULL) { /* append if not found */
4030 ki = NUMKEYS(mpp.mp_page);
4031 DPRINTF("appending key at index %i", ki);
4033 } else if (rc == MDB_NOTFOUND) {
4035 /* new file, just write a root leaf page */
4036 DPUTS("allocating new root leaf page");
4037 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
4040 mpp.mp_page = &dp->p;
4041 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
4042 txn->mt_dbs[dbi].md_depth++;
4043 txn->mt_dbxs[dbi].md_dirty = 1;
4044 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
4045 mpp.mp_page->mp_flags |= P_LEAF2;
4051 assert(IS_LEAF(mpp.mp_page));
4052 DPRINTF("there are %u keys, should insert new key at index %i",
4053 NUMKEYS(mpp.mp_page), ki);
4058 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
4059 if (SIZELEFT(mpp.mp_page) < nsize) {
4060 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
4062 /* There is room already in this leaf page. */
4063 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
4066 if (rc != MDB_SUCCESS)
4067 txn->mt_flags |= MDB_TXN_ERROR;
4069 /* Remember if we just added a subdatabase */
4070 if (flags & F_SUBDATA) {
4071 leaf = NODEPTR(mpp.mp_page, ki);
4072 leaf->mn_flags |= F_SUBDATA;
4075 /* Now store the actual data in the child DB. Note that we're
4076 * storing the user data in the keys field, so there are strict
4077 * size limits on dupdata. The actual data fields of the child
4078 * DB are all zero size.
4084 leaf = NODEPTR(mpp.mp_page, ki);
4089 mc.mc_xcursor = &mx;
4090 mdb_xcursor_init0(&mc);
4091 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
4094 if (flags == MDB_NODUPDATA)
4095 flags = MDB_NOOVERWRITE;
4096 /* converted, write the original data first */
4098 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
4100 leaf->mn_flags |= F_DUPDATA;
4102 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
4103 mdb_xcursor_fini(&mc);
4104 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
4107 txn->mt_dbs[dbi].md_entries++;
4115 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4116 MDB_val *key, MDB_val *data, unsigned int flags)
4122 assert(key != NULL);
4123 assert(data != NULL);
4125 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4128 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4132 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4136 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4143 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4144 mc.mc_xcursor = &mx;
4145 mdb_xcursor_init0(&mc);
4147 mc.mc_xcursor = NULL;
4149 rc = mdb_cursor_put(&mc, key, data, flags);
4150 if (mc.mc_xcursor) {
4153 mdb_xcursor_fini(&mc);
4154 top = CURSOR_TOP(&mc);
4155 leaf = NODEPTR(top->mp_page, top->mp_ki);
4156 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
4163 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4165 #define CHANGEABLE (MDB_NOSYNC)
4166 if ((flag & CHANGEABLE) != flag)
4169 env->me_flags |= flag;
4171 env->me_flags &= ~flag;
4176 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4181 *arg = env->me_flags;
4186 mdb_env_get_path(MDB_env *env, const char **arg)
4191 *arg = env->me_path;
4196 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4198 arg->ms_psize = env->me_psize;
4199 arg->ms_depth = db->md_depth;
4200 arg->ms_branch_pages = db->md_branch_pages;
4201 arg->ms_leaf_pages = db->md_leaf_pages;
4202 arg->ms_overflow_pages = db->md_overflow_pages;
4203 arg->ms_entries = db->md_entries;
4208 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4212 if (env == NULL || arg == NULL)
4215 mdb_env_read_meta(env, &toggle);
4217 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4220 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4230 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4231 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4235 /* Is the DB already open? */
4237 for (i=2; i<txn->mt_numdbs; i++) {
4238 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4239 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4245 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4248 /* Find the DB info */
4250 key.mv_data = (void *)name;
4251 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4253 /* Create if requested */
4254 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4256 data.mv_size = sizeof(MDB_db);
4257 data.mv_data = &dummy;
4258 memset(&dummy, 0, sizeof(dummy));
4259 dummy.md_root = P_INVALID;
4260 dummy.md_flags = flags & 0xffff;
4261 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
4265 /* OK, got info, add to table */
4266 if (rc == MDB_SUCCESS) {
4267 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4268 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4269 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
4270 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
4271 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4272 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4273 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4274 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4275 *dbi = txn->mt_numdbs;
4276 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4277 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4284 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4286 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4289 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4292 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4295 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4297 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4298 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4299 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4303 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4305 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4308 txn->mt_dbxs[dbi].md_cmp = cmp;
4312 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4314 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4317 txn->mt_dbxs[dbi].md_dcmp = cmp;
4321 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4323 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4326 txn->mt_dbxs[dbi].md_rel = rel;