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