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