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