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