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