]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
c37a21bc7038eb8f9d6e98470dfea22ea0090a68
[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 "midl.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  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
349 static int  mdb_env_read_meta(MDB_env *env, int *which);
350 static int  mdb_env_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_midl_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 mdb_env_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 = mdb_env_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 = mdb_env_sync(env)) != 0 ||
903             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS ||
904             (n = mdb_env_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 mdb_env_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 mdb_env_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 mdb_env_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 mdb_env_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 mdb_env_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 mdb_env_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 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1115 {
1116         env->me_maxdbs = dbs;
1117         return MDB_SUCCESS;
1118 }
1119
1120 int
1121 mdb_env_set_maxreaders(MDB_env *env, int readers)
1122 {
1123         env->me_maxreaders = readers;
1124         return MDB_SUCCESS;
1125 }
1126
1127 int
1128 mdb_env_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 mdb_env_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 = mdb_env_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 = mdb_env_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 = mdb_env_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 mdb_env_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 mdb_env_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 mdb_env_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 mdb_env_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 = mdb_env_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 = mdb_env_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, mdb_env_reader_dest);
1345                 if (excl)
1346                         mdb_env_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 mdb_env_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         pthread_key_delete(env->me_txkey);
1370
1371         if (env->me_map) {
1372                 munmap(env->me_map, env->me_mapsize);
1373         }
1374         close(env->me_fd);
1375         if (env->me_txns) {
1376                 pid_t pid = getpid();
1377                 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1378                 int i;
1379                 for (i=0; i<env->me_txns->mti_numreaders; i++)
1380                         if (env->me_txns->mti_readers[i].mr_pid == pid)
1381                                 env->me_txns->mti_readers[i].mr_pid = 0;
1382                 munmap(env->me_txns, size);
1383         }
1384         close(env->me_lfd);
1385         free(env);
1386 }
1387
1388 /* Search for key within a leaf page, using binary search.
1389  * Returns the smallest entry larger or equal to the key.
1390  * If exactp is non-null, stores whether the found entry was an exact match
1391  * in *exactp (1 or 0).
1392  * If kip is non-null, stores the index of the found entry in *kip.
1393  * If no entry larger or equal to the key is found, returns NULL.
1394  */
1395 static MDB_node *
1396 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1397     int *exactp, unsigned int *kip)
1398 {
1399         unsigned int     i = 0;
1400         int              low, high;
1401         int              rc = 0;
1402         MDB_node        *node;
1403         MDB_val  nodekey;
1404
1405         DPRINTF("searching %u keys in %s page %lu",
1406             NUMKEYS(mp),
1407             IS_LEAF(mp) ? "leaf" : "branch",
1408             mp->mp_pgno);
1409
1410         assert(NUMKEYS(mp) > 0);
1411
1412         memset(&nodekey, 0, sizeof(nodekey));
1413
1414         low = IS_LEAF(mp) ? 0 : 1;
1415         high = NUMKEYS(mp) - 1;
1416         while (low <= high) {
1417                 i = (low + high) >> 1;
1418                 node = NODEPTR(mp, i);
1419
1420                 nodekey.mv_size = node->mn_ksize;
1421                 nodekey.mv_data = NODEKEY(node);
1422
1423                 if (txn->mt_dbxs[dbi].md_cmp)
1424                         rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1425                 else
1426                         rc = _mdb_cmp(txn, dbi, key, &nodekey);
1427
1428                 if (IS_LEAF(mp))
1429                         DPRINTF("found leaf index %u [%.*s], rc = %i",
1430                             i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1431                 else
1432                         DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1433                             i, (int)node->mn_ksize, (char *)NODEKEY(node),
1434                             node->mn_pgno, rc);
1435
1436                 if (rc == 0)
1437                         break;
1438                 if (rc > 0)
1439                         low = i + 1;
1440                 else
1441                         high = i - 1;
1442         }
1443
1444         if (rc > 0) {   /* Found entry is less than the key. */
1445                 i++;    /* Skip to get the smallest entry larger than key. */
1446                 if (i >= NUMKEYS(mp))
1447                         /* There is no entry larger or equal to the key. */
1448                         return NULL;
1449         }
1450         if (exactp)
1451                 *exactp = (rc == 0);
1452         if (kip)        /* Store the key index if requested. */
1453                 *kip = i;
1454
1455         return NODEPTR(mp, i);
1456 }
1457
1458 static void
1459 cursor_pop_page(MDB_cursor *cursor)
1460 {
1461         MDB_ppage       *top;
1462
1463         top = CURSOR_TOP(cursor);
1464         CURSOR_POP(cursor);
1465
1466         DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1467
1468         free(top);
1469 }
1470
1471 static MDB_ppage *
1472 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1473 {
1474         MDB_ppage       *ppage;
1475
1476         DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1477
1478         if ((ppage = calloc(1, sizeof(MDB_ppage))) == NULL)
1479                 return NULL;
1480         ppage->mp_page = mp;
1481         CURSOR_PUSH(cursor, ppage);
1482         return ppage;
1483 }
1484
1485 static MDB_page *
1486 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1487 {
1488         MDB_page *p = NULL;
1489         int found = 0;
1490
1491         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1492                 MDB_dpage *dp;
1493                 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1494                         if (dp->p.mp_pgno == pgno) {
1495                                 p = &dp->p;
1496                                 found = 1;
1497                                 break;
1498                         }
1499                 }
1500         }
1501         if (!found) {
1502                 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1503                         return NULL;
1504                 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1505         }
1506         return p;
1507 }
1508
1509 static int
1510 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1511     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1512 {
1513         MDB_page        *mp = mpp->mp_page;
1514         int rc;
1515
1516         if (cursor && cursor_push_page(cursor, mp) == NULL)
1517                 return MDB_FAIL;
1518
1519         while (IS_BRANCH(mp)) {
1520                 unsigned int     i = 0;
1521                 MDB_node        *node;
1522
1523                 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1524                 assert(NUMKEYS(mp) > 1);
1525                 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1526
1527                 if (key == NULL)        /* Initialize cursor to first page. */
1528                         i = 0;
1529                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1530                                                         /* cursor to last page */
1531                         i = NUMKEYS(mp)-1;
1532                 } else {
1533                         int      exact;
1534                         node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1535                         if (node == NULL)
1536                                 i = NUMKEYS(mp) - 1;
1537                         else if (!exact) {
1538                                 assert(i > 0);
1539                                 i--;
1540                         }
1541                 }
1542
1543                 if (key)
1544                         DPRINTF("following index %u for key %.*s",
1545                             i, (int)key->mv_size, (char *)key->mv_data);
1546                 assert(i < NUMKEYS(mp));
1547                 node = NODEPTR(mp, i);
1548
1549                 if (cursor)
1550                         CURSOR_TOP(cursor)->mp_ki = i;
1551
1552                 mpp->mp_parent = mp;
1553                 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1554                         return MDB_FAIL;
1555                 mpp->mp_pi = i;
1556                 mpp->mp_page = mp;
1557
1558                 if (cursor && cursor_push_page(cursor, mp) == NULL)
1559                         return MDB_FAIL;
1560
1561                 if (modify) {
1562                         MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1563                         if ((rc = mdb_touch(txn, mpp)) != 0)
1564                                 return rc;
1565                         dh = ((MDB_dhead *)mpp->mp_page)-1;
1566                         dh->md_parent = mpp->mp_parent;
1567                         dh->md_pi = mpp->mp_pi;
1568                 }
1569
1570                 mp = mpp->mp_page;
1571         }
1572
1573         if (!IS_LEAF(mp)) {
1574                 DPRINTF("internal error, index points to a %02X page!?",
1575                     mp->mp_flags);
1576                 return MDB_FAIL;
1577         }
1578
1579         DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1580             key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1581
1582         return MDB_SUCCESS;
1583 }
1584
1585 /* Search for the page a given key should be in.
1586  * Stores a pointer to the found page in *mpp.
1587  * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1588  * If cursor is non-null, pushes parent pages on the cursor stack.
1589  * If modify is true, visited pages are updated with new page numbers.
1590  */
1591 static int
1592 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1593     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1594 {
1595         int              rc;
1596         pgno_t           root;
1597
1598         /* Choose which root page to start with. If a transaction is given
1599          * use the root page from the transaction, otherwise read the last
1600          * committed root page.
1601          */
1602         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1603                 DPRINTF("transaction has failed, must abort");
1604                 return EINVAL;
1605         } else
1606                 root = txn->mt_dbs[dbi].md_root;
1607
1608         if (root == P_INVALID) {                /* Tree is empty. */
1609                 DPRINTF("tree is empty");
1610                 return MDB_NOTFOUND;
1611         }
1612
1613         if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1614                 return MDB_FAIL;
1615
1616         DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1617
1618         if (modify) {
1619                 /* For sub-databases, update main root first */
1620                 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1621                         MDB_pageparent mp2;
1622                         rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1623                                 NULL, 1, &mp2);
1624                         if (rc)
1625                                 return rc;
1626                         txn->mt_dbxs[dbi].md_dirty = 1;
1627                 }
1628                 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1629                         mpp->mp_parent = NULL;
1630                         mpp->mp_pi = 0;
1631                         if ((rc = mdb_touch(txn, mpp)))
1632                                 return rc;
1633                         txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1634                 }
1635         }
1636
1637         return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1638 }
1639
1640 static int
1641 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1642 {
1643         MDB_page        *omp;           /* overflow mpage */
1644         pgno_t           pgno;
1645
1646         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1647                 data->mv_size = leaf->mn_dsize;
1648                 data->mv_data = NODEDATA(leaf);
1649                 return MDB_SUCCESS;
1650         }
1651
1652         /* Read overflow data.
1653          */
1654         data->mv_size = leaf->mn_dsize;
1655         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1656         if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1657                 DPRINTF("read overflow page %lu failed", pgno);
1658                 return MDB_FAIL;
1659         }
1660         data->mv_data = omp;
1661
1662         return MDB_SUCCESS;
1663 }
1664
1665 int
1666 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1667     MDB_val *key, MDB_val *data)
1668 {
1669         int              rc, exact;
1670         MDB_node        *leaf;
1671         MDB_pageparent mpp;
1672
1673         assert(key);
1674         assert(data);
1675         DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1676
1677         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1678                 return EINVAL;
1679
1680         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1681                 return EINVAL;
1682         }
1683
1684         if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1685                 return rc;
1686
1687         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1688         if (leaf && exact) {
1689                 /* Return first duplicate data item */
1690                 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1691                         MDB_xcursor mx;
1692
1693                         mdb_xcursor_init0(txn, dbi, &mx);
1694                         mdb_xcursor_init1(txn, dbi, &mx, leaf);
1695                         rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1696                         if (rc != MDB_SUCCESS)
1697                                 return rc;
1698                         leaf = NODEPTR(mpp.mp_page, 0);
1699                 }
1700                 rc = mdb_read_data(txn, leaf, data);
1701         } else {
1702                 rc = MDB_NOTFOUND;
1703         }
1704
1705         return rc;
1706 }
1707
1708 static int
1709 mdb_sibling(MDB_cursor *cursor, int move_right)
1710 {
1711         int              rc;
1712         MDB_node        *indx;
1713         MDB_ppage       *parent, *top;
1714         MDB_page        *mp;
1715
1716         top = CURSOR_TOP(cursor);
1717         if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1718                 return MDB_NOTFOUND;            /* root has no siblings */
1719         }
1720
1721         DPRINTF("parent page is page %lu, index %u",
1722             parent->mp_page->mp_pgno, parent->mp_ki);
1723
1724         cursor_pop_page(cursor);
1725         if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1726                        : (parent->mp_ki == 0)) {
1727                 DPRINTF("no more keys left, moving to %s sibling",
1728                     move_right ? "right" : "left");
1729                 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1730                         return rc;
1731                 parent = CURSOR_TOP(cursor);
1732         } else {
1733                 if (move_right)
1734                         parent->mp_ki++;
1735                 else
1736                         parent->mp_ki--;
1737                 DPRINTF("just moving to %s index key %u",
1738                     move_right ? "right" : "left", parent->mp_ki);
1739         }
1740         assert(IS_BRANCH(parent->mp_page));
1741
1742         indx = NODEPTR(parent->mp_page, parent->mp_ki);
1743         if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1744                 return MDB_FAIL;
1745 #if 0
1746         mp->parent = parent->mp_page;
1747         mp->parent_index = parent->mp_ki;
1748 #endif
1749
1750         cursor_push_page(cursor, mp);
1751
1752         return MDB_SUCCESS;
1753 }
1754
1755 static int
1756 mdb_set_key(MDB_node *node, MDB_val *key)
1757 {
1758         if (key == NULL)
1759                 return 0;
1760
1761         key->mv_size = node->mn_ksize;
1762         key->mv_data = NODEKEY(node);
1763
1764         return 0;
1765 }
1766
1767 static int
1768 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1769 {
1770         MDB_ppage       *top;
1771         MDB_page        *mp;
1772         MDB_node        *leaf;
1773         int rc;
1774
1775         if (cursor->mc_eof) {
1776                 return MDB_NOTFOUND;
1777         }
1778
1779         assert(cursor->mc_initialized);
1780
1781         if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1782                 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
1783                         rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
1784                         if (op != MDB_NEXT || rc == MDB_SUCCESS)
1785                                 return rc;
1786                 }
1787         }
1788
1789         top = CURSOR_TOP(cursor);
1790         mp = top->mp_page;
1791
1792         DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1793
1794         if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1795                 DPRINTF("=====> move to next sibling page");
1796                 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1797                         cursor->mc_eof = 1;
1798                         return MDB_NOTFOUND;
1799                 }
1800                 top = CURSOR_TOP(cursor);
1801                 mp = top->mp_page;
1802                 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1803         } else
1804                 top->mp_ki++;
1805
1806         DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1807             mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1808
1809         assert(IS_LEAF(mp));
1810         leaf = NODEPTR(mp, top->mp_ki);
1811
1812         if (data) {
1813                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1814                         return rc;
1815
1816                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1817                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1818                         rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1819                         if (rc != MDB_SUCCESS)
1820                                 return rc;
1821                 }
1822         }
1823
1824         return mdb_set_key(leaf, key);
1825 }
1826
1827 static int
1828 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1829 {
1830         MDB_ppage       *top;
1831         MDB_page        *mp;
1832         MDB_node        *leaf;
1833         int rc;
1834
1835         assert(cursor->mc_initialized);
1836
1837         if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1838                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
1839                         rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
1840                         if (op != MDB_PREV || rc == MDB_SUCCESS)
1841                                 return rc;
1842                 }
1843         }
1844
1845         top = CURSOR_TOP(cursor);
1846         mp = top->mp_page;
1847
1848         DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1849
1850         if (top->mp_ki == 0)  {
1851                 DPRINTF("=====> move to prev sibling page");
1852                 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1853                         return MDB_NOTFOUND;
1854                 }
1855                 top = CURSOR_TOP(cursor);
1856                 mp = top->mp_page;
1857                 top->mp_ki = NUMKEYS(mp) - 1;
1858                 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1859         } else
1860                 top->mp_ki--;
1861
1862         cursor->mc_eof = 0;
1863
1864         DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1865             mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1866
1867         assert(IS_LEAF(mp));
1868         leaf = NODEPTR(mp, top->mp_ki);
1869
1870         if (data) {
1871                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1872                         return rc;
1873
1874                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1875                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1876                         rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
1877                         if (rc != MDB_SUCCESS)
1878                                 return rc;
1879                 }
1880         }
1881
1882         return mdb_set_key(leaf, key);
1883 }
1884
1885 static int
1886 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1887     MDB_cursor_op op, int *exactp)
1888 {
1889         int              rc;
1890         MDB_node        *leaf;
1891         MDB_ppage       *top;
1892         MDB_pageparent mpp;
1893
1894         assert(cursor);
1895         assert(key);
1896         assert(key->mv_size > 0);
1897
1898         while (CURSOR_TOP(cursor) != NULL)
1899                 cursor_pop_page(cursor);
1900
1901         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1902         if (rc != MDB_SUCCESS)
1903                 return rc;
1904         assert(IS_LEAF(mpp.mp_page));
1905
1906         top = CURSOR_TOP(cursor);
1907         leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1908         if (exactp != NULL && !*exactp) {
1909                 /* MDB_SET specified and not an exact match. */
1910                 return MDB_NOTFOUND;
1911         }
1912
1913         if (leaf == NULL) {
1914                 DPRINTF("===> inexact leaf not found, goto sibling");
1915                 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1916                         return rc;              /* no entries matched */
1917                 top = CURSOR_TOP(cursor);
1918                 top->mp_ki = 0;
1919                 mpp.mp_page = top->mp_page;
1920                 assert(IS_LEAF(mpp.mp_page));
1921                 leaf = NODEPTR(mpp.mp_page, 0);
1922         }
1923
1924         cursor->mc_initialized = 1;
1925         cursor->mc_eof = 0;
1926
1927         if (data) {
1928                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1929                         return rc;
1930
1931                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1932                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1933                         if (op == MDB_SET || op == MDB_SET_RANGE) {
1934                                 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1935                         } else {
1936                                 int ex2, *ex2p;
1937                                 MDB_cursor_op op2;
1938                                 if (op == MDB_GET_BOTH) {
1939                                         ex2p = &ex2;
1940                                         op2 = MDB_SET;
1941                                 } else {
1942                                         ex2p = NULL;
1943                                         op2 = MDB_SET_RANGE;
1944                                 }
1945                                 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, op2, ex2p);
1946                                 if (rc != MDB_SUCCESS)
1947                                         return rc;
1948                         }
1949                 }
1950         }
1951
1952         rc = mdb_set_key(leaf, key);
1953         if (rc == MDB_SUCCESS) {
1954                 DPRINTF("==> cursor placed on key %.*s",
1955                         (int)key->mv_size, (char *)key->mv_data);
1956                 ;
1957         }
1958
1959         return rc;
1960 }
1961
1962 static int
1963 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1964 {
1965         int              rc;
1966         MDB_pageparent  mpp;
1967         MDB_node        *leaf;
1968
1969         while (CURSOR_TOP(cursor) != NULL)
1970                 cursor_pop_page(cursor);
1971
1972         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1973         if (rc != MDB_SUCCESS)
1974                 return rc;
1975         assert(IS_LEAF(mpp.mp_page));
1976
1977         leaf = NODEPTR(mpp.mp_page, 0);
1978         cursor->mc_initialized = 1;
1979         cursor->mc_eof = 0;
1980
1981         if (data) {
1982                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1983                         return rc;
1984
1985                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1986                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1987                         rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1988                         if (rc)
1989                                 return rc;
1990                 }
1991         }
1992         return mdb_set_key(leaf, key);
1993 }
1994
1995 static int
1996 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1997 {
1998         int              rc;
1999         MDB_ppage       *top;
2000         MDB_pageparent  mpp;
2001         MDB_node        *leaf;
2002         MDB_val lkey;
2003
2004         while (CURSOR_TOP(cursor) != NULL)
2005                 cursor_pop_page(cursor);
2006
2007         lkey.mv_size = MAXKEYSIZE+1;
2008         lkey.mv_data = NULL;
2009
2010         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2011         if (rc != MDB_SUCCESS)
2012                 return rc;
2013         assert(IS_LEAF(mpp.mp_page));
2014
2015         leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2016         cursor->mc_initialized = 1;
2017         cursor->mc_eof = 0;
2018
2019         top = CURSOR_TOP(cursor);
2020         top->mp_ki = NUMKEYS(top->mp_page) - 1;
2021
2022         if (data) {
2023                 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2024                         return rc;
2025
2026                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2027                         mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2028                         rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2029                         if (rc)
2030                                 return rc;
2031                 }
2032         }
2033
2034         return mdb_set_key(leaf, key);
2035 }
2036
2037 int
2038 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2039     MDB_cursor_op op)
2040 {
2041         int              rc;
2042         int              exact = 0;
2043
2044         assert(cursor);
2045
2046         switch (op) {
2047         case MDB_GET_BOTH:
2048         case MDB_GET_BOTH_RANGE:
2049                 if (data == NULL) {
2050                         rc = EINVAL;
2051                         break;
2052                 }
2053                 /* FALLTHRU */
2054         case MDB_SET:
2055         case MDB_SET_RANGE:
2056                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2057                         rc = EINVAL;
2058                 } else if (op != MDB_SET_RANGE)
2059                         rc = mdb_cursor_set(cursor, key, data, op, NULL);
2060                 else
2061                         rc = mdb_cursor_set(cursor, key, data, op, &exact);
2062                 break;
2063         case MDB_NEXT:
2064         case MDB_NEXT_DUP:
2065         case MDB_NEXT_NODUP:
2066                 if (!cursor->mc_initialized)
2067                         rc = mdb_cursor_first(cursor, key, data);
2068                 else
2069                         rc = mdb_cursor_next(cursor, key, data, op);
2070                 break;
2071         case MDB_PREV:
2072         case MDB_PREV_DUP:
2073         case MDB_PREV_NODUP:
2074                 if (!cursor->mc_initialized || cursor->mc_eof)
2075                         rc = mdb_cursor_last(cursor, key, data);
2076                 else
2077                         rc = mdb_cursor_prev(cursor, key, data, op);
2078                 break;
2079         case MDB_FIRST:
2080                 rc = mdb_cursor_first(cursor, key, data);
2081                 break;
2082         case MDB_LAST:
2083                 rc = mdb_cursor_last(cursor, key, data);
2084                 break;
2085         default:
2086                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2087                 rc = EINVAL;
2088                 break;
2089         }
2090
2091         return rc;
2092 }
2093
2094 /* Allocate a page and initialize it
2095  */
2096 static MDB_dpage *
2097 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2098 {
2099         MDB_dpage       *dp;
2100
2101         if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2102                 return NULL;
2103         DPRINTF("allocated new mpage %lu, page size %u",
2104             dp->p.mp_pgno, txn->mt_env->me_psize);
2105         dp->p.mp_flags = flags | P_DIRTY;
2106         dp->p.mp_lower = PAGEHDRSZ;
2107         dp->p.mp_upper = txn->mt_env->me_psize;
2108
2109         if (IS_BRANCH(&dp->p))
2110                 txn->mt_dbs[dbi].md_branch_pages++;
2111         else if (IS_LEAF(&dp->p))
2112                 txn->mt_dbs[dbi].md_leaf_pages++;
2113         else if (IS_OVERFLOW(&dp->p)) {
2114                 txn->mt_dbs[dbi].md_overflow_pages += num;
2115                 dp->p.mp_pages = num;
2116         }
2117
2118         return dp;
2119 }
2120
2121 static size_t
2122 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2123 {
2124         size_t           sz;
2125
2126         sz = LEAFSIZE(key, data);
2127         if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2128                 /* put on overflow page */
2129                 sz -= data->mv_size - sizeof(pgno_t);
2130         }
2131
2132         return sz + sizeof(indx_t);
2133 }
2134
2135 static size_t
2136 mdb_branch_size(MDB_env *env, MDB_val *key)
2137 {
2138         size_t           sz;
2139
2140         sz = INDXSIZE(key);
2141         if (sz >= env->me_psize / MDB_MINKEYS) {
2142                 /* put on overflow page */
2143                 /* not implemented */
2144                 /* sz -= key->size - sizeof(pgno_t); */
2145         }
2146
2147         return sz + sizeof(indx_t);
2148 }
2149
2150 static int
2151 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2152     MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2153 {
2154         unsigned int     i;
2155         size_t           node_size = NODESIZE;
2156         indx_t           ofs;
2157         MDB_node        *node;
2158         MDB_dpage       *ofp = NULL;            /* overflow page */
2159
2160         assert(mp->mp_upper >= mp->mp_lower);
2161
2162         DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2163             key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2164             IS_LEAF(mp) ? "leaf" : "branch",
2165             mp->mp_pgno, indx, key ? key->mv_size : 0);
2166
2167         if (key != NULL)
2168                 node_size += key->mv_size;
2169
2170         if (IS_LEAF(mp)) {
2171                 assert(data);
2172                 if (F_ISSET(flags, F_BIGDATA)) {
2173                         /* Data already on overflow page. */
2174                         node_size += sizeof(pgno_t);
2175                 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2176                         int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2177                         /* Put data on overflow page. */
2178                         DPRINTF("data size is %zu, put on overflow page",
2179                             data->mv_size);
2180                         node_size += sizeof(pgno_t);
2181                         if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2182                                 return MDB_FAIL;
2183                         DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2184                         flags |= F_BIGDATA;
2185                 } else {
2186                         node_size += data->mv_size;
2187                 }
2188         }
2189
2190         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2191                 DPRINTF("not enough room in page %lu, got %u ptrs",
2192                     mp->mp_pgno, NUMKEYS(mp));
2193                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2194                     mp->mp_upper - mp->mp_lower);
2195                 DPRINTF("node size = %zu", node_size);
2196                 return ENOSPC;
2197         }
2198
2199         /* Move higher pointers up one slot. */
2200         for (i = NUMKEYS(mp); i > indx; i--)
2201                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2202
2203         /* Adjust free space offsets. */
2204         ofs = mp->mp_upper - node_size;
2205         assert(ofs >= mp->mp_lower + sizeof(indx_t));
2206         mp->mp_ptrs[indx] = ofs;
2207         mp->mp_upper = ofs;
2208         mp->mp_lower += sizeof(indx_t);
2209
2210         /* Write the node data. */
2211         node = NODEPTR(mp, indx);
2212         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2213         node->mn_flags = flags;
2214         if (IS_LEAF(mp))
2215                 node->mn_dsize = data->mv_size;
2216         else
2217                 node->mn_pgno = pgno;
2218
2219         if (key)
2220                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2221
2222         if (IS_LEAF(mp)) {
2223                 assert(key);
2224                 if (ofp == NULL) {
2225                         if (F_ISSET(flags, F_BIGDATA))
2226                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
2227                                     sizeof(pgno_t));
2228                         else
2229                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
2230                                     data->mv_size);
2231                 } else {
2232                         memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2233                             sizeof(pgno_t));
2234                         memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2235                 }
2236         }
2237
2238         return MDB_SUCCESS;
2239 }
2240
2241 static void
2242 mdb_del_node(MDB_page *mp, indx_t indx)
2243 {
2244         unsigned int     sz;
2245         indx_t           i, j, numkeys, ptr;
2246         MDB_node        *node;
2247         char            *base;
2248
2249         DPRINTF("delete node %u on %s page %lu", indx,
2250             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2251         assert(indx < NUMKEYS(mp));
2252
2253         node = NODEPTR(mp, indx);
2254         sz = NODESIZE + node->mn_ksize;
2255         if (IS_LEAF(mp)) {
2256                 if (F_ISSET(node->mn_flags, F_BIGDATA))
2257                         sz += sizeof(pgno_t);
2258                 else
2259                         sz += NODEDSZ(node);
2260         }
2261
2262         ptr = mp->mp_ptrs[indx];
2263         numkeys = NUMKEYS(mp);
2264         for (i = j = 0; i < numkeys; i++) {
2265                 if (i != indx) {
2266                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
2267                         if (mp->mp_ptrs[i] < ptr)
2268                                 mp->mp_ptrs[j] += sz;
2269                         j++;
2270                 }
2271         }
2272
2273         base = (char *)mp + mp->mp_upper;
2274         memmove(base + sz, base, ptr - mp->mp_upper);
2275
2276         mp->mp_lower -= sizeof(indx_t);
2277         mp->mp_upper += sz;
2278 }
2279
2280 static void
2281 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2282 {
2283         MDB_dbi dbn;
2284
2285         mx->mx_txn = *txn;
2286         mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2287         mx->mx_txn.mt_dbs = mx->mx_dbs;
2288         mx->mx_dbxs[0] = txn->mt_dbxs[0];
2289         mx->mx_dbxs[1] = txn->mt_dbxs[1];
2290         if (dbi > 1) {
2291                 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2292                 dbn = 2;
2293         } else {
2294                 dbn = 1;
2295         }
2296         mx->mx_dbxs[dbn+1].md_parent = dbn;
2297         mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2298         mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2299         mx->mx_dbxs[dbn+1].md_dirty = 0;
2300         mx->mx_txn.mt_numdbs = dbn+2;
2301
2302         SLIST_INIT(&mx->mx_cursor.mc_stack);
2303         mx->mx_cursor.mc_txn = &mx->mx_txn;
2304         mx->mx_cursor.mc_dbi = dbn+1;
2305 }
2306
2307 static void
2308 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node)
2309 {
2310         MDB_db *db = NODEDATA(node);
2311         MDB_dbi dbn;
2312         mx->mx_dbs[0] = txn->mt_dbs[0];
2313         mx->mx_dbs[1] = txn->mt_dbs[1];
2314         if (dbi > 1) {
2315                 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2316                 dbn = 3;
2317         } else {
2318                 dbn = 2;
2319         }
2320         mx->mx_dbs[dbn] = *db;
2321         mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2322         mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2323         mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2324         mx->mx_txn.mt_oldest = txn->mt_oldest;
2325         mx->mx_txn.mt_u = txn->mt_u;
2326 }
2327
2328 static void
2329 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2330 {
2331         txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2332         txn->mt_oldest = mx->mx_txn.mt_oldest;
2333         txn->mt_u = mx->mx_txn.mt_u;
2334         txn->mt_dbs[0] = mx->mx_dbs[0];
2335         txn->mt_dbs[1] = mx->mx_dbs[1];
2336         txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2337         txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2338         if (dbi > 1) {
2339                 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2340                 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2341         }
2342 }
2343
2344 int
2345 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2346 {
2347         MDB_cursor      *cursor;
2348         size_t size = sizeof(MDB_cursor);
2349
2350         if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2351                 return EINVAL;
2352
2353         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2354                 size += sizeof(MDB_xcursor);
2355
2356         if ((cursor = calloc(1, size)) != NULL) {
2357                 SLIST_INIT(&cursor->mc_stack);
2358                 cursor->mc_dbi = dbi;
2359                 cursor->mc_txn = txn;
2360                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2361                         MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2362                         cursor->mc_xcursor = mx;
2363                         mdb_xcursor_init0(txn, dbi, mx);
2364                 }
2365         } else {
2366                 return ENOMEM;
2367         }
2368
2369         *ret = cursor;
2370
2371         return MDB_SUCCESS;
2372 }
2373
2374 /* Return the count of duplicate data items for the current key */
2375 int
2376 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2377 {
2378         if (mc == NULL || countp == NULL)
2379                 return EINVAL;
2380
2381         if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2382                 return EINVAL;
2383
2384         if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2385                 return EINVAL;
2386
2387         *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2388         return MDB_SUCCESS;
2389 }
2390
2391 void
2392 mdb_cursor_close(MDB_cursor *cursor)
2393 {
2394         if (cursor != NULL) {
2395                 while(!CURSOR_EMPTY(cursor))
2396                         cursor_pop_page(cursor);
2397                 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2398                         mdb_xcursor_fini(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor);
2399                         while(!CURSOR_EMPTY(&cursor->mc_xcursor->mx_cursor))
2400                                 cursor_pop_page(&cursor->mc_xcursor->mx_cursor);
2401                 }
2402
2403                 free(cursor);
2404         }
2405 }
2406
2407 static int
2408 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2409 {
2410         indx_t                   ptr, i, numkeys;
2411         int                      delta;
2412         size_t                   len;
2413         MDB_node                *node;
2414         char                    *base;
2415
2416         node = NODEPTR(mp, indx);
2417         ptr = mp->mp_ptrs[indx];
2418         DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2419             indx, ptr,
2420             (int)node->mn_ksize, (char *)NODEKEY(node),
2421             (int)key->mv_size, (char *)key->mv_data,
2422             mp->mp_pgno);
2423
2424         delta = key->mv_size - node->mn_ksize;
2425         if (delta) {
2426                 if (delta > 0 && SIZELEFT(mp) < delta) {
2427                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
2428                         return ENOSPC;
2429                 }
2430
2431                 numkeys = NUMKEYS(mp);
2432                 for (i = 0; i < numkeys; i++) {
2433                         if (mp->mp_ptrs[i] <= ptr)
2434                                 mp->mp_ptrs[i] -= delta;
2435                 }
2436
2437                 base = (char *)mp + mp->mp_upper;
2438                 len = ptr - mp->mp_upper + NODESIZE;
2439                 memmove(base - delta, base, len);
2440                 mp->mp_upper -= delta;
2441
2442                 node = NODEPTR(mp, indx);
2443                 node->mn_ksize = key->mv_size;
2444         }
2445
2446         memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2447
2448         return MDB_SUCCESS;
2449 }
2450
2451 /* Move a node from src to dst.
2452  */
2453 static int
2454 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2455     MDB_pageparent *dst, indx_t dstindx)
2456 {
2457         int                      rc;
2458         MDB_node                *srcnode;
2459         MDB_val          key, data;
2460
2461         srcnode = NODEPTR(src->mp_page, srcindx);
2462         DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2463             IS_LEAF(src->mp_page) ? "leaf" : "branch",
2464             srcindx,
2465             (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2466             src->mp_page->mp_pgno,
2467             dstindx, dst->mp_page->mp_pgno);
2468
2469         /* Mark src and dst as dirty. */
2470         if ((rc = mdb_touch(txn, src)) ||
2471             (rc = mdb_touch(txn, dst)))
2472                 return rc;;
2473
2474         /* Add the node to the destination page.
2475          */
2476         key.mv_size = srcnode->mn_ksize;
2477         key.mv_data = NODEKEY(srcnode);
2478         data.mv_size = NODEDSZ(srcnode);
2479         data.mv_data = NODEDATA(srcnode);
2480         rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2481             srcnode->mn_flags);
2482         if (rc != MDB_SUCCESS)
2483                 return rc;
2484
2485         /* Delete the node from the source page.
2486          */
2487         mdb_del_node(src->mp_page, srcindx);
2488
2489         /* Update the parent separators.
2490          */
2491         if (srcindx == 0 && src->mp_pi != 0) {
2492                 DPRINTF("update separator for source page %lu to [%.*s]",
2493                     src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2494                 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2495                     &key)) != MDB_SUCCESS)
2496                         return rc;
2497         }
2498
2499         if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2500                 MDB_val  nullkey;
2501                 nullkey.mv_size = 0;
2502                 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2503         }
2504
2505         if (dstindx == 0 && dst->mp_pi != 0) {
2506                 DPRINTF("update separator for destination page %lu to [%.*s]",
2507                     dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2508                 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2509                     &key)) != MDB_SUCCESS)
2510                         return rc;
2511         }
2512
2513         if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2514                 MDB_val  nullkey;
2515                 nullkey.mv_size = 0;
2516                 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2517         }
2518
2519         return MDB_SUCCESS;
2520 }
2521
2522 static int
2523 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2524 {
2525         int                      rc;
2526         indx_t                   i;
2527         MDB_node                *srcnode;
2528         MDB_val          key, data;
2529         MDB_pageparent  mpp;
2530         MDB_dhead *dh;
2531
2532         DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2533
2534         assert(txn != NULL);
2535         assert(src->mp_parent); /* can't merge root page */
2536         assert(dst->mp_parent);
2537
2538         /* Mark src and dst as dirty. */
2539         if ((rc = mdb_touch(txn, src)) ||
2540             (rc = mdb_touch(txn, dst)))
2541                 return rc;
2542
2543         /* Move all nodes from src to dst.
2544          */
2545         for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2546                 srcnode = NODEPTR(src->mp_page, i);
2547
2548                 key.mv_size = srcnode->mn_ksize;
2549                 key.mv_data = NODEKEY(srcnode);
2550                 data.mv_size = NODEDSZ(srcnode);
2551                 data.mv_data = NODEDATA(srcnode);
2552                 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2553                     &data, NODEPGNO(srcnode), srcnode->mn_flags);
2554                 if (rc != MDB_SUCCESS)
2555                         return rc;
2556         }
2557
2558         DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2559             dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2560
2561         /* Unlink the src page from parent.
2562          */
2563         mdb_del_node(src->mp_parent, src->mp_pi);
2564         if (src->mp_pi == 0) {
2565                 key.mv_size = 0;
2566                 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2567                         return rc;
2568         }
2569
2570         if (IS_LEAF(src->mp_page))
2571                 txn->mt_dbs[dbi].md_leaf_pages--;
2572         else
2573                 txn->mt_dbs[dbi].md_branch_pages--;
2574
2575         mpp.mp_page = src->mp_parent;
2576         dh = (MDB_dhead *)src->mp_parent;
2577         dh--;
2578         mpp.mp_parent = dh->md_parent;
2579         mpp.mp_pi = dh->md_pi;
2580
2581         return mdb_rebalance(txn, dbi, &mpp);
2582 }
2583
2584 #define FILL_THRESHOLD   250
2585
2586 static int
2587 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2588 {
2589         MDB_node        *node;
2590         MDB_page        *root;
2591         MDB_pageparent npp;
2592         indx_t           si = 0, di = 0;
2593
2594         assert(txn != NULL);
2595         assert(mpp != NULL);
2596
2597         DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2598             IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2599             mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2600
2601         if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2602                 DPRINTF("no need to rebalance page %lu, above fill threshold",
2603                     mpp->mp_page->mp_pgno);
2604                 return MDB_SUCCESS;
2605         }
2606
2607         if (mpp->mp_parent == NULL) {
2608                 if (NUMKEYS(mpp->mp_page) == 0) {
2609                         DPRINTF("tree is completely empty");
2610                         txn->mt_dbs[dbi].md_root = P_INVALID;
2611                         txn->mt_dbs[dbi].md_depth--;
2612                         txn->mt_dbs[dbi].md_leaf_pages--;
2613                 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2614                         DPRINTF("collapsing root page!");
2615                         txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2616                         if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2617                                 return MDB_FAIL;
2618                         txn->mt_dbs[dbi].md_depth--;
2619                         txn->mt_dbs[dbi].md_branch_pages--;
2620                 } else
2621                         DPRINTF("root page doesn't need rebalancing");
2622                 return MDB_SUCCESS;
2623         }
2624
2625         /* The parent (branch page) must have at least 2 pointers,
2626          * otherwise the tree is invalid.
2627          */
2628         assert(NUMKEYS(mpp->mp_parent) > 1);
2629
2630         /* Leaf page fill factor is below the threshold.
2631          * Try to move keys from left or right neighbor, or
2632          * merge with a neighbor page.
2633          */
2634
2635         /* Find neighbors.
2636          */
2637         if (mpp->mp_pi == 0) {
2638                 /* We're the leftmost leaf in our parent.
2639                  */
2640                 DPRINTF("reading right neighbor");
2641                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2642                 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2643                         return MDB_FAIL;
2644                 npp.mp_pi = mpp->mp_pi + 1;
2645                 si = 0;
2646                 di = NUMKEYS(mpp->mp_page);
2647         } else {
2648                 /* There is at least one neighbor to the left.
2649                  */
2650                 DPRINTF("reading left neighbor");
2651                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2652                 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2653                         return MDB_FAIL;
2654                 npp.mp_pi = mpp->mp_pi - 1;
2655                 si = NUMKEYS(npp.mp_page) - 1;
2656                 di = 0;
2657         }
2658         npp.mp_parent = mpp->mp_parent;
2659
2660         DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2661             npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2662
2663         /* If the neighbor page is above threshold and has at least two
2664          * keys, move one key from it.
2665          *
2666          * Otherwise we should try to merge them.
2667          */
2668         if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2669                 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2670         else { /* FIXME: if (has_enough_room()) */
2671                 if (mpp->mp_pi == 0)
2672                         return mdb_merge(txn, dbi, &npp, mpp);
2673                 else
2674                         return mdb_merge(txn, dbi, mpp, &npp);
2675         }
2676 }
2677
2678 static int
2679 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2680 {
2681         int rc;
2682
2683         /* add overflow pages to free list */
2684         if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2685                 int i, ovpages;
2686                 pgno_t pg;
2687
2688                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2689                 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2690                 for (i=0; i<ovpages; i++) {
2691                         DPRINTF("freed ov page %lu", pg);
2692                         mdb_midl_insert(txn->mt_free_pgs, pg);
2693                         pg++;
2694                 }
2695         }
2696         mdb_del_node(mpp->mp_page, ki);
2697         txn->mt_dbs[dbi].md_entries--;
2698         rc = mdb_rebalance(txn, dbi, mpp);
2699         if (rc != MDB_SUCCESS)
2700                 txn->mt_flags |= MDB_TXN_ERROR;
2701
2702         return rc;
2703 }
2704
2705 int
2706 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2707     MDB_val *key, MDB_val *data,
2708         unsigned int flags)
2709 {
2710         int              rc, exact;
2711         unsigned int     ki;
2712         MDB_node        *leaf;
2713         MDB_pageparent  mpp;
2714
2715         DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2716
2717         assert(key != NULL);
2718
2719         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2720                 return EINVAL;
2721
2722         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2723                 return EINVAL;
2724         }
2725
2726         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2727                 return EINVAL;
2728         }
2729
2730         mpp.mp_parent = NULL;
2731         mpp.mp_pi = 0;
2732         if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2733                 return rc;
2734
2735         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2736         if (leaf == NULL || !exact) {
2737                 return MDB_NOTFOUND;
2738         }
2739
2740         if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2741                 MDB_xcursor mx;
2742                 MDB_pageparent mp2;
2743
2744                 mdb_xcursor_init0(txn, dbi, &mx);
2745                 mdb_xcursor_init1(txn, dbi, &mx, leaf);
2746                 if (flags == MDB_DEL_DUP) {
2747                         rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
2748                         mdb_xcursor_fini(txn, dbi, &mx);
2749                         if (rc != MDB_SUCCESS)
2750                                 return rc;
2751                         /* If sub-DB still has entries, we're done */
2752                         if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
2753                                 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
2754                                         sizeof(MDB_db));
2755                                 return rc;
2756                         }
2757                         /* otherwise fall thru and delete the sub-DB */
2758                 } else {
2759                         /* add all the child DB's pages to the free list */
2760                         rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2761                                 NULL, &mx.mx_cursor, 0, &mp2);
2762                         if (rc == MDB_SUCCESS) {
2763                                 MDB_ppage *top, *parent;
2764                                 MDB_node *ni;
2765                                 unsigned int i;
2766
2767                                 cursor_pop_page(&mx.mx_cursor);
2768                                 top = CURSOR_TOP(&mx.mx_cursor);
2769                                 if (top != NULL) {
2770                                         parent = SLIST_NEXT(top, mp_entry);
2771                                         while (parent != NULL) {
2772                                                 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2773                                                         ni = NODEPTR(top->mp_page, i);
2774                                                         mdb_midl_insert(txn->mt_free_pgs, ni->mn_pgno);
2775                                                 }
2776                                                 if (parent) {
2777                                                         parent->mp_ki++;
2778                                                         if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2779                                                                 cursor_pop_page(&mx.mx_cursor);
2780                                                                 top = CURSOR_TOP(&mx.mx_cursor);
2781                                                                 parent = SLIST_NEXT(top, mp_entry);
2782                                                         } else {
2783                                                                 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2784                                                                 top->mp_page = mdb_get_page(&mx.mx_txn, ni->mn_pgno);
2785                                                         }
2786                                                 }
2787                                         }
2788                                 }
2789                                 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2790                         }
2791                 }
2792         }
2793
2794         if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2795                 return rc;
2796
2797         return mdb_del0(txn, dbi, ki, &mpp, leaf);
2798 }
2799
2800 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2801  * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2802  * *newindxp with the actual values after split, ie if *mpp and *newindxp
2803  * refer to a node in the new right sibling page.
2804  */
2805 static int
2806 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2807     MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2808 {
2809         uint8_t          flags;
2810         int              rc = MDB_SUCCESS, ins_new = 0;
2811         indx_t           newindx;
2812         pgno_t           pgno = 0;
2813         unsigned int     i, j, split_indx;
2814         MDB_node        *node;
2815         MDB_val  sepkey, rkey, rdata;
2816         MDB_page        *copy;
2817         MDB_dpage       *mdp, *rdp, *pdp;
2818         MDB_dhead *dh;
2819
2820         assert(txn != NULL);
2821
2822         dh = ((MDB_dhead *)*mpp) - 1;
2823         mdp = (MDB_dpage *)dh;
2824         newindx = *newindxp;
2825
2826         DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2827             IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2828             (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2829
2830         if (mdp->h.md_parent == NULL) {
2831                 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2832                         return MDB_FAIL;
2833                 mdp->h.md_pi = 0;
2834                 mdp->h.md_parent = &pdp->p;
2835                 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2836                 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2837                 txn->mt_dbs[dbi].md_depth++;
2838
2839                 /* Add left (implicit) pointer. */
2840                 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2841                     mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2842                         return MDB_FAIL;
2843         } else {
2844                 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2845         }
2846
2847         /* Create a right sibling. */
2848         if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2849                 return MDB_FAIL;
2850         rdp->h.md_parent = mdp->h.md_parent;
2851         rdp->h.md_pi = mdp->h.md_pi + 1;
2852         DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2853
2854         /* Move half of the keys to the right sibling. */
2855         if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2856                 return MDB_FAIL;
2857         memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2858         memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2859         mdp->p.mp_lower = PAGEHDRSZ;
2860         mdp->p.mp_upper = txn->mt_env->me_psize;
2861
2862         split_indx = NUMKEYS(copy) / 2 + 1;
2863
2864         /* First find the separating key between the split pages.
2865          */
2866         memset(&sepkey, 0, sizeof(sepkey));
2867         if (newindx == split_indx) {
2868                 sepkey.mv_size = newkey->mv_size;
2869                 sepkey.mv_data = newkey->mv_data;
2870         } else {
2871                 node = NODEPTR(copy, split_indx);
2872                 sepkey.mv_size = node->mn_ksize;
2873                 sepkey.mv_data = NODEKEY(node);
2874         }
2875
2876         DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2877
2878         /* Copy separator key to the parent.
2879          */
2880         if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2881                 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2882                     &sepkey, NULL, rdp->p.mp_pgno);
2883
2884                 /* Right page might now have changed parent.
2885                  * Check if left page also changed parent.
2886                  */
2887                 if (rdp->h.md_parent != mdp->h.md_parent &&
2888                     mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2889                         mdp->h.md_parent = rdp->h.md_parent;
2890                         mdp->h.md_pi = rdp->h.md_pi - 1;
2891                 }
2892         } else {
2893                 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2894                     &sepkey, NULL, rdp->p.mp_pgno, 0);
2895         }
2896         if (rc != MDB_SUCCESS) {
2897                 free(copy);
2898                 return MDB_FAIL;
2899         }
2900
2901         for (i = j = 0; i <= NUMKEYS(copy); j++) {
2902                 if (i < split_indx) {
2903                         /* Re-insert in left sibling. */
2904                         pdp = mdp;
2905                 } else {
2906                         /* Insert in right sibling. */
2907                         if (i == split_indx)
2908                                 /* Reset insert index for right sibling. */
2909                                 j = (i == newindx && ins_new);
2910                         pdp = rdp;
2911                 }
2912
2913                 if (i == newindx && !ins_new) {
2914                         /* Insert the original entry that caused the split. */
2915                         rkey.mv_data = newkey->mv_data;
2916                         rkey.mv_size = newkey->mv_size;
2917                         if (IS_LEAF(&mdp->p)) {
2918                                 rdata.mv_data = newdata->mv_data;
2919                                 rdata.mv_size = newdata->mv_size;
2920                         } else
2921                                 pgno = newpgno;
2922                         flags = 0;
2923
2924                         ins_new = 1;
2925
2926                         /* Update page and index for the new key. */
2927                         *newindxp = j;
2928                         *mpp = &pdp->p;
2929                 } else if (i == NUMKEYS(copy)) {
2930                         break;
2931                 } else {
2932                         node = NODEPTR(copy, i);
2933                         rkey.mv_data = NODEKEY(node);
2934                         rkey.mv_size = node->mn_ksize;
2935                         if (IS_LEAF(&mdp->p)) {
2936                                 rdata.mv_data = NODEDATA(node);
2937                                 rdata.mv_size = node->mn_dsize;
2938                         } else
2939                                 pgno = node->mn_pgno;
2940                         flags = node->mn_flags;
2941
2942                         i++;
2943                 }
2944
2945                 if (!IS_LEAF(&mdp->p) && j == 0) {
2946                         /* First branch index doesn't need key data. */
2947                         rkey.mv_size = 0;
2948                 }
2949
2950                 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2951         }
2952
2953         free(copy);
2954         return rc;
2955 }
2956
2957 static int
2958 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
2959     MDB_val *key, MDB_val *data, unsigned int flags)
2960 {
2961         int              rc = MDB_SUCCESS, exact;
2962         unsigned int     ki;
2963         MDB_node        *leaf;
2964         MDB_pageparent  mpp;
2965         MDB_val xdata, *rdata;
2966         MDB_db dummy;
2967
2968         DPRINTF("==> put key %.*s, size %zu, data size %zu",
2969                 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2970
2971         mpp.mp_parent = NULL;
2972         mpp.mp_pi = 0;
2973         rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2974         if (rc == MDB_SUCCESS) {
2975                 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2976                 if (leaf && exact) {
2977                         if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2978                                 goto put_sub;
2979                         }
2980                         if (flags == MDB_NOOVERWRITE) {
2981                                 DPRINTF("duplicate key %.*s",
2982                                     (int)key->mv_size, (char *)key->mv_data);
2983                                 return MDB_KEYEXIST;
2984                         }
2985                         /* same size, just replace it */
2986                         if (NODEDSZ(leaf) == data->mv_size) {
2987                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
2988                                 goto done;
2989                         }
2990                         mdb_del_node(mpp.mp_page, ki);
2991                 }
2992                 if (leaf == NULL) {             /* append if not found */
2993                         ki = NUMKEYS(mpp.mp_page);
2994                         DPRINTF("appending key at index %i", ki);
2995                 }
2996         } else if (rc == MDB_NOTFOUND) {
2997                 MDB_dpage *dp;
2998                 /* new file, just write a root leaf page */
2999                 DPRINTF("allocating new root leaf page");
3000                 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3001                         return ENOMEM;
3002                 }
3003                 mpp.mp_page = &dp->p;
3004                 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3005                 txn->mt_dbs[dbi].md_depth++;
3006                 ki = 0;
3007         }
3008         else
3009                 goto done;
3010
3011         assert(IS_LEAF(mpp.mp_page));
3012         DPRINTF("there are %u keys, should insert new key at index %i",
3013                 NUMKEYS(mpp.mp_page), ki);
3014
3015         /* For sorted dups, the data item at this level is a DB record
3016          * for a child DB; the actual data elements are stored as keys
3017          * in the child DB.
3018          */
3019         if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3020                 rdata = &xdata;
3021                 xdata.mv_size = sizeof(MDB_db);
3022                 xdata.mv_data = &dummy;
3023                 memset(&dummy, 0, sizeof(dummy));
3024                 dummy.md_root = P_INVALID;
3025         } else {
3026                 rdata = data;
3027         }
3028
3029         if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, rdata)) {
3030                 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3031         } else {
3032                 /* There is room already in this leaf page. */
3033                 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3034         }
3035
3036         if (rc != MDB_SUCCESS)
3037                 txn->mt_flags |= MDB_TXN_ERROR;
3038         else {
3039                 txn->mt_dbs[dbi].md_entries++;
3040
3041                 /* Remember if we just added a subdatabase */
3042                 if (flags & F_SUBDATA) {
3043                         leaf = NODEPTR(mpp.mp_page, ki);
3044                         leaf->mn_flags |= F_SUBDATA;
3045                 }
3046
3047                 /* Now store the actual data in the child DB. Note that we're
3048                  * storing the user data in the keys field, so there are strict
3049                  * size limits on dupdata. The actual data fields of the child
3050                  * DB are all zero size.
3051                  */
3052                 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3053                         MDB_xcursor mx;
3054
3055                         leaf = NODEPTR(mpp.mp_page, ki);
3056 put_sub:
3057                         mdb_xcursor_init0(txn, dbi, &mx);
3058                         mdb_xcursor_init1(txn, dbi, &mx, leaf);
3059                         xdata.mv_size = 0;
3060                         xdata.mv_data = "";
3061                         if (flags == MDB_NODUPDATA)
3062                                 flags = MDB_NOOVERWRITE;
3063                         rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3064                         mdb_xcursor_fini(txn, dbi, &mx);
3065                         memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3066                                 sizeof(MDB_db));
3067                 }
3068         }
3069
3070 done:
3071         return rc;
3072 }
3073
3074 int
3075 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3076     MDB_val *key, MDB_val *data, unsigned int flags)
3077 {
3078         assert(key != NULL);
3079         assert(data != NULL);
3080
3081         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3082                 return EINVAL;
3083
3084         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3085                 return EINVAL;
3086         }
3087
3088         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3089                 return EINVAL;
3090         }
3091
3092         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3093                 return EINVAL;
3094
3095         return mdb_put0(txn, dbi, key, data, flags);
3096 }
3097
3098 int
3099 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3100 {
3101         if (!env || !arg)
3102                 return EINVAL;
3103
3104         *arg = env->me_flags;
3105         return MDB_SUCCESS;
3106 }
3107
3108 int
3109 mdb_env_get_path(MDB_env *env, const char **arg)
3110 {
3111         if (!env || !arg)
3112                 return EINVAL;
3113
3114         *arg = env->me_path;
3115         return MDB_SUCCESS;
3116 }
3117
3118 static int
3119 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3120 {
3121         arg->ms_psize = env->me_psize;
3122         arg->ms_depth = db->md_depth;
3123         arg->ms_branch_pages = db->md_branch_pages;
3124         arg->ms_leaf_pages = db->md_leaf_pages;
3125         arg->ms_overflow_pages = db->md_overflow_pages;
3126         arg->ms_entries = db->md_entries;
3127
3128         return MDB_SUCCESS;
3129 }
3130 int
3131 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3132 {
3133         if (env == NULL || arg == NULL)
3134                 return EINVAL;
3135
3136         return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3137 }
3138
3139 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3140 {
3141         MDB_val key, data;
3142         MDB_dbi i;
3143         int rc, dirty = 0;
3144         size_t len;
3145
3146         /* main DB? */
3147         if (!name) {
3148                 *dbi = MAIN_DBI;
3149                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3150                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3151                 return MDB_SUCCESS;
3152         }
3153
3154         /* Is the DB already open? */
3155         len = strlen(name);
3156         for (i=2; i<txn->mt_numdbs; i++) {
3157                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3158                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3159                         *dbi = i;
3160                         return MDB_SUCCESS;
3161                 }
3162         }
3163
3164         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3165                 return ENFILE;
3166
3167         /* Find the DB info */
3168         key.mv_size = len;
3169         key.mv_data = (void *)name;
3170         rc = mdb_get(txn, MAIN_DBI, &key, &data);
3171
3172         /* Create if requested */
3173         if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3174                 MDB_db dummy;
3175                 data.mv_size = sizeof(MDB_db);
3176                 data.mv_data = &dummy;
3177                 memset(&dummy, 0, sizeof(dummy));
3178                 dummy.md_root = P_INVALID;
3179                 dummy.md_flags = flags & 0xffff;
3180                 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3181                 dirty = 1;
3182         }
3183
3184         /* OK, got info, add to table */
3185         if (rc == MDB_SUCCESS) {
3186                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3187                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3188                 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3189                 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3190                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3191                 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3192                 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3193                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3194                 *dbi = txn->mt_numdbs;
3195                 txn->mt_numdbs++;
3196         }
3197
3198         return rc;
3199 }
3200
3201 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3202 {
3203         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3204                 return EINVAL;
3205
3206         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3207 }
3208
3209 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3210 {
3211         char *ptr;
3212         if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3213                 return;
3214         ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3215         txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3216         txn->mt_dbxs[dbi].md_name.mv_size = 0;
3217         free(ptr);
3218 }
3219
3220 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3221 {
3222         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3223                 return EINVAL;
3224
3225         txn->mt_dbxs[dbi].md_cmp = cmp;
3226         return MDB_SUCCESS;
3227 }
3228
3229 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3230 {
3231         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3232                 return EINVAL;
3233
3234         txn->mt_dbxs[dbi].md_dcmp = cmp;
3235         return MDB_SUCCESS;
3236 }
3237
3238 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3239 {
3240         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3241                 return EINVAL;
3242
3243         txn->mt_dbxs[dbi].md_rel = rel;
3244         return MDB_SUCCESS;
3245 }