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