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
353 struct MDB_xcursor *mc_xcursor;
356 unsigned int mc_snum; /* number of pushed pages */
357 unsigned int mc_flags;
358 #define C_INITIALIZED 0x01
360 #define C_XDIRTY 0x04
361 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
364 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
366 /* We guarantee 2-byte alignment for nodes */
367 typedef struct MDB_node {
368 /* lo and hi are used for data size on leaf nodes and for
369 * child pgno on branch nodes. On 64 bit platforms, flags
370 * is also used for pgno. (branch nodes ignore flags)
372 unsigned short mn_lo;
373 unsigned short mn_hi;
374 unsigned short mn_flags;
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 */
378 unsigned short mn_ksize; /* key size */
382 typedef struct MDB_dbx {
384 MDB_cmp_func *md_cmp; /* user compare function */
385 MDB_cmp_func *md_dcmp; /* user dupsort function */
386 MDB_rel_func *md_rel; /* user relocate function */
388 unsigned int md_dirty;
392 pgno_t mt_next_pgno; /* next unallocated page */
395 pgno_t *mt_free_pgs; /* this is an IDL */
397 ID2L dirty_list; /* modified pages */
400 MDB_dbx *mt_dbxs; /* array */
402 unsigned int mt_numdbs;
404 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
405 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
406 unsigned int mt_flags;
407 unsigned int mt_toggle;
410 /* Context for sorted-dup records */
411 typedef struct MDB_xcursor {
412 MDB_cursor mx_cursor;
421 HANDLE me_mfd; /* just for writing the meta pages */
422 #define MDB_FATAL_ERROR 0x80000000U
424 uint32_t me_extrapad; /* unused for now */
425 unsigned int me_maxreaders;
426 unsigned int me_numdbs;
427 unsigned int me_maxdbs;
430 MDB_txninfo *me_txns;
431 MDB_meta *me_metas[2];
432 MDB_txn *me_txn; /* current write transaction */
434 off_t me_size; /* current file size */
435 pgno_t me_maxpg; /* me_mapsize / me_psize */
436 unsigned int me_psize;
437 unsigned int me_db_toggle;
438 MDB_dbx *me_dbxs; /* array */
440 MDB_oldpages *me_pghead;
441 pthread_key_t me_txkey; /* thread-key for readers */
442 MDB_dpage *me_dpages;
443 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
444 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
445 LAZY_RWLOCK_DEF(me_dblock);
447 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
452 #define NODESIZE offsetof(MDB_node, mn_data)
454 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
455 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
456 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
457 #define NODEKEY(node) (void *)((node)->mn_data)
458 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
459 #if LONG_MAX == 0x7fffffff
460 #define NODEPGNO(node) ((node)->mn_lo | ((node)->mn_hi << 16))
461 #define SETPGNO(node,pgno) do { \
462 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16;} while(0)
464 #define NODEPGNO(node) ((node)->mn_lo | ((node)->mn_hi << 16) | ((unsigned long)(node)->mn_flags << 32))
465 #define SETPGNO(node,pgno) do { \
466 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
467 (node)->mn_flags = (pgno) >> 32; } while(0)
469 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
470 #define SETDSZ(node,size) do { \
471 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
472 #define NODEKSZ(node) ((node)->mn_ksize)
473 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
475 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
477 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
479 static int mdb_search_page_root(MDB_txn *txn,
480 MDB_dbi dbi, MDB_val *key,
481 MDB_cursor *cursor, int modify,
482 MDB_pageparent *mpp);
483 static int mdb_search_page(MDB_txn *txn,
484 MDB_dbi dbi, MDB_val *key,
485 MDB_cursor *cursor, int modify,
486 MDB_pageparent *mpp);
488 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
489 static int mdb_env_read_meta(MDB_env *env, int *which);
490 static int mdb_env_write_meta(MDB_txn *txn);
491 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
493 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
494 MDB_val *key, int *exactp, unsigned int *kip);
495 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
496 indx_t indx, MDB_val *key, MDB_val *data,
497 pgno_t pgno, uint8_t flags);
498 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
499 static int mdb_del0(MDB_cursor *mc, unsigned int ki,
500 MDB_pageparent *mpp, MDB_node *leaf);
501 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
503 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
504 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
505 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
506 MDB_pageparent *src, indx_t srcindx,
507 MDB_pageparent *dst, indx_t dstindx);
508 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
509 MDB_pageparent *dst);
510 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
511 unsigned int *newindxp, MDB_val *newkey,
512 MDB_val *newdata, pgno_t newpgno);
513 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
515 static void cursor_pop_page(MDB_cursor *cursor);
516 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
519 static int mdb_sibling(MDB_cursor *cursor, int move_right);
520 static int mdb_cursor_next(MDB_cursor *cursor,
521 MDB_val *key, MDB_val *data, MDB_cursor_op op);
522 static int mdb_cursor_prev(MDB_cursor *cursor,
523 MDB_val *key, MDB_val *data, MDB_cursor_op op);
524 static int mdb_cursor_set(MDB_cursor *cursor,
525 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
526 static int mdb_cursor_first(MDB_cursor *cursor,
527 MDB_val *key, MDB_val *data);
528 static int mdb_cursor_last(MDB_cursor *cursor,
529 MDB_val *key, MDB_val *data);
531 static void mdb_xcursor_init0(MDB_cursor *mc);
532 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_page *mp, MDB_node *node);
533 static void mdb_xcursor_init2(MDB_cursor *mc);
534 static void mdb_xcursor_fini(MDB_cursor *mc);
536 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
538 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
540 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
542 static MDB_cmp_func memncmp, memnrcmp, intcmp, cintcmp;
545 static SECURITY_DESCRIPTOR mdb_null_sd;
546 static SECURITY_ATTRIBUTES mdb_all_sa;
547 static int mdb_sec_inited;
551 mdb_version(int *maj, int *min, int *pat)
553 if (maj) *maj = MDB_VERSION_MAJOR;
554 if (min) *min = MDB_VERSION_MINOR;
555 if (pat) *pat = MDB_VERSION_PATCH;
556 return MDB_VERSION_STRING;
559 static char *const mdb_errstr[] = {
560 "MDB_KEYEXIST: Key/data pair already exists",
561 "MDB_NOTFOUND: No matching key/data pair found",
562 "MDB_PAGE_NOTFOUND: Requested page not found",
563 "MDB_CORRUPTED: Located page was wrong type",
564 "MDB_PANIC: Update of meta page failed",
565 "MDB_VERSION_MISMATCH: Database environment version mismatch"
569 mdb_strerror(int err)
572 return ("Successful return: 0");
574 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
575 return mdb_errstr[err - MDB_KEYEXIST];
577 return strerror(err);
582 mdb_dkey(MDB_val *key, char *buf)
585 unsigned char *c = key->mv_data;
587 if (key->mv_size > MAXKEYSIZE)
590 for (i=0; i<key->mv_size; i++)
591 ptr += sprintf(ptr, "%02x", *c++);
593 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
600 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
602 return txn->mt_dbxs[dbi].md_cmp(a, b);
606 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
608 if (txn->mt_dbxs[dbi].md_dcmp)
609 return txn->mt_dbxs[dbi].md_dcmp(a, b);
611 return EINVAL; /* too bad you can't distinguish this from a valid result */
614 /* Allocate new page(s) for writing */
616 mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num)
619 pgno_t pgno = P_INVALID;
622 if (txn->mt_txnid > 2) {
624 if (!txn->mt_env->me_pghead && dbi != FREE_DBI &&
625 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
626 /* See if there's anything in the free DB */
632 mpp.mp_parent = NULL;
635 mc.mc_dbi = FREE_DBI;
638 mdb_search_page(txn, FREE_DBI, NULL, &mc, 0, &mpp);
639 leaf = NODEPTR(mpp.mp_page, 0);
640 kptr = (ULONG *)NODEKEY(leaf);
644 oldest = txn->mt_txnid - 1;
645 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
646 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
647 if (mr && mr < oldest)
652 if (oldest > *kptr) {
653 /* It's usable, grab it.
660 mdb_read_data(txn, leaf, &data);
661 idl = (ULONG *)data.mv_data;
662 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
663 mop->mo_next = txn->mt_env->me_pghead;
664 mop->mo_txnid = *kptr;
665 txn->mt_env->me_pghead = mop;
666 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
671 DPRINTF("IDL read txn %lu root %lu num %lu",
672 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
673 for (i=0; i<idl[0]; i++) {
674 DPRINTF("IDL %lu", idl[i+1]);
678 /* drop this IDL from the DB */
679 top = CURSOR_TOP(&mc);
681 mc.mc_flags = C_INITIALIZED;
682 mdb_cursor_del(&mc, 0);
685 if (txn->mt_env->me_pghead) {
686 MDB_oldpages *mop = txn->mt_env->me_pghead;
688 /* FIXME: For now, always use fresh pages. We
689 * really ought to search the free list for a
694 /* peel pages off tail, so we only have to truncate the list */
695 pgno = MDB_IDL_LAST(mop->mo_pages);
696 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
698 if (mop->mo_pages[2] > mop->mo_pages[1])
699 mop->mo_pages[0] = 0;
703 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
704 txn->mt_env->me_pghead = mop->mo_next;
711 if (pgno == P_INVALID) {
712 /* DB size is maxed out */
713 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
716 if (txn->mt_env->me_dpages && num == 1) {
717 dp = txn->mt_env->me_dpages;
718 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
720 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
724 dp->h.md_parent = parent;
725 dp->h.md_pi = parent_idx;
726 if (pgno == P_INVALID) {
727 dp->p.mp_pgno = txn->mt_next_pgno;
728 txn->mt_next_pgno += num;
730 dp->p.mp_pgno = pgno;
732 mid.mid = dp->p.mp_pgno;
734 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
739 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
742 mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *pp)
744 MDB_page *mp = pp->mp_page;
749 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
751 if ((dp = mdb_alloc_page(txn, dbi, pp->mp_parent, pp->mp_pi, 1)) == NULL)
753 DPRINTF("touched db %u page %lu -> %lu", dbi, mp->mp_pgno, dp->p.mp_pgno);
754 assert(mp->mp_pgno != dp->p.mp_pgno);
755 mdb_midl_append(txn->mt_free_pgs, mp->mp_pgno);
756 pgno = dp->p.mp_pgno;
757 memcpy(&dp->p, mp, txn->mt_env->me_psize);
760 mp->mp_flags |= P_DIRTY;
762 /* Update the page number to new touched page. */
763 if (pp->mp_parent != NULL)
764 SETPGNO(NODEPTR(pp->mp_parent, pp->mp_pi), mp->mp_pgno);
771 mdb_env_sync(MDB_env *env, int force)
774 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
775 if (fdatasync(env->me_fd))
782 mdb_txn_reset0(MDB_txn *txn);
785 mdb_txn_renew0(MDB_txn *txn)
787 MDB_env *env = txn->mt_env;
789 if (txn->mt_flags & MDB_TXN_RDONLY) {
790 MDB_reader *r = pthread_getspecific(env->me_txkey);
793 pid_t pid = getpid();
794 pthread_t tid = pthread_self();
797 for (i=0; i<env->me_txns->mti_numreaders; i++)
798 if (env->me_txns->mti_readers[i].mr_pid == 0)
800 if (i == env->me_maxreaders) {
804 env->me_txns->mti_readers[i].mr_pid = pid;
805 env->me_txns->mti_readers[i].mr_tid = tid;
806 if (i >= env->me_txns->mti_numreaders)
807 env->me_txns->mti_numreaders = i+1;
809 r = &env->me_txns->mti_readers[i];
810 pthread_setspecific(env->me_txkey, r);
812 txn->mt_txnid = env->me_txns->mti_txnid;
813 txn->mt_toggle = env->me_txns->mti_me_toggle;
814 r->mr_txnid = txn->mt_txnid;
815 txn->mt_u.reader = r;
819 txn->mt_txnid = env->me_txns->mti_txnid+1;
820 txn->mt_toggle = env->me_txns->mti_me_toggle;
821 txn->mt_u.dirty_list = env->me_dirty_list;
822 txn->mt_u.dirty_list[0].mid = 0;
823 txn->mt_free_pgs = env->me_free_pgs;
824 txn->mt_free_pgs[0] = 0;
825 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
829 /* Copy the DB arrays */
830 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
831 txn->mt_numdbs = env->me_numdbs;
832 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
833 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
834 if (txn->mt_numdbs > 2)
835 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
836 (txn->mt_numdbs - 2) * sizeof(MDB_db));
837 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
843 mdb_txn_renew(MDB_txn *txn)
850 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
851 DPUTS("environment had fatal error, must shutdown!");
855 rc = mdb_txn_renew0(txn);
856 if (rc == MDB_SUCCESS) {
857 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
858 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
859 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
865 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
870 if (env->me_flags & MDB_FATAL_ERROR) {
871 DPUTS("environment had fatal error, must shutdown!");
874 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
875 DPRINTF("calloc: %s", strerror(ErrCode()));
878 txn->mt_dbs = (MDB_db *)(txn+1);
879 if (flags & MDB_RDONLY) {
880 txn->mt_flags |= MDB_TXN_RDONLY;
884 rc = mdb_txn_renew0(txn);
889 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
890 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
891 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
898 mdb_txn_reset0(MDB_txn *txn)
900 MDB_env *env = txn->mt_env;
902 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
903 txn->mt_u.reader->mr_txnid = 0;
909 /* return all dirty pages to dpage list */
910 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
911 dp = txn->mt_u.dirty_list[i].mptr;
912 if (dp->h.md_num == 1) {
913 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
914 txn->mt_env->me_dpages = dp;
916 /* large pages just get freed directly */
921 while ((mop = txn->mt_env->me_pghead)) {
922 txn->mt_env->me_pghead = mop->mo_next;
927 for (i=2; i<env->me_numdbs; i++)
928 env->me_dbxs[i].md_dirty = 0;
934 mdb_txn_reset(MDB_txn *txn)
939 DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
940 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
941 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
947 mdb_txn_abort(MDB_txn *txn)
952 DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
953 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
954 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
961 mdb_txn_commit(MDB_txn *txn)
973 assert(txn->mt_env != NULL);
977 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
982 if (txn != env->me_txn) {
983 DPUTS("attempt to commit unknown transaction");
988 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
989 DPUTS("error flag is set, can't commit");
994 if (!txn->mt_u.dirty_list[0].mid)
997 DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
998 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1001 mc.mc_dbi = FREE_DBI;
1004 /* should only be one record now */
1005 if (env->me_pghead) {
1008 /* make sure first page of freeDB is touched and on freelist */
1009 mpp.mp_parent = NULL;
1012 mdb_search_page(txn, FREE_DBI, NULL, &mc, 1, &mpp);
1014 /* save to free list */
1015 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1020 /* make sure last page of freeDB is touched and on freelist */
1021 key.mv_size = MAXKEYSIZE+1;
1023 mpp.mp_parent = NULL;
1026 mdb_search_page(txn, FREE_DBI, &key, &mc, 1, &mpp);
1028 mdb_midl_sort(txn->mt_free_pgs);
1032 ULONG *idl = txn->mt_free_pgs;
1033 DPRINTF("IDL write txn %lu root %lu num %lu",
1034 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1035 for (i=0; i<idl[0]; i++) {
1036 DPRINTF("IDL %lu", idl[i+1]);
1040 /* write to last page of freeDB */
1041 key.mv_size = sizeof(pgno_t);
1042 key.mv_data = (char *)&txn->mt_txnid;
1043 data.mv_data = txn->mt_free_pgs;
1044 /* The free list can still grow during this call,
1045 * despite the pre-emptive touches above. So check
1046 * and make sure the entire thing got written.
1049 i = txn->mt_free_pgs[0];
1050 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1051 rc = mdb_cursor_put(&mc, &key, &data, 0);
1056 } while (i != txn->mt_free_pgs[0]);
1058 /* should only be one record now */
1059 if (env->me_pghead) {
1063 mop = env->me_pghead;
1064 key.mv_size = sizeof(pgno_t);
1065 key.mv_data = (char *)&mop->mo_txnid;
1066 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1067 data.mv_data = mop->mo_pages;
1068 mdb_cursor_put(&mc, &key, &data, 0);
1069 free(env->me_pghead);
1070 env->me_pghead = NULL;
1073 /* Update DB root pointers. Their pages have already been
1074 * touched so this is all in-place and cannot fail.
1078 data.mv_size = sizeof(MDB_db);
1080 mc.mc_dbi = MAIN_DBI;
1082 for (i = 2; i < txn->mt_numdbs; i++) {
1083 if (txn->mt_dbxs[i].md_dirty) {
1084 data.mv_data = &txn->mt_dbs[i];
1085 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1090 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1096 /* Windows actually supports scatter/gather I/O, but only on
1097 * unbuffered file handles. Since we're relying on the OS page
1098 * cache for all our data, that's self-defeating. So we just
1099 * write pages one at a time. We use the ov structure to set
1100 * the write offset, to at least save the overhead of a Seek
1104 memset(&ov, 0, sizeof(ov));
1105 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1106 dp = txn->mt_u.dirty_list[i].mptr;
1107 DPRINTF("committing page %lu", dp->p.mp_pgno);
1108 size = dp->p.mp_pgno * env->me_psize;
1109 ov.Offset = size & 0xffffffff;
1110 ov.OffsetHigh = size >> 16;
1111 ov.OffsetHigh >>= 16;
1112 /* clear dirty flag */
1113 dp->p.mp_flags &= ~P_DIRTY;
1114 rc = WriteFile(env->me_fd, &dp->p, env->me_psize * dp->h.md_num, NULL, &ov);
1117 DPRINTF("WriteFile: %d", n);
1124 struct iovec iov[MDB_COMMIT_PAGES];
1128 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1129 dp = txn->mt_u.dirty_list[i].mptr;
1130 if (dp->p.mp_pgno != next) {
1132 DPRINTF("committing %u dirty pages", n);
1133 rc = writev(env->me_fd, iov, n);
1137 DPUTS("short write, filesystem full?");
1139 DPRINTF("writev: %s", strerror(n));
1146 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1147 next = dp->p.mp_pgno;
1149 DPRINTF("committing page %lu", dp->p.mp_pgno);
1150 iov[n].iov_len = env->me_psize * dp->h.md_num;
1151 iov[n].iov_base = &dp->p;
1152 size += iov[n].iov_len;
1153 next = dp->p.mp_pgno + dp->h.md_num;
1154 /* clear dirty flag */
1155 dp->p.mp_flags &= ~P_DIRTY;
1156 if (++n >= MDB_COMMIT_PAGES) {
1166 DPRINTF("committing %u dirty pages", n);
1167 rc = writev(env->me_fd, iov, n);
1171 DPUTS("short write, filesystem full?");
1173 DPRINTF("writev: %s", strerror(n));
1180 /* Drop the dirty pages.
1182 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1183 dp = txn->mt_u.dirty_list[i].mptr;
1184 if (dp->h.md_num == 1) {
1185 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1186 txn->mt_env->me_dpages = dp;
1190 txn->mt_u.dirty_list[i].mid = 0;
1192 txn->mt_u.dirty_list[0].mid = 0;
1194 if ((n = mdb_env_sync(env, 0)) != 0 ||
1195 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1202 /* update the DB tables */
1204 int toggle = !env->me_db_toggle;
1207 ip = &env->me_dbs[toggle][2];
1208 jp = &txn->mt_dbs[2];
1209 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1210 for (i = 2; i < txn->mt_numdbs; i++) {
1211 if (ip->md_root != jp->md_root)
1216 for (i = 2; i < txn->mt_numdbs; i++) {
1217 if (txn->mt_dbxs[i].md_dirty)
1218 txn->mt_dbxs[i].md_dirty = 0;
1220 env->me_db_toggle = toggle;
1221 env->me_numdbs = txn->mt_numdbs;
1222 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1225 UNLOCK_MUTEX_W(env);
1232 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1234 char page[PAGESIZE];
1239 /* We don't know the page size yet, so use a minimum value.
1243 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1245 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1250 else if (rc != PAGESIZE) {
1254 DPRINTF("read: %s", strerror(err));
1258 p = (MDB_page *)page;
1260 if (!F_ISSET(p->mp_flags, P_META)) {
1261 DPRINTF("page %lu not a meta page", p->mp_pgno);
1266 if (m->mm_magic != MDB_MAGIC) {
1267 DPUTS("meta has invalid magic");
1271 if (m->mm_version != MDB_VERSION) {
1272 DPRINTF("database is version %u, expected version %u",
1273 m->mm_version, MDB_VERSION);
1274 return MDB_VERSION_MISMATCH;
1277 memcpy(meta, m, sizeof(*m));
1282 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1289 DPUTS("writing new meta page");
1293 meta->mm_magic = MDB_MAGIC;
1294 meta->mm_version = MDB_VERSION;
1295 meta->mm_psize = psize;
1296 meta->mm_last_pg = 1;
1297 meta->mm_flags = env->me_flags & 0xffff;
1298 meta->mm_flags |= MDB_INTEGERKEY;
1299 meta->mm_dbs[0].md_root = P_INVALID;
1300 meta->mm_dbs[1].md_root = P_INVALID;
1302 p = calloc(2, psize);
1304 p->mp_flags = P_META;
1307 memcpy(m, meta, sizeof(*meta));
1309 q = (MDB_page *)((char *)p + psize);
1312 q->mp_flags = P_META;
1315 memcpy(m, meta, sizeof(*meta));
1320 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1321 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1324 rc = write(env->me_fd, p, psize * 2);
1325 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1332 mdb_env_write_meta(MDB_txn *txn)
1335 MDB_meta meta, metab;
1337 int rc, len, toggle;
1343 assert(txn != NULL);
1344 assert(txn->mt_env != NULL);
1346 toggle = !txn->mt_toggle;
1347 DPRINTF("writing meta page %d for root page %lu",
1348 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1352 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1353 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1355 ptr = (char *)&meta;
1356 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1357 len = sizeof(MDB_meta) - off;
1360 meta.mm_dbs[0] = txn->mt_dbs[0];
1361 meta.mm_dbs[1] = txn->mt_dbs[1];
1362 meta.mm_last_pg = txn->mt_next_pgno - 1;
1363 meta.mm_txnid = txn->mt_txnid;
1366 off += env->me_psize;
1369 /* Write to the SYNC fd */
1372 memset(&ov, 0, sizeof(ov));
1374 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1377 rc = pwrite(env->me_mfd, ptr, len, off);
1382 DPUTS("write failed, disk error?");
1383 /* On a failure, the pagecache still contains the new data.
1384 * Write some old data back, to prevent it from being used.
1385 * Use the non-SYNC fd; we know it will fail anyway.
1387 meta.mm_last_pg = metab.mm_last_pg;
1388 meta.mm_txnid = metab.mm_txnid;
1390 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1392 r2 = pwrite(env->me_fd, ptr, len, off);
1394 env->me_flags |= MDB_FATAL_ERROR;
1397 /* Memory ordering issues are irrelevant; since the entire writer
1398 * is wrapped by wmutex, all of these changes will become visible
1399 * after the wmutex is unlocked. Since the DB is multi-version,
1400 * readers will get consistent data regardless of how fresh or
1401 * how stale their view of these values is.
1403 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1404 txn->mt_env->me_txns->mti_me_toggle = toggle;
1405 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1406 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1412 mdb_env_read_meta(MDB_env *env, int *which)
1416 assert(env != NULL);
1418 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1421 DPRINTF("Using meta page %d", toggle);
1428 mdb_env_create(MDB_env **env)
1432 e = calloc(1, sizeof(MDB_env));
1433 if (!e) return ENOMEM;
1435 e->me_maxreaders = DEFAULT_READERS;
1437 e->me_fd = INVALID_HANDLE_VALUE;
1438 e->me_lfd = INVALID_HANDLE_VALUE;
1439 e->me_mfd = INVALID_HANDLE_VALUE;
1445 mdb_env_set_mapsize(MDB_env *env, size_t size)
1449 env->me_mapsize = size;
1454 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1458 env->me_maxdbs = dbs;
1463 mdb_env_set_maxreaders(MDB_env *env, int readers)
1467 env->me_maxreaders = readers;
1472 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1474 if (!env || !readers)
1476 *readers = env->me_maxreaders;
1481 mdb_env_open2(MDB_env *env, unsigned int flags)
1483 int i, newenv = 0, toggle;
1487 env->me_flags = flags;
1489 memset(&meta, 0, sizeof(meta));
1491 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1494 DPUTS("new mdbenv");
1498 if (!env->me_mapsize) {
1499 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1505 LONG sizelo, sizehi;
1506 sizelo = env->me_mapsize & 0xffffffff;
1507 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1509 /* Windows won't create mappings for zero length files.
1510 * Just allocate the maxsize right now.
1513 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1514 if (!SetEndOfFile(env->me_fd))
1516 SetFilePointer(env->me_fd, 0, NULL, 0);
1518 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1519 sizehi, sizelo, NULL);
1522 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1530 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1532 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1534 if (env->me_map == MAP_FAILED)
1539 meta.mm_mapsize = env->me_mapsize;
1540 if (flags & MDB_FIXEDMAP)
1541 meta.mm_address = env->me_map;
1542 i = mdb_env_init_meta(env, &meta);
1543 if (i != MDB_SUCCESS) {
1544 munmap(env->me_map, env->me_mapsize);
1548 env->me_psize = meta.mm_psize;
1550 env->me_maxpg = env->me_mapsize / env->me_psize;
1552 p = (MDB_page *)env->me_map;
1553 env->me_metas[0] = METADATA(p);
1554 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1556 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1559 DPRINTF("opened database version %u, pagesize %u",
1560 env->me_metas[toggle]->mm_version, env->me_psize);
1561 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1562 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1563 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1564 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1565 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1566 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1572 /* Windows doesn't support destructor callbacks for thread-specific storage */
1574 mdb_env_reader_dest(void *ptr)
1576 MDB_reader *reader = ptr;
1578 reader->mr_txnid = 0;
1584 /* downgrade the exclusive lock on the region back to shared */
1586 mdb_env_share_locks(MDB_env *env)
1590 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1592 env->me_txns->mti_me_toggle = toggle;
1593 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1598 /* First acquire a shared lock. The Unlock will
1599 * then release the existing exclusive lock.
1601 memset(&ov, 0, sizeof(ov));
1602 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1603 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1607 struct flock lock_info;
1608 /* The shared lock replaces the existing lock */
1609 memset((void *)&lock_info, 0, sizeof(lock_info));
1610 lock_info.l_type = F_RDLCK;
1611 lock_info.l_whence = SEEK_SET;
1612 lock_info.l_start = 0;
1613 lock_info.l_len = 1;
1614 fcntl(env->me_lfd, F_SETLK, &lock_info);
1620 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1628 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1629 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1630 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1634 /* Try to get exclusive lock. If we succeed, then
1635 * nobody is using the lock region and we should initialize it.
1638 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1642 memset(&ov, 0, sizeof(ov));
1643 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
1649 size = GetFileSize(env->me_lfd, NULL);
1651 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1655 /* Try to get exclusive lock. If we succeed, then
1656 * nobody is using the lock region and we should initialize it.
1659 struct flock lock_info;
1660 memset((void *)&lock_info, 0, sizeof(lock_info));
1661 lock_info.l_type = F_WRLCK;
1662 lock_info.l_whence = SEEK_SET;
1663 lock_info.l_start = 0;
1664 lock_info.l_len = 1;
1665 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1669 lock_info.l_type = F_RDLCK;
1670 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
1677 size = lseek(env->me_lfd, 0, SEEK_END);
1679 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1680 if (size < rsize && *excl) {
1682 SetFilePointer(env->me_lfd, rsize, NULL, 0);
1683 if (!SetEndOfFile(env->me_lfd)) {
1688 if (ftruncate(env->me_lfd, rsize) != 0) {
1695 size = rsize - sizeof(MDB_txninfo);
1696 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1701 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
1707 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
1709 if (!env->me_txns) {
1715 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1717 if (env->me_txns == MAP_FAILED) {
1725 if (!mdb_sec_inited) {
1726 InitializeSecurityDescriptor(&mdb_null_sd,
1727 SECURITY_DESCRIPTOR_REVISION);
1728 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
1729 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1730 mdb_all_sa.bInheritHandle = FALSE;
1731 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
1734 /* FIXME: only using up to 20 characters of the env path here,
1735 * probably not enough to assure uniqueness...
1737 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
1738 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
1739 while ((ptr = strchr(ptr, '\\')))
1741 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1742 if (!env->me_rmutex) {
1746 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
1747 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
1748 while ((ptr = strchr(ptr, '\\')))
1750 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1751 if (!env->me_wmutex) {
1756 pthread_mutexattr_t mattr;
1758 pthread_mutexattr_init(&mattr);
1759 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1763 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1764 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1766 env->me_txns->mti_version = MDB_VERSION;
1767 env->me_txns->mti_magic = MDB_MAGIC;
1768 env->me_txns->mti_txnid = 0;
1769 env->me_txns->mti_numreaders = 0;
1770 env->me_txns->mti_me_toggle = 0;
1773 if (env->me_txns->mti_magic != MDB_MAGIC) {
1774 DPUTS("lock region has invalid magic");
1778 if (env->me_txns->mti_version != MDB_VERSION) {
1779 DPRINTF("lock region is version %u, expected version %u",
1780 env->me_txns->mti_version, MDB_VERSION);
1781 rc = MDB_VERSION_MISMATCH;
1785 if (rc != EACCES && rc != EAGAIN) {
1789 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
1790 if (!env->me_rmutex) {
1794 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
1795 if (!env->me_wmutex) {
1805 env->me_lfd = INVALID_HANDLE_VALUE;
1810 #define LOCKNAME "/lock.mdb"
1811 #define DATANAME "/data.mdb"
1813 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1815 int oflags, rc, len, excl;
1816 char *lpath, *dpath;
1819 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1822 dpath = lpath + len + sizeof(LOCKNAME);
1823 sprintf(lpath, "%s" LOCKNAME, path);
1824 sprintf(dpath, "%s" DATANAME, path);
1826 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1831 if (F_ISSET(flags, MDB_RDONLY)) {
1832 oflags = GENERIC_READ;
1833 len = OPEN_EXISTING;
1835 oflags = GENERIC_READ|GENERIC_WRITE;
1838 mode = FILE_ATTRIBUTE_NORMAL;
1839 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1840 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1845 if (F_ISSET(flags, MDB_RDONLY))
1848 oflags = O_RDWR | O_CREAT;
1850 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1856 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1857 /* synchronous fd for meta writes */
1859 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1860 mode |= FILE_FLAG_WRITE_THROUGH;
1861 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1862 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1867 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1868 oflags |= MDB_DSYNC;
1869 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1874 env->me_path = strdup(path);
1875 DPRINTF("opened dbenv %p", (void *) env);
1876 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1877 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1879 mdb_env_share_locks(env);
1880 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1881 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1882 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1888 if (env->me_fd != INVALID_HANDLE_VALUE) {
1890 env->me_fd = INVALID_HANDLE_VALUE;
1892 if (env->me_lfd != INVALID_HANDLE_VALUE) {
1894 env->me_lfd = INVALID_HANDLE_VALUE;
1902 mdb_env_close(MDB_env *env)
1909 while (env->me_dpages) {
1910 dp = env->me_dpages;
1911 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1915 free(env->me_dbs[1]);
1916 free(env->me_dbs[0]);
1920 LAZY_RWLOCK_DESTROY(&env->me_dblock);
1921 pthread_key_delete(env->me_txkey);
1924 munmap(env->me_map, env->me_mapsize);
1929 pid_t pid = getpid();
1931 for (i=0; i<env->me_txns->mti_numreaders; i++)
1932 if (env->me_txns->mti_readers[i].mr_pid == pid)
1933 env->me_txns->mti_readers[i].mr_pid = 0;
1934 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
1940 /* only for aligned ints */
1942 intcmp(const MDB_val *a, const MDB_val *b)
1944 if (a->mv_size == sizeof(long))
1946 unsigned long *la, *lb;
1951 unsigned int *ia, *ib;
1958 /* ints must always be the same size */
1960 cintcmp(const MDB_val *a, const MDB_val *b)
1962 #if __BYTE_ORDER == __LITTLE_ENDIAN
1963 unsigned char *u, *c;
1966 u = a->mv_data + a->mv_size;
1967 c = b->mv_data + a->mv_size;
1968 while(u > (unsigned char *)a->mv_data) {
1974 return memcmp(a->mv_data, b->mv_data, a->mv_size);
1979 memncmp(const MDB_val *a, const MDB_val *b)
1985 len_diff = a->mv_size - b->mv_size;
1988 diff = memcmp(a->mv_data, b->mv_data, len);
1989 return diff ? diff : len_diff;
1993 memnrcmp(const MDB_val *a, const MDB_val *b)
1995 const unsigned char *p1, *p2, *p1_lim;
1998 if (b->mv_size == 0)
1999 return a->mv_size != 0;
2000 if (a->mv_size == 0)
2003 p1 = (const unsigned char *)a->mv_data + a->mv_size - 1;
2004 p2 = (const unsigned char *)b->mv_data + b->mv_size - 1;
2006 len_diff = a->mv_size - b->mv_size;
2008 p1_lim = p1 - a->mv_size;
2010 p1_lim = p1 - b->mv_size;
2012 while (p1 > p1_lim) {
2022 /* Search for key within a leaf page, using binary search.
2023 * Returns the smallest entry larger or equal to the key.
2024 * If exactp is non-null, stores whether the found entry was an exact match
2025 * in *exactp (1 or 0).
2026 * If kip is non-null, stores the index of the found entry in *kip.
2027 * If no entry larger or equal to the key is found, returns NULL.
2030 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
2031 int *exactp, unsigned int *kip)
2033 unsigned int i = 0, nkeys;
2036 MDB_node *node = NULL;
2041 nkeys = NUMKEYS(mp);
2043 DPRINTF("searching %u keys in %s page %lu",
2044 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2049 low = IS_LEAF(mp) ? 0 : 1;
2051 cmp = txn->mt_dbxs[dbi].md_cmp;
2053 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
2054 node = NODEPTR(mp, 0); /* fake */
2056 while (low <= high) {
2057 i = (low + high) >> 1;
2060 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2062 node = NODEPTR(mp, i);
2064 nodekey.mv_size = node->mn_ksize;
2065 nodekey.mv_data = NODEKEY(node);
2068 rc = cmp(key, &nodekey);
2072 DPRINTF("found leaf index %u [%s], rc = %i",
2073 i, DKEY(&nodekey), rc);
2075 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2076 i, DKEY(&nodekey), NODEPGNO(node), rc);
2087 if (rc > 0) { /* Found entry is less than the key. */
2088 i++; /* Skip to get the smallest entry larger than key. */
2090 node = NODEPTR(mp, i);
2093 *exactp = (rc == 0);
2094 if (kip) /* Store the key index if requested. */
2097 /* There is no entry larger or equal to the key. */
2100 /* nodeptr is fake for LEAF2 */
2105 cursor_pop_page(MDB_cursor *cursor)
2109 if (cursor->mc_snum) {
2110 top = CURSOR_TOP(cursor);
2113 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
2114 cursor->mc_dbi, (void *) cursor);
2119 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
2123 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2124 cursor->mc_dbi, (void *) cursor);
2126 assert(cursor->mc_snum < CURSOR_STACK);
2128 ppage = &cursor->mc_stack[cursor->mc_snum++];
2129 ppage->mp_page = mp;
2135 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2139 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2142 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2143 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2144 dp = txn->mt_u.dirty_list[x].mptr;
2149 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2150 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2154 DPRINTF("page %lu not found", pgno);
2157 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2161 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2162 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2164 MDB_page *mp = mpp->mp_page;
2168 if (cursor && cursor_push_page(cursor, mp) == NULL)
2171 while (IS_BRANCH(mp)) {
2175 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2176 assert(NUMKEYS(mp) > 1);
2177 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2179 if (key == NULL) /* Initialize cursor to first page. */
2181 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2182 /* cursor to last page */
2186 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
2188 i = NUMKEYS(mp) - 1;
2196 DPRINTF("following index %u for key [%s]",
2198 assert(i < NUMKEYS(mp));
2199 node = NODEPTR(mp, i);
2202 CURSOR_TOP(cursor)->mp_ki = i;
2204 mpp->mp_parent = mp;
2205 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
2210 if (cursor && cursor_push_page(cursor, mp) == NULL)
2215 if ((rc = mdb_touch(txn, dbi, mpp)) != 0)
2217 dh = ((MDB_dhead *)mpp->mp_page)-1;
2218 dh->md_parent = mpp->mp_parent;
2219 dh->md_pi = mpp->mp_pi;
2226 DPRINTF("internal error, index points to a %02X page!?",
2228 return MDB_CORRUPTED;
2231 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2232 key ? DKEY(key) : NULL);
2237 /* Search for the page a given key should be in.
2238 * Stores a pointer to the found page in *mpp.
2239 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2240 * If cursor is non-null, pushes parent pages on the cursor stack.
2241 * If modify is true, visited pages are updated with new page numbers.
2244 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2245 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2250 /* Choose which root page to start with. If a transaction is given
2251 * use the root page from the transaction, otherwise read the last
2252 * committed root page.
2254 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2255 DPUTS("transaction has failed, must abort");
2258 root = txn->mt_dbs[dbi].md_root;
2260 if (root == P_INVALID) { /* Tree is empty. */
2261 DPUTS("tree is empty");
2262 return MDB_NOTFOUND;
2265 if ((rc = mdb_get_page(txn, root, &mpp->mp_page)))
2268 DPRINTF("db %u root page %lu has flags 0x%X",
2269 dbi, root, mpp->mp_page->mp_flags);
2272 /* For sub-databases, update main root first */
2273 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
2275 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
2279 txn->mt_dbxs[dbi].md_dirty = 1;
2281 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
2282 mpp->mp_parent = NULL;
2284 if ((rc = mdb_touch(txn, dbi, mpp)))
2286 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
2290 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
2294 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2296 MDB_page *omp; /* overflow mpage */
2300 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2301 data->mv_size = NODEDSZ(leaf);
2302 data->mv_data = NODEDATA(leaf);
2306 /* Read overflow data.
2308 data->mv_size = NODEDSZ(leaf);
2309 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2310 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2311 DPRINTF("read overflow page %lu failed", pgno);
2314 data->mv_data = METADATA(omp);
2320 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2321 MDB_val *key, MDB_val *data)
2330 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2332 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2335 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2342 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2343 mc.mc_xcursor = &mx;
2344 mdb_xcursor_init0(&mc);
2346 mc.mc_xcursor = NULL;
2348 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2352 mdb_sibling(MDB_cursor *cursor, int move_right)
2359 if (cursor->mc_snum < 2) {
2360 return MDB_NOTFOUND; /* root has no siblings */
2362 parent = CURSOR_PARENT(cursor);
2364 DPRINTF("parent page is page %lu, index %u",
2365 parent->mp_page->mp_pgno, parent->mp_ki);
2367 cursor_pop_page(cursor);
2368 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
2369 : (parent->mp_ki == 0)) {
2370 DPRINTF("no more keys left, moving to %s sibling",
2371 move_right ? "right" : "left");
2372 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2374 parent = CURSOR_TOP(cursor);
2380 DPRINTF("just moving to %s index key %u",
2381 move_right ? "right" : "left", parent->mp_ki);
2383 assert(IS_BRANCH(parent->mp_page));
2385 indx = NODEPTR(parent->mp_page, parent->mp_ki);
2386 if ((rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp)))
2389 mp->parent = parent->mp_page;
2390 mp->parent_index = parent->mp_ki;
2393 cursor_push_page(cursor, mp);
2399 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2406 if (cursor->mc_flags & C_EOF) {
2407 return MDB_NOTFOUND;
2410 assert(cursor->mc_flags & C_INITIALIZED);
2412 top = CURSOR_TOP(cursor);
2415 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2416 leaf = NODEPTR(mp, top->mp_ki);
2417 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2418 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2419 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2420 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2424 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2425 if (op == MDB_NEXT_DUP)
2426 return MDB_NOTFOUND;
2430 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2432 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2433 DPUTS("=====> move to next sibling page");
2434 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2435 cursor->mc_flags |= C_EOF;
2436 return MDB_NOTFOUND;
2438 top = CURSOR_TOP(cursor);
2440 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2444 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2445 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2448 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2449 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2453 assert(IS_LEAF(mp));
2454 leaf = NODEPTR(mp, top->mp_ki);
2456 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2457 mdb_xcursor_init1(cursor, mp, leaf);
2460 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2463 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2464 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2465 if (rc != MDB_SUCCESS)
2470 MDB_SET_KEY(leaf, key);
2475 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2482 assert(cursor->mc_flags & C_INITIALIZED);
2484 top = CURSOR_TOP(cursor);
2487 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2488 leaf = NODEPTR(mp, top->mp_ki);
2489 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2490 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2491 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2492 if (op != MDB_PREV || rc == MDB_SUCCESS)
2495 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2496 if (op == MDB_PREV_DUP)
2497 return MDB_NOTFOUND;
2502 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2504 if (top->mp_ki == 0) {
2505 DPUTS("=====> move to prev sibling page");
2506 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2507 cursor->mc_flags &= ~C_INITIALIZED;
2508 return MDB_NOTFOUND;
2510 top = CURSOR_TOP(cursor);
2512 top->mp_ki = NUMKEYS(mp) - 1;
2513 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2517 cursor->mc_flags &= ~C_EOF;
2519 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2520 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2523 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2524 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2528 assert(IS_LEAF(mp));
2529 leaf = NODEPTR(mp, top->mp_ki);
2531 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2532 mdb_xcursor_init1(cursor, mp, leaf);
2535 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2538 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2539 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2540 if (rc != MDB_SUCCESS)
2545 MDB_SET_KEY(leaf, key);
2550 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2551 MDB_cursor_op op, int *exactp)
2561 assert(key->mv_size > 0);
2563 /* See if we're already on the right page */
2564 if (cursor->mc_flags & C_INITIALIZED) {
2567 top = CURSOR_TOP(cursor);
2568 if (top->mp_page->mp_flags & P_LEAF2) {
2569 nodekey.mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2570 nodekey.mv_data = LEAF2KEY(top->mp_page, 0, nodekey.mv_size);
2572 leaf = NODEPTR(top->mp_page, 0);
2573 MDB_SET_KEY(leaf, &nodekey);
2575 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(key, &nodekey);
2577 /* Probably happens rarely, but first node on the page
2578 * was the one we wanted.
2582 mpp.mp_page = top->mp_page;
2586 leaf = NODEPTR(top->mp_page, top->mp_ki);
2591 if (NUMKEYS(top->mp_page) > 1) {
2592 if (top->mp_page->mp_flags & P_LEAF2) {
2593 nodekey.mv_data = LEAF2KEY(top->mp_page,
2594 NUMKEYS(top->mp_page)-1, nodekey.mv_size);
2596 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2597 MDB_SET_KEY(leaf, &nodekey);
2599 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(key, &nodekey);
2601 /* last node was the one we wanted */
2602 top->mp_ki = NUMKEYS(top->mp_page)-1;
2606 /* This is definitely the right page, skip search_page */
2607 mpp.mp_page = top->mp_page;
2612 /* If any parents have right-sibs, search.
2613 * Otherwise, there's nothing further.
2615 for (i=0; i<cursor->mc_snum-1; i++)
2616 if (cursor->mc_stack[i].mp_ki <
2617 NUMKEYS(cursor->mc_stack[i].mp_page)-1)
2619 if (i == cursor->mc_snum - 1) {
2620 /* There are no other pages */
2621 top->mp_ki = NUMKEYS(top->mp_page);
2622 return MDB_NOTFOUND;
2627 cursor->mc_snum = 0;
2629 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2630 if (rc != MDB_SUCCESS)
2633 assert(IS_LEAF(mpp.mp_page));
2635 top = CURSOR_TOP(cursor);
2637 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2638 if (exactp != NULL && !*exactp) {
2639 /* MDB_SET specified and not an exact match. */
2640 return MDB_NOTFOUND;
2644 DPUTS("===> inexact leaf not found, goto sibling");
2645 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2646 return rc; /* no entries matched */
2647 top = CURSOR_TOP(cursor);
2649 mpp.mp_page = top->mp_page;
2650 assert(IS_LEAF(mpp.mp_page));
2651 leaf = NODEPTR(mpp.mp_page, 0);
2655 cursor->mc_flags |= C_INITIALIZED;
2656 cursor->mc_flags &= ~C_EOF;
2658 if (IS_LEAF2(mpp.mp_page)) {
2659 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2660 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2664 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2665 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2668 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2669 if (op == MDB_SET || op == MDB_SET_RANGE) {
2670 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2673 if (op == MDB_GET_BOTH) {
2679 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2680 if (rc != MDB_SUCCESS)
2683 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2685 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2687 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_dcmp(data, &d2);
2689 if (op == MDB_GET_BOTH || rc > 0)
2690 return MDB_NOTFOUND;
2694 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2699 /* The key already matches in all other cases */
2700 if (op == MDB_SET_RANGE)
2701 MDB_SET_KEY(leaf, key);
2702 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2708 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2714 cursor->mc_snum = 0;
2716 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2717 if (rc != MDB_SUCCESS)
2719 assert(IS_LEAF(mpp.mp_page));
2721 leaf = NODEPTR(mpp.mp_page, 0);
2722 cursor->mc_flags |= C_INITIALIZED;
2723 cursor->mc_flags &= ~C_EOF;
2725 if (IS_LEAF2(mpp.mp_page)) {
2726 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2727 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2732 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2733 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2734 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2738 if (cursor->mc_xcursor)
2739 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2740 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2744 MDB_SET_KEY(leaf, key);
2749 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2757 cursor->mc_snum = 0;
2759 lkey.mv_size = MAXKEYSIZE+1;
2760 lkey.mv_data = NULL;
2762 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2763 if (rc != MDB_SUCCESS)
2765 assert(IS_LEAF(mpp.mp_page));
2767 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2768 cursor->mc_flags |= C_INITIALIZED;
2769 cursor->mc_flags &= ~C_EOF;
2771 top = CURSOR_TOP(cursor);
2772 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2774 if (IS_LEAF2(mpp.mp_page)) {
2775 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2776 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2781 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2782 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2783 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2787 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2792 MDB_SET_KEY(leaf, key);
2797 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2807 case MDB_GET_BOTH_RANGE:
2808 if (data == NULL || cursor->mc_xcursor == NULL) {
2815 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2817 } else if (op == MDB_SET_RANGE)
2818 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2820 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2822 case MDB_GET_MULTIPLE:
2824 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2825 !(cursor->mc_flags & C_INITIALIZED)) {
2830 if (!(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
2831 (cursor->mc_xcursor->mx_cursor.mc_flags & C_EOF))
2834 case MDB_NEXT_MULTIPLE:
2836 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2840 if (!(cursor->mc_flags & C_INITIALIZED))
2841 rc = mdb_cursor_first(cursor, key, data);
2843 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2844 if (rc == MDB_SUCCESS) {
2845 if (cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
2848 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2849 data->mv_size = NUMKEYS(top->mp_page) *
2850 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2851 data->mv_data = METADATA(top->mp_page);
2852 top->mp_ki = NUMKEYS(top->mp_page)-1;
2860 case MDB_NEXT_NODUP:
2861 if (!(cursor->mc_flags & C_INITIALIZED))
2862 rc = mdb_cursor_first(cursor, key, data);
2864 rc = mdb_cursor_next(cursor, key, data, op);
2868 case MDB_PREV_NODUP:
2869 if (!(cursor->mc_flags & C_INITIALIZED) || (cursor->mc_flags & C_EOF))
2870 rc = mdb_cursor_last(cursor, key, data);
2872 rc = mdb_cursor_prev(cursor, key, data, op);
2875 rc = mdb_cursor_first(cursor, key, data);
2879 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2880 !(cursor->mc_flags & C_INITIALIZED) ||
2881 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2885 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2888 rc = mdb_cursor_last(cursor, key, data);
2892 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2893 !(cursor->mc_flags & C_INITIALIZED) ||
2894 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2898 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2901 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2910 mdb_cursor_touch(MDB_cursor *mc)
2917 mpp.mp_parent = NULL;
2919 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2920 rc = mdb_search_page(mc->mc_txn, MAIN_DBI, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name,
2923 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2925 for(i=0; i<mc->mc_snum; i++) {
2926 mpp.mp_page = mc->mc_stack[i].mp_page;
2927 if (!F_ISSET(mpp.mp_page->mp_flags, P_DIRTY)) {
2928 rc = mdb_touch(mc->mc_txn, mc->mc_dbi, &mpp);
2930 mc->mc_stack[i].mp_page = mpp.mp_page;
2932 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mpp.mp_page->mp_pgno;
2935 dh = ((MDB_dhead *)mpp.mp_page)-1;
2936 dh->md_parent = mpp.mp_parent;
2937 dh->md_pi = mpp.mp_pi;
2938 mpp.mp_parent = mpp.mp_page;
2939 mpp.mp_pi = mc->mc_stack[i].mp_ki;
2945 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2950 MDB_val xdata, *rdata, dkey;
2952 char dbuf[PAGESIZE];
2958 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
2961 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
2962 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
2966 if (flags == MDB_CURRENT) {
2967 if (!(mc->mc_flags & C_INITIALIZED))
2970 } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
2972 /* new database, write a root leaf page */
2973 DPUTS("allocating new root leaf page");
2974 if ((dp = mdb_new_page(mc->mc_txn, mc->mc_dbi, P_LEAF, 1)) == NULL) {
2978 cursor_push_page(mc, &dp->p);
2979 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = dp->p.mp_pgno;
2980 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
2981 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2982 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
2984 dp->p.mp_flags |= P_LEAF2;
2985 mc->mc_flags |= C_INITIALIZED;
2990 rc = mdb_cursor_set(mc, key, NULL, MDB_SET, &exact);
2991 if (flags == MDB_NOOVERWRITE && rc == 0) {
2992 DPRINTF("duplicate key [%s]", DKEY(key));
2993 return MDB_KEYEXIST;
2995 if (rc && rc != MDB_NOTFOUND)
2999 /* Cursor is positioned, now make sure all pages are writable */
3000 rc2 = mdb_cursor_touch(mc);
3001 if (rc2) return rc2;
3004 top = CURSOR_TOP(mc);
3006 /* The key already exists */
3007 if (rc == MDB_SUCCESS) {
3008 /* there's only a key anyway, so this is a no-op */
3009 if (IS_LEAF2(top->mp_page)) {
3010 unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3011 if (key->mv_size != ksize)
3013 if (flags == MDB_CURRENT) {
3014 char *ptr = LEAF2KEY(top->mp_page, top->mp_ki, ksize);
3015 memcpy(ptr, key->mv_data, ksize);
3020 leaf = NODEPTR(top->mp_page, top->mp_ki);
3023 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
3024 /* Was a single item before, must convert now */
3025 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3026 dkey.mv_size = NODEDSZ(leaf);
3027 dkey.mv_data = dbuf;
3028 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3029 /* data matches, ignore it */
3030 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
3031 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3032 memset(&dummy, 0, sizeof(dummy));
3033 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
3034 dummy.md_pad = data->mv_size;
3035 dummy.md_flags = MDB_DUPFIXED;
3036 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
3037 dummy.md_flags |= MDB_INTEGERKEY;
3039 dummy.md_root = P_INVALID;
3040 if (dkey.mv_size == sizeof(MDB_db)) {
3041 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3044 mdb_del_node(top->mp_page, top->mp_ki, 0);
3047 xdata.mv_size = sizeof(MDB_db);
3048 xdata.mv_data = &dummy;
3053 /* same size, just replace it */
3054 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3055 NODEDSZ(leaf) == data->mv_size) {
3056 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3059 mdb_del_node(top->mp_page, top->mp_ki, 0);
3061 DPRINTF("inserting key at index %i", top->mp_ki);
3067 nsize = IS_LEAF2(top->mp_page) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3068 if (SIZELEFT(top->mp_page) < nsize) {
3069 rc = mdb_split(mc->mc_txn, mc->mc_dbi, &top->mp_page, &top->mp_ki, key, rdata, P_INVALID);
3071 /* There is room already in this leaf page. */
3072 rc = mdb_add_node(mc->mc_txn, mc->mc_dbi, top->mp_page, top->mp_ki, key, rdata, 0, 0);
3075 if (rc != MDB_SUCCESS)
3076 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3078 /* Remember if we just added a subdatabase */
3079 if (flags & F_SUBDATA) {
3080 leaf = NODEPTR(top->mp_page, top->mp_ki);
3081 leaf->mn_flags |= F_SUBDATA;
3084 /* Now store the actual data in the child DB. Note that we're
3085 * storing the user data in the keys field, so there are strict
3086 * size limits on dupdata. The actual data fields of the child
3087 * DB are all zero size.
3090 leaf = NODEPTR(top->mp_page, top->mp_ki);
3092 if (flags == MDB_CURRENT)
3093 mdb_xcursor_init2(mc);
3095 mdb_xcursor_init1(mc, top->mp_page, leaf);
3098 if (flags == MDB_NODUPDATA)
3099 flags = MDB_NOOVERWRITE;
3100 /* converted, write the original data first */
3102 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3104 leaf->mn_flags |= F_DUPDATA;
3106 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3107 mdb_xcursor_fini(mc);
3108 memcpy(NODEDATA(leaf),
3109 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3112 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3119 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3126 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3129 if (!mc->mc_flags & C_INITIALIZED)
3132 rc = mdb_cursor_touch(mc);
3135 top = CURSOR_TOP(mc);
3136 leaf = NODEPTR(top->mp_page, top->mp_ki);
3137 mpp.mp_page = top->mp_page;
3138 if (mc->mc_snum > 1) {
3139 MDB_ppage *parent = CURSOR_PARENT(mc);
3140 mpp.mp_parent = parent->mp_page;
3141 mpp.mp_pi = parent->mp_ki;
3143 mpp.mp_parent = NULL;
3147 if (!IS_LEAF2(top->mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3150 if (flags != MDB_NODUPDATA) {
3151 mdb_xcursor_init2(mc);
3152 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3153 mdb_xcursor_fini(mc);
3154 /* If sub-DB still has entries, we're done */
3155 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3157 memcpy(NODEDATA(leaf),
3158 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3160 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3163 /* otherwise fall thru and delete the sub-DB */
3166 /* add all the child DB's pages to the free list */
3167 mc->mc_xcursor->mx_cursor.mc_snum = 0;
3168 rc = mdb_search_page(&mc->mc_xcursor->mx_txn, mc->mc_xcursor->mx_cursor.mc_dbi,
3169 NULL, &mc->mc_xcursor->mx_cursor, 0, &mp2);
3170 if (rc == MDB_SUCCESS) {
3171 MDB_ppage *top, *parent;
3180 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3181 mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3183 cursor_pop_page(&mc->mc_xcursor->mx_cursor);
3184 if (mc->mc_xcursor->mx_cursor.mc_snum) {
3186 if (mc->mc_xcursor->mx_cursor.mc_stack[0].mp_page->mp_flags & P_DIRTY) {
3190 while (mc->mc_xcursor->mx_cursor.mc_snum > 1) {
3191 top = CURSOR_TOP(&mc->mc_xcursor->mx_cursor);
3192 parent = CURSOR_PARENT(&mc->mc_xcursor->mx_cursor);
3193 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3196 ni = NODEPTR(top->mp_page, i);
3198 if ((rc = mdb_get_page(mc->mc_txn, pg, &mp)))
3201 if (mp->mp_flags & P_DIRTY) {
3204 mdb_mid2l_delete(mc->mc_txn->mt_u.dirty_list, &mid);
3206 dp->h.md_parent = (MDB_page *)mc->mc_txn->mt_env->me_dpages;
3207 mc->mc_txn->mt_env->me_dpages = dp;
3212 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3215 rc = mdb_sibling(&mc->mc_xcursor->mx_cursor, 1);
3222 mid.mid = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root;
3223 mdb_mid2l_delete(mc->mc_txn->mt_u.dirty_list, &mid);
3225 dp->h.md_parent = (MDB_page *)mc->mc_txn->mt_env->me_dpages;
3226 mc->mc_txn->mt_env->me_dpages = dp;
3231 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3232 mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root);
3237 return mdb_del0(mc, top->mp_ki, &mpp, leaf);
3240 /* Allocate a page and initialize it
3243 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
3247 if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
3249 DPRINTF("allocated new mpage %lu, page size %u",
3250 dp->p.mp_pgno, txn->mt_env->me_psize);
3251 dp->p.mp_flags = flags | P_DIRTY;
3252 dp->p.mp_lower = PAGEHDRSZ;
3253 dp->p.mp_upper = txn->mt_env->me_psize;
3255 if (IS_BRANCH(&dp->p))
3256 txn->mt_dbs[dbi].md_branch_pages++;
3257 else if (IS_LEAF(&dp->p))
3258 txn->mt_dbs[dbi].md_leaf_pages++;
3259 else if (IS_OVERFLOW(&dp->p)) {
3260 txn->mt_dbs[dbi].md_overflow_pages += num;
3261 dp->p.mp_pages = num;
3268 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3272 sz = LEAFSIZE(key, data);
3273 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3274 /* put on overflow page */
3275 sz -= data->mv_size - sizeof(pgno_t);
3279 return sz + sizeof(indx_t);
3283 mdb_branch_size(MDB_env *env, MDB_val *key)
3288 if (sz >= env->me_psize / MDB_MINKEYS) {
3289 /* put on overflow page */
3290 /* not implemented */
3291 /* sz -= key->size - sizeof(pgno_t); */
3294 return sz + sizeof(indx_t);
3298 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
3299 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3302 size_t node_size = NODESIZE;
3305 MDB_dpage *ofp = NULL; /* overflow page */
3308 assert(mp->mp_upper >= mp->mp_lower);
3310 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
3311 IS_LEAF(mp) ? "leaf" : "branch",
3312 mp->mp_pgno, indx, data ? data->mv_size : 0,
3313 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3316 /* Move higher keys up one slot. */
3317 int ksize = txn->mt_dbs[dbi].md_pad, dif;
3318 char *ptr = LEAF2KEY(mp, indx, ksize);
3319 dif = NUMKEYS(mp) - indx;
3321 memmove(ptr+ksize, ptr, dif*ksize);
3322 /* insert new key */
3323 memcpy(ptr, key->mv_data, ksize);
3325 /* Just using these for counting */
3326 mp->mp_lower += sizeof(indx_t);
3327 mp->mp_upper -= ksize - sizeof(indx_t);
3332 node_size += key->mv_size;
3336 if (F_ISSET(flags, F_BIGDATA)) {
3337 /* Data already on overflow page. */
3338 node_size += sizeof(pgno_t);
3339 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
3340 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
3341 /* Put data on overflow page. */
3342 DPRINTF("data size is %zu, put on overflow page",
3344 node_size += sizeof(pgno_t);
3345 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
3347 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
3350 node_size += data->mv_size;
3353 node_size += node_size & 1;
3355 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3356 DPRINTF("not enough room in page %lu, got %u ptrs",
3357 mp->mp_pgno, NUMKEYS(mp));
3358 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3359 mp->mp_upper - mp->mp_lower);
3360 DPRINTF("node size = %zu", node_size);
3364 /* Move higher pointers up one slot. */
3365 for (i = NUMKEYS(mp); i > indx; i--)
3366 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3368 /* Adjust free space offsets. */
3369 ofs = mp->mp_upper - node_size;
3370 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3371 mp->mp_ptrs[indx] = ofs;
3373 mp->mp_lower += sizeof(indx_t);
3375 /* Write the node data. */
3376 node = NODEPTR(mp, indx);
3377 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3378 node->mn_flags = flags;
3380 SETDSZ(node,data->mv_size);
3385 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3390 if (F_ISSET(flags, F_BIGDATA))
3391 memcpy(node->mn_data + key->mv_size, data->mv_data,
3394 memcpy(node->mn_data + key->mv_size, data->mv_data,
3397 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
3399 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
3407 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3410 indx_t i, j, numkeys, ptr;
3414 DPRINTF("delete node %u on %s page %lu", indx,
3415 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3416 assert(indx < NUMKEYS(mp));
3419 int x = NUMKEYS(mp) - 1 - indx;
3420 base = LEAF2KEY(mp, indx, ksize);
3422 memmove(base, base + ksize, x * ksize);
3423 mp->mp_lower -= sizeof(indx_t);
3424 mp->mp_upper += ksize - sizeof(indx_t);
3428 node = NODEPTR(mp, indx);
3429 sz = NODESIZE + node->mn_ksize;
3431 if (F_ISSET(node->mn_flags, F_BIGDATA))
3432 sz += sizeof(pgno_t);
3434 sz += NODEDSZ(node);
3438 ptr = mp->mp_ptrs[indx];
3439 numkeys = NUMKEYS(mp);
3440 for (i = j = 0; i < numkeys; i++) {
3442 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3443 if (mp->mp_ptrs[i] < ptr)
3444 mp->mp_ptrs[j] += sz;
3449 base = (char *)mp + mp->mp_upper;
3450 memmove(base + sz, base, ptr - mp->mp_upper);
3452 mp->mp_lower -= sizeof(indx_t);
3457 mdb_xcursor_init0(MDB_cursor *mc)
3459 MDB_xcursor *mx = mc->mc_xcursor;
3462 mx->mx_txn = *mc->mc_txn;
3463 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3464 mx->mx_txn.mt_dbs = mx->mx_dbs;
3465 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3466 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3467 if (mc->mc_dbi > 1) {
3468 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3473 mx->mx_dbxs[dbn+1].md_parent = dbn;
3474 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3475 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3476 mx->mx_dbxs[dbn+1].md_dirty = 0;
3477 mx->mx_txn.mt_numdbs = dbn+2;
3478 mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3480 mx->mx_cursor.mc_xcursor = NULL;
3481 mx->mx_cursor.mc_txn = &mx->mx_txn;
3482 mx->mx_cursor.mc_dbi = dbn+1;
3486 mdb_xcursor_init1(MDB_cursor *mc, MDB_page *mp, MDB_node *node)
3488 MDB_db *db = NODEDATA(node);
3489 MDB_xcursor *mx = mc->mc_xcursor;
3491 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3492 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3493 if (mc->mc_dbi > 1) {
3494 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3495 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3500 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi, db->md_root);
3501 mx->mx_dbs[dbn] = *db;
3502 if (F_ISSET(mp->mp_flags, P_DIRTY))
3503 mx->mx_dbxs[dbn].md_dirty = 1;
3504 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3505 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3506 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3507 mx->mx_cursor.mc_snum = 0;
3508 mx->mx_cursor.mc_flags = 0;
3512 mdb_xcursor_init2(MDB_cursor *mc)
3514 MDB_xcursor *mx = mc->mc_xcursor;
3516 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3517 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3518 if (mc->mc_dbi > 1) {
3519 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3520 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3525 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi,
3526 mx->mx_dbs[dbn].md_root);
3527 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3531 mdb_xcursor_fini(MDB_cursor *mc)
3533 MDB_xcursor *mx = mc->mc_xcursor;
3534 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3535 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3536 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3537 if (mc->mc_dbi > 1) {
3538 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3539 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3544 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3547 size_t size = sizeof(MDB_cursor);
3549 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3552 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3553 size += sizeof(MDB_xcursor);
3555 if ((cursor = calloc(1, size)) != NULL) {
3556 cursor->mc_dbi = dbi;
3557 cursor->mc_txn = txn;
3558 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3559 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
3560 cursor->mc_xcursor = mx;
3561 mdb_xcursor_init0(cursor);
3572 /* Return the count of duplicate data items for the current key */
3574 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3579 if (mc == NULL || countp == NULL)
3582 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3585 top = CURSOR_TOP(mc);
3586 leaf = NODEPTR(top->mp_page, top->mp_ki);
3587 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3590 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3593 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3600 mdb_cursor_reset(MDB_cursor *mc)
3603 if (mc->mc_flags & C_XDIRTY) {
3605 mdb_xcursor_fini(mc);
3607 /* If sub-DB still has entries, update root record */
3608 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3612 top = CURSOR_TOP(mc);
3613 leaf = NODEPTR(top->mp_page, top->mp_ki);
3614 memcpy(NODEDATA(leaf),
3615 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3618 mc->mc_flags ^= C_XDIRTY;
3625 mdb_cursor_close(MDB_cursor *cursor)
3627 if (cursor != NULL) {
3633 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3635 indx_t ptr, i, numkeys;
3642 node = NODEPTR(mp, indx);
3643 ptr = mp->mp_ptrs[indx];
3644 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3646 (int)node->mn_ksize, (char *)NODEKEY(node),
3650 delta = key->mv_size - node->mn_ksize;
3652 if (delta > 0 && SIZELEFT(mp) < delta) {
3653 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3657 numkeys = NUMKEYS(mp);
3658 for (i = 0; i < numkeys; i++) {
3659 if (mp->mp_ptrs[i] <= ptr)
3660 mp->mp_ptrs[i] -= delta;
3663 base = (char *)mp + mp->mp_upper;
3664 len = ptr - mp->mp_upper + NODESIZE;
3665 memmove(base - delta, base, len);
3666 mp->mp_upper -= delta;
3668 node = NODEPTR(mp, indx);
3669 node->mn_ksize = key->mv_size;
3672 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3677 /* Move a node from src to dst.
3680 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
3681 MDB_pageparent *dst, indx_t dstindx)
3688 /* Mark src and dst as dirty. */
3689 if ((rc = mdb_touch(txn, dbi, src)) ||
3690 (rc = mdb_touch(txn, dbi, dst)))
3693 if (IS_LEAF2(src->mp_page)) {
3694 srcnode = NODEPTR(src->mp_page, 0); /* fake */
3695 key.mv_size = txn->mt_dbs[dbi].md_pad;
3696 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3698 data.mv_data = NULL;
3700 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
3701 /* must find the lowest key below src */
3703 mpp.mp_page = src->mp_page;
3705 mdb_search_page_root(txn, dbi, NULL, NULL, 0, &mpp);
3706 srcnode = NODEPTR(mpp.mp_page, 0);
3708 srcnode = NODEPTR(src->mp_page, srcindx);
3710 key.mv_size = NODEKSZ(srcnode);
3711 key.mv_data = NODEKEY(srcnode);
3712 data.mv_size = NODEDSZ(srcnode);
3713 data.mv_data = NODEDATA(srcnode);
3715 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3716 IS_LEAF(src->mp_page) ? "leaf" : "branch",
3719 src->mp_page->mp_pgno,
3720 dstindx, dst->mp_page->mp_pgno);
3722 /* Add the node to the destination page.
3724 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
3726 if (rc != MDB_SUCCESS)
3729 /* Delete the node from the source page.
3731 mdb_del_node(src->mp_page, srcindx, key.mv_size);
3733 /* Update the parent separators.
3736 if (src->mp_pi != 0) {
3737 if (IS_LEAF2(src->mp_page)) {
3738 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3740 srcnode = NODEPTR(src->mp_page, srcindx);
3741 key.mv_size = NODEKSZ(srcnode);
3742 key.mv_data = NODEKEY(srcnode);
3744 DPRINTF("update separator for source page %lu to [%s]",
3745 src->mp_page->mp_pgno, DKEY(&key));
3746 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
3747 &key)) != MDB_SUCCESS)
3750 if (IS_BRANCH(src->mp_page)) {
3752 nullkey.mv_size = 0;
3753 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
3758 if (dst->mp_pi != 0) {
3759 if (IS_LEAF2(src->mp_page)) {
3760 key.mv_data = LEAF2KEY(dst->mp_page, 0, key.mv_size);
3762 srcnode = NODEPTR(dst->mp_page, 0);
3763 key.mv_size = NODEKSZ(srcnode);
3764 key.mv_data = NODEKEY(srcnode);
3766 DPRINTF("update separator for destination page %lu to [%s]",
3767 dst->mp_page->mp_pgno, DKEY(&key));
3768 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
3769 &key)) != MDB_SUCCESS)
3772 if (IS_BRANCH(dst->mp_page)) {
3774 nullkey.mv_size = 0;
3775 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
3783 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
3792 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
3794 assert(txn != NULL);
3795 assert(src->mp_parent); /* can't merge root page */
3796 assert(dst->mp_parent);
3798 /* Mark src and dst as dirty. */
3799 if ((rc = mdb_touch(txn, dbi, src)) ||
3800 (rc = mdb_touch(txn, dbi, dst)))
3803 /* Move all nodes from src to dst.
3805 if (IS_LEAF2(src->mp_page)) {
3806 key.mv_size = txn->mt_dbs[dbi].md_pad;
3807 key.mv_data = METADATA(src->mp_page);
3808 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3809 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3811 if (rc != MDB_SUCCESS)
3813 key.mv_data = (char *)key.mv_data + key.mv_size;
3816 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3817 srcnode = NODEPTR(src->mp_page, i);
3819 key.mv_size = srcnode->mn_ksize;
3820 key.mv_data = NODEKEY(srcnode);
3821 data.mv_size = NODEDSZ(srcnode);
3822 data.mv_data = NODEDATA(srcnode);
3823 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3824 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3825 if (rc != MDB_SUCCESS)
3830 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3831 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3833 /* Unlink the src page from parent.
3835 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3836 if (src->mp_pi == 0) {
3838 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3842 if (IS_LEAF(src->mp_page))
3843 txn->mt_dbs[dbi].md_leaf_pages--;
3845 txn->mt_dbs[dbi].md_branch_pages--;
3847 mpp.mp_page = src->mp_parent;
3848 dh = (MDB_dhead *)src->mp_parent;
3850 mpp.mp_parent = dh->md_parent;
3851 mpp.mp_pi = dh->md_pi;
3853 return mdb_rebalance(txn, dbi, &mpp);
3856 #define FILL_THRESHOLD 250
3859 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3864 indx_t si = 0, di = 0;
3867 assert(txn != NULL);
3868 assert(mpp != NULL);
3870 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3871 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3872 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3874 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3875 DPRINTF("no need to rebalance page %lu, above fill threshold",
3876 mpp->mp_page->mp_pgno);
3880 if (mpp->mp_parent == NULL) {
3881 if (NUMKEYS(mpp->mp_page) == 0) {
3882 DPUTS("tree is completely empty");
3883 txn->mt_dbs[dbi].md_root = P_INVALID;
3884 txn->mt_dbs[dbi].md_depth = 0;
3885 txn->mt_dbs[dbi].md_leaf_pages = 0;
3886 mdb_midl_append(txn->mt_free_pgs, mpp->mp_page->mp_pgno);
3887 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3888 DPUTS("collapsing root page!");
3889 mdb_midl_append(txn->mt_free_pgs, mpp->mp_page->mp_pgno);
3890 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3891 if ((rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root)))
3893 txn->mt_dbs[dbi].md_depth--;
3894 txn->mt_dbs[dbi].md_branch_pages--;
3896 DPUTS("root page doesn't need rebalancing");
3900 /* The parent (branch page) must have at least 2 pointers,
3901 * otherwise the tree is invalid.
3903 assert(NUMKEYS(mpp->mp_parent) > 1);
3905 /* Leaf page fill factor is below the threshold.
3906 * Try to move keys from left or right neighbor, or
3907 * merge with a neighbor page.
3912 if (mpp->mp_pi == 0) {
3913 /* We're the leftmost leaf in our parent.
3915 DPUTS("reading right neighbor");
3916 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3917 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3919 npp.mp_pi = mpp->mp_pi + 1;
3921 di = NUMKEYS(mpp->mp_page);
3923 /* There is at least one neighbor to the left.
3925 DPUTS("reading left neighbor");
3926 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3927 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3929 npp.mp_pi = mpp->mp_pi - 1;
3930 si = NUMKEYS(npp.mp_page) - 1;
3933 npp.mp_parent = mpp->mp_parent;
3935 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3936 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3938 /* If the neighbor page is above threshold and has at least two
3939 * keys, move one key from it.
3941 * Otherwise we should try to merge them.
3943 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3944 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3945 else { /* FIXME: if (has_enough_room()) */
3946 if (mpp->mp_pi == 0)
3947 return mdb_merge(txn, dbi, &npp, mpp);
3949 return mdb_merge(txn, dbi, mpp, &npp);
3954 mdb_del0(MDB_cursor *mc, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3958 /* add overflow pages to free list */
3959 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3963 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3964 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
3965 for (i=0; i<ovpages; i++) {
3966 DPRINTF("freed ov page %lu", pg);
3967 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3971 mdb_del_node(mpp->mp_page, ki, mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad);
3972 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3973 rc = mdb_rebalance(mc->mc_txn, mc->mc_dbi, mpp);
3974 if (rc != MDB_SUCCESS)
3975 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3981 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3982 MDB_val *key, MDB_val *data)
3987 MDB_val rdata, *xdata;
3991 assert(key != NULL);
3993 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3995 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3998 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4002 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4009 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4010 mc.mc_xcursor = &mx;
4011 mdb_xcursor_init0(&mc);
4013 mc.mc_xcursor = NULL;
4025 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4027 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4031 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
4032 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
4033 * *newindxp with the actual values after split, ie if *mpp and *newindxp
4034 * refer to a node in the new right sibling page.
4037 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
4038 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4041 int rc = MDB_SUCCESS, ins_new = 0;
4044 unsigned int i, j, split_indx, nkeys, pmax;
4046 MDB_val sepkey, rkey, rdata;
4047 MDB_page *copy, *cptr;
4048 MDB_dpage *mdp, *rdp, *pdp;
4052 assert(txn != NULL);
4054 dh = ((MDB_dhead *)*mpp) - 1;
4055 mdp = (MDB_dpage *)dh;
4056 newindx = *newindxp;
4058 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
4059 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
4060 DKEY(newkey), *newindxp);
4062 if (mdp->h.md_parent == NULL) {
4063 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
4066 mdp->h.md_parent = &pdp->p;
4067 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
4068 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
4069 txn->mt_dbs[dbi].md_depth++;
4071 /* Add left (implicit) pointer. */
4072 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
4073 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
4076 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
4079 /* Create a right sibling. */
4080 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
4082 rdp->h.md_parent = mdp->h.md_parent;
4083 rdp->h.md_pi = mdp->h.md_pi + 1;
4084 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
4086 nkeys = NUMKEYS(&mdp->p);
4087 split_indx = nkeys / 2 + 1;
4089 if (IS_LEAF2(&rdp->p)) {
4092 unsigned int lsize, rsize, ksize;
4093 /* Move half of the keys to the right sibling */
4095 x = *newindxp - split_indx;
4096 ksize = txn->mt_dbs[dbi].md_pad;
4097 split = LEAF2KEY(&mdp->p, split_indx, ksize);
4098 rsize = (nkeys - split_indx) * ksize;
4099 lsize = (nkeys - split_indx) * sizeof(indx_t);
4100 mdp->p.mp_lower -= lsize;
4101 rdp->p.mp_lower += lsize;
4102 mdp->p.mp_upper += rsize - lsize;
4103 rdp->p.mp_upper -= rsize - lsize;
4104 sepkey.mv_size = ksize;
4105 if (newindx == split_indx) {
4106 sepkey.mv_data = newkey->mv_data;
4108 sepkey.mv_data = split;
4111 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
4112 memcpy(&rdp->p.mp_ptrs, split, rsize);
4113 sepkey.mv_data = &rdp->p.mp_ptrs;
4114 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
4115 memcpy(ins, newkey->mv_data, ksize);
4116 mdp->p.mp_lower += sizeof(indx_t);
4117 mdp->p.mp_upper -= ksize - sizeof(indx_t);
4120 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
4121 ins = LEAF2KEY(&rdp->p, x, ksize);
4122 memcpy(ins, newkey->mv_data, ksize);
4123 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4124 rdp->p.mp_lower += sizeof(indx_t);
4125 rdp->p.mp_upper -= ksize - sizeof(indx_t);
4132 /* For leaf pages, check the split point based on what
4133 * fits where, since otherwise add_node can fail.
4135 if (IS_LEAF(&mdp->p)) {
4136 unsigned int psize, nsize;
4137 /* Maximum free space in an empty page */
4138 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
4139 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
4140 if (newindx < split_indx) {
4142 for (i=0; i<split_indx; i++) {
4143 node = NODEPTR(&mdp->p, i);
4144 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4145 if (F_ISSET(node->mn_flags, F_BIGDATA))
4146 psize += sizeof(pgno_t);
4148 psize += NODEDSZ(node);
4157 for (i=nkeys-1; i>=split_indx; i--) {
4158 node = NODEPTR(&mdp->p, i);
4159 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4160 if (F_ISSET(node->mn_flags, F_BIGDATA))
4161 psize += sizeof(pgno_t);
4163 psize += NODEDSZ(node);
4173 /* First find the separating key between the split pages.
4175 if (newindx == split_indx) {
4176 sepkey.mv_size = newkey->mv_size;
4177 sepkey.mv_data = newkey->mv_data;
4179 node = NODEPTR(&mdp->p, split_indx);
4180 sepkey.mv_size = node->mn_ksize;
4181 sepkey.mv_data = NODEKEY(node);
4185 DPRINTF("separator is [%s]", DKEY(&sepkey));
4187 /* Copy separator key to the parent.
4189 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
4190 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
4191 &sepkey, NULL, rdp->p.mp_pgno);
4193 /* Right page might now have changed parent.
4194 * Check if left page also changed parent.
4196 if (rdp->h.md_parent != mdp->h.md_parent &&
4197 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
4198 mdp->h.md_parent = rdp->h.md_parent;
4199 mdp->h.md_pi = rdp->h.md_pi - 1;
4202 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
4203 &sepkey, NULL, rdp->p.mp_pgno, 0);
4205 if (IS_LEAF2(&rdp->p)) {
4208 if (rc != MDB_SUCCESS) {
4212 /* Move half of the keys to the right sibling. */
4213 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
4216 copy->mp_pgno = mdp->p.mp_pgno;
4217 copy->mp_flags = mdp->p.mp_flags;
4218 copy->mp_lower = PAGEHDRSZ;
4219 copy->mp_upper = txn->mt_env->me_psize;
4221 for (i = j = 0; i <= nkeys; j++) {
4222 if (i == split_indx) {
4223 /* Insert in right sibling. */
4224 /* Reset insert index for right sibling. */
4225 j = (i == newindx && ins_new);
4229 if (i == newindx && !ins_new) {
4230 /* Insert the original entry that caused the split. */
4231 rkey.mv_data = newkey->mv_data;
4232 rkey.mv_size = newkey->mv_size;
4233 if (IS_LEAF(&mdp->p)) {
4234 rdata.mv_data = newdata->mv_data;
4235 rdata.mv_size = newdata->mv_size;
4242 /* Update page and index for the new key. */
4244 if (cptr == &rdp->p)
4246 } else if (i == nkeys) {
4249 node = NODEPTR(&mdp->p, i);
4250 rkey.mv_data = NODEKEY(node);
4251 rkey.mv_size = node->mn_ksize;
4252 if (IS_LEAF(&mdp->p)) {
4253 rdata.mv_data = NODEDATA(node);
4254 rdata.mv_size = NODEDSZ(node);
4256 pgno = NODEPGNO(node);
4257 flags = node->mn_flags;
4262 if (!IS_LEAF(&mdp->p) && j == 0) {
4263 /* First branch index doesn't need key data. */
4267 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
4269 nkeys = NUMKEYS(copy);
4270 for (i=0; i<nkeys; i++)
4271 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
4272 mdp->p.mp_lower = copy->mp_lower;
4273 mdp->p.mp_upper = copy->mp_upper;
4274 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
4275 txn->mt_env->me_psize - copy->mp_upper);
4282 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4283 MDB_val *key, MDB_val *data, unsigned int flags)
4288 assert(key != NULL);
4289 assert(data != NULL);
4291 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4294 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4298 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4302 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4309 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4310 mc.mc_xcursor = &mx;
4311 mdb_xcursor_init0(&mc);
4313 mc.mc_xcursor = NULL;
4315 return mdb_cursor_put(&mc, key, data, flags);
4319 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4321 #define CHANGEABLE (MDB_NOSYNC)
4322 if ((flag & CHANGEABLE) != flag)
4325 env->me_flags |= flag;
4327 env->me_flags &= ~flag;
4332 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4337 *arg = env->me_flags;
4342 mdb_env_get_path(MDB_env *env, const char **arg)
4347 *arg = env->me_path;
4352 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4354 arg->ms_psize = env->me_psize;
4355 arg->ms_depth = db->md_depth;
4356 arg->ms_branch_pages = db->md_branch_pages;
4357 arg->ms_leaf_pages = db->md_leaf_pages;
4358 arg->ms_overflow_pages = db->md_overflow_pages;
4359 arg->ms_entries = db->md_entries;
4364 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4368 if (env == NULL || arg == NULL)
4371 mdb_env_read_meta(env, &toggle);
4373 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4377 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4379 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4380 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4381 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4382 txn->mt_dbxs[dbi].md_cmp = cintcmp;
4384 txn->mt_dbxs[dbi].md_cmp = memncmp;
4386 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4387 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4388 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4389 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4391 txn->mt_dbxs[dbi].md_dcmp = cintcmp;
4392 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4393 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4395 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4398 txn->mt_dbxs[dbi].md_dcmp = NULL;
4402 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4409 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4410 mdb_default_cmp(txn, FREE_DBI);
4416 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4417 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4418 mdb_default_cmp(txn, MAIN_DBI);
4422 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4423 mdb_default_cmp(txn, MAIN_DBI);
4426 /* Is the DB already open? */
4428 for (i=2; i<txn->mt_numdbs; i++) {
4429 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4430 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4436 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4439 /* Find the DB info */
4441 key.mv_data = (void *)name;
4442 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4444 /* Create if requested */
4445 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4448 data.mv_size = sizeof(MDB_db);
4449 data.mv_data = &dummy;
4450 memset(&dummy, 0, sizeof(dummy));
4451 dummy.md_root = P_INVALID;
4452 dummy.md_flags = flags & 0xffff;
4454 mc.mc_dbi = MAIN_DBI;
4456 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4460 /* OK, got info, add to table */
4461 if (rc == MDB_SUCCESS) {
4462 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4463 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4464 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4465 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4466 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4467 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4468 *dbi = txn->mt_numdbs;
4469 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4470 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4471 mdb_default_cmp(txn, txn->mt_numdbs);
4478 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4480 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4483 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4486 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4489 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4491 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4492 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4493 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4497 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4499 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4502 txn->mt_dbxs[dbi].md_cmp = cmp;
4506 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4508 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4511 txn->mt_dbxs[dbi].md_dcmp = cmp;
4515 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4517 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4520 txn->mt_dbxs[dbi].md_rel = rel;