]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
b0b572dfefb7fdac13ef2f9583a6ebf89cd90f09
[openldap] / libraries / libmdb / mdb.c
1 /* mdb.c - memory-mapped database library */
2 /*
3  * Copyright 2011 Howard Chu, Symas Corp.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted only as authorized by the OpenLDAP
8  * Public License.
9  *
10  * A copy of this license is available in the file LICENSE in the
11  * top-level directory of the distribution or, alternatively, at
12  * <http://www.OpenLDAP.org/license.html>.
13  *
14  * This code is derived from btree.c written by Martin Hedenfalk.
15  *
16  * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
17  *
18  * Permission to use, copy, modify, and distribute this software for any
19  * purpose with or without fee is hereby granted, provided that the above
20  * copyright notice and this permission notice appear in all copies.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
23  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
25  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
27  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
28  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
29  */
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/queue.h>
33 #include <sys/param.h>
34 #include <sys/uio.h>
35 #include <sys/mman.h>
36 #ifdef HAVE_SYS_FILE_H
37 #include <sys/file.h>
38 #endif
39 #include <fcntl.h>
40
41 #include <assert.h>
42 #include <errno.h>
43 #include <stddef.h>
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <time.h>
49 #include <unistd.h>
50 #include <pthread.h>
51
52 #include "mdb.h"
53
54 #define ULONG           unsigned long
55 typedef ULONG           pgno_t;
56
57 #include "midl.h"
58
59 #ifndef DEBUG
60 #define DEBUG 1
61 #endif
62
63 #if DEBUG && defined(__GNUC__)
64 # define DPRINTF(fmt, ...) \
65         fprintf(stderr, "%s:%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
66 #else
67 # define DPRINTF(...)   ((void) 0)
68 #endif
69
70 #define PAGESIZE         4096
71 #define MDB_MINKEYS      4
72 #define MDB_MAGIC        0xBEEFC0DE
73 #define MDB_VERSION      1
74 #define MAXKEYSIZE       511
75
76 #define P_INVALID        (~0UL)
77
78 #define F_ISSET(w, f)    (((w) & (f)) == (f))
79
80 typedef uint16_t         indx_t;
81
82 #define DEFAULT_READERS 126
83 #define DEFAULT_MAPSIZE 1048576
84
85 /* Lock descriptor stuff */
86 #define RXBODY  \
87         ULONG           mr_txnid; \
88         pid_t           mr_pid; \
89         pthread_t       mr_tid
90 typedef struct MDB_rxbody {
91         RXBODY;
92 } MDB_rxbody;
93
94 #ifndef CACHELINE
95 # ifdef __APPLE__
96 #  define CACHELINE     128     /* 64 is too small to contain a mutex */
97 # else
98 #  define CACHELINE     64      /* most CPUs. Itanium uses 128 */
99 # endif
100 #endif
101
102 typedef struct MDB_reader {
103         RXBODY;
104         /* cache line alignment */
105         char pad[CACHELINE-sizeof(MDB_rxbody)];
106 } MDB_reader;
107
108 #define TXBODY \
109         uint32_t        mt_magic;       \
110         uint32_t        mt_version;     \
111         pthread_mutex_t mt_mutex;       \
112         ULONG           mt_txnid;       \
113         uint32_t        mt_numreaders
114 typedef struct MDB_txbody {
115         TXBODY;
116 } MDB_txbody;
117
118 typedef struct MDB_txninfo {
119         TXBODY;
120         char pad[CACHELINE-sizeof(MDB_txbody)];
121         pthread_mutex_t mt_wmutex;
122         char pad2[CACHELINE-sizeof(pthread_mutex_t)];
123         MDB_reader      mt_readers[1];
124 } MDB_txninfo;
125
126 /* Common header for all page types. Overflow pages
127  * occupy a number of contiguous pages with no
128  * headers on any page after the first.
129  */
130 typedef struct MDB_page {               /* represents a page of storage */
131 #define mp_pgno         mp_p.p_pgno
132         union padded {
133                 pgno_t          p_pgno;         /* page number */
134                 void *          p_pad;
135         } mp_p;
136 #define P_BRANCH         0x01           /* branch page */
137 #define P_LEAF           0x02           /* leaf page */
138 #define P_OVERFLOW       0x04           /* overflow page */
139 #define P_META           0x08           /* meta page */
140 #define P_DIRTY          0x10           /* dirty page */
141         uint32_t        mp_flags;
142 #define mp_lower        mp_pb.pb.pb_lower
143 #define mp_upper        mp_pb.pb.pb_upper
144 #define mp_pages        mp_pb.pb_pages
145         union page_bounds {
146                 struct {
147                         indx_t          pb_lower;               /* lower bound of free space */
148                         indx_t          pb_upper;               /* upper bound of free space */
149                 } pb;
150                 uint32_t        pb_pages;       /* number of overflow pages */
151         } mp_pb;
152         indx_t          mp_ptrs[1];             /* dynamic size */
153 } MDB_page;
154
155 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
156
157 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
158 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
159 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
160                                 ((env)->me_psize - PAGEHDRSZ))
161 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
162 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
163 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
164
165 #define OVPAGES(size, psize)    (PAGEHDRSZ + size + psize - 1) / psize;
166
167 typedef struct MDB_db {
168         uint32_t        md_pad;
169         uint16_t        md_flags;
170         uint16_t        md_depth;
171         ULONG           md_branch_pages;
172         ULONG           md_leaf_pages;
173         ULONG           md_overflow_pages;
174         ULONG           md_entries;
175         pgno_t          md_root;
176 } MDB_db;
177
178 #define FREE_DBI        0
179 #define MAIN_DBI        1
180
181 typedef struct MDB_meta {                       /* meta (footer) page content */
182         uint32_t        mm_magic;
183         uint32_t        mm_version;
184         void            *mm_address;            /* address for fixed mapping */
185         size_t          mm_mapsize;                     /* size of mmap region */
186         MDB_db          mm_dbs[2];                      /* first is free space, 2nd is main db */
187 #define mm_psize        mm_dbs[0].md_pad
188 #define mm_flags        mm_dbs[0].md_flags
189         pgno_t          mm_last_pg;                     /* last used page in file */
190         ULONG           mm_txnid;                       /* txnid that committed this page */
191 } MDB_meta;
192
193 typedef struct MDB_dhead {                                      /* a dirty page */
194         STAILQ_ENTRY(MDB_dpage)  md_next;       /* queue of dirty pages */
195         MDB_page        *md_parent;
196         unsigned        md_pi;                          /* parent index */
197         int                     md_num;
198 } MDB_dhead;
199
200 typedef struct MDB_dpage {
201         MDB_dhead       h;
202         MDB_page        p;
203 } MDB_dpage;
204
205 STAILQ_HEAD(dirty_queue, MDB_dpage);    /* FIXME: use a sorted data structure */
206
207 typedef struct MDB_oldpages {
208         struct MDB_oldpages *mo_next;
209         ULONG           mo_txnid;
210         pgno_t          mo_pages[1];    /* dynamic */
211 } MDB_oldpages;
212
213 typedef struct MDB_pageparent {
214         MDB_page *mp_page;
215         MDB_page *mp_parent;
216         unsigned mp_pi;
217 } MDB_pageparent;
218
219 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
220 static int              mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
221
222 typedef struct MDB_ppage {                                      /* ordered list of pages */
223         SLIST_ENTRY(MDB_ppage)   mp_entry;
224         MDB_page                *mp_page;
225         unsigned int    mp_ki;          /* cursor index on page */
226 } MDB_ppage;
227 SLIST_HEAD(page_stack, MDB_ppage);
228
229 /* FIXME: tree depth is mostly bounded, we should just
230  * use a fixed array and avoid malloc/pointer chasing
231  */
232 #define CURSOR_EMPTY(c)          SLIST_EMPTY(&(c)->mc_stack)
233 #define CURSOR_TOP(c)            SLIST_FIRST(&(c)->mc_stack)
234 #define CURSOR_POP(c)            SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
235 #define CURSOR_PUSH(c,p)         SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
236
237 struct MDB_xcursor;
238
239 struct MDB_cursor {
240         MDB_txn         *mc_txn;
241         struct page_stack        mc_stack;              /* stack of parent pages */
242         MDB_dbi         mc_dbi;
243         short           mc_initialized; /* 1 if initialized */
244         short           mc_eof;         /* 1 if end is reached */
245         struct MDB_xcursor      *mc_xcursor;
246 };
247
248 #define METAHASHLEN      offsetof(MDB_meta, mm_hash)
249 #define METADATA(p)      ((void *)((char *)p + PAGEHDRSZ))
250
251 typedef struct MDB_node {
252 #define mn_pgno          mn_p.np_pgno
253 #define mn_dsize         mn_p.np_dsize
254         union {
255                 pgno_t           np_pgno;       /* child page number */
256                 uint32_t         np_dsize;      /* leaf data size */
257         } mn_p;
258         unsigned int    mn_flags:4;
259         unsigned int    mn_ksize:12;                    /* key size */
260 #define F_BIGDATA        0x01                   /* data put on overflow page */
261 #define F_SUBDATA        0x02                   /* data is a sub-database */
262         char            mn_data[1];
263 } MDB_node;
264
265 typedef struct MDB_dbx {
266         MDB_val         md_name;
267         MDB_cmp_func    *md_cmp;                /* user compare function */
268         MDB_cmp_func    *md_dcmp;               /* user dupsort function */
269         MDB_rel_func    *md_rel;                /* user relocate function */
270         MDB_dbi md_parent;
271         unsigned int    md_dirty;
272 } MDB_dbx;
273
274 struct MDB_txn {
275         pgno_t          mt_next_pgno;   /* next unallocated page */
276         ULONG           mt_txnid;
277         ULONG           mt_oldest;
278         MDB_env         *mt_env;        
279         pgno_t          *mt_free_pgs;   /* this is an IDL */
280         union {
281                 struct dirty_queue      *dirty_queue;   /* modified pages */
282                 MDB_reader      *reader;
283         } mt_u;
284         MDB_dbx         *mt_dbxs;               /* array */
285         MDB_db          *mt_dbs;
286         unsigned int    mt_numdbs;
287
288 #define MDB_TXN_RDONLY           0x01           /* read-only transaction */
289 #define MDB_TXN_ERROR            0x02           /* an error has occurred */
290 #define MDB_TXN_METOGGLE        0x04            /* used meta page 1 */
291         unsigned int    mt_flags;
292 };
293
294 /* Context for sorted-dup records */
295 typedef struct MDB_xcursor {
296         MDB_cursor mx_cursor;
297         MDB_txn mx_txn;
298         MDB_dbx mx_dbxs[4];
299         MDB_db  mx_dbs[4];
300 } MDB_xcursor;
301
302 struct MDB_env {
303         int                     me_fd;
304         int                     me_lfd;
305         uint32_t        me_flags;
306         unsigned int    me_maxreaders;
307         unsigned int    me_numdbs;
308         unsigned int    me_maxdbs;
309         char            *me_path;
310         char            *me_map;
311         MDB_txninfo     *me_txns;
312         MDB_meta        *me_metas[2];
313         MDB_meta        *me_meta;
314         MDB_txn         *me_txn;                /* current write transaction */
315         size_t          me_mapsize;
316         off_t           me_size;                /* current file size */
317         unsigned int    me_psize;
318         int                     me_db_toggle;
319         MDB_dbx         *me_dbxs;               /* array */
320         MDB_db          *me_dbs[2];
321         MDB_oldpages *me_pghead;
322         pthread_key_t   me_txkey;       /* thread-key for readers */
323         pgno_t          me_free_pgs[MDB_IDL_UM_SIZE];
324 };
325
326 #define NODESIZE         offsetof(MDB_node, mn_data)
327
328 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
329 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
330 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
331 #define NODEKEY(node)    (void *)((node)->mn_data)
332 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
333 #define NODEPGNO(node)   ((node)->mn_pgno)
334 #define NODEDSZ(node)    ((node)->mn_dsize)
335
336 #define MDB_COMMIT_PAGES         64     /* max number of pages to write in one commit */
337 #define MDB_MAXCACHE_DEF         1024   /* max number of pages to keep in cache  */
338
339 static int  mdb_search_page_root(MDB_txn *txn,
340                             MDB_dbi dbi, MDB_val *key,
341                             MDB_cursor *cursor, int modify,
342                             MDB_pageparent *mpp);
343 static int  mdb_search_page(MDB_txn *txn,
344                             MDB_dbi dbi, MDB_val *key,
345                             MDB_cursor *cursor, int modify,
346                             MDB_pageparent *mpp);
347
348 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
349 static int  mdb_env_read_meta(MDB_env *env, int *which);
350 static int  mdb_env_write_meta(MDB_txn *txn);
351 static MDB_page *mdb_get_page(MDB_txn *txn, pgno_t pgno);
352
353 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
354                             MDB_val *key, int *exactp, unsigned int *kip);
355 static int  mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
356                             indx_t indx, MDB_val *key, MDB_val *data,
357                             pgno_t pgno, uint8_t flags);
358 static void mdb_del_node(MDB_page *mp, indx_t indx);
359 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
360     MDB_pageparent *mpp, MDB_node *leaf);
361 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
362     MDB_val *key, MDB_val *data, unsigned int flags);
363 static int  mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
364
365 static int               mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
366 static int               mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
367 static int               mdb_move_node(MDB_txn *txn, MDB_dbi dbi, 
368                                 MDB_pageparent *src, indx_t srcindx,
369                                 MDB_pageparent *dst, indx_t dstindx);
370 static int               mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
371                             MDB_pageparent *dst);
372 static int               mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
373                             unsigned int *newindxp, MDB_val *newkey,
374                             MDB_val *newdata, pgno_t newpgno);
375 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
376
377 static void              cursor_pop_page(MDB_cursor *cursor);
378 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
379                             MDB_page *mp);
380
381 static int               mdb_set_key(MDB_node *node, MDB_val *key);
382 static int               mdb_sibling(MDB_cursor *cursor, int move_right);
383 static int               mdb_cursor_next(MDB_cursor *cursor,
384                             MDB_val *key, MDB_val *data, MDB_cursor_op op);
385 static int               mdb_cursor_prev(MDB_cursor *cursor,
386                             MDB_val *key, MDB_val *data, MDB_cursor_op op);
387 static int               mdb_cursor_set(MDB_cursor *cursor,
388                             MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
389 static int               mdb_cursor_first(MDB_cursor *cursor,
390                             MDB_val *key, MDB_val *data);
391 static int               mdb_cursor_last(MDB_cursor *cursor,
392                             MDB_val *key, MDB_val *data);
393
394 static void             mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
395 static void             mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node);
396 static void             mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
397
398 static size_t            mdb_leaf_size(MDB_env *env, MDB_val *key,
399                             MDB_val *data);
400 static size_t            mdb_branch_size(MDB_env *env, MDB_val *key);
401
402 static int               memncmp(const void *s1, size_t n1,
403                                  const void *s2, size_t n2);
404 static int               memnrcmp(const void *s1, size_t n1,
405                                   const void *s2, size_t n2);
406
407 static int
408 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
409 {
410         int diff, len_diff = -1;
411
412         if (n1 >= n2) {
413                 len_diff = (n1 > n2);
414                 n1 = n2;
415         }
416         diff = memcmp(s1, s2, n1);
417         return diff ? diff : len_diff;
418 }
419
420 static int
421 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
422 {
423         const unsigned char     *p1, *p2, *p1_lim;
424
425         if (n2 == 0)
426                 return n1 != 0;
427         if (n1 == 0)
428                 return -1;
429
430         p1 = (const unsigned char *)s1 + n1 - 1;
431         p2 = (const unsigned char *)s2 + n2 - 1;
432
433         for (p1_lim = (n1 <= n2 ? s1 : s2);  *p1 == *p2;  p1--, p2--) {
434                 if (p1 == p1_lim)
435                         return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
436         }
437         return *p1 - *p2;
438 }
439
440 char *
441 mdb_version(int *maj, int *min, int *pat)
442 {
443         *maj = MDB_VERSION_MAJOR;
444         *min = MDB_VERSION_MINOR;
445         *pat = MDB_VERSION_PATCH;
446         return MDB_VERSION_STRING;
447 }
448
449 int
450 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
451 {
452         return txn->mt_dbxs[dbi].md_cmp(a, b);
453 }
454
455 static int
456 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
457 {
458         if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
459 #if __BYTE_ORDER == __LITTLE_ENDIAN
460                 |MDB_INTEGERKEY
461 #endif
462         ))
463                 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
464         else
465                 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
466 }
467
468 /* Allocate new page(s) for writing */
469 static MDB_dpage *
470 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
471 {
472         MDB_dpage *dp;
473         pgno_t pgno = P_INVALID;
474         ULONG oldest;
475
476         if (txn->mt_txnid > 2) {
477
478         oldest = txn->mt_txnid - 2;
479         if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
480                 /* See if there's anything in the free DB */
481                 MDB_pageparent mpp;
482                 MDB_node *leaf;
483                 ULONG *kptr;
484
485                 mpp.mp_parent = NULL;
486                 mpp.mp_pi = 0;
487                 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
488                 leaf = NODEPTR(mpp.mp_page, 0);
489                 kptr = (ULONG *)NODEKEY(leaf);
490
491                 /* It's potentially usable, unless there are still
492                  * older readers outstanding. Grab it.
493                  */
494                 if (oldest > *kptr) {
495                         MDB_oldpages *mop;
496                         MDB_val data;
497                         pgno_t *idl;
498
499                         mdb_read_data(txn, leaf, &data);
500                         idl = (ULONG *)data.mv_data;
501                         mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
502                         mop->mo_next = txn->mt_env->me_pghead;
503                         mop->mo_txnid = *kptr;
504                         txn->mt_env->me_pghead = mop;
505                         memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
506
507 #if DEBUG > 1
508                         {
509                                 unsigned int i;
510                                 DPRINTF("IDL read txn %lu root %lu num %lu",
511                                         mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
512                                 for (i=0; i<idl[0]; i++) {
513                                         DPRINTF("IDL %lu", idl[i+1]);
514                                 }
515                         }
516 #endif
517                         /* drop this IDL from the DB */
518                         mpp.mp_parent = NULL;
519                         mpp.mp_pi = 0;
520                         mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
521                         leaf = NODEPTR(mpp.mp_page, 0);
522                         mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
523                 }
524         }
525         if (txn->mt_env->me_pghead) {
526                 unsigned int i;
527                 for (i=0; i<txn->mt_env->me_txns->mt_numreaders; i++) {
528                         ULONG mr = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
529                         if (!mr) continue;
530                         if (mr < oldest)
531                                 oldest = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
532                 }
533                 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
534                         MDB_oldpages *mop = txn->mt_env->me_pghead;
535                         txn->mt_oldest = oldest;
536                         if (num > 1) {
537                                 /* FIXME: For now, always use fresh pages. We
538                                  * really ought to search the free list for a
539                                  * contiguous range.
540                                  */
541                                 ;
542                         } else {
543                                 /* peel pages off tail, so we only have to truncate the list */
544                                 pgno = MDB_IDL_LAST(mop->mo_pages);
545                                 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
546                                         mop->mo_pages[2]++;
547                                         if (mop->mo_pages[2] > mop->mo_pages[1])
548                                                 mop->mo_pages[0] = 0;
549                                 } else {
550                                         mop->mo_pages[0]--;
551                                 }
552                                 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
553                                         txn->mt_env->me_pghead = mop->mo_next;
554                                         free(mop);
555                                 }
556                         }
557                 }
558         }
559         }
560
561         if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
562                 return NULL;
563         dp->h.md_num = num;
564         dp->h.md_parent = parent;
565         dp->h.md_pi = parent_idx;
566         STAILQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
567         if (pgno == P_INVALID) {
568                 dp->p.mp_pgno = txn->mt_next_pgno;
569                 txn->mt_next_pgno += num;
570         } else {
571                 dp->p.mp_pgno = pgno;
572         }
573
574         return dp;
575 }
576
577 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
578  */
579 static int
580 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
581 {
582         MDB_page *mp = pp->mp_page;
583         pgno_t  pgno;
584         assert(txn != NULL);
585         assert(pp != NULL);
586
587         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
588                 MDB_dpage *dp;
589                 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
590                         return ENOMEM;
591                 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
592                 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
593                 pgno = dp->p.mp_pgno;
594                 memcpy(&dp->p, mp, txn->mt_env->me_psize);
595                 mp = &dp->p;
596                 mp->mp_pgno = pgno;
597                 mp->mp_flags |= P_DIRTY;
598
599                 /* Update the page number to new touched page. */
600                 if (pp->mp_parent != NULL)
601                         NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
602                 pp->mp_page = mp;
603         }
604         return 0;
605 }
606
607 int
608 mdb_env_sync(MDB_env *env, int force)
609 {
610         int rc = 0;
611         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
612                 if (fsync(env->me_fd))
613                         rc = errno;
614         }
615         return rc;
616 }
617
618 int
619 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
620 {
621         MDB_txn *txn;
622         int rc, toggle;
623
624         if ((txn = calloc(1, sizeof(MDB_txn))) == NULL) {
625                 DPRINTF("calloc: %s", strerror(errno));
626                 return ENOMEM;
627         }
628
629         if (rdonly) {
630                 txn->mt_flags |= MDB_TXN_RDONLY;
631         } else {
632                 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
633                 if (txn->mt_u.dirty_queue == NULL) {
634                         free(txn);
635                         return ENOMEM;
636                 }
637                 STAILQ_INIT(txn->mt_u.dirty_queue);
638
639                 pthread_mutex_lock(&env->me_txns->mt_wmutex);
640                 env->me_txns->mt_txnid++;
641                 txn->mt_free_pgs = env->me_free_pgs;
642                 txn->mt_free_pgs[0] = 0;
643         }
644
645         txn->mt_txnid = env->me_txns->mt_txnid;
646         if (rdonly) {
647                 MDB_reader *r = pthread_getspecific(env->me_txkey);
648                 if (!r) {
649                         unsigned int i;
650                         pthread_mutex_lock(&env->me_txns->mt_mutex);
651                         for (i=0; i<env->me_txns->mt_numreaders; i++)
652                                 if (env->me_txns->mt_readers[i].mr_pid == 0)
653                                         break;
654                         if (i == env->me_maxreaders) {
655                                 pthread_mutex_unlock(&env->me_txns->mti_mutex);
656                                 return ENOSPC;
657                         }
658                         env->me_txns->mt_readers[i].mr_pid = getpid();
659                         env->me_txns->mt_readers[i].mr_tid = pthread_self();
660                         r = &env->me_txns->mt_readers[i];
661                         pthread_setspecific(env->me_txkey, r);
662                         if (i >= env->me_txns->mt_numreaders)
663                                 env->me_txns->mt_numreaders = i+1;
664                         pthread_mutex_unlock(&env->me_txns->mt_mutex);
665                 }
666                 r->mr_txnid = txn->mt_txnid;
667                 txn->mt_u.reader = r;
668         } else {
669                 env->me_txn = txn;
670         }
671
672         txn->mt_env = env;
673
674         if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
675                 mdb_txn_abort(txn);
676                 return rc;
677         }
678
679         /* Copy the DB arrays */
680         txn->mt_numdbs = env->me_numdbs;
681         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
682         txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
683         memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
684         if (txn->mt_numdbs > 2)
685                 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
686                         (txn->mt_numdbs - 2) * sizeof(MDB_db));
687
688         if (!rdonly) {
689                 if (toggle)
690                         txn->mt_flags |= MDB_TXN_METOGGLE;
691                 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
692         }
693
694         DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
695                 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
696
697         *ret = txn;
698         return MDB_SUCCESS;
699 }
700
701 void
702 mdb_txn_abort(MDB_txn *txn)
703 {
704         MDB_dpage *dp;
705         MDB_env *env;
706
707         if (txn == NULL)
708                 return;
709
710         env = txn->mt_env;
711         DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
712                 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
713
714         free(txn->mt_dbs);
715
716         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
717                 txn->mt_u.reader->mr_txnid = 0;
718         } else {
719                 MDB_oldpages *mop;
720                 unsigned int i;
721
722                 /* Discard all dirty pages. */
723                 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
724                         dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
725                         STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
726                         free(dp);
727                 }
728                 free(txn->mt_u.dirty_queue);
729
730                 while ((mop = txn->mt_env->me_pghead)) {
731                         txn->mt_env->me_pghead = mop->mo_next;
732                         free(mop);
733                 }
734
735                 env->me_txn = NULL;
736                 env->me_txns->mt_txnid--;
737                 for (i=2; i<env->me_numdbs; i++)
738                         env->me_dbxs[i].md_dirty = 0;
739                 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
740         }
741
742         free(txn);
743 }
744
745 int
746 mdb_txn_commit(MDB_txn *txn)
747 {
748         int              n, done;
749         unsigned int i;
750         ssize_t          rc;
751         off_t            size;
752         MDB_dpage       *dp;
753         MDB_env *env;
754         pgno_t  next;
755         struct iovec     iov[MDB_COMMIT_PAGES];
756
757         assert(txn != NULL);
758         assert(txn->mt_env != NULL);
759
760         env = txn->mt_env;
761
762         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
763                 DPRINTF("attempt to commit read-only transaction");
764                 mdb_txn_abort(txn);
765                 return EPERM;
766         }
767
768         if (txn != env->me_txn) {
769                 DPRINTF("attempt to commit unknown transaction");
770                 mdb_txn_abort(txn);
771                 return EINVAL;
772         }
773
774         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
775                 DPRINTF("error flag is set, can't commit");
776                 mdb_txn_abort(txn);
777                 return EINVAL;
778         }
779
780         if (STAILQ_EMPTY(txn->mt_u.dirty_queue))
781                 goto done;
782
783         DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
784             txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
785
786         /* should only be one record now */
787         if (env->me_pghead) {
788                 MDB_val key, data;
789                 MDB_oldpages *mop;
790
791                 mop = env->me_pghead;
792                 key.mv_size = sizeof(pgno_t);
793                 key.mv_data = (char *)&mop->mo_txnid;
794                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
795                 data.mv_data = mop->mo_pages;
796                 mdb_put0(txn, FREE_DBI, &key, &data, 0);
797                 free(env->me_pghead);
798                 env->me_pghead = NULL;
799         }
800         /* save to free list */
801         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
802                 MDB_val key, data;
803                 MDB_pageparent mpp;
804
805                 /* make sure last page of freeDB is touched and on freelist */
806                 key.mv_size = MAXKEYSIZE+1;
807                 key.mv_data = NULL;
808                 mpp.mp_parent = NULL;
809                 mpp.mp_pi = 0;
810                 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
811
812 #if DEBUG > 1
813                 {
814                         unsigned int i;
815                         ULONG *idl = txn->mt_free_pgs;
816                         DPRINTF("IDL write txn %lu root %lu num %lu",
817                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
818                         for (i=0; i<idl[0]; i++) {
819                                 DPRINTF("IDL %lu", idl[i+1]);
820                         }
821                 }
822 #endif
823                 /* write to last page of freeDB */
824                 key.mv_size = sizeof(pgno_t);
825                 key.mv_data = (char *)&txn->mt_txnid;
826                 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
827                 data.mv_data = txn->mt_free_pgs;
828                 mdb_put0(txn, FREE_DBI, &key, &data, 0);
829         }
830
831         /* Update DB root pointers. Their pages have already been
832          * touched so this is all in-place and cannot fail.
833          */
834         {
835                 MDB_val data;
836                 data.mv_size = sizeof(MDB_db);
837
838                 for (i = 2; i < txn->mt_numdbs; i++) {
839                         if (txn->mt_dbxs[i].md_dirty) {
840                                 data.mv_data = &txn->mt_dbs[i];
841                                 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
842                         }
843                 }
844         }
845
846         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
847          */
848         next = 0;
849         do {
850                 n = 0;
851                 done = 1;
852                 size = 0;
853                 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
854                         if (dp->p.mp_pgno != next) {
855                                 if (n) {
856                                         DPRINTF("committing %u dirty pages", n);
857                                         rc = writev(env->me_fd, iov, n);
858                                         if (rc != size) {
859                                                 n = errno;
860                                                 if (rc > 0)
861                                                         DPRINTF("short write, filesystem full?");
862                                                 else
863                                                         DPRINTF("writev: %s", strerror(errno));
864                                                 mdb_txn_abort(txn);
865                                                 return n;
866                                         }
867                                         n = 0;
868                                         size = 0;
869                                 }
870                                 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
871                                 next = dp->p.mp_pgno;
872                         }
873                         DPRINTF("committing page %lu", dp->p.mp_pgno);
874                         iov[n].iov_len = env->me_psize * dp->h.md_num;
875                         iov[n].iov_base = &dp->p;
876                         size += iov[n].iov_len;
877                         next = dp->p.mp_pgno + dp->h.md_num;
878                         /* clear dirty flag */
879                         dp->p.mp_flags &= ~P_DIRTY;
880                         if (++n >= MDB_COMMIT_PAGES) {
881                                 done = 0;
882                                 break;
883                         }
884                 }
885
886                 if (n == 0)
887                         break;
888
889                 DPRINTF("committing %u dirty pages", n);
890                 rc = writev(env->me_fd, iov, n);
891                 if (rc != size) {
892                         n = errno;
893                         if (rc > 0)
894                                 DPRINTF("short write, filesystem full?");
895                         else
896                                 DPRINTF("writev: %s", strerror(errno));
897                         mdb_txn_abort(txn);
898                         return n;
899                 }
900
901         } while (!done);
902
903         /* Drop the dirty pages.
904          */
905         while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
906                 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
907                 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
908                 free(dp);
909         }
910
911         if ((n = mdb_env_sync(env, 0)) != 0 ||
912             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS ||
913             (n = mdb_env_sync(env, 0)) != 0) {
914                 mdb_txn_abort(txn);
915                 return n;
916         }
917         env->me_txn = NULL;
918
919         /* update the DB tables */
920         {
921                 int toggle = !env->me_db_toggle;
922
923                 for (i = 2; i < env->me_numdbs; i++) {
924                         if (txn->mt_dbxs[i].md_dirty) {
925                                 env->me_dbs[toggle][i] = txn->mt_dbs[i];
926                                 txn->mt_dbxs[i].md_dirty = 0;
927                         }
928                 }
929                 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
930                         txn->mt_dbxs[i].md_dirty = 0;
931                         env->me_dbxs[i] = txn->mt_dbxs[i];
932                         env->me_dbs[toggle][i] = txn->mt_dbs[i];
933                 }
934                 env->me_db_toggle = toggle;
935                 env->me_numdbs = txn->mt_numdbs;
936
937                 free(txn->mt_dbs);
938         }
939
940         pthread_mutex_unlock(&env->me_txns->mt_wmutex);
941         free(txn->mt_u.dirty_queue);
942         free(txn);
943         txn = NULL;
944
945 done:
946         mdb_txn_abort(txn);
947
948         return MDB_SUCCESS;
949 }
950
951 static int
952 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
953 {
954         char             page[PAGESIZE];
955         MDB_page        *p;
956         MDB_meta        *m;
957         int              rc;
958
959         assert(env != NULL);
960
961         /* We don't know the page size yet, so use a minimum value.
962          */
963
964         if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
965                 return ENOENT;
966         } else if (rc != PAGESIZE) {
967                 if (rc > 0)
968                         errno = EINVAL;
969                 DPRINTF("read: %s", strerror(errno));
970                 return errno;
971         }
972
973         p = (MDB_page *)page;
974
975         if (!F_ISSET(p->mp_flags, P_META)) {
976                 DPRINTF("page %lu not a meta page", p->mp_pgno);
977                 return EINVAL;
978         }
979
980         m = METADATA(p);
981         if (m->mm_magic != MDB_MAGIC) {
982                 DPRINTF("meta has invalid magic");
983                 return EINVAL;
984         }
985
986         if (m->mm_version != MDB_VERSION) {
987                 DPRINTF("database is version %u, expected version %u",
988                     m->mm_version, MDB_VERSION);
989                 return MDB_VERSION_MISMATCH;
990         }
991
992         memcpy(meta, m, sizeof(*m));
993         return 0;
994 }
995
996 static int
997 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
998 {
999         MDB_page *p, *q;
1000         MDB_meta *m;
1001         int rc;
1002         unsigned int     psize;
1003
1004         DPRINTF("writing new meta page");
1005         psize = sysconf(_SC_PAGE_SIZE);
1006
1007         meta->mm_magic = MDB_MAGIC;
1008         meta->mm_version = MDB_VERSION;
1009         meta->mm_psize = psize;
1010         meta->mm_last_pg = 1;
1011         meta->mm_flags = env->me_flags & 0xffff;
1012         meta->mm_flags |= MDB_INTEGERKEY;
1013         meta->mm_dbs[0].md_root = P_INVALID;
1014         meta->mm_dbs[1].md_root = P_INVALID;
1015
1016         p = calloc(2, psize);
1017         p->mp_pgno = 0;
1018         p->mp_flags = P_META;
1019
1020         m = METADATA(p);
1021         memcpy(m, meta, sizeof(*meta));
1022
1023         q = (MDB_page *)((char *)p + psize);
1024
1025         q->mp_pgno = 1;
1026         q->mp_flags = P_META;
1027
1028         m = METADATA(q);
1029         memcpy(m, meta, sizeof(*meta));
1030
1031         rc = write(env->me_fd, p, psize * 2);
1032         free(p);
1033         return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1034 }
1035
1036 static int
1037 mdb_env_write_meta(MDB_txn *txn)
1038 {
1039         MDB_env *env;
1040         MDB_meta        meta;
1041         off_t off;
1042         int rc, len;
1043         char *ptr;
1044
1045         assert(txn != NULL);
1046         assert(txn->mt_env != NULL);
1047
1048         DPRINTF("writing meta page %d for root page %lu",
1049                 !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE), txn->mt_dbs[MAIN_DBI].md_root);
1050
1051         env = txn->mt_env;
1052
1053         ptr = (char *)&meta;
1054         off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1055         len = sizeof(MDB_meta) - off;
1056
1057         ptr += off;
1058         meta.mm_dbs[0] = txn->mt_dbs[0];
1059         meta.mm_dbs[1] = txn->mt_dbs[1];
1060         meta.mm_last_pg = txn->mt_next_pgno - 1;
1061         meta.mm_txnid = txn->mt_txnid;
1062
1063         if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1064                 off += env->me_psize;
1065         off += PAGEHDRSZ;
1066
1067         lseek(env->me_fd, off, SEEK_SET);
1068         rc = write(env->me_fd, ptr, len);
1069         if (rc != len) {
1070                 DPRINTF("write failed, disk error?");
1071                 return errno;
1072         }
1073
1074         return MDB_SUCCESS;
1075 }
1076
1077 static int
1078 mdb_env_read_meta(MDB_env *env, int *which)
1079 {
1080         int toggle = 0;
1081
1082         assert(env != NULL);
1083
1084         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1085                 toggle = 1;
1086
1087         if (env->me_meta != env->me_metas[toggle])
1088                 env->me_meta = env->me_metas[toggle];
1089         if (which)
1090                 *which = toggle;
1091
1092         DPRINTF("Using meta page %d", toggle);
1093
1094         return MDB_SUCCESS;
1095 }
1096
1097 int
1098 mdb_env_create(MDB_env **env)
1099 {
1100         MDB_env *e;
1101
1102         e = calloc(1, sizeof(MDB_env));
1103         if (!e) return ENOMEM;
1104
1105         e->me_maxreaders = DEFAULT_READERS;
1106         e->me_maxdbs = 2;
1107         e->me_fd = -1;
1108         e->me_lfd = -1;
1109         *env = e;
1110         return MDB_SUCCESS;
1111 }
1112
1113 int
1114 mdb_env_set_mapsize(MDB_env *env, size_t size)
1115 {
1116         if (env->me_map)
1117                 return EINVAL;
1118         env->me_mapsize = size;
1119         return MDB_SUCCESS;
1120 }
1121
1122 int
1123 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1124 {
1125         env->me_maxdbs = dbs;
1126         return MDB_SUCCESS;
1127 }
1128
1129 int
1130 mdb_env_set_maxreaders(MDB_env *env, int readers)
1131 {
1132         env->me_maxreaders = readers;
1133         return MDB_SUCCESS;
1134 }
1135
1136 int
1137 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1138 {
1139         if (!env || !readers)
1140                 return EINVAL;
1141         *readers = env->me_maxreaders;
1142         return MDB_SUCCESS;
1143 }
1144
1145 static int
1146 mdb_env_open2(MDB_env *env, unsigned int flags)
1147 {
1148         int i, newenv = 0;
1149         MDB_meta meta;
1150         MDB_page *p;
1151
1152         env->me_flags = flags;
1153
1154         memset(&meta, 0, sizeof(meta));
1155
1156         if ((i = mdb_env_read_header(env, &meta)) != 0) {
1157                 if (i != ENOENT)
1158                         return i;
1159                 DPRINTF("new mdbenv");
1160                 newenv = 1;
1161         }
1162
1163         if (!env->me_mapsize) {
1164                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1165         }
1166
1167         i = MAP_SHARED;
1168         if (meta.mm_address && (flags & MDB_FIXEDMAP))
1169                 i |= MAP_FIXED;
1170         env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1171                 env->me_fd, 0);
1172         if (env->me_map == MAP_FAILED)
1173                 return errno;
1174
1175         if (newenv) {
1176                 meta.mm_mapsize = env->me_mapsize;
1177                 if (flags & MDB_FIXEDMAP)
1178                         meta.mm_address = env->me_map;
1179                 i = mdb_env_init_meta(env, &meta);
1180                 if (i != MDB_SUCCESS) {
1181                         munmap(env->me_map, env->me_mapsize);
1182                         return i;
1183                 }
1184         }
1185         env->me_psize = meta.mm_psize;
1186
1187         p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1188         env->me_metas[0] = METADATA(p);
1189         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1190
1191         if ((i = mdb_env_read_meta(env, NULL)) != 0)
1192                 return i;
1193
1194         DPRINTF("opened database version %u, pagesize %u",
1195             env->me_meta->mm_version, env->me_psize);
1196         DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1197         DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1198         DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1199         DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1200         DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1201         DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1202
1203         return MDB_SUCCESS;
1204 }
1205
1206 static void
1207 mdb_env_reader_dest(void *ptr)
1208 {
1209         MDB_reader *reader = ptr;
1210
1211         reader->mr_txnid = 0;
1212         reader->mr_pid = 0;
1213         reader->mr_tid = 0;
1214 }
1215
1216 /* downgrade the exclusive lock on the region back to shared */
1217 static void
1218 mdb_env_share_locks(MDB_env *env)
1219 {
1220         struct flock lock_info;
1221
1222         env->me_txns->mt_txnid = env->me_meta->mm_txnid;
1223
1224         memset((void *)&lock_info, 0, sizeof(lock_info));
1225         lock_info.l_type = F_RDLCK;
1226         lock_info.l_whence = SEEK_SET;
1227         lock_info.l_start = 0;
1228         lock_info.l_len = 1;
1229         fcntl(env->me_lfd, F_SETLK, &lock_info);
1230 }
1231
1232 static int
1233 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1234 {
1235         int rc;
1236         off_t size, rsize;
1237         struct flock lock_info;
1238
1239         *excl = 0;
1240
1241         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1242                 rc = errno;
1243                 return rc;
1244         }
1245         /* Try to get exclusive lock. If we succeed, then
1246          * nobody is using the lock region and we should initialize it.
1247          */
1248         memset((void *)&lock_info, 0, sizeof(lock_info));
1249         lock_info.l_type = F_WRLCK;
1250         lock_info.l_whence = SEEK_SET;
1251         lock_info.l_start = 0;
1252         lock_info.l_len = 1;
1253         rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1254         if (rc == 0) {
1255                 *excl = 1;
1256         } else {
1257                 lock_info.l_type = F_RDLCK;
1258                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1259                 if (rc) {
1260                         rc = errno;
1261                         goto fail;
1262                 }
1263         }
1264         size = lseek(env->me_lfd, 0, SEEK_END);
1265         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1266         if (size < rsize && *excl) {
1267                 if (ftruncate(env->me_lfd, rsize) != 0) {
1268                         rc = errno;
1269                         goto fail;
1270                 }
1271         } else {
1272                 rsize = size;
1273                 size = rsize - sizeof(MDB_txninfo);
1274                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1275         }
1276         env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1277                 env->me_lfd, 0);
1278         if (env->me_txns == MAP_FAILED) {
1279                 rc = errno;
1280                 goto fail;
1281         }
1282         if (*excl) {
1283                 pthread_mutexattr_t mattr;
1284
1285                 pthread_mutexattr_init(&mattr);
1286                 pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1287                 pthread_mutex_init(&env->me_txns->mt_mutex, &mattr);
1288                 pthread_mutex_init(&env->me_txns->mt_wmutex, &mattr);
1289                 env->me_txns->mt_version = MDB_VERSION;
1290                 env->me_txns->mt_magic = MDB_MAGIC;
1291                 env->me_txns->mt_txnid = 0;
1292                 env->me_txns->mt_numreaders = 0;
1293
1294         } else {
1295                 if (env->me_txns->mt_magic != MDB_MAGIC) {
1296                         DPRINTF("lock region has invalid magic");
1297                         rc = EINVAL;
1298                         goto fail;
1299                 }
1300                 if (env->me_txns->mt_version != MDB_VERSION) {
1301                         DPRINTF("lock region is version %u, expected version %u",
1302                                 env->me_txns->mt_version, MDB_VERSION);
1303                         rc = MDB_VERSION_MISMATCH;
1304                         goto fail;
1305                 }
1306                 if (errno != EACCES && errno != EAGAIN) {
1307                         rc = errno;
1308                         goto fail;
1309                 }
1310         }
1311         return MDB_SUCCESS;
1312
1313 fail:
1314         close(env->me_lfd);
1315         return rc;
1316
1317 }
1318
1319 #define LOCKNAME        "/lock.mdb"
1320 #define DATANAME        "/data.mdb"
1321 int
1322 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1323 {
1324         int             oflags, rc, len, excl;
1325         char *lpath, *dpath;
1326
1327         len = strlen(path);
1328         lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1329         if (!lpath)
1330                 return ENOMEM;
1331         dpath = lpath + len + sizeof(LOCKNAME);
1332         sprintf(lpath, "%s" LOCKNAME, path);
1333         sprintf(dpath, "%s" DATANAME, path);
1334
1335         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1336         if (rc)
1337                 goto leave;
1338
1339         if (F_ISSET(flags, MDB_RDONLY))
1340                 oflags = O_RDONLY;
1341         else
1342                 oflags = O_RDWR | O_CREAT;
1343
1344         if ((env->me_fd = open(dpath, oflags, mode)) == -1)
1345                 return errno;
1346
1347         if ((rc = mdb_env_open2(env, flags)) != MDB_SUCCESS) {
1348                 close(env->me_fd);
1349                 env->me_fd = -1;
1350         } else {
1351                 env->me_path = strdup(path);
1352                 DPRINTF("opened dbenv %p", (void *) env);
1353                 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1354                 if (excl)
1355                         mdb_env_share_locks(env);
1356                 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1357                 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1358                 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1359                 env->me_numdbs = 2;
1360         }
1361
1362 leave:
1363         free(lpath);
1364         return rc;
1365 }
1366
1367 void
1368 mdb_env_close(MDB_env *env)
1369 {
1370         if (env == NULL)
1371                 return;
1372
1373         free(env->me_dbs[1]);
1374         free(env->me_dbs[0]);
1375         free(env->me_dbxs);
1376         free(env->me_path);
1377
1378         pthread_key_delete(env->me_txkey);
1379
1380         if (env->me_map) {
1381                 munmap(env->me_map, env->me_mapsize);
1382         }
1383         close(env->me_fd);
1384         if (env->me_txns) {
1385                 pid_t pid = getpid();
1386                 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1387                 int i;
1388                 for (i=0; i<env->me_txns->mti_numreaders; i++)
1389                         if (env->me_txns->mti_readers[i].mr_pid == pid)
1390                                 env->me_txns->mti_readers[i].mr_pid = 0;
1391                 munmap(env->me_txns, size);
1392         }
1393         close(env->me_lfd);
1394         free(env);
1395 }
1396
1397 /* Search for key within a leaf page, using binary search.
1398  * Returns the smallest entry larger or equal to the key.
1399  * If exactp is non-null, stores whether the found entry was an exact match
1400  * in *exactp (1 or 0).
1401  * If kip is non-null, stores the index of the found entry in *kip.
1402  * If no entry larger or equal to the key is found, returns NULL.
1403  */
1404 static MDB_node *
1405 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1406     int *exactp, unsigned int *kip)
1407 {
1408         unsigned int     i = 0;
1409         int              low, high;
1410         int              rc = 0;
1411         MDB_node        *node;
1412         MDB_val  nodekey;
1413
1414         DPRINTF("searching %u keys in %s page %lu",
1415             NUMKEYS(mp),
1416             IS_LEAF(mp) ? "leaf" : "branch",
1417             mp->mp_pgno);
1418
1419         assert(NUMKEYS(mp) > 0);
1420
1421         memset(&nodekey, 0, sizeof(nodekey));
1422
1423         low = IS_LEAF(mp) ? 0 : 1;
1424         high = NUMKEYS(mp) - 1;
1425         while (low <= high) {
1426                 i = (low + high) >> 1;
1427                 node = NODEPTR(mp, i);
1428
1429                 nodekey.mv_size = node->mn_ksize;
1430                 nodekey.mv_data = NODEKEY(node);
1431
1432                 if (txn->mt_dbxs[dbi].md_cmp)
1433                         rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1434                 else
1435                         rc = _mdb_cmp(txn, dbi, key, &nodekey);
1436
1437                 if (IS_LEAF(mp))
1438                         DPRINTF("found leaf index %u [%.*s], rc = %i",
1439                             i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1440                 else
1441                         DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1442                             i, (int)node->mn_ksize, (char *)NODEKEY(node),
1443                             node->mn_pgno, rc);
1444
1445                 if (rc == 0)
1446                         break;
1447                 if (rc > 0)
1448                         low = i + 1;
1449                 else
1450                         high = i - 1;
1451         }
1452
1453         if (rc > 0) {   /* Found entry is less than the key. */
1454                 i++;    /* Skip to get the smallest entry larger than key. */
1455                 if (i >= NUMKEYS(mp))
1456                         /* There is no entry larger or equal to the key. */
1457                         return NULL;
1458         }
1459         if (exactp)
1460                 *exactp = (rc == 0);
1461         if (kip)        /* Store the key index if requested. */
1462                 *kip = i;
1463
1464         return NODEPTR(mp, i);
1465 }
1466
1467 static void
1468 cursor_pop_page(MDB_cursor *cursor)
1469 {
1470         MDB_ppage       *top;
1471
1472         top = CURSOR_TOP(cursor);
1473         CURSOR_POP(cursor);
1474
1475         DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1476
1477         free(top);
1478 }
1479
1480 static MDB_ppage *
1481 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1482 {
1483         MDB_ppage       *ppage;
1484
1485         DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1486
1487         if ((ppage = calloc(1, sizeof(MDB_ppage))) == NULL)
1488                 return NULL;
1489         ppage->mp_page = mp;
1490         CURSOR_PUSH(cursor, ppage);
1491         return ppage;
1492 }
1493
1494 static MDB_page *
1495 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1496 {
1497         MDB_page *p = NULL;
1498         int found = 0;
1499
1500         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1501                 MDB_dpage *dp;
1502                 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1503                         if (dp->p.mp_pgno == pgno) {
1504                                 p = &dp->p;
1505                                 found = 1;
1506                                 break;
1507                         }
1508                 }
1509         }
1510         if (!found) {
1511                 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1512                         return NULL;
1513                 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1514         }
1515         return p;
1516 }
1517
1518 static int
1519 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1520     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1521 {
1522         MDB_page        *mp = mpp->mp_page;
1523         int rc;
1524
1525         if (cursor && cursor_push_page(cursor, mp) == NULL)
1526                 return MDB_FAIL;
1527
1528         while (IS_BRANCH(mp)) {
1529                 unsigned int     i = 0;
1530                 MDB_node        *node;
1531
1532                 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1533                 assert(NUMKEYS(mp) > 1);
1534                 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1535
1536                 if (key == NULL)        /* Initialize cursor to first page. */
1537                         i = 0;
1538                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1539                                                         /* cursor to last page */
1540                         i = NUMKEYS(mp)-1;
1541                 } else {
1542                         int      exact;
1543                         node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1544                         if (node == NULL)
1545                                 i = NUMKEYS(mp) - 1;
1546                         else if (!exact) {
1547                                 assert(i > 0);
1548                                 i--;
1549                         }
1550                 }
1551
1552                 if (key)
1553                         DPRINTF("following index %u for key %.*s",
1554                             i, (int)key->mv_size, (char *)key->mv_data);
1555                 assert(i < NUMKEYS(mp));
1556                 node = NODEPTR(mp, i);
1557
1558                 if (cursor)
1559                         CURSOR_TOP(cursor)->mp_ki = i;
1560
1561                 mpp->mp_parent = mp;
1562                 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1563                         return MDB_FAIL;
1564                 mpp->mp_pi = i;
1565                 mpp->mp_page = mp;
1566
1567                 if (cursor && cursor_push_page(cursor, mp) == NULL)
1568                         return MDB_FAIL;
1569
1570                 if (modify) {
1571                         MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1572                         if ((rc = mdb_touch(txn, mpp)) != 0)
1573                                 return rc;
1574                         dh = ((MDB_dhead *)mpp->mp_page)-1;
1575                         dh->md_parent = mpp->mp_parent;
1576                         dh->md_pi = mpp->mp_pi;
1577                 }
1578
1579                 mp = mpp->mp_page;
1580         }
1581
1582         if (!IS_LEAF(mp)) {
1583                 DPRINTF("internal error, index points to a %02X page!?",
1584                     mp->mp_flags);
1585                 return MDB_FAIL;
1586         }
1587
1588         DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1589             key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1590
1591         return MDB_SUCCESS;
1592 }
1593
1594 /* Search for the page a given key should be in.
1595  * Stores a pointer to the found page in *mpp.
1596  * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1597  * If cursor is non-null, pushes parent pages on the cursor stack.
1598  * If modify is true, visited pages are updated with new page numbers.
1599  */
1600 static int
1601 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1602     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1603 {
1604         int              rc;
1605         pgno_t           root;
1606
1607         /* Choose which root page to start with. If a transaction is given
1608          * use the root page from the transaction, otherwise read the last
1609          * committed root page.
1610          */
1611         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1612                 DPRINTF("transaction has failed, must abort");
1613                 return EINVAL;
1614         } else
1615                 root = txn->mt_dbs[dbi].md_root;
1616
1617         if (root == P_INVALID) {                /* Tree is empty. */
1618                 DPRINTF("tree is empty");
1619                 return MDB_NOTFOUND;
1620         }
1621
1622         if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1623                 return MDB_FAIL;
1624
1625         DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1626
1627         if (modify) {
1628                 /* For sub-databases, update main root first */
1629                 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1630                         MDB_pageparent mp2;
1631                         rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1632                                 NULL, 1, &mp2);
1633                         if (rc)
1634                                 return rc;
1635                         txn->mt_dbxs[dbi].md_dirty = 1;
1636                 }
1637                 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1638                         mpp->mp_parent = NULL;
1639                         mpp->mp_pi = 0;
1640                         if ((rc = mdb_touch(txn, mpp)))
1641                                 return rc;
1642                         txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1643                 }
1644         }
1645
1646         return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1647 }
1648
1649 static int
1650 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1651 {
1652         MDB_page        *omp;           /* overflow mpage */
1653         pgno_t           pgno;
1654
1655         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1656                 data->mv_size = leaf->mn_dsize;
1657                 data->mv_data = NODEDATA(leaf);
1658                 return MDB_SUCCESS;
1659         }
1660
1661         /* Read overflow data.
1662          */
1663         data->mv_size = leaf->mn_dsize;
1664         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1665         if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1666                 DPRINTF("read overflow page %lu failed", pgno);
1667                 return MDB_FAIL;
1668         }
1669         data->mv_data = omp;
1670
1671         return MDB_SUCCESS;
1672 }
1673
1674 int
1675 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1676     MDB_val *key, MDB_val *data)
1677 {
1678         int              rc, exact;
1679         MDB_node        *leaf;
1680         MDB_pageparent mpp;
1681
1682         assert(key);
1683         assert(data);
1684         DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1685
1686         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1687                 return EINVAL;
1688
1689         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1690                 return EINVAL;
1691         }
1692
1693         if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1694                 return rc;
1695
1696         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1697         if (leaf && exact) {
1698                 /* Return first duplicate data item */
1699                 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1700                         MDB_xcursor mx;
1701
1702                         mdb_xcursor_init0(txn, dbi, &mx);
1703                         mdb_xcursor_init1(txn, dbi, &mx, leaf);
1704                         rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1705                         if (rc != MDB_SUCCESS)
1706                                 return rc;
1707                         leaf = NODEPTR(mpp.mp_page, 0);
1708                 }
1709                 rc = mdb_read_data(txn, leaf, data);
1710         } else {
1711                 rc = MDB_NOTFOUND;
1712         }
1713
1714         return rc;
1715 }
1716
1717 static int
1718 mdb_sibling(MDB_cursor *cursor, int move_right)
1719 {
1720         int              rc;
1721         MDB_node        *indx;
1722         MDB_ppage       *parent, *top;
1723         MDB_page        *mp;
1724
1725         top = CURSOR_TOP(cursor);
1726         if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1727                 return MDB_NOTFOUND;            /* root has no siblings */
1728         }
1729
1730         DPRINTF("parent page is page %lu, index %u",
1731             parent->mp_page->mp_pgno, parent->mp_ki);
1732
1733         cursor_pop_page(cursor);
1734         if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1735                        : (parent->mp_ki == 0)) {
1736                 DPRINTF("no more keys left, moving to %s sibling",
1737                     move_right ? "right" : "left");
1738                 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1739                         return rc;
1740                 parent = CURSOR_TOP(cursor);
1741         } else {
1742                 if (move_right)
1743                         parent->mp_ki++;
1744                 else
1745                         parent->mp_ki--;
1746                 DPRINTF("just moving to %s index key %u",
1747                     move_right ? "right" : "left", parent->mp_ki);
1748         }
1749         assert(IS_BRANCH(parent->mp_page));
1750
1751         indx = NODEPTR(parent->mp_page, parent->mp_ki);
1752         if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1753                 return MDB_FAIL;
1754 #if 0
1755         mp->parent = parent->mp_page;
1756         mp->parent_index = parent->mp_ki;
1757 #endif
1758
1759         cursor_push_page(cursor, mp);
1760
1761         return MDB_SUCCESS;
1762 }
1763
1764 static int
1765 mdb_set_key(MDB_node *node, MDB_val *key)
1766 {
1767         if (key == NULL)
1768                 return 0;
1769
1770         key->mv_size = node->mn_ksize;
1771         key->mv_data = NODEKEY(node);
1772
1773         return 0;
1774 }
1775
1776 static int
1777 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1778 {
1779         MDB_ppage       *top;
1780         MDB_page        *mp;
1781         MDB_node        *leaf;
1782         int rc;
1783
1784         if (cursor->mc_eof) {
1785                 return MDB_NOTFOUND;
1786         }
1787
1788         assert(cursor->mc_initialized);
1789
1790         if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1791                 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
1792                         rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
1793                         if (op != MDB_NEXT || rc == MDB_SUCCESS)
1794                                 return rc;
1795                 }
1796         }
1797
1798         top = CURSOR_TOP(cursor);
1799         mp = top->mp_page;
1800
1801         DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1802
1803         if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1804                 DPRINTF("=====> move to next sibling page");
1805                 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1806                         cursor->mc_eof = 1;
1807                         return MDB_NOTFOUND;
1808                 }
1809                 top = CURSOR_TOP(cursor);
1810                 mp = top->mp_page;
1811                 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1812         } else
1813                 top->mp_ki++;
1814
1815         DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1816             mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1817
1818         assert(IS_LEAF(mp));
1819         leaf = NODEPTR(mp, top->mp_ki);
1820
1821         if (data) {
1822                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1823                         return rc;
1824
1825                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1826                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1827                         rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1828                         if (rc != MDB_SUCCESS)
1829                                 return rc;
1830                 }
1831         }
1832
1833         return mdb_set_key(leaf, key);
1834 }
1835
1836 static int
1837 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1838 {
1839         MDB_ppage       *top;
1840         MDB_page        *mp;
1841         MDB_node        *leaf;
1842         int rc;
1843
1844         assert(cursor->mc_initialized);
1845
1846         if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1847                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
1848                         rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
1849                         if (op != MDB_PREV || rc == MDB_SUCCESS)
1850                                 return rc;
1851                 }
1852         }
1853
1854         top = CURSOR_TOP(cursor);
1855         mp = top->mp_page;
1856
1857         DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1858
1859         if (top->mp_ki == 0)  {
1860                 DPRINTF("=====> move to prev sibling page");
1861                 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1862                         return MDB_NOTFOUND;
1863                 }
1864                 top = CURSOR_TOP(cursor);
1865                 mp = top->mp_page;
1866                 top->mp_ki = NUMKEYS(mp) - 1;
1867                 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1868         } else
1869                 top->mp_ki--;
1870
1871         cursor->mc_eof = 0;
1872
1873         DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1874             mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1875
1876         assert(IS_LEAF(mp));
1877         leaf = NODEPTR(mp, top->mp_ki);
1878
1879         if (data) {
1880                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1881                         return rc;
1882
1883                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1884                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1885                         rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
1886                         if (rc != MDB_SUCCESS)
1887                                 return rc;
1888                 }
1889         }
1890
1891         return mdb_set_key(leaf, key);
1892 }
1893
1894 static int
1895 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1896     MDB_cursor_op op, int *exactp)
1897 {
1898         int              rc;
1899         MDB_node        *leaf;
1900         MDB_ppage       *top;
1901         MDB_pageparent mpp;
1902
1903         assert(cursor);
1904         assert(key);
1905         assert(key->mv_size > 0);
1906
1907         while (CURSOR_TOP(cursor) != NULL)
1908                 cursor_pop_page(cursor);
1909
1910         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1911         if (rc != MDB_SUCCESS)
1912                 return rc;
1913         assert(IS_LEAF(mpp.mp_page));
1914
1915         top = CURSOR_TOP(cursor);
1916         leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1917         if (exactp != NULL && !*exactp) {
1918                 /* MDB_SET specified and not an exact match. */
1919                 return MDB_NOTFOUND;
1920         }
1921
1922         if (leaf == NULL) {
1923                 DPRINTF("===> inexact leaf not found, goto sibling");
1924                 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1925                         return rc;              /* no entries matched */
1926                 top = CURSOR_TOP(cursor);
1927                 top->mp_ki = 0;
1928                 mpp.mp_page = top->mp_page;
1929                 assert(IS_LEAF(mpp.mp_page));
1930                 leaf = NODEPTR(mpp.mp_page, 0);
1931         }
1932
1933         cursor->mc_initialized = 1;
1934         cursor->mc_eof = 0;
1935
1936         if (data) {
1937                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1938                         return rc;
1939
1940                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1941                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1942                         if (op == MDB_SET || op == MDB_SET_RANGE) {
1943                                 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1944                         } else {
1945                                 int ex2, *ex2p;
1946                                 MDB_cursor_op op2;
1947                                 if (op == MDB_GET_BOTH) {
1948                                         ex2p = &ex2;
1949                                         op2 = MDB_SET;
1950                                 } else {
1951                                         ex2p = NULL;
1952                                         op2 = MDB_SET_RANGE;
1953                                 }
1954                                 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, op2, ex2p);
1955                                 if (rc != MDB_SUCCESS)
1956                                         return rc;
1957                         }
1958                 }
1959         }
1960
1961         rc = mdb_set_key(leaf, key);
1962         if (rc == MDB_SUCCESS) {
1963                 DPRINTF("==> cursor placed on key %.*s",
1964                         (int)key->mv_size, (char *)key->mv_data);
1965                 ;
1966         }
1967
1968         return rc;
1969 }
1970
1971 static int
1972 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1973 {
1974         int              rc;
1975         MDB_pageparent  mpp;
1976         MDB_node        *leaf;
1977
1978         while (CURSOR_TOP(cursor) != NULL)
1979                 cursor_pop_page(cursor);
1980
1981         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1982         if (rc != MDB_SUCCESS)
1983                 return rc;
1984         assert(IS_LEAF(mpp.mp_page));
1985
1986         leaf = NODEPTR(mpp.mp_page, 0);
1987         cursor->mc_initialized = 1;
1988         cursor->mc_eof = 0;
1989
1990         if (data) {
1991                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1992                         return rc;
1993
1994                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1995                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1996                         rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1997                         if (rc)
1998                                 return rc;
1999                 }
2000         }
2001         return mdb_set_key(leaf, key);
2002 }
2003
2004 static int
2005 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2006 {
2007         int              rc;
2008         MDB_ppage       *top;
2009         MDB_pageparent  mpp;
2010         MDB_node        *leaf;
2011         MDB_val lkey;
2012
2013         while (CURSOR_TOP(cursor) != NULL)
2014                 cursor_pop_page(cursor);
2015
2016         lkey.mv_size = MAXKEYSIZE+1;
2017         lkey.mv_data = NULL;
2018
2019         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2020         if (rc != MDB_SUCCESS)
2021                 return rc;
2022         assert(IS_LEAF(mpp.mp_page));
2023
2024         leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2025         cursor->mc_initialized = 1;
2026         cursor->mc_eof = 0;
2027
2028         top = CURSOR_TOP(cursor);
2029         top->mp_ki = NUMKEYS(top->mp_page) - 1;
2030
2031         if (data) {
2032                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2033                         return rc;
2034
2035                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2036                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2037                         rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2038                         if (rc)
2039                                 return rc;
2040                 }
2041         }
2042
2043         return mdb_set_key(leaf, key);
2044 }
2045
2046 int
2047 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2048     MDB_cursor_op op)
2049 {
2050         int              rc;
2051         int              exact = 0;
2052
2053         assert(cursor);
2054
2055         switch (op) {
2056         case MDB_GET_BOTH:
2057         case MDB_GET_BOTH_RANGE:
2058                 if (data == NULL) {
2059                         rc = EINVAL;
2060                         break;
2061                 }
2062                 /* FALLTHRU */
2063         case MDB_SET:
2064         case MDB_SET_RANGE:
2065                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2066                         rc = EINVAL;
2067                 } else if (op != MDB_SET_RANGE)
2068                         rc = mdb_cursor_set(cursor, key, data, op, NULL);
2069                 else
2070                         rc = mdb_cursor_set(cursor, key, data, op, &exact);
2071                 break;
2072         case MDB_NEXT:
2073         case MDB_NEXT_DUP:
2074         case MDB_NEXT_NODUP:
2075                 if (!cursor->mc_initialized)
2076                         rc = mdb_cursor_first(cursor, key, data);
2077                 else
2078                         rc = mdb_cursor_next(cursor, key, data, op);
2079                 break;
2080         case MDB_PREV:
2081         case MDB_PREV_DUP:
2082         case MDB_PREV_NODUP:
2083                 if (!cursor->mc_initialized || cursor->mc_eof)
2084                         rc = mdb_cursor_last(cursor, key, data);
2085                 else
2086                         rc = mdb_cursor_prev(cursor, key, data, op);
2087                 break;
2088         case MDB_FIRST:
2089                 rc = mdb_cursor_first(cursor, key, data);
2090                 break;
2091         case MDB_LAST:
2092                 rc = mdb_cursor_last(cursor, key, data);
2093                 break;
2094         default:
2095                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2096                 rc = EINVAL;
2097                 break;
2098         }
2099
2100         return rc;
2101 }
2102
2103 /* Allocate a page and initialize it
2104  */
2105 static MDB_dpage *
2106 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2107 {
2108         MDB_dpage       *dp;
2109
2110         if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2111                 return NULL;
2112         DPRINTF("allocated new mpage %lu, page size %u",
2113             dp->p.mp_pgno, txn->mt_env->me_psize);
2114         dp->p.mp_flags = flags | P_DIRTY;
2115         dp->p.mp_lower = PAGEHDRSZ;
2116         dp->p.mp_upper = txn->mt_env->me_psize;
2117
2118         if (IS_BRANCH(&dp->p))
2119                 txn->mt_dbs[dbi].md_branch_pages++;
2120         else if (IS_LEAF(&dp->p))
2121                 txn->mt_dbs[dbi].md_leaf_pages++;
2122         else if (IS_OVERFLOW(&dp->p)) {
2123                 txn->mt_dbs[dbi].md_overflow_pages += num;
2124                 dp->p.mp_pages = num;
2125         }
2126
2127         return dp;
2128 }
2129
2130 static size_t
2131 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2132 {
2133         size_t           sz;
2134
2135         sz = LEAFSIZE(key, data);
2136         if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2137                 /* put on overflow page */
2138                 sz -= data->mv_size - sizeof(pgno_t);
2139         }
2140
2141         return sz + sizeof(indx_t);
2142 }
2143
2144 static size_t
2145 mdb_branch_size(MDB_env *env, MDB_val *key)
2146 {
2147         size_t           sz;
2148
2149         sz = INDXSIZE(key);
2150         if (sz >= env->me_psize / MDB_MINKEYS) {
2151                 /* put on overflow page */
2152                 /* not implemented */
2153                 /* sz -= key->size - sizeof(pgno_t); */
2154         }
2155
2156         return sz + sizeof(indx_t);
2157 }
2158
2159 static int
2160 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2161     MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2162 {
2163         unsigned int     i;
2164         size_t           node_size = NODESIZE;
2165         indx_t           ofs;
2166         MDB_node        *node;
2167         MDB_dpage       *ofp = NULL;            /* overflow page */
2168
2169         assert(mp->mp_upper >= mp->mp_lower);
2170
2171         DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2172             key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2173             IS_LEAF(mp) ? "leaf" : "branch",
2174             mp->mp_pgno, indx, key ? key->mv_size : 0);
2175
2176         if (key != NULL)
2177                 node_size += key->mv_size;
2178
2179         if (IS_LEAF(mp)) {
2180                 assert(data);
2181                 if (F_ISSET(flags, F_BIGDATA)) {
2182                         /* Data already on overflow page. */
2183                         node_size += sizeof(pgno_t);
2184                 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2185                         int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2186                         /* Put data on overflow page. */
2187                         DPRINTF("data size is %zu, put on overflow page",
2188                             data->mv_size);
2189                         node_size += sizeof(pgno_t);
2190                         if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2191                                 return MDB_FAIL;
2192                         DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2193                         flags |= F_BIGDATA;
2194                 } else {
2195                         node_size += data->mv_size;
2196                 }
2197         }
2198
2199         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2200                 DPRINTF("not enough room in page %lu, got %u ptrs",
2201                     mp->mp_pgno, NUMKEYS(mp));
2202                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2203                     mp->mp_upper - mp->mp_lower);
2204                 DPRINTF("node size = %zu", node_size);
2205                 return ENOSPC;
2206         }
2207
2208         /* Move higher pointers up one slot. */
2209         for (i = NUMKEYS(mp); i > indx; i--)
2210                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2211
2212         /* Adjust free space offsets. */
2213         ofs = mp->mp_upper - node_size;
2214         assert(ofs >= mp->mp_lower + sizeof(indx_t));
2215         mp->mp_ptrs[indx] = ofs;
2216         mp->mp_upper = ofs;
2217         mp->mp_lower += sizeof(indx_t);
2218
2219         /* Write the node data. */
2220         node = NODEPTR(mp, indx);
2221         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2222         node->mn_flags = flags;
2223         if (IS_LEAF(mp))
2224                 node->mn_dsize = data->mv_size;
2225         else
2226                 node->mn_pgno = pgno;
2227
2228         if (key)
2229                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2230
2231         if (IS_LEAF(mp)) {
2232                 assert(key);
2233                 if (ofp == NULL) {
2234                         if (F_ISSET(flags, F_BIGDATA))
2235                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
2236                                     sizeof(pgno_t));
2237                         else
2238                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
2239                                     data->mv_size);
2240                 } else {
2241                         memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2242                             sizeof(pgno_t));
2243                         memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2244                 }
2245         }
2246
2247         return MDB_SUCCESS;
2248 }
2249
2250 static void
2251 mdb_del_node(MDB_page *mp, indx_t indx)
2252 {
2253         unsigned int     sz;
2254         indx_t           i, j, numkeys, ptr;
2255         MDB_node        *node;
2256         char            *base;
2257
2258         DPRINTF("delete node %u on %s page %lu", indx,
2259             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2260         assert(indx < NUMKEYS(mp));
2261
2262         node = NODEPTR(mp, indx);
2263         sz = NODESIZE + node->mn_ksize;
2264         if (IS_LEAF(mp)) {
2265                 if (F_ISSET(node->mn_flags, F_BIGDATA))
2266                         sz += sizeof(pgno_t);
2267                 else
2268                         sz += NODEDSZ(node);
2269         }
2270
2271         ptr = mp->mp_ptrs[indx];
2272         numkeys = NUMKEYS(mp);
2273         for (i = j = 0; i < numkeys; i++) {
2274                 if (i != indx) {
2275                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
2276                         if (mp->mp_ptrs[i] < ptr)
2277                                 mp->mp_ptrs[j] += sz;
2278                         j++;
2279                 }
2280         }
2281
2282         base = (char *)mp + mp->mp_upper;
2283         memmove(base + sz, base, ptr - mp->mp_upper);
2284
2285         mp->mp_lower -= sizeof(indx_t);
2286         mp->mp_upper += sz;
2287 }
2288
2289 static void
2290 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2291 {
2292         MDB_dbi dbn;
2293
2294         mx->mx_txn = *txn;
2295         mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2296         mx->mx_txn.mt_dbs = mx->mx_dbs;
2297         mx->mx_dbxs[0] = txn->mt_dbxs[0];
2298         mx->mx_dbxs[1] = txn->mt_dbxs[1];
2299         if (dbi > 1) {
2300                 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2301                 dbn = 2;
2302         } else {
2303                 dbn = 1;
2304         }
2305         mx->mx_dbxs[dbn+1].md_parent = dbn;
2306         mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2307         mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2308         mx->mx_dbxs[dbn+1].md_dirty = 0;
2309         mx->mx_txn.mt_numdbs = dbn+2;
2310
2311         SLIST_INIT(&mx->mx_cursor.mc_stack);
2312         mx->mx_cursor.mc_txn = &mx->mx_txn;
2313         mx->mx_cursor.mc_dbi = dbn+1;
2314 }
2315
2316 static void
2317 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node)
2318 {
2319         MDB_db *db = NODEDATA(node);
2320         MDB_dbi dbn;
2321         mx->mx_dbs[0] = txn->mt_dbs[0];
2322         mx->mx_dbs[1] = txn->mt_dbs[1];
2323         if (dbi > 1) {
2324                 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2325                 dbn = 3;
2326         } else {
2327                 dbn = 2;
2328         }
2329         mx->mx_dbs[dbn] = *db;
2330         mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2331         mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2332         mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2333         mx->mx_txn.mt_oldest = txn->mt_oldest;
2334         mx->mx_txn.mt_u = txn->mt_u;
2335 }
2336
2337 static void
2338 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2339 {
2340         txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2341         txn->mt_oldest = mx->mx_txn.mt_oldest;
2342         txn->mt_u = mx->mx_txn.mt_u;
2343         txn->mt_dbs[0] = mx->mx_dbs[0];
2344         txn->mt_dbs[1] = mx->mx_dbs[1];
2345         txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2346         txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2347         if (dbi > 1) {
2348                 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2349                 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2350         }
2351 }
2352
2353 int
2354 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2355 {
2356         MDB_cursor      *cursor;
2357         size_t size = sizeof(MDB_cursor);
2358
2359         if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2360                 return EINVAL;
2361
2362         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2363                 size += sizeof(MDB_xcursor);
2364
2365         if ((cursor = calloc(1, size)) != NULL) {
2366                 SLIST_INIT(&cursor->mc_stack);
2367                 cursor->mc_dbi = dbi;
2368                 cursor->mc_txn = txn;
2369                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2370                         MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2371                         cursor->mc_xcursor = mx;
2372                         mdb_xcursor_init0(txn, dbi, mx);
2373                 }
2374         } else {
2375                 return ENOMEM;
2376         }
2377
2378         *ret = cursor;
2379
2380         return MDB_SUCCESS;
2381 }
2382
2383 /* Return the count of duplicate data items for the current key */
2384 int
2385 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2386 {
2387         if (mc == NULL || countp == NULL)
2388                 return EINVAL;
2389
2390         if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2391                 return EINVAL;
2392
2393         if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2394                 return EINVAL;
2395
2396         *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2397         return MDB_SUCCESS;
2398 }
2399
2400 void
2401 mdb_cursor_close(MDB_cursor *cursor)
2402 {
2403         if (cursor != NULL) {
2404                 while(!CURSOR_EMPTY(cursor))
2405                         cursor_pop_page(cursor);
2406                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2407                         mdb_xcursor_fini(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor);
2408                         while(!CURSOR_EMPTY(&cursor->mc_xcursor->mx_cursor))
2409                                 cursor_pop_page(&cursor->mc_xcursor->mx_cursor);
2410                 }
2411
2412                 free(cursor);
2413         }
2414 }
2415
2416 static int
2417 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2418 {
2419         indx_t                   ptr, i, numkeys;
2420         int                      delta;
2421         size_t                   len;
2422         MDB_node                *node;
2423         char                    *base;
2424
2425         node = NODEPTR(mp, indx);
2426         ptr = mp->mp_ptrs[indx];
2427         DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2428             indx, ptr,
2429             (int)node->mn_ksize, (char *)NODEKEY(node),
2430             (int)key->mv_size, (char *)key->mv_data,
2431             mp->mp_pgno);
2432
2433         delta = key->mv_size - node->mn_ksize;
2434         if (delta) {
2435                 if (delta > 0 && SIZELEFT(mp) < delta) {
2436                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
2437                         return ENOSPC;
2438                 }
2439
2440                 numkeys = NUMKEYS(mp);
2441                 for (i = 0; i < numkeys; i++) {
2442                         if (mp->mp_ptrs[i] <= ptr)
2443                                 mp->mp_ptrs[i] -= delta;
2444                 }
2445
2446                 base = (char *)mp + mp->mp_upper;
2447                 len = ptr - mp->mp_upper + NODESIZE;
2448                 memmove(base - delta, base, len);
2449                 mp->mp_upper -= delta;
2450
2451                 node = NODEPTR(mp, indx);
2452                 node->mn_ksize = key->mv_size;
2453         }
2454
2455         memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2456
2457         return MDB_SUCCESS;
2458 }
2459
2460 /* Move a node from src to dst.
2461  */
2462 static int
2463 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2464     MDB_pageparent *dst, indx_t dstindx)
2465 {
2466         int                      rc;
2467         MDB_node                *srcnode;
2468         MDB_val          key, data;
2469
2470         srcnode = NODEPTR(src->mp_page, srcindx);
2471         DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2472             IS_LEAF(src->mp_page) ? "leaf" : "branch",
2473             srcindx,
2474             (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2475             src->mp_page->mp_pgno,
2476             dstindx, dst->mp_page->mp_pgno);
2477
2478         /* Mark src and dst as dirty. */
2479         if ((rc = mdb_touch(txn, src)) ||
2480             (rc = mdb_touch(txn, dst)))
2481                 return rc;;
2482
2483         /* Add the node to the destination page.
2484          */
2485         key.mv_size = srcnode->mn_ksize;
2486         key.mv_data = NODEKEY(srcnode);
2487         data.mv_size = NODEDSZ(srcnode);
2488         data.mv_data = NODEDATA(srcnode);
2489         rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2490             srcnode->mn_flags);
2491         if (rc != MDB_SUCCESS)
2492                 return rc;
2493
2494         /* Delete the node from the source page.
2495          */
2496         mdb_del_node(src->mp_page, srcindx);
2497
2498         /* Update the parent separators.
2499          */
2500         if (srcindx == 0 && src->mp_pi != 0) {
2501                 DPRINTF("update separator for source page %lu to [%.*s]",
2502                     src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2503                 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2504                     &key)) != MDB_SUCCESS)
2505                         return rc;
2506         }
2507
2508         if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2509                 MDB_val  nullkey;
2510                 nullkey.mv_size = 0;
2511                 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2512         }
2513
2514         if (dstindx == 0 && dst->mp_pi != 0) {
2515                 DPRINTF("update separator for destination page %lu to [%.*s]",
2516                     dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2517                 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2518                     &key)) != MDB_SUCCESS)
2519                         return rc;
2520         }
2521
2522         if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2523                 MDB_val  nullkey;
2524                 nullkey.mv_size = 0;
2525                 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2526         }
2527
2528         return MDB_SUCCESS;
2529 }
2530
2531 static int
2532 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2533 {
2534         int                      rc;
2535         indx_t                   i;
2536         MDB_node                *srcnode;
2537         MDB_val          key, data;
2538         MDB_pageparent  mpp;
2539         MDB_dhead *dh;
2540
2541         DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2542
2543         assert(txn != NULL);
2544         assert(src->mp_parent); /* can't merge root page */
2545         assert(dst->mp_parent);
2546
2547         /* Mark src and dst as dirty. */
2548         if ((rc = mdb_touch(txn, src)) ||
2549             (rc = mdb_touch(txn, dst)))
2550                 return rc;
2551
2552         /* Move all nodes from src to dst.
2553          */
2554         for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2555                 srcnode = NODEPTR(src->mp_page, i);
2556
2557                 key.mv_size = srcnode->mn_ksize;
2558                 key.mv_data = NODEKEY(srcnode);
2559                 data.mv_size = NODEDSZ(srcnode);
2560                 data.mv_data = NODEDATA(srcnode);
2561                 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2562                     &data, NODEPGNO(srcnode), srcnode->mn_flags);
2563                 if (rc != MDB_SUCCESS)
2564                         return rc;
2565         }
2566
2567         DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2568             dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2569
2570         /* Unlink the src page from parent.
2571          */
2572         mdb_del_node(src->mp_parent, src->mp_pi);
2573         if (src->mp_pi == 0) {
2574                 key.mv_size = 0;
2575                 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2576                         return rc;
2577         }
2578
2579         if (IS_LEAF(src->mp_page))
2580                 txn->mt_dbs[dbi].md_leaf_pages--;
2581         else
2582                 txn->mt_dbs[dbi].md_branch_pages--;
2583
2584         mpp.mp_page = src->mp_parent;
2585         dh = (MDB_dhead *)src->mp_parent;
2586         dh--;
2587         mpp.mp_parent = dh->md_parent;
2588         mpp.mp_pi = dh->md_pi;
2589
2590         return mdb_rebalance(txn, dbi, &mpp);
2591 }
2592
2593 #define FILL_THRESHOLD   250
2594
2595 static int
2596 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2597 {
2598         MDB_node        *node;
2599         MDB_page        *root;
2600         MDB_pageparent npp;
2601         indx_t           si = 0, di = 0;
2602
2603         assert(txn != NULL);
2604         assert(mpp != NULL);
2605
2606         DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2607             IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2608             mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2609
2610         if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2611                 DPRINTF("no need to rebalance page %lu, above fill threshold",
2612                     mpp->mp_page->mp_pgno);
2613                 return MDB_SUCCESS;
2614         }
2615
2616         if (mpp->mp_parent == NULL) {
2617                 if (NUMKEYS(mpp->mp_page) == 0) {
2618                         DPRINTF("tree is completely empty");
2619                         txn->mt_dbs[dbi].md_root = P_INVALID;
2620                         txn->mt_dbs[dbi].md_depth--;
2621                         txn->mt_dbs[dbi].md_leaf_pages--;
2622                 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2623                         DPRINTF("collapsing root page!");
2624                         txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2625                         if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2626                                 return MDB_FAIL;
2627                         txn->mt_dbs[dbi].md_depth--;
2628                         txn->mt_dbs[dbi].md_branch_pages--;
2629                 } else
2630                         DPRINTF("root page doesn't need rebalancing");
2631                 return MDB_SUCCESS;
2632         }
2633
2634         /* The parent (branch page) must have at least 2 pointers,
2635          * otherwise the tree is invalid.
2636          */
2637         assert(NUMKEYS(mpp->mp_parent) > 1);
2638
2639         /* Leaf page fill factor is below the threshold.
2640          * Try to move keys from left or right neighbor, or
2641          * merge with a neighbor page.
2642          */
2643
2644         /* Find neighbors.
2645          */
2646         if (mpp->mp_pi == 0) {
2647                 /* We're the leftmost leaf in our parent.
2648                  */
2649                 DPRINTF("reading right neighbor");
2650                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2651                 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2652                         return MDB_FAIL;
2653                 npp.mp_pi = mpp->mp_pi + 1;
2654                 si = 0;
2655                 di = NUMKEYS(mpp->mp_page);
2656         } else {
2657                 /* There is at least one neighbor to the left.
2658                  */
2659                 DPRINTF("reading left neighbor");
2660                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2661                 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2662                         return MDB_FAIL;
2663                 npp.mp_pi = mpp->mp_pi - 1;
2664                 si = NUMKEYS(npp.mp_page) - 1;
2665                 di = 0;
2666         }
2667         npp.mp_parent = mpp->mp_parent;
2668
2669         DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2670             npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2671
2672         /* If the neighbor page is above threshold and has at least two
2673          * keys, move one key from it.
2674          *
2675          * Otherwise we should try to merge them.
2676          */
2677         if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2678                 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2679         else { /* FIXME: if (has_enough_room()) */
2680                 if (mpp->mp_pi == 0)
2681                         return mdb_merge(txn, dbi, &npp, mpp);
2682                 else
2683                         return mdb_merge(txn, dbi, mpp, &npp);
2684         }
2685 }
2686
2687 static int
2688 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2689 {
2690         int rc;
2691
2692         /* add overflow pages to free list */
2693         if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2694                 int i, ovpages;
2695                 pgno_t pg;
2696
2697                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2698                 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2699                 for (i=0; i<ovpages; i++) {
2700                         DPRINTF("freed ov page %lu", pg);
2701                         mdb_midl_insert(txn->mt_free_pgs, pg);
2702                         pg++;
2703                 }
2704         }
2705         mdb_del_node(mpp->mp_page, ki);
2706         txn->mt_dbs[dbi].md_entries--;
2707         rc = mdb_rebalance(txn, dbi, mpp);
2708         if (rc != MDB_SUCCESS)
2709                 txn->mt_flags |= MDB_TXN_ERROR;
2710
2711         return rc;
2712 }
2713
2714 int
2715 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2716     MDB_val *key, MDB_val *data,
2717         unsigned int flags)
2718 {
2719         int              rc, exact;
2720         unsigned int     ki;
2721         MDB_node        *leaf;
2722         MDB_pageparent  mpp;
2723
2724         DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2725
2726         assert(key != NULL);
2727
2728         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2729                 return EINVAL;
2730
2731         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2732                 return EINVAL;
2733         }
2734
2735         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2736                 return EINVAL;
2737         }
2738
2739         mpp.mp_parent = NULL;
2740         mpp.mp_pi = 0;
2741         if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2742                 return rc;
2743
2744         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2745         if (leaf == NULL || !exact) {
2746                 return MDB_NOTFOUND;
2747         }
2748
2749         if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2750                 MDB_xcursor mx;
2751                 MDB_pageparent mp2;
2752
2753                 mdb_xcursor_init0(txn, dbi, &mx);
2754                 mdb_xcursor_init1(txn, dbi, &mx, leaf);
2755                 if (flags == MDB_DEL_DUP) {
2756                         rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
2757                         mdb_xcursor_fini(txn, dbi, &mx);
2758                         if (rc != MDB_SUCCESS)
2759                                 return rc;
2760                         /* If sub-DB still has entries, we're done */
2761                         if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
2762                                 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
2763                                         sizeof(MDB_db));
2764                                 return rc;
2765                         }
2766                         /* otherwise fall thru and delete the sub-DB */
2767                 } else {
2768                         /* add all the child DB's pages to the free list */
2769                         rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2770                                 NULL, &mx.mx_cursor, 0, &mp2);
2771                         if (rc == MDB_SUCCESS) {
2772                                 MDB_ppage *top, *parent;
2773                                 MDB_node *ni;
2774                                 unsigned int i;
2775
2776                                 cursor_pop_page(&mx.mx_cursor);
2777                                 top = CURSOR_TOP(&mx.mx_cursor);
2778                                 if (top != NULL) {
2779                                         parent = SLIST_NEXT(top, mp_entry);
2780                                         while (parent != NULL) {
2781                                                 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2782                                                         ni = NODEPTR(top->mp_page, i);
2783                                                         mdb_midl_insert(txn->mt_free_pgs, ni->mn_pgno);
2784                                                 }
2785                                                 if (parent) {
2786                                                         parent->mp_ki++;
2787                                                         if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2788                                                                 cursor_pop_page(&mx.mx_cursor);
2789                                                                 top = CURSOR_TOP(&mx.mx_cursor);
2790                                                                 parent = SLIST_NEXT(top, mp_entry);
2791                                                         } else {
2792                                                                 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2793                                                                 top->mp_page = mdb_get_page(&mx.mx_txn, ni->mn_pgno);
2794                                                         }
2795                                                 }
2796                                         }
2797                                 }
2798                                 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2799                         }
2800                 }
2801         }
2802
2803         if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2804                 return rc;
2805
2806         return mdb_del0(txn, dbi, ki, &mpp, leaf);
2807 }
2808
2809 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2810  * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2811  * *newindxp with the actual values after split, ie if *mpp and *newindxp
2812  * refer to a node in the new right sibling page.
2813  */
2814 static int
2815 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2816     MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2817 {
2818         uint8_t          flags;
2819         int              rc = MDB_SUCCESS, ins_new = 0;
2820         indx_t           newindx;
2821         pgno_t           pgno = 0;
2822         unsigned int     i, j, split_indx;
2823         MDB_node        *node;
2824         MDB_val  sepkey, rkey, rdata;
2825         MDB_page        *copy;
2826         MDB_dpage       *mdp, *rdp, *pdp;
2827         MDB_dhead *dh;
2828
2829         assert(txn != NULL);
2830
2831         dh = ((MDB_dhead *)*mpp) - 1;
2832         mdp = (MDB_dpage *)dh;
2833         newindx = *newindxp;
2834
2835         DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2836             IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2837             (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2838
2839         if (mdp->h.md_parent == NULL) {
2840                 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2841                         return MDB_FAIL;
2842                 mdp->h.md_pi = 0;
2843                 mdp->h.md_parent = &pdp->p;
2844                 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2845                 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2846                 txn->mt_dbs[dbi].md_depth++;
2847
2848                 /* Add left (implicit) pointer. */
2849                 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2850                     mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2851                         return MDB_FAIL;
2852         } else {
2853                 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2854         }
2855
2856         /* Create a right sibling. */
2857         if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2858                 return MDB_FAIL;
2859         rdp->h.md_parent = mdp->h.md_parent;
2860         rdp->h.md_pi = mdp->h.md_pi + 1;
2861         DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2862
2863         /* Move half of the keys to the right sibling. */
2864         if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2865                 return MDB_FAIL;
2866         memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2867         memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2868         mdp->p.mp_lower = PAGEHDRSZ;
2869         mdp->p.mp_upper = txn->mt_env->me_psize;
2870
2871         split_indx = NUMKEYS(copy) / 2 + 1;
2872
2873         /* First find the separating key between the split pages.
2874          */
2875         memset(&sepkey, 0, sizeof(sepkey));
2876         if (newindx == split_indx) {
2877                 sepkey.mv_size = newkey->mv_size;
2878                 sepkey.mv_data = newkey->mv_data;
2879         } else {
2880                 node = NODEPTR(copy, split_indx);
2881                 sepkey.mv_size = node->mn_ksize;
2882                 sepkey.mv_data = NODEKEY(node);
2883         }
2884
2885         DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2886
2887         /* Copy separator key to the parent.
2888          */
2889         if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2890                 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2891                     &sepkey, NULL, rdp->p.mp_pgno);
2892
2893                 /* Right page might now have changed parent.
2894                  * Check if left page also changed parent.
2895                  */
2896                 if (rdp->h.md_parent != mdp->h.md_parent &&
2897                     mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2898                         mdp->h.md_parent = rdp->h.md_parent;
2899                         mdp->h.md_pi = rdp->h.md_pi - 1;
2900                 }
2901         } else {
2902                 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2903                     &sepkey, NULL, rdp->p.mp_pgno, 0);
2904         }
2905         if (rc != MDB_SUCCESS) {
2906                 free(copy);
2907                 return MDB_FAIL;
2908         }
2909
2910         for (i = j = 0; i <= NUMKEYS(copy); j++) {
2911                 if (i < split_indx) {
2912                         /* Re-insert in left sibling. */
2913                         pdp = mdp;
2914                 } else {
2915                         /* Insert in right sibling. */
2916                         if (i == split_indx)
2917                                 /* Reset insert index for right sibling. */
2918                                 j = (i == newindx && ins_new);
2919                         pdp = rdp;
2920                 }
2921
2922                 if (i == newindx && !ins_new) {
2923                         /* Insert the original entry that caused the split. */
2924                         rkey.mv_data = newkey->mv_data;
2925                         rkey.mv_size = newkey->mv_size;
2926                         if (IS_LEAF(&mdp->p)) {
2927                                 rdata.mv_data = newdata->mv_data;
2928                                 rdata.mv_size = newdata->mv_size;
2929                         } else
2930                                 pgno = newpgno;
2931                         flags = 0;
2932
2933                         ins_new = 1;
2934
2935                         /* Update page and index for the new key. */
2936                         *newindxp = j;
2937                         *mpp = &pdp->p;
2938                 } else if (i == NUMKEYS(copy)) {
2939                         break;
2940                 } else {
2941                         node = NODEPTR(copy, i);
2942                         rkey.mv_data = NODEKEY(node);
2943                         rkey.mv_size = node->mn_ksize;
2944                         if (IS_LEAF(&mdp->p)) {
2945                                 rdata.mv_data = NODEDATA(node);
2946                                 rdata.mv_size = node->mn_dsize;
2947                         } else
2948                                 pgno = node->mn_pgno;
2949                         flags = node->mn_flags;
2950
2951                         i++;
2952                 }
2953
2954                 if (!IS_LEAF(&mdp->p) && j == 0) {
2955                         /* First branch index doesn't need key data. */
2956                         rkey.mv_size = 0;
2957                 }
2958
2959                 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2960         }
2961
2962         free(copy);
2963         return rc;
2964 }
2965
2966 static int
2967 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
2968     MDB_val *key, MDB_val *data, unsigned int flags)
2969 {
2970         int              rc = MDB_SUCCESS, exact;
2971         unsigned int     ki;
2972         MDB_node        *leaf;
2973         MDB_pageparent  mpp;
2974         MDB_val xdata, *rdata;
2975         MDB_db dummy;
2976
2977         DPRINTF("==> put key %.*s, size %zu, data size %zu",
2978                 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2979
2980         mpp.mp_parent = NULL;
2981         mpp.mp_pi = 0;
2982         rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2983         if (rc == MDB_SUCCESS) {
2984                 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2985                 if (leaf && exact) {
2986                         if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2987                                 goto put_sub;
2988                         }
2989                         if (flags == MDB_NOOVERWRITE) {
2990                                 DPRINTF("duplicate key %.*s",
2991                                     (int)key->mv_size, (char *)key->mv_data);
2992                                 return MDB_KEYEXIST;
2993                         }
2994                         /* same size, just replace it */
2995                         if (NODEDSZ(leaf) == data->mv_size) {
2996                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
2997                                 goto done;
2998                         }
2999                         mdb_del_node(mpp.mp_page, ki);
3000                 }
3001                 if (leaf == NULL) {             /* append if not found */
3002                         ki = NUMKEYS(mpp.mp_page);
3003                         DPRINTF("appending key at index %i", ki);
3004                 }
3005         } else if (rc == MDB_NOTFOUND) {
3006                 MDB_dpage *dp;
3007                 /* new file, just write a root leaf page */
3008                 DPRINTF("allocating new root leaf page");
3009                 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3010                         return ENOMEM;
3011                 }
3012                 mpp.mp_page = &dp->p;
3013                 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3014                 txn->mt_dbs[dbi].md_depth++;
3015                 ki = 0;
3016         }
3017         else
3018                 goto done;
3019
3020         assert(IS_LEAF(mpp.mp_page));
3021         DPRINTF("there are %u keys, should insert new key at index %i",
3022                 NUMKEYS(mpp.mp_page), ki);
3023
3024         /* For sorted dups, the data item at this level is a DB record
3025          * for a child DB; the actual data elements are stored as keys
3026          * in the child DB.
3027          */
3028         if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3029                 rdata = &xdata;
3030                 xdata.mv_size = sizeof(MDB_db);
3031                 xdata.mv_data = &dummy;
3032                 memset(&dummy, 0, sizeof(dummy));
3033                 dummy.md_root = P_INVALID;
3034         } else {
3035                 rdata = data;
3036         }
3037
3038         if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, rdata)) {
3039                 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3040         } else {
3041                 /* There is room already in this leaf page. */
3042                 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3043         }
3044
3045         if (rc != MDB_SUCCESS)
3046                 txn->mt_flags |= MDB_TXN_ERROR;
3047         else {
3048                 txn->mt_dbs[dbi].md_entries++;
3049
3050                 /* Remember if we just added a subdatabase */
3051                 if (flags & F_SUBDATA) {
3052                         leaf = NODEPTR(mpp.mp_page, ki);
3053                         leaf->mn_flags |= F_SUBDATA;
3054                 }
3055
3056                 /* Now store the actual data in the child DB. Note that we're
3057                  * storing the user data in the keys field, so there are strict
3058                  * size limits on dupdata. The actual data fields of the child
3059                  * DB are all zero size.
3060                  */
3061                 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3062                         MDB_xcursor mx;
3063
3064                         leaf = NODEPTR(mpp.mp_page, ki);
3065 put_sub:
3066                         mdb_xcursor_init0(txn, dbi, &mx);
3067                         mdb_xcursor_init1(txn, dbi, &mx, leaf);
3068                         xdata.mv_size = 0;
3069                         xdata.mv_data = "";
3070                         if (flags == MDB_NODUPDATA)
3071                                 flags = MDB_NOOVERWRITE;
3072                         rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3073                         mdb_xcursor_fini(txn, dbi, &mx);
3074                         memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3075                                 sizeof(MDB_db));
3076                 }
3077         }
3078
3079 done:
3080         return rc;
3081 }
3082
3083 int
3084 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3085     MDB_val *key, MDB_val *data, unsigned int flags)
3086 {
3087         assert(key != NULL);
3088         assert(data != NULL);
3089
3090         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3091                 return EINVAL;
3092
3093         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3094                 return EINVAL;
3095         }
3096
3097         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3098                 return EINVAL;
3099         }
3100
3101         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3102                 return EINVAL;
3103
3104         return mdb_put0(txn, dbi, key, data, flags);
3105 }
3106
3107 int
3108 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3109 {
3110         if (!env || !arg)
3111                 return EINVAL;
3112
3113         *arg = env->me_flags;
3114         return MDB_SUCCESS;
3115 }
3116
3117 int
3118 mdb_env_get_path(MDB_env *env, const char **arg)
3119 {
3120         if (!env || !arg)
3121                 return EINVAL;
3122
3123         *arg = env->me_path;
3124         return MDB_SUCCESS;
3125 }
3126
3127 static int
3128 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3129 {
3130         arg->ms_psize = env->me_psize;
3131         arg->ms_depth = db->md_depth;
3132         arg->ms_branch_pages = db->md_branch_pages;
3133         arg->ms_leaf_pages = db->md_leaf_pages;
3134         arg->ms_overflow_pages = db->md_overflow_pages;
3135         arg->ms_entries = db->md_entries;
3136
3137         return MDB_SUCCESS;
3138 }
3139 int
3140 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3141 {
3142         if (env == NULL || arg == NULL)
3143                 return EINVAL;
3144
3145         return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3146 }
3147
3148 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3149 {
3150         MDB_val key, data;
3151         MDB_dbi i;
3152         int rc, dirty = 0;
3153         size_t len;
3154
3155         /* main DB? */
3156         if (!name) {
3157                 *dbi = MAIN_DBI;
3158                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3159                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3160                 return MDB_SUCCESS;
3161         }
3162
3163         /* Is the DB already open? */
3164         len = strlen(name);
3165         for (i=2; i<txn->mt_numdbs; i++) {
3166                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3167                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3168                         *dbi = i;
3169                         return MDB_SUCCESS;
3170                 }
3171         }
3172
3173         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3174                 return ENFILE;
3175
3176         /* Find the DB info */
3177         key.mv_size = len;
3178         key.mv_data = (void *)name;
3179         rc = mdb_get(txn, MAIN_DBI, &key, &data);
3180
3181         /* Create if requested */
3182         if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3183                 MDB_db dummy;
3184                 data.mv_size = sizeof(MDB_db);
3185                 data.mv_data = &dummy;
3186                 memset(&dummy, 0, sizeof(dummy));
3187                 dummy.md_root = P_INVALID;
3188                 dummy.md_flags = flags & 0xffff;
3189                 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3190                 dirty = 1;
3191         }
3192
3193         /* OK, got info, add to table */
3194         if (rc == MDB_SUCCESS) {
3195                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3196                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3197                 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3198                 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3199                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3200                 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3201                 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3202                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3203                 *dbi = txn->mt_numdbs;
3204                 txn->mt_numdbs++;
3205         }
3206
3207         return rc;
3208 }
3209
3210 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3211 {
3212         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3213                 return EINVAL;
3214
3215         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3216 }
3217
3218 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3219 {
3220         char *ptr;
3221         if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3222                 return;
3223         ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3224         txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3225         txn->mt_dbxs[dbi].md_name.mv_size = 0;
3226         free(ptr);
3227 }
3228
3229 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3230 {
3231         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3232                 return EINVAL;
3233
3234         txn->mt_dbxs[dbi].md_cmp = cmp;
3235         return MDB_SUCCESS;
3236 }
3237
3238 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3239 {
3240         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3241                 return EINVAL;
3242
3243         txn->mt_dbxs[dbi].md_dcmp = cmp;
3244         return MDB_SUCCESS;
3245 }
3246
3247 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3248 {
3249         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3250                 return EINVAL;
3251
3252         txn->mt_dbxs[dbi].md_rel = rel;
3253         return MDB_SUCCESS;
3254 }