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