]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
Fix mdb_split, fix MDB_GET_BOTH
[openldap] / libraries / libmdb / mdb.c
1 /** @file mdb.c
2  *      @brief memory-mapped database library
3  *
4  *      A Btree-based database management library modeled loosely on the
5  *      BerkeleyDB API, but much simplified.
6  */
7 /*
8  * Copyright 2011 Howard Chu, Symas Corp.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted only as authorized by the OpenLDAP
13  * Public License.
14  *
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>.
18  *
19  * This code is derived from btree.c written by Martin Hedenfalk.
20  *
21  * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
22  *
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.
26  *
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.
34  */
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/param.h>
38 #ifdef _WIN32
39 #include <windows.h>
40 #else
41 #include <sys/uio.h>
42 #include <sys/mman.h>
43 #ifdef HAVE_SYS_FILE_H
44 #include <sys/file.h>
45 #endif
46 #include <fcntl.h>
47 #endif
48
49 #include <assert.h>
50 #include <errno.h>
51 #include <stddef.h>
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <time.h>
57 #include <unistd.h>
58
59 #ifndef _WIN32
60 #include <pthread.h>
61 #endif
62
63 #include "mdb.h"
64 #include "midl.h"
65
66 /** @defgroup internal  MDB Internals
67  *      @{
68  */
69 /** @defgroup compat    Windows Compatibility Macros
70  *      @{
71  */
72 #ifdef _WIN32
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)
93 #else
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
99 #define HANDLE  int
100 #define INVALID_HANDLE_VALUE    -1
101 #define GetPageSize(x)  (x) = sysconf(_SC_PAGE_SIZE)
102 #endif
103
104 /** @} */
105
106 #ifndef _WIN32
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.
110  */
111 #ifndef MDB_DSYNC
112 # define MDB_DSYNC      O_DSYNC
113 #endif
114 #endif
115
116 #define ULONG           unsigned long
117 typedef ULONG           pgno_t;
118
119 #ifndef DEBUG
120 #define DEBUG 0
121 #endif
122
123 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
124 # define DPRINTF        (void)  /* Vararg macros may be unsupported */
125 #elif DEBUG
126 # define DPRINTF(fmt, ...)      /* Requires 2 or more args */ \
127         fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
128 #else
129 # define DPRINTF(fmt, ...)      ((void) 0)
130 #endif
131 #define DPUTS(arg)      DPRINTF("%s", arg)
132
133 #define PAGESIZE         4096
134 #define MDB_MINKEYS      2
135 #define MDB_MAGIC        0xBEEFC0DE
136 #define MDB_VERSION      1
137 #define MAXKEYSIZE       511
138 #if DEBUG
139 #define KBUF    (MAXKEYSIZE*2+1)
140 #define DKBUF   char kbuf[KBUF]
141 #define DKEY(x) mdb_dkey(x, kbuf)
142 #else
143 #define DKBUF
144 #define DKEY(x)
145 #endif
146
147 /* The DB view is always consistent because all writes are wrapped in
148  * the wmutex. Finer-grained locks aren't necessary.
149  */
150 #ifndef LAZY_LOCKS
151 #define LAZY_LOCKS      1
152 #endif
153 #if     LAZY_LOCKS
154 #define LAZY_MUTEX_LOCK(x)
155 #define LAZY_MUTEX_UNLOCK(x)
156 #define LAZY_RWLOCK_UNLOCK(x)
157 #define LAZY_RWLOCK_WRLOCK(x)
158 #define LAZY_RWLOCK_RDLOCK(x)
159 #define LAZY_RWLOCK_DEF(x)
160 #define LAZY_RWLOCK_INIT(x,y)
161 #define LAZY_RWLOCK_DESTROY(x)
162 #else
163 #define LAZY_MUTEX_LOCK(x)              pthread_mutex_lock(x)
164 #define LAZY_MUTEX_UNLOCK(x)    pthread_mutex_unlock(x)
165 #define LAZY_RWLOCK_UNLOCK(x)   pthread_rwlock_unlock(x)
166 #define LAZY_RWLOCK_WRLOCK(x)   pthread_rwlock_wrlock(x)
167 #define LAZY_RWLOCK_RDLOCK(x)   pthread_rwlock_rdlock(x)
168 #define LAZY_RWLOCK_DEF(x)              pthread_rwlock_t        x
169 #define LAZY_RWLOCK_INIT(x,y)   pthread_rwlock_init(x,y)
170 #define LAZY_RWLOCK_DESTROY(x)  pthread_rwlock_destroy(x)
171 #endif
172
173 #define P_INVALID        (~0UL)
174
175 #define F_ISSET(w, f)    (((w) & (f)) == (f))
176
177 typedef uint16_t         indx_t;
178
179 #define DEFAULT_READERS 126
180 #define DEFAULT_MAPSIZE 1048576
181
182 /* Lock descriptor stuff */
183 #ifndef CACHELINE
184 #define CACHELINE       64      /* most CPUs. Itanium uses 128 */
185 #endif
186
187 typedef struct MDB_rxbody {
188         ULONG           mrb_txnid;
189         pid_t           mrb_pid;
190         pthread_t       mrb_tid;
191 } MDB_rxbody;
192
193 typedef struct MDB_reader {
194         union {
195                 MDB_rxbody mrx;
196 #define mr_txnid        mru.mrx.mrb_txnid
197 #define mr_pid  mru.mrx.mrb_pid
198 #define mr_tid  mru.mrx.mrb_tid
199                 /* cache line alignment */
200                 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
201         } mru;
202 } MDB_reader;
203
204 typedef struct MDB_txbody {
205         uint32_t        mtb_magic;
206         uint32_t        mtb_version;
207 /* For POSIX the actual mutexes reside in shared memory.
208  * On Windows, mutexes are allocated by the kernel; we store
209  * the name in shared memory so that other processes can
210  * grab them.
211  */
212 #ifdef _WIN32
213         char    mtb_rmname[32];
214 #else
215         pthread_mutex_t mtb_mutex;
216 #endif
217         ULONG           mtb_txnid;
218         uint32_t        mtb_numreaders;
219         uint32_t        mtb_me_toggle;
220 } MDB_txbody;
221
222 typedef struct MDB_txninfo {
223         union {
224                 MDB_txbody mtb;
225 #define mti_magic       mt1.mtb.mtb_magic
226 #define mti_version     mt1.mtb.mtb_version
227 #define mti_mutex       mt1.mtb.mtb_mutex
228 #define mti_rmname      mt1.mtb.mtb_rmname
229 #define mti_txnid       mt1.mtb.mtb_txnid
230 #define mti_numreaders  mt1.mtb.mtb_numreaders
231 #define mti_me_toggle   mt1.mtb.mtb_me_toggle
232                 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
233         } mt1;
234         union {
235 #ifdef _WIN32
236                 char mt2_wmname[32];
237 #define mti_wmname      mt2.mt2_wmname
238 #else
239                 pthread_mutex_t mt2_wmutex;
240 #define mti_wmutex      mt2.mt2_wmutex
241 #endif
242                 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
243         } mt2;
244         MDB_reader      mti_readers[1];
245 } MDB_txninfo;
246
247 /* Common header for all page types. Overflow pages
248  * occupy a number of contiguous pages with no
249  * headers on any page after the first.
250  */
251 typedef struct MDB_page {               /* represents a page of storage */
252 #define mp_pgno         mp_p.p_pgno
253         union padded {
254                 pgno_t          p_pgno;         /* page number */
255                 void *          p_align;        /* for IL32P64 */
256         } mp_p;
257 #define P_BRANCH         0x01           /* branch page */
258 #define P_LEAF           0x02           /* leaf page */
259 #define P_OVERFLOW       0x04           /* overflow page */
260 #define P_META           0x08           /* meta page */
261 #define P_DIRTY          0x10           /* dirty page */
262 #define P_LEAF2          0x20           /* DB with small, fixed size keys and no data */
263         uint32_t        mp_flags;
264 #define mp_lower        mp_pb.pb.pb_lower
265 #define mp_upper        mp_pb.pb.pb_upper
266 #define mp_pages        mp_pb.pb_pages
267         union page_bounds {
268                 struct {
269                         indx_t          pb_lower;               /* lower bound of free space */
270                         indx_t          pb_upper;               /* upper bound of free space */
271                 } pb;
272                 uint32_t        pb_pages;       /* number of overflow pages */
273         } mp_pb;
274         indx_t          mp_ptrs[1];             /* dynamic size */
275 } MDB_page;
276
277 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
278
279 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
280 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
281 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
282                                 ((env)->me_psize - PAGEHDRSZ))
283 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
284 #define IS_LEAF2(p)      F_ISSET((p)->mp_flags, P_LEAF2)
285 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
286 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
287
288 #define OVPAGES(size, psize)    ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
289
290 typedef struct MDB_db {
291         uint32_t        md_pad;         /* also ksize for LEAF2 pages */
292         uint16_t        md_flags;
293         uint16_t        md_depth;
294         ULONG           md_branch_pages;
295         ULONG           md_leaf_pages;
296         ULONG           md_overflow_pages;
297         ULONG           md_entries;
298         pgno_t          md_root;
299 } MDB_db;
300
301 #define FREE_DBI        0
302 #define MAIN_DBI        1
303
304 typedef struct MDB_meta {                       /* meta (footer) page content */
305         uint32_t        mm_magic;
306         uint32_t        mm_version;
307         void            *mm_address;            /* address for fixed mapping */
308         size_t          mm_mapsize;                     /* size of mmap region */
309         MDB_db          mm_dbs[2];                      /* first is free space, 2nd is main db */
310 #define mm_psize        mm_dbs[0].md_pad
311 #define mm_flags        mm_dbs[0].md_flags
312         pgno_t          mm_last_pg;                     /* last used page in file */
313         ULONG           mm_txnid;                       /* txnid that committed this page */
314 } MDB_meta;
315
316 typedef struct MDB_dhead {                                      /* a dirty page */
317         MDB_page        *md_parent;
318         unsigned        md_pi;                          /* parent index */
319         int                     md_num;
320 } MDB_dhead;
321
322 typedef struct MDB_dpage {
323         MDB_dhead       h;
324         MDB_page        p;
325 } MDB_dpage;
326
327 typedef struct MDB_oldpages {
328         struct MDB_oldpages *mo_next;
329         ULONG           mo_txnid;
330         pgno_t          mo_pages[1];    /* dynamic */
331 } MDB_oldpages;
332
333 typedef struct MDB_pageparent {
334         MDB_page *mp_page;
335         MDB_page *mp_parent;
336         unsigned mp_pi;
337 } MDB_pageparent;
338
339 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num);
340 static int              mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
341
342 typedef struct MDB_ppage {                                      /* ordered list of pages */
343         MDB_page                *mp_page;
344         unsigned int    mp_ki;          /* cursor index on page */
345 } MDB_ppage;
346
347 #define CURSOR_TOP(c)            (&(c)->mc_stack[(c)->mc_snum-1])
348 #define CURSOR_PARENT(c)         (&(c)->mc_stack[(c)->mc_snum-2])
349 #define CURSOR_STACK             32
350
351 struct MDB_xcursor;
352
353 struct MDB_cursor {
354         MDB_txn         *mc_txn;
355         MDB_ppage       mc_stack[CURSOR_STACK];         /* stack of parent pages */
356         unsigned int    mc_snum;                /* number of pushed pages */
357         MDB_dbi         mc_dbi;
358         short           mc_initialized; /* 1 if initialized */
359         short           mc_eof;         /* 1 if end is reached */
360         struct MDB_xcursor      *mc_xcursor;
361 };
362
363 #define METADATA(p)      ((void *)((char *)(p) + PAGEHDRSZ))
364
365 typedef struct MDB_node {
366 #define mn_pgno          mn_p.np_pgno
367 #define mn_dsize         mn_p.np_dsize
368         union {
369                 pgno_t           np_pgno;       /* child page number */
370                 uint32_t         np_dsize;      /* leaf data size */
371         } mn_p;
372         unsigned int    mn_flags:4;
373         unsigned int    mn_ksize:12;                    /* key size */
374 #define F_BIGDATA        0x01                   /* data put on overflow page */
375 #define F_SUBDATA        0x02                   /* data is a sub-database */
376 #define F_DUPDATA        0x04                   /* data has duplicates */
377         char            mn_data[1];
378 } MDB_node;
379
380 typedef struct MDB_dbx {
381         MDB_val         md_name;
382         MDB_cmp_func    *md_cmp;                /* user compare function */
383         MDB_cmp_func    *md_dcmp;               /* user dupsort function */
384         MDB_rel_func    *md_rel;                /* user relocate function */
385         MDB_dbi md_parent;
386         unsigned int    md_dirty;
387 } MDB_dbx;
388
389 struct MDB_txn {
390         pgno_t          mt_next_pgno;   /* next unallocated page */
391         ULONG           mt_txnid;
392         MDB_env         *mt_env;        
393         pgno_t          *mt_free_pgs;   /* this is an IDL */
394         union {
395                 ID2L    dirty_list;     /* modified pages */
396                 MDB_reader      *reader;
397         } mt_u;
398         MDB_dbx         *mt_dbxs;               /* array */
399         MDB_db          *mt_dbs;
400         unsigned int    mt_numdbs;
401
402 #define MDB_TXN_RDONLY          0x01            /* read-only transaction */
403 #define MDB_TXN_ERROR           0x02            /* an error has occurred */
404         unsigned int    mt_flags;
405         unsigned int    mt_toggle;
406 };
407
408 /* Context for sorted-dup records */
409 typedef struct MDB_xcursor {
410         MDB_cursor mx_cursor;
411         MDB_txn mx_txn;
412         MDB_dbx mx_dbxs[4];
413         MDB_db  mx_dbs[4];
414 } MDB_xcursor;
415
416 struct MDB_env {
417         HANDLE          me_fd;
418         HANDLE          me_lfd;
419         HANDLE          me_mfd;                 /* just for writing the meta pages */
420 #define MDB_FATAL_ERROR 0x80000000U
421         uint32_t        me_flags;
422         uint32_t        me_extrapad;    /* unused for now */
423         unsigned int    me_maxreaders;
424         unsigned int    me_numdbs;
425         unsigned int    me_maxdbs;
426         char            *me_path;
427         char            *me_map;
428         MDB_txninfo     *me_txns;
429         MDB_meta        *me_metas[2];
430         MDB_txn         *me_txn;                /* current write transaction */
431         size_t          me_mapsize;
432         off_t           me_size;                /* current file size */
433         pgno_t          me_maxpg;               /* me_mapsize / me_psize */
434         unsigned int    me_psize;
435         unsigned int    me_db_toggle;
436         MDB_dbx         *me_dbxs;               /* array */
437         MDB_db          *me_dbs[2];
438         MDB_oldpages *me_pghead;
439         pthread_key_t   me_txkey;       /* thread-key for readers */
440         MDB_dpage       *me_dpages;
441         pgno_t          me_free_pgs[MDB_IDL_UM_SIZE];
442         ID2                     me_dirty_list[MDB_IDL_DB_SIZE];
443         LAZY_RWLOCK_DEF(me_dblock);
444 #ifdef _WIN32
445         HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
446         HANDLE          me_wmutex;
447 #endif
448 };
449
450 #define NODESIZE         offsetof(MDB_node, mn_data)
451
452 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
453 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
454 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
455 #define NODEKEY(node)    (void *)((node)->mn_data)
456 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
457 #define NODEPGNO(node)   ((node)->mn_pgno)
458 #define NODEDSZ(node)    ((node)->mn_dsize)
459 #define NODEKSZ(node)    ((node)->mn_ksize)
460 #define LEAF2KEY(p, i, ks)      ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
461
462 #define MDB_SET_KEY(node, key)  if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
463
464 #define MDB_COMMIT_PAGES         64     /* max number of pages to write in one commit */
465
466 static int  mdb_search_page_root(MDB_txn *txn,
467                             MDB_dbi dbi, MDB_val *key,
468                             MDB_cursor *cursor, int modify,
469                             MDB_pageparent *mpp);
470 static int  mdb_search_page(MDB_txn *txn,
471                             MDB_dbi dbi, MDB_val *key,
472                             MDB_cursor *cursor, int modify,
473                             MDB_pageparent *mpp);
474
475 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
476 static int  mdb_env_read_meta(MDB_env *env, int *which);
477 static int  mdb_env_write_meta(MDB_txn *txn);
478 static int  mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
479
480 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
481                             MDB_val *key, int *exactp, unsigned int *kip);
482 static int  mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
483                             indx_t indx, MDB_val *key, MDB_val *data,
484                             pgno_t pgno, uint8_t flags);
485 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
486 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
487     MDB_pageparent *mpp, MDB_node *leaf);
488 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
489     MDB_val *key, MDB_val *data, unsigned int flags);
490 static int  mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
491
492 static int               mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
493 static int               mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
494 static int               mdb_move_node(MDB_txn *txn, MDB_dbi dbi, 
495                                 MDB_pageparent *src, indx_t srcindx,
496                                 MDB_pageparent *dst, indx_t dstindx);
497 static int               mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
498                             MDB_pageparent *dst);
499 static int               mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
500                             unsigned int *newindxp, MDB_val *newkey,
501                             MDB_val *newdata, pgno_t newpgno);
502 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
503
504 static void              cursor_pop_page(MDB_cursor *cursor);
505 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
506                             MDB_page *mp);
507
508 static int               mdb_sibling(MDB_cursor *cursor, int move_right);
509 static int               mdb_cursor_next(MDB_cursor *cursor,
510                             MDB_val *key, MDB_val *data, MDB_cursor_op op);
511 static int               mdb_cursor_prev(MDB_cursor *cursor,
512                             MDB_val *key, MDB_val *data, MDB_cursor_op op);
513 static int               mdb_cursor_set(MDB_cursor *cursor,
514                             MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
515 static int               mdb_cursor_first(MDB_cursor *cursor,
516                             MDB_val *key, MDB_val *data);
517 static int               mdb_cursor_last(MDB_cursor *cursor,
518                             MDB_val *key, MDB_val *data);
519
520 static void             mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
521 static void             mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx,
522                                         MDB_page *mp, MDB_node *node);
523 static void             mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
524
525 static size_t            mdb_leaf_size(MDB_env *env, MDB_val *key,
526                             MDB_val *data);
527 static size_t            mdb_branch_size(MDB_env *env, MDB_val *key);
528
529 static int               memncmp(const void *s1, size_t n1,
530                                  const void *s2, size_t n2);
531 static int               memnrcmp(const void *s1, size_t n1,
532                                   const void *s2, size_t n2);
533
534 #ifdef _WIN32
535 static SECURITY_DESCRIPTOR mdb_null_sd;
536 static SECURITY_ATTRIBUTES mdb_all_sa;
537 static int mdb_sec_inited;
538 #endif
539
540 static int
541 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
542 {
543         int diff, len_diff = -1;
544
545         if (n1 >= n2) {
546                 len_diff = (n1 > n2);
547                 n1 = n2;
548         }
549         diff = memcmp(s1, s2, n1);
550         return diff ? diff : len_diff;
551 }
552
553 static int
554 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
555 {
556         const unsigned char     *p1, *p2, *p1_lim;
557
558         if (n2 == 0)
559                 return n1 != 0;
560         if (n1 == 0)
561                 return -1;
562
563         p1 = (const unsigned char *)s1 + n1 - 1;
564         p2 = (const unsigned char *)s2 + n2 - 1;
565
566         for (p1_lim = (n1 <= n2 ? s1 : s2);  *p1 == *p2;  p1--, p2--) {
567                 if (p1 == p1_lim)
568                         return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
569         }
570         return *p1 - *p2;
571 }
572
573 char *
574 mdb_version(int *maj, int *min, int *pat)
575 {
576         if (maj) *maj = MDB_VERSION_MAJOR;
577         if (min) *min = MDB_VERSION_MINOR;
578         if (pat) *pat = MDB_VERSION_PATCH;
579         return MDB_VERSION_STRING;
580 }
581
582 static char *const mdb_errstr[] = {
583         "MDB_KEYEXIST: Key/data pair already exists",
584         "MDB_NOTFOUND: No matching key/data pair found",
585         "MDB_PAGE_NOTFOUND: Requested page not found",
586         "MDB_CORRUPTED: Located page was wrong type",
587         "MDB_PANIC: Update of meta page failed",
588         "MDB_VERSION_MISMATCH: Database environment version mismatch"
589 };
590
591 char *
592 mdb_strerror(int err)
593 {
594         if (!err)
595                 return ("Successful return: 0");
596
597         if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
598                 return mdb_errstr[err - MDB_KEYEXIST];
599
600         return strerror(err);
601 }
602
603 #if DEBUG
604 static char *
605 mdb_dkey(MDB_val *key, char *buf)
606 {
607         char *ptr = buf;
608         unsigned char *c = key->mv_data;
609         unsigned int i;
610         if (key->mv_size > MAXKEYSIZE)
611                 return "MAXKEYSIZE";
612         for (i=0; i<key->mv_size; i++)
613                 ptr += sprintf(ptr, "%02x", *c++);
614         return buf;
615 }
616 #endif
617
618 int
619 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
620 {
621         if (txn->mt_dbxs[dbi].md_cmp)
622                 return txn->mt_dbxs[dbi].md_cmp(a, b);
623
624         if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
625 #if __BYTE_ORDER == __LITTLE_ENDIAN
626                 |MDB_INTEGERKEY
627 #endif
628         ))
629                 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
630         else
631                 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
632 }
633
634 int
635 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
636 {
637         if (txn->mt_dbxs[dbi].md_dcmp)
638                 return txn->mt_dbxs[dbi].md_dcmp(a, b);
639
640         if (txn->mt_dbs[dbi].md_flags & (0
641 #if __BYTE_ORDER == __LITTLE_ENDIAN
642                 |MDB_INTEGERDUP
643 #endif
644         ))
645                 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
646         else
647                 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
648 }
649
650 /* Allocate new page(s) for writing */
651 static MDB_dpage *
652 mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num)
653 {
654         MDB_dpage *dp;
655         pgno_t pgno = P_INVALID;
656         ID2 mid;
657
658         if (txn->mt_txnid > 2) {
659
660                 if (!txn->mt_env->me_pghead && dbi != FREE_DBI &&
661                         txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
662                         /* See if there's anything in the free DB */
663                         MDB_pageparent mpp;
664                         MDB_node *leaf;
665                         ULONG *kptr, oldest;
666
667                         mpp.mp_parent = NULL;
668                         mpp.mp_pi = 0;
669                         mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
670                         leaf = NODEPTR(mpp.mp_page, 0);
671                         kptr = (ULONG *)NODEKEY(leaf);
672
673                         {
674                                 unsigned int i;
675                                 oldest = txn->mt_txnid - 1;
676                                 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
677                                         ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
678                                         if (mr && mr < oldest)
679                                                 oldest = mr;
680                                 }
681                         }
682
683                         if (oldest > *kptr) {
684                                 /* It's usable, grab it.
685                                  */
686                                 MDB_oldpages *mop;
687                                 MDB_val data;
688                                 pgno_t *idl;
689
690                                 mdb_read_data(txn, leaf, &data);
691                                 idl = (ULONG *)data.mv_data;
692                                 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
693                                 mop->mo_next = txn->mt_env->me_pghead;
694                                 mop->mo_txnid = *kptr;
695                                 txn->mt_env->me_pghead = mop;
696                                 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
697
698 #if DEBUG > 1
699                                 {
700                                         unsigned int i;
701                                         DPRINTF("IDL read txn %lu root %lu num %lu",
702                                                 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
703                                         for (i=0; i<idl[0]; i++) {
704                                                 DPRINTF("IDL %lu", idl[i+1]);
705                                         }
706                                 }
707 #endif
708                                 /* drop this IDL from the DB */
709                                 mpp.mp_parent = NULL;
710                                 mpp.mp_pi = 0;
711                                 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
712                                 leaf = NODEPTR(mpp.mp_page, 0);
713                                 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
714                         }
715                 }
716                 if (txn->mt_env->me_pghead) {
717                         MDB_oldpages *mop = txn->mt_env->me_pghead;
718                         if (num > 1) {
719                                 /* FIXME: For now, always use fresh pages. We
720                                  * really ought to search the free list for a
721                                  * contiguous range.
722                                  */
723                                 ;
724                         } else {
725                                 /* peel pages off tail, so we only have to truncate the list */
726                                 pgno = MDB_IDL_LAST(mop->mo_pages);
727                                 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
728                                         mop->mo_pages[2]++;
729                                         if (mop->mo_pages[2] > mop->mo_pages[1])
730                                                 mop->mo_pages[0] = 0;
731                                 } else {
732                                         mop->mo_pages[0]--;
733                                 }
734                                 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
735                                         txn->mt_env->me_pghead = mop->mo_next;
736                                         free(mop);
737                                 }
738                         }
739                 }
740         }
741
742         if (pgno == P_INVALID) {
743                 /* DB size is maxed out */
744                 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
745                         return NULL;
746         }
747         if (txn->mt_env->me_dpages && num == 1) {
748                 dp = txn->mt_env->me_dpages;
749                 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
750         } else {
751                 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
752                         return NULL;
753         }
754         dp->h.md_num = num;
755         dp->h.md_parent = parent;
756         dp->h.md_pi = parent_idx;
757         if (pgno == P_INVALID) {
758                 dp->p.mp_pgno = txn->mt_next_pgno;
759                 txn->mt_next_pgno += num;
760         } else {
761                 dp->p.mp_pgno = pgno;
762         }
763         mid.mid = dp->p.mp_pgno;
764         mid.mptr = dp;
765         mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
766
767         return dp;
768 }
769
770 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
771  */
772 static int
773 mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *pp)
774 {
775         MDB_page *mp = pp->mp_page;
776         pgno_t  pgno;
777         assert(txn != NULL);
778         assert(pp != NULL);
779
780         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
781                 MDB_dpage *dp;
782                 if ((dp = mdb_alloc_page(txn, dbi, pp->mp_parent, pp->mp_pi, 1)) == NULL)
783                         return ENOMEM;
784                 DPRINTF("touched db %u page %lu -> %lu", dbi, mp->mp_pgno, dp->p.mp_pgno);
785                 assert(mp->mp_pgno != dp->p.mp_pgno);
786                 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
787                 pgno = dp->p.mp_pgno;
788                 memcpy(&dp->p, mp, txn->mt_env->me_psize);
789                 mp = &dp->p;
790                 mp->mp_pgno = pgno;
791                 mp->mp_flags |= P_DIRTY;
792
793                 /* Update the page number to new touched page. */
794                 if (pp->mp_parent != NULL)
795                         NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
796                 pp->mp_page = mp;
797         }
798         return 0;
799 }
800
801 int
802 mdb_env_sync(MDB_env *env, int force)
803 {
804         int rc = 0;
805         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
806                 if (fdatasync(env->me_fd))
807                         rc = ErrCode();
808         }
809         return rc;
810 }
811
812 static inline void
813 mdb_txn_reset0(MDB_txn *txn);
814
815 static inline int
816 mdb_txn_renew0(MDB_txn *txn)
817 {
818         MDB_env *env = txn->mt_env;
819
820         if (txn->mt_flags & MDB_TXN_RDONLY) {
821                 MDB_reader *r = pthread_getspecific(env->me_txkey);
822                 if (!r) {
823                         unsigned int i;
824                         pid_t pid = getpid();
825                         pthread_t tid = pthread_self();
826
827                         LOCK_MUTEX_R(env);
828                         for (i=0; i<env->me_txns->mti_numreaders; i++)
829                                 if (env->me_txns->mti_readers[i].mr_pid == 0)
830                                         break;
831                         if (i == env->me_maxreaders) {
832                                 UNLOCK_MUTEX_R(env);
833                                 return ENOMEM;
834                         }
835                         env->me_txns->mti_readers[i].mr_pid = pid;
836                         env->me_txns->mti_readers[i].mr_tid = tid;
837                         if (i >= env->me_txns->mti_numreaders)
838                                 env->me_txns->mti_numreaders = i+1;
839                         UNLOCK_MUTEX_R(env);
840                         r = &env->me_txns->mti_readers[i];
841                         pthread_setspecific(env->me_txkey, r);
842                 }
843                 txn->mt_txnid = env->me_txns->mti_txnid;
844                 txn->mt_toggle = env->me_txns->mti_me_toggle;
845                 r->mr_txnid = txn->mt_txnid;
846                 txn->mt_u.reader = r;
847         } else {
848                 LOCK_MUTEX_W(env);
849
850                 txn->mt_txnid = env->me_txns->mti_txnid+1;
851                 txn->mt_toggle = env->me_txns->mti_me_toggle;
852                 txn->mt_u.dirty_list = env->me_dirty_list;
853                 txn->mt_u.dirty_list[0].mid = 0;
854                 txn->mt_free_pgs = env->me_free_pgs;
855                 txn->mt_free_pgs[0] = 0;
856                 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
857                 env->me_txn = txn;
858         }
859
860         /* Copy the DB arrays */
861         LAZY_RWLOCK_RDLOCK(&env->me_dblock);
862         txn->mt_numdbs = env->me_numdbs;
863         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
864         memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
865         if (txn->mt_numdbs > 2)
866                 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
867                         (txn->mt_numdbs - 2) * sizeof(MDB_db));
868         LAZY_RWLOCK_UNLOCK(&env->me_dblock);
869
870         return MDB_SUCCESS;
871 }
872
873 int
874 mdb_txn_renew(MDB_txn *txn)
875 {
876         int rc;
877
878         if (!txn)
879                 return EINVAL;
880
881         if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
882                 DPUTS("environment had fatal error, must shutdown!");
883                 return MDB_PANIC;
884         }
885
886         rc = mdb_txn_renew0(txn);
887         if (rc == MDB_SUCCESS) {
888                 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
889                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
890                         (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
891         }
892         return rc;
893 }
894
895 int
896 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
897 {
898         MDB_txn *txn;
899         int rc;
900
901         if (env->me_flags & MDB_FATAL_ERROR) {
902                 DPUTS("environment had fatal error, must shutdown!");
903                 return MDB_PANIC;
904         }
905         if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
906                 DPRINTF("calloc: %s", strerror(ErrCode()));
907                 return ENOMEM;
908         }
909         txn->mt_dbs = (MDB_db *)(txn+1);
910         if (flags & MDB_RDONLY) {
911                 txn->mt_flags |= MDB_TXN_RDONLY;
912         }
913         txn->mt_env = env;
914
915         rc = mdb_txn_renew0(txn);
916         if (rc)
917                 free(txn);
918         else {
919                 *ret = txn;
920                 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
921                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
922                         (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
923         }
924
925         return rc;
926 }
927
928 static inline void
929 mdb_txn_reset0(MDB_txn *txn)
930 {
931         MDB_env *env = txn->mt_env;
932
933         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
934                 txn->mt_u.reader->mr_txnid = 0;
935         } else {
936                 MDB_oldpages *mop;
937                 MDB_dpage *dp;
938                 unsigned int i;
939
940                 /* return all dirty pages to dpage list */
941                 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
942                         dp = txn->mt_u.dirty_list[i].mptr;
943                         if (dp->h.md_num == 1) {
944                                 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
945                                 txn->mt_env->me_dpages = dp;
946                         } else {
947                                 /* large pages just get freed directly */
948                                 free(dp);
949                         }
950                 }
951
952                 while ((mop = txn->mt_env->me_pghead)) {
953                         txn->mt_env->me_pghead = mop->mo_next;
954                         free(mop);
955                 }
956
957                 env->me_txn = NULL;
958                 for (i=2; i<env->me_numdbs; i++)
959                         env->me_dbxs[i].md_dirty = 0;
960                 UNLOCK_MUTEX_W(env);
961         }
962 }
963
964 void
965 mdb_txn_reset(MDB_txn *txn)
966 {
967         if (txn == NULL)
968                 return;
969
970         DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
971                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
972                 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
973
974         mdb_txn_reset0(txn);
975 }
976
977 void
978 mdb_txn_abort(MDB_txn *txn)
979 {
980         if (txn == NULL)
981                 return;
982
983         DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
984                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
985                 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
986
987         mdb_txn_reset0(txn);
988         free(txn);
989 }
990
991 int
992 mdb_txn_commit(MDB_txn *txn)
993 {
994         int              n, done;
995         unsigned int i;
996         ssize_t          rc;
997         off_t            size;
998         MDB_dpage       *dp;
999         MDB_env *env;
1000         pgno_t  next;
1001
1002         assert(txn != NULL);
1003         assert(txn->mt_env != NULL);
1004
1005         env = txn->mt_env;
1006
1007         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1008                 mdb_txn_abort(txn);
1009                 return MDB_SUCCESS;
1010         }
1011
1012         if (txn != env->me_txn) {
1013                 DPUTS("attempt to commit unknown transaction");
1014                 mdb_txn_abort(txn);
1015                 return EINVAL;
1016         }
1017
1018         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1019                 DPUTS("error flag is set, can't commit");
1020                 mdb_txn_abort(txn);
1021                 return EINVAL;
1022         }
1023
1024         if (!txn->mt_u.dirty_list[0].mid)
1025                 goto done;
1026
1027         DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
1028             txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1029
1030         /* should only be one record now */
1031         if (env->me_pghead) {
1032                 MDB_pageparent mpp;
1033
1034                 /* make sure first page of freeDB is touched and on freelist */
1035                 mpp.mp_parent = NULL;
1036                 mpp.mp_pi = 0;
1037                 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
1038         }
1039         /* save to free list */
1040         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1041                 MDB_val key, data;
1042                 MDB_pageparent mpp;
1043                 ULONG i;
1044
1045                 /* make sure last page of freeDB is touched and on freelist */
1046                 key.mv_size = MAXKEYSIZE+1;
1047                 key.mv_data = NULL;
1048                 mpp.mp_parent = NULL;
1049                 mpp.mp_pi = 0;
1050                 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
1051
1052 #if DEBUG > 1
1053                 {
1054                         unsigned int i;
1055                         ULONG *idl = txn->mt_free_pgs;
1056                         DPRINTF("IDL write txn %lu root %lu num %lu",
1057                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1058                         for (i=0; i<idl[0]; i++) {
1059                                 DPRINTF("IDL %lu", idl[i+1]);
1060                         }
1061                 }
1062 #endif
1063                 /* write to last page of freeDB */
1064                 key.mv_size = sizeof(pgno_t);
1065                 key.mv_data = (char *)&txn->mt_txnid;
1066                 data.mv_data = txn->mt_free_pgs;
1067                 /* The free list can still grow during this call,
1068                  * despite the pre-emptive touches above. So check
1069                  * and make sure the entire thing got written.
1070                  */
1071                 do {
1072                         i = txn->mt_free_pgs[0];
1073                         data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1074                         rc = mdb_put0(txn, FREE_DBI, &key, &data, 0);
1075                         if (rc) {
1076                                 mdb_txn_abort(txn);
1077                                 return rc;
1078                         }
1079                 } while (i != txn->mt_free_pgs[0]);
1080         }
1081         /* should only be one record now */
1082         if (env->me_pghead) {
1083                 MDB_val key, data;
1084                 MDB_oldpages *mop;
1085
1086                 mop = env->me_pghead;
1087                 key.mv_size = sizeof(pgno_t);
1088                 key.mv_data = (char *)&mop->mo_txnid;
1089                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1090                 data.mv_data = mop->mo_pages;
1091                 mdb_put0(txn, FREE_DBI, &key, &data, 0);
1092                 free(env->me_pghead);
1093                 env->me_pghead = NULL;
1094         }
1095
1096         /* Update DB root pointers. Their pages have already been
1097          * touched so this is all in-place and cannot fail.
1098          */
1099         {
1100                 MDB_val data;
1101                 data.mv_size = sizeof(MDB_db);
1102
1103                 for (i = 2; i < txn->mt_numdbs; i++) {
1104                         if (txn->mt_dbxs[i].md_dirty) {
1105                                 data.mv_data = &txn->mt_dbs[i];
1106                                 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
1107                         }
1108                 }
1109         }
1110
1111         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1112          */
1113         next = 0;
1114         i = 1;
1115         do {
1116 #ifdef _WIN32
1117                 /* Windows actually supports scatter/gather I/O, but only on
1118                  * unbuffered file handles. Since we're relying on the OS page
1119                  * cache for all our data, that's self-defeating. So we just
1120                  * write pages one at a time. We use the ov structure to set
1121                  * the write offset, to at least save the overhead of a Seek
1122                  * system call.
1123                  */
1124                 OVERLAPPED ov;
1125                 memset(&ov, 0, sizeof(ov));
1126                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1127                         dp = txn->mt_u.dirty_list[i].mptr;
1128                         DPRINTF("committing page %lu", dp->p.mp_pgno);
1129                         size = dp->p.mp_pgno * env->me_psize;
1130                         ov.Offset = size & 0xffffffff;
1131                         ov.OffsetHigh = size >> 16;
1132                         ov.OffsetHigh >>= 16;
1133                         /* clear dirty flag */
1134                         dp->p.mp_flags &= ~P_DIRTY;
1135                         rc = WriteFile(env->me_fd, &dp->p, env->me_psize * dp->h.md_num, NULL, &ov);
1136                         if (!rc) {
1137                                 n = ErrCode();
1138                                 DPRINTF("WriteFile: %d", n);
1139                                 mdb_txn_abort(txn);
1140                                 return n;
1141                         }
1142                 }
1143                 done = 1;;
1144 #else
1145                 struct iovec     iov[MDB_COMMIT_PAGES];
1146                 n = 0;
1147                 done = 1;
1148                 size = 0;
1149                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1150                         dp = txn->mt_u.dirty_list[i].mptr;
1151                         if (dp->p.mp_pgno != next) {
1152                                 if (n) {
1153                                         DPRINTF("committing %u dirty pages", n);
1154                                         rc = writev(env->me_fd, iov, n);
1155                                         if (rc != size) {
1156                                                 n = ErrCode();
1157                                                 if (rc > 0)
1158                                                         DPUTS("short write, filesystem full?");
1159                                                 else
1160                                                         DPRINTF("writev: %s", strerror(n));
1161                                                 mdb_txn_abort(txn);
1162                                                 return n;
1163                                         }
1164                                         n = 0;
1165                                         size = 0;
1166                                 }
1167                                 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1168                                 next = dp->p.mp_pgno;
1169                         }
1170                         DPRINTF("committing page %lu", dp->p.mp_pgno);
1171                         iov[n].iov_len = env->me_psize * dp->h.md_num;
1172                         iov[n].iov_base = &dp->p;
1173                         size += iov[n].iov_len;
1174                         next = dp->p.mp_pgno + dp->h.md_num;
1175                         /* clear dirty flag */
1176                         dp->p.mp_flags &= ~P_DIRTY;
1177                         if (++n >= MDB_COMMIT_PAGES) {
1178                                 done = 0;
1179                                 i++;
1180                                 break;
1181                         }
1182                 }
1183
1184                 if (n == 0)
1185                         break;
1186
1187                 DPRINTF("committing %u dirty pages", n);
1188                 rc = writev(env->me_fd, iov, n);
1189                 if (rc != size) {
1190                         n = ErrCode();
1191                         if (rc > 0)
1192                                 DPUTS("short write, filesystem full?");
1193                         else
1194                                 DPRINTF("writev: %s", strerror(n));
1195                         mdb_txn_abort(txn);
1196                         return n;
1197                 }
1198 #endif
1199         } while (!done);
1200
1201         /* Drop the dirty pages.
1202          */
1203         for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1204                 dp = txn->mt_u.dirty_list[i].mptr;
1205                 if (dp->h.md_num == 1) {
1206                         dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1207                         txn->mt_env->me_dpages = dp;
1208                 } else {
1209                         free(dp);
1210                 }
1211                 txn->mt_u.dirty_list[i].mid = 0;
1212         }
1213         txn->mt_u.dirty_list[0].mid = 0;
1214
1215         if ((n = mdb_env_sync(env, 0)) != 0 ||
1216             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1217                 mdb_txn_abort(txn);
1218                 return n;
1219         }
1220
1221 done:
1222         env->me_txn = NULL;
1223         /* update the DB tables */
1224         {
1225                 int toggle = !env->me_db_toggle;
1226                 MDB_db *ip, *jp;
1227
1228                 ip = &env->me_dbs[toggle][2];
1229                 jp = &txn->mt_dbs[2];
1230                 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1231                 for (i = 2; i < txn->mt_numdbs; i++) {
1232                         if (ip->md_root != jp->md_root)
1233                                 *ip = *jp;
1234                         ip++; jp++;
1235                 }
1236
1237                 for (i = 2; i < txn->mt_numdbs; i++) {
1238                         if (txn->mt_dbxs[i].md_dirty)
1239                                 txn->mt_dbxs[i].md_dirty = 0;
1240                 }
1241                 env->me_db_toggle = toggle;
1242                 env->me_numdbs = txn->mt_numdbs;
1243                 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1244         }
1245
1246         UNLOCK_MUTEX_W(env);
1247         free(txn);
1248
1249         return MDB_SUCCESS;
1250 }
1251
1252 static int
1253 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1254 {
1255         char             page[PAGESIZE];
1256         MDB_page        *p;
1257         MDB_meta        *m;
1258         int              rc, err;
1259
1260         /* We don't know the page size yet, so use a minimum value.
1261          */
1262
1263 #ifdef _WIN32
1264         if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1265 #else
1266         if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1267 #endif
1268         {
1269                 return ENOENT;
1270         }
1271         else if (rc != PAGESIZE) {
1272                 err = ErrCode();
1273                 if (rc > 0)
1274                         err = EINVAL;
1275                 DPRINTF("read: %s", strerror(err));
1276                 return err;
1277         }
1278
1279         p = (MDB_page *)page;
1280
1281         if (!F_ISSET(p->mp_flags, P_META)) {
1282                 DPRINTF("page %lu not a meta page", p->mp_pgno);
1283                 return EINVAL;
1284         }
1285
1286         m = METADATA(p);
1287         if (m->mm_magic != MDB_MAGIC) {
1288                 DPUTS("meta has invalid magic");
1289                 return EINVAL;
1290         }
1291
1292         if (m->mm_version != MDB_VERSION) {
1293                 DPRINTF("database is version %u, expected version %u",
1294                     m->mm_version, MDB_VERSION);
1295                 return MDB_VERSION_MISMATCH;
1296         }
1297
1298         memcpy(meta, m, sizeof(*m));
1299         return 0;
1300 }
1301
1302 static int
1303 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1304 {
1305         MDB_page *p, *q;
1306         MDB_meta *m;
1307         int rc;
1308         unsigned int     psize;
1309
1310         DPUTS("writing new meta page");
1311
1312         GetPageSize(psize);
1313
1314         meta->mm_magic = MDB_MAGIC;
1315         meta->mm_version = MDB_VERSION;
1316         meta->mm_psize = psize;
1317         meta->mm_last_pg = 1;
1318         meta->mm_flags = env->me_flags & 0xffff;
1319         meta->mm_flags |= MDB_INTEGERKEY;
1320         meta->mm_dbs[0].md_root = P_INVALID;
1321         meta->mm_dbs[1].md_root = P_INVALID;
1322
1323         p = calloc(2, psize);
1324         p->mp_pgno = 0;
1325         p->mp_flags = P_META;
1326
1327         m = METADATA(p);
1328         memcpy(m, meta, sizeof(*meta));
1329
1330         q = (MDB_page *)((char *)p + psize);
1331
1332         q->mp_pgno = 1;
1333         q->mp_flags = P_META;
1334
1335         m = METADATA(q);
1336         memcpy(m, meta, sizeof(*meta));
1337
1338 #ifdef _WIN32
1339         {
1340                 DWORD len;
1341                 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1342                 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1343         }
1344 #else
1345         rc = write(env->me_fd, p, psize * 2);
1346         rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1347 #endif
1348         free(p);
1349         return rc;
1350 }
1351
1352 static int
1353 mdb_env_write_meta(MDB_txn *txn)
1354 {
1355         MDB_env *env;
1356         MDB_meta        meta, metab;
1357         off_t off;
1358         int rc, len, toggle;
1359         char *ptr;
1360 #ifdef _WIN32
1361         OVERLAPPED ov;
1362 #endif
1363
1364         assert(txn != NULL);
1365         assert(txn->mt_env != NULL);
1366
1367         toggle = !txn->mt_toggle;
1368         DPRINTF("writing meta page %d for root page %lu",
1369                 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1370
1371         env = txn->mt_env;
1372
1373         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1374         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1375
1376         ptr = (char *)&meta;
1377         off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1378         len = sizeof(MDB_meta) - off;
1379
1380         ptr += off;
1381         meta.mm_dbs[0] = txn->mt_dbs[0];
1382         meta.mm_dbs[1] = txn->mt_dbs[1];
1383         meta.mm_last_pg = txn->mt_next_pgno - 1;
1384         meta.mm_txnid = txn->mt_txnid;
1385
1386         if (toggle)
1387                 off += env->me_psize;
1388         off += PAGEHDRSZ;
1389
1390         /* Write to the SYNC fd */
1391 #ifdef _WIN32
1392         {
1393                 memset(&ov, 0, sizeof(ov));
1394                 ov.Offset = off;
1395                 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1396         }
1397 #else
1398         rc = pwrite(env->me_mfd, ptr, len, off);
1399 #endif
1400         if (rc != len) {
1401                 int r2;
1402                 rc = ErrCode();
1403                 DPUTS("write failed, disk error?");
1404                 /* On a failure, the pagecache still contains the new data.
1405                  * Write some old data back, to prevent it from being used.
1406                  * Use the non-SYNC fd; we know it will fail anyway.
1407                  */
1408                 meta.mm_last_pg = metab.mm_last_pg;
1409                 meta.mm_txnid = metab.mm_txnid;
1410 #ifdef _WIN32
1411                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1412 #else
1413                 r2 = pwrite(env->me_fd, ptr, len, off);
1414 #endif
1415                 env->me_flags |= MDB_FATAL_ERROR;
1416                 return rc;
1417         }
1418         /* Memory ordering issues are irrelevant; since the entire writer
1419          * is wrapped by wmutex, all of these changes will become visible
1420          * after the wmutex is unlocked. Since the DB is multi-version,
1421          * readers will get consistent data regardless of how fresh or
1422          * how stale their view of these values is.
1423          */
1424         LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1425         txn->mt_env->me_txns->mti_me_toggle = toggle;
1426         txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1427         LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1428
1429         return MDB_SUCCESS;
1430 }
1431
1432 static int
1433 mdb_env_read_meta(MDB_env *env, int *which)
1434 {
1435         int toggle = 0;
1436
1437         assert(env != NULL);
1438
1439         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1440                 toggle = 1;
1441
1442         DPRINTF("Using meta page %d", toggle);
1443         *which = toggle;
1444
1445         return MDB_SUCCESS;
1446 }
1447
1448 int
1449 mdb_env_create(MDB_env **env)
1450 {
1451         MDB_env *e;
1452
1453         e = calloc(1, sizeof(MDB_env));
1454         if (!e) return ENOMEM;
1455
1456         e->me_maxreaders = DEFAULT_READERS;
1457         e->me_maxdbs = 2;
1458         e->me_fd = INVALID_HANDLE_VALUE;
1459         e->me_lfd = INVALID_HANDLE_VALUE;
1460         e->me_mfd = INVALID_HANDLE_VALUE;
1461         *env = e;
1462         return MDB_SUCCESS;
1463 }
1464
1465 int
1466 mdb_env_set_mapsize(MDB_env *env, size_t size)
1467 {
1468         if (env->me_map)
1469                 return EINVAL;
1470         env->me_mapsize = size;
1471         return MDB_SUCCESS;
1472 }
1473
1474 int
1475 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1476 {
1477         if (env->me_map)
1478                 return EINVAL;
1479         env->me_maxdbs = dbs;
1480         return MDB_SUCCESS;
1481 }
1482
1483 int
1484 mdb_env_set_maxreaders(MDB_env *env, int readers)
1485 {
1486         if (env->me_map)
1487                 return EINVAL;
1488         env->me_maxreaders = readers;
1489         return MDB_SUCCESS;
1490 }
1491
1492 int
1493 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1494 {
1495         if (!env || !readers)
1496                 return EINVAL;
1497         *readers = env->me_maxreaders;
1498         return MDB_SUCCESS;
1499 }
1500
1501 static int
1502 mdb_env_open2(MDB_env *env, unsigned int flags)
1503 {
1504         int i, newenv = 0, toggle;
1505         MDB_meta meta;
1506         MDB_page *p;
1507
1508         env->me_flags = flags;
1509
1510         memset(&meta, 0, sizeof(meta));
1511
1512         if ((i = mdb_env_read_header(env, &meta)) != 0) {
1513                 if (i != ENOENT)
1514                         return i;
1515                 DPUTS("new mdbenv");
1516                 newenv = 1;
1517         }
1518
1519         if (!env->me_mapsize) {
1520                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1521         }
1522
1523 #ifdef _WIN32
1524         {
1525                 HANDLE mh;
1526                 LONG sizelo, sizehi;
1527                 sizelo = env->me_mapsize & 0xffffffff;
1528                 sizehi = env->me_mapsize >> 16;         /* pointless on WIN32, only needed on W64 */
1529                 sizehi >>= 16;
1530                 /* Windows won't create mappings for zero length files.
1531                  * Just allocate the maxsize right now.
1532                  */
1533                 if (newenv) {
1534                         SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1535                         if (!SetEndOfFile(env->me_fd))
1536                                 return ErrCode();
1537                         SetFilePointer(env->me_fd, 0, NULL, 0);
1538                 }
1539                 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1540                         sizehi, sizelo, NULL);
1541                 if (!mh)
1542                         return ErrCode();
1543                 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1544                         meta.mm_address);
1545                 CloseHandle(mh);
1546                 if (!env->me_map)
1547                         return ErrCode();
1548         }
1549 #else
1550         i = MAP_SHARED;
1551         if (meta.mm_address && (flags & MDB_FIXEDMAP))
1552                 i |= MAP_FIXED;
1553         env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1554                 env->me_fd, 0);
1555         if (env->me_map == MAP_FAILED)
1556                 return ErrCode();
1557 #endif
1558
1559         if (newenv) {
1560                 meta.mm_mapsize = env->me_mapsize;
1561                 if (flags & MDB_FIXEDMAP)
1562                         meta.mm_address = env->me_map;
1563                 i = mdb_env_init_meta(env, &meta);
1564                 if (i != MDB_SUCCESS) {
1565                         munmap(env->me_map, env->me_mapsize);
1566                         return i;
1567                 }
1568         }
1569         env->me_psize = meta.mm_psize;
1570
1571         env->me_maxpg = env->me_mapsize / env->me_psize;
1572
1573         p = (MDB_page *)env->me_map;
1574         env->me_metas[0] = METADATA(p);
1575         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1576
1577         if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1578                 return i;
1579
1580         DPRINTF("opened database version %u, pagesize %u",
1581             env->me_metas[toggle]->mm_version, env->me_psize);
1582         DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1583         DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1584         DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1585         DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1586         DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1587         DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1588
1589         return MDB_SUCCESS;
1590 }
1591
1592 #ifndef _WIN32
1593 /* Windows doesn't support destructor callbacks for thread-specific storage */
1594 static void
1595 mdb_env_reader_dest(void *ptr)
1596 {
1597         MDB_reader *reader = ptr;
1598
1599         reader->mr_txnid = 0;
1600         reader->mr_pid = 0;
1601         reader->mr_tid = 0;
1602 }
1603 #endif
1604
1605 /* downgrade the exclusive lock on the region back to shared */
1606 static void
1607 mdb_env_share_locks(MDB_env *env)
1608 {
1609         int toggle = 0;
1610
1611         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1612                 toggle = 1;
1613         env->me_txns->mti_me_toggle = toggle;
1614         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1615
1616 #ifdef _WIN32
1617         {
1618                 OVERLAPPED ov;
1619                 /* First acquire a shared lock. The Unlock will
1620                  * then release the existing exclusive lock.
1621                  */
1622                 memset(&ov, 0, sizeof(ov));
1623                 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1624                 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1625         }
1626 #else
1627         {
1628                 struct flock lock_info;
1629                 /* The shared lock replaces the existing lock */
1630                 memset((void *)&lock_info, 0, sizeof(lock_info));
1631                 lock_info.l_type = F_RDLCK;
1632                 lock_info.l_whence = SEEK_SET;
1633                 lock_info.l_start = 0;
1634                 lock_info.l_len = 1;
1635                 fcntl(env->me_lfd, F_SETLK, &lock_info);
1636         }
1637 #endif
1638 }
1639
1640 static int
1641 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1642 {
1643         int rc;
1644         off_t size, rsize;
1645
1646         *excl = 0;
1647
1648 #ifdef _WIN32
1649         if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1650                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1651                 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1652                 rc = ErrCode();
1653                 return rc;
1654         }
1655         /* Try to get exclusive lock. If we succeed, then
1656          * nobody is using the lock region and we should initialize it.
1657          */
1658         {
1659                 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1660                         *excl = 1;
1661                 } else {
1662                         OVERLAPPED ov;
1663                         memset(&ov, 0, sizeof(ov));
1664                         if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
1665                                 rc = ErrCode();
1666                                 goto fail;
1667                         }
1668                 }
1669         }
1670         size = GetFileSize(env->me_lfd, NULL);
1671 #else
1672         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1673                 rc = ErrCode();
1674                 return rc;
1675         }
1676         /* Try to get exclusive lock. If we succeed, then
1677          * nobody is using the lock region and we should initialize it.
1678          */
1679         {
1680                 struct flock lock_info;
1681                 memset((void *)&lock_info, 0, sizeof(lock_info));
1682                 lock_info.l_type = F_WRLCK;
1683                 lock_info.l_whence = SEEK_SET;
1684                 lock_info.l_start = 0;
1685                 lock_info.l_len = 1;
1686                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1687                 if (rc == 0) {
1688                         *excl = 1;
1689                 } else {
1690                         lock_info.l_type = F_RDLCK;
1691                         rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
1692                         if (rc) {
1693                                 rc = ErrCode();
1694                                 goto fail;
1695                         }
1696                 }
1697         }
1698         size = lseek(env->me_lfd, 0, SEEK_END);
1699 #endif
1700         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1701         if (size < rsize && *excl) {
1702 #ifdef _WIN32
1703                 SetFilePointer(env->me_lfd, rsize, NULL, 0);
1704                 if (!SetEndOfFile(env->me_lfd)) {
1705                         rc = ErrCode();
1706                         goto fail;
1707                 }
1708 #else
1709                 if (ftruncate(env->me_lfd, rsize) != 0) {
1710                         rc = ErrCode();
1711                         goto fail;
1712                 }
1713 #endif
1714         } else {
1715                 rsize = size;
1716                 size = rsize - sizeof(MDB_txninfo);
1717                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1718         }
1719 #ifdef _WIN32
1720         {
1721                 HANDLE mh;
1722                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
1723                         0, 0, NULL);
1724                 if (!mh) {
1725                         rc = ErrCode();
1726                         goto fail;
1727                 }
1728                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
1729                 CloseHandle(mh);
1730                 if (!env->me_txns) {
1731                         rc = ErrCode();
1732                         goto fail;
1733                 }
1734         }
1735 #else
1736         env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1737                 env->me_lfd, 0);
1738         if (env->me_txns == MAP_FAILED) {
1739                 rc = ErrCode();
1740                 goto fail;
1741         }
1742 #endif
1743         if (*excl) {
1744 #ifdef _WIN32
1745                 char *ptr;
1746                 if (!mdb_sec_inited) {
1747                         InitializeSecurityDescriptor(&mdb_null_sd,
1748                                 SECURITY_DESCRIPTOR_REVISION);
1749                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
1750                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1751                         mdb_all_sa.bInheritHandle = FALSE;
1752                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
1753                         mdb_sec_inited = 1;
1754                 }
1755                 /* FIXME: only using up to 20 characters of the env path here,
1756                  * probably not enough to assure uniqueness...
1757                  */
1758                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
1759                 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
1760                 while ((ptr = strchr(ptr, '\\')))
1761                         *ptr++ = '/';
1762                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1763                 if (!env->me_rmutex) {
1764                         rc = ErrCode();
1765                         goto fail;
1766                 }
1767                 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
1768                 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
1769                 while ((ptr = strchr(ptr, '\\')))
1770                         *ptr++ = '/';
1771                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1772                 if (!env->me_wmutex) {
1773                         rc = ErrCode();
1774                         goto fail;
1775                 }
1776 #else
1777                 pthread_mutexattr_t mattr;
1778
1779                 pthread_mutexattr_init(&mattr);
1780                 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1781                 if (rc) {
1782                         goto fail;
1783                 }
1784                 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1785                 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1786 #endif
1787                 env->me_txns->mti_version = MDB_VERSION;
1788                 env->me_txns->mti_magic = MDB_MAGIC;
1789                 env->me_txns->mti_txnid = 0;
1790                 env->me_txns->mti_numreaders = 0;
1791                 env->me_txns->mti_me_toggle = 0;
1792
1793         } else {
1794                 if (env->me_txns->mti_magic != MDB_MAGIC) {
1795                         DPUTS("lock region has invalid magic");
1796                         rc = EINVAL;
1797                         goto fail;
1798                 }
1799                 if (env->me_txns->mti_version != MDB_VERSION) {
1800                         DPRINTF("lock region is version %u, expected version %u",
1801                                 env->me_txns->mti_version, MDB_VERSION);
1802                         rc = MDB_VERSION_MISMATCH;
1803                         goto fail;
1804                 }
1805                 rc = ErrCode();
1806                 if (rc != EACCES && rc != EAGAIN) {
1807                         goto fail;
1808                 }
1809 #ifdef _WIN32
1810                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
1811                 if (!env->me_rmutex) {
1812                         rc = ErrCode();
1813                         goto fail;
1814                 }
1815                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
1816                 if (!env->me_wmutex) {
1817                         rc = ErrCode();
1818                         goto fail;
1819                 }
1820 #endif
1821         }
1822         return MDB_SUCCESS;
1823
1824 fail:
1825         close(env->me_lfd);
1826         env->me_lfd = INVALID_HANDLE_VALUE;
1827         return rc;
1828
1829 }
1830
1831 #define LOCKNAME        "/lock.mdb"
1832 #define DATANAME        "/data.mdb"
1833 int
1834 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1835 {
1836         int             oflags, rc, len, excl;
1837         char *lpath, *dpath;
1838
1839         len = strlen(path);
1840         lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1841         if (!lpath)
1842                 return ENOMEM;
1843         dpath = lpath + len + sizeof(LOCKNAME);
1844         sprintf(lpath, "%s" LOCKNAME, path);
1845         sprintf(dpath, "%s" DATANAME, path);
1846
1847         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1848         if (rc)
1849                 goto leave;
1850
1851 #ifdef _WIN32
1852         if (F_ISSET(flags, MDB_RDONLY)) {
1853                 oflags = GENERIC_READ;
1854                 len = OPEN_EXISTING;
1855         } else {
1856                 oflags = GENERIC_READ|GENERIC_WRITE;
1857                 len = OPEN_ALWAYS;
1858         }
1859         mode = FILE_ATTRIBUTE_NORMAL;
1860         if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1861                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1862                 rc = ErrCode();
1863                 goto leave;
1864         }
1865 #else
1866         if (F_ISSET(flags, MDB_RDONLY))
1867                 oflags = O_RDONLY;
1868         else
1869                 oflags = O_RDWR | O_CREAT;
1870
1871         if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1872                 rc = ErrCode();
1873                 goto leave;
1874         }
1875 #endif
1876
1877         if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1878                 /* synchronous fd for meta writes */
1879 #ifdef _WIN32
1880                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1881                         mode |= FILE_FLAG_WRITE_THROUGH;
1882                 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1883                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1884                         rc = ErrCode();
1885                         goto leave;
1886                 }
1887 #else
1888                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1889                         oflags |= MDB_DSYNC;
1890                 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1891                         rc = ErrCode();
1892                         goto leave;
1893                 }
1894 #endif
1895                 env->me_path = strdup(path);
1896                 DPRINTF("opened dbenv %p", (void *) env);
1897                 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1898                 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1899                 if (excl)
1900                         mdb_env_share_locks(env);
1901                 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1902                 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1903                 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1904                 env->me_numdbs = 2;
1905         }
1906
1907 leave:
1908         if (rc) {
1909                 if (env->me_fd != INVALID_HANDLE_VALUE) {
1910                         close(env->me_fd);
1911                         env->me_fd = INVALID_HANDLE_VALUE;
1912                 }
1913                 if (env->me_lfd != INVALID_HANDLE_VALUE) {
1914                         close(env->me_lfd);
1915                         env->me_lfd = INVALID_HANDLE_VALUE;
1916                 }
1917         }
1918         free(lpath);
1919         return rc;
1920 }
1921
1922 void
1923 mdb_env_close(MDB_env *env)
1924 {
1925         MDB_dpage *dp;
1926
1927         if (env == NULL)
1928                 return;
1929
1930         while (env->me_dpages) {
1931                 dp = env->me_dpages;
1932                 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1933                 free(dp);
1934         }
1935
1936         free(env->me_dbs[1]);
1937         free(env->me_dbs[0]);
1938         free(env->me_dbxs);
1939         free(env->me_path);
1940
1941         LAZY_RWLOCK_DESTROY(&env->me_dblock);
1942         pthread_key_delete(env->me_txkey);
1943
1944         if (env->me_map) {
1945                 munmap(env->me_map, env->me_mapsize);
1946         }
1947         close(env->me_mfd);
1948         close(env->me_fd);
1949         if (env->me_txns) {
1950                 pid_t pid = getpid();
1951                 unsigned int i;
1952                 for (i=0; i<env->me_txns->mti_numreaders; i++)
1953                         if (env->me_txns->mti_readers[i].mr_pid == pid)
1954                                 env->me_txns->mti_readers[i].mr_pid = 0;
1955                 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
1956         }
1957         close(env->me_lfd);
1958         free(env);
1959 }
1960
1961 /* Search for key within a leaf page, using binary search.
1962  * Returns the smallest entry larger or equal to the key.
1963  * If exactp is non-null, stores whether the found entry was an exact match
1964  * in *exactp (1 or 0).
1965  * If kip is non-null, stores the index of the found entry in *kip.
1966  * If no entry larger or equal to the key is found, returns NULL.
1967  */
1968 static MDB_node *
1969 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1970     int *exactp, unsigned int *kip)
1971 {
1972         unsigned int     i = 0;
1973         int              low, high;
1974         int              rc = 0;
1975         MDB_node        *node = NULL;
1976         MDB_val  nodekey;
1977         DKBUF;
1978
1979         DPRINTF("searching %u keys in %s page %lu",
1980             NUMKEYS(mp),
1981             IS_LEAF(mp) ? "leaf" : "branch",
1982             mp->mp_pgno);
1983
1984         assert(NUMKEYS(mp) > 0);
1985
1986         memset(&nodekey, 0, sizeof(nodekey));
1987
1988         low = IS_LEAF(mp) ? 0 : 1;
1989         high = NUMKEYS(mp) - 1;
1990         while (low <= high) {
1991                 i = (low + high) >> 1;
1992
1993                 if (IS_LEAF2(mp)) {
1994                         nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
1995                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
1996                 } else {
1997                         node = NODEPTR(mp, i);
1998
1999                         nodekey.mv_size = node->mn_ksize;
2000                         nodekey.mv_data = NODEKEY(node);
2001                 }
2002
2003                 rc = mdb_cmp(txn, dbi, key, &nodekey);
2004
2005                 if (IS_LEAF(mp))
2006                         DPRINTF("found leaf index %u [%s], rc = %i",
2007                             i, DKEY(&nodekey), rc);
2008                 else
2009                         DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2010                             i, DKEY(&nodekey), NODEPGNO(node), rc);
2011
2012                 if (rc == 0)
2013                         break;
2014                 if (rc > 0)
2015                         low = i + 1;
2016                 else
2017                         high = i - 1;
2018         }
2019
2020         if (rc > 0) {   /* Found entry is less than the key. */
2021                 i++;    /* Skip to get the smallest entry larger than key. */
2022                 if (i >= NUMKEYS(mp))
2023                         /* There is no entry larger or equal to the key. */
2024                         return NULL;
2025         }
2026         if (exactp)
2027                 *exactp = (rc == 0);
2028         if (kip)        /* Store the key index if requested. */
2029                 *kip = i;
2030
2031         /* nodeptr is fake for LEAF2 */
2032         return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
2033 }
2034
2035 static void
2036 cursor_pop_page(MDB_cursor *cursor)
2037 {
2038         MDB_ppage       *top;
2039
2040         if (cursor->mc_snum) {
2041                 top = CURSOR_TOP(cursor);
2042                 cursor->mc_snum--;
2043
2044                 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
2045                         cursor->mc_dbi, (void *) cursor);
2046         }
2047 }
2048
2049 static MDB_ppage *
2050 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
2051 {
2052         MDB_ppage       *ppage;
2053
2054         DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2055                 cursor->mc_dbi, (void *) cursor);
2056
2057         assert(cursor->mc_snum < CURSOR_STACK);
2058
2059         ppage = &cursor->mc_stack[cursor->mc_snum++];
2060         ppage->mp_page = mp;
2061         ppage->mp_ki = 0;
2062         return ppage;
2063 }
2064
2065 static int
2066 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2067 {
2068         MDB_page *p = NULL;
2069
2070         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2071                 MDB_dpage *dp;
2072                 unsigned x;
2073                 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2074                 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2075                         dp = txn->mt_u.dirty_list[x].mptr;
2076                         p = &dp->p;
2077                 }
2078         }
2079         if (!p) {
2080                 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2081                         p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2082         }
2083         *ret = p;
2084         if (!p) {
2085                 DPRINTF("page %lu not found", pgno);
2086                 assert(p != NULL);
2087         }
2088         return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2089 }
2090
2091 static int
2092 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2093     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2094 {
2095         MDB_page        *mp = mpp->mp_page;
2096         DKBUF;
2097         int rc;
2098
2099         if (cursor && cursor_push_page(cursor, mp) == NULL)
2100                 return ENOMEM;
2101
2102         while (IS_BRANCH(mp)) {
2103                 unsigned int     i = 0;
2104                 MDB_node        *node;
2105
2106                 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2107                 assert(NUMKEYS(mp) > 1);
2108                 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2109
2110                 if (key == NULL)        /* Initialize cursor to first page. */
2111                         i = 0;
2112                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2113                                                         /* cursor to last page */
2114                         i = NUMKEYS(mp)-1;
2115                 } else {
2116                         int      exact;
2117                         node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
2118                         if (node == NULL)
2119                                 i = NUMKEYS(mp) - 1;
2120                         else if (!exact) {
2121                                 assert(i > 0);
2122                                 i--;
2123                         }
2124                 }
2125
2126                 if (key)
2127                         DPRINTF("following index %u for key [%s]",
2128                             i, DKEY(key));
2129                 assert(i < NUMKEYS(mp));
2130                 node = NODEPTR(mp, i);
2131
2132                 if (cursor)
2133                         CURSOR_TOP(cursor)->mp_ki = i;
2134
2135                 mpp->mp_parent = mp;
2136                 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
2137                         return rc;
2138                 mpp->mp_pi = i;
2139                 mpp->mp_page = mp;
2140
2141                 if (cursor && cursor_push_page(cursor, mp) == NULL)
2142                         return ENOMEM;
2143
2144                 if (modify) {
2145                         MDB_dhead *dh = ((MDB_dhead *)mp)-1;
2146                         if ((rc = mdb_touch(txn, dbi, mpp)) != 0)
2147                                 return rc;
2148                         dh = ((MDB_dhead *)mpp->mp_page)-1;
2149                         dh->md_parent = mpp->mp_parent;
2150                         dh->md_pi = mpp->mp_pi;
2151                 }
2152
2153                 mp = mpp->mp_page;
2154         }
2155
2156         if (!IS_LEAF(mp)) {
2157                 DPRINTF("internal error, index points to a %02X page!?",
2158                     mp->mp_flags);
2159                 return MDB_CORRUPTED;
2160         }
2161
2162         DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2163             key ? DKEY(key) : NULL);
2164
2165         return MDB_SUCCESS;
2166 }
2167
2168 /* Search for the page a given key should be in.
2169  * Stores a pointer to the found page in *mpp.
2170  * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2171  * If cursor is non-null, pushes parent pages on the cursor stack.
2172  * If modify is true, visited pages are updated with new page numbers.
2173  */
2174 static int
2175 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2176     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2177 {
2178         int              rc;
2179         pgno_t           root;
2180
2181         /* Choose which root page to start with. If a transaction is given
2182          * use the root page from the transaction, otherwise read the last
2183          * committed root page.
2184          */
2185         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2186                 DPUTS("transaction has failed, must abort");
2187                 return EINVAL;
2188         } else
2189                 root = txn->mt_dbs[dbi].md_root;
2190
2191         if (root == P_INVALID) {                /* Tree is empty. */
2192                 DPUTS("tree is empty");
2193                 return MDB_NOTFOUND;
2194         }
2195
2196         if ((rc = mdb_get_page(txn, root, &mpp->mp_page)))
2197                 return rc;
2198
2199         DPRINTF("db %u root page %lu has flags 0x%X",
2200                 dbi, root,  mpp->mp_page->mp_flags);
2201
2202         if (modify) {
2203                 /* For sub-databases, update main root first */
2204                 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
2205                         MDB_pageparent mp2;
2206                         rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
2207                                 NULL, 1, &mp2);
2208                         if (rc)
2209                                 return rc;
2210                         txn->mt_dbxs[dbi].md_dirty = 1;
2211                 }
2212                 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
2213                         mpp->mp_parent = NULL;
2214                         mpp->mp_pi = 0;
2215                         if ((rc = mdb_touch(txn, dbi, mpp)))
2216                                 return rc;
2217                         txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
2218                 }
2219         }
2220
2221         return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
2222 }
2223
2224 static int
2225 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2226 {
2227         MDB_page        *omp;           /* overflow mpage */
2228         pgno_t           pgno;
2229         int rc;
2230
2231         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2232                 data->mv_size = leaf->mn_dsize;
2233                 data->mv_data = NODEDATA(leaf);
2234                 return MDB_SUCCESS;
2235         }
2236
2237         /* Read overflow data.
2238          */
2239         data->mv_size = leaf->mn_dsize;
2240         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2241         if ((rc = mdb_get_page(txn, pgno, &omp))) {
2242                 DPRINTF("read overflow page %lu failed", pgno);
2243                 return rc;
2244         }
2245         data->mv_data = METADATA(omp);
2246
2247         return MDB_SUCCESS;
2248 }
2249
2250 int
2251 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2252     MDB_val *key, MDB_val *data)
2253 {
2254         int              rc, exact;
2255         MDB_node        *leaf;
2256         MDB_pageparent mpp;
2257         DKBUF;
2258
2259         assert(key);
2260         assert(data);
2261         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2262
2263         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2264                 return EINVAL;
2265
2266         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2267                 return EINVAL;
2268         }
2269
2270         if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
2271                 return rc;
2272
2273         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
2274         if (leaf && exact) {
2275                 /* Return first duplicate data item */
2276                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2277                         MDB_xcursor mx;
2278
2279                         mdb_xcursor_init0(txn, dbi, &mx);
2280                         mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
2281                         rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
2282                         if (rc != MDB_SUCCESS)
2283                                 return rc;
2284                         if (IS_LEAF2(mpp.mp_page)) {
2285                                 data->mv_size = txn->mt_dbs[dbi].md_pad;
2286                                 data->mv_data = LEAF2KEY(mpp.mp_page, 0, data->mv_size);
2287                         } else {
2288                                 leaf = NODEPTR(mpp.mp_page, 0);
2289                                 data->mv_size = NODEKSZ(leaf);
2290                                 data->mv_data = NODEKEY(leaf);
2291                         }
2292                 } else {
2293                         rc = mdb_read_data(txn, leaf, data);
2294                 }
2295         } else {
2296                 rc = MDB_NOTFOUND;
2297         }
2298
2299         return rc;
2300 }
2301
2302 static int
2303 mdb_sibling(MDB_cursor *cursor, int move_right)
2304 {
2305         int              rc;
2306         MDB_node        *indx;
2307         MDB_ppage       *parent;
2308         MDB_page        *mp;
2309
2310         if (cursor->mc_snum < 2) {
2311                 return MDB_NOTFOUND;            /* root has no siblings */
2312         }
2313         parent = CURSOR_PARENT(cursor);
2314
2315         DPRINTF("parent page is page %lu, index %u",
2316             parent->mp_page->mp_pgno, parent->mp_ki);
2317
2318         cursor_pop_page(cursor);
2319         if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
2320                        : (parent->mp_ki == 0)) {
2321                 DPRINTF("no more keys left, moving to %s sibling",
2322                     move_right ? "right" : "left");
2323                 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2324                         return rc;
2325                 parent = CURSOR_TOP(cursor);
2326         } else {
2327                 if (move_right)
2328                         parent->mp_ki++;
2329                 else
2330                         parent->mp_ki--;
2331                 DPRINTF("just moving to %s index key %u",
2332                     move_right ? "right" : "left", parent->mp_ki);
2333         }
2334         assert(IS_BRANCH(parent->mp_page));
2335
2336         indx = NODEPTR(parent->mp_page, parent->mp_ki);
2337         if ((rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp)))
2338                 return rc;;
2339 #if 0
2340         mp->parent = parent->mp_page;
2341         mp->parent_index = parent->mp_ki;
2342 #endif
2343
2344         cursor_push_page(cursor, mp);
2345
2346         return MDB_SUCCESS;
2347 }
2348
2349 static int
2350 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2351 {
2352         MDB_ppage       *top;
2353         MDB_page        *mp;
2354         MDB_node        *leaf;
2355         int rc;
2356
2357         if (cursor->mc_eof) {
2358                 return MDB_NOTFOUND;
2359         }
2360
2361         assert(cursor->mc_initialized);
2362
2363         top = CURSOR_TOP(cursor);
2364         mp = top->mp_page;
2365
2366         if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2367                 leaf = NODEPTR(mp, top->mp_ki);
2368                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2369                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2370                                 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2371                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2372                                         return rc;
2373                         }
2374                 } else {
2375                         cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2376                         if (op == MDB_NEXT_DUP)
2377                                 return MDB_NOTFOUND;
2378                 }
2379         }
2380
2381         DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2382
2383         if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2384                 DPUTS("=====> move to next sibling page");
2385                 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2386                         cursor->mc_eof = 1;
2387                         return MDB_NOTFOUND;
2388                 }
2389                 top = CURSOR_TOP(cursor);
2390                 mp = top->mp_page;
2391                 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2392         } else
2393                 top->mp_ki++;
2394
2395         DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2396             mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2397
2398         if (IS_LEAF2(mp)) {
2399                 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2400                 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2401                 return MDB_SUCCESS;
2402         }
2403
2404         assert(IS_LEAF(mp));
2405         leaf = NODEPTR(mp, top->mp_ki);
2406
2407         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2408                 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2409         }
2410         if (data) {
2411                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2412                         return rc;
2413
2414                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2415                         rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2416                         if (rc != MDB_SUCCESS)
2417                                 return rc;
2418                 }
2419         }
2420
2421         MDB_SET_KEY(leaf, key);
2422         return MDB_SUCCESS;
2423 }
2424
2425 static int
2426 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2427 {
2428         MDB_ppage       *top;
2429         MDB_page        *mp;
2430         MDB_node        *leaf;
2431         int rc;
2432
2433         assert(cursor->mc_initialized);
2434
2435         top = CURSOR_TOP(cursor);
2436         mp = top->mp_page;
2437
2438         if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2439                 leaf = NODEPTR(mp, top->mp_ki);
2440                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2441                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2442                                 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2443                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
2444                                         return rc;
2445                         } else {
2446                                 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2447                                 if (op == MDB_PREV_DUP)
2448                                         return MDB_NOTFOUND;
2449                         }
2450                 }
2451         }
2452
2453         DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2454
2455         if (top->mp_ki == 0)  {
2456                 DPUTS("=====> move to prev sibling page");
2457                 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2458                         cursor->mc_initialized = 0;
2459                         return MDB_NOTFOUND;
2460                 }
2461                 top = CURSOR_TOP(cursor);
2462                 mp = top->mp_page;
2463                 top->mp_ki = NUMKEYS(mp) - 1;
2464                 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2465         } else
2466                 top->mp_ki--;
2467
2468         cursor->mc_eof = 0;
2469
2470         DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2471             mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2472
2473         if (IS_LEAF2(mp)) {
2474                 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2475                 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2476                 return MDB_SUCCESS;
2477         }
2478
2479         assert(IS_LEAF(mp));
2480         leaf = NODEPTR(mp, top->mp_ki);
2481
2482         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2483                 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2484         }
2485         if (data) {
2486                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2487                         return rc;
2488
2489                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2490                         rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2491                         if (rc != MDB_SUCCESS)
2492                                 return rc;
2493                 }
2494         }
2495
2496         MDB_SET_KEY(leaf, key);
2497         return MDB_SUCCESS;
2498 }
2499
2500 static int
2501 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2502     MDB_cursor_op op, int *exactp)
2503 {
2504         int              rc;
2505         MDB_node        *leaf;
2506         MDB_ppage       *top;
2507         MDB_pageparent mpp;
2508         DKBUF;
2509
2510         assert(cursor);
2511         assert(key);
2512         assert(key->mv_size > 0);
2513
2514         /* See if we're already on the right page */
2515         if (cursor->mc_initialized) {
2516                 MDB_val nodekey;
2517                 top = CURSOR_TOP(cursor);
2518                 /* Don't try this for LEAF2 pages. Maybe support that later. */
2519                 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2520                         leaf = NODEPTR(top->mp_page, 0);
2521                         MDB_SET_KEY(leaf, &nodekey);
2522                         rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2523                         if (rc >= 0) {
2524                                 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2525                                 MDB_SET_KEY(leaf, &nodekey);
2526                                 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2527                                 if (rc <= 0) {
2528                                         /* we're already on the right page */
2529                                         mpp.mp_page = top->mp_page;
2530                                         rc = 0;
2531                                         goto set2;
2532                                 }
2533                         }
2534                 }
2535         }
2536         cursor->mc_snum = 0;
2537
2538         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2539         if (rc != MDB_SUCCESS)
2540                 return rc;
2541
2542         assert(IS_LEAF(mpp.mp_page));
2543
2544         top = CURSOR_TOP(cursor);
2545 set2:
2546         leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2547         if (exactp != NULL && !*exactp) {
2548                 /* MDB_SET specified and not an exact match. */
2549                 return MDB_NOTFOUND;
2550         }
2551
2552         if (leaf == NULL) {
2553                 DPUTS("===> inexact leaf not found, goto sibling");
2554                 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2555                         return rc;              /* no entries matched */
2556                 top = CURSOR_TOP(cursor);
2557                 top->mp_ki = 0;
2558                 mpp.mp_page = top->mp_page;
2559                 assert(IS_LEAF(mpp.mp_page));
2560                 leaf = NODEPTR(mpp.mp_page, 0);
2561         }
2562
2563         cursor->mc_initialized = 1;
2564         cursor->mc_eof = 0;
2565
2566         if (IS_LEAF2(mpp.mp_page)) {
2567                 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2568                 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2569                 return MDB_SUCCESS;
2570         }
2571
2572         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2573                 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2574         }
2575         if (data) {
2576                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2577                         if (op == MDB_SET || op == MDB_SET_RANGE) {
2578                                 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2579                         } else {
2580                                 int ex2, *ex2p;
2581                                 if (op == MDB_GET_BOTH) {
2582                                         ex2p = &ex2;
2583                                         ex2 = 0;
2584                                 } else {
2585                                         ex2p = NULL;
2586                                 }
2587                                 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2588                                 if (rc != MDB_SUCCESS)
2589                                         return rc;
2590                         }
2591                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2592                         MDB_val d2;
2593                         if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2594                                 return rc;
2595                         rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2596                         if (rc) {
2597                                 if (op == MDB_GET_BOTH || rc > 0)
2598                                         return MDB_NOTFOUND;
2599                         }
2600
2601                 } else {
2602                         if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2603                                 return rc;
2604                 }
2605         }
2606
2607         /* The key already matches in all other cases */
2608         if (op == MDB_SET_RANGE)
2609                 MDB_SET_KEY(leaf, key);
2610         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2611
2612         return rc;
2613 }
2614
2615 static int
2616 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2617 {
2618         int              rc;
2619         MDB_pageparent  mpp;
2620         MDB_node        *leaf;
2621
2622         cursor->mc_snum = 0;
2623
2624         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2625         if (rc != MDB_SUCCESS)
2626                 return rc;
2627         assert(IS_LEAF(mpp.mp_page));
2628
2629         leaf = NODEPTR(mpp.mp_page, 0);
2630         cursor->mc_initialized = 1;
2631         cursor->mc_eof = 0;
2632
2633         if (IS_LEAF2(mpp.mp_page)) {
2634                 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2635                 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2636                 return MDB_SUCCESS;
2637         }
2638
2639         if (data) {
2640                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2641                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2642                         rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2643                         if (rc)
2644                                 return rc;
2645                 } else {
2646                         if (cursor->mc_xcursor)
2647                                 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2648                         if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2649                                 return rc;
2650                 }
2651         }
2652         MDB_SET_KEY(leaf, key);
2653         return MDB_SUCCESS;
2654 }
2655
2656 static int
2657 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2658 {
2659         int              rc;
2660         MDB_ppage       *top;
2661         MDB_pageparent  mpp;
2662         MDB_node        *leaf;
2663         MDB_val lkey;
2664
2665         cursor->mc_snum = 0;
2666
2667         lkey.mv_size = MAXKEYSIZE+1;
2668         lkey.mv_data = NULL;
2669
2670         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2671         if (rc != MDB_SUCCESS)
2672                 return rc;
2673         assert(IS_LEAF(mpp.mp_page));
2674
2675         leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2676         cursor->mc_initialized = 1;
2677         cursor->mc_eof = 0;
2678
2679         top = CURSOR_TOP(cursor);
2680         top->mp_ki = NUMKEYS(top->mp_page) - 1;
2681
2682         if (IS_LEAF2(mpp.mp_page)) {
2683                 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2684                 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2685                 return MDB_SUCCESS;
2686         }
2687
2688         if (data) {
2689                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2690                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2691                         rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2692                         if (rc)
2693                                 return rc;
2694                 } else {
2695                         if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2696                                 return rc;
2697                 }
2698         }
2699
2700         MDB_SET_KEY(leaf, key);
2701         return MDB_SUCCESS;
2702 }
2703
2704 int
2705 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2706     MDB_cursor_op op)
2707 {
2708         int              rc;
2709         int              exact = 0;
2710
2711         assert(cursor);
2712
2713         switch (op) {
2714         case MDB_GET_BOTH:
2715         case MDB_GET_BOTH_RANGE:
2716                 if (data == NULL || cursor->mc_xcursor == NULL) {
2717                         rc = EINVAL;
2718                         break;
2719                 }
2720                 /* FALLTHRU */
2721         case MDB_SET:
2722         case MDB_SET_RANGE:
2723                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2724                         rc = EINVAL;
2725                 } else if (op == MDB_SET_RANGE)
2726                         rc = mdb_cursor_set(cursor, key, data, op, NULL);
2727                 else
2728                         rc = mdb_cursor_set(cursor, key, data, op, &exact);
2729                 break;
2730         case MDB_GET_MULTIPLE:
2731                 if (data == NULL ||
2732                         !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2733                         !cursor->mc_initialized) {
2734                         rc = EINVAL;
2735                         break;
2736                 }
2737                 rc = MDB_SUCCESS;
2738                 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2739                         break;
2740                 goto fetchm;
2741         case MDB_NEXT_MULTIPLE:
2742                 if (data == NULL ||
2743                         !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2744                         rc = EINVAL;
2745                         break;
2746                 }
2747                 if (!cursor->mc_initialized)
2748                         rc = mdb_cursor_first(cursor, key, data);
2749                 else
2750                         rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2751                 if (rc == MDB_SUCCESS) {
2752                         if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2753                                 MDB_ppage       *top;
2754 fetchm:
2755                                 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2756                                 data->mv_size = NUMKEYS(top->mp_page) *
2757                                         cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2758                                 data->mv_data = METADATA(top->mp_page);
2759                                 top->mp_ki = NUMKEYS(top->mp_page)-1;
2760                         } else {
2761                                 rc = MDB_NOTFOUND;
2762                         }
2763                 }
2764                 break;
2765         case MDB_NEXT:
2766         case MDB_NEXT_DUP:
2767         case MDB_NEXT_NODUP:
2768                 if (!cursor->mc_initialized)
2769                         rc = mdb_cursor_first(cursor, key, data);
2770                 else
2771                         rc = mdb_cursor_next(cursor, key, data, op);
2772                 break;
2773         case MDB_PREV:
2774         case MDB_PREV_DUP:
2775         case MDB_PREV_NODUP:
2776                 if (!cursor->mc_initialized || cursor->mc_eof)
2777                         rc = mdb_cursor_last(cursor, key, data);
2778                 else
2779                         rc = mdb_cursor_prev(cursor, key, data, op);
2780                 break;
2781         case MDB_FIRST:
2782                 rc = mdb_cursor_first(cursor, key, data);
2783                 break;
2784         case MDB_LAST:
2785                 rc = mdb_cursor_last(cursor, key, data);
2786                 break;
2787         default:
2788                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2789                 rc = EINVAL;
2790                 break;
2791         }
2792
2793         return rc;
2794 }
2795
2796 /* Allocate a page and initialize it
2797  */
2798 static MDB_dpage *
2799 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2800 {
2801         MDB_dpage       *dp;
2802
2803         if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
2804                 return NULL;
2805         DPRINTF("allocated new mpage %lu, page size %u",
2806             dp->p.mp_pgno, txn->mt_env->me_psize);
2807         dp->p.mp_flags = flags | P_DIRTY;
2808         dp->p.mp_lower = PAGEHDRSZ;
2809         dp->p.mp_upper = txn->mt_env->me_psize;
2810
2811         if (IS_BRANCH(&dp->p))
2812                 txn->mt_dbs[dbi].md_branch_pages++;
2813         else if (IS_LEAF(&dp->p))
2814                 txn->mt_dbs[dbi].md_leaf_pages++;
2815         else if (IS_OVERFLOW(&dp->p)) {
2816                 txn->mt_dbs[dbi].md_overflow_pages += num;
2817                 dp->p.mp_pages = num;
2818         }
2819
2820         return dp;
2821 }
2822
2823 static size_t
2824 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2825 {
2826         size_t           sz;
2827
2828         sz = LEAFSIZE(key, data);
2829         if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2830                 /* put on overflow page */
2831                 sz -= data->mv_size - sizeof(pgno_t);
2832         }
2833
2834         return sz + sizeof(indx_t);
2835 }
2836
2837 static size_t
2838 mdb_branch_size(MDB_env *env, MDB_val *key)
2839 {
2840         size_t           sz;
2841
2842         sz = INDXSIZE(key);
2843         if (sz >= env->me_psize / MDB_MINKEYS) {
2844                 /* put on overflow page */
2845                 /* not implemented */
2846                 /* sz -= key->size - sizeof(pgno_t); */
2847         }
2848
2849         return sz + sizeof(indx_t);
2850 }
2851
2852 static int
2853 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2854     MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2855 {
2856         unsigned int     i;
2857         size_t           node_size = NODESIZE;
2858         indx_t           ofs;
2859         MDB_node        *node;
2860         MDB_dpage       *ofp = NULL;            /* overflow page */
2861         DKBUF;
2862
2863         assert(mp->mp_upper >= mp->mp_lower);
2864
2865         DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
2866             IS_LEAF(mp) ? "leaf" : "branch",
2867             mp->mp_pgno, indx, data ? data->mv_size : 0,
2868                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
2869
2870         if (IS_LEAF2(mp)) {
2871                 /* Move higher keys up one slot. */
2872                 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2873                 char *ptr = LEAF2KEY(mp, indx, ksize);
2874                 dif = NUMKEYS(mp) - indx;
2875                 if (dif > 0)
2876                         memmove(ptr+ksize, ptr, dif*ksize);
2877                 /* insert new key */
2878                 memcpy(ptr, key->mv_data, ksize);
2879
2880                 /* Just using these for counting */
2881                 mp->mp_lower += sizeof(indx_t);
2882                 mp->mp_upper -= ksize - sizeof(indx_t);
2883                 return MDB_SUCCESS;
2884         }
2885
2886         if (key != NULL)
2887                 node_size += key->mv_size;
2888
2889         if (IS_LEAF(mp)) {
2890                 assert(data);
2891                 if (F_ISSET(flags, F_BIGDATA)) {
2892                         /* Data already on overflow page. */
2893                         node_size += sizeof(pgno_t);
2894                 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2895                         int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2896                         /* Put data on overflow page. */
2897                         DPRINTF("data size is %zu, put on overflow page",
2898                             data->mv_size);
2899                         node_size += sizeof(pgno_t);
2900                         if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2901                                 return ENOMEM;
2902                         DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2903                         flags |= F_BIGDATA;
2904                 } else {
2905                         node_size += data->mv_size;
2906                 }
2907         }
2908
2909         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2910                 DPRINTF("not enough room in page %lu, got %u ptrs",
2911                     mp->mp_pgno, NUMKEYS(mp));
2912                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2913                     mp->mp_upper - mp->mp_lower);
2914                 DPRINTF("node size = %zu", node_size);
2915                 return ENOSPC;
2916         }
2917
2918         /* Move higher pointers up one slot. */
2919         for (i = NUMKEYS(mp); i > indx; i--)
2920                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2921
2922         /* Adjust free space offsets. */
2923         ofs = mp->mp_upper - node_size;
2924         assert(ofs >= mp->mp_lower + sizeof(indx_t));
2925         mp->mp_ptrs[indx] = ofs;
2926         mp->mp_upper = ofs;
2927         mp->mp_lower += sizeof(indx_t);
2928
2929         /* Write the node data. */
2930         node = NODEPTR(mp, indx);
2931         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2932         node->mn_flags = flags;
2933         if (IS_LEAF(mp))
2934                 node->mn_dsize = data->mv_size;
2935         else
2936                 NODEPGNO(node) = pgno;
2937
2938         if (key)
2939                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2940
2941         if (IS_LEAF(mp)) {
2942                 assert(key);
2943                 if (ofp == NULL) {
2944                         if (F_ISSET(flags, F_BIGDATA))
2945                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
2946                                     sizeof(pgno_t));
2947                         else
2948                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
2949                                     data->mv_size);
2950                 } else {
2951                         memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2952                             sizeof(pgno_t));
2953                         memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2954                 }
2955         }
2956
2957         return MDB_SUCCESS;
2958 }
2959
2960 static void
2961 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2962 {
2963         unsigned int     sz;
2964         indx_t           i, j, numkeys, ptr;
2965         MDB_node        *node;
2966         char            *base;
2967
2968         DPRINTF("delete node %u on %s page %lu", indx,
2969             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2970         assert(indx < NUMKEYS(mp));
2971
2972         if (IS_LEAF2(mp)) {
2973                 int x = NUMKEYS(mp) - 1 - indx;
2974                 base = LEAF2KEY(mp, indx, ksize);
2975                 if (x)
2976                         memmove(base, base + ksize, x * ksize);
2977                 mp->mp_lower -= sizeof(indx_t);
2978                 mp->mp_upper += ksize - sizeof(indx_t);
2979                 return;
2980         }
2981
2982         node = NODEPTR(mp, indx);
2983         sz = NODESIZE + node->mn_ksize;
2984         if (IS_LEAF(mp)) {
2985                 if (F_ISSET(node->mn_flags, F_BIGDATA))
2986                         sz += sizeof(pgno_t);
2987                 else
2988                         sz += NODEDSZ(node);
2989         }
2990
2991         ptr = mp->mp_ptrs[indx];
2992         numkeys = NUMKEYS(mp);
2993         for (i = j = 0; i < numkeys; i++) {
2994                 if (i != indx) {
2995                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
2996                         if (mp->mp_ptrs[i] < ptr)
2997                                 mp->mp_ptrs[j] += sz;
2998                         j++;
2999                 }
3000         }
3001
3002         base = (char *)mp + mp->mp_upper;
3003         memmove(base + sz, base, ptr - mp->mp_upper);
3004
3005         mp->mp_lower -= sizeof(indx_t);
3006         mp->mp_upper += sz;
3007 }
3008
3009 static void
3010 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3011 {
3012         MDB_dbi dbn;
3013
3014         mx->mx_txn = *txn;
3015         mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3016         mx->mx_txn.mt_dbs = mx->mx_dbs;
3017         mx->mx_dbxs[0] = txn->mt_dbxs[0];
3018         mx->mx_dbxs[1] = txn->mt_dbxs[1];
3019         if (dbi > 1) {
3020                 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
3021                 dbn = 2;
3022         } else {
3023                 dbn = 1;
3024         }
3025         mx->mx_dbxs[dbn+1].md_parent = dbn;
3026         mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3027         mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3028         mx->mx_dbxs[dbn+1].md_dirty = 0;
3029         mx->mx_txn.mt_numdbs = dbn+2;
3030
3031         mx->mx_cursor.mc_snum = 0;
3032         mx->mx_cursor.mc_txn = &mx->mx_txn;
3033         mx->mx_cursor.mc_dbi = dbn+1;
3034 }
3035
3036 static void
3037 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
3038 {
3039         MDB_db *db = NODEDATA(node);
3040         MDB_dbi dbn;
3041         mx->mx_dbs[0] = txn->mt_dbs[0];
3042         mx->mx_dbs[1] = txn->mt_dbs[1];
3043         if (dbi > 1) {
3044                 mx->mx_dbs[2] = txn->mt_dbs[dbi];
3045                 dbn = 3;
3046         } else {
3047                 dbn = 2;
3048         }
3049         DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
3050         mx->mx_dbs[dbn] = *db;
3051         if (F_ISSET(mp->mp_flags, P_DIRTY))
3052                 mx->mx_dbxs[dbn].md_dirty = 1;
3053         mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3054         mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3055         mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
3056         mx->mx_txn.mt_u = txn->mt_u;
3057         mx->mx_cursor.mc_initialized = 0;
3058         mx->mx_cursor.mc_eof = 0;
3059 }
3060
3061 static void
3062 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3063 {
3064         txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3065         txn->mt_u = mx->mx_txn.mt_u;
3066         txn->mt_dbs[0] = mx->mx_dbs[0];
3067         txn->mt_dbs[1] = mx->mx_dbs[1];
3068         txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
3069         txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
3070         if (dbi > 1) {
3071                 txn->mt_dbs[dbi] = mx->mx_dbs[2];
3072                 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3073         }
3074 }
3075
3076 int
3077 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3078 {
3079         MDB_cursor      *cursor;
3080         size_t size = sizeof(MDB_cursor);
3081
3082         if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3083                 return EINVAL;
3084
3085         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3086                 size += sizeof(MDB_xcursor);
3087
3088         if ((cursor = calloc(1, size)) != NULL) {
3089                 cursor->mc_dbi = dbi;
3090                 cursor->mc_txn = txn;
3091                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3092                         MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
3093                         cursor->mc_xcursor = mx;
3094                         mdb_xcursor_init0(txn, dbi, mx);
3095                 }
3096         } else {
3097                 return ENOMEM;
3098         }
3099
3100         *ret = cursor;
3101
3102         return MDB_SUCCESS;
3103 }
3104
3105 /* Return the count of duplicate data items for the current key */
3106 int
3107 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3108 {
3109         MDB_ppage       *top;
3110         MDB_node        *leaf;
3111
3112         if (mc == NULL || countp == NULL)
3113                 return EINVAL;
3114
3115         if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3116                 return EINVAL;
3117
3118         top = CURSOR_TOP(mc);
3119         leaf = NODEPTR(top->mp_page, top->mp_ki);
3120         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3121                 *countp = 1;
3122         } else {
3123                 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
3124                         return EINVAL;
3125
3126                 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3127         }
3128         return MDB_SUCCESS;
3129 }
3130
3131 void
3132 mdb_cursor_close(MDB_cursor *cursor)
3133 {
3134         if (cursor != NULL) {
3135                 free(cursor);
3136         }
3137 }
3138
3139 static int
3140 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3141 {
3142         indx_t                   ptr, i, numkeys;
3143         int                      delta;
3144         size_t                   len;
3145         MDB_node                *node;
3146         char                    *base;
3147         DKBUF;
3148
3149         node = NODEPTR(mp, indx);
3150         ptr = mp->mp_ptrs[indx];
3151         DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3152             indx, ptr,
3153             (int)node->mn_ksize, (char *)NODEKEY(node),
3154                 DKEY(key),
3155             mp->mp_pgno);
3156
3157         delta = key->mv_size - node->mn_ksize;
3158         if (delta) {
3159                 if (delta > 0 && SIZELEFT(mp) < delta) {
3160                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
3161                         return ENOSPC;
3162                 }
3163
3164                 numkeys = NUMKEYS(mp);
3165                 for (i = 0; i < numkeys; i++) {
3166                         if (mp->mp_ptrs[i] <= ptr)
3167                                 mp->mp_ptrs[i] -= delta;
3168                 }
3169
3170                 base = (char *)mp + mp->mp_upper;
3171                 len = ptr - mp->mp_upper + NODESIZE;
3172                 memmove(base - delta, base, len);
3173                 mp->mp_upper -= delta;
3174
3175                 node = NODEPTR(mp, indx);
3176                 node->mn_ksize = key->mv_size;
3177         }
3178
3179         memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3180
3181         return MDB_SUCCESS;
3182 }
3183
3184 /* Move a node from src to dst.
3185  */
3186 static int
3187 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
3188     MDB_pageparent *dst, indx_t dstindx)
3189 {
3190         int                      rc;
3191         MDB_node                *srcnode;
3192         MDB_val          key, data;
3193         DKBUF;
3194
3195         /* Mark src and dst as dirty. */
3196         if ((rc = mdb_touch(txn, dbi, src)) ||
3197             (rc = mdb_touch(txn, dbi, dst)))
3198                 return rc;;
3199
3200         if (IS_LEAF2(src->mp_page)) {
3201                 srcnode = NODEPTR(src->mp_page, 0);     /* fake */
3202                 key.mv_size = txn->mt_dbs[dbi].md_pad;
3203                 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3204                 data.mv_size = 0;
3205                 data.mv_data = NULL;
3206         } else {
3207                 srcnode = NODEPTR(src->mp_page, srcindx);
3208                 key.mv_size = NODEKSZ(srcnode);
3209                 key.mv_data = NODEKEY(srcnode);
3210                 data.mv_size = NODEDSZ(srcnode);
3211                 data.mv_data = NODEDATA(srcnode);
3212         }
3213         DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3214             IS_LEAF(src->mp_page) ? "leaf" : "branch",
3215             srcindx,
3216                 DKEY(&key),
3217             src->mp_page->mp_pgno,
3218             dstindx, dst->mp_page->mp_pgno);
3219
3220         /* Add the node to the destination page.
3221          */
3222         rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
3223             srcnode->mn_flags);
3224         if (rc != MDB_SUCCESS)
3225                 return rc;
3226
3227         /* Delete the node from the source page.
3228          */
3229         mdb_del_node(src->mp_page, srcindx, key.mv_size);
3230
3231         /* The key value just changed due to del_node, find it again.
3232          */
3233         if (!IS_LEAF2(src->mp_page)) {
3234                 srcnode = NODEPTR(src->mp_page, srcindx);
3235                 key.mv_data = NODEKEY(srcnode);
3236         }
3237
3238         /* Update the parent separators.
3239          */
3240         if (srcindx == 0) {
3241                 if (src->mp_pi != 0) {
3242                         DPRINTF("update separator for source page %lu to [%s]",
3243                                 src->mp_page->mp_pgno, DKEY(&key));
3244                         if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
3245                                 &key)) != MDB_SUCCESS)
3246                                 return rc;
3247                 }
3248                 if (IS_BRANCH(src->mp_page)) {
3249                         MDB_val  nullkey;
3250                         nullkey.mv_size = 0;
3251                         assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
3252                 }
3253         }
3254
3255         if (dstindx == 0) {
3256                 if (dst->mp_pi != 0) {
3257                         DPRINTF("update separator for destination page %lu to [%s]",
3258                                 dst->mp_page->mp_pgno, DKEY(&key));
3259                         if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
3260                                 &key)) != MDB_SUCCESS)
3261                                 return rc;
3262                 }
3263                 if (IS_BRANCH(dst->mp_page)) {
3264                         MDB_val  nullkey;
3265                         nullkey.mv_size = 0;
3266                         assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
3267                 }
3268         }
3269
3270         return MDB_SUCCESS;
3271 }
3272
3273 static int
3274 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
3275 {
3276         int                      rc;
3277         indx_t                   i;
3278         MDB_node                *srcnode;
3279         MDB_val          key, data;
3280         MDB_pageparent  mpp;
3281         MDB_dhead *dh;
3282
3283         DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
3284
3285         assert(txn != NULL);
3286         assert(src->mp_parent); /* can't merge root page */
3287         assert(dst->mp_parent);
3288
3289         /* Mark src and dst as dirty. */
3290         if ((rc = mdb_touch(txn, dbi, src)) ||
3291             (rc = mdb_touch(txn, dbi, dst)))
3292                 return rc;
3293
3294         /* Move all nodes from src to dst.
3295          */
3296         if (IS_LEAF2(src->mp_page)) {
3297                 key.mv_size = txn->mt_dbs[dbi].md_pad;
3298                 key.mv_data = METADATA(src->mp_page);
3299                 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3300                         rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3301                                 NULL, 0, 0);
3302                         if (rc != MDB_SUCCESS)
3303                                 return rc;
3304                         key.mv_data = (char *)key.mv_data + key.mv_size;
3305                 }
3306         } else {
3307                 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3308                         srcnode = NODEPTR(src->mp_page, i);
3309
3310                         key.mv_size = srcnode->mn_ksize;
3311                         key.mv_data = NODEKEY(srcnode);
3312                         data.mv_size = NODEDSZ(srcnode);
3313                         data.mv_data = NODEDATA(srcnode);
3314                         rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3315                                 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3316                         if (rc != MDB_SUCCESS)
3317                                 return rc;
3318                 }
3319         }
3320
3321         DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3322             dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3323
3324         /* Unlink the src page from parent.
3325          */
3326         mdb_del_node(src->mp_parent, src->mp_pi, 0);
3327         if (src->mp_pi == 0) {
3328                 key.mv_size = 0;
3329                 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3330                         return rc;
3331         }
3332
3333         if (IS_LEAF(src->mp_page))
3334                 txn->mt_dbs[dbi].md_leaf_pages--;
3335         else
3336                 txn->mt_dbs[dbi].md_branch_pages--;
3337
3338         mpp.mp_page = src->mp_parent;
3339         dh = (MDB_dhead *)src->mp_parent;
3340         dh--;
3341         mpp.mp_parent = dh->md_parent;
3342         mpp.mp_pi = dh->md_pi;
3343
3344         return mdb_rebalance(txn, dbi, &mpp);
3345 }
3346
3347 #define FILL_THRESHOLD   250
3348
3349 static int
3350 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3351 {
3352         MDB_node        *node;
3353         MDB_page        *root;
3354         MDB_pageparent npp;
3355         indx_t           si = 0, di = 0;
3356         int rc;
3357
3358         assert(txn != NULL);
3359         assert(mpp != NULL);
3360
3361         DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3362             IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3363             mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3364
3365         if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3366                 DPRINTF("no need to rebalance page %lu, above fill threshold",
3367                     mpp->mp_page->mp_pgno);
3368                 return MDB_SUCCESS;
3369         }
3370
3371         if (mpp->mp_parent == NULL) {
3372                 if (NUMKEYS(mpp->mp_page) == 0) {
3373                         DPUTS("tree is completely empty");
3374                         txn->mt_dbs[dbi].md_root = P_INVALID;
3375                         txn->mt_dbs[dbi].md_depth = 0;
3376                         txn->mt_dbs[dbi].md_leaf_pages = 0;
3377                 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3378                         DPUTS("collapsing root page!");
3379                         txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3380                         if ((rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root)))
3381                                 return rc;
3382                         txn->mt_dbs[dbi].md_depth--;
3383                         txn->mt_dbs[dbi].md_branch_pages--;
3384                 } else
3385                         DPUTS("root page doesn't need rebalancing");
3386                 return MDB_SUCCESS;
3387         }
3388
3389         /* The parent (branch page) must have at least 2 pointers,
3390          * otherwise the tree is invalid.
3391          */
3392         assert(NUMKEYS(mpp->mp_parent) > 1);
3393
3394         /* Leaf page fill factor is below the threshold.
3395          * Try to move keys from left or right neighbor, or
3396          * merge with a neighbor page.
3397          */
3398
3399         /* Find neighbors.
3400          */
3401         if (mpp->mp_pi == 0) {
3402                 /* We're the leftmost leaf in our parent.
3403                  */
3404                 DPUTS("reading right neighbor");
3405                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3406                 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3407                         return rc;
3408                 npp.mp_pi = mpp->mp_pi + 1;
3409                 si = 0;
3410                 di = NUMKEYS(mpp->mp_page);
3411         } else {
3412                 /* There is at least one neighbor to the left.
3413                  */
3414                 DPUTS("reading left neighbor");
3415                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3416                 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3417                         return rc;
3418                 npp.mp_pi = mpp->mp_pi - 1;
3419                 si = NUMKEYS(npp.mp_page) - 1;
3420                 di = 0;
3421         }
3422         npp.mp_parent = mpp->mp_parent;
3423
3424         DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3425             npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3426
3427         /* If the neighbor page is above threshold and has at least two
3428          * keys, move one key from it.
3429          *
3430          * Otherwise we should try to merge them.
3431          */
3432         if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3433                 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3434         else { /* FIXME: if (has_enough_room()) */
3435                 if (mpp->mp_pi == 0)
3436                         return mdb_merge(txn, dbi, &npp, mpp);
3437                 else
3438                         return mdb_merge(txn, dbi, mpp, &npp);
3439         }
3440 }
3441
3442 static int
3443 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3444 {
3445         int rc;
3446
3447         /* add overflow pages to free list */
3448         if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3449                 int i, ovpages;
3450                 pgno_t pg;
3451
3452                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3453                 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3454                 for (i=0; i<ovpages; i++) {
3455                         DPRINTF("freed ov page %lu", pg);
3456                         mdb_midl_insert(txn->mt_free_pgs, pg);
3457                         pg++;
3458                 }
3459         }
3460         mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3461         txn->mt_dbs[dbi].md_entries--;
3462         rc = mdb_rebalance(txn, dbi, mpp);
3463         if (rc != MDB_SUCCESS)
3464                 txn->mt_flags |= MDB_TXN_ERROR;
3465
3466         return rc;
3467 }
3468
3469 int
3470 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3471     MDB_val *key, MDB_val *data)
3472 {
3473         int              rc, exact;
3474         unsigned int     ki;
3475         MDB_node        *leaf;
3476         MDB_pageparent  mpp;
3477         DKBUF;
3478
3479         assert(key != NULL);
3480
3481         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3482
3483         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3484                 return EINVAL;
3485
3486         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3487                 return EACCES;
3488         }
3489
3490         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3491                 return EINVAL;
3492         }
3493
3494         mpp.mp_parent = NULL;
3495         mpp.mp_pi = 0;
3496         if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3497                 return rc;
3498
3499         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3500         if (leaf == NULL || !exact) {
3501                 return MDB_NOTFOUND;
3502         }
3503
3504         if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3505                 MDB_xcursor mx;
3506                 MDB_pageparent mp2;
3507
3508                 mdb_xcursor_init0(txn, dbi, &mx);
3509                 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3510                 if (data) {
3511                         rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL);
3512                         mdb_xcursor_fini(txn, dbi, &mx);
3513                         /* If sub-DB still has entries, we're done */
3514                         if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3515                                 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3516                                         sizeof(MDB_db));
3517                                 txn->mt_dbs[dbi].md_entries--;
3518                                 return rc;
3519                         }
3520                         /* otherwise fall thru and delete the sub-DB */
3521                 } else {
3522                         /* add all the child DB's pages to the free list */
3523                         rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3524                                 NULL, &mx.mx_cursor, 0, &mp2);
3525                         if (rc == MDB_SUCCESS) {
3526                                 MDB_ppage *top, *parent;
3527                                 MDB_node *ni;
3528                                 unsigned int i;
3529
3530                                 cursor_pop_page(&mx.mx_cursor);
3531                                 if (mx.mx_cursor.mc_snum) {
3532                                         top = CURSOR_TOP(&mx.mx_cursor);
3533                                         while (mx.mx_cursor.mc_snum > 1) {
3534                                                 parent = CURSOR_PARENT(&mx.mx_cursor);
3535                                                 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3536                                                         ni = NODEPTR(top->mp_page, i);
3537                                                         mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3538                                                 }
3539                                                 parent->mp_ki++;
3540                                                 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3541                                                         cursor_pop_page(&mx.mx_cursor);
3542                                                         top = parent;
3543                                                 } else {
3544                                                         ni = NODEPTR(parent->mp_page, parent->mp_ki);
3545                                                         rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3546                                                 }
3547                                         }
3548                                 }
3549                                 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3550                         }
3551                 }
3552         }
3553
3554         return mdb_del0(txn, dbi, ki, &mpp, leaf);
3555 }
3556
3557 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3558  * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3559  * *newindxp with the actual values after split, ie if *mpp and *newindxp
3560  * refer to a node in the new right sibling page.
3561  */
3562 static int
3563 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3564     MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3565 {
3566         uint8_t          flags;
3567         int              rc = MDB_SUCCESS, ins_new = 0;
3568         indx_t           newindx;
3569         pgno_t           pgno = 0;
3570         unsigned int     i, j, split_indx, nkeys, pmax;
3571         MDB_node        *node;
3572         MDB_val  sepkey, rkey, rdata;
3573         MDB_page        *copy, *cptr;
3574         MDB_dpage       *mdp, *rdp, *pdp;
3575         MDB_dhead *dh;
3576         DKBUF;
3577
3578         assert(txn != NULL);
3579
3580         dh = ((MDB_dhead *)*mpp) - 1;
3581         mdp = (MDB_dpage *)dh;
3582         newindx = *newindxp;
3583
3584         DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3585             IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3586             DKEY(newkey), *newindxp);
3587
3588         if (mdp->h.md_parent == NULL) {
3589                 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3590                         return ENOMEM;
3591                 mdp->h.md_pi = 0;
3592                 mdp->h.md_parent = &pdp->p;
3593                 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3594                 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3595                 txn->mt_dbs[dbi].md_depth++;
3596
3597                 /* Add left (implicit) pointer. */
3598                 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3599                     mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3600                         return rc;
3601         } else {
3602                 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3603         }
3604
3605         /* Create a right sibling. */
3606         if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3607                 return ENOMEM;
3608         rdp->h.md_parent = mdp->h.md_parent;
3609         rdp->h.md_pi = mdp->h.md_pi + 1;
3610         DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3611
3612         nkeys = NUMKEYS(&mdp->p);
3613         split_indx = nkeys / 2 + 1;
3614
3615         if (IS_LEAF2(&rdp->p)) {
3616                 char *split, *ins;
3617                 int x;
3618                 unsigned int lsize, rsize, ksize;
3619                 /* Move half of the keys to the right sibling */
3620                 copy = NULL;
3621                 x = *newindxp - split_indx;
3622                 ksize = txn->mt_dbs[dbi].md_pad;
3623                 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3624                 rsize = (nkeys - split_indx) * ksize;
3625                 lsize = (nkeys - split_indx) * sizeof(indx_t);
3626                 mdp->p.mp_lower -= lsize;
3627                 rdp->p.mp_lower += lsize;
3628                 mdp->p.mp_upper += rsize - lsize;
3629                 rdp->p.mp_upper -= rsize - lsize;
3630                 sepkey.mv_size = ksize;
3631                 if (newindx == split_indx) {
3632                         sepkey.mv_data = newkey->mv_data;
3633                 } else {
3634                         sepkey.mv_data = split;
3635                 }
3636                 if (x<0) {
3637                         ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3638                         memcpy(&rdp->p.mp_ptrs, split, rsize);
3639                         sepkey.mv_data = &rdp->p.mp_ptrs;
3640                         memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3641                         memcpy(ins, newkey->mv_data, ksize);
3642                         mdp->p.mp_lower += sizeof(indx_t);
3643                         mdp->p.mp_upper -= ksize - sizeof(indx_t);
3644                 } else {
3645                         if (x)
3646                                 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3647                         ins = LEAF2KEY(&rdp->p, x, ksize);
3648                         memcpy(ins, newkey->mv_data, ksize);
3649                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3650                         rdp->p.mp_lower += sizeof(indx_t);
3651                         rdp->p.mp_upper -= ksize - sizeof(indx_t);
3652                         *newindxp = x;
3653                         *mpp = &rdp->p;
3654                 }
3655                 goto newsep;
3656         }
3657
3658         /* For leaf pages, check the split point based on what
3659          * fits where, since otherwise add_node can fail.
3660          */
3661         if (IS_LEAF(&mdp->p)) {
3662                 unsigned int psize, nsize;
3663                 /* Maximum free space in an empty page */
3664                 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
3665                 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
3666                 if (newindx < split_indx) {
3667                         psize = nsize;
3668                         for (i=0; i<split_indx; i++) {
3669                                 node = NODEPTR(&mdp->p, i);
3670                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
3671                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
3672                                         psize += sizeof(pgno_t);
3673                                 else
3674                                         psize += NODEDSZ(node);
3675                                 if (psize > pmax) {
3676                                         split_indx = i;
3677                                         break;
3678                                 }
3679                         }
3680                 } else {
3681                         psize = nsize;
3682                         for (i=nkeys-1; i>=split_indx; i--) {
3683                                 node = NODEPTR(&mdp->p, i);
3684                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
3685                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
3686                                         psize += sizeof(pgno_t);
3687                                 else
3688                                         psize += NODEDSZ(node);
3689                                 if (psize > pmax) {
3690                                         split_indx = i+1;
3691                                         break;
3692                                 }
3693                         }
3694                 }
3695         }
3696
3697         /* First find the separating key between the split pages.
3698          */
3699         memset(&sepkey, 0, sizeof(sepkey));
3700         if (newindx == split_indx) {
3701                 sepkey.mv_size = newkey->mv_size;
3702                 sepkey.mv_data = newkey->mv_data;
3703         } else {
3704                 node = NODEPTR(&mdp->p, split_indx);
3705                 sepkey.mv_size = node->mn_ksize;
3706                 sepkey.mv_data = NODEKEY(node);
3707         }
3708
3709 newsep:
3710         DPRINTF("separator is [%s]", DKEY(&sepkey));
3711
3712         /* Copy separator key to the parent.
3713          */
3714         if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3715                 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3716                     &sepkey, NULL, rdp->p.mp_pgno);
3717
3718                 /* Right page might now have changed parent.
3719                  * Check if left page also changed parent.
3720                  */
3721                 if (rdp->h.md_parent != mdp->h.md_parent &&
3722                     mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3723                         mdp->h.md_parent = rdp->h.md_parent;
3724                         mdp->h.md_pi = rdp->h.md_pi - 1;
3725                 }
3726         } else {
3727                 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3728                     &sepkey, NULL, rdp->p.mp_pgno, 0);
3729         }
3730         if (IS_LEAF2(&rdp->p)) {
3731                 return rc;
3732         }
3733         if (rc != MDB_SUCCESS) {
3734                 return rc;
3735         }
3736
3737         /* Move half of the keys to the right sibling. */
3738         if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3739                 return ENOMEM;
3740
3741         copy->mp_pgno  = mdp->p.mp_pgno;
3742         copy->mp_flags = mdp->p.mp_flags;
3743         copy->mp_lower = PAGEHDRSZ;
3744         copy->mp_upper = txn->mt_env->me_psize;
3745         cptr = copy;
3746         for (i = j = 0; i <= nkeys; j++) {
3747                 if (i == split_indx) {
3748                 /* Insert in right sibling. */
3749                 /* Reset insert index for right sibling. */
3750                         j = (i == newindx && ins_new);
3751                         cptr = &rdp->p;
3752                 }
3753
3754                 if (i == newindx && !ins_new) {
3755                         /* Insert the original entry that caused the split. */
3756                         rkey.mv_data = newkey->mv_data;
3757                         rkey.mv_size = newkey->mv_size;
3758                         if (IS_LEAF(&mdp->p)) {
3759                                 rdata.mv_data = newdata->mv_data;
3760                                 rdata.mv_size = newdata->mv_size;
3761                         } else
3762                                 pgno = newpgno;
3763                         flags = 0;
3764
3765                         ins_new = 1;
3766
3767                         /* Update page and index for the new key. */
3768                         *newindxp = j;
3769                         if (cptr == &rdp->p)
3770                                 *mpp = cptr;
3771                 } else if (i == nkeys) {
3772                         break;
3773                 } else {
3774                         node = NODEPTR(&mdp->p, i);
3775                         rkey.mv_data = NODEKEY(node);
3776                         rkey.mv_size = node->mn_ksize;
3777                         if (IS_LEAF(&mdp->p)) {
3778                                 rdata.mv_data = NODEDATA(node);
3779                                 rdata.mv_size = node->mn_dsize;
3780                         } else
3781                                 pgno = NODEPGNO(node);
3782                         flags = node->mn_flags;
3783
3784                         i++;
3785                 }
3786
3787                 if (!IS_LEAF(&mdp->p) && j == 0) {
3788                         /* First branch index doesn't need key data. */
3789                         rkey.mv_size = 0;
3790                 }
3791
3792                 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
3793         }
3794         nkeys = NUMKEYS(copy);
3795         for (i=0; i<nkeys; i++)
3796                 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
3797         mdp->p.mp_lower = copy->mp_lower;
3798         mdp->p.mp_upper = copy->mp_upper;
3799         memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
3800                 txn->mt_env->me_psize - copy->mp_upper);
3801
3802         free(copy);
3803         return rc;
3804 }
3805
3806 static int
3807 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3808     MDB_val *key, MDB_val *data, unsigned int flags)
3809 {
3810         int              rc = MDB_SUCCESS, exact;
3811         unsigned int     ki;
3812         MDB_node        *leaf;
3813         MDB_pageparent  mpp;
3814         MDB_val xdata, *rdata, dkey;
3815         MDB_db dummy;
3816         char dbuf[PAGESIZE];
3817         int do_sub = 0;
3818         size_t nsize;
3819         DKBUF;
3820
3821         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3822                 dbi, DKEY(key), key->mv_size, data->mv_size);
3823
3824         dkey.mv_size = 0;
3825         mpp.mp_parent = NULL;
3826         mpp.mp_pi = 0;
3827         rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3828         if (rc == MDB_SUCCESS) {
3829                 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3830                 if (leaf && exact) {
3831                         if (flags == MDB_NOOVERWRITE) {
3832                                 DPRINTF("duplicate key [%s]", DKEY(key));
3833                                 return MDB_KEYEXIST;
3834                         }
3835                         /* there's only a key anyway, so this is a no-op */
3836                         if (IS_LEAF2(mpp.mp_page))
3837                                 return MDB_SUCCESS;
3838
3839                         if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3840                                 /* Was a single item before, must convert now */
3841                                 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3842                                         dkey.mv_size = NODEDSZ(leaf);
3843                                         dkey.mv_data = dbuf;
3844                                         memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3845                                         /* data matches, ignore it */
3846                                         if (!mdb_dcmp(txn, dbi, data, &dkey))
3847                                                 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3848                                         memset(&dummy, 0, sizeof(dummy));
3849                                         if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3850                                                 dummy.md_pad = data->mv_size;
3851                                                 dummy.md_flags = MDB_DUPFIXED;
3852                                                 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3853                                                         dummy.md_flags |= MDB_INTEGERKEY;
3854                                         }
3855                                         dummy.md_root = P_INVALID;
3856                                         if (dkey.mv_size == sizeof(MDB_db)) {
3857                                                 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3858                                                 goto put_sub;
3859                                         }
3860                                         mdb_del_node(mpp.mp_page, ki, 0);
3861                                         do_sub = 1;
3862                                         rdata = &xdata;
3863                                         xdata.mv_size = sizeof(MDB_db);
3864                                         xdata.mv_data = &dummy;
3865                                         goto new_sub;
3866                                 }
3867                                 goto put_sub;
3868                         }
3869                         /* same size, just replace it */
3870                         if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3871                                 NODEDSZ(leaf) == data->mv_size) {
3872                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3873                                 goto done;
3874                         }
3875                         mdb_del_node(mpp.mp_page, ki, 0);
3876                 }
3877                 if (leaf == NULL) {             /* append if not found */
3878                         ki = NUMKEYS(mpp.mp_page);
3879                         DPRINTF("appending key at index %i", ki);
3880                 }
3881         } else if (rc == MDB_NOTFOUND) {
3882                 MDB_dpage *dp;
3883                 /* new file, just write a root leaf page */
3884                 DPUTS("allocating new root leaf page");
3885                 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3886                         return ENOMEM;
3887                 }
3888                 mpp.mp_page = &dp->p;
3889                 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3890                 txn->mt_dbs[dbi].md_depth++;
3891                 txn->mt_dbxs[dbi].md_dirty = 1;
3892                 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3893                         mpp.mp_page->mp_flags |= P_LEAF2;
3894                 ki = 0;
3895         }
3896         else
3897                 goto done;
3898
3899         assert(IS_LEAF(mpp.mp_page));
3900         DPRINTF("there are %u keys, should insert new key at index %i",
3901                 NUMKEYS(mpp.mp_page), ki);
3902
3903         rdata = data;
3904
3905 new_sub:
3906         nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3907         if (SIZELEFT(mpp.mp_page) < nsize) {
3908                 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3909         } else {
3910                 /* There is room already in this leaf page. */
3911                 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3912         }
3913
3914         if (rc != MDB_SUCCESS)
3915                 txn->mt_flags |= MDB_TXN_ERROR;
3916         else {
3917                 /* Remember if we just added a subdatabase */
3918                 if (flags & F_SUBDATA) {
3919                         leaf = NODEPTR(mpp.mp_page, ki);
3920                         leaf->mn_flags |= F_SUBDATA;
3921                 }
3922
3923                 /* Now store the actual data in the child DB. Note that we're
3924                  * storing the user data in the keys field, so there are strict
3925                  * size limits on dupdata. The actual data fields of the child
3926                  * DB are all zero size.
3927                  */
3928                 if (do_sub) {
3929                         MDB_xcursor mx;
3930
3931                         leaf = NODEPTR(mpp.mp_page, ki);
3932 put_sub:
3933                         mdb_xcursor_init0(txn, dbi, &mx);
3934                         mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3935                         xdata.mv_size = 0;
3936                         xdata.mv_data = "";
3937                         if (flags == MDB_NODUPDATA)
3938                                 flags = MDB_NOOVERWRITE;
3939                         /* converted, write the original data first */
3940                         if (dkey.mv_size) {
3941                                 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3942                                 if (rc) return rc;
3943                                 leaf->mn_flags |= F_DUPDATA;
3944                         }
3945                         rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3946                         mdb_xcursor_fini(txn, dbi, &mx);
3947                         memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3948                                 sizeof(MDB_db));
3949                 }
3950                 txn->mt_dbs[dbi].md_entries++;
3951         }
3952
3953 done:
3954         return rc;
3955 }
3956
3957 int
3958 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3959     MDB_val *key, MDB_val *data, unsigned int flags)
3960 {
3961         assert(key != NULL);
3962         assert(data != NULL);
3963
3964         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3965                 return EINVAL;
3966
3967         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3968                 return EACCES;
3969         }
3970
3971         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3972                 return EINVAL;
3973         }
3974
3975         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3976                 return EINVAL;
3977
3978         return mdb_put0(txn, dbi, key, data, flags);
3979 }
3980
3981 int
3982 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3983 {
3984 #define CHANGEABLE      (MDB_NOSYNC)
3985         if ((flag & CHANGEABLE) != flag)
3986                 return EINVAL;
3987         if (onoff)
3988                 env->me_flags |= flag;
3989         else
3990                 env->me_flags &= ~flag;
3991         return MDB_SUCCESS;
3992 }
3993
3994 int
3995 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3996 {
3997         if (!env || !arg)
3998                 return EINVAL;
3999
4000         *arg = env->me_flags;
4001         return MDB_SUCCESS;
4002 }
4003
4004 int
4005 mdb_env_get_path(MDB_env *env, const char **arg)
4006 {
4007         if (!env || !arg)
4008                 return EINVAL;
4009
4010         *arg = env->me_path;
4011         return MDB_SUCCESS;
4012 }
4013
4014 static int
4015 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4016 {
4017         arg->ms_psize = env->me_psize;
4018         arg->ms_depth = db->md_depth;
4019         arg->ms_branch_pages = db->md_branch_pages;
4020         arg->ms_leaf_pages = db->md_leaf_pages;
4021         arg->ms_overflow_pages = db->md_overflow_pages;
4022         arg->ms_entries = db->md_entries;
4023
4024         return MDB_SUCCESS;
4025 }
4026 int
4027 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4028 {
4029         int toggle;
4030
4031         if (env == NULL || arg == NULL)
4032                 return EINVAL;
4033
4034         mdb_env_read_meta(env, &toggle);
4035
4036         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4037 }
4038
4039 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4040 {
4041         MDB_val key, data;
4042         MDB_dbi i;
4043         int rc, dirty = 0;
4044         size_t len;
4045
4046         /* main DB? */
4047         if (!name) {
4048                 *dbi = MAIN_DBI;
4049                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4050                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4051                 return MDB_SUCCESS;
4052         }
4053
4054         /* Is the DB already open? */
4055         len = strlen(name);
4056         for (i=2; i<txn->mt_numdbs; i++) {
4057                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4058                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4059                         *dbi = i;
4060                         return MDB_SUCCESS;
4061                 }
4062         }
4063
4064         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4065                 return ENFILE;
4066
4067         /* Find the DB info */
4068         key.mv_size = len;
4069         key.mv_data = (void *)name;
4070         rc = mdb_get(txn, MAIN_DBI, &key, &data);
4071
4072         /* Create if requested */
4073         if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4074                 MDB_db dummy;
4075                 data.mv_size = sizeof(MDB_db);
4076                 data.mv_data = &dummy;
4077                 memset(&dummy, 0, sizeof(dummy));
4078                 dummy.md_root = P_INVALID;
4079                 dummy.md_flags = flags & 0xffff;
4080                 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
4081                 dirty = 1;
4082         }
4083
4084         /* OK, got info, add to table */
4085         if (rc == MDB_SUCCESS) {
4086                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4087                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4088                 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
4089                 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
4090                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4091                 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4092                 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4093                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4094                 *dbi = txn->mt_numdbs;
4095                 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4096                 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4097                 txn->mt_numdbs++;
4098         }
4099
4100         return rc;
4101 }
4102
4103 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4104 {
4105         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4106                 return EINVAL;
4107
4108         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4109 }
4110
4111 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4112 {
4113         char *ptr;
4114         if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4115                 return;
4116         ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4117         txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4118         txn->mt_dbxs[dbi].md_name.mv_size = 0;
4119         free(ptr);
4120 }
4121
4122 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4123 {
4124         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4125                 return EINVAL;
4126
4127         txn->mt_dbxs[dbi].md_cmp = cmp;
4128         return MDB_SUCCESS;
4129 }
4130
4131 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4132 {
4133         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4134                 return EINVAL;
4135
4136         txn->mt_dbxs[dbi].md_dcmp = cmp;
4137         return MDB_SUCCESS;
4138 }
4139
4140 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4141 {
4142         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4143                 return EINVAL;
4144
4145         txn->mt_dbxs[dbi].md_rel = rel;
4146         return MDB_SUCCESS;
4147 }
4148
4149 /** @} */