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