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