]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
Restore missing LAZY_LOCKS semicolon.
[openldap] / libraries / libmdb / mdb.c
1 /** @file mdb.c
2  *      @brief memory-mapped database library
3  *
4  *      A Btree-based database management library modeled loosely on the
5  *      BerkeleyDB API, but much simplified.
6  */
7 /*
8  * Copyright 2011 Howard Chu, Symas Corp.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted only as authorized by the OpenLDAP
13  * Public License.
14  *
15  * A copy of this license is available in the file LICENSE in the
16  * top-level directory of the distribution or, alternatively, at
17  * <http://www.OpenLDAP.org/license.html>.
18  *
19  * This code is derived from btree.c written by Martin Hedenfalk.
20  *
21  * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
22  *
23  * Permission to use, copy, modify, and distribute this software for any
24  * purpose with or without fee is hereby granted, provided that the above
25  * copyright notice and this permission notice appear in all copies.
26  *
27  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34  */
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/param.h>
38 #ifdef _WIN32
39 #include <windows.h>
40 #else
41 #include <sys/uio.h>
42 #include <sys/mman.h>
43 #ifdef HAVE_SYS_FILE_H
44 #include <sys/file.h>
45 #endif
46 #include <fcntl.h>
47 #endif
48
49 #include <assert.h>
50 #include <errno.h>
51 #include <limits.h>
52 #include <stddef.h>
53 #include <stdint.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58 #include <unistd.h>
59
60 #ifndef _WIN32
61 #include <pthread.h>
62 #endif
63
64 #include "mdb.h"
65 #include "midl.h"
66
67 #if (__BYTE_ORDER == __LITTLE_ENDIAN) == (__BYTE_ORDER == __BIG_ENDIAN)
68 # error "Unknown or unsupported endianness (__BYTE_ORDER)"
69 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
70 # error "Two's complement, reasonably sized integer types, please"
71 #endif
72
73 /** @defgroup internal  MDB Internals
74  *      @{
75  */
76 /** @defgroup compat    Windows Compatibility Macros
77  *      A bunch of macros to minimize the amount of platform-specific ifdefs
78  *      needed throughout the rest of the code. When the features this library
79  *      needs are similar enough to POSIX to be hidden in a one-or-two line
80  *      replacement, this macro approach is used.
81  *      @{
82  */
83 #ifdef _WIN32
84 #define pthread_t       DWORD
85 #define pthread_mutex_t HANDLE
86 #define pthread_key_t   DWORD
87 #define pthread_self()  GetCurrentThreadId()
88 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
89 #define pthread_key_delete(x)   TlsFree(x)
90 #define pthread_getspecific(x)  TlsGetValue(x)
91 #define pthread_setspecific(x,y)        TlsSetValue(x,y)
92 #define pthread_mutex_unlock(x) ReleaseMutex(x)
93 #define pthread_mutex_lock(x)   WaitForSingleObject(x, INFINITE)
94 #define LOCK_MUTEX_R(env)       pthread_mutex_lock((env)->me_rmutex)
95 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock((env)->me_rmutex)
96 #define LOCK_MUTEX_W(env)       pthread_mutex_lock((env)->me_wmutex)
97 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock((env)->me_wmutex)
98 #define getpid()        GetCurrentProcessId()
99 #define fdatasync(fd)   (!FlushFileBuffers(fd))
100 #define ErrCode()       GetLastError()
101 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
102 #define close(fd)       CloseHandle(fd)
103 #define munmap(ptr,len) UnmapViewOfFile(ptr)
104 #else
105         /** Lock the reader mutex.
106          */
107 #define LOCK_MUTEX_R(env)       pthread_mutex_lock(&(env)->me_txns->mti_mutex)
108         /** Unlock the reader mutex.
109          */
110 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
111
112         /** Lock the writer mutex.
113          *      Only a single write transaction is allowed at a time. Other writers
114          *      will block waiting for this mutex.
115          */
116 #define LOCK_MUTEX_W(env)       pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
117         /** Unlock the writer mutex.
118          */
119 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
120
121         /** Get the error code for the last failed system function.
122          */
123 #define ErrCode()       errno
124
125         /** An abstraction for a file handle.
126          *      On POSIX systems file handles are small integers. On Windows
127          *      they're opaque pointers.
128          */
129 #define HANDLE  int
130
131         /**     A value for an invalid file handle.
132          *      Mainly used to initialize file variables and signify that they are
133          *      unused.
134          */
135 #define INVALID_HANDLE_VALUE    (-1)
136
137         /** Get the size of a memory page for the system.
138          *      This is the basic size that the platform's memory manager uses, and is
139          *      fundamental to the use of memory-mapped files.
140          */
141 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
142 #endif
143
144 /** @} */
145
146 #ifndef _WIN32
147 /**     A flag for opening a file and requesting synchronous data writes.
148  *      This is only used when writing a meta page. It's not strictly needed;
149  *      we could just do a normal write and then immediately perform a flush.
150  *      But if this flag is available it saves us an extra system call.
151  *
152  *      @note If O_DSYNC is undefined but exists in /usr/include,
153  * preferably set some compiler flag to get the definition.
154  * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
155  */
156 #ifndef MDB_DSYNC
157 # define MDB_DSYNC      O_DSYNC
158 #endif
159 #endif
160
161         /** A page number in the database.
162          *      Note that 64 bit page numbers are overkill, since pages themselves
163          *      already represent 12-13 bits of addressable memory, and the OS will
164          *      always limit applications to a maximum of 63 bits of address space.
165          *
166          *      @note In the #MDB_node structure, we only store 48 bits of this value,
167          *      which thus limits us to only 60 bits of addressable data.
168          */
169 typedef ID      pgno_t;
170
171         /** A transaction ID.
172          *      See struct MDB_txn.mt_txnid for details.
173          */
174 typedef ID      txnid_t;
175
176 /** @defgroup debug     Debug Macros
177  *      @{
178  */
179 #ifndef DEBUG
180         /**     Enable debug output.
181          *      Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
182          *      read from and written to the database (used for free space management).
183          */
184 #define DEBUG 0
185 #endif
186
187 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
188 # define DPRINTF        (void)  /* Vararg macros may be unsupported */
189 #elif DEBUG
190         /**     Print a debug message with printf formatting. */
191 # define DPRINTF(fmt, ...)      /**< Requires 2 or more args */ \
192         fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
193 #else
194 # define DPRINTF(fmt, ...)      ((void) 0)
195 #endif
196         /**     Print a debug string.
197          *      The string is printed literally, with no format processing.
198          */
199 #define DPUTS(arg)      DPRINTF("%s", arg)
200 /** @} */
201
202         /** A default memory page size.
203          *      The actual size is platform-dependent, but we use this for
204          *      boot-strapping. We probably should not be using this any more.
205          *      The #GET_PAGESIZE() macro is used to get the actual size.
206          *
207          *      Note that we don't currently support Huge pages. On Linux,
208          *      regular data files cannot use Huge pages, and in general
209          *      Huge pages aren't actually pageable. We rely on the OS
210          *      demand-pager to read our data and page it out when memory
211          *      pressure from other processes is high. So until OSs have
212          *      actual paging support for Huge pages, they're not viable.
213          */
214 #define PAGESIZE         4096
215
216         /** The minimum number of keys required in a database page.
217          *      Setting this to a larger value will place a smaller bound on the
218          *      maximum size of a data item. Data items larger than this size will
219          *      be pushed into overflow pages instead of being stored directly in
220          *      the B-tree node. This value used to default to 4. With a page size
221          *      of 4096 bytes that meant that any item larger than 1024 bytes would
222          *      go into an overflow page. That also meant that on average 2-3KB of
223          *      each overflow page was wasted space. The value cannot be lower than
224          *      2 because then there would no longer be a tree structure. With this
225          *      value, items larger than 2KB will go into overflow pages, and on
226          *      average only 1KB will be wasted.
227          */
228 #define MDB_MINKEYS      2
229
230         /**     A stamp that identifies a file as an MDB file.
231          *      There's nothing special about this value other than that it is easily
232          *      recognizable, and it will reflect any byte order mismatches.
233          */
234 #define MDB_MAGIC        0xBEEFC0DE
235
236         /**     The version number for a database's file format. */
237 #define MDB_VERSION      1
238
239         /**     The maximum size of a key in the database.
240          *      While data items have essentially unbounded size, we require that
241          *      keys all fit onto a regular page. This limit could be raised a bit
242          *      further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
243          */
244 #define MAXKEYSIZE       511
245
246 #if DEBUG
247         /**     A key buffer.
248          *      @ingroup debug
249          *      This is used for printing a hex dump of a key's contents.
250          */
251 #define DKBUF   char kbuf[(MAXKEYSIZE*2+1)]
252         /**     Display a key in hex.
253          *      @ingroup debug
254          *      Invoke a function to display a key in hex.
255          */
256 #define DKEY(x) mdb_dkey(x, kbuf)
257 #else
258 #define DKBUF   typedef int dummy_kbuf  /* so we can put ';' after */
259 #define DKEY(x)
260 #endif
261
262 /**     @defgroup lazylock      Lazy Locking
263  *      Macros for locks that are't actually needed.
264  *      The DB view is always consistent because all writes are wrapped in
265  *      the wmutex. Finer-grained locks aren't necessary.
266  *      @{
267  */
268 #ifndef LAZY_LOCKS
269         /**     Use lazy locking. I.e., don't lock these accesses at all. */
270 #define LAZY_LOCKS      1
271 #endif
272 #if     LAZY_LOCKS
273         /** Grab the reader lock */
274 #define LAZY_MUTEX_LOCK(x)
275         /** Release the reader lock */
276 #define LAZY_MUTEX_UNLOCK(x)
277         /** Release the DB table reader/writer lock */
278 #define LAZY_RWLOCK_UNLOCK(x)
279         /** Grab the DB table write lock */
280 #define LAZY_RWLOCK_WRLOCK(x)
281         /** Grab the DB table read lock */
282 #define LAZY_RWLOCK_RDLOCK(x)
283         /** Declare the DB table rwlock.  Should not be followed by ';'. */
284 #define LAZY_RWLOCK_DEF(x)
285         /** Initialize the DB table rwlock */
286 #define LAZY_RWLOCK_INIT(x,y)
287         /**     Destroy the DB table rwlock */
288 #define LAZY_RWLOCK_DESTROY(x)
289 #else
290 #define LAZY_MUTEX_LOCK(x)              pthread_mutex_lock(x)
291 #define LAZY_MUTEX_UNLOCK(x)    pthread_mutex_unlock(x)
292 #define LAZY_RWLOCK_UNLOCK(x)   pthread_rwlock_unlock(x)
293 #define LAZY_RWLOCK_WRLOCK(x)   pthread_rwlock_wrlock(x)
294 #define LAZY_RWLOCK_RDLOCK(x)   pthread_rwlock_rdlock(x)
295 #define LAZY_RWLOCK_DEF(x)              pthread_rwlock_t        x;
296 #define LAZY_RWLOCK_INIT(x,y)   pthread_rwlock_init(x,y)
297 #define LAZY_RWLOCK_DESTROY(x)  pthread_rwlock_destroy(x)
298 #endif
299 /** @} */
300
301         /** An invalid page number.
302          *      Mainly used to denote an empty tree.
303          */
304 #define P_INVALID        (~0UL)
305
306         /** Test if a flag \b f is set in a flag word \b w. */
307 #define F_ISSET(w, f)    (((w) & (f)) == (f))
308
309         /**     Used for offsets within a single page.
310          *      Since memory pages are typically 4 or 8KB in size, 12-13 bits,
311          *      this is plenty.
312          */
313 typedef uint16_t         indx_t;
314
315         /**     Default size of memory map.
316          *      This is certainly too small for any actual applications. Apps should always set
317          *      the size explicitly using #mdb_env_set_mapsize().
318          */
319 #define DEFAULT_MAPSIZE 1048576
320
321 /**     @defgroup readers       Reader Lock Table
322  *      Readers don't acquire any locks for their data access. Instead, they
323  *      simply record their transaction ID in the reader table. The reader
324  *      mutex is needed just to find an empty slot in the reader table. The
325  *      slot's address is saved in thread-specific data so that subsequent read
326  *      transactions started by the same thread need no further locking to proceed.
327  *
328  *      Since the database uses multi-version concurrency control, readers don't
329  *      actually need any locking. This table is used to keep track of which
330  *      readers are using data from which old transactions, so that we'll know
331  *      when a particular old transaction is no longer in use. Old transactions
332  *      that have discarded any data pages can then have those pages reclaimed
333  *      for use by a later write transaction.
334  *
335  *      The lock table is constructed such that reader slots are aligned with the
336  *      processor's cache line size. Any slot is only ever used by one thread.
337  *      This alignment guarantees that there will be no contention or cache
338  *      thrashing as threads update their own slot info, and also eliminates
339  *      any need for locking when accessing a slot.
340  *
341  *      A writer thread will scan every slot in the table to determine the oldest
342  *      outstanding reader transaction. Any freed pages older than this will be
343  *      reclaimed by the writer. The writer doesn't use any locks when scanning
344  *      this table. This means that there's no guarantee that the writer will
345  *      see the most up-to-date reader info, but that's not required for correct
346  *      operation - all we need is to know the upper bound on the oldest reader,
347  *      we don't care at all about the newest reader. So the only consequence of
348  *      reading stale information here is that old pages might hang around a
349  *      while longer before being reclaimed. That's actually good anyway, because
350  *      the longer we delay reclaiming old pages, the more likely it is that a
351  *      string of contiguous pages can be found after coalescing old pages from
352  *      many old transactions together.
353  *
354  *      @todo We don't actually do such coalescing yet, we grab pages from one
355  *      old transaction at a time.
356  *      @{
357  */
358         /**     Number of slots in the reader table.
359          *      This value was chosen somewhat arbitrarily. 126 readers plus a
360          *      couple mutexes fit exactly into 8KB on my development machine.
361          *      Applications should set the table size using #mdb_env_set_maxreaders().
362          */
363 #define DEFAULT_READERS 126
364
365         /**     The size of a CPU cache line in bytes. We want our lock structures
366          *      aligned to this size to avoid false cache line sharing in the
367          *      lock table.
368          *      This value works for most CPUs. For Itanium this should be 128.
369          */
370 #ifndef CACHELINE
371 #define CACHELINE       64
372 #endif
373
374         /**     The information we store in a single slot of the reader table.
375          *      In addition to a transaction ID, we also record the process and
376          *      thread ID that owns a slot, so that we can detect stale information,
377          *      e.g. threads or processes that went away without cleaning up.
378          *      @note We currently don't check for stale records. We simply re-init
379          *      the table when we know that we're the only process opening the
380          *      lock file.
381          */
382 typedef struct MDB_rxbody {
383         /**     The current Transaction ID when this transaction began.
384          *      Multiple readers that start at the same time will probably have the
385          *      same ID here. Again, it's not important to exclude them from
386          *      anything; all we need to know is which version of the DB they
387          *      started from so we can avoid overwriting any data used in that
388          *      particular version.
389          */
390         txnid_t         mrb_txnid;
391         /** The process ID of the process owning this reader txn. */
392         pid_t           mrb_pid;
393         /** The thread ID of the thread owning this txn. */
394         pthread_t       mrb_tid;
395 } MDB_rxbody;
396
397         /** The actual reader record, with cacheline padding. */
398 typedef struct MDB_reader {
399         union {
400                 MDB_rxbody mrx;
401                 /** shorthand for mrb_txnid */
402 #define mr_txnid        mru.mrx.mrb_txnid
403 #define mr_pid  mru.mrx.mrb_pid
404 #define mr_tid  mru.mrx.mrb_tid
405                 /** cache line alignment */
406                 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
407         } mru;
408 } MDB_reader;
409
410         /** The header for the reader table.
411          *      The table resides in a memory-mapped file. (This is a different file
412          *      than is used for the main database.)
413          *
414          *      For POSIX the actual mutexes reside in the shared memory of this
415          *      mapped file. On Windows, mutexes are named objects allocated by the
416          *      kernel; we store the mutex names in this mapped file so that other
417          *      processes can grab them. This same approach will also be used on
418          *      MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
419          *      process-shared POSIX mutexes.
420          */
421 typedef struct MDB_txbody {
422                 /** Stamp identifying this as an MDB lock file. It must be set
423                  *      to #MDB_MAGIC. */
424         uint32_t        mtb_magic;
425                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
426         uint32_t        mtb_version;
427 #ifdef _WIN32
428         char    mtb_rmname[32];
429 #else
430                 /** Mutex protecting access to this table.
431                  *      This is the reader lock that #LOCK_MUTEX_R acquires.
432                  */
433         pthread_mutex_t mtb_mutex;
434 #endif
435                 /**     The ID of the last transaction committed to the database.
436                  *      This is recorded here only for convenience; the value can always
437                  *      be determined by reading the main database meta pages.
438                  */
439         txnid_t         mtb_txnid;
440                 /** The number of slots that have been used in the reader table.
441                  *      This always records the maximum count, it is not decremented
442                  *      when readers release their slots.
443                  */
444         unsigned        mtb_numreaders;
445                 /**     The ID of the most recent meta page in the database.
446                  *      This is recorded here only for convenience; the value can always
447                  *      be determined by reading the main database meta pages.
448                  */
449         uint32_t        mtb_me_toggle;
450 } MDB_txbody;
451
452         /** The actual reader table definition. */
453 typedef struct MDB_txninfo {
454         union {
455                 MDB_txbody mtb;
456 #define mti_magic       mt1.mtb.mtb_magic
457 #define mti_version     mt1.mtb.mtb_version
458 #define mti_mutex       mt1.mtb.mtb_mutex
459 #define mti_rmname      mt1.mtb.mtb_rmname
460 #define mti_txnid       mt1.mtb.mtb_txnid
461 #define mti_numreaders  mt1.mtb.mtb_numreaders
462 #define mti_me_toggle   mt1.mtb.mtb_me_toggle
463                 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
464         } mt1;
465         union {
466 #ifdef _WIN32
467                 char mt2_wmname[32];
468 #define mti_wmname      mt2.mt2_wmname
469 #else
470                 pthread_mutex_t mt2_wmutex;
471 #define mti_wmutex      mt2.mt2_wmutex
472 #endif
473                 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
474         } mt2;
475         MDB_reader      mti_readers[1];
476 } MDB_txninfo;
477 /** @} */
478
479 /** Common header for all page types.
480  * Overflow pages occupy a number of contiguous pages with no
481  * headers on any page after the first.
482  */
483 typedef struct MDB_page {
484 #define mp_pgno mp_p.p_pgno
485 #define mp_next mp_p.p_next
486         union padded {
487                 pgno_t          p_pgno; /**< page number */
488                 void *          p_next; /**< for in-memory list of freed structs */
489         } mp_p;
490 #define P_BRANCH         0x01           /**< branch page */
491 #define P_LEAF           0x02           /**< leaf page */
492 #define P_OVERFLOW       0x04           /**< overflow page */
493 #define P_META           0x08           /**< meta page */
494 #define P_DIRTY          0x10           /**< dirty page */
495 #define P_LEAF2          0x20           /**< for #MDB_DUPFIXED records */
496         uint32_t        mp_flags;
497 #define mp_lower        mp_pb.pb.pb_lower
498 #define mp_upper        mp_pb.pb.pb_upper
499 #define mp_pages        mp_pb.pb_pages
500         union page_bounds {
501                 struct {
502                         indx_t          pb_lower;               /**< lower bound of free space */
503                         indx_t          pb_upper;               /**< upper bound of free space */
504                 } pb;
505                 uint32_t        pb_pages;       /**< number of overflow pages */
506         } mp_pb;
507         indx_t          mp_ptrs[1];             /**< dynamic size */
508 } MDB_page;
509
510         /** Size of the page header, excluding dynamic data at the end */
511 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
512
513         /** Address of first usable data byte in a page, after the header */
514 #define METADATA(p)      ((void *)((char *)(p) + PAGEHDRSZ))
515
516         /** Number of nodes on a page */
517 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
518
519         /** The amount of space remaining in the page */
520 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
521
522         /** The percentage of space used in the page, in tenths of a percent. */
523 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
524                                 ((env)->me_psize - PAGEHDRSZ))
525         /** The minimum page fill factor, in tenths of a percent.
526          *      Pages emptier than this are candidates for merging.
527          */
528 #define FILL_THRESHOLD   250
529
530         /** Test if a page is a leaf page */
531 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
532         /** Test if a page is a LEAF2 page */
533 #define IS_LEAF2(p)      F_ISSET((p)->mp_flags, P_LEAF2)
534         /** Test if a page is a branch page */
535 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
536         /** Test if a page is an overflow page */
537 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
538
539         /** The number of overflow pages needed to store the given size. */
540 #define OVPAGES(size, psize)    ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
541
542         /** Header for a single key/data pair within a page.
543          * We guarantee 2-byte alignment for nodes.
544          */
545 typedef struct MDB_node {
546         /** lo and hi are used for data size on leaf nodes and for
547          * child pgno on branch nodes. On 64 bit platforms, flags
548          * is also used for pgno. (Branch nodes have no flags).
549          * They are in in host byte order in case that lets some
550          * accesses be optimized into a 32-bit word access.
551          */
552 #define mn_lo mn_offset[__BYTE_ORDER!=__LITTLE_ENDIAN]
553 #define mn_hi mn_offset[__BYTE_ORDER==__LITTLE_ENDIAN] /**< part of dsize or pgno */
554         unsigned short  mn_offset[2];
555         unsigned short  mn_flags;               /**< flags for special node types */
556 #define F_BIGDATA        0x01                   /**< data put on overflow page */
557 #define F_SUBDATA        0x02                   /**< data is a sub-database */
558 #define F_DUPDATA        0x04                   /**< data has duplicates */
559         unsigned short  mn_ksize;               /**< key size */
560         char            mn_data[1];                     /**< key and data are appended here */
561 } MDB_node;
562
563         /** Size of the node header, excluding dynamic data at the end */
564 #define NODESIZE         offsetof(MDB_node, mn_data)
565
566         /** Bit position of top word in page number, for shifting mn_flags */
567 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
568
569         /** Size of a node in a branch page with a given key.
570          *      This is just the node header plus the key, there is no data.
571          */
572 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
573
574         /** Size of a node in a leaf page with a given key and data.
575          *      This is node header plus key plus data size.
576          */
577 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
578
579         /** Address of node \b i in page \b p */
580 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
581
582         /** Address of the key for the node */
583 #define NODEKEY(node)    (void *)((node)->mn_data)
584
585         /** Address of the data for a node */
586 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
587
588         /** Get the page number pointed to by a branch node */
589 #define NODEPGNO(node) \
590         ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
591          (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
592         /** Set the page number in a branch node */
593 #define SETPGNO(node,pgno)      do { \
594         (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
595         if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
596
597         /** Get the size of the data in a leaf node */
598 #define NODEDSZ(node)    ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
599         /** Set the size of the data for a leaf node */
600 #define SETDSZ(node,size)       do { \
601         (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
602         /** The size of a key in a node */
603 #define NODEKSZ(node)    ((node)->mn_ksize)
604
605         /** The address of a key in a LEAF2 page.
606          *      LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
607          *      There are no node headers, keys are stored contiguously.
608          */
609 #define LEAF2KEY(p, i, ks)      ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
610
611         /** Set the \b node's key into \b key, if requested. */
612 #define MDB_SET_KEY(node, key)  { if ((key) != NULL) { \
613         (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
614
615         /** Information about a single database in the environment. */
616 typedef struct MDB_db {
617         uint32_t        md_pad;         /**< also ksize for LEAF2 pages */
618         uint16_t        md_flags;       /**< @ref mdb_open */
619         uint16_t        md_depth;       /**< depth of this tree */
620         pgno_t          md_branch_pages;        /**< number of internal pages */
621         pgno_t          md_leaf_pages;          /**< number of leaf pages */
622         pgno_t          md_overflow_pages;      /**< number of overflow pages */
623         size_t          md_entries;             /**< number of data items */
624         pgno_t          md_root;                /**< the root page of this tree */
625 } MDB_db;
626
627         /** Handle for the DB used to track free pages. */
628 #define FREE_DBI        0
629         /** Handle for the default DB. */
630 #define MAIN_DBI        1
631
632         /** Meta page content. */
633 typedef struct MDB_meta {
634                 /** Stamp identifying this as an MDB data file. It must be set
635                  *      to #MDB_MAGIC. */
636         uint32_t        mm_magic;
637                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
638         uint32_t        mm_version;
639         void            *mm_address;            /**< address for fixed mapping */
640         size_t          mm_mapsize;                     /**< size of mmap region */
641         MDB_db          mm_dbs[2];                      /**< first is free space, 2nd is main db */
642         /** The size of pages used in this DB */
643 #define mm_psize        mm_dbs[0].md_pad
644         /** Any persistent environment flags. @ref mdb_env */
645 #define mm_flags        mm_dbs[0].md_flags
646         pgno_t          mm_last_pg;                     /**< last used page in file */
647         txnid_t         mm_txnid;                       /**< txnid that committed this page */
648 } MDB_meta;
649
650         /** Auxiliary DB info.
651          *      The information here is mostly static/read-only. There is
652          *      only a single copy of this record in the environment.
653          *      The \b md_dirty flag is not read-only, but only a write
654          *      transaction can ever update it, and only write transactions
655          *      need to worry about it.
656          */
657 typedef struct MDB_dbx {
658         MDB_val         md_name;                /**< name of the database */
659         MDB_cmp_func    *md_cmp;        /**< function for comparing keys */
660         MDB_cmp_func    *md_dcmp;       /**< function for comparing data items */
661         MDB_rel_func    *md_rel;        /**< user relocate function */
662         MDB_dbi md_parent;                      /**< parent DB of a sub-DB */
663         unsigned int    md_dirty;       /**< TRUE if DB was written in this txn */
664 } MDB_dbx;
665
666         /** A database transaction.
667          *      Every operation requires a transaction handle.
668          */
669 struct MDB_txn {
670         pgno_t          mt_next_pgno;   /**< next unallocated page */
671         /** The ID of this transaction. IDs are integers incrementing from 1.
672          *      Only committed write transactions increment the ID. If a transaction
673          *      aborts, the ID may be re-used by the next writer.
674          */
675         txnid_t         mt_txnid;
676         MDB_env         *mt_env;                /**< the DB environment */
677         /** The list of pages that became unused during this transaction.
678          *      This is an #IDL.
679          */
680         pgno_t          *mt_free_pgs;
681         union {
682                 ID2L    dirty_list;     /**< modified pages */
683                 MDB_reader      *reader;        /**< this thread's slot in the reader table */
684         } mt_u;
685         /** Array of records for each DB known in the environment. */
686         MDB_dbx         *mt_dbxs;
687         /** Array of MDB_db records for each known DB */
688         MDB_db          *mt_dbs;
689         /**     Number of DB records in use. This number only ever increments;
690          *      we don't decrement it when individual DB handles are closed.
691          */
692         MDB_dbi         mt_numdbs;
693
694 #define MDB_TXN_RDONLY          0x01            /**< read-only transaction */
695 #define MDB_TXN_ERROR           0x02            /**< an error has occurred */
696         unsigned int    mt_flags;
697         /** Tracks which of the two meta pages was used at the start
698          *      of this transaction.
699          */
700         unsigned int    mt_toggle;
701 };
702
703 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
704  * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
705  * raise this on a 64 bit machine.
706  */
707 #define CURSOR_STACK             32
708
709 struct MDB_xcursor;
710
711         /** Cursors are used for all DB operations */
712 struct MDB_cursor {
713         /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
714         struct MDB_xcursor      *mc_xcursor;
715         /** The transaction that owns this cursor */
716         MDB_txn         *mc_txn;
717         /** The database handle this cursor operates on */
718         MDB_dbi         mc_dbi;
719         unsigned short  mc_snum;        /**< number of pushed pages */
720         unsigned short  mc_top;         /**< index of top page, mc_snum-1 */
721         unsigned int    mc_flags;
722 #define C_INITIALIZED   0x01    /**< cursor has been initialized and is valid */
723 #define C_EOF   0x02                    /**< No more data */
724 #define C_XDIRTY        0x04            /**< @deprecated mc_xcursor needs to be flushed */
725         MDB_page        *mc_pg[CURSOR_STACK];   /**< stack of pushed pages */
726         indx_t          mc_ki[CURSOR_STACK];    /**< stack of page indices */
727 };
728
729         /** Context for sorted-dup records.
730          *      We could have gone to a fully recursive design, with arbitrarily
731          *      deep nesting of sub-databases. But for now we only handle these
732          *      levels - main DB, optional sub-DB, sorted-duplicate DB.
733          */
734 typedef struct MDB_xcursor {
735         /** A sub-cursor for traversing the Dup DB */
736         MDB_cursor mx_cursor;
737         /** A fake transaction struct for pointing to our own table
738          *      of DB info.
739          */
740         MDB_txn mx_txn;
741         /**     Our private DB information tables. Slots 0 and 1 are always
742          *      copies of the corresponding slots in the main transaction. These
743          *      hold the FREEDB and MAINDB, respectively. If the main cursor is
744          *      on a sub-database, that will be copied to slot 2, and the duplicate
745          *      database info will be in slot 3. If the main cursor is on the MAINDB
746          *      then the duplicate DB info will be in slot 2 and slot 3 will be unused.
747          */
748         MDB_dbx mx_dbxs[4];
749         /** MDB_db table */
750         MDB_db  mx_dbs[4];
751 } MDB_xcursor;
752
753         /** A set of pages freed by an earlier transaction. */
754 typedef struct MDB_oldpages {
755         /** Usually we only read one record from the FREEDB at a time, but
756          *      in case we read more, this will chain them together.
757          */
758         struct MDB_oldpages *mo_next;
759         /**     The ID of the transaction in which these pages were freed. */
760         txnid_t         mo_txnid;
761         /** An #IDL of the pages */
762         pgno_t          mo_pages[1];    /* dynamic */
763 } MDB_oldpages;
764
765         /** The database environment. */
766 struct MDB_env {
767         HANDLE          me_fd;          /**< The main data file */
768         HANDLE          me_lfd;         /**< The lock file */
769         HANDLE          me_mfd;                 /**< just for writing the meta pages */
770         /** Failed to update the meta page. Probably an I/O error. */
771 #define MDB_FATAL_ERROR 0x80000000U
772         uint32_t        me_flags;
773         uint32_t        me_extrapad;    /**< unused for now */
774         unsigned int    me_maxreaders;  /**< size of the reader table */
775         MDB_dbi         me_numdbs;              /**< number of DBs opened */
776         MDB_dbi         me_maxdbs;              /**< size of the DB table */
777         char            *me_path;               /**< path to the DB files */
778         char            *me_map;                /**< the memory map of the data file */
779         MDB_txninfo     *me_txns;               /**< the memory map of the lock file */
780         MDB_meta        *me_metas[2];   /**< pointers to the two meta pages */
781         MDB_txn         *me_txn;                /**< current write transaction */
782         size_t          me_mapsize;             /**< size of the data memory map */
783         off_t           me_size;                /**< current file size */
784         pgno_t          me_maxpg;               /**< me_mapsize / me_psize */
785         unsigned int    me_psize;       /**< size of a page, from #GET_PAGESIZE */
786         unsigned int    me_db_toggle;   /**< which DB table is current */
787         MDB_dbx         *me_dbxs;               /**< array of static DB info */
788         MDB_db          *me_dbs[2];             /**< two arrays of MDB_db info */
789         MDB_oldpages *me_pghead;        /**< list of old page records */
790         pthread_key_t   me_txkey;       /**< thread-key for readers */
791         MDB_page        *me_dpages;             /**< list of malloc'd blocks for re-use */
792         /** IDL of pages that became unused in a write txn */
793         pgno_t          me_free_pgs[MDB_IDL_UM_SIZE];
794         /** ID2L of pages that were written during a write txn */
795         ID2                     me_dirty_list[MDB_IDL_UM_SIZE];
796         /** rwlock for the DB tables, if #LAZY_LOCKS is false */
797         LAZY_RWLOCK_DEF(me_dblock)
798 #ifdef _WIN32
799         HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
800         HANDLE          me_wmutex;
801 #endif
802 };
803         /** max number of pages to commit in one writev() call */
804 #define MDB_COMMIT_PAGES         64
805
806 static MDB_page *mdb_alloc_page(MDB_cursor *mc, int num);
807 static int              mdb_touch(MDB_cursor *mc);
808
809 static int  mdb_search_page_root(MDB_cursor *mc,
810                             MDB_val *key, int modify);
811 static int  mdb_search_page(MDB_cursor *mc,
812                             MDB_val *key, int modify);
813
814 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
815 static int  mdb_env_read_meta(MDB_env *env, int *which);
816 static int  mdb_env_write_meta(MDB_txn *txn);
817 static int  mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
818
819 static MDB_node *mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp);
820 static int  mdb_add_node(MDB_cursor *mc, indx_t indx,
821                             MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
822 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
823 static int mdb_del0(MDB_cursor *mc, MDB_node *leaf);
824 static int  mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
825
826 static int      mdb_rebalance(MDB_cursor *mc);
827 static int      mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
828 static int      mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst);
829 static int      mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst);
830 static int      mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
831                                 pgno_t newpgno);
832 static MDB_page *mdb_new_page(MDB_cursor *mc, uint32_t flags, int num);
833
834 static void     cursor_pop_page(MDB_cursor *mc);
835 static int      cursor_push_page(MDB_cursor *mc, MDB_page *mp);
836
837 static int      mdb_sibling(MDB_cursor *mc, int move_right);
838 static int      mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
839 static int      mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
840 static int      mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
841                                 int *exactp);
842 static int      mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
843 static int      mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
844
845 static void     mdb_xcursor_init0(MDB_cursor *mc);
846 static void     mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
847 static void     mdb_xcursor_init2(MDB_cursor *mc);
848 static void     mdb_xcursor_fini(MDB_cursor *mc);
849
850 static size_t   mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
851 static size_t   mdb_branch_size(MDB_env *env, MDB_val *key);
852
853 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
854
855 /** @cond */
856 static MDB_cmp_func     memncmp, memnrcmp, intcmp, cintcmp;
857 /** @endcond */
858
859 #ifdef _WIN32
860 static SECURITY_DESCRIPTOR mdb_null_sd;
861 static SECURITY_ATTRIBUTES mdb_all_sa;
862 static int mdb_sec_inited;
863 #endif
864
865 /** Return the library version info. */
866 char *
867 mdb_version(int *major, int *minor, int *patch)
868 {
869         if (major) *major = MDB_VERSION_MAJOR;
870         if (minor) *minor = MDB_VERSION_MINOR;
871         if (patch) *patch = MDB_VERSION_PATCH;
872         return MDB_VERSION_STRING;
873 }
874
875 /** Table of descriptions for MDB @ref errors */
876 static char *const mdb_errstr[] = {
877         "MDB_KEYEXIST: Key/data pair already exists",
878         "MDB_NOTFOUND: No matching key/data pair found",
879         "MDB_PAGE_NOTFOUND: Requested page not found",
880         "MDB_CORRUPTED: Located page was wrong type",
881         "MDB_PANIC: Update of meta page failed",
882         "MDB_VERSION_MISMATCH: Database environment version mismatch"
883 };
884
885 char *
886 mdb_strerror(int err)
887 {
888         if (!err)
889                 return ("Successful return: 0");
890
891         if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
892                 return mdb_errstr[err - MDB_KEYEXIST];
893
894         return strerror(err);
895 }
896
897 #if DEBUG
898 /** Display a key in hexadecimal and return the address of the result.
899  * @param[in] key the key to display
900  * @param[in] buf the buffer to write into. Should always be #DKBUF.
901  * @return The key in hexadecimal form.
902  */
903 char *
904 mdb_dkey(MDB_val *key, char *buf)
905 {
906         char *ptr = buf;
907         unsigned char *c = key->mv_data;
908         unsigned int i;
909         if (key->mv_size > MAXKEYSIZE)
910                 return "MAXKEYSIZE";
911         /* may want to make this a dynamic check: if the key is mostly
912          * printable characters, print it as-is instead of converting to hex.
913          */
914 #if 1
915         for (i=0; i<key->mv_size; i++)
916                 ptr += sprintf(ptr, "%02x", *c++);
917 #else
918         sprintf(buf, "%.*s", key->mv_size, key->mv_data);
919 #endif
920         return buf;
921 }
922 #endif
923
924 int
925 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
926 {
927         return txn->mt_dbxs[dbi].md_cmp(a, b);
928 }
929
930 /** Compare two data items according to a particular database.
931  * This returns a comparison as if the two items were data items of
932  * a sorted duplicates #MDB_DUPSORT database.
933  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
934  * @param[in] dbi A database handle returned by #mdb_open()
935  * @param[in] a The first item to compare
936  * @param[in] b The second item to compare
937  * @return < 0 if a < b, 0 if a == b, > 0 if a > b
938  */
939 int
940 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
941 {
942         if (txn->mt_dbxs[dbi].md_dcmp)
943                 return txn->mt_dbxs[dbi].md_dcmp(a, b);
944         else
945                 return EINVAL;  /* too bad you can't distinguish this from a valid result */
946 }
947
948 /** Allocate pages for writing.
949  * If there are free pages available from older transactions, they
950  * will be re-used first. Otherwise a new page will be allocated.
951  * @param[in] mc cursor A cursor handle identifying the transaction and
952  *      database for which we are allocating.
953  * @param[in] num the number of pages to allocate.
954  * @return Address of the allocated page(s). Requests for multiple pages
955  *  will always be satisfied by a single contiguous chunk of memory.
956  */
957 static MDB_page *
958 mdb_alloc_page(MDB_cursor *mc, int num)
959 {
960         MDB_txn *txn = mc->mc_txn;
961         MDB_page *np;
962         pgno_t pgno = P_INVALID;
963         ID2 mid;
964
965         if (txn->mt_txnid > 2) {
966
967                 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
968                         txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
969                         /* See if there's anything in the free DB */
970                         MDB_cursor m2;
971                         MDB_node *leaf;
972                         txnid_t *kptr, oldest;
973
974                         m2.mc_txn = txn;
975                         m2.mc_dbi = FREE_DBI;
976                         m2.mc_snum = 0;
977                         m2.mc_flags = 0;
978                         mdb_search_page(&m2, NULL, 0);
979                         leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
980                         kptr = (txnid_t *)NODEKEY(leaf);
981
982                         {
983                                 unsigned int i;
984                                 oldest = txn->mt_txnid - 1;
985                                 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
986                                         txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
987                                         if (mr && mr < oldest)
988                                                 oldest = mr;
989                                 }
990                         }
991
992                         if (oldest > *kptr) {
993                                 /* It's usable, grab it.
994                                  */
995                                 MDB_oldpages *mop;
996                                 MDB_val data;
997                                 pgno_t *idl;
998
999                                 mdb_read_data(txn, leaf, &data);
1000                                 idl = (ID *) data.mv_data;
1001                                 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1002                                 mop->mo_next = txn->mt_env->me_pghead;
1003                                 mop->mo_txnid = *kptr;
1004                                 txn->mt_env->me_pghead = mop;
1005                                 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1006
1007 #if DEBUG > 1
1008                                 {
1009                                         unsigned int i;
1010                                         DPRINTF("IDL read txn %zu root %zu num %zu",
1011                                                 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1012                                         for (i=0; i<idl[0]; i++) {
1013                                                 DPRINTF("IDL %zu", idl[i+1]);
1014                                         }
1015                                 }
1016 #endif
1017                                 /* drop this IDL from the DB */
1018                                 m2.mc_ki[m2.mc_top] = 0;
1019                                 m2.mc_flags = C_INITIALIZED;
1020                                 mdb_cursor_del(&m2, 0);
1021                         }
1022                 }
1023                 if (txn->mt_env->me_pghead) {
1024                         MDB_oldpages *mop = txn->mt_env->me_pghead;
1025                         if (num > 1) {
1026                                 /* FIXME: For now, always use fresh pages. We
1027                                  * really ought to search the free list for a
1028                                  * contiguous range.
1029                                  */
1030                                 ;
1031                         } else {
1032                                 /* peel pages off tail, so we only have to truncate the list */
1033                                 pgno = MDB_IDL_LAST(mop->mo_pages);
1034                                 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1035                                         mop->mo_pages[2]++;
1036                                         if (mop->mo_pages[2] > mop->mo_pages[1])
1037                                                 mop->mo_pages[0] = 0;
1038                                 } else {
1039                                         mop->mo_pages[0]--;
1040                                 }
1041                                 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1042                                         txn->mt_env->me_pghead = mop->mo_next;
1043                                         free(mop);
1044                                 }
1045                         }
1046                 }
1047         }
1048
1049         if (pgno == P_INVALID) {
1050                 /* DB size is maxed out */
1051                 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
1052                         return NULL;
1053         }
1054         if (txn->mt_env->me_dpages && num == 1) {
1055                 np = txn->mt_env->me_dpages;
1056                 txn->mt_env->me_dpages = np->mp_next;
1057         } else {
1058                 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1059                         return NULL;
1060         }
1061         if (pgno == P_INVALID) {
1062                 np->mp_pgno = txn->mt_next_pgno;
1063                 txn->mt_next_pgno += num;
1064         } else {
1065                 np->mp_pgno = pgno;
1066         }
1067         mid.mid = np->mp_pgno;
1068         mid.mptr = np;
1069         mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1070
1071         return np;
1072 }
1073
1074 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1075  * @param[in] mc cursor pointing to the page to be touched
1076  * @return 0 on success, non-zero on failure.
1077  */
1078 static int
1079 mdb_touch(MDB_cursor *mc)
1080 {
1081         MDB_page *mp = mc->mc_pg[mc->mc_top];
1082         pgno_t  pgno;
1083
1084         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1085                 MDB_page *np;
1086                 if ((np = mdb_alloc_page(mc, 1)) == NULL)
1087                         return ENOMEM;
1088                 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1089                 assert(mp->mp_pgno != np->mp_pgno);
1090                 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1091                 pgno = np->mp_pgno;
1092                 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1093                 mp = np;
1094                 mp->mp_pgno = pgno;
1095                 mp->mp_flags |= P_DIRTY;
1096
1097                 mc->mc_pg[mc->mc_top] = mp;
1098                 /** If this page has a parent, update the parent to point to
1099                  * this new page.
1100                  */
1101                 if (mc->mc_top)
1102                         SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1103         }
1104         return 0;
1105 }
1106
1107 int
1108 mdb_env_sync(MDB_env *env, int force)
1109 {
1110         int rc = 0;
1111         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1112                 if (fdatasync(env->me_fd))
1113                         rc = ErrCode();
1114         }
1115         return rc;
1116 }
1117
1118 static inline void
1119 mdb_txn_reset0(MDB_txn *txn);
1120
1121 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1122  * @param[in] txn the transaction handle to initialize
1123  * @return 0 on success, non-zero on failure. This can only
1124  * fail for read-only transactions, and then only if the
1125  * reader table is full.
1126  */
1127 static inline int
1128 mdb_txn_renew0(MDB_txn *txn)
1129 {
1130         MDB_env *env = txn->mt_env;
1131
1132         if (txn->mt_flags & MDB_TXN_RDONLY) {
1133                 MDB_reader *r = pthread_getspecific(env->me_txkey);
1134                 if (!r) {
1135                         unsigned int i;
1136                         pid_t pid = getpid();
1137                         pthread_t tid = pthread_self();
1138
1139                         LOCK_MUTEX_R(env);
1140                         for (i=0; i<env->me_txns->mti_numreaders; i++)
1141                                 if (env->me_txns->mti_readers[i].mr_pid == 0)
1142                                         break;
1143                         if (i == env->me_maxreaders) {
1144                                 UNLOCK_MUTEX_R(env);
1145                                 return ENOMEM;
1146                         }
1147                         env->me_txns->mti_readers[i].mr_pid = pid;
1148                         env->me_txns->mti_readers[i].mr_tid = tid;
1149                         if (i >= env->me_txns->mti_numreaders)
1150                                 env->me_txns->mti_numreaders = i+1;
1151                         UNLOCK_MUTEX_R(env);
1152                         r = &env->me_txns->mti_readers[i];
1153                         pthread_setspecific(env->me_txkey, r);
1154                 }
1155                 txn->mt_txnid = env->me_txns->mti_txnid;
1156                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1157                 r->mr_txnid = txn->mt_txnid;
1158                 txn->mt_u.reader = r;
1159         } else {
1160                 LOCK_MUTEX_W(env);
1161
1162                 txn->mt_txnid = env->me_txns->mti_txnid+1;
1163                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1164                 txn->mt_u.dirty_list = env->me_dirty_list;
1165                 txn->mt_u.dirty_list[0].mid = 0;
1166                 txn->mt_free_pgs = env->me_free_pgs;
1167                 txn->mt_free_pgs[0] = 0;
1168                 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1169                 env->me_txn = txn;
1170         }
1171
1172         /* Copy the DB arrays */
1173         LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1174         txn->mt_numdbs = env->me_numdbs;
1175         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
1176         memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1177         if (txn->mt_numdbs > 2)
1178                 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1179                         (txn->mt_numdbs - 2) * sizeof(MDB_db));
1180         LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1181
1182         return MDB_SUCCESS;
1183 }
1184
1185 int
1186 mdb_txn_renew(MDB_txn *txn)
1187 {
1188         int rc;
1189
1190         if (!txn)
1191                 return EINVAL;
1192
1193         if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1194                 DPUTS("environment had fatal error, must shutdown!");
1195                 return MDB_PANIC;
1196         }
1197
1198         rc = mdb_txn_renew0(txn);
1199         if (rc == MDB_SUCCESS) {
1200                 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1201                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1202                         (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1203         }
1204         return rc;
1205 }
1206
1207 int
1208 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1209 {
1210         MDB_txn *txn;
1211         int rc;
1212
1213         if (env->me_flags & MDB_FATAL_ERROR) {
1214                 DPUTS("environment had fatal error, must shutdown!");
1215                 return MDB_PANIC;
1216         }
1217         if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1218                 DPRINTF("calloc: %s", strerror(ErrCode()));
1219                 return ENOMEM;
1220         }
1221         txn->mt_dbs = (MDB_db *)(txn+1);
1222         if (flags & MDB_RDONLY) {
1223                 txn->mt_flags |= MDB_TXN_RDONLY;
1224         }
1225         txn->mt_env = env;
1226
1227         rc = mdb_txn_renew0(txn);
1228         if (rc)
1229                 free(txn);
1230         else {
1231                 *ret = txn;
1232                 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1233                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1234                         (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1235         }
1236
1237         return rc;
1238 }
1239
1240 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1241  * @param[in] txn the transaction handle to reset
1242  */
1243 static inline void
1244 mdb_txn_reset0(MDB_txn *txn)
1245 {
1246         MDB_env *env = txn->mt_env;
1247
1248         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1249                 txn->mt_u.reader->mr_txnid = 0;
1250         } else {
1251                 MDB_oldpages *mop;
1252                 MDB_page *dp;
1253                 MDB_dbi dbi;
1254                 unsigned int i;
1255
1256                 /* return all dirty pages to dpage list */
1257                 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1258                         dp = txn->mt_u.dirty_list[i].mptr;
1259                         if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1260                                 dp->mp_next = txn->mt_env->me_dpages;
1261                                 txn->mt_env->me_dpages = dp;
1262                         } else {
1263                                 /* large pages just get freed directly */
1264                                 free(dp);
1265                         }
1266                 }
1267
1268                 while ((mop = txn->mt_env->me_pghead)) {
1269                         txn->mt_env->me_pghead = mop->mo_next;
1270                         free(mop);
1271                 }
1272
1273                 env->me_txn = NULL;
1274                 for (dbi=2; dbi<env->me_numdbs; dbi++)
1275                         env->me_dbxs[dbi].md_dirty = 0;
1276                 /* The writer mutex was locked in mdb_txn_begin. */
1277                 UNLOCK_MUTEX_W(env);
1278         }
1279 }
1280
1281 void
1282 mdb_txn_reset(MDB_txn *txn)
1283 {
1284         if (txn == NULL)
1285                 return;
1286
1287         DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1288                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1289                 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1290
1291         mdb_txn_reset0(txn);
1292 }
1293
1294 void
1295 mdb_txn_abort(MDB_txn *txn)
1296 {
1297         if (txn == NULL)
1298                 return;
1299
1300         DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1301                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1302                 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1303
1304         mdb_txn_reset0(txn);
1305         free(txn);
1306 }
1307
1308 int
1309 mdb_txn_commit(MDB_txn *txn)
1310 {
1311         int              n, done;
1312         unsigned int i;
1313         ssize_t          rc;
1314         off_t            size;
1315         MDB_page        *dp;
1316         MDB_env *env;
1317         pgno_t  next;
1318         MDB_cursor mc;
1319
1320         assert(txn != NULL);
1321         assert(txn->mt_env != NULL);
1322
1323         env = txn->mt_env;
1324
1325         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1326                 mdb_txn_abort(txn);
1327                 return MDB_SUCCESS;
1328         }
1329
1330         if (txn != env->me_txn) {
1331                 DPUTS("attempt to commit unknown transaction");
1332                 mdb_txn_abort(txn);
1333                 return EINVAL;
1334         }
1335
1336         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1337                 DPUTS("error flag is set, can't commit");
1338                 mdb_txn_abort(txn);
1339                 return EINVAL;
1340         }
1341
1342         if (!txn->mt_u.dirty_list[0].mid)
1343                 goto done;
1344
1345         DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1346             txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1347
1348         mc.mc_txn = txn;
1349         mc.mc_dbi = FREE_DBI;
1350         mc.mc_flags = 0;
1351
1352         /* should only be one record now */
1353         if (env->me_pghead) {
1354                 /* make sure first page of freeDB is touched and on freelist */
1355                 mdb_search_page(&mc, NULL, 1);
1356         }
1357         /* save to free list */
1358         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1359                 MDB_val key, data;
1360                 pgno_t i;
1361
1362                 /* make sure last page of freeDB is touched and on freelist */
1363                 key.mv_size = MAXKEYSIZE+1;
1364                 key.mv_data = NULL;
1365                 mdb_search_page(&mc, &key, 1);
1366
1367                 mdb_midl_sort(txn->mt_free_pgs);
1368 #if DEBUG > 1
1369                 {
1370                         unsigned int i;
1371                         ID *idl = txn->mt_free_pgs;
1372                         DPRINTF("IDL write txn %zu root %zu num %zu",
1373                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1374                         for (i=0; i<idl[0]; i++) {
1375                                 DPRINTF("IDL %zu", idl[i+1]);
1376                         }
1377                 }
1378 #endif
1379                 /* write to last page of freeDB */
1380                 key.mv_size = sizeof(pgno_t);
1381                 key.mv_data = &txn->mt_txnid;
1382                 data.mv_data = txn->mt_free_pgs;
1383                 /* The free list can still grow during this call,
1384                  * despite the pre-emptive touches above. So check
1385                  * and make sure the entire thing got written.
1386                  */
1387                 do {
1388                         i = txn->mt_free_pgs[0];
1389                         data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1390                         rc = mdb_cursor_put(&mc, &key, &data, 0);
1391                         if (rc) {
1392                                 mdb_txn_abort(txn);
1393                                 return rc;
1394                         }
1395                 } while (i != txn->mt_free_pgs[0]);
1396         }
1397         /* should only be one record now */
1398         if (env->me_pghead) {
1399                 MDB_val key, data;
1400                 MDB_oldpages *mop;
1401
1402                 mop = env->me_pghead;
1403                 key.mv_size = sizeof(pgno_t);
1404                 key.mv_data = &mop->mo_txnid;
1405                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1406                 data.mv_data = mop->mo_pages;
1407                 mdb_cursor_put(&mc, &key, &data, 0);
1408                 free(env->me_pghead);
1409                 env->me_pghead = NULL;
1410         }
1411
1412         /* Update DB root pointers. Their pages have already been
1413          * touched so this is all in-place and cannot fail.
1414          */
1415         {
1416                 MDB_dbi i;
1417                 MDB_val data;
1418                 data.mv_size = sizeof(MDB_db);
1419
1420                 mc.mc_dbi = MAIN_DBI;
1421                 mc.mc_flags = 0;
1422                 for (i = 2; i < txn->mt_numdbs; i++) {
1423                         if (txn->mt_dbxs[i].md_dirty) {
1424                                 data.mv_data = &txn->mt_dbs[i];
1425                                 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1426                         }
1427                 }
1428         }
1429
1430         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1431          */
1432         next = 0;
1433         i = 1;
1434         do {
1435 #ifdef _WIN32
1436                 /* Windows actually supports scatter/gather I/O, but only on
1437                  * unbuffered file handles. Since we're relying on the OS page
1438                  * cache for all our data, that's self-defeating. So we just
1439                  * write pages one at a time. We use the ov structure to set
1440                  * the write offset, to at least save the overhead of a Seek
1441                  * system call.
1442                  */
1443                 OVERLAPPED ov;
1444                 memset(&ov, 0, sizeof(ov));
1445                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1446                         size_t wsize;
1447                         dp = txn->mt_u.dirty_list[i].mptr;
1448                         DPRINTF("committing page %zu", dp->mp_pgno);
1449                         size = dp->mp_pgno * env->me_psize;
1450                         ov.Offset = size & 0xffffffff;
1451                         ov.OffsetHigh = size >> 16;
1452                         ov.OffsetHigh >>= 16;
1453                         /* clear dirty flag */
1454                         dp->mp_flags &= ~P_DIRTY;
1455                         wsize = env->me_psize;
1456                         if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1457                         rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1458                         if (!rc) {
1459                                 n = ErrCode();
1460                                 DPRINTF("WriteFile: %d", n);
1461                                 mdb_txn_abort(txn);
1462                                 return n;
1463                         }
1464                 }
1465                 done = 1;;
1466 #else
1467                 struct iovec     iov[MDB_COMMIT_PAGES];
1468                 n = 0;
1469                 done = 1;
1470                 size = 0;
1471                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1472                         dp = txn->mt_u.dirty_list[i].mptr;
1473                         if (dp->mp_pgno != next) {
1474                                 if (n) {
1475                                         DPRINTF("committing %u dirty pages", n);
1476                                         rc = writev(env->me_fd, iov, n);
1477                                         if (rc != size) {
1478                                                 n = ErrCode();
1479                                                 if (rc > 0)
1480                                                         DPUTS("short write, filesystem full?");
1481                                                 else
1482                                                         DPRINTF("writev: %s", strerror(n));
1483                                                 mdb_txn_abort(txn);
1484                                                 return n;
1485                                         }
1486                                         n = 0;
1487                                         size = 0;
1488                                 }
1489                                 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1490                                 next = dp->mp_pgno;
1491                         }
1492                         DPRINTF("committing page %zu", dp->mp_pgno);
1493                         iov[n].iov_len = env->me_psize;
1494                         if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1495                         iov[n].iov_base = dp;
1496                         size += iov[n].iov_len;
1497                         next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1498                         /* clear dirty flag */
1499                         dp->mp_flags &= ~P_DIRTY;
1500                         if (++n >= MDB_COMMIT_PAGES) {
1501                                 done = 0;
1502                                 i++;
1503                                 break;
1504                         }
1505                 }
1506
1507                 if (n == 0)
1508                         break;
1509
1510                 DPRINTF("committing %u dirty pages", n);
1511                 rc = writev(env->me_fd, iov, n);
1512                 if (rc != size) {
1513                         n = ErrCode();
1514                         if (rc > 0)
1515                                 DPUTS("short write, filesystem full?");
1516                         else
1517                                 DPRINTF("writev: %s", strerror(n));
1518                         mdb_txn_abort(txn);
1519                         return n;
1520                 }
1521 #endif
1522         } while (!done);
1523
1524         /* Drop the dirty pages.
1525          */
1526         for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1527                 dp = txn->mt_u.dirty_list[i].mptr;
1528                 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1529                         dp->mp_next = txn->mt_env->me_dpages;
1530                         txn->mt_env->me_dpages = dp;
1531                 } else {
1532                         free(dp);
1533                 }
1534                 txn->mt_u.dirty_list[i].mid = 0;
1535         }
1536         txn->mt_u.dirty_list[0].mid = 0;
1537
1538         if ((n = mdb_env_sync(env, 0)) != 0 ||
1539             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1540                 mdb_txn_abort(txn);
1541                 return n;
1542         }
1543
1544 done:
1545         env->me_txn = NULL;
1546         /* update the DB tables */
1547         {
1548                 int toggle = !env->me_db_toggle;
1549                 MDB_db *ip, *jp;
1550                 MDB_dbi i;
1551
1552                 ip = &env->me_dbs[toggle][2];
1553                 jp = &txn->mt_dbs[2];
1554                 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1555                 for (i = 2; i < txn->mt_numdbs; i++) {
1556                         if (ip->md_root != jp->md_root)
1557                                 *ip = *jp;
1558                         ip++; jp++;
1559                 }
1560
1561                 for (i = 2; i < txn->mt_numdbs; i++) {
1562                         if (txn->mt_dbxs[i].md_dirty)
1563                                 txn->mt_dbxs[i].md_dirty = 0;
1564                 }
1565                 env->me_db_toggle = toggle;
1566                 env->me_numdbs = txn->mt_numdbs;
1567                 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1568         }
1569
1570         UNLOCK_MUTEX_W(env);
1571         free(txn);
1572
1573         return MDB_SUCCESS;
1574 }
1575
1576 /** Read the environment parameters of a DB environment before
1577  * mapping it into memory.
1578  * @param[in] env the environment handle
1579  * @param[out] meta address of where to store the meta information
1580  * @return 0 on success, non-zero on failure.
1581  */
1582 static int
1583 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1584 {
1585         char             page[PAGESIZE];
1586         MDB_page        *p;
1587         MDB_meta        *m;
1588         int              rc, err;
1589
1590         /* We don't know the page size yet, so use a minimum value.
1591          */
1592
1593 #ifdef _WIN32
1594         if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1595 #else
1596         if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1597 #endif
1598         {
1599                 return ENOENT;
1600         }
1601         else if (rc != PAGESIZE) {
1602                 err = ErrCode();
1603                 if (rc > 0)
1604                         err = EINVAL;
1605                 DPRINTF("read: %s", strerror(err));
1606                 return err;
1607         }
1608
1609         p = (MDB_page *)page;
1610
1611         if (!F_ISSET(p->mp_flags, P_META)) {
1612                 DPRINTF("page %zu not a meta page", p->mp_pgno);
1613                 return EINVAL;
1614         }
1615
1616         m = METADATA(p);
1617         if (m->mm_magic != MDB_MAGIC) {
1618                 DPUTS("meta has invalid magic");
1619                 return EINVAL;
1620         }
1621
1622         if (m->mm_version != MDB_VERSION) {
1623                 DPRINTF("database is version %u, expected version %u",
1624                     m->mm_version, MDB_VERSION);
1625                 return MDB_VERSION_MISMATCH;
1626         }
1627
1628         memcpy(meta, m, sizeof(*m));
1629         return 0;
1630 }
1631
1632 /** Write the environment parameters of a freshly created DB environment.
1633  * @param[in] env the environment handle
1634  * @param[out] meta address of where to store the meta information
1635  * @return 0 on success, non-zero on failure.
1636  */
1637 static int
1638 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1639 {
1640         MDB_page *p, *q;
1641         MDB_meta *m;
1642         int rc;
1643         unsigned int     psize;
1644
1645         DPUTS("writing new meta page");
1646
1647         GET_PAGESIZE(psize);
1648
1649         meta->mm_magic = MDB_MAGIC;
1650         meta->mm_version = MDB_VERSION;
1651         meta->mm_psize = psize;
1652         meta->mm_last_pg = 1;
1653         meta->mm_flags = env->me_flags & 0xffff;
1654         meta->mm_flags |= MDB_INTEGERKEY;
1655         meta->mm_dbs[0].md_root = P_INVALID;
1656         meta->mm_dbs[1].md_root = P_INVALID;
1657
1658         p = calloc(2, psize);
1659         p->mp_pgno = 0;
1660         p->mp_flags = P_META;
1661
1662         m = METADATA(p);
1663         memcpy(m, meta, sizeof(*meta));
1664
1665         q = (MDB_page *)((char *)p + psize);
1666
1667         q->mp_pgno = 1;
1668         q->mp_flags = P_META;
1669
1670         m = METADATA(q);
1671         memcpy(m, meta, sizeof(*meta));
1672
1673 #ifdef _WIN32
1674         {
1675                 DWORD len;
1676                 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1677                 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1678         }
1679 #else
1680         rc = write(env->me_fd, p, psize * 2);
1681         rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1682 #endif
1683         free(p);
1684         return rc;
1685 }
1686
1687 /** Update the environment info to commit a transaction.
1688  * @param[in] txn the transaction that's being committed
1689  * @return 0 on success, non-zero on failure.
1690  */
1691 static int
1692 mdb_env_write_meta(MDB_txn *txn)
1693 {
1694         MDB_env *env;
1695         MDB_meta        meta, metab;
1696         off_t off;
1697         int rc, len, toggle;
1698         char *ptr;
1699 #ifdef _WIN32
1700         OVERLAPPED ov;
1701 #endif
1702
1703         assert(txn != NULL);
1704         assert(txn->mt_env != NULL);
1705
1706         toggle = !txn->mt_toggle;
1707         DPRINTF("writing meta page %d for root page %zu",
1708                 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1709
1710         env = txn->mt_env;
1711
1712         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1713         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1714
1715         ptr = (char *)&meta;
1716         off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1717         len = sizeof(MDB_meta) - off;
1718
1719         ptr += off;
1720         meta.mm_dbs[0] = txn->mt_dbs[0];
1721         meta.mm_dbs[1] = txn->mt_dbs[1];
1722         meta.mm_last_pg = txn->mt_next_pgno - 1;
1723         meta.mm_txnid = txn->mt_txnid;
1724
1725         if (toggle)
1726                 off += env->me_psize;
1727         off += PAGEHDRSZ;
1728
1729         /* Write to the SYNC fd */
1730 #ifdef _WIN32
1731         {
1732                 memset(&ov, 0, sizeof(ov));
1733                 ov.Offset = off;
1734                 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1735         }
1736 #else
1737         rc = pwrite(env->me_mfd, ptr, len, off);
1738 #endif
1739         if (rc != len) {
1740                 int r2;
1741                 rc = ErrCode();
1742                 DPUTS("write failed, disk error?");
1743                 /* On a failure, the pagecache still contains the new data.
1744                  * Write some old data back, to prevent it from being used.
1745                  * Use the non-SYNC fd; we know it will fail anyway.
1746                  */
1747                 meta.mm_last_pg = metab.mm_last_pg;
1748                 meta.mm_txnid = metab.mm_txnid;
1749 #ifdef _WIN32
1750                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1751 #else
1752                 r2 = pwrite(env->me_fd, ptr, len, off);
1753 #endif
1754                 env->me_flags |= MDB_FATAL_ERROR;
1755                 return rc;
1756         }
1757         /* Memory ordering issues are irrelevant; since the entire writer
1758          * is wrapped by wmutex, all of these changes will become visible
1759          * after the wmutex is unlocked. Since the DB is multi-version,
1760          * readers will get consistent data regardless of how fresh or
1761          * how stale their view of these values is.
1762          */
1763         LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1764         txn->mt_env->me_txns->mti_me_toggle = toggle;
1765         txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1766         LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1767
1768         return MDB_SUCCESS;
1769 }
1770
1771 /** Check both meta pages to see which one is newer.
1772  * @param[in] env the environment handle
1773  * @param[out] which address of where to store the meta toggle ID
1774  * @return 0 on success, non-zero on failure.
1775  */
1776 static int
1777 mdb_env_read_meta(MDB_env *env, int *which)
1778 {
1779         int toggle = 0;
1780
1781         assert(env != NULL);
1782
1783         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1784                 toggle = 1;
1785
1786         DPRINTF("Using meta page %d", toggle);
1787         *which = toggle;
1788
1789         return MDB_SUCCESS;
1790 }
1791
1792 int
1793 mdb_env_create(MDB_env **env)
1794 {
1795         MDB_env *e;
1796
1797         e = calloc(1, sizeof(MDB_env));
1798         if (!e) return ENOMEM;
1799
1800         e->me_maxreaders = DEFAULT_READERS;
1801         e->me_maxdbs = 2;
1802         e->me_fd = INVALID_HANDLE_VALUE;
1803         e->me_lfd = INVALID_HANDLE_VALUE;
1804         e->me_mfd = INVALID_HANDLE_VALUE;
1805         *env = e;
1806         return MDB_SUCCESS;
1807 }
1808
1809 int
1810 mdb_env_set_mapsize(MDB_env *env, size_t size)
1811 {
1812         if (env->me_map)
1813                 return EINVAL;
1814         env->me_mapsize = size;
1815         return MDB_SUCCESS;
1816 }
1817
1818 int
1819 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1820 {
1821         if (env->me_map)
1822                 return EINVAL;
1823         env->me_maxdbs = dbs;
1824         return MDB_SUCCESS;
1825 }
1826
1827 int
1828 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1829 {
1830         if (env->me_map || readers < 1)
1831                 return EINVAL;
1832         env->me_maxreaders = readers;
1833         return MDB_SUCCESS;
1834 }
1835
1836 int
1837 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1838 {
1839         if (!env || !readers)
1840                 return EINVAL;
1841         *readers = env->me_maxreaders;
1842         return MDB_SUCCESS;
1843 }
1844
1845 /** Further setup required for opening an MDB environment
1846  */
1847 static int
1848 mdb_env_open2(MDB_env *env, unsigned int flags)
1849 {
1850         int i, newenv = 0, toggle;
1851         MDB_meta meta;
1852         MDB_page *p;
1853
1854         env->me_flags = flags;
1855
1856         memset(&meta, 0, sizeof(meta));
1857
1858         if ((i = mdb_env_read_header(env, &meta)) != 0) {
1859                 if (i != ENOENT)
1860                         return i;
1861                 DPUTS("new mdbenv");
1862                 newenv = 1;
1863         }
1864
1865         if (!env->me_mapsize) {
1866                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1867         }
1868
1869 #ifdef _WIN32
1870         {
1871                 HANDLE mh;
1872                 LONG sizelo, sizehi;
1873                 sizelo = env->me_mapsize & 0xffffffff;
1874                 sizehi = env->me_mapsize >> 16;         /* pointless on WIN32, only needed on W64 */
1875                 sizehi >>= 16;
1876                 /* Windows won't create mappings for zero length files.
1877                  * Just allocate the maxsize right now.
1878                  */
1879                 if (newenv) {
1880                         SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1881                         if (!SetEndOfFile(env->me_fd))
1882                                 return ErrCode();
1883                         SetFilePointer(env->me_fd, 0, NULL, 0);
1884                 }
1885                 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1886                         sizehi, sizelo, NULL);
1887                 if (!mh)
1888                         return ErrCode();
1889                 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1890                         meta.mm_address);
1891                 CloseHandle(mh);
1892                 if (!env->me_map)
1893                         return ErrCode();
1894         }
1895 #else
1896         i = MAP_SHARED;
1897         if (meta.mm_address && (flags & MDB_FIXEDMAP))
1898                 i |= MAP_FIXED;
1899         env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1900                 env->me_fd, 0);
1901         if (env->me_map == MAP_FAILED)
1902                 return ErrCode();
1903 #endif
1904
1905         if (newenv) {
1906                 meta.mm_mapsize = env->me_mapsize;
1907                 if (flags & MDB_FIXEDMAP)
1908                         meta.mm_address = env->me_map;
1909                 i = mdb_env_init_meta(env, &meta);
1910                 if (i != MDB_SUCCESS) {
1911                         munmap(env->me_map, env->me_mapsize);
1912                         return i;
1913                 }
1914         }
1915         env->me_psize = meta.mm_psize;
1916
1917         env->me_maxpg = env->me_mapsize / env->me_psize;
1918
1919         p = (MDB_page *)env->me_map;
1920         env->me_metas[0] = METADATA(p);
1921         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1922
1923         if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1924                 return i;
1925
1926         DPRINTF("opened database version %u, pagesize %u",
1927             env->me_metas[toggle]->mm_version, env->me_psize);
1928         DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1929         DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1930         DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1931         DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1932         DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1933         DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1934
1935         return MDB_SUCCESS;
1936 }
1937
1938 #ifndef _WIN32
1939 /* Windows doesn't support destructor callbacks for thread-specific storage */
1940 static void
1941 mdb_env_reader_dest(void *ptr)
1942 {
1943         MDB_reader *reader = ptr;
1944
1945         reader->mr_txnid = 0;
1946         reader->mr_pid = 0;
1947         reader->mr_tid = 0;
1948 }
1949 #endif
1950
1951 /* downgrade the exclusive lock on the region back to shared */
1952 static void
1953 mdb_env_share_locks(MDB_env *env)
1954 {
1955         int toggle = 0;
1956
1957         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1958                 toggle = 1;
1959         env->me_txns->mti_me_toggle = toggle;
1960         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1961
1962 #ifdef _WIN32
1963         {
1964                 OVERLAPPED ov;
1965                 /* First acquire a shared lock. The Unlock will
1966                  * then release the existing exclusive lock.
1967                  */
1968                 memset(&ov, 0, sizeof(ov));
1969                 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1970                 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1971         }
1972 #else
1973         {
1974                 struct flock lock_info;
1975                 /* The shared lock replaces the existing lock */
1976                 memset((void *)&lock_info, 0, sizeof(lock_info));
1977                 lock_info.l_type = F_RDLCK;
1978                 lock_info.l_whence = SEEK_SET;
1979                 lock_info.l_start = 0;
1980                 lock_info.l_len = 1;
1981                 fcntl(env->me_lfd, F_SETLK, &lock_info);
1982         }
1983 #endif
1984 }
1985
1986 static int
1987 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1988 {
1989         int rc;
1990         off_t size, rsize;
1991
1992         *excl = 0;
1993
1994 #ifdef _WIN32
1995         if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1996                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1997                 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1998                 rc = ErrCode();
1999                 return rc;
2000         }
2001         /* Try to get exclusive lock. If we succeed, then
2002          * nobody is using the lock region and we should initialize it.
2003          */
2004         {
2005                 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2006                         *excl = 1;
2007                 } else {
2008                         OVERLAPPED ov;
2009                         memset(&ov, 0, sizeof(ov));
2010                         if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2011                                 rc = ErrCode();
2012                                 goto fail;
2013                         }
2014                 }
2015         }
2016         size = GetFileSize(env->me_lfd, NULL);
2017 #else
2018         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2019                 rc = ErrCode();
2020                 return rc;
2021         }
2022         /* Try to get exclusive lock. If we succeed, then
2023          * nobody is using the lock region and we should initialize it.
2024          */
2025         {
2026                 struct flock lock_info;
2027                 memset((void *)&lock_info, 0, sizeof(lock_info));
2028                 lock_info.l_type = F_WRLCK;
2029                 lock_info.l_whence = SEEK_SET;
2030                 lock_info.l_start = 0;
2031                 lock_info.l_len = 1;
2032                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2033                 if (rc == 0) {
2034                         *excl = 1;
2035                 } else {
2036                         lock_info.l_type = F_RDLCK;
2037                         rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2038                         if (rc) {
2039                                 rc = ErrCode();
2040                                 goto fail;
2041                         }
2042                 }
2043         }
2044         size = lseek(env->me_lfd, 0, SEEK_END);
2045 #endif
2046         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2047         if (size < rsize && *excl) {
2048 #ifdef _WIN32
2049                 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2050                 if (!SetEndOfFile(env->me_lfd)) {
2051                         rc = ErrCode();
2052                         goto fail;
2053                 }
2054 #else
2055                 if (ftruncate(env->me_lfd, rsize) != 0) {
2056                         rc = ErrCode();
2057                         goto fail;
2058                 }
2059 #endif
2060         } else {
2061                 rsize = size;
2062                 size = rsize - sizeof(MDB_txninfo);
2063                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2064         }
2065 #ifdef _WIN32
2066         {
2067                 HANDLE mh;
2068                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2069                         0, 0, NULL);
2070                 if (!mh) {
2071                         rc = ErrCode();
2072                         goto fail;
2073                 }
2074                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2075                 CloseHandle(mh);
2076                 if (!env->me_txns) {
2077                         rc = ErrCode();
2078                         goto fail;
2079                 }
2080         }
2081 #else
2082         env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2083                 env->me_lfd, 0);
2084         if (env->me_txns == MAP_FAILED) {
2085                 rc = ErrCode();
2086                 goto fail;
2087         }
2088 #endif
2089         if (*excl) {
2090 #ifdef _WIN32
2091                 char *ptr;
2092                 if (!mdb_sec_inited) {
2093                         InitializeSecurityDescriptor(&mdb_null_sd,
2094                                 SECURITY_DESCRIPTOR_REVISION);
2095                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2096                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2097                         mdb_all_sa.bInheritHandle = FALSE;
2098                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2099                         mdb_sec_inited = 1;
2100                 }
2101                 /* FIXME: only using up to 20 characters of the env path here,
2102                  * probably not enough to assure uniqueness...
2103                  */
2104                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
2105                 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
2106                 while ((ptr = strchr(ptr, '\\')))
2107                         *ptr++ = '/';
2108                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2109                 if (!env->me_rmutex) {
2110                         rc = ErrCode();
2111                         goto fail;
2112                 }
2113                 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
2114                 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
2115                 while ((ptr = strchr(ptr, '\\')))
2116                         *ptr++ = '/';
2117                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2118                 if (!env->me_wmutex) {
2119                         rc = ErrCode();
2120                         goto fail;
2121                 }
2122 #else
2123                 pthread_mutexattr_t mattr;
2124
2125                 pthread_mutexattr_init(&mattr);
2126                 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2127                 if (rc) {
2128                         goto fail;
2129                 }
2130                 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2131                 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2132 #endif
2133                 env->me_txns->mti_version = MDB_VERSION;
2134                 env->me_txns->mti_magic = MDB_MAGIC;
2135                 env->me_txns->mti_txnid = 0;
2136                 env->me_txns->mti_numreaders = 0;
2137                 env->me_txns->mti_me_toggle = 0;
2138
2139         } else {
2140                 if (env->me_txns->mti_magic != MDB_MAGIC) {
2141                         DPUTS("lock region has invalid magic");
2142                         rc = EINVAL;
2143                         goto fail;
2144                 }
2145                 if (env->me_txns->mti_version != MDB_VERSION) {
2146                         DPRINTF("lock region is version %u, expected version %u",
2147                                 env->me_txns->mti_version, MDB_VERSION);
2148                         rc = MDB_VERSION_MISMATCH;
2149                         goto fail;
2150                 }
2151                 rc = ErrCode();
2152                 if (rc != EACCES && rc != EAGAIN) {
2153                         goto fail;
2154                 }
2155 #ifdef _WIN32
2156                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2157                 if (!env->me_rmutex) {
2158                         rc = ErrCode();
2159                         goto fail;
2160                 }
2161                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2162                 if (!env->me_wmutex) {
2163                         rc = ErrCode();
2164                         goto fail;
2165                 }
2166 #endif
2167         }
2168         return MDB_SUCCESS;
2169
2170 fail:
2171         close(env->me_lfd);
2172         env->me_lfd = INVALID_HANDLE_VALUE;
2173         return rc;
2174
2175 }
2176
2177         /** The name of the lock file in the DB environment */
2178 #define LOCKNAME        "/lock.mdb"
2179         /** The name of the data file in the DB environment */
2180 #define DATANAME        "/data.mdb"
2181 int
2182 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2183 {
2184         int             oflags, rc, len, excl;
2185         char *lpath, *dpath;
2186
2187         len = strlen(path);
2188         lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2189         if (!lpath)
2190                 return ENOMEM;
2191         dpath = lpath + len + sizeof(LOCKNAME);
2192         sprintf(lpath, "%s" LOCKNAME, path);
2193         sprintf(dpath, "%s" DATANAME, path);
2194
2195         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2196         if (rc)
2197                 goto leave;
2198
2199 #ifdef _WIN32
2200         if (F_ISSET(flags, MDB_RDONLY)) {
2201                 oflags = GENERIC_READ;
2202                 len = OPEN_EXISTING;
2203         } else {
2204                 oflags = GENERIC_READ|GENERIC_WRITE;
2205                 len = OPEN_ALWAYS;
2206         }
2207         mode = FILE_ATTRIBUTE_NORMAL;
2208         if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2209                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2210                 rc = ErrCode();
2211                 goto leave;
2212         }
2213 #else
2214         if (F_ISSET(flags, MDB_RDONLY))
2215                 oflags = O_RDONLY;
2216         else
2217                 oflags = O_RDWR | O_CREAT;
2218
2219         if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2220                 rc = ErrCode();
2221                 goto leave;
2222         }
2223 #endif
2224
2225         if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2226                 /* synchronous fd for meta writes */
2227 #ifdef _WIN32
2228                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2229                         mode |= FILE_FLAG_WRITE_THROUGH;
2230                 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2231                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2232                         rc = ErrCode();
2233                         goto leave;
2234                 }
2235 #else
2236                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2237                         oflags |= MDB_DSYNC;
2238                 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2239                         rc = ErrCode();
2240                         goto leave;
2241                 }
2242 #endif
2243                 env->me_path = strdup(path);
2244                 DPRINTF("opened dbenv %p", (void *) env);
2245                 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2246                 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2247                 if (excl)
2248                         mdb_env_share_locks(env);
2249                 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2250                 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2251                 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2252                 env->me_numdbs = 2;
2253         }
2254
2255 leave:
2256         if (rc) {
2257                 if (env->me_fd != INVALID_HANDLE_VALUE) {
2258                         close(env->me_fd);
2259                         env->me_fd = INVALID_HANDLE_VALUE;
2260                 }
2261                 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2262                         close(env->me_lfd);
2263                         env->me_lfd = INVALID_HANDLE_VALUE;
2264                 }
2265         }
2266         free(lpath);
2267         return rc;
2268 }
2269
2270 void
2271 mdb_env_close(MDB_env *env)
2272 {
2273         MDB_page *dp;
2274
2275         if (env == NULL)
2276                 return;
2277
2278         while (env->me_dpages) {
2279                 dp = env->me_dpages;
2280                 env->me_dpages = dp->mp_next;
2281                 free(dp);
2282         }
2283
2284         free(env->me_dbs[1]);
2285         free(env->me_dbs[0]);
2286         free(env->me_dbxs);
2287         free(env->me_path);
2288
2289         LAZY_RWLOCK_DESTROY(&env->me_dblock);
2290         pthread_key_delete(env->me_txkey);
2291
2292         if (env->me_map) {
2293                 munmap(env->me_map, env->me_mapsize);
2294         }
2295         close(env->me_mfd);
2296         close(env->me_fd);
2297         if (env->me_txns) {
2298                 pid_t pid = getpid();
2299                 unsigned int i;
2300                 for (i=0; i<env->me_txns->mti_numreaders; i++)
2301                         if (env->me_txns->mti_readers[i].mr_pid == pid)
2302                                 env->me_txns->mti_readers[i].mr_pid = 0;
2303                 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2304         }
2305         close(env->me_lfd);
2306         free(env);
2307 }
2308
2309 /* only for aligned ints */
2310 static int
2311 intcmp(const MDB_val *a, const MDB_val *b)
2312 {
2313         if (a->mv_size == sizeof(long))
2314         {
2315                 unsigned long *la, *lb;
2316                 la = a->mv_data;
2317                 lb = b->mv_data;
2318                 return *la - *lb;
2319         } else {
2320                 unsigned int *ia, *ib;
2321                 ia = a->mv_data;
2322                 ib = b->mv_data;
2323                 return *ia - *ib;
2324         }
2325 }
2326
2327 /* ints must always be the same size */
2328 static int
2329 cintcmp(const MDB_val *a, const MDB_val *b)
2330 {
2331 #if __BYTE_ORDER == __LITTLE_ENDIAN
2332         unsigned short *u, *c;
2333         int x;
2334
2335         u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2336         c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2337         do {
2338                 x = *--u - *--c;
2339         } while(!x && u > (unsigned short *)a->mv_data);
2340         return x;
2341 #else
2342         return memcmp(a->mv_data, b->mv_data, a->mv_size);
2343 #endif
2344 }
2345
2346 static int
2347 memncmp(const MDB_val *a, const MDB_val *b)
2348 {
2349         int diff;
2350         ssize_t len_diff;
2351         unsigned int len;
2352
2353         len = a->mv_size;
2354         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2355         if (len_diff > 0) {
2356                 len = b->mv_size;
2357                 len_diff = 1;
2358         }
2359
2360         diff = memcmp(a->mv_data, b->mv_data, len);
2361         return diff ? diff : len_diff<0 ? -1 : len_diff;
2362 }
2363
2364 static int
2365 memnrcmp(const MDB_val *a, const MDB_val *b)
2366 {
2367         const unsigned char     *p1, *p2, *p1_lim;
2368         ssize_t len_diff;
2369         int diff;
2370
2371         p1_lim = (const unsigned char *)a->mv_data;
2372         p1 = (const unsigned char *)a->mv_data + a->mv_size;
2373         p2 = (const unsigned char *)b->mv_data + b->mv_size;
2374
2375         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2376         if (len_diff > 0) {
2377                 p1_lim += len_diff;
2378                 len_diff = 1;
2379         }
2380
2381         while (p1 > p1_lim) {
2382                 diff = *--p1 - *--p2;
2383                 if (diff)
2384                         return diff;
2385         }
2386         return len_diff<0 ? -1 : len_diff;
2387 }
2388
2389 /* Search for key within a leaf page, using binary search.
2390  * Returns the smallest entry larger or equal to the key.
2391  * If exactp is non-null, stores whether the found entry was an exact match
2392  * in *exactp (1 or 0).
2393  * If kip is non-null, stores the index of the found entry in *kip.
2394  * If no entry larger or equal to the key is found, returns NULL.
2395  */
2396 static MDB_node *
2397 mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp)
2398 {
2399         unsigned int     i = 0, nkeys;
2400         int              low, high;
2401         int              rc = 0;
2402         MDB_page *mp = mc->mc_pg[mc->mc_top];
2403         MDB_node        *node = NULL;
2404         MDB_val  nodekey;
2405         MDB_cmp_func *cmp;
2406         DKBUF;
2407
2408         nkeys = NUMKEYS(mp);
2409
2410         DPRINTF("searching %u keys in %s page %zu",
2411             nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2412             mp->mp_pgno);
2413
2414         assert(nkeys > 0);
2415
2416         low = IS_LEAF(mp) ? 0 : 1;
2417         high = nkeys - 1;
2418         cmp = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp;
2419         if (IS_LEAF2(mp)) {
2420                 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2421                 node = NODEPTR(mp, 0);  /* fake */
2422         }
2423         while (low <= high) {
2424                 i = (low + high) >> 1;
2425
2426                 if (IS_LEAF2(mp)) {
2427                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2428                 } else {
2429                         node = NODEPTR(mp, i);
2430
2431                         nodekey.mv_size = node->mn_ksize;
2432                         nodekey.mv_data = NODEKEY(node);
2433                 }
2434
2435                 rc = cmp(key, &nodekey);
2436
2437 #if DEBUG
2438                 if (IS_LEAF(mp))
2439                         DPRINTF("found leaf index %u [%s], rc = %i",
2440                             i, DKEY(&nodekey), rc);
2441                 else
2442                         DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2443                             i, DKEY(&nodekey), NODEPGNO(node), rc);
2444 #endif
2445
2446                 if (rc == 0)
2447                         break;
2448                 if (rc > 0)
2449                         low = i + 1;
2450                 else
2451                         high = i - 1;
2452         }
2453
2454         if (rc > 0) {   /* Found entry is less than the key. */
2455                 i++;    /* Skip to get the smallest entry larger than key. */
2456                 if (!IS_LEAF2(mp))
2457                         node = NODEPTR(mp, i);
2458         }
2459         if (exactp)
2460                 *exactp = (rc == 0);
2461         /* store the key index */
2462         mc->mc_ki[mc->mc_top] = i;
2463         if (i >= nkeys)
2464                 /* There is no entry larger or equal to the key. */
2465                 return NULL;
2466
2467         /* nodeptr is fake for LEAF2 */
2468         return node;
2469 }
2470
2471 static void
2472 cursor_pop_page(MDB_cursor *mc)
2473 {
2474         MDB_page        *top;
2475
2476         if (mc->mc_snum) {
2477                 top = mc->mc_pg[mc->mc_top];
2478                 mc->mc_snum--;
2479                 if (mc->mc_snum)
2480                         mc->mc_top--;
2481
2482                 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2483                         mc->mc_dbi, (void *) mc);
2484         }
2485 }
2486
2487 static int
2488 cursor_push_page(MDB_cursor *mc, MDB_page *mp)
2489 {
2490         DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2491                 mc->mc_dbi, (void *) mc);
2492
2493         if (mc->mc_snum >= CURSOR_STACK)
2494                 return ENOMEM;
2495
2496         mc->mc_top = mc->mc_snum++;
2497         mc->mc_pg[mc->mc_top] = mp;
2498         mc->mc_ki[mc->mc_top] = 0;
2499
2500         return MDB_SUCCESS;
2501 }
2502
2503 static int
2504 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2505 {
2506         MDB_page *p = NULL;
2507
2508         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2509                 unsigned x;
2510                 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2511                 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2512                         p = txn->mt_u.dirty_list[x].mptr;
2513                 }
2514         }
2515         if (!p) {
2516                 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2517                         p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2518         }
2519         *ret = p;
2520         if (!p) {
2521                 DPRINTF("page %zu not found", pgno);
2522                 assert(p != NULL);
2523         }
2524         return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2525 }
2526
2527 static int
2528 mdb_search_page_root(MDB_cursor *mc, MDB_val *key, int modify)
2529 {
2530         MDB_page        *mp = mc->mc_pg[mc->mc_top];
2531         DKBUF;
2532         int rc;
2533
2534
2535         while (IS_BRANCH(mp)) {
2536                 MDB_node        *node;
2537
2538                 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2539                 assert(NUMKEYS(mp) > 1);
2540                 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2541
2542                 if (key == NULL)        /* Initialize cursor to first page. */
2543                         mc->mc_ki[mc->mc_top] = 0;
2544                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2545                                                         /* cursor to last page */
2546                         mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
2547                 } else {
2548                         int      exact;
2549                         node = mdb_search_node(mc, key, &exact);
2550                         if (node == NULL)
2551                                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2552                         else if (!exact) {
2553                                 assert(mc->mc_ki[mc->mc_top] > 0);
2554                                 mc->mc_ki[mc->mc_top]--;
2555                         }
2556                 }
2557
2558                 if (key)
2559                         DPRINTF("following index %u for key [%s]",
2560                             mc->mc_ki[mc->mc_top], DKEY(key));
2561                 assert(mc->mc_ki[mc->mc_top] < NUMKEYS(mp));
2562                 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2563
2564                 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mp)))
2565                         return rc;
2566
2567                 if ((rc = cursor_push_page(mc, mp)))
2568                         return rc;
2569
2570                 if (modify) {
2571                         if ((rc = mdb_touch(mc)) != 0)
2572                                 return rc;
2573                         mp = mc->mc_pg[mc->mc_top];
2574                 }
2575         }
2576
2577         if (!IS_LEAF(mp)) {
2578                 DPRINTF("internal error, index points to a %02X page!?",
2579                     mp->mp_flags);
2580                 return MDB_CORRUPTED;
2581         }
2582
2583         DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2584             key ? DKEY(key) : NULL);
2585
2586         return MDB_SUCCESS;
2587 }
2588
2589 /* Search for the page a given key should be in.
2590  * Pushes parent pages on the cursor stack.
2591  * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2592  * If modify is true, visited pages are updated with new page numbers.
2593  */
2594 static int
2595 mdb_search_page(MDB_cursor *mc, MDB_val *key, int modify)
2596 {
2597         int              rc;
2598         pgno_t           root;
2599
2600         /* Make sure the txn is still viable, then find the root from
2601          * the txn's db table.
2602          */
2603         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2604                 DPUTS("transaction has failed, must abort");
2605                 return EINVAL;
2606         } else
2607                 root = mc->mc_txn->mt_dbs[mc->mc_dbi].md_root;
2608
2609         if (root == P_INVALID) {                /* Tree is empty. */
2610                 DPUTS("tree is empty");
2611                 return MDB_NOTFOUND;
2612         }
2613
2614         if ((rc = mdb_get_page(mc->mc_txn, root, &mc->mc_pg[0])))
2615                 return rc;
2616
2617         mc->mc_snum = 1;
2618         mc->mc_top = 0;
2619
2620         DPRINTF("db %u root page %zu has flags 0x%X",
2621                 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2622
2623         if (modify) {
2624                 /* For sub-databases, update main root first */
2625                 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2626                         MDB_cursor mc2;
2627                         mc2.mc_txn = mc->mc_txn;
2628                         mc2.mc_dbi = MAIN_DBI;
2629                         rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
2630                         if (rc)
2631                                 return rc;
2632                         mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2633                 }
2634                 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2635                         if ((rc = mdb_touch(mc)))
2636                                 return rc;
2637                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mc->mc_pg[0]->mp_pgno;
2638                 }
2639         }
2640
2641         return mdb_search_page_root(mc, key, modify);
2642 }
2643
2644 static int
2645 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2646 {
2647         MDB_page        *omp;           /* overflow mpage */
2648         pgno_t           pgno;
2649         int rc;
2650
2651         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2652                 data->mv_size = NODEDSZ(leaf);
2653                 data->mv_data = NODEDATA(leaf);
2654                 return MDB_SUCCESS;
2655         }
2656
2657         /* Read overflow data.
2658          */
2659         data->mv_size = NODEDSZ(leaf);
2660         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2661         if ((rc = mdb_get_page(txn, pgno, &omp))) {
2662                 DPRINTF("read overflow page %zu failed", pgno);
2663                 return rc;
2664         }
2665         data->mv_data = METADATA(omp);
2666
2667         return MDB_SUCCESS;
2668 }
2669
2670 int
2671 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2672     MDB_val *key, MDB_val *data)
2673 {
2674         MDB_cursor      mc;
2675         MDB_xcursor     mx;
2676         int exact = 0;
2677         DKBUF;
2678
2679         assert(key);
2680         assert(data);
2681         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2682
2683         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2684                 return EINVAL;
2685
2686         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2687                 return EINVAL;
2688         }
2689
2690         mc.mc_txn = txn;
2691         mc.mc_dbi = dbi;
2692         mc.mc_flags = 0;
2693         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2694                 mc.mc_xcursor = &mx;
2695                 mdb_xcursor_init0(&mc);
2696         } else {
2697                 mc.mc_xcursor = NULL;
2698         }
2699         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2700 }
2701
2702 static int
2703 mdb_sibling(MDB_cursor *mc, int move_right)
2704 {
2705         int              rc;
2706         unsigned int    ptop;
2707         MDB_node        *indx;
2708         MDB_page        *mp;
2709
2710         if (mc->mc_snum < 2) {
2711                 return MDB_NOTFOUND;            /* root has no siblings */
2712         }
2713         ptop = mc->mc_top-1;
2714
2715         DPRINTF("parent page is page %zu, index %u",
2716                 mc->mc_pg[ptop]->mp_pgno, mc->mc_ki[ptop]);
2717
2718         cursor_pop_page(mc);
2719         if (move_right ? (mc->mc_ki[ptop] + 1u >= NUMKEYS(mc->mc_pg[ptop]))
2720                        : (mc->mc_ki[ptop] == 0)) {
2721                 DPRINTF("no more keys left, moving to %s sibling",
2722                     move_right ? "right" : "left");
2723                 if ((rc = mdb_sibling(mc, move_right)) != MDB_SUCCESS)
2724                         return rc;
2725         } else {
2726                 if (move_right)
2727                         mc->mc_ki[ptop]++;
2728                 else
2729                         mc->mc_ki[ptop]--;
2730                 DPRINTF("just moving to %s index key %u",
2731                     move_right ? "right" : "left", mc->mc_ki[ptop]);
2732         }
2733         assert(IS_BRANCH(mc->mc_pg[ptop]));
2734
2735         indx = NODEPTR(mc->mc_pg[ptop], mc->mc_ki[ptop]);
2736         if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(indx), &mp)))
2737                 return rc;;
2738
2739         cursor_push_page(mc, mp);
2740
2741         return MDB_SUCCESS;
2742 }
2743
2744 static int
2745 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2746 {
2747         MDB_page        *mp;
2748         MDB_node        *leaf;
2749         int rc;
2750
2751         if (mc->mc_flags & C_EOF) {
2752                 return MDB_NOTFOUND;
2753         }
2754
2755         assert(mc->mc_flags & C_INITIALIZED);
2756
2757         mp = mc->mc_pg[mc->mc_top];
2758
2759         if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2760                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2761                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2762                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2763                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2764                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2765                                         return rc;
2766                         }
2767                 } else {
2768                         mc->mc_xcursor->mx_cursor.mc_flags = 0;
2769                         if (op == MDB_NEXT_DUP)
2770                                 return MDB_NOTFOUND;
2771                 }
2772         }
2773
2774         DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2775
2776         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2777                 DPUTS("=====> move to next sibling page");
2778                 if (mdb_sibling(mc, 1) != MDB_SUCCESS) {
2779                         mc->mc_flags |= C_EOF;
2780                         return MDB_NOTFOUND;
2781                 }
2782                 mp = mc->mc_pg[mc->mc_top];
2783                 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2784         } else
2785                 mc->mc_ki[mc->mc_top]++;
2786
2787         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2788             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2789
2790         if (IS_LEAF2(mp)) {
2791                 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2792                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2793                 return MDB_SUCCESS;
2794         }
2795
2796         assert(IS_LEAF(mp));
2797         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2798
2799         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2800                 mdb_xcursor_init1(mc, leaf);
2801         }
2802         if (data) {
2803                 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2804                         return rc;
2805
2806                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2807                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2808                         if (rc != MDB_SUCCESS)
2809                                 return rc;
2810                 }
2811         }
2812
2813         MDB_SET_KEY(leaf, key);
2814         return MDB_SUCCESS;
2815 }
2816
2817 static int
2818 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2819 {
2820         MDB_page        *mp;
2821         MDB_node        *leaf;
2822         int rc;
2823
2824         assert(mc->mc_flags & C_INITIALIZED);
2825
2826         mp = mc->mc_pg[mc->mc_top];
2827
2828         if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2829                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2830                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2831                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2832                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2833                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
2834                                         return rc;
2835                         } else {
2836                                 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2837                                 if (op == MDB_PREV_DUP)
2838                                         return MDB_NOTFOUND;
2839                         }
2840                 }
2841         }
2842
2843         DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2844
2845         if (mc->mc_ki[mc->mc_top] == 0)  {
2846                 DPUTS("=====> move to prev sibling page");
2847                 if (mdb_sibling(mc, 0) != MDB_SUCCESS) {
2848                         mc->mc_flags &= ~C_INITIALIZED;
2849                         return MDB_NOTFOUND;
2850                 }
2851                 mp = mc->mc_pg[mc->mc_top];
2852                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2853                 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2854         } else
2855                 mc->mc_ki[mc->mc_top]--;
2856
2857         mc->mc_flags &= ~C_EOF;
2858
2859         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2860             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2861
2862         if (IS_LEAF2(mp)) {
2863                 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2864                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2865                 return MDB_SUCCESS;
2866         }
2867
2868         assert(IS_LEAF(mp));
2869         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2870
2871         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2872                 mdb_xcursor_init1(mc, leaf);
2873         }
2874         if (data) {
2875                 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2876                         return rc;
2877
2878                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2879                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
2880                         if (rc != MDB_SUCCESS)
2881                                 return rc;
2882                 }
2883         }
2884
2885         MDB_SET_KEY(leaf, key);
2886         return MDB_SUCCESS;
2887 }
2888
2889 static int
2890 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2891     MDB_cursor_op op, int *exactp)
2892 {
2893         int              rc;
2894         MDB_node        *leaf;
2895         DKBUF;
2896
2897         assert(mc);
2898         assert(key);
2899         assert(key->mv_size > 0);
2900
2901         /* See if we're already on the right page */
2902         if (mc->mc_flags & C_INITIALIZED) {
2903                 MDB_val nodekey;
2904
2905                 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2906                         nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2907                         nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, nodekey.mv_size);
2908                 } else {
2909                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2910                         MDB_SET_KEY(leaf, &nodekey);
2911                 }
2912                 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2913                 if (rc == 0) {
2914                         /* Probably happens rarely, but first node on the page
2915                          * was the one we wanted.
2916                          */
2917                         mc->mc_ki[mc->mc_top] = 0;
2918 set1:
2919                         if (exactp)
2920                                 *exactp = 1;
2921                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2922                         goto set3;
2923                 }
2924                 if (rc > 0) {
2925                         unsigned int i;
2926                         if (NUMKEYS(mc->mc_pg[mc->mc_top]) > 1) {
2927                                 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2928                                         nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top],
2929                                                  NUMKEYS(mc->mc_pg[mc->mc_top])-1, nodekey.mv_size);
2930                                 } else {
2931                                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
2932                                         MDB_SET_KEY(leaf, &nodekey);
2933                                 }
2934                                 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2935                                 if (rc == 0) {
2936                                         /* last node was the one we wanted */
2937                                         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top])-1;
2938                                         goto set1;
2939                                 }
2940                                 if (rc < 0) {
2941                                         /* This is definitely the right page, skip search_page */
2942                                         rc = 0;
2943                                         goto set2;
2944                                 }
2945                         }
2946                         /* If any parents have right-sibs, search.
2947                          * Otherwise, there's nothing further.
2948                          */
2949                         for (i=0; i<mc->mc_top; i++)
2950                                 if (mc->mc_ki[i] <
2951                                         NUMKEYS(mc->mc_pg[i])-1)
2952                                         break;
2953                         if (i == mc->mc_top) {
2954                                 /* There are no other pages */
2955                                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
2956                                 return MDB_NOTFOUND;
2957                         }
2958                 }
2959         }
2960
2961         rc = mdb_search_page(mc, key, 0);
2962         if (rc != MDB_SUCCESS)
2963                 return rc;
2964
2965         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2966
2967 set2:
2968         leaf = mdb_search_node(mc, key, exactp);
2969         if (exactp != NULL && !*exactp) {
2970                 /* MDB_SET specified and not an exact match. */
2971                 return MDB_NOTFOUND;
2972         }
2973
2974         if (leaf == NULL) {
2975                 DPUTS("===> inexact leaf not found, goto sibling");
2976                 if ((rc = mdb_sibling(mc, 1)) != MDB_SUCCESS)
2977                         return rc;              /* no entries matched */
2978                 mc->mc_ki[mc->mc_top] = 0;
2979                 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2980                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2981         }
2982
2983 set3:
2984         mc->mc_flags |= C_INITIALIZED;
2985         mc->mc_flags &= ~C_EOF;
2986
2987         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
2988                 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2989                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
2990                 return MDB_SUCCESS;
2991         }
2992
2993         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2994                 mdb_xcursor_init1(mc, leaf);
2995         }
2996         if (data) {
2997                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2998                         if (op == MDB_SET || op == MDB_SET_RANGE) {
2999                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3000                         } else {
3001                                 int ex2, *ex2p;
3002                                 if (op == MDB_GET_BOTH) {
3003                                         ex2p = &ex2;
3004                                         ex2 = 0;
3005                                 } else {
3006                                         ex2p = NULL;
3007                                 }
3008                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3009                                 if (rc != MDB_SUCCESS)
3010                                         return rc;
3011                         }
3012                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3013                         MDB_val d2;
3014                         if ((rc = mdb_read_data(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3015                                 return rc;
3016                         rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dcmp(data, &d2);
3017                         if (rc) {
3018                                 if (op == MDB_GET_BOTH || rc > 0)
3019                                         return MDB_NOTFOUND;
3020                         }
3021
3022                 } else {
3023                         if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3024                                 return rc;
3025                 }
3026         }
3027
3028         /* The key already matches in all other cases */
3029         if (op == MDB_SET_RANGE)
3030                 MDB_SET_KEY(leaf, key);
3031         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3032
3033         return rc;
3034 }
3035
3036 static int
3037 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3038 {
3039         int              rc;
3040         MDB_node        *leaf;
3041
3042         rc = mdb_search_page(mc, NULL, 0);
3043         if (rc != MDB_SUCCESS)
3044                 return rc;
3045         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3046
3047         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3048         mc->mc_flags |= C_INITIALIZED;
3049         mc->mc_flags &= ~C_EOF;
3050
3051         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3052                 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3053                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3054                 return MDB_SUCCESS;
3055         }
3056
3057         if (data) {
3058                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3059                         mdb_xcursor_init1(mc, leaf);
3060                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3061                         if (rc)
3062                                 return rc;
3063                 } else {
3064                         if (mc->mc_xcursor)
3065                                 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3066                         if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3067                                 return rc;
3068                 }
3069         }
3070         MDB_SET_KEY(leaf, key);
3071         return MDB_SUCCESS;
3072 }
3073
3074 static int
3075 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3076 {
3077         int              rc;
3078         MDB_node        *leaf;
3079         MDB_val lkey;
3080
3081         lkey.mv_size = MAXKEYSIZE+1;
3082         lkey.mv_data = NULL;
3083
3084         rc = mdb_search_page(mc, &lkey, 0);
3085         if (rc != MDB_SUCCESS)
3086                 return rc;
3087         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3088
3089         leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3090         mc->mc_flags |= C_INITIALIZED;
3091         mc->mc_flags &= ~C_EOF;
3092
3093         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3094
3095         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3096                 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3097                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3098                 return MDB_SUCCESS;
3099         }
3100
3101         if (data) {
3102                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3103                         mdb_xcursor_init1(mc, leaf);
3104                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3105                         if (rc)
3106                                 return rc;
3107                 } else {
3108                         if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3109                                 return rc;
3110                 }
3111         }
3112
3113         MDB_SET_KEY(leaf, key);
3114         return MDB_SUCCESS;
3115 }
3116
3117 int
3118 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3119     MDB_cursor_op op)
3120 {
3121         int              rc;
3122         int              exact = 0;
3123
3124         assert(mc);
3125
3126         switch (op) {
3127         case MDB_GET_BOTH:
3128         case MDB_GET_BOTH_RANGE:
3129                 if (data == NULL || mc->mc_xcursor == NULL) {
3130                         rc = EINVAL;
3131                         break;
3132                 }
3133                 /* FALLTHRU */
3134         case MDB_SET:
3135         case MDB_SET_RANGE:
3136                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3137                         rc = EINVAL;
3138                 } else if (op == MDB_SET_RANGE)
3139                         rc = mdb_cursor_set(mc, key, data, op, NULL);
3140                 else
3141                         rc = mdb_cursor_set(mc, key, data, op, &exact);
3142                 break;
3143         case MDB_GET_MULTIPLE:
3144                 if (data == NULL ||
3145                         !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) ||
3146                         !(mc->mc_flags & C_INITIALIZED)) {
3147                         rc = EINVAL;
3148                         break;
3149                 }
3150                 rc = MDB_SUCCESS;
3151                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3152                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3153                         break;
3154                 goto fetchm;
3155         case MDB_NEXT_MULTIPLE:
3156                 if (data == NULL ||
3157                         !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED)) {
3158                         rc = EINVAL;
3159                         break;
3160                 }
3161                 if (!(mc->mc_flags & C_INITIALIZED))
3162                         rc = mdb_cursor_first(mc, key, data);
3163                 else
3164                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3165                 if (rc == MDB_SUCCESS) {
3166                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3167                                 MDB_cursor *mx;
3168 fetchm:
3169                                 mx = &mc->mc_xcursor->mx_cursor;
3170                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3171                                         mx->mc_txn->mt_dbs[mx->mc_dbi].md_pad;
3172                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3173                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3174                         } else {
3175                                 rc = MDB_NOTFOUND;
3176                         }
3177                 }
3178                 break;
3179         case MDB_NEXT:
3180         case MDB_NEXT_DUP:
3181         case MDB_NEXT_NODUP:
3182                 if (!(mc->mc_flags & C_INITIALIZED))
3183                         rc = mdb_cursor_first(mc, key, data);
3184                 else
3185                         rc = mdb_cursor_next(mc, key, data, op);
3186                 break;
3187         case MDB_PREV:
3188         case MDB_PREV_DUP:
3189         case MDB_PREV_NODUP:
3190                 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3191                         rc = mdb_cursor_last(mc, key, data);
3192                 else
3193                         rc = mdb_cursor_prev(mc, key, data, op);
3194                 break;
3195         case MDB_FIRST:
3196                 rc = mdb_cursor_first(mc, key, data);
3197                 break;
3198         case MDB_FIRST_DUP:
3199                 if (data == NULL ||
3200                         !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3201                         !(mc->mc_flags & C_INITIALIZED) ||
3202                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3203                         rc = EINVAL;
3204                         break;
3205                 }
3206                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3207                 break;
3208         case MDB_LAST:
3209                 rc = mdb_cursor_last(mc, key, data);
3210                 break;
3211         case MDB_LAST_DUP:
3212                 if (data == NULL ||
3213                         !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3214                         !(mc->mc_flags & C_INITIALIZED) ||
3215                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3216                         rc = EINVAL;
3217                         break;
3218                 }
3219                 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3220                 break;
3221         default:
3222                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3223                 rc = EINVAL;
3224                 break;
3225         }
3226
3227         return rc;
3228 }
3229
3230 static int
3231 mdb_cursor_touch(MDB_cursor *mc)
3232 {
3233         int rc;
3234
3235         if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
3236                 MDB_cursor mc2;
3237                 mc2.mc_txn = mc->mc_txn;
3238                 mc2.mc_dbi = MAIN_DBI;
3239                 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
3240                 if (rc) return rc;
3241                 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3242         }
3243         for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3244                 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3245                         rc = mdb_touch(mc);
3246                         if (rc) return rc;
3247                         if (!mc->mc_top) {
3248                                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root =
3249                                         mc->mc_pg[mc->mc_top]->mp_pgno;
3250                         }
3251                 }
3252         }
3253         mc->mc_top = mc->mc_snum-1;
3254         return MDB_SUCCESS;
3255 }
3256
3257 int
3258 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3259     unsigned int flags)
3260 {
3261         MDB_node        *leaf;
3262         MDB_val xdata, *rdata, dkey;
3263         MDB_db dummy;
3264         char dbuf[PAGESIZE];
3265         int do_sub = 0;
3266         size_t nsize;
3267         DKBUF;
3268         int rc, rc2;
3269
3270         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3271                 return EACCES;
3272
3273         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3274                 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3275
3276         dkey.mv_size = 0;
3277
3278         if (flags == MDB_CURRENT) {
3279                 if (!(mc->mc_flags & C_INITIALIZED))
3280                         return EINVAL;
3281                 rc = MDB_SUCCESS;
3282         } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
3283                 MDB_page *np;
3284                 /* new database, write a root leaf page */
3285                 DPUTS("allocating new root leaf page");
3286                 if ((np = mdb_new_page(mc, P_LEAF, 1)) == NULL) {
3287                         return ENOMEM;
3288                 }
3289                 mc->mc_snum = 0;
3290                 cursor_push_page(mc, np);
3291                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = np->mp_pgno;
3292                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
3293                 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3294                 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3295                         == MDB_DUPFIXED)
3296                         np->mp_flags |= P_LEAF2;
3297                 mc->mc_flags |= C_INITIALIZED;
3298                 rc = MDB_NOTFOUND;
3299                 goto top;
3300         } else {
3301                 int exact = 0;
3302                 MDB_val d2;
3303                 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3304                 if (flags == MDB_NOOVERWRITE && rc == 0) {
3305                         DPRINTF("duplicate key [%s]", DKEY(key));
3306                         *data = d2;
3307                         return MDB_KEYEXIST;
3308                 }
3309                 if (rc && rc != MDB_NOTFOUND)
3310                         return rc;
3311         }
3312
3313         /* Cursor is positioned, now make sure all pages are writable */
3314         rc2 = mdb_cursor_touch(mc);
3315         if (rc2) return rc2;
3316
3317 top:
3318         /* The key already exists */
3319         if (rc == MDB_SUCCESS) {
3320                 /* there's only a key anyway, so this is a no-op */
3321                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3322                         unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3323                         if (key->mv_size != ksize)
3324                                 return EINVAL;
3325                         if (flags == MDB_CURRENT) {
3326                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3327                                 memcpy(ptr, key->mv_data, ksize);
3328                         }
3329                         return MDB_SUCCESS;
3330                 }
3331
3332                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3333
3334                 /* DB has dups? */
3335                 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
3336                         /* Was a single item before, must convert now */
3337                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3338                                 dkey.mv_size = NODEDSZ(leaf);
3339                                 dkey.mv_data = dbuf;
3340                                 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3341                                 /* data matches, ignore it */
3342                                 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
3343                                         return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3344                                 memset(&dummy, 0, sizeof(dummy));
3345                                 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
3346                                         dummy.md_pad = data->mv_size;
3347                                         dummy.md_flags = MDB_DUPFIXED;
3348                                         if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
3349                                                 dummy.md_flags |= MDB_INTEGERKEY;
3350                                 }
3351                                 dummy.md_root = P_INVALID;
3352                                 if (dkey.mv_size == sizeof(MDB_db)) {
3353                                         memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3354                                         goto put_sub;
3355                                 }
3356                                 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3357                                 do_sub = 1;
3358                                 rdata = &xdata;
3359                                 xdata.mv_size = sizeof(MDB_db);
3360                                 xdata.mv_data = &dummy;
3361                                 /* new sub-DB, must fully init xcursor */
3362                                 if (flags == MDB_CURRENT)
3363                                         flags = 0;
3364                                 goto new_sub;
3365                         }
3366                         goto put_sub;
3367                 }
3368                 /* same size, just replace it */
3369                 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3370                         NODEDSZ(leaf) == data->mv_size) {
3371                         memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3372                         goto done;
3373                 }
3374                 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3375         } else {
3376                 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3377         }
3378
3379         rdata = data;
3380
3381 new_sub:
3382         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3383         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3384                 rc = mdb_split(mc, key, rdata, P_INVALID);
3385         } else {
3386                 /* There is room already in this leaf page. */
3387                 rc = mdb_add_node(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3388         }
3389
3390         if (rc != MDB_SUCCESS)
3391                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3392         else {
3393                 /* Remember if we just added a subdatabase */
3394                 if (flags & F_SUBDATA) {
3395                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3396                         leaf->mn_flags |= F_SUBDATA;
3397                 }
3398
3399                 /* Now store the actual data in the child DB. Note that we're
3400                  * storing the user data in the keys field, so there are strict
3401                  * size limits on dupdata. The actual data fields of the child
3402                  * DB are all zero size.
3403                  */
3404                 if (do_sub) {
3405                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3406 put_sub:
3407                         if (flags == MDB_CURRENT)
3408                                 mdb_xcursor_init2(mc);
3409                         else
3410                                 mdb_xcursor_init1(mc, leaf);
3411                         xdata.mv_size = 0;
3412                         xdata.mv_data = "";
3413                         if (flags == MDB_NODUPDATA)
3414                                 flags = MDB_NOOVERWRITE;
3415                         /* converted, write the original data first */
3416                         if (dkey.mv_size) {
3417                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3418                                 if (rc) return rc;
3419                                 leaf->mn_flags |= F_DUPDATA;
3420                         }
3421                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3422                         mdb_xcursor_fini(mc);
3423                         memcpy(NODEDATA(leaf),
3424                                 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3425                                 sizeof(MDB_db));
3426                 }
3427                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3428         }
3429 done:
3430         return rc;
3431 }
3432
3433 int
3434 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3435 {
3436         MDB_node        *leaf;
3437         int rc;
3438
3439         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3440                 return EACCES;
3441
3442         if (!mc->mc_flags & C_INITIALIZED)
3443                 return EINVAL;
3444
3445         rc = mdb_cursor_touch(mc);
3446         if (rc) return rc;
3447
3448         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3449
3450         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3451                 if (flags != MDB_NODUPDATA) {
3452                         mdb_xcursor_init2(mc);
3453                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3454                         mdb_xcursor_fini(mc);
3455                         /* If sub-DB still has entries, we're done */
3456                         if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3457                                 != P_INVALID) {
3458                                 memcpy(NODEDATA(leaf),
3459                                         &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3460                                         sizeof(MDB_db));
3461                                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3462                                 return rc;
3463                         }
3464                         /* otherwise fall thru and delete the sub-DB */
3465                 }
3466
3467                 /* add all the child DB's pages to the free list */
3468                 rc = mdb_search_page(&mc->mc_xcursor->mx_cursor, NULL, 0);
3469                 if (rc == MDB_SUCCESS) {
3470                         MDB_node *ni;
3471                         MDB_cursor *mx;
3472                         unsigned int i;
3473
3474                         mx = &mc->mc_xcursor->mx_cursor;
3475                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3476                                 mx->mc_txn->mt_dbs[mx->mc_dbi].md_entries;
3477
3478                         cursor_pop_page(mx);
3479                         if (mx->mc_snum) {
3480                                 while (mx->mc_snum > 1) {
3481                                         for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3482                                                 pgno_t pg;
3483                                                 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3484                                                 pg = NODEPGNO(ni);
3485                                                 /* free it */
3486                                                 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3487                                         }
3488                                         rc = mdb_sibling(mx, 1);
3489                                         if (rc) break;
3490                                 }
3491                         }
3492                         /* free it */
3493                         mdb_midl_append(mc->mc_txn->mt_free_pgs,
3494                                 mx->mc_txn->mt_dbs[mx->mc_dbi].md_root);
3495                 }
3496         }
3497
3498         return mdb_del0(mc, leaf);
3499 }
3500
3501 /* Allocate a page and initialize it
3502  */
3503 static MDB_page *
3504 mdb_new_page(MDB_cursor *mc, uint32_t flags, int num)
3505 {
3506         MDB_page        *np;
3507
3508         if ((np = mdb_alloc_page(mc, num)) == NULL)
3509                 return NULL;
3510         DPRINTF("allocated new mpage %zu, page size %u",
3511             np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3512         np->mp_flags = flags | P_DIRTY;
3513         np->mp_lower = PAGEHDRSZ;
3514         np->mp_upper = mc->mc_txn->mt_env->me_psize;
3515
3516         if (IS_BRANCH(np))
3517                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages++;
3518         else if (IS_LEAF(np))
3519                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages++;
3520         else if (IS_OVERFLOW(np)) {
3521                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_overflow_pages += num;
3522                 np->mp_pages = num;
3523         }
3524
3525         return np;
3526 }
3527
3528 static size_t
3529 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3530 {
3531         size_t           sz;
3532
3533         sz = LEAFSIZE(key, data);
3534         if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3535                 /* put on overflow page */
3536                 sz -= data->mv_size - sizeof(pgno_t);
3537         }
3538         sz += sz & 1;
3539
3540         return sz + sizeof(indx_t);
3541 }
3542
3543 static size_t
3544 mdb_branch_size(MDB_env *env, MDB_val *key)
3545 {
3546         size_t           sz;
3547
3548         sz = INDXSIZE(key);
3549         if (sz >= env->me_psize / MDB_MINKEYS) {
3550                 /* put on overflow page */
3551                 /* not implemented */
3552                 /* sz -= key->size - sizeof(pgno_t); */
3553         }
3554
3555         return sz + sizeof(indx_t);
3556 }
3557
3558 static int
3559 mdb_add_node(MDB_cursor *mc, indx_t indx,
3560     MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3561 {
3562         unsigned int     i;
3563         size_t           node_size = NODESIZE;
3564         indx_t           ofs;
3565         MDB_node        *node;
3566         MDB_page        *mp = mc->mc_pg[mc->mc_top];
3567         MDB_page        *ofp = NULL;            /* overflow page */
3568         DKBUF;
3569
3570         assert(mp->mp_upper >= mp->mp_lower);
3571
3572         DPRINTF("add to %s page %zu index %i, data size %zu key size %zu [%s]",
3573             IS_LEAF(mp) ? "leaf" : "branch",
3574             mp->mp_pgno, indx, data ? data->mv_size : 0,
3575                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3576
3577         if (IS_LEAF2(mp)) {
3578                 /* Move higher keys up one slot. */
3579                 int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad, dif;
3580                 char *ptr = LEAF2KEY(mp, indx, ksize);
3581                 dif = NUMKEYS(mp) - indx;
3582                 if (dif > 0)
3583                         memmove(ptr+ksize, ptr, dif*ksize);
3584                 /* insert new key */
3585                 memcpy(ptr, key->mv_data, ksize);
3586
3587                 /* Just using these for counting */
3588                 mp->mp_lower += sizeof(indx_t);
3589                 mp->mp_upper -= ksize - sizeof(indx_t);
3590                 return MDB_SUCCESS;
3591         }
3592
3593         if (key != NULL)
3594                 node_size += key->mv_size;
3595
3596         if (IS_LEAF(mp)) {
3597                 assert(data);
3598                 if (F_ISSET(flags, F_BIGDATA)) {
3599                         /* Data already on overflow page. */
3600                         node_size += sizeof(pgno_t);
3601                 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3602                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3603                         /* Put data on overflow page. */
3604                         DPRINTF("data size is %zu, put on overflow page",
3605                             data->mv_size);
3606                         node_size += sizeof(pgno_t);
3607                         if ((ofp = mdb_new_page(mc, P_OVERFLOW, ovpages)) == NULL)
3608                                 return ENOMEM;
3609                         DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
3610                         flags |= F_BIGDATA;
3611                 } else {
3612                         node_size += data->mv_size;
3613                 }
3614         }
3615         node_size += node_size & 1;
3616
3617         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3618                 DPRINTF("not enough room in page %zu, got %u ptrs",
3619                     mp->mp_pgno, NUMKEYS(mp));
3620                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3621                     mp->mp_upper - mp->mp_lower);
3622                 DPRINTF("node size = %zu", node_size);
3623                 return ENOSPC;
3624         }
3625
3626         /* Move higher pointers up one slot. */
3627         for (i = NUMKEYS(mp); i > indx; i--)
3628                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3629
3630         /* Adjust free space offsets. */
3631         ofs = mp->mp_upper - node_size;
3632         assert(ofs >= mp->mp_lower + sizeof(indx_t));
3633         mp->mp_ptrs[indx] = ofs;
3634         mp->mp_upper = ofs;
3635         mp->mp_lower += sizeof(indx_t);
3636
3637         /* Write the node data. */
3638         node = NODEPTR(mp, indx);
3639         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3640         node->mn_flags = flags;
3641         if (IS_LEAF(mp))
3642                 SETDSZ(node,data->mv_size);
3643         else
3644                 SETPGNO(node,pgno);
3645
3646         if (key)
3647                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3648
3649         if (IS_LEAF(mp)) {
3650                 assert(key);
3651                 if (ofp == NULL) {
3652                         if (F_ISSET(flags, F_BIGDATA))
3653                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
3654                                     sizeof(pgno_t));
3655                         else
3656                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
3657                                     data->mv_size);
3658                 } else {
3659                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3660                             sizeof(pgno_t));
3661                         memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3662                 }
3663         }
3664
3665         return MDB_SUCCESS;
3666 }
3667
3668 static void
3669 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3670 {
3671         unsigned int     sz;
3672         indx_t           i, j, numkeys, ptr;
3673         MDB_node        *node;
3674         char            *base;
3675
3676         DPRINTF("delete node %u on %s page %zu", indx,
3677             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3678         assert(indx < NUMKEYS(mp));
3679
3680         if (IS_LEAF2(mp)) {
3681                 int x = NUMKEYS(mp) - 1 - indx;
3682                 base = LEAF2KEY(mp, indx, ksize);
3683                 if (x)
3684                         memmove(base, base + ksize, x * ksize);
3685                 mp->mp_lower -= sizeof(indx_t);
3686                 mp->mp_upper += ksize - sizeof(indx_t);
3687                 return;
3688         }
3689
3690         node = NODEPTR(mp, indx);
3691         sz = NODESIZE + node->mn_ksize;
3692         if (IS_LEAF(mp)) {
3693                 if (F_ISSET(node->mn_flags, F_BIGDATA))
3694                         sz += sizeof(pgno_t);
3695                 else
3696                         sz += NODEDSZ(node);
3697         }
3698         sz += sz & 1;
3699
3700         ptr = mp->mp_ptrs[indx];
3701         numkeys = NUMKEYS(mp);
3702         for (i = j = 0; i < numkeys; i++) {
3703                 if (i != indx) {
3704                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
3705                         if (mp->mp_ptrs[i] < ptr)
3706                                 mp->mp_ptrs[j] += sz;
3707                         j++;
3708                 }
3709         }
3710
3711         base = (char *)mp + mp->mp_upper;
3712         memmove(base + sz, base, ptr - mp->mp_upper);
3713
3714         mp->mp_lower -= sizeof(indx_t);
3715         mp->mp_upper += sz;
3716 }
3717
3718 static void
3719 mdb_xcursor_init0(MDB_cursor *mc)
3720 {
3721         MDB_xcursor *mx = mc->mc_xcursor;
3722         MDB_dbi dbn;
3723
3724         mx->mx_txn = *mc->mc_txn;
3725         mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3726         mx->mx_txn.mt_dbs = mx->mx_dbs;
3727         mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3728         mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3729         if (mc->mc_dbi > 1) {
3730                 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3731                 dbn = 2;
3732         } else {
3733                 dbn = 1;
3734         }
3735         mx->mx_dbxs[dbn+1].md_parent = dbn;
3736         mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3737         mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3738         mx->mx_dbxs[dbn+1].md_dirty = 0;
3739         mx->mx_txn.mt_numdbs = dbn+2;
3740         mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3741
3742         mx->mx_cursor.mc_xcursor = NULL;
3743         mx->mx_cursor.mc_txn = &mx->mx_txn;
3744         mx->mx_cursor.mc_dbi = dbn+1;
3745 }
3746
3747 static void
3748 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
3749 {
3750         MDB_db *db = NODEDATA(node);
3751         MDB_xcursor *mx = mc->mc_xcursor;
3752         MDB_dbi dbn;
3753         mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3754         mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3755         if (mc->mc_dbi > 1) {
3756                 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3757                 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3758                 dbn = 3;
3759         } else {
3760                 dbn = 2;
3761         }
3762         DPRINTF("Sub-db %u for db %u root page %zu", dbn, mc->mc_dbi, db->md_root);
3763         mx->mx_dbs[dbn] = *db;
3764         if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
3765                 mx->mx_dbxs[dbn].md_dirty = 1;
3766         mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3767         mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3768         mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3769         mx->mx_cursor.mc_snum = 0;
3770         mx->mx_cursor.mc_flags = 0;
3771 }
3772
3773 static void
3774 mdb_xcursor_init2(MDB_cursor *mc)
3775 {
3776         MDB_xcursor *mx = mc->mc_xcursor;
3777         MDB_dbi dbn;
3778         mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3779         mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3780         if (mc->mc_dbi > 1) {
3781                 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3782                 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3783                 dbn = 3;
3784         } else {
3785                 dbn = 2;
3786         }
3787         DPRINTF("Sub-db %u for db %u root page %zu", dbn, mc->mc_dbi,
3788                 mx->mx_dbs[dbn].md_root);
3789         mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3790 }
3791
3792 static void
3793 mdb_xcursor_fini(MDB_cursor *mc)
3794 {
3795         MDB_xcursor *mx = mc->mc_xcursor;
3796         mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3797         mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3798         mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3799         if (mc->mc_dbi > 1) {
3800                 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3801                 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3802         }
3803 }
3804
3805 int
3806 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3807 {
3808         MDB_cursor      *mc;
3809         size_t size = sizeof(MDB_cursor);
3810
3811         if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3812                 return EINVAL;
3813
3814         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3815                 size += sizeof(MDB_xcursor);
3816
3817         if ((mc = calloc(1, size)) != NULL) {
3818                 mc->mc_dbi = dbi;
3819                 mc->mc_txn = txn;
3820                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3821                         MDB_xcursor *mx = (MDB_xcursor *)(mc + 1);
3822                         mc->mc_xcursor = mx;
3823                         mdb_xcursor_init0(mc);
3824                 }
3825         } else {
3826                 return ENOMEM;
3827         }
3828
3829         *ret = mc;
3830
3831         return MDB_SUCCESS;
3832 }
3833
3834 /* Return the count of duplicate data items for the current key */
3835 int
3836 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
3837 {
3838         MDB_node        *leaf;
3839
3840         if (mc == NULL || countp == NULL)
3841                 return EINVAL;
3842
3843         if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3844                 return EINVAL;
3845
3846         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3847         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3848                 *countp = 1;
3849         } else {
3850                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3851                         return EINVAL;
3852
3853                 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3854         }
3855         return MDB_SUCCESS;
3856 }
3857
3858 void
3859 mdb_cursor_close(MDB_cursor *mc)
3860 {
3861         if (mc != NULL) {
3862                 free(mc);
3863         }
3864 }
3865
3866 static int
3867 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3868 {
3869         indx_t                   ptr, i, numkeys;
3870         int                      delta;
3871         size_t                   len;
3872         MDB_node                *node;
3873         char                    *base;
3874         DKBUF;
3875
3876         node = NODEPTR(mp, indx);
3877         ptr = mp->mp_ptrs[indx];
3878         DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
3879             indx, ptr,
3880             (int)node->mn_ksize, (char *)NODEKEY(node),
3881                 DKEY(key),
3882             mp->mp_pgno);
3883
3884         delta = key->mv_size - node->mn_ksize;
3885         if (delta) {
3886                 if (delta > 0 && SIZELEFT(mp) < delta) {
3887                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
3888                         return ENOSPC;
3889                 }
3890
3891                 numkeys = NUMKEYS(mp);
3892                 for (i = 0; i < numkeys; i++) {
3893                         if (mp->mp_ptrs[i] <= ptr)
3894                                 mp->mp_ptrs[i] -= delta;
3895                 }
3896
3897                 base = (char *)mp + mp->mp_upper;
3898                 len = ptr - mp->mp_upper + NODESIZE;
3899                 memmove(base - delta, base, len);
3900                 mp->mp_upper -= delta;
3901
3902                 node = NODEPTR(mp, indx);
3903                 node->mn_ksize = key->mv_size;
3904         }
3905
3906         memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3907
3908         return MDB_SUCCESS;
3909 }
3910
3911 /* Move a node from csrc to cdst.
3912  */
3913 static int
3914 mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst)
3915 {
3916         int                      rc;
3917         MDB_node                *srcnode;
3918         MDB_val          key, data;
3919         DKBUF;
3920
3921         /* Mark src and dst as dirty. */
3922         if ((rc = mdb_touch(csrc)) ||
3923             (rc = mdb_touch(cdst)))
3924                 return rc;;
3925
3926         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3927                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
3928                 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
3929                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3930                 data.mv_size = 0;
3931                 data.mv_data = NULL;
3932         } else {
3933                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3934                         unsigned int snum = csrc->mc_snum;
3935                         /* must find the lowest key below src */
3936                         mdb_search_page_root(csrc, NULL, 0);
3937                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
3938                         csrc->mc_snum = snum--;
3939                         csrc->mc_top = snum;
3940                 } else {
3941                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3942                 }
3943                 key.mv_size = NODEKSZ(srcnode);
3944                 key.mv_data = NODEKEY(srcnode);
3945                 data.mv_size = NODEDSZ(srcnode);
3946                 data.mv_data = NODEDATA(srcnode);
3947         }
3948         DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
3949             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
3950             csrc->mc_ki[csrc->mc_top],
3951                 DKEY(&key),
3952             csrc->mc_pg[csrc->mc_top]->mp_pgno,
3953             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
3954
3955         /* Add the node to the destination page.
3956          */
3957         rc = mdb_add_node(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
3958             srcnode->mn_flags);
3959         if (rc != MDB_SUCCESS)
3960                 return rc;
3961
3962         /* Delete the node from the source page.
3963          */
3964         mdb_del_node(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3965
3966         /* Update the parent separators.
3967          */
3968         if (csrc->mc_ki[csrc->mc_top] == 0) {
3969                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
3970                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3971                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3972                         } else {
3973                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3974                                 key.mv_size = NODEKSZ(srcnode);
3975                                 key.mv_data = NODEKEY(srcnode);
3976                         }
3977                         DPRINTF("update separator for source page %zu to [%s]",
3978                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
3979                         if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
3980                                 &key)) != MDB_SUCCESS)
3981                                 return rc;
3982                 }
3983                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3984                         MDB_val  nullkey;
3985                         nullkey.mv_size = 0;
3986                         assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
3987                 }
3988         }
3989
3990         if (cdst->mc_ki[cdst->mc_top] == 0) {
3991                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
3992                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3993                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
3994                         } else {
3995                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
3996                                 key.mv_size = NODEKSZ(srcnode);
3997                                 key.mv_data = NODEKEY(srcnode);
3998                         }
3999                         DPRINTF("update separator for destination page %zu to [%s]",
4000                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4001                         if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4002                                 &key)) != MDB_SUCCESS)
4003                                 return rc;
4004                 }
4005                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4006                         MDB_val  nullkey;
4007                         nullkey.mv_size = 0;
4008                         assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4009                 }
4010         }
4011
4012         return MDB_SUCCESS;
4013 }
4014
4015 static int
4016 mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4017 {
4018         int                      rc;
4019         indx_t                   i, j;
4020         MDB_node                *srcnode;
4021         MDB_val          key, data;
4022
4023         DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4024                 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4025
4026         assert(csrc->mc_snum > 1);      /* can't merge root page */
4027         assert(cdst->mc_snum > 1);
4028
4029         /* Mark dst as dirty. */
4030         if ((rc = mdb_touch(cdst)))
4031                 return rc;
4032
4033         /* Move all nodes from src to dst.
4034          */
4035         j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4036         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4037                 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
4038                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4039                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4040                         rc = mdb_add_node(cdst, j, &key, NULL, 0, 0);
4041                         if (rc != MDB_SUCCESS)
4042                                 return rc;
4043                         key.mv_data = (char *)key.mv_data + key.mv_size;
4044                 }
4045         } else {
4046                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4047                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4048
4049                         key.mv_size = srcnode->mn_ksize;
4050                         key.mv_data = NODEKEY(srcnode);
4051                         data.mv_size = NODEDSZ(srcnode);
4052                         data.mv_data = NODEDATA(srcnode);
4053                         rc = mdb_add_node(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4054                         if (rc != MDB_SUCCESS)
4055                                 return rc;
4056                 }
4057         }
4058
4059         DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4060             cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]), (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10);
4061
4062         /* Unlink the src page from parent and add to free list.
4063          */
4064         mdb_del_node(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4065         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4066                 key.mv_size = 0;
4067                 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4068                         return rc;
4069         }
4070
4071         mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4072         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4073                 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_leaf_pages--;
4074         else
4075                 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_branch_pages--;
4076         cursor_pop_page(csrc);
4077
4078         return mdb_rebalance(csrc);
4079 }
4080
4081 static void
4082 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4083 {
4084         unsigned int i;
4085
4086         cdst->mc_txn = csrc->mc_txn;
4087         cdst->mc_dbi = csrc->mc_dbi;
4088         cdst->mc_snum = csrc->mc_snum;
4089         cdst->mc_top = csrc->mc_top;
4090         cdst->mc_flags = csrc->mc_flags;
4091
4092         for (i=0; i<csrc->mc_snum; i++) {
4093                 cdst->mc_pg[i] = csrc->mc_pg[i];
4094                 cdst->mc_ki[i] = csrc->mc_ki[i];
4095         }
4096 }
4097
4098 static int
4099 mdb_rebalance(MDB_cursor *mc)
4100 {
4101         MDB_node        *node;
4102         MDB_page        *root;
4103         int rc;
4104         unsigned int ptop;
4105         MDB_cursor      mn;
4106
4107         DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4108             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4109             mc->mc_pg[mc->mc_top]->mp_pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
4110
4111         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4112                 DPRINTF("no need to rebalance page %zu, above fill threshold",
4113                     mc->mc_pg[mc->mc_top]->mp_pgno);
4114                 return MDB_SUCCESS;
4115         }
4116
4117         if (mc->mc_snum < 2) {
4118                 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4119                         DPUTS("tree is completely empty");
4120                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = P_INVALID;
4121                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth = 0;
4122                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages = 0;
4123                         mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4124                 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4125                         DPUTS("collapsing root page!");
4126                         mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4127                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4128                         if ((rc = mdb_get_page(mc->mc_txn, mc->mc_txn->mt_dbs[mc->mc_dbi].md_root, &root)))
4129                                 return rc;
4130                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4131                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages--;
4132                 } else
4133                         DPUTS("root page doesn't need rebalancing");
4134                 return MDB_SUCCESS;
4135         }
4136
4137         /* The parent (branch page) must have at least 2 pointers,
4138          * otherwise the tree is invalid.
4139          */
4140         ptop = mc->mc_top-1;
4141         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4142
4143         /* Leaf page fill factor is below the threshold.
4144          * Try to move keys from left or right neighbor, or
4145          * merge with a neighbor page.
4146          */
4147
4148         /* Find neighbors.
4149          */
4150         mdb_cursor_copy(mc, &mn);
4151         mn.mc_xcursor = NULL;
4152
4153         if (mc->mc_ki[ptop] == 0) {
4154                 /* We're the leftmost leaf in our parent.
4155                  */
4156                 DPUTS("reading right neighbor");
4157                 mn.mc_ki[ptop]++;
4158                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4159                 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4160                         return rc;
4161                 mn.mc_ki[mn.mc_top] = 0;
4162                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4163         } else {
4164                 /* There is at least one neighbor to the left.
4165                  */
4166                 DPUTS("reading left neighbor");
4167                 mn.mc_ki[ptop]--;
4168                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4169                 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4170                         return rc;
4171                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4172                 mc->mc_ki[mc->mc_top] = 0;
4173         }
4174
4175         DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4176             mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10);
4177
4178         /* If the neighbor page is above threshold and has at least two
4179          * keys, move one key from it.
4180          *
4181          * Otherwise we should try to merge them.
4182          */
4183         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4184                 return mdb_move_node(&mn, mc);
4185         else { /* FIXME: if (has_enough_room()) */
4186                 if (mc->mc_ki[ptop] == 0)
4187                         return mdb_merge(&mn, mc);
4188                 else
4189                         return mdb_merge(mc, &mn);
4190         }
4191 }
4192
4193 static int
4194 mdb_del0(MDB_cursor *mc, MDB_node *leaf)
4195 {
4196         int rc;
4197
4198         /* add overflow pages to free list */
4199         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4200                 int i, ovpages;
4201                 pgno_t pg;
4202
4203                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4204                 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4205                 for (i=0; i<ovpages; i++) {
4206                         DPRINTF("freed ov page %zu", pg);
4207                         mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4208                         pg++;
4209                 }
4210         }
4211         mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad);
4212         mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
4213         rc = mdb_rebalance(mc);
4214         if (rc != MDB_SUCCESS)
4215                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4216
4217         return rc;
4218 }
4219
4220 int
4221 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4222     MDB_val *key, MDB_val *data)
4223 {
4224         MDB_cursor mc;
4225         MDB_xcursor mx;
4226         MDB_cursor_op op;
4227         MDB_val rdata, *xdata;
4228         int              rc, exact;
4229         DKBUF;
4230
4231         assert(key != NULL);
4232
4233         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4234
4235         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4236                 return EINVAL;
4237
4238         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4239                 return EACCES;
4240         }
4241
4242         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4243                 return EINVAL;
4244         }
4245
4246         mc.mc_txn = txn;
4247         mc.mc_dbi = dbi;
4248         mc.mc_flags = 0;
4249         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4250                 mc.mc_xcursor = &mx;
4251                 mdb_xcursor_init0(&mc);
4252         } else {
4253                 mc.mc_xcursor = NULL;
4254         }
4255
4256         exact = 0;
4257         if (data) {
4258                 op = MDB_GET_BOTH;
4259                 rdata = *data;
4260                 xdata = &rdata;
4261         } else {
4262                 op = MDB_SET;
4263                 xdata = NULL;
4264         }
4265         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4266         if (rc == 0)
4267                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4268         return rc;
4269 }
4270
4271 /* Split page <mc->top>, and insert <key,(data|newpgno)> in either left or
4272  * right sibling, at index <mc->ki> (as if unsplit). Updates mc->top and
4273  * mc->ki with the actual values after split, ie if mc->top and mc->ki
4274  * refer to a node in the new right sibling page.
4275  */
4276 static int
4277 mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4278 {
4279         uint8_t          flags;
4280         int              rc = MDB_SUCCESS, ins_new = 0;
4281         indx_t           newindx;
4282         pgno_t           pgno = 0;
4283         unsigned int     i, j, split_indx, nkeys, pmax;
4284         MDB_node        *node;
4285         MDB_val  sepkey, rkey, rdata;
4286         MDB_page        *copy;
4287         MDB_page        *mp, *rp, *pp;
4288         unsigned int ptop;
4289         MDB_cursor      mn;
4290         DKBUF;
4291
4292         mp = mc->mc_pg[mc->mc_top];
4293         newindx = mc->mc_ki[mc->mc_top];
4294
4295         DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4296             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4297             DKEY(newkey), mc->mc_ki[mc->mc_top]);
4298
4299         if (mc->mc_snum < 2) {
4300                 if ((pp = mdb_new_page(mc, P_BRANCH, 1)) == NULL)
4301                         return ENOMEM;
4302                 /* shift current top to make room for new parent */
4303                 mc->mc_pg[1] = mc->mc_pg[0];
4304                 mc->mc_ki[1] = mc->mc_ki[0];
4305                 mc->mc_pg[0] = pp;
4306                 mc->mc_ki[0] = 0;
4307                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = pp->mp_pgno;
4308                 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4309                 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
4310
4311                 /* Add left (implicit) pointer. */
4312                 if ((rc = mdb_add_node(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4313                         /* undo the pre-push */
4314                         mc->mc_pg[0] = mc->mc_pg[1];
4315                         mc->mc_ki[0] = mc->mc_ki[1];
4316                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mp->mp_pgno;
4317                         mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4318                         return rc;
4319                 }
4320                 mc->mc_snum = 2;
4321                 mc->mc_top = 1;
4322                 ptop = 0;
4323         } else {
4324                 ptop = mc->mc_top-1;
4325                 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4326         }
4327
4328         /* Create a right sibling. */
4329         if ((rp = mdb_new_page(mc, mp->mp_flags, 1)) == NULL)
4330                 return ENOMEM;
4331         mdb_cursor_copy(mc, &mn);
4332         mn.mc_pg[mn.mc_top] = rp;
4333         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4334         DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4335
4336         nkeys = NUMKEYS(mp);
4337         split_indx = nkeys / 2 + 1;
4338
4339         if (IS_LEAF2(rp)) {
4340                 char *split, *ins;
4341                 int x;
4342                 unsigned int lsize, rsize, ksize;
4343                 /* Move half of the keys to the right sibling */
4344                 copy = NULL;
4345                 x = mc->mc_ki[mc->mc_top] - split_indx;
4346                 ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
4347                 split = LEAF2KEY(mp, split_indx, ksize);
4348                 rsize = (nkeys - split_indx) * ksize;
4349                 lsize = (nkeys - split_indx) * sizeof(indx_t);
4350                 mp->mp_lower -= lsize;
4351                 rp->mp_lower += lsize;
4352                 mp->mp_upper += rsize - lsize;
4353                 rp->mp_upper -= rsize - lsize;
4354                 sepkey.mv_size = ksize;
4355                 if (newindx == split_indx) {
4356                         sepkey.mv_data = newkey->mv_data;
4357                 } else {
4358                         sepkey.mv_data = split;
4359                 }
4360                 if (x<0) {
4361                         ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4362                         memcpy(rp->mp_ptrs, split, rsize);
4363                         sepkey.mv_data = rp->mp_ptrs;
4364                         memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4365                         memcpy(ins, newkey->mv_data, ksize);
4366                         mp->mp_lower += sizeof(indx_t);
4367                         mp->mp_upper -= ksize - sizeof(indx_t);
4368                 } else {
4369                         if (x)
4370                                 memcpy(rp->mp_ptrs, split, x * ksize);
4371                         ins = LEAF2KEY(rp, x, ksize);
4372                         memcpy(ins, newkey->mv_data, ksize);
4373                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4374                         rp->mp_lower += sizeof(indx_t);
4375                         rp->mp_upper -= ksize - sizeof(indx_t);
4376                         mc->mc_ki[mc->mc_top] = x;
4377                         mc->mc_pg[mc->mc_top] = rp;
4378                 }
4379                 goto newsep;
4380         }
4381
4382         /* For leaf pages, check the split point based on what
4383          * fits where, since otherwise add_node can fail.
4384          */
4385         if (IS_LEAF(mp)) {
4386                 unsigned int psize, nsize;
4387                 /* Maximum free space in an empty page */
4388                 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4389                 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4390                 if (newindx < split_indx) {
4391                         psize = nsize;
4392                         for (i=0; i<split_indx; i++) {
4393                                 node = NODEPTR(mp, i);
4394                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4395                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4396                                         psize += sizeof(pgno_t);
4397                                 else
4398                                         psize += NODEDSZ(node);
4399                                 psize += psize & 1;
4400                                 if (psize > pmax) {
4401                                         split_indx = i;
4402                                         break;
4403                                 }
4404                         }
4405                 } else {
4406                         psize = nsize;
4407                         for (i=nkeys-1; i>=split_indx; i--) {
4408                                 node = NODEPTR(mp, i);
4409                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4410                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4411                                         psize += sizeof(pgno_t);
4412                                 else
4413                                         psize += NODEDSZ(node);
4414                                 psize += psize & 1;
4415                                 if (psize > pmax) {
4416                                         split_indx = i+1;
4417                                         break;
4418                                 }
4419                         }
4420                 }
4421         }
4422
4423         /* First find the separating key between the split pages.
4424          */
4425         if (newindx == split_indx) {
4426                 sepkey.mv_size = newkey->mv_size;
4427                 sepkey.mv_data = newkey->mv_data;
4428         } else {
4429                 node = NODEPTR(mp, split_indx);
4430                 sepkey.mv_size = node->mn_ksize;
4431                 sepkey.mv_data = NODEKEY(node);
4432         }
4433
4434 newsep:
4435         DPRINTF("separator is [%s]", DKEY(&sepkey));
4436
4437         /* Copy separator key to the parent.
4438          */
4439         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4440                 mn.mc_snum--;
4441                 mn.mc_top--;
4442                 rc = mdb_split(&mn, &sepkey, NULL, rp->mp_pgno);
4443
4444                 /* Right page might now have changed parent.
4445                  * Check if left page also changed parent.
4446                  */
4447                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4448                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4449                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
4450                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4451                 }
4452         } else {
4453                 mn.mc_top--;
4454                 rc = mdb_add_node(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4455                 mn.mc_top++;
4456         }
4457         if (IS_LEAF2(rp)) {
4458                 return rc;
4459         }
4460         if (rc != MDB_SUCCESS) {
4461                 return rc;
4462         }
4463
4464         /* Move half of the keys to the right sibling. */
4465
4466         /* grab a page to hold a temporary copy */
4467         if (mc->mc_txn->mt_env->me_dpages) {
4468                 copy = mc->mc_txn->mt_env->me_dpages;
4469                 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4470         } else {
4471                 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4472                         return ENOMEM;
4473         }
4474
4475         copy->mp_pgno  = mp->mp_pgno;
4476         copy->mp_flags = mp->mp_flags;
4477         copy->mp_lower = PAGEHDRSZ;
4478         copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4479         mc->mc_pg[mc->mc_top] = copy;
4480         for (i = j = 0; i <= nkeys; j++) {
4481                 if (i == split_indx) {
4482                 /* Insert in right sibling. */
4483                 /* Reset insert index for right sibling. */
4484                         j = (i == newindx && ins_new);
4485                         mc->mc_pg[mc->mc_top] = rp;
4486                 }
4487
4488                 if (i == newindx && !ins_new) {
4489                         /* Insert the original entry that caused the split. */
4490                         rkey.mv_data = newkey->mv_data;
4491                         rkey.mv_size = newkey->mv_size;
4492                         if (IS_LEAF(mp)) {
4493                                 rdata.mv_data = newdata->mv_data;
4494                                 rdata.mv_size = newdata->mv_size;
4495                         } else
4496                                 pgno = newpgno;
4497                         flags = 0;
4498
4499                         ins_new = 1;
4500
4501                         /* Update page and index for the new key. */
4502                         mc->mc_ki[mc->mc_top] = j;
4503                 } else if (i == nkeys) {
4504                         break;
4505                 } else {
4506                         node = NODEPTR(mp, i);
4507                         rkey.mv_data = NODEKEY(node);
4508                         rkey.mv_size = node->mn_ksize;
4509                         if (IS_LEAF(mp)) {
4510                                 rdata.mv_data = NODEDATA(node);
4511                                 rdata.mv_size = NODEDSZ(node);
4512                         } else
4513                                 pgno = NODEPGNO(node);
4514                         flags = node->mn_flags;
4515
4516                         i++;
4517                 }
4518
4519                 if (!IS_LEAF(mp) && j == 0) {
4520                         /* First branch index doesn't need key data. */
4521                         rkey.mv_size = 0;
4522                 }
4523
4524                 rc = mdb_add_node(mc, j, &rkey, &rdata, pgno, flags);
4525         }
4526
4527         /* reset back to original page */
4528         if (newindx < split_indx)
4529                 mc->mc_pg[mc->mc_top] = mp;
4530
4531         nkeys = NUMKEYS(copy);
4532         for (i=0; i<nkeys; i++)
4533                 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4534         mp->mp_lower = copy->mp_lower;
4535         mp->mp_upper = copy->mp_upper;
4536         memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4537                 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4538
4539         /* return tmp page to freelist */
4540         copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4541         mc->mc_txn->mt_env->me_dpages = copy;
4542         return rc;
4543 }
4544
4545 int
4546 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4547     MDB_val *key, MDB_val *data, unsigned int flags)
4548 {
4549         MDB_cursor mc;
4550         MDB_xcursor mx;
4551
4552         assert(key != NULL);
4553         assert(data != NULL);
4554
4555         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4556                 return EINVAL;
4557
4558         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4559                 return EACCES;
4560         }
4561
4562         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4563                 return EINVAL;
4564         }
4565
4566         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4567                 return EINVAL;
4568
4569         mc.mc_txn = txn;
4570         mc.mc_dbi = dbi;
4571         mc.mc_snum = 0;
4572         mc.mc_flags = 0;
4573         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4574                 mc.mc_xcursor = &mx;
4575                 mdb_xcursor_init0(&mc);
4576         } else {
4577                 mc.mc_xcursor = NULL;
4578         }
4579         return mdb_cursor_put(&mc, key, data, flags);
4580 }
4581
4582 int
4583 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4584 {
4585         /** Only a subset of the @ref mdb_env flags can be changed
4586          *      at runtime. Changing other flags requires closing the environment
4587          *      and re-opening it with the new flags.
4588          */
4589 #define CHANGEABLE      (MDB_NOSYNC)
4590         if ((flag & CHANGEABLE) != flag)
4591                 return EINVAL;
4592         if (onoff)
4593                 env->me_flags |= flag;
4594         else
4595                 env->me_flags &= ~flag;
4596         return MDB_SUCCESS;
4597 }
4598
4599 int
4600 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4601 {
4602         if (!env || !arg)
4603                 return EINVAL;
4604
4605         *arg = env->me_flags;
4606         return MDB_SUCCESS;
4607 }
4608
4609 int
4610 mdb_env_get_path(MDB_env *env, const char **arg)
4611 {
4612         if (!env || !arg)
4613                 return EINVAL;
4614
4615         *arg = env->me_path;
4616         return MDB_SUCCESS;
4617 }
4618
4619 static int
4620 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4621 {
4622         arg->ms_psize = env->me_psize;
4623         arg->ms_depth = db->md_depth;
4624         arg->ms_branch_pages = db->md_branch_pages;
4625         arg->ms_leaf_pages = db->md_leaf_pages;
4626         arg->ms_overflow_pages = db->md_overflow_pages;
4627         arg->ms_entries = db->md_entries;
4628
4629         return MDB_SUCCESS;
4630 }
4631 int
4632 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4633 {
4634         int toggle;
4635
4636         if (env == NULL || arg == NULL)
4637                 return EINVAL;
4638
4639         mdb_env_read_meta(env, &toggle);
4640
4641         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4642 }
4643
4644 static void
4645 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4646 {
4647         if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4648                 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4649         else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4650                 txn->mt_dbxs[dbi].md_cmp = cintcmp;
4651         else
4652                 txn->mt_dbxs[dbi].md_cmp = memncmp;
4653
4654         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4655                 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4656                         if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4657                                 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4658                         else
4659                                 txn->mt_dbxs[dbi].md_dcmp = cintcmp;
4660                 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4661                         txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4662                 } else {
4663                         txn->mt_dbxs[dbi].md_dcmp = memncmp;
4664                 }
4665         } else {
4666                 txn->mt_dbxs[dbi].md_dcmp = NULL;
4667         }
4668 }
4669
4670 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4671 {
4672         MDB_val key, data;
4673         MDB_dbi i;
4674         int rc, dirty = 0;
4675         size_t len;
4676
4677         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4678                 mdb_default_cmp(txn, FREE_DBI);
4679         }
4680
4681         /* main DB? */
4682         if (!name) {
4683                 *dbi = MAIN_DBI;
4684                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4685                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4686                 mdb_default_cmp(txn, MAIN_DBI);
4687                 return MDB_SUCCESS;
4688         }
4689
4690         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4691                 mdb_default_cmp(txn, MAIN_DBI);
4692         }
4693
4694         /* Is the DB already open? */
4695         len = strlen(name);
4696         for (i=2; i<txn->mt_numdbs; i++) {
4697                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4698                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4699                         *dbi = i;
4700                         return MDB_SUCCESS;
4701                 }
4702         }
4703
4704         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4705                 return ENFILE;
4706
4707         /* Find the DB info */
4708         key.mv_size = len;
4709         key.mv_data = (void *)name;
4710         rc = mdb_get(txn, MAIN_DBI, &key, &data);
4711
4712         /* Create if requested */
4713         if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4714                 MDB_cursor mc;
4715                 MDB_db dummy;
4716                 data.mv_size = sizeof(MDB_db);
4717                 data.mv_data = &dummy;
4718                 memset(&dummy, 0, sizeof(dummy));
4719                 dummy.md_root = P_INVALID;
4720                 dummy.md_flags = flags & 0xffff;
4721                 mc.mc_txn = txn;
4722                 mc.mc_dbi = MAIN_DBI;
4723                 mc.mc_flags = 0;
4724                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4725                 dirty = 1;
4726         }
4727
4728         /* OK, got info, add to table */
4729         if (rc == MDB_SUCCESS) {
4730                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4731                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4732                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4733                 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4734                 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4735                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4736                 *dbi = txn->mt_numdbs;
4737                 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4738                 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4739                 mdb_default_cmp(txn, txn->mt_numdbs);
4740                 txn->mt_numdbs++;
4741         }
4742
4743         return rc;
4744 }
4745
4746 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4747 {
4748         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4749                 return EINVAL;
4750
4751         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4752 }
4753
4754 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4755 {
4756         char *ptr;
4757         if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4758                 return;
4759         ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4760         txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4761         txn->mt_dbxs[dbi].md_name.mv_size = 0;
4762         free(ptr);
4763 }
4764
4765 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4766 {
4767         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4768                 return EINVAL;
4769
4770         txn->mt_dbxs[dbi].md_cmp = cmp;
4771         return MDB_SUCCESS;
4772 }
4773
4774 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4775 {
4776         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4777                 return EINVAL;
4778
4779         txn->mt_dbxs[dbi].md_dcmp = cmp;
4780         return MDB_SUCCESS;
4781 }
4782
4783 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4784 {
4785         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4786                 return EINVAL;
4787
4788         txn->mt_dbxs[dbi].md_rel = rel;
4789         return MDB_SUCCESS;
4790 }
4791
4792 /** @} */