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