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