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