]> git.sur5r.net Git - openldap/blob - libraries/liblmdb/mdb.c
bc25bb39f07c00ce4d813c9b78bc034dfe73e4aa
[openldap] / libraries / liblmdb / 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-2013 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 #define _GNU_SOURCE 1
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/param.h>
39 #ifdef _WIN32
40 #include <windows.h>
41 #else
42 #include <sys/uio.h>
43 #include <sys/mman.h>
44 #ifdef HAVE_SYS_FILE_H
45 #include <sys/file.h>
46 #endif
47 #include <fcntl.h>
48 #endif
49
50 #include <assert.h>
51 #include <errno.h>
52 #include <limits.h>
53 #include <stddef.h>
54 #include <inttypes.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60
61 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
62 #include <netinet/in.h>
63 #include <resolv.h>     /* defines BYTE_ORDER on HPUX and Solaris */
64 #endif
65
66 #if defined(__APPLE__) || defined (BSD)
67 # define MDB_USE_POSIX_SEM      1
68 # define MDB_FDATASYNC          fsync
69 #elif defined(ANDROID)
70 # define MDB_FDATASYNC          fsync
71 #endif
72
73 #ifndef _WIN32
74 #include <pthread.h>
75 #ifdef MDB_USE_POSIX_SEM
76 #include <semaphore.h>
77 #endif
78 #endif
79
80 #ifdef USE_VALGRIND
81 #include <valgrind/memcheck.h>
82 #define VGMEMP_CREATE(h,r,z)    VALGRIND_CREATE_MEMPOOL(h,r,z)
83 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
84 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
85 #define VGMEMP_DESTROY(h)       VALGRIND_DESTROY_MEMPOOL(h)
86 #define VGMEMP_DEFINED(a,s)     VALGRIND_MAKE_MEM_DEFINED(a,s)
87 #else
88 #define VGMEMP_CREATE(h,r,z)
89 #define VGMEMP_ALLOC(h,a,s)
90 #define VGMEMP_FREE(h,a)
91 #define VGMEMP_DESTROY(h)
92 #define VGMEMP_DEFINED(a,s)
93 #endif
94
95 #ifndef BYTE_ORDER
96 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
97 /* Solaris just defines one or the other */
98 #  define LITTLE_ENDIAN 1234
99 #  define BIG_ENDIAN    4321
100 #  ifdef _LITTLE_ENDIAN
101 #   define BYTE_ORDER  LITTLE_ENDIAN
102 #  else
103 #   define BYTE_ORDER  BIG_ENDIAN
104 #  endif
105 # else
106 #  define BYTE_ORDER   __BYTE_ORDER
107 # endif
108 #endif
109
110 #ifndef LITTLE_ENDIAN
111 #define LITTLE_ENDIAN   __LITTLE_ENDIAN
112 #endif
113 #ifndef BIG_ENDIAN
114 #define BIG_ENDIAN      __BIG_ENDIAN
115 #endif
116
117 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
118 #define MISALIGNED_OK   1
119 #endif
120
121 #include "lmdb.h"
122 #include "midl.h"
123
124 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
125 # error "Unknown or unsupported endianness (BYTE_ORDER)"
126 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
127 # error "Two's complement, reasonably sized integer types, please"
128 #endif
129
130 /** @defgroup internal  MDB Internals
131  *      @{
132  */
133 /** @defgroup compat    Windows Compatibility Macros
134  *      A bunch of macros to minimize the amount of platform-specific ifdefs
135  *      needed throughout the rest of the code. When the features this library
136  *      needs are similar enough to POSIX to be hidden in a one-or-two line
137  *      replacement, this macro approach is used.
138  *      @{
139  */
140 #ifdef _WIN32
141 #define pthread_t       DWORD
142 #define pthread_mutex_t HANDLE
143 #define pthread_key_t   DWORD
144 #define pthread_self()  GetCurrentThreadId()
145 #define pthread_key_create(x,y) \
146         ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
147 #define pthread_key_delete(x)   TlsFree(x)
148 #define pthread_getspecific(x)  TlsGetValue(x)
149 #define pthread_setspecific(x,y)        (TlsSetValue(x,y) ? 0 : ErrCode())
150 #define pthread_mutex_unlock(x) ReleaseMutex(x)
151 #define pthread_mutex_lock(x)   WaitForSingleObject(x, INFINITE)
152 #define LOCK_MUTEX_R(env)       pthread_mutex_lock((env)->me_rmutex)
153 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock((env)->me_rmutex)
154 #define LOCK_MUTEX_W(env)       pthread_mutex_lock((env)->me_wmutex)
155 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock((env)->me_wmutex)
156 #define getpid()        GetCurrentProcessId()
157 #define MDB_FDATASYNC(fd)       (!FlushFileBuffers(fd))
158 #define MDB_MSYNC(addr,len,flags)       (!FlushViewOfFile(addr,len))
159 #define ErrCode()       GetLastError()
160 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
161 #define close(fd)       CloseHandle(fd)
162 #define munmap(ptr,len) UnmapViewOfFile(ptr)
163 #else
164
165 #ifdef MDB_USE_POSIX_SEM
166
167 #define LOCK_MUTEX_R(env)       mdb_sem_wait((env)->me_rmutex)
168 #define UNLOCK_MUTEX_R(env)     sem_post((env)->me_rmutex)
169 #define LOCK_MUTEX_W(env)       mdb_sem_wait((env)->me_wmutex)
170 #define UNLOCK_MUTEX_W(env)     sem_post((env)->me_wmutex)
171
172 static int
173 mdb_sem_wait(sem_t *sem)
174 {
175    int rc;
176    while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
177    return rc;
178 }
179
180 #else
181         /** Lock the reader mutex.
182          */
183 #define LOCK_MUTEX_R(env)       pthread_mutex_lock(&(env)->me_txns->mti_mutex)
184         /** Unlock the reader mutex.
185          */
186 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
187
188         /** Lock the writer mutex.
189          *      Only a single write transaction is allowed at a time. Other writers
190          *      will block waiting for this mutex.
191          */
192 #define LOCK_MUTEX_W(env)       pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
193         /** Unlock the writer mutex.
194          */
195 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
196 #endif  /* MDB_USE_POSIX_SEM */
197
198         /** Get the error code for the last failed system function.
199          */
200 #define ErrCode()       errno
201
202         /** An abstraction for a file handle.
203          *      On POSIX systems file handles are small integers. On Windows
204          *      they're opaque pointers.
205          */
206 #define HANDLE  int
207
208         /**     A value for an invalid file handle.
209          *      Mainly used to initialize file variables and signify that they are
210          *      unused.
211          */
212 #define INVALID_HANDLE_VALUE    (-1)
213
214         /** Get the size of a memory page for the system.
215          *      This is the basic size that the platform's memory manager uses, and is
216          *      fundamental to the use of memory-mapped files.
217          */
218 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
219 #endif
220
221 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
222 #define MNAME_LEN       32
223 #else
224 #define MNAME_LEN       (sizeof(pthread_mutex_t))
225 #endif
226
227 /** @} */
228
229 #ifndef _WIN32
230 /**     A flag for opening a file and requesting synchronous data writes.
231  *      This is only used when writing a meta page. It's not strictly needed;
232  *      we could just do a normal write and then immediately perform a flush.
233  *      But if this flag is available it saves us an extra system call.
234  *
235  *      @note If O_DSYNC is undefined but exists in /usr/include,
236  * preferably set some compiler flag to get the definition.
237  * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
238  */
239 #ifndef MDB_DSYNC
240 # define MDB_DSYNC      O_DSYNC
241 #endif
242 #endif
243
244 /** Function for flushing the data of a file. Define this to fsync
245  *      if fdatasync() is not supported.
246  */
247 #ifndef MDB_FDATASYNC
248 # define MDB_FDATASYNC  fdatasync
249 #endif
250
251 #ifndef MDB_MSYNC
252 # define MDB_MSYNC(addr,len,flags)      msync(addr,len,flags)
253 #endif
254
255 #ifndef MS_SYNC
256 #define MS_SYNC 1
257 #endif
258
259 #ifndef MS_ASYNC
260 #define MS_ASYNC        0
261 #endif
262
263         /** A page number in the database.
264          *      Note that 64 bit page numbers are overkill, since pages themselves
265          *      already represent 12-13 bits of addressable memory, and the OS will
266          *      always limit applications to a maximum of 63 bits of address space.
267          *
268          *      @note In the #MDB_node structure, we only store 48 bits of this value,
269          *      which thus limits us to only 60 bits of addressable data.
270          */
271 typedef MDB_ID  pgno_t;
272
273         /** A transaction ID.
274          *      See struct MDB_txn.mt_txnid for details.
275          */
276 typedef MDB_ID  txnid_t;
277
278 /** @defgroup debug     Debug Macros
279  *      @{
280  */
281 #ifndef MDB_DEBUG
282         /**     Enable debug output.
283          *      Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
284          *      read from and written to the database (used for free space management).
285          */
286 #define MDB_DEBUG 0
287 #endif
288
289 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
290 # undef  MDB_DEBUG
291 # define MDB_DEBUG      0
292 # define DPRINTF        (void)  /* Vararg macros may be unsupported */
293 #elif MDB_DEBUG
294 static int mdb_debug;
295 static txnid_t mdb_debug_start;
296
297         /**     Print a debug message with printf formatting. */
298 # define DPRINTF(fmt, ...)      /**< Requires 2 or more args */ \
299         ((void) ((mdb_debug) && \
300          fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
301 #else
302 # define DPRINTF(fmt, ...)      ((void) 0)
303 # define MDB_DEBUG_SKIP
304 #endif
305         /**     Print a debug string.
306          *      The string is printed literally, with no format processing.
307          */
308 #define DPUTS(arg)      DPRINTF("%s", arg)
309 /** @} */
310
311         /** A default memory page size.
312          *      The actual size is platform-dependent, but we use this for
313          *      boot-strapping. We probably should not be using this any more.
314          *      The #GET_PAGESIZE() macro is used to get the actual size.
315          *
316          *      Note that we don't currently support Huge pages. On Linux,
317          *      regular data files cannot use Huge pages, and in general
318          *      Huge pages aren't actually pageable. We rely on the OS
319          *      demand-pager to read our data and page it out when memory
320          *      pressure from other processes is high. So until OSs have
321          *      actual paging support for Huge pages, they're not viable.
322          */
323 #define MDB_PAGESIZE     4096
324
325         /** The minimum number of keys required in a database page.
326          *      Setting this to a larger value will place a smaller bound on the
327          *      maximum size of a data item. Data items larger than this size will
328          *      be pushed into overflow pages instead of being stored directly in
329          *      the B-tree node. This value used to default to 4. With a page size
330          *      of 4096 bytes that meant that any item larger than 1024 bytes would
331          *      go into an overflow page. That also meant that on average 2-3KB of
332          *      each overflow page was wasted space. The value cannot be lower than
333          *      2 because then there would no longer be a tree structure. With this
334          *      value, items larger than 2KB will go into overflow pages, and on
335          *      average only 1KB will be wasted.
336          */
337 #define MDB_MINKEYS      2
338
339         /**     A stamp that identifies a file as an MDB file.
340          *      There's nothing special about this value other than that it is easily
341          *      recognizable, and it will reflect any byte order mismatches.
342          */
343 #define MDB_MAGIC        0xBEEFC0DE
344
345         /**     The version number for a database's file format. */
346 #define MDB_VERSION      1
347
348         /**     @brief The maximum size of a key in the database.
349          *
350          *      We require that keys all fit onto a regular page. This limit
351          *      could be raised a bit further if needed; to something just
352          *      under #MDB_PAGESIZE / #MDB_MINKEYS.
353          *
354          *      Note that data items in an #MDB_DUPSORT database are actually keys
355          *      of a subDB, so they're also limited to this size.
356          */
357 #ifndef MDB_MAXKEYSIZE
358 #define MDB_MAXKEYSIZE   511
359 #endif
360
361         /**     @brief The maximum size of a data item.
362          *
363          *      We only store a 32 bit value for node sizes.
364          */
365 #define MAXDATASIZE     0xffffffffUL
366
367 #if MDB_DEBUG
368         /**     A key buffer.
369          *      @ingroup debug
370          *      This is used for printing a hex dump of a key's contents.
371          */
372 #define DKBUF   char kbuf[(MDB_MAXKEYSIZE*2+1)]
373         /**     Display a key in hex.
374          *      @ingroup debug
375          *      Invoke a function to display a key in hex.
376          */
377 #define DKEY(x) mdb_dkey(x, kbuf)
378 #else
379 #define DKBUF   typedef int dummy_kbuf  /* so we can put ';' after */
380 #define DKEY(x) 0
381 #endif
382
383         /** An invalid page number.
384          *      Mainly used to denote an empty tree.
385          */
386 #define P_INVALID        (~(pgno_t)0)
387
388         /** Test if the flags \b f are set in a flag word \b w. */
389 #define F_ISSET(w, f)    (((w) & (f)) == (f))
390
391         /**     Used for offsets within a single page.
392          *      Since memory pages are typically 4 or 8KB in size, 12-13 bits,
393          *      this is plenty.
394          */
395 typedef uint16_t         indx_t;
396
397         /**     Default size of memory map.
398          *      This is certainly too small for any actual applications. Apps should always set
399          *      the size explicitly using #mdb_env_set_mapsize().
400          */
401 #define DEFAULT_MAPSIZE 1048576
402
403 /**     @defgroup readers       Reader Lock Table
404  *      Readers don't acquire any locks for their data access. Instead, they
405  *      simply record their transaction ID in the reader table. The reader
406  *      mutex is needed just to find an empty slot in the reader table. The
407  *      slot's address is saved in thread-specific data so that subsequent read
408  *      transactions started by the same thread need no further locking to proceed.
409  *
410  *      If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
411  *
412  *      No reader table is used if the database is on a read-only filesystem.
413  *
414  *      Since the database uses multi-version concurrency control, readers don't
415  *      actually need any locking. This table is used to keep track of which
416  *      readers are using data from which old transactions, so that we'll know
417  *      when a particular old transaction is no longer in use. Old transactions
418  *      that have discarded any data pages can then have those pages reclaimed
419  *      for use by a later write transaction.
420  *
421  *      The lock table is constructed such that reader slots are aligned with the
422  *      processor's cache line size. Any slot is only ever used by one thread.
423  *      This alignment guarantees that there will be no contention or cache
424  *      thrashing as threads update their own slot info, and also eliminates
425  *      any need for locking when accessing a slot.
426  *
427  *      A writer thread will scan every slot in the table to determine the oldest
428  *      outstanding reader transaction. Any freed pages older than this will be
429  *      reclaimed by the writer. The writer doesn't use any locks when scanning
430  *      this table. This means that there's no guarantee that the writer will
431  *      see the most up-to-date reader info, but that's not required for correct
432  *      operation - all we need is to know the upper bound on the oldest reader,
433  *      we don't care at all about the newest reader. So the only consequence of
434  *      reading stale information here is that old pages might hang around a
435  *      while longer before being reclaimed. That's actually good anyway, because
436  *      the longer we delay reclaiming old pages, the more likely it is that a
437  *      string of contiguous pages can be found after coalescing old pages from
438  *      many old transactions together.
439  *      @{
440  */
441         /**     Number of slots in the reader table.
442          *      This value was chosen somewhat arbitrarily. 126 readers plus a
443          *      couple mutexes fit exactly into 8KB on my development machine.
444          *      Applications should set the table size using #mdb_env_set_maxreaders().
445          */
446 #define DEFAULT_READERS 126
447
448         /**     The size of a CPU cache line in bytes. We want our lock structures
449          *      aligned to this size to avoid false cache line sharing in the
450          *      lock table.
451          *      This value works for most CPUs. For Itanium this should be 128.
452          */
453 #ifndef CACHELINE
454 #define CACHELINE       64
455 #endif
456
457         /**     The information we store in a single slot of the reader table.
458          *      In addition to a transaction ID, we also record the process and
459          *      thread ID that owns a slot, so that we can detect stale information,
460          *      e.g. threads or processes that went away without cleaning up.
461          *      @note We currently don't check for stale records. We simply re-init
462          *      the table when we know that we're the only process opening the
463          *      lock file.
464          */
465 typedef struct MDB_rxbody {
466         /**     Current Transaction ID when this transaction began, or (txnid_t)-1.
467          *      Multiple readers that start at the same time will probably have the
468          *      same ID here. Again, it's not important to exclude them from
469          *      anything; all we need to know is which version of the DB they
470          *      started from so we can avoid overwriting any data used in that
471          *      particular version.
472          */
473         txnid_t         mrb_txnid;
474         /** The process ID of the process owning this reader txn. */
475         pid_t           mrb_pid;
476         /** The thread ID of the thread owning this txn. */
477         pthread_t       mrb_tid;
478 } MDB_rxbody;
479
480         /** The actual reader record, with cacheline padding. */
481 typedef struct MDB_reader {
482         union {
483                 MDB_rxbody mrx;
484                 /** shorthand for mrb_txnid */
485 #define mr_txnid        mru.mrx.mrb_txnid
486 #define mr_pid  mru.mrx.mrb_pid
487 #define mr_tid  mru.mrx.mrb_tid
488                 /** cache line alignment */
489                 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
490         } mru;
491 } MDB_reader;
492
493         /** The header for the reader table.
494          *      The table resides in a memory-mapped file. (This is a different file
495          *      than is used for the main database.)
496          *
497          *      For POSIX the actual mutexes reside in the shared memory of this
498          *      mapped file. On Windows, mutexes are named objects allocated by the
499          *      kernel; we store the mutex names in this mapped file so that other
500          *      processes can grab them. This same approach is also used on
501          *      MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
502          *      process-shared POSIX mutexes. For these cases where a named object
503          *      is used, the object name is derived from a 64 bit FNV hash of the
504          *      environment pathname. As such, naming collisions are extremely
505          *      unlikely. If a collision occurs, the results are unpredictable.
506          */
507 typedef struct MDB_txbody {
508                 /** Stamp identifying this as an MDB file. It must be set
509                  *      to #MDB_MAGIC. */
510         uint32_t        mtb_magic;
511                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
512         uint32_t        mtb_version;
513 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
514         char    mtb_rmname[MNAME_LEN];
515 #else
516                 /** Mutex protecting access to this table.
517                  *      This is the reader lock that #LOCK_MUTEX_R acquires.
518                  */
519         pthread_mutex_t mtb_mutex;
520 #endif
521                 /**     The ID of the last transaction committed to the database.
522                  *      This is recorded here only for convenience; the value can always
523                  *      be determined by reading the main database meta pages.
524                  */
525         txnid_t         mtb_txnid;
526                 /** The number of slots that have been used in the reader table.
527                  *      This always records the maximum count, it is not decremented
528                  *      when readers release their slots.
529                  */
530         unsigned        mtb_numreaders;
531 } MDB_txbody;
532
533         /** The actual reader table definition. */
534 typedef struct MDB_txninfo {
535         union {
536                 MDB_txbody mtb;
537 #define mti_magic       mt1.mtb.mtb_magic
538 #define mti_version     mt1.mtb.mtb_version
539 #define mti_mutex       mt1.mtb.mtb_mutex
540 #define mti_rmname      mt1.mtb.mtb_rmname
541 #define mti_txnid       mt1.mtb.mtb_txnid
542 #define mti_numreaders  mt1.mtb.mtb_numreaders
543                 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
544         } mt1;
545         union {
546 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
547                 char mt2_wmname[MNAME_LEN];
548 #define mti_wmname      mt2.mt2_wmname
549 #else
550                 pthread_mutex_t mt2_wmutex;
551 #define mti_wmutex      mt2.mt2_wmutex
552 #endif
553                 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
554         } mt2;
555         MDB_reader      mti_readers[1];
556 } MDB_txninfo;
557 /** @} */
558
559 /** Common header for all page types.
560  * Overflow records occupy a number of contiguous pages with no
561  * headers on any page after the first.
562  */
563 typedef struct MDB_page {
564 #define mp_pgno mp_p.p_pgno
565 #define mp_next mp_p.p_next
566         union {
567                 pgno_t          p_pgno; /**< page number */
568                 void *          p_next; /**< for in-memory list of freed structs */
569         } mp_p;
570         uint16_t        mp_pad;
571 /**     @defgroup mdb_page      Page Flags
572  *      @ingroup internal
573  *      Flags for the page headers.
574  *      @{
575  */
576 #define P_BRANCH         0x01           /**< branch page */
577 #define P_LEAF           0x02           /**< leaf page */
578 #define P_OVERFLOW       0x04           /**< overflow page */
579 #define P_META           0x08           /**< meta page */
580 #define P_DIRTY          0x10           /**< dirty page */
581 #define P_LEAF2          0x20           /**< for #MDB_DUPFIXED records */
582 #define P_SUBP           0x40           /**< for #MDB_DUPSORT sub-pages */
583 /** @} */
584         uint16_t        mp_flags;               /**< @ref mdb_page */
585 #define mp_lower        mp_pb.pb.pb_lower
586 #define mp_upper        mp_pb.pb.pb_upper
587 #define mp_pages        mp_pb.pb_pages
588         union {
589                 struct {
590                         indx_t          pb_lower;               /**< lower bound of free space */
591                         indx_t          pb_upper;               /**< upper bound of free space */
592                 } pb;
593                 uint32_t        pb_pages;       /**< number of overflow pages */
594         } mp_pb;
595         indx_t          mp_ptrs[1];             /**< dynamic size */
596 } MDB_page;
597
598         /** Size of the page header, excluding dynamic data at the end */
599 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
600
601         /** Address of first usable data byte in a page, after the header */
602 #define METADATA(p)      ((void *)((char *)(p) + PAGEHDRSZ))
603
604         /** Number of nodes on a page */
605 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
606
607         /** The amount of space remaining in the page */
608 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
609
610         /** The percentage of space used in the page, in tenths of a percent. */
611 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
612                                 ((env)->me_psize - PAGEHDRSZ))
613         /** The minimum page fill factor, in tenths of a percent.
614          *      Pages emptier than this are candidates for merging.
615          */
616 #define FILL_THRESHOLD   250
617
618         /** Test if a page is a leaf page */
619 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
620         /** Test if a page is a LEAF2 page */
621 #define IS_LEAF2(p)      F_ISSET((p)->mp_flags, P_LEAF2)
622         /** Test if a page is a branch page */
623 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
624         /** Test if a page is an overflow page */
625 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
626         /** Test if a page is a sub page */
627 #define IS_SUBP(p)       F_ISSET((p)->mp_flags, P_SUBP)
628
629         /** The number of overflow pages needed to store the given size. */
630 #define OVPAGES(size, psize)    ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
631
632         /** Header for a single key/data pair within a page.
633          * We guarantee 2-byte alignment for nodes.
634          */
635 typedef struct MDB_node {
636         /** lo and hi are used for data size on leaf nodes and for
637          * child pgno on branch nodes. On 64 bit platforms, flags
638          * is also used for pgno. (Branch nodes have no flags).
639          * They are in host byte order in case that lets some
640          * accesses be optimized into a 32-bit word access.
641          */
642 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
643 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
644         unsigned short  mn_offset[2];   /**< storage for #mn_lo and #mn_hi */
645 /** @defgroup mdb_node Node Flags
646  *      @ingroup internal
647  *      Flags for node headers.
648  *      @{
649  */
650 #define F_BIGDATA        0x01                   /**< data put on overflow page */
651 #define F_SUBDATA        0x02                   /**< data is a sub-database */
652 #define F_DUPDATA        0x04                   /**< data has duplicates */
653
654 /** valid flags for #mdb_node_add() */
655 #define NODE_ADD_FLAGS  (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
656
657 /** @} */
658         unsigned short  mn_flags;               /**< @ref mdb_node */
659         unsigned short  mn_ksize;               /**< key size */
660         char            mn_data[1];                     /**< key and data are appended here */
661 } MDB_node;
662
663         /** Size of the node header, excluding dynamic data at the end */
664 #define NODESIZE         offsetof(MDB_node, mn_data)
665
666         /** Bit position of top word in page number, for shifting mn_flags */
667 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
668
669         /** Size of a node in a branch page with a given key.
670          *      This is just the node header plus the key, there is no data.
671          */
672 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
673
674         /** Size of a node in a leaf page with a given key and data.
675          *      This is node header plus key plus data size.
676          */
677 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
678
679         /** Address of node \b i in page \b p */
680 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
681
682         /** Address of the key for the node */
683 #define NODEKEY(node)    (void *)((node)->mn_data)
684
685         /** Address of the data for a node */
686 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
687
688         /** Get the page number pointed to by a branch node */
689 #define NODEPGNO(node) \
690         ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
691          (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
692         /** Set the page number in a branch node */
693 #define SETPGNO(node,pgno)      do { \
694         (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
695         if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
696
697         /** Get the size of the data in a leaf node */
698 #define NODEDSZ(node)    ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
699         /** Set the size of the data for a leaf node */
700 #define SETDSZ(node,size)       do { \
701         (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
702         /** The size of a key in a node */
703 #define NODEKSZ(node)    ((node)->mn_ksize)
704
705         /** Copy a page number from src to dst */
706 #ifdef MISALIGNED_OK
707 #define COPY_PGNO(dst,src)      dst = src
708 #else
709 #if SIZE_MAX > 4294967295UL
710 #define COPY_PGNO(dst,src)      do { \
711         unsigned short *s, *d;  \
712         s = (unsigned short *)&(src);   \
713         d = (unsigned short *)&(dst);   \
714         *d++ = *s++;    \
715         *d++ = *s++;    \
716         *d++ = *s++;    \
717         *d = *s;        \
718 } while (0)
719 #else
720 #define COPY_PGNO(dst,src)      do { \
721         unsigned short *s, *d;  \
722         s = (unsigned short *)&(src);   \
723         d = (unsigned short *)&(dst);   \
724         *d++ = *s++;    \
725         *d = *s;        \
726 } while (0)
727 #endif
728 #endif
729         /** The address of a key in a LEAF2 page.
730          *      LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
731          *      There are no node headers, keys are stored contiguously.
732          */
733 #define LEAF2KEY(p, i, ks)      ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
734
735         /** Set the \b node's key into \b key, if requested. */
736 #define MDB_GET_KEY(node, key)  { if ((key) != NULL) { \
737         (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
738
739         /** Information about a single database in the environment. */
740 typedef struct MDB_db {
741         uint32_t        md_pad;         /**< also ksize for LEAF2 pages */
742         uint16_t        md_flags;       /**< @ref mdb_dbi_open */
743         uint16_t        md_depth;       /**< depth of this tree */
744         pgno_t          md_branch_pages;        /**< number of internal pages */
745         pgno_t          md_leaf_pages;          /**< number of leaf pages */
746         pgno_t          md_overflow_pages;      /**< number of overflow pages */
747         size_t          md_entries;             /**< number of data items */
748         pgno_t          md_root;                /**< the root page of this tree */
749 } MDB_db;
750
751         /** mdb_dbi_open flags */
752 #define MDB_VALID       0x8000          /**< DB handle is valid, for me_dbflags */
753 #define PERSISTENT_FLAGS        (0xffff & ~(MDB_VALID))
754 #define VALID_FLAGS     (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
755         MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
756
757         /** Handle for the DB used to track free pages. */
758 #define FREE_DBI        0
759         /** Handle for the default DB. */
760 #define MAIN_DBI        1
761
762         /** Meta page content. */
763 typedef struct MDB_meta {
764                 /** Stamp identifying this as an MDB file. It must be set
765                  *      to #MDB_MAGIC. */
766         uint32_t        mm_magic;
767                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
768         uint32_t        mm_version;
769         void            *mm_address;            /**< address for fixed mapping */
770         size_t          mm_mapsize;                     /**< size of mmap region */
771         MDB_db          mm_dbs[2];                      /**< first is free space, 2nd is main db */
772         /** The size of pages used in this DB */
773 #define mm_psize        mm_dbs[0].md_pad
774         /** Any persistent environment flags. @ref mdb_env */
775 #define mm_flags        mm_dbs[0].md_flags
776         pgno_t          mm_last_pg;                     /**< last used page in file */
777         txnid_t         mm_txnid;                       /**< txnid that committed this page */
778 } MDB_meta;
779
780         /** Buffer for a stack-allocated dirty page.
781          *      The members define size and alignment, and silence type
782          *      aliasing warnings.  They are not used directly; that could
783          *      mean incorrectly using several union members in parallel.
784          */
785 typedef union MDB_pagebuf {
786         char            mb_raw[MDB_PAGESIZE];
787         MDB_page        mb_page;
788         struct {
789                 char            mm_pad[PAGEHDRSZ];
790                 MDB_meta        mm_meta;
791         } mb_metabuf;
792 } MDB_pagebuf;
793
794         /** Auxiliary DB info.
795          *      The information here is mostly static/read-only. There is
796          *      only a single copy of this record in the environment.
797          */
798 typedef struct MDB_dbx {
799         MDB_val         md_name;                /**< name of the database */
800         MDB_cmp_func    *md_cmp;        /**< function for comparing keys */
801         MDB_cmp_func    *md_dcmp;       /**< function for comparing data items */
802         MDB_rel_func    *md_rel;        /**< user relocate function */
803         void            *md_relctx;             /**< user-provided context for md_rel */
804 } MDB_dbx;
805
806         /** A database transaction.
807          *      Every operation requires a transaction handle.
808          */
809 struct MDB_txn {
810         MDB_txn         *mt_parent;             /**< parent of a nested txn */
811         MDB_txn         *mt_child;              /**< nested txn under this txn */
812         pgno_t          mt_next_pgno;   /**< next unallocated page */
813         /** The ID of this transaction. IDs are integers incrementing from 1.
814          *      Only committed write transactions increment the ID. If a transaction
815          *      aborts, the ID may be re-used by the next writer.
816          */
817         txnid_t         mt_txnid;
818         MDB_env         *mt_env;                /**< the DB environment */
819         /** The list of pages that became unused during this transaction.
820          */
821         MDB_IDL         mt_free_pgs;
822         union {
823                 MDB_ID2L        dirty_list;     /**< for write txns: modified pages */
824                 MDB_reader      *reader;        /**< this thread's reader table slot or NULL */
825         } mt_u;
826         /** Array of records for each DB known in the environment. */
827         MDB_dbx         *mt_dbxs;
828         /** Array of MDB_db records for each known DB */
829         MDB_db          *mt_dbs;
830 /** @defgroup mt_dbflag Transaction DB Flags
831  *      @ingroup internal
832  * @{
833  */
834 #define DB_DIRTY        0x01            /**< DB was written in this txn */
835 #define DB_STALE        0x02            /**< DB record is older than txnID */
836 #define DB_NEW          0x04            /**< DB handle opened in this txn */
837 #define DB_VALID        0x08            /**< DB handle is valid, see also #MDB_VALID */
838 /** @} */
839         /** In write txns, array of cursors for each DB */
840         MDB_cursor      **mt_cursors;
841         /** Array of flags for each DB */
842         unsigned char   *mt_dbflags;
843         /**     Number of DB records in use. This number only ever increments;
844          *      we don't decrement it when individual DB handles are closed.
845          */
846         MDB_dbi         mt_numdbs;
847
848 /** @defgroup mdb_txn   Transaction Flags
849  *      @ingroup internal
850  *      @{
851  */
852 #define MDB_TXN_RDONLY          0x01            /**< read-only transaction */
853 #define MDB_TXN_ERROR           0x02            /**< an error has occurred */
854 #define MDB_TXN_DIRTY           0x04            /**< must write, even if dirty list is empty */
855 /** @} */
856         unsigned int    mt_flags;               /**< @ref mdb_txn */
857         /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
858         unsigned int    mt_dirty_room;
859         /** Tracks which of the two meta pages was used at the start
860          *      of this transaction.
861          */
862         unsigned int    mt_toggle;
863 };
864
865 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
866  * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
867  * raise this on a 64 bit machine.
868  */
869 #define CURSOR_STACK             32
870
871 struct MDB_xcursor;
872
873         /** Cursors are used for all DB operations */
874 struct MDB_cursor {
875         /** Next cursor on this DB in this txn */
876         MDB_cursor      *mc_next;
877         /** Original cursor if this is a shadow */
878         MDB_cursor      *mc_orig;
879         /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
880         struct MDB_xcursor      *mc_xcursor;
881         /** The transaction that owns this cursor */
882         MDB_txn         *mc_txn;
883         /** The database handle this cursor operates on */
884         MDB_dbi         mc_dbi;
885         /** The database record for this cursor */
886         MDB_db          *mc_db;
887         /** The database auxiliary record for this cursor */
888         MDB_dbx         *mc_dbx;
889         /** The @ref mt_dbflag for this database */
890         unsigned char   *mc_dbflag;
891         unsigned short  mc_snum;        /**< number of pushed pages */
892         unsigned short  mc_top;         /**< index of top page, normally mc_snum-1 */
893 /** @defgroup mdb_cursor        Cursor Flags
894  *      @ingroup internal
895  *      Cursor state flags.
896  *      @{
897  */
898 #define C_INITIALIZED   0x01    /**< cursor has been initialized and is valid */
899 #define C_EOF   0x02                    /**< No more data */
900 #define C_SUB   0x04                    /**< Cursor is a sub-cursor */
901 #define C_SHADOW        0x08            /**< Cursor is a dup from a parent txn */
902 #define C_ALLOCD        0x10            /**< Cursor was malloc'd */
903 #define C_SPLITTING     0x20            /**< Cursor is in page_split */
904 #define C_UNTRACK       0x40            /**< Un-track cursor when closing */
905 /** @} */
906         unsigned int    mc_flags;       /**< @ref mdb_cursor */
907         MDB_page        *mc_pg[CURSOR_STACK];   /**< stack of pushed pages */
908         indx_t          mc_ki[CURSOR_STACK];    /**< stack of page indices */
909 };
910
911         /** Context for sorted-dup records.
912          *      We could have gone to a fully recursive design, with arbitrarily
913          *      deep nesting of sub-databases. But for now we only handle these
914          *      levels - main DB, optional sub-DB, sorted-duplicate DB.
915          */
916 typedef struct MDB_xcursor {
917         /** A sub-cursor for traversing the Dup DB */
918         MDB_cursor mx_cursor;
919         /** The database record for this Dup DB */
920         MDB_db  mx_db;
921         /**     The auxiliary DB record for this Dup DB */
922         MDB_dbx mx_dbx;
923         /** The @ref mt_dbflag for this Dup DB */
924         unsigned char mx_dbflag;
925 } MDB_xcursor;
926
927         /** State of FreeDB old pages, stored in the MDB_env */
928 typedef struct MDB_pgstate {
929         txnid_t         mf_pglast;      /**< ID of last old page record we used */
930         pgno_t          *mf_pghead;     /**< old pages reclaimed from freelist */
931         pgno_t          *mf_pgfree;     /**< memory to free when dropping me_pghead */
932 } MDB_pgstate;
933
934         /** The database environment. */
935 struct MDB_env {
936         HANDLE          me_fd;          /**< The main data file */
937         HANDLE          me_lfd;         /**< The lock file */
938         HANDLE          me_mfd;                 /**< just for writing the meta pages */
939         /** Failed to update the meta page. Probably an I/O error. */
940 #define MDB_FATAL_ERROR 0x80000000U
941         /** Some fields are initialized. */
942 #define MDB_ENV_ACTIVE  0x20000000U
943         /** me_txkey is set */
944 #define MDB_ENV_TXKEY   0x10000000U
945         uint32_t        me_flags;               /**< @ref mdb_env */
946         unsigned int    me_psize;       /**< size of a page, from #GET_PAGESIZE */
947         unsigned int    me_maxreaders;  /**< size of the reader table */
948         unsigned int    me_numreaders;  /**< max numreaders set by this env */
949         MDB_dbi         me_numdbs;              /**< number of DBs opened */
950         MDB_dbi         me_maxdbs;              /**< size of the DB table */
951         pid_t           me_pid;         /**< process ID of this env */
952         char            *me_path;               /**< path to the DB files */
953         char            *me_map;                /**< the memory map of the data file */
954         MDB_txninfo     *me_txns;               /**< the memory map of the lock file or NULL */
955         MDB_meta        *me_metas[2];   /**< pointers to the two meta pages */
956         MDB_txn         *me_txn;                /**< current write transaction */
957         size_t          me_mapsize;             /**< size of the data memory map */
958         off_t           me_size;                /**< current file size */
959         pgno_t          me_maxpg;               /**< me_mapsize / me_psize */
960         MDB_dbx         *me_dbxs;               /**< array of static DB info */
961         uint16_t        *me_dbflags;    /**< array of flags from MDB_db.md_flags */
962         pthread_key_t   me_txkey;       /**< thread-key for readers */
963         MDB_pgstate     me_pgstate;             /**< state of old pages from freeDB */
964 #       define          me_pglast       me_pgstate.mf_pglast
965 #       define          me_pghead       me_pgstate.mf_pghead
966 #       define          me_pgfree       me_pgstate.mf_pgfree
967         MDB_page        *me_dpages;             /**< list of malloc'd blocks for re-use */
968         /** IDL of pages that became unused in a write txn */
969         MDB_IDL         me_free_pgs;
970         /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
971         MDB_ID2L        me_dirty_list;
972         /** Max number of freelist items that can fit in a single overflow page */
973         unsigned int    me_maxfree_1pg;
974         /** Max size of a node on a page */
975         unsigned int    me_nodemax;
976 #ifdef _WIN32
977         HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
978         HANDLE          me_wmutex;
979 #elif defined(MDB_USE_POSIX_SEM)
980         sem_t           *me_rmutex;             /* Shared mutexes are not supported */
981         sem_t           *me_wmutex;
982 #endif
983 };
984
985         /** Nested transaction */
986 typedef struct MDB_ntxn {
987         MDB_txn         mnt_txn;                /* the transaction */
988         MDB_pgstate     mnt_pgstate;    /* parent transaction's saved freestate */
989 } MDB_ntxn;
990
991         /** max number of pages to commit in one writev() call */
992 #define MDB_COMMIT_PAGES         64
993 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
994 #undef MDB_COMMIT_PAGES
995 #define MDB_COMMIT_PAGES        IOV_MAX
996 #endif
997
998 static int  mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
999 static int  mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1000 static int  mdb_page_touch(MDB_cursor *mc);
1001
1002 static int  mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1003 static int  mdb_page_search_root(MDB_cursor *mc,
1004                             MDB_val *key, int modify);
1005 #define MDB_PS_MODIFY   1
1006 #define MDB_PS_ROOTONLY 2
1007 static int  mdb_page_search(MDB_cursor *mc,
1008                             MDB_val *key, int flags);
1009 static int      mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1010
1011 #define MDB_SPLIT_REPLACE       MDB_APPENDDUP   /**< newkey is not new */
1012 static int      mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1013                                 pgno_t newpgno, unsigned int nflags);
1014
1015 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1016 static int  mdb_env_pick_meta(const MDB_env *env);
1017 static int  mdb_env_write_meta(MDB_txn *txn);
1018 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1019 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1020 #endif
1021 static void mdb_env_close0(MDB_env *env, int excl);
1022
1023 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1024 static int  mdb_node_add(MDB_cursor *mc, indx_t indx,
1025                             MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1026 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1027 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1028 static int      mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1029 static int  mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1030 static size_t   mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1031 static size_t   mdb_branch_size(MDB_env *env, MDB_val *key);
1032
1033 static int      mdb_rebalance(MDB_cursor *mc);
1034 static int      mdb_update_key(MDB_cursor *mc, MDB_val *key);
1035
1036 static void     mdb_cursor_pop(MDB_cursor *mc);
1037 static int      mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1038
1039 static int      mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1040 static int      mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1041 static int      mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1042 static int      mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1043 static int      mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1044                                 int *exactp);
1045 static int      mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1046 static int      mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1047
1048 static void     mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1049 static void     mdb_xcursor_init0(MDB_cursor *mc);
1050 static void     mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1051
1052 static int      mdb_drop0(MDB_cursor *mc, int subs);
1053 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1054
1055 /** @cond */
1056 static MDB_cmp_func     mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1057 /** @endcond */
1058
1059 #ifdef _WIN32
1060 static SECURITY_DESCRIPTOR mdb_null_sd;
1061 static SECURITY_ATTRIBUTES mdb_all_sa;
1062 static int mdb_sec_inited;
1063 #endif
1064
1065 /** Return the library version info. */
1066 char *
1067 mdb_version(int *major, int *minor, int *patch)
1068 {
1069         if (major) *major = MDB_VERSION_MAJOR;
1070         if (minor) *minor = MDB_VERSION_MINOR;
1071         if (patch) *patch = MDB_VERSION_PATCH;
1072         return MDB_VERSION_STRING;
1073 }
1074
1075 /** Table of descriptions for MDB @ref errors */
1076 static char *const mdb_errstr[] = {
1077         "MDB_KEYEXIST: Key/data pair already exists",
1078         "MDB_NOTFOUND: No matching key/data pair found",
1079         "MDB_PAGE_NOTFOUND: Requested page not found",
1080         "MDB_CORRUPTED: Located page was wrong type",
1081         "MDB_PANIC: Update of meta page failed",
1082         "MDB_VERSION_MISMATCH: Database environment version mismatch",
1083         "MDB_INVALID: File is not an MDB file",
1084         "MDB_MAP_FULL: Environment mapsize limit reached",
1085         "MDB_DBS_FULL: Environment maxdbs limit reached",
1086         "MDB_READERS_FULL: Environment maxreaders limit reached",
1087         "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1088         "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1089         "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1090         "MDB_PAGE_FULL: Internal error - page has no more space",
1091         "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1092         "MDB_INCOMPATIBLE: Database flags changed or would change",
1093         "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1094 };
1095
1096 char *
1097 mdb_strerror(int err)
1098 {
1099         int i;
1100         if (!err)
1101                 return ("Successful return: 0");
1102
1103         if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1104                 i = err - MDB_KEYEXIST;
1105                 return mdb_errstr[i];
1106         }
1107
1108         return strerror(err);
1109 }
1110
1111 #if MDB_DEBUG
1112 /** Display a key in hexadecimal and return the address of the result.
1113  * @param[in] key the key to display
1114  * @param[in] buf the buffer to write into. Should always be #DKBUF.
1115  * @return The key in hexadecimal form.
1116  */
1117 char *
1118 mdb_dkey(MDB_val *key, char *buf)
1119 {
1120         char *ptr = buf;
1121         unsigned char *c = key->mv_data;
1122         unsigned int i;
1123
1124         if (!key)
1125                 return "";
1126
1127         if (key->mv_size > MDB_MAXKEYSIZE)
1128                 return "MDB_MAXKEYSIZE";
1129         /* may want to make this a dynamic check: if the key is mostly
1130          * printable characters, print it as-is instead of converting to hex.
1131          */
1132 #if 1
1133         buf[0] = '\0';
1134         for (i=0; i<key->mv_size; i++)
1135                 ptr += sprintf(ptr, "%02x", *c++);
1136 #else
1137         sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1138 #endif
1139         return buf;
1140 }
1141
1142 /** Display all the keys in the page. */
1143 void
1144 mdb_page_list(MDB_page *mp)
1145 {
1146         MDB_node *node;
1147         unsigned int i, nkeys, nsize;
1148         MDB_val key;
1149         DKBUF;
1150
1151         nkeys = NUMKEYS(mp);
1152         fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
1153         for (i=0; i<nkeys; i++) {
1154                 node = NODEPTR(mp, i);
1155                 key.mv_size = node->mn_ksize;
1156                 key.mv_data = node->mn_data;
1157                 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1158                 if (IS_BRANCH(mp)) {
1159                         fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
1160                                 DKEY(&key));
1161                 } else {
1162                         if (F_ISSET(node->mn_flags, F_BIGDATA))
1163                                 nsize += sizeof(pgno_t);
1164                         else
1165                                 nsize += NODEDSZ(node);
1166                         fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1167                 }
1168         }
1169 }
1170
1171 void
1172 mdb_cursor_chk(MDB_cursor *mc)
1173 {
1174         unsigned int i;
1175         MDB_node *node;
1176         MDB_page *mp;
1177
1178         if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1179         for (i=0; i<mc->mc_top; i++) {
1180                 mp = mc->mc_pg[i];
1181                 node = NODEPTR(mp, mc->mc_ki[i]);
1182                 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1183                         printf("oops!\n");
1184         }
1185         if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1186                 printf("ack!\n");
1187 }
1188 #endif
1189
1190 #if MDB_DEBUG > 2
1191 /** Count all the pages in each DB and in the freelist
1192  *  and make sure it matches the actual number of pages
1193  *  being used.
1194  */
1195 static void mdb_audit(MDB_txn *txn)
1196 {
1197         MDB_cursor mc;
1198         MDB_val key, data;
1199         MDB_ID freecount, count;
1200         MDB_dbi i;
1201         int rc;
1202
1203         freecount = 0;
1204         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1205         while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1206                 freecount += *(MDB_ID *)data.mv_data;
1207
1208         count = 0;
1209         for (i = 0; i<txn->mt_numdbs; i++) {
1210                 MDB_xcursor mx;
1211                 mdb_cursor_init(&mc, txn, i, &mx);
1212                 if (txn->mt_dbs[i].md_root == P_INVALID)
1213                         continue;
1214                 count += txn->mt_dbs[i].md_branch_pages +
1215                         txn->mt_dbs[i].md_leaf_pages +
1216                         txn->mt_dbs[i].md_overflow_pages;
1217                 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1218                         mdb_page_search(&mc, NULL, 0);
1219                         do {
1220                                 unsigned j;
1221                                 MDB_page *mp;
1222                                 mp = mc.mc_pg[mc.mc_top];
1223                                 for (j=0; j<NUMKEYS(mp); j++) {
1224                                         MDB_node *leaf = NODEPTR(mp, j);
1225                                         if (leaf->mn_flags & F_SUBDATA) {
1226                                                 MDB_db db;
1227                                                 memcpy(&db, NODEDATA(leaf), sizeof(db));
1228                                                 count += db.md_branch_pages + db.md_leaf_pages +
1229                                                         db.md_overflow_pages;
1230                                         }
1231                                 }
1232                         }
1233                         while (mdb_cursor_sibling(&mc, 1) == 0);
1234                 }
1235         }
1236         if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1237                 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1238                         txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1239         }
1240 }
1241 #endif
1242
1243 int
1244 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1245 {
1246         return txn->mt_dbxs[dbi].md_cmp(a, b);
1247 }
1248
1249 int
1250 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1251 {
1252         return txn->mt_dbxs[dbi].md_dcmp(a, b);
1253 }
1254
1255 /** Allocate a page.
1256  * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1257  */
1258 static MDB_page *
1259 mdb_page_malloc(MDB_cursor *mc, unsigned num)
1260 {
1261         MDB_env *env = mc->mc_txn->mt_env;
1262         MDB_page *ret = env->me_dpages;
1263         size_t sz = env->me_psize;
1264         if (num == 1) {
1265                 if (ret) {
1266                         VGMEMP_ALLOC(env, ret, sz);
1267                         VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1268                         env->me_dpages = ret->mp_next;
1269                         return ret;
1270                 }
1271         } else {
1272                 sz *= num;
1273         }
1274         if ((ret = malloc(sz)) != NULL) {
1275                 VGMEMP_ALLOC(env, ret, sz);
1276         }
1277         return ret;
1278 }
1279
1280 /** Free a single page.
1281  * Saves single pages to a list, for future reuse.
1282  * (This is not used for multi-page overflow pages.)
1283  */
1284 static void
1285 mdb_page_free(MDB_env *env, MDB_page *mp)
1286 {
1287         mp->mp_next = env->me_dpages;
1288         VGMEMP_FREE(env, mp);
1289         env->me_dpages = mp;
1290 }
1291
1292 /* Return all dirty pages to dpage list */
1293 static void
1294 mdb_dlist_free(MDB_txn *txn)
1295 {
1296         MDB_env *env = txn->mt_env;
1297         MDB_ID2L dl = txn->mt_u.dirty_list;
1298         unsigned i, n = dl[0].mid;
1299
1300         for (i = 1; i <= n; i++) {
1301                 MDB_page *dp = dl[i].mptr;
1302                 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1303                         mdb_page_free(env, dp);
1304                 } else {
1305                         /* large pages just get freed directly */
1306                         VGMEMP_FREE(env, dp);
1307                         free(dp);
1308                 }
1309         }
1310         dl[0].mid = 0;
1311 }
1312
1313 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1314 static txnid_t
1315 mdb_find_oldest(MDB_txn *txn)
1316 {
1317         int i;
1318         txnid_t mr, oldest = txn->mt_txnid - 1;
1319         MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1320         for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1321                 if (r[i].mr_pid) {
1322                         mr = r[i].mr_txnid;
1323                         if (oldest > mr)
1324                                 oldest = mr;
1325                 }
1326         }
1327         return oldest;
1328 }
1329
1330 /** Allocate pages for writing.
1331  * If there are free pages available from older transactions, they
1332  * will be re-used first. Otherwise a new page will be allocated.
1333  * @param[in] mc cursor A cursor handle identifying the transaction and
1334  *      database for which we are allocating.
1335  * @param[in] num the number of pages to allocate.
1336  * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1337  *  will always be satisfied by a single contiguous chunk of memory.
1338  * @return 0 on success, non-zero on failure.
1339  */
1340 static int
1341 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1342 {
1343         MDB_txn *txn = mc->mc_txn;
1344         MDB_page *np;
1345         pgno_t pgno = P_INVALID;
1346         MDB_ID2 mid;
1347         txnid_t oldest = 0, last;
1348         int rc;
1349
1350         *mp = NULL;
1351
1352         /* If our dirty list is already full, we can't do anything */
1353         if (txn->mt_dirty_room == 0)
1354                 return MDB_TXN_FULL;
1355
1356         /* The free list won't have any content at all until txn 2 has
1357          * committed. The pages freed by txn 2 will be unreferenced
1358          * after txn 3 commits, and so will be safe to re-use in txn 4.
1359          */
1360         if (txn->mt_txnid > 3) {
1361                 if (!txn->mt_env->me_pghead &&
1362                         txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1363                         /* See if there's anything in the free DB */
1364                         MDB_cursor m2;
1365                         MDB_node *leaf;
1366                         MDB_val data;
1367                         txnid_t *kptr;
1368
1369                         mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1370                         if (!txn->mt_env->me_pglast) {
1371                                 mdb_page_search(&m2, NULL, 0);
1372                                 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1373                                 kptr = (txnid_t *)NODEKEY(leaf);
1374                                 last = *kptr;
1375                         } else {
1376                                 MDB_val key;
1377 again:
1378                                 last = txn->mt_env->me_pglast + 1;
1379                                 leaf = NULL;
1380                                 key.mv_data = &last;
1381                                 key.mv_size = sizeof(last);
1382                                 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET_RANGE, NULL);
1383                                 if (rc)
1384                                         goto none;
1385                                 last = *(txnid_t *)key.mv_data;
1386                         }
1387
1388                         if (!oldest)
1389                                 oldest = mdb_find_oldest(txn);
1390
1391                         if (oldest > last) {
1392                                 /* It's usable, grab it.
1393                                  */
1394                                 pgno_t *idl, *mop;
1395
1396                                 if (!txn->mt_env->me_pglast) {
1397                                         mdb_node_read(txn, leaf, &data);
1398                                 }
1399                                 idl = (MDB_ID *) data.mv_data;
1400                                 /* We might have a zero-length IDL due to freelist growth
1401                                  * during a prior commit
1402                                  */
1403                                 if (!idl[0]) {
1404                                         txn->mt_env->me_pglast = last;
1405                                         goto again;
1406                                 }
1407                                 mop = malloc(MDB_IDL_SIZEOF(idl));
1408                                 if (!mop)
1409                                         return ENOMEM;
1410                                 txn->mt_env->me_pglast = last;
1411                                 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = mop;
1412                                 memcpy(mop, idl, MDB_IDL_SIZEOF(idl));
1413
1414 #if MDB_DEBUG > 1
1415                                 {
1416                                         unsigned int i;
1417                                         DPRINTF("IDL read txn %zu root %zu num %zu",
1418                                                 last, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1419                                         for (i=0; i<idl[0]; i++) {
1420                                                 DPRINTF("IDL %zu", idl[i+1]);
1421                                         }
1422                                 }
1423 #endif
1424                         }
1425                 }
1426 none:
1427                 if (txn->mt_env->me_pghead) {
1428                         pgno_t *mop = txn->mt_env->me_pghead;
1429                         if (num > 1) {
1430                                 MDB_cursor m2;
1431                                 int retry = 1, readit = 0, n2 = num-1;
1432                                 unsigned int i, j, k;
1433
1434                                 /* If current list is too short, must fetch more and coalesce */
1435                                 if (mop[0] < (unsigned)num)
1436                                         readit = 1;
1437
1438                                 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1439                                 do {
1440 #ifdef MDB_PARANOID     /* Seems like we can ignore this now */
1441                                         /* If on freelist, don't try to read more. If what we have
1442                                          * right now isn't enough just use new pages.
1443                                          * TODO: get all of this working. Many circular dependencies...
1444                                          */
1445                                         if (mc->mc_dbi == FREE_DBI) {
1446                                                 retry = 0;
1447                                                 readit = 0;
1448                                         }
1449 #endif
1450                                         if (readit) {
1451                                                 MDB_val key, data;
1452                                                 pgno_t *idl, *mop2;
1453
1454                                                 last = txn->mt_env->me_pglast + 1;
1455
1456                                                 /* We haven't hit the readers list yet? */
1457                                                 if (!oldest) {
1458                                                         oldest = mdb_find_oldest(txn);
1459                                                 }
1460
1461                                                 /* There's nothing we can use on the freelist */
1462                                                 if (oldest - last < 1)
1463                                                         break;
1464
1465                                                 key.mv_data = &last;
1466                                                 key.mv_size = sizeof(last);
1467                                                 rc = mdb_cursor_set(&m2,&key,&data,MDB_SET_RANGE,NULL);
1468                                                 if (rc) {
1469                                                         if (rc == MDB_NOTFOUND)
1470                                                                 break;
1471                                                         return rc;
1472                                                 }
1473                                                 last = *(txnid_t*)key.mv_data;
1474                                                 if (oldest <= last)
1475                                                         break;
1476                                                 idl = (MDB_ID *) data.mv_data;
1477                                                 mop2 = malloc(MDB_IDL_SIZEOF(idl) + MDB_IDL_SIZEOF(mop));
1478                                                 if (!mop2)
1479                                                         return ENOMEM;
1480                                                 /* merge in sorted order */
1481                                                 i = idl[0]; j = mop[0]; mop2[0] = k = i+j;
1482                                                 mop[0] = P_INVALID;
1483                                                 while (i>0  || j>0) {
1484                                                         if (i && idl[i] < mop[j])
1485                                                                 mop2[k--] = idl[i--];
1486                                                         else
1487                                                                 mop2[k--] = mop[j--];
1488                                                 }
1489                                                 txn->mt_env->me_pglast = last;
1490                                                 free(txn->mt_env->me_pgfree);
1491                                                 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = mop2;
1492                                                 mop = mop2;
1493                                                 /* Keep trying to read until we have enough */
1494                                                 if (mop[0] < (unsigned)num) {
1495                                                         continue;
1496                                                 }
1497                                         }
1498
1499                                         /* current list has enough pages, but are they contiguous? */
1500                                         for (i=mop[0]; i>=(unsigned)num; i--) {
1501                                                 if (mop[i-n2] == mop[i] + n2) {
1502                                                         pgno = mop[i];
1503                                                         i -= n2;
1504                                                         /* move any stragglers down */
1505                                                         for (j=i+num; j<=mop[0]; j++)
1506                                                                 mop[i++] = mop[j];
1507                                                         mop[0] -= num;
1508                                                         break;
1509                                                 }
1510                                         }
1511
1512                                         /* Stop if we succeeded, or no retries */
1513                                         if (!retry || pgno != P_INVALID)
1514                                                 break;
1515                                         readit = 1;
1516
1517                                 } while (1);
1518                         } else {
1519                                 /* peel pages off tail, so we only have to truncate the list */
1520                                 pgno = MDB_IDL_LAST(mop);
1521                                 mop[0]--;
1522                         }
1523                         if (MDB_IDL_IS_ZERO(mop)) {
1524                                 free(txn->mt_env->me_pgfree);
1525                                 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = NULL;
1526                         }
1527                 }
1528         }
1529
1530         if (pgno == P_INVALID) {
1531                 /* DB size is maxed out */
1532                 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1533                         DPUTS("DB size maxed out");
1534                         return MDB_MAP_FULL;
1535                 }
1536         }
1537         if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1538                 if (pgno == P_INVALID) {
1539                         pgno = txn->mt_next_pgno;
1540                         txn->mt_next_pgno += num;
1541                 }
1542                 np = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1543                 np->mp_pgno = pgno;
1544         } else {
1545                 if (!(np = mdb_page_malloc(mc, num)))
1546                         return ENOMEM;
1547                 if (pgno == P_INVALID) {
1548                         np->mp_pgno = txn->mt_next_pgno;
1549                         txn->mt_next_pgno += num;
1550                 } else {
1551                         np->mp_pgno = pgno;
1552                 }
1553         }
1554         mid.mid = np->mp_pgno;
1555         mid.mptr = np;
1556         if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1557                 mdb_mid2l_append(txn->mt_u.dirty_list, &mid);
1558         } else {
1559                 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1560         }
1561         txn->mt_dirty_room--;
1562         *mp = np;
1563
1564         return MDB_SUCCESS;
1565 }
1566
1567 /** Copy a page: avoid copying unused portions of the page.
1568  * @param[in] dst page to copy into
1569  * @param[in] src page to copy from
1570  * @param[in] psize size of a page
1571  */
1572 static void
1573 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1574 {
1575         dst->mp_flags = src->mp_flags | P_DIRTY;
1576         dst->mp_pages = src->mp_pages;
1577
1578         if (IS_LEAF2(src)) {
1579                 memcpy(dst->mp_ptrs, src->mp_ptrs, psize - PAGEHDRSZ - SIZELEFT(src));
1580         } else {
1581                 unsigned int i, nkeys = NUMKEYS(src);
1582                 for (i=0; i<nkeys; i++)
1583                         dst->mp_ptrs[i] = src->mp_ptrs[i];
1584                 memcpy((char *)dst+src->mp_upper, (char *)src+src->mp_upper,
1585                         psize - src->mp_upper);
1586         }
1587 }
1588
1589 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1590  * @param[in] mc cursor pointing to the page to be touched
1591  * @return 0 on success, non-zero on failure.
1592  */
1593 static int
1594 mdb_page_touch(MDB_cursor *mc)
1595 {
1596         MDB_page *mp = mc->mc_pg[mc->mc_top];
1597         pgno_t  pgno;
1598         int rc;
1599
1600         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1601                 MDB_page *np;
1602                 if ((rc = mdb_page_alloc(mc, 1, &np)))
1603                         return rc;
1604                 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1605                 assert(mp->mp_pgno != np->mp_pgno);
1606                 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1607                 if (SIZELEFT(mp)) {
1608                         /* If page isn't full, just copy the used portion */
1609                         mdb_page_copy(np, mp, mc->mc_txn->mt_env->me_psize);
1610                 } else {
1611                         pgno = np->mp_pgno;
1612                         memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1613                         np->mp_pgno = pgno;
1614                         np->mp_flags |= P_DIRTY;
1615                 }
1616                 mp = np;
1617
1618 finish:
1619                 /* Adjust other cursors pointing to mp */
1620                 if (mc->mc_flags & C_SUB) {
1621                         MDB_cursor *m2, *m3;
1622                         MDB_dbi dbi = mc->mc_dbi-1;
1623
1624                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1625                                 if (m2 == mc) continue;
1626                                 m3 = &m2->mc_xcursor->mx_cursor;
1627                                 if (m3->mc_snum < mc->mc_snum) continue;
1628                                 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1629                                         m3->mc_pg[mc->mc_top] = mp;
1630                                 }
1631                         }
1632                 } else {
1633                         MDB_cursor *m2;
1634
1635                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1636                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1637                                 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1638                                         m2->mc_pg[mc->mc_top] = mp;
1639                                         if (mc->mc_db->md_flags & MDB_DUPSORT)
1640                                                 m2->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
1641                                 }
1642                         }
1643                 }
1644                 mc->mc_pg[mc->mc_top] = mp;
1645                 /** If this page has a parent, update the parent to point to
1646                  * this new page.
1647                  */
1648                 if (mc->mc_top)
1649                         SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1650                 else
1651                         mc->mc_db->md_root = mp->mp_pgno;
1652         } else if (mc->mc_txn->mt_parent && !(mp->mp_flags & P_SUBP)) {
1653                 MDB_page *np;
1654                 MDB_ID2 mid, *dl = mc->mc_txn->mt_u.dirty_list;
1655                 /* If txn has a parent, make sure the page is in our
1656                  * dirty list.
1657                  */
1658                 if (dl[0].mid) {
1659                         unsigned x = mdb_mid2l_search(dl, mp->mp_pgno);
1660                         if (x <= dl[0].mid && dl[x].mid == mp->mp_pgno) {
1661                                 np = dl[x].mptr;
1662                                 if (mp != np)
1663                                         mc->mc_pg[mc->mc_top] = np;
1664                                 return 0;
1665                         }
1666                 }
1667                 assert(dl[0].mid < MDB_IDL_UM_MAX);
1668                 /* No - copy it */
1669                 np = mdb_page_malloc(mc, 1);
1670                 if (!np)
1671                         return ENOMEM;
1672                 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1673                 mid.mid = np->mp_pgno;
1674                 mid.mptr = np;
1675                 mdb_mid2l_insert(dl, &mid);
1676                 mp = np;
1677                 goto finish;
1678         }
1679         return 0;
1680 }
1681
1682 int
1683 mdb_env_sync(MDB_env *env, int force)
1684 {
1685         int rc = 0;
1686         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1687                 if (env->me_flags & MDB_WRITEMAP) {
1688                         int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1689                                 ? MS_ASYNC : MS_SYNC;
1690                         if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1691                                 rc = ErrCode();
1692 #ifdef _WIN32
1693                         else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1694                                 rc = ErrCode();
1695 #endif
1696                 } else {
1697                         if (MDB_FDATASYNC(env->me_fd))
1698                                 rc = ErrCode();
1699                 }
1700         }
1701         return rc;
1702 }
1703
1704 /** Make shadow copies of all of parent txn's cursors */
1705 static int
1706 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1707 {
1708         MDB_cursor *mc, *m2;
1709         unsigned int i, j, size;
1710
1711         for (i=0;i<src->mt_numdbs; i++) {
1712                 if (src->mt_cursors[i]) {
1713                         size = sizeof(MDB_cursor);
1714                         if (src->mt_cursors[i]->mc_xcursor)
1715                                 size += sizeof(MDB_xcursor);
1716                         for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1717                                 mc = malloc(size);
1718                                 if (!mc)
1719                                         return ENOMEM;
1720                                 mc->mc_orig = m2;
1721                                 mc->mc_txn = dst;
1722                                 mc->mc_dbi = i;
1723                                 mc->mc_db = &dst->mt_dbs[i];
1724                                 mc->mc_dbx = m2->mc_dbx;
1725                                 mc->mc_dbflag = &dst->mt_dbflags[i];
1726                                 mc->mc_snum = m2->mc_snum;
1727                                 mc->mc_top = m2->mc_top;
1728                                 mc->mc_flags = m2->mc_flags | (C_SHADOW|C_ALLOCD);
1729                                 for (j=0; j<mc->mc_snum; j++) {
1730                                         mc->mc_pg[j] = m2->mc_pg[j];
1731                                         mc->mc_ki[j] = m2->mc_ki[j];
1732                                 }
1733                                 if (m2->mc_xcursor) {
1734                                         MDB_xcursor *mx, *mx2;
1735                                         mx = (MDB_xcursor *)(mc+1);
1736                                         mc->mc_xcursor = mx;
1737                                         mx2 = m2->mc_xcursor;
1738                                         mx->mx_db = mx2->mx_db;
1739                                         mx->mx_dbx = mx2->mx_dbx;
1740                                         mx->mx_dbflag = mx2->mx_dbflag;
1741                                         mx->mx_cursor.mc_txn = dst;
1742                                         mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1743                                         mx->mx_cursor.mc_db = &mx->mx_db;
1744                                         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1745                                         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1746                                         mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1747                                         mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1748                                         mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1749                                         for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1750                                                 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1751                                                 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1752                                         }
1753                                 } else {
1754                                         mc->mc_xcursor = NULL;
1755                                 }
1756                                 mc->mc_next = dst->mt_cursors[i];
1757                                 dst->mt_cursors[i] = mc;
1758                         }
1759                 }
1760         }
1761         return MDB_SUCCESS;
1762 }
1763
1764 /** Close this write txn's cursors, after optionally merging its shadow
1765  * cursors back into parent's.
1766  * @param[in] txn the transaction handle.
1767  * @param[in] merge 0 to not merge cursors, C_SHADOW to merge.
1768  * @return 0 on success, non-zero on failure.
1769  */
1770 static void
1771 mdb_cursors_close(MDB_txn *txn, unsigned merge)
1772 {
1773         MDB_cursor **cursors = txn->mt_cursors, *mc, *next;
1774         int i, j;
1775
1776         for (i = txn->mt_numdbs; --i >= 0; ) {
1777                 for (mc = cursors[i]; mc; mc = next) {
1778                                 next = mc->mc_next;
1779                                 if (mc->mc_flags & merge) {
1780                                         MDB_cursor *m2 = mc->mc_orig;
1781                                         m2->mc_snum = mc->mc_snum;
1782                                         m2->mc_top = mc->mc_top;
1783                                         for (j = mc->mc_snum; --j >= 0; ) {
1784                                                 m2->mc_pg[j] = mc->mc_pg[j];
1785                                                 m2->mc_ki[j] = mc->mc_ki[j];
1786                                         }
1787                                 }
1788                                 if (mc->mc_flags & C_ALLOCD)
1789                                         free(mc);
1790                 }
1791                 cursors[i] = NULL;
1792         }
1793 }
1794
1795 static void
1796 mdb_txn_reset0(MDB_txn *txn);
1797
1798 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1799  * @param[in] txn the transaction handle to initialize
1800  * @return 0 on success, non-zero on failure.
1801  */
1802 static int
1803 mdb_txn_renew0(MDB_txn *txn)
1804 {
1805         MDB_env *env = txn->mt_env;
1806         unsigned int i;
1807         uint16_t x;
1808         int rc, new_notls = 0;
1809
1810         /* Setup db info */
1811         txn->mt_numdbs = env->me_numdbs;
1812         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
1813
1814         if (txn->mt_flags & MDB_TXN_RDONLY) {
1815                 if (!env->me_txns) {
1816                         i = mdb_env_pick_meta(env);
1817                         txn->mt_txnid = env->me_metas[i]->mm_txnid;
1818                         txn->mt_u.reader = NULL;
1819                 } else {
1820                         MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
1821                                 pthread_getspecific(env->me_txkey);
1822                         if (r) {
1823                                 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
1824                                         return MDB_BAD_RSLOT;
1825                         } else {
1826                                 pid_t pid = env->me_pid;
1827                                 pthread_t tid = pthread_self();
1828
1829                                 LOCK_MUTEX_R(env);
1830                                 for (i=0; i<env->me_txns->mti_numreaders; i++)
1831                                         if (env->me_txns->mti_readers[i].mr_pid == 0)
1832                                                 break;
1833                                 if (i == env->me_maxreaders) {
1834                                         UNLOCK_MUTEX_R(env);
1835                                         return MDB_READERS_FULL;
1836                                 }
1837                                 env->me_txns->mti_readers[i].mr_pid = pid;
1838                                 env->me_txns->mti_readers[i].mr_tid = tid;
1839                                 if (i >= env->me_txns->mti_numreaders)
1840                                         env->me_txns->mti_numreaders = i+1;
1841                                 /* Save numreaders for un-mutexed mdb_env_close() */
1842                                 env->me_numreaders = env->me_txns->mti_numreaders;
1843                                 UNLOCK_MUTEX_R(env);
1844                                 r = &env->me_txns->mti_readers[i];
1845                                 new_notls = (env->me_flags & MDB_NOTLS);
1846                                 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
1847                                         r->mr_pid = 0;
1848                                         return rc;
1849                                 }
1850                         }
1851                         txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1852                         txn->mt_u.reader = r;
1853                 }
1854                 txn->mt_toggle = txn->mt_txnid & 1;
1855                 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1856         } else {
1857                 LOCK_MUTEX_W(env);
1858
1859                 txn->mt_txnid = env->me_txns->mti_txnid;
1860                 txn->mt_toggle = txn->mt_txnid & 1;
1861                 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1862                 txn->mt_txnid++;
1863 #if MDB_DEBUG
1864                 if (txn->mt_txnid == mdb_debug_start)
1865                         mdb_debug = 1;
1866 #endif
1867                 txn->mt_dirty_room = MDB_IDL_UM_MAX;
1868                 txn->mt_u.dirty_list = env->me_dirty_list;
1869                 txn->mt_u.dirty_list[0].mid = 0;
1870                 txn->mt_free_pgs = env->me_free_pgs;
1871                 txn->mt_free_pgs[0] = 0;
1872                 env->me_txn = txn;
1873         }
1874
1875         /* Copy the DB info and flags */
1876         memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1877         for (i=2; i<txn->mt_numdbs; i++) {
1878                 x = env->me_dbflags[i];
1879                 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
1880                 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
1881         }
1882         txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
1883
1884         if (env->me_maxpg < txn->mt_next_pgno) {
1885                 mdb_txn_reset0(txn);
1886                 if (new_notls) {
1887                         txn->mt_u.reader->mr_pid = 0;
1888                         txn->mt_u.reader = NULL;
1889                 }
1890                 return MDB_MAP_RESIZED;
1891         }
1892
1893         return MDB_SUCCESS;
1894 }
1895
1896 int
1897 mdb_txn_renew(MDB_txn *txn)
1898 {
1899         int rc;
1900
1901         if (!txn || txn->mt_dbxs)       /* A reset txn has mt_dbxs==NULL */
1902                 return EINVAL;
1903
1904         if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1905                 DPUTS("environment had fatal error, must shutdown!");
1906                 return MDB_PANIC;
1907         }
1908
1909         rc = mdb_txn_renew0(txn);
1910         if (rc == MDB_SUCCESS) {
1911                 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1912                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1913                         (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1914         }
1915         return rc;
1916 }
1917
1918 int
1919 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1920 {
1921         MDB_txn *txn;
1922         MDB_ntxn *ntxn;
1923         int rc, size, tsize = sizeof(MDB_txn);
1924
1925         if (env->me_flags & MDB_FATAL_ERROR) {
1926                 DPUTS("environment had fatal error, must shutdown!");
1927                 return MDB_PANIC;
1928         }
1929         if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
1930                 return EACCES;
1931         if (parent) {
1932                 /* Nested transactions: Max 1 child, write txns only, no writemap */
1933                 if (parent->mt_child ||
1934                         (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
1935                         (env->me_flags & MDB_WRITEMAP))
1936                 {
1937                         return EINVAL;
1938                 }
1939                 tsize = sizeof(MDB_ntxn);
1940         }
1941         size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
1942         if (!(flags & MDB_RDONLY))
1943                 size += env->me_maxdbs * sizeof(MDB_cursor *);
1944
1945         if ((txn = calloc(1, size)) == NULL) {
1946                 DPRINTF("calloc: %s", strerror(ErrCode()));
1947                 return ENOMEM;
1948         }
1949         txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
1950         if (flags & MDB_RDONLY) {
1951                 txn->mt_flags |= MDB_TXN_RDONLY;
1952                 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1953         } else {
1954                 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1955                 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1956         }
1957         txn->mt_env = env;
1958
1959         if (parent) {
1960                 unsigned int i;
1961                 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1962                 if (!txn->mt_u.dirty_list ||
1963                         !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
1964                 {
1965                         free(txn->mt_u.dirty_list);
1966                         free(txn);
1967                         return ENOMEM;
1968                 }
1969                 txn->mt_txnid = parent->mt_txnid;
1970                 txn->mt_toggle = parent->mt_toggle;
1971                 txn->mt_dirty_room = parent->mt_dirty_room;
1972                 txn->mt_u.dirty_list[0].mid = 0;
1973                 txn->mt_free_pgs[0] = 0;
1974                 txn->mt_next_pgno = parent->mt_next_pgno;
1975                 parent->mt_child = txn;
1976                 txn->mt_parent = parent;
1977                 txn->mt_numdbs = parent->mt_numdbs;
1978                 txn->mt_dbxs = parent->mt_dbxs;
1979                 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1980                 /* Copy parent's mt_dbflags, but clear DB_NEW */
1981                 for (i=0; i<txn->mt_numdbs; i++)
1982                         txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
1983                 rc = 0;
1984                 ntxn = (MDB_ntxn *)txn;
1985                 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
1986                 if (env->me_pghead) {
1987                         size = MDB_IDL_SIZEOF(env->me_pghead);
1988                         env->me_pghead = malloc(size);
1989                         if (env->me_pghead)
1990                                 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
1991                         else
1992                                 rc = ENOMEM;
1993                 }
1994                 env->me_pgfree = env->me_pghead;
1995                 if (!rc)
1996                         rc = mdb_cursor_shadow(parent, txn);
1997                 if (rc)
1998                         mdb_txn_reset0(txn);
1999         } else {
2000                 rc = mdb_txn_renew0(txn);
2001         }
2002         if (rc)
2003                 free(txn);
2004         else {
2005                 *ret = txn;
2006                 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
2007                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2008                         (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
2009         }
2010
2011         return rc;
2012 }
2013
2014 /** Export or close DBI handles opened in this txn. */
2015 static void
2016 mdb_dbis_update(MDB_txn *txn, int keep)
2017 {
2018         int i;
2019         MDB_dbi n = txn->mt_numdbs;
2020         MDB_env *env = txn->mt_env;
2021         unsigned char *tdbflags = txn->mt_dbflags;
2022
2023         for (i = n; --i >= 2;) {
2024                 if (tdbflags[i] & DB_NEW) {
2025                         if (keep) {
2026                                 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2027                         } else {
2028                                 char *ptr = env->me_dbxs[i].md_name.mv_data;
2029                                 env->me_dbxs[i].md_name.mv_data = NULL;
2030                                 env->me_dbxs[i].md_name.mv_size = 0;
2031                                 env->me_dbflags[i] = 0;
2032                                 free(ptr);
2033                         }
2034                 }
2035         }
2036         if (keep && env->me_numdbs < n)
2037                 env->me_numdbs = n;
2038 }
2039
2040 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2041  * May be called twice for readonly txns: First reset it, then abort.
2042  * @param[in] txn the transaction handle to reset
2043  */
2044 static void
2045 mdb_txn_reset0(MDB_txn *txn)
2046 {
2047         MDB_env *env = txn->mt_env;
2048
2049         /* Close any DBI handles opened in this txn */
2050         mdb_dbis_update(txn, 0);
2051
2052         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2053                 if (txn->mt_u.reader) {
2054                         txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2055                         if (!(env->me_flags & MDB_NOTLS))
2056                                 txn->mt_u.reader = NULL; /* txn does not own reader */
2057                 }
2058                 txn->mt_numdbs = 0;             /* close nothing if called again */
2059                 txn->mt_dbxs = NULL;    /* mark txn as reset */
2060         } else {
2061                 mdb_cursors_close(txn, 0);
2062
2063                 if (!(env->me_flags & MDB_WRITEMAP)) {
2064                         mdb_dlist_free(txn);
2065                 }
2066                 free(env->me_pgfree);
2067
2068                 if (txn->mt_parent) {
2069                         txn->mt_parent->mt_child = NULL;
2070                         env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2071                         mdb_midl_free(txn->mt_free_pgs);
2072                         free(txn->mt_u.dirty_list);
2073                         return;
2074                 } else {
2075                         if (mdb_midl_shrink(&txn->mt_free_pgs))
2076                                 env->me_free_pgs = txn->mt_free_pgs;
2077                 }
2078
2079                 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = NULL;
2080                 txn->mt_env->me_pglast = 0;
2081
2082                 env->me_txn = NULL;
2083                 /* The writer mutex was locked in mdb_txn_begin. */
2084                 UNLOCK_MUTEX_W(env);
2085         }
2086 }
2087
2088 void
2089 mdb_txn_reset(MDB_txn *txn)
2090 {
2091         if (txn == NULL)
2092                 return;
2093
2094         DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
2095                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2096                 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2097
2098         /* This call is only valid for read-only txns */
2099         if (!(txn->mt_flags & MDB_TXN_RDONLY))
2100                 return;
2101
2102         mdb_txn_reset0(txn);
2103 }
2104
2105 void
2106 mdb_txn_abort(MDB_txn *txn)
2107 {
2108         if (txn == NULL)
2109                 return;
2110
2111         DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
2112                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2113                 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2114
2115         if (txn->mt_child)
2116                 mdb_txn_abort(txn->mt_child);
2117
2118         mdb_txn_reset0(txn);
2119         /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2120         if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2121                 txn->mt_u.reader->mr_pid = 0;
2122
2123         free(txn);
2124 }
2125
2126 int
2127 mdb_txn_commit(MDB_txn *txn)
2128 {
2129         int              n, done;
2130         unsigned int i;
2131         ssize_t          rc;
2132         off_t            size;
2133         MDB_page        *dp;
2134         MDB_env *env;
2135         pgno_t  next, freecnt;
2136         txnid_t oldpg_txnid, id;
2137         MDB_cursor mc;
2138
2139         assert(txn != NULL);
2140         assert(txn->mt_env != NULL);
2141
2142         if (txn->mt_child) {
2143                 rc = mdb_txn_commit(txn->mt_child);
2144                 txn->mt_child = NULL;
2145                 if (rc) {
2146                         mdb_txn_abort(txn);
2147                         return rc;
2148                 }
2149         }
2150
2151         env = txn->mt_env;
2152
2153         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2154                 mdb_dbis_update(txn, 1);
2155                 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2156                 mdb_txn_abort(txn);
2157                 return MDB_SUCCESS;
2158         }
2159
2160         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2161                 DPUTS("error flag is set, can't commit");
2162                 if (txn->mt_parent)
2163                         txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2164                 mdb_txn_abort(txn);
2165                 return EINVAL;
2166         }
2167
2168         if (txn->mt_parent) {
2169                 MDB_txn *parent = txn->mt_parent;
2170                 unsigned x, y, len;
2171                 MDB_ID2L dst, src;
2172
2173                 /* Append our free list to parent's */
2174                 if (mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs)) {
2175                         mdb_txn_abort(txn);
2176                         return ENOMEM;
2177                 }
2178                 mdb_midl_free(txn->mt_free_pgs);
2179
2180                 parent->mt_next_pgno = txn->mt_next_pgno;
2181                 parent->mt_flags = txn->mt_flags;
2182
2183                 /* Merge our cursors into parent's and close them */
2184                 mdb_cursors_close(txn, C_SHADOW);
2185
2186                 /* Update parent's DB table. */
2187                 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2188                 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
2189                 txn->mt_parent->mt_dbflags[0] = txn->mt_dbflags[0];
2190                 txn->mt_parent->mt_dbflags[1] = txn->mt_dbflags[1];
2191                 for (i=2; i<txn->mt_numdbs; i++) {
2192                         /* preserve parent's DB_NEW status */
2193                         x = txn->mt_parent->mt_dbflags[i] & DB_NEW;
2194                         txn->mt_parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2195                 }
2196
2197                 dst = txn->mt_parent->mt_u.dirty_list;
2198                 src = txn->mt_u.dirty_list;
2199                 /* Find len = length of merging our dirty list with parent's */
2200                 x = dst[0].mid;
2201                 dst[0].mid = 0;         /* simplify loops */
2202                 if (parent->mt_parent) {
2203                         len = x + src[0].mid;
2204                         y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2205                         for (i = x; y && i; y--) {
2206                                 pgno_t yp = src[y].mid;
2207                                 while (yp < dst[i].mid)
2208                                         i--;
2209                                 if (yp == dst[i].mid) {
2210                                         i--;
2211                                         len--;
2212                                 }
2213                         }
2214                 } else { /* Simplify the above for single-ancestor case */
2215                         len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2216                 }
2217                 /* Merge our dirty list with parent's */
2218                 y = src[0].mid;
2219                 for (i = len; y; dst[i--] = src[y--]) {
2220                         pgno_t yp = src[y].mid;
2221                         while (yp < dst[x].mid)
2222                                 dst[i--] = dst[x--];
2223                         if (yp == dst[x].mid)
2224                                 free(dst[x--].mptr);
2225                 }
2226                 assert(i == x);
2227                 dst[0].mid = len;
2228                 free(txn->mt_u.dirty_list);
2229                 parent->mt_dirty_room = txn->mt_dirty_room;
2230
2231                 txn->mt_parent->mt_child = NULL;
2232                 free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pgfree);
2233                 free(txn);
2234                 return MDB_SUCCESS;
2235         }
2236
2237         if (txn != env->me_txn) {
2238                 DPUTS("attempt to commit unknown transaction");
2239                 mdb_txn_abort(txn);
2240                 return EINVAL;
2241         }
2242
2243         mdb_cursors_close(txn, 0);
2244
2245         if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2246                 goto done;
2247
2248         DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2249             txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2250
2251         /* Update DB root pointers */
2252         if (txn->mt_numdbs > 2) {
2253                 MDB_dbi i;
2254                 MDB_val data;
2255                 data.mv_size = sizeof(MDB_db);
2256
2257                 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2258                 for (i = 2; i < txn->mt_numdbs; i++) {
2259                         if (txn->mt_dbflags[i] & DB_DIRTY) {
2260                                 data.mv_data = &txn->mt_dbs[i];
2261                                 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2262                                 if (rc)
2263                                         goto fail;
2264                         }
2265                 }
2266         }
2267
2268         /* Save the freelist as of this transaction to the freeDB. This
2269          * can change the freelist, so keep trying until it stabilizes.
2270          *
2271          * env->me_pglast and the length of txn->mt_free_pgs cannot decrease,
2272          * except the code below can decrease env->me_pglast to split pghead.
2273          * Page numbers cannot disappear from txn->mt_free_pgs.  New pages
2274          * can only appear in env->me_pghead when env->me_pglast increases.
2275          * Until then, the me_pghead pointer won't move but can become NULL.
2276          */
2277
2278         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2279         oldpg_txnid = id = 0;
2280         freecnt = 0;
2281
2282         /* should only be one record now */
2283         if (env->me_pghead || env->me_pglast) {
2284                 /* make sure first page of freeDB is touched and on freelist */
2285                 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2286                 if (rc && rc != MDB_NOTFOUND) {
2287 fail:
2288                         mdb_txn_abort(txn);
2289                         return rc;
2290                 }
2291         }
2292
2293         /* Delete IDLs we used from the free list */
2294         if (env->me_pglast) {
2295                 MDB_val key;
2296
2297                 do {
2298 free_pgfirst:
2299                         rc = mdb_cursor_first(&mc, &key, NULL);
2300                         if (rc)
2301                                 goto fail;
2302                         oldpg_txnid = *(txnid_t *)key.mv_data;
2303 again:
2304                         assert(oldpg_txnid <= env->me_pglast);
2305                         id = 0;
2306                         rc = mdb_cursor_del(&mc, 0);
2307                         if (rc)
2308                                 goto fail;
2309                 } while (oldpg_txnid < env->me_pglast);
2310         }
2311
2312         /* Save IDL of pages freed by this txn, to freeDB */
2313 free2:
2314         if (freecnt != txn->mt_free_pgs[0]) {
2315                 MDB_val key, data;
2316
2317                 /* make sure last page of freeDB is touched and on freelist */
2318                 key.mv_size = MDB_MAXKEYSIZE+1;
2319                 key.mv_data = NULL;
2320                 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2321                 if (rc && rc != MDB_NOTFOUND)
2322                         goto fail;
2323
2324 #if MDB_DEBUG > 1
2325                 {
2326                         unsigned int i;
2327                         MDB_IDL idl = txn->mt_free_pgs;
2328                         mdb_midl_sort(txn->mt_free_pgs);
2329                         DPRINTF("IDL write txn %zu root %zu num %zu",
2330                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
2331                         for (i=1; i<=idl[0]; i++) {
2332                                 DPRINTF("IDL %zu", idl[i]);
2333                         }
2334                 }
2335 #endif
2336                 /* write to last page of freeDB */
2337                 key.mv_size = sizeof(pgno_t);
2338                 key.mv_data = &txn->mt_txnid;
2339                 /* The free list can still grow during this call,
2340                  * despite the pre-emptive touches above. So retry
2341                  * until the reserved space remains big enough.
2342                  */
2343                 do {
2344                         assert(freecnt < txn->mt_free_pgs[0]);
2345                         freecnt = txn->mt_free_pgs[0];
2346                         data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
2347                         rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2348                         if (rc)
2349                                 goto fail;
2350                 } while (freecnt != txn->mt_free_pgs[0]);
2351                 mdb_midl_sort(txn->mt_free_pgs);
2352                 memcpy(data.mv_data, txn->mt_free_pgs, data.mv_size);
2353                 if (oldpg_txnid < env->me_pglast || (!env->me_pghead && id))
2354                         goto free_pgfirst;      /* used up freeDB[oldpg_txnid] */
2355         }
2356
2357         /* Put back page numbers we took from freeDB but did not use */
2358         if (env->me_pghead) {
2359           for (;;) {
2360                 MDB_val key, data;
2361                 pgno_t orig, *mop;
2362
2363                 mop = env->me_pghead;
2364                 id = env->me_pglast;
2365                 key.mv_size = sizeof(id);
2366                 key.mv_data = &id;
2367                 /* These steps may grow the freelist again
2368                  * due to freed overflow pages...
2369                  */
2370                 i = 2;
2371                 do {
2372                         orig = mop[0];
2373                         if (orig > env->me_maxfree_1pg && id > 4)
2374                                 orig = env->me_maxfree_1pg; /* Do not use more than 1 page */
2375                         data.mv_size = (orig + 1) * sizeof(pgno_t);
2376                         rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2377                         if (rc)
2378                                 goto fail;
2379                         assert(!env->me_pghead || env->me_pglast);
2380                         /* mop could have been used again here */
2381                         if (id != env->me_pglast || env->me_pghead == NULL)
2382                                 goto again;             /* was completely used up */
2383                         assert(mop == env->me_pghead);
2384                 } while (mop[0] < orig && --i);
2385                 memcpy(data.mv_data, mop, data.mv_size);
2386                 if (mop[0] <= orig)
2387                         break;
2388                 *(pgno_t *)data.mv_data = orig;
2389                 mop[orig] = mop[0] - orig;
2390                 env->me_pghead = mop += orig;
2391                 /* Save more oldpages at the previous txnid. */
2392                 assert(env->me_pglast == id && id == oldpg_txnid);
2393                 env->me_pglast = --oldpg_txnid;
2394           }
2395         }
2396
2397         /* Check for growth of freelist again */
2398         if (freecnt != txn->mt_free_pgs[0])
2399                 goto free2;
2400
2401         free(env->me_pgfree);
2402         env->me_pghead = env->me_pgfree = NULL;
2403
2404         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2405                 if (mdb_midl_shrink(&txn->mt_free_pgs))
2406                         env->me_free_pgs = txn->mt_free_pgs;
2407         }
2408
2409 #if MDB_DEBUG > 2
2410         mdb_audit(txn);
2411 #endif
2412
2413         if (env->me_flags & MDB_WRITEMAP) {
2414                 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2415                         dp = txn->mt_u.dirty_list[i].mptr;
2416                         /* clear dirty flag */
2417                         dp->mp_flags &= ~P_DIRTY;
2418                 }
2419                 txn->mt_u.dirty_list[0].mid = 0;
2420                 goto sync;
2421         }
2422
2423         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2424          */
2425         next = 0;
2426         i = 1;
2427         do {
2428 #ifdef _WIN32
2429                 /* Windows actually supports scatter/gather I/O, but only on
2430                  * unbuffered file handles. Since we're relying on the OS page
2431                  * cache for all our data, that's self-defeating. So we just
2432                  * write pages one at a time. We use the ov structure to set
2433                  * the write offset, to at least save the overhead of a Seek
2434                  * system call.
2435                  */
2436                 OVERLAPPED ov;
2437                 memset(&ov, 0, sizeof(ov));
2438                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2439                         size_t wsize;
2440                         dp = txn->mt_u.dirty_list[i].mptr;
2441                         DPRINTF("committing page %zu", dp->mp_pgno);
2442                         size = dp->mp_pgno * env->me_psize;
2443                         ov.Offset = size & 0xffffffff;
2444                         ov.OffsetHigh = size >> 16;
2445                         ov.OffsetHigh >>= 16;
2446                         /* clear dirty flag */
2447                         dp->mp_flags &= ~P_DIRTY;
2448                         wsize = env->me_psize;
2449                         if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2450                         rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2451                         if (!rc) {
2452                                 n = ErrCode();
2453                                 DPRINTF("WriteFile: %d", n);
2454                                 mdb_txn_abort(txn);
2455                                 return n;
2456                         }
2457                 }
2458                 done = 1;
2459 #else
2460                 struct iovec     iov[MDB_COMMIT_PAGES];
2461                 n = 0;
2462                 done = 1;
2463                 size = 0;
2464                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2465                         dp = txn->mt_u.dirty_list[i].mptr;
2466                         if (dp->mp_pgno != next) {
2467                                 if (n) {
2468                                         rc = writev(env->me_fd, iov, n);
2469                                         if (rc != size) {
2470                                                 n = ErrCode();
2471                                                 if (rc > 0)
2472                                                         DPUTS("short write, filesystem full?");
2473                                                 else
2474                                                         DPRINTF("writev: %s", strerror(n));
2475                                                 mdb_txn_abort(txn);
2476                                                 return n;
2477                                         }
2478                                         n = 0;
2479                                         size = 0;
2480                                 }
2481                                 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2482                                 next = dp->mp_pgno;
2483                         }
2484                         DPRINTF("committing page %zu", dp->mp_pgno);
2485                         iov[n].iov_len = env->me_psize;
2486                         if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2487                         iov[n].iov_base = (char *)dp;
2488                         size += iov[n].iov_len;
2489                         next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2490                         /* clear dirty flag */
2491                         dp->mp_flags &= ~P_DIRTY;
2492                         if (++n >= MDB_COMMIT_PAGES) {
2493                                 done = 0;
2494                                 i++;
2495                                 break;
2496                         }
2497                 }
2498
2499                 if (n == 0)
2500                         break;
2501
2502                 rc = writev(env->me_fd, iov, n);
2503                 if (rc != size) {
2504                         n = ErrCode();
2505                         if (rc > 0)
2506                                 DPUTS("short write, filesystem full?");
2507                         else
2508                                 DPRINTF("writev: %s", strerror(n));
2509                         mdb_txn_abort(txn);
2510                         return n;
2511                 }
2512 #endif
2513         } while (!done);
2514
2515         mdb_dlist_free(txn);
2516
2517 sync:
2518         if ((n = mdb_env_sync(env, 0)) != 0 ||
2519             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2520                 mdb_txn_abort(txn);
2521                 return n;
2522         }
2523
2524 done:
2525         env->me_pglast = 0;
2526         env->me_txn = NULL;
2527         mdb_dbis_update(txn, 1);
2528
2529         UNLOCK_MUTEX_W(env);
2530         free(txn);
2531
2532         return MDB_SUCCESS;
2533 }
2534
2535 /** Read the environment parameters of a DB environment before
2536  * mapping it into memory.
2537  * @param[in] env the environment handle
2538  * @param[out] meta address of where to store the meta information
2539  * @return 0 on success, non-zero on failure.
2540  */
2541 static int
2542 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2543 {
2544         MDB_pagebuf     pbuf;
2545         MDB_page        *p;
2546         MDB_meta        *m;
2547         int              i, rc, err;
2548
2549         /* We don't know the page size yet, so use a minimum value.
2550          * Read both meta pages so we can use the latest one.
2551          */
2552
2553         for (i=0; i<2; i++) {
2554 #ifdef _WIN32
2555                 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2556 #else
2557                 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2558 #endif
2559                 {
2560                         return ENOENT;
2561                 }
2562                 else if (rc != MDB_PAGESIZE) {
2563                         err = ErrCode();
2564                         if (rc > 0)
2565                                 err = MDB_INVALID;
2566                         DPRINTF("read: %s", strerror(err));
2567                         return err;
2568                 }
2569
2570                 p = (MDB_page *)&pbuf;
2571
2572                 if (!F_ISSET(p->mp_flags, P_META)) {
2573                         DPRINTF("page %zu not a meta page", p->mp_pgno);
2574                         return MDB_INVALID;
2575                 }
2576
2577                 m = METADATA(p);
2578                 if (m->mm_magic != MDB_MAGIC) {
2579                         DPUTS("meta has invalid magic");
2580                         return MDB_INVALID;
2581                 }
2582
2583                 if (m->mm_version != MDB_VERSION) {
2584                         DPRINTF("database is version %u, expected version %u",
2585                                 m->mm_version, MDB_VERSION);
2586                         return MDB_VERSION_MISMATCH;
2587                 }
2588
2589                 if (i) {
2590                         if (m->mm_txnid > meta->mm_txnid)
2591                                 memcpy(meta, m, sizeof(*m));
2592                 } else {
2593                         memcpy(meta, m, sizeof(*m));
2594 #ifdef _WIN32
2595                         if (SetFilePointer(env->me_fd, meta->mm_psize, NULL, FILE_BEGIN) != meta->mm_psize)
2596 #else
2597                         if (lseek(env->me_fd, meta->mm_psize, SEEK_SET) != meta->mm_psize)
2598 #endif
2599                                 return ErrCode();
2600                 }
2601         }
2602         return 0;
2603 }
2604
2605 /** Write the environment parameters of a freshly created DB environment.
2606  * @param[in] env the environment handle
2607  * @param[out] meta address of where to store the meta information
2608  * @return 0 on success, non-zero on failure.
2609  */
2610 static int
2611 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2612 {
2613         MDB_page *p, *q;
2614         MDB_meta *m;
2615         int rc;
2616         unsigned int     psize;
2617
2618         DPUTS("writing new meta page");
2619
2620         GET_PAGESIZE(psize);
2621
2622         meta->mm_magic = MDB_MAGIC;
2623         meta->mm_version = MDB_VERSION;
2624         meta->mm_mapsize = env->me_mapsize;
2625         meta->mm_psize = psize;
2626         meta->mm_last_pg = 1;
2627         meta->mm_flags = env->me_flags & 0xffff;
2628         meta->mm_flags |= MDB_INTEGERKEY;
2629         meta->mm_dbs[0].md_root = P_INVALID;
2630         meta->mm_dbs[1].md_root = P_INVALID;
2631
2632         p = calloc(2, psize);
2633         p->mp_pgno = 0;
2634         p->mp_flags = P_META;
2635
2636         m = METADATA(p);
2637         memcpy(m, meta, sizeof(*meta));
2638
2639         q = (MDB_page *)((char *)p + psize);
2640
2641         q->mp_pgno = 1;
2642         q->mp_flags = P_META;
2643
2644         m = METADATA(q);
2645         memcpy(m, meta, sizeof(*meta));
2646
2647 #ifdef _WIN32
2648         {
2649                 DWORD len;
2650                 SetFilePointer(env->me_fd, 0, NULL, FILE_BEGIN);
2651                 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2652                 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2653         }
2654 #else
2655         lseek(env->me_fd, 0, SEEK_SET);
2656         rc = write(env->me_fd, p, psize * 2);
2657         rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2658 #endif
2659         free(p);
2660         return rc;
2661 }
2662
2663 /** Update the environment info to commit a transaction.
2664  * @param[in] txn the transaction that's being committed
2665  * @return 0 on success, non-zero on failure.
2666  */
2667 static int
2668 mdb_env_write_meta(MDB_txn *txn)
2669 {
2670         MDB_env *env;
2671         MDB_meta        meta, metab, *mp;
2672         off_t off;
2673         int rc, len, toggle;
2674         char *ptr;
2675         HANDLE mfd;
2676 #ifdef _WIN32
2677         OVERLAPPED ov;
2678 #endif
2679
2680         assert(txn != NULL);
2681         assert(txn->mt_env != NULL);
2682
2683         toggle = !txn->mt_toggle;
2684         DPRINTF("writing meta page %d for root page %zu",
2685                 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2686
2687         env = txn->mt_env;
2688         mp = env->me_metas[toggle];
2689
2690         if (env->me_flags & MDB_WRITEMAP) {
2691                 /* Persist any increases of mapsize config */
2692                 if (env->me_mapsize > mp->mm_mapsize)
2693                         mp->mm_mapsize = env->me_mapsize;
2694                 mp->mm_dbs[0] = txn->mt_dbs[0];
2695                 mp->mm_dbs[1] = txn->mt_dbs[1];
2696                 mp->mm_last_pg = txn->mt_next_pgno - 1;
2697                 mp->mm_txnid = txn->mt_txnid;
2698                 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2699                         rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2700                         ptr = env->me_map;
2701                         if (toggle)
2702                                 ptr += env->me_psize;
2703                         if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2704                                 rc = ErrCode();
2705                                 goto fail;
2706                         }
2707                 }
2708                 goto done;
2709         }
2710         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2711         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2712
2713         ptr = (char *)&meta;
2714         if (env->me_mapsize > mp->mm_mapsize) {
2715                 /* Persist any increases of mapsize config */
2716                 meta.mm_mapsize = env->me_mapsize;
2717                 off = offsetof(MDB_meta, mm_mapsize);
2718         } else {
2719                 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2720         }
2721         len = sizeof(MDB_meta) - off;
2722
2723         ptr += off;
2724         meta.mm_dbs[0] = txn->mt_dbs[0];
2725         meta.mm_dbs[1] = txn->mt_dbs[1];
2726         meta.mm_last_pg = txn->mt_next_pgno - 1;
2727         meta.mm_txnid = txn->mt_txnid;
2728
2729         if (toggle)
2730                 off += env->me_psize;
2731         off += PAGEHDRSZ;
2732
2733         /* Write to the SYNC fd */
2734         mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
2735                 env->me_fd : env->me_mfd;
2736 #ifdef _WIN32
2737         {
2738                 memset(&ov, 0, sizeof(ov));
2739                 ov.Offset = off;
2740                 WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov);
2741         }
2742 #else
2743         rc = pwrite(mfd, ptr, len, off);
2744 #endif
2745         if (rc != len) {
2746                 int r2;
2747                 rc = ErrCode();
2748                 DPUTS("write failed, disk error?");
2749                 /* On a failure, the pagecache still contains the new data.
2750                  * Write some old data back, to prevent it from being used.
2751                  * Use the non-SYNC fd; we know it will fail anyway.
2752                  */
2753                 meta.mm_last_pg = metab.mm_last_pg;
2754                 meta.mm_txnid = metab.mm_txnid;
2755 #ifdef _WIN32
2756                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2757 #else
2758                 r2 = pwrite(env->me_fd, ptr, len, off);
2759 #endif
2760 fail:
2761                 env->me_flags |= MDB_FATAL_ERROR;
2762                 return rc;
2763         }
2764 done:
2765         /* Memory ordering issues are irrelevant; since the entire writer
2766          * is wrapped by wmutex, all of these changes will become visible
2767          * after the wmutex is unlocked. Since the DB is multi-version,
2768          * readers will get consistent data regardless of how fresh or
2769          * how stale their view of these values is.
2770          */
2771         txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2772
2773         return MDB_SUCCESS;
2774 }
2775
2776 /** Check both meta pages to see which one is newer.
2777  * @param[in] env the environment handle
2778  * @return meta toggle (0 or 1).
2779  */
2780 static int
2781 mdb_env_pick_meta(const MDB_env *env)
2782 {
2783         return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2784 }
2785
2786 int
2787 mdb_env_create(MDB_env **env)
2788 {
2789         MDB_env *e;
2790
2791         e = calloc(1, sizeof(MDB_env));
2792         if (!e)
2793                 return ENOMEM;
2794
2795         e->me_maxreaders = DEFAULT_READERS;
2796         e->me_maxdbs = e->me_numdbs = 2;
2797         e->me_fd = INVALID_HANDLE_VALUE;
2798         e->me_lfd = INVALID_HANDLE_VALUE;
2799         e->me_mfd = INVALID_HANDLE_VALUE;
2800 #ifdef MDB_USE_POSIX_SEM
2801         e->me_rmutex = SEM_FAILED;
2802         e->me_wmutex = SEM_FAILED;
2803 #endif
2804         e->me_pid = getpid();
2805         VGMEMP_CREATE(e,0,0);
2806         *env = e;
2807         return MDB_SUCCESS;
2808 }
2809
2810 int
2811 mdb_env_set_mapsize(MDB_env *env, size_t size)
2812 {
2813         if (env->me_map)
2814                 return EINVAL;
2815         env->me_mapsize = size;
2816         if (env->me_psize)
2817                 env->me_maxpg = env->me_mapsize / env->me_psize;
2818         return MDB_SUCCESS;
2819 }
2820
2821 int
2822 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2823 {
2824         if (env->me_map)
2825                 return EINVAL;
2826         env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
2827         return MDB_SUCCESS;
2828 }
2829
2830 int
2831 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2832 {
2833         if (env->me_map || readers < 1)
2834                 return EINVAL;
2835         env->me_maxreaders = readers;
2836         return MDB_SUCCESS;
2837 }
2838
2839 int
2840 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2841 {
2842         if (!env || !readers)
2843                 return EINVAL;
2844         *readers = env->me_maxreaders;
2845         return MDB_SUCCESS;
2846 }
2847
2848 /** Further setup required for opening an MDB environment
2849  */
2850 static int
2851 mdb_env_open2(MDB_env *env)
2852 {
2853         unsigned int flags = env->me_flags;
2854         int i, newenv = 0, prot;
2855         MDB_meta meta;
2856         MDB_page *p;
2857
2858         memset(&meta, 0, sizeof(meta));
2859
2860         if ((i = mdb_env_read_header(env, &meta)) != 0) {
2861                 if (i != ENOENT)
2862                         return i;
2863                 DPUTS("new mdbenv");
2864                 newenv = 1;
2865         }
2866
2867         /* Was a mapsize configured? */
2868         if (!env->me_mapsize) {
2869                 /* If this is a new environment, take the default,
2870                  * else use the size recorded in the existing env.
2871                  */
2872                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2873         } else if (env->me_mapsize < meta.mm_mapsize) {
2874                 /* If the configured size is smaller, make sure it's
2875                  * still big enough. Silently round up to minimum if not.
2876                  */
2877                 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
2878                 if (env->me_mapsize < minsize)
2879                         env->me_mapsize = minsize;
2880         }
2881
2882 #ifdef _WIN32
2883         {
2884                 HANDLE mh;
2885                 LONG sizelo, sizehi;
2886                 sizelo = env->me_mapsize & 0xffffffff;
2887                 sizehi = env->me_mapsize >> 16;         /* pointless on WIN32, only needed on W64 */
2888                 sizehi >>= 16;
2889                 /* Windows won't create mappings for zero length files.
2890                  * Just allocate the maxsize right now.
2891                  */
2892                 if (newenv) {
2893                         SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2894                         if (!SetEndOfFile(env->me_fd))
2895                                 return ErrCode();
2896                         SetFilePointer(env->me_fd, 0, NULL, 0);
2897                 }
2898                 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
2899                         PAGE_READWRITE : PAGE_READONLY,
2900                         sizehi, sizelo, NULL);
2901                 if (!mh)
2902                         return ErrCode();
2903                 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
2904                         FILE_MAP_WRITE : FILE_MAP_READ,
2905                         0, 0, env->me_mapsize, meta.mm_address);
2906                 CloseHandle(mh);
2907                 if (!env->me_map)
2908                         return ErrCode();
2909         }
2910 #else
2911         i = MAP_SHARED;
2912         prot = PROT_READ;
2913         if (flags & MDB_WRITEMAP) {
2914                 prot |= PROT_WRITE;
2915                 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
2916                         return ErrCode();
2917         }
2918         env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
2919                 env->me_fd, 0);
2920         if (env->me_map == MAP_FAILED) {
2921                 env->me_map = NULL;
2922                 return ErrCode();
2923         }
2924         /* Turn off readahead. It's harmful when the DB is larger than RAM. */
2925 #ifdef MADV_RANDOM
2926         madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
2927 #else
2928 #ifdef POSIX_MADV_RANDOM
2929         posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
2930 #endif /* POSIX_MADV_RANDOM */
2931 #endif /* MADV_RANDOM */
2932 #endif /* _WIN32 */
2933
2934         if (newenv) {
2935                 if (flags & MDB_FIXEDMAP)
2936                         meta.mm_address = env->me_map;
2937                 i = mdb_env_init_meta(env, &meta);
2938                 if (i != MDB_SUCCESS) {
2939                         return i;
2940                 }
2941         } else if (meta.mm_address && env->me_map != meta.mm_address) {
2942                 /* Can happen because the address argument to mmap() is just a
2943                  * hint.  mmap() can pick another, e.g. if the range is in use.
2944                  * The MAP_FIXED flag would prevent that, but then mmap could
2945                  * instead unmap existing pages to make room for the new map.
2946                  */
2947                 return EBUSY;   /* TODO: Make a new MDB_* error code? */
2948         }
2949         env->me_psize = meta.mm_psize;
2950         env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
2951         env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
2952
2953         env->me_maxpg = env->me_mapsize / env->me_psize;
2954
2955         p = (MDB_page *)env->me_map;
2956         env->me_metas[0] = METADATA(p);
2957         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2958
2959 #if MDB_DEBUG
2960         {
2961                 int toggle = mdb_env_pick_meta(env);
2962                 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2963
2964                 DPRINTF("opened database version %u, pagesize %u",
2965                         env->me_metas[0]->mm_version, env->me_psize);
2966                 DPRINTF("using meta page %d",  toggle);
2967                 DPRINTF("depth: %u",           db->md_depth);
2968                 DPRINTF("entries: %zu",        db->md_entries);
2969                 DPRINTF("branch pages: %zu",   db->md_branch_pages);
2970                 DPRINTF("leaf pages: %zu",     db->md_leaf_pages);
2971                 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2972                 DPRINTF("root: %zu",           db->md_root);
2973         }
2974 #endif
2975
2976         return MDB_SUCCESS;
2977 }
2978
2979
2980 /** Release a reader thread's slot in the reader lock table.
2981  *      This function is called automatically when a thread exits.
2982  * @param[in] ptr This points to the slot in the reader lock table.
2983  */
2984 static void
2985 mdb_env_reader_dest(void *ptr)
2986 {
2987         MDB_reader *reader = ptr;
2988
2989         reader->mr_pid = 0;
2990 }
2991
2992 #ifdef _WIN32
2993 /** Junk for arranging thread-specific callbacks on Windows. This is
2994  *      necessarily platform and compiler-specific. Windows supports up
2995  *      to 1088 keys. Let's assume nobody opens more than 64 environments
2996  *      in a single process, for now. They can override this if needed.
2997  */
2998 #ifndef MAX_TLS_KEYS
2999 #define MAX_TLS_KEYS    64
3000 #endif
3001 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3002 static int mdb_tls_nkeys;
3003
3004 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3005 {
3006         int i;
3007         switch(reason) {
3008         case DLL_PROCESS_ATTACH: break;
3009         case DLL_THREAD_ATTACH: break;
3010         case DLL_THREAD_DETACH:
3011                 for (i=0; i<mdb_tls_nkeys; i++) {
3012                         MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3013                         mdb_env_reader_dest(r);
3014                 }
3015                 break;
3016         case DLL_PROCESS_DETACH: break;
3017         }
3018 }
3019 #ifdef __GNUC__
3020 #ifdef _WIN64
3021 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3022 #else
3023 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3024 #endif
3025 #else
3026 #ifdef _WIN64
3027 /* Force some symbol references.
3028  *      _tls_used forces the linker to create the TLS directory if not already done
3029  *      mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3030  */
3031 #pragma comment(linker, "/INCLUDE:_tls_used")
3032 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3033 #pragma const_seg(".CRT$XLB")
3034 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3035 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3036 #pragma const_seg()
3037 #else   /* WIN32 */
3038 #pragma comment(linker, "/INCLUDE:__tls_used")
3039 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3040 #pragma data_seg(".CRT$XLB")
3041 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3042 #pragma data_seg()
3043 #endif  /* WIN 32/64 */
3044 #endif  /* !__GNUC__ */
3045 #endif
3046
3047 /** Downgrade the exclusive lock on the region back to shared */
3048 static int
3049 mdb_env_share_locks(MDB_env *env, int *excl)
3050 {
3051         int rc = 0, toggle = mdb_env_pick_meta(env);
3052
3053         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3054
3055 #ifdef _WIN32
3056         {
3057                 OVERLAPPED ov;
3058                 /* First acquire a shared lock. The Unlock will
3059                  * then release the existing exclusive lock.
3060                  */
3061                 memset(&ov, 0, sizeof(ov));
3062                 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3063                         rc = ErrCode();
3064                 } else {
3065                         UnlockFile(env->me_lfd, 0, 0, 1, 0);
3066                         *excl = 0;
3067                 }
3068         }
3069 #else
3070         {
3071                 struct flock lock_info;
3072                 /* The shared lock replaces the existing lock */
3073                 memset((void *)&lock_info, 0, sizeof(lock_info));
3074                 lock_info.l_type = F_RDLCK;
3075                 lock_info.l_whence = SEEK_SET;
3076                 lock_info.l_start = 0;
3077                 lock_info.l_len = 1;
3078                 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3079                                 (rc = ErrCode()) == EINTR) ;
3080                 *excl = rc ? -1 : 0;    /* error may mean we lost the lock */
3081         }
3082 #endif
3083
3084         return rc;
3085 }
3086
3087 /** Try to get exlusive lock, otherwise shared.
3088  *      Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3089  */
3090 static int
3091 mdb_env_excl_lock(MDB_env *env, int *excl)
3092 {
3093         int rc = 0;
3094 #ifdef _WIN32
3095         if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3096                 *excl = 1;
3097         } else {
3098                 OVERLAPPED ov;
3099                 memset(&ov, 0, sizeof(ov));
3100                 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3101                         *excl = 0;
3102                 } else {
3103                         rc = ErrCode();
3104                 }
3105         }
3106 #else
3107         struct flock lock_info;
3108         memset((void *)&lock_info, 0, sizeof(lock_info));
3109         lock_info.l_type = F_WRLCK;
3110         lock_info.l_whence = SEEK_SET;
3111         lock_info.l_start = 0;
3112         lock_info.l_len = 1;
3113         while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3114                         (rc = ErrCode()) == EINTR) ;
3115         if (!rc) {
3116                 *excl = 1;
3117         } else
3118 # ifdef MDB_USE_POSIX_SEM
3119         if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3120 # endif
3121         {
3122                 lock_info.l_type = F_RDLCK;
3123                 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3124                                 (rc = ErrCode()) == EINTR) ;
3125                 if (rc == 0)
3126                         *excl = 0;
3127         }
3128 #endif
3129         return rc;
3130 }
3131
3132 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3133 /*
3134  * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3135  *
3136  * @(#) $Revision: 5.1 $
3137  * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3138  * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3139  *
3140  *        http://www.isthe.com/chongo/tech/comp/fnv/index.html
3141  *
3142  ***
3143  *
3144  * Please do not copyright this code.  This code is in the public domain.
3145  *
3146  * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3147  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3148  * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3149  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3150  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3151  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3152  * PERFORMANCE OF THIS SOFTWARE.
3153  *
3154  * By:
3155  *      chongo <Landon Curt Noll> /\oo/\
3156  *        http://www.isthe.com/chongo/
3157  *
3158  * Share and Enjoy!     :-)
3159  */
3160
3161 typedef unsigned long long      mdb_hash_t;
3162 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3163
3164 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3165  * @param[in] str string to hash
3166  * @param[in] hval      initial value for hash
3167  * @return 64 bit hash
3168  *
3169  * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3170  *       hval arg on the first call.
3171  */
3172 static mdb_hash_t
3173 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3174 {
3175         unsigned char *s = (unsigned char *)val->mv_data;       /* unsigned string */
3176         unsigned char *end = s + val->mv_size;
3177         /*
3178          * FNV-1a hash each octet of the string
3179          */
3180         while (s < end) {
3181                 /* xor the bottom with the current octet */
3182                 hval ^= (mdb_hash_t)*s++;
3183
3184                 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3185                 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3186                         (hval << 7) + (hval << 8) + (hval << 40);
3187         }
3188         /* return our new hash value */
3189         return hval;
3190 }
3191
3192 /** Hash the string and output the hash in hex.
3193  * @param[in] str string to hash
3194  * @param[out] hexbuf an array of 17 chars to hold the hash
3195  */
3196 static void
3197 mdb_hash_hex(MDB_val *val, char *hexbuf)
3198 {
3199         int i;
3200         mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3201         for (i=0; i<8; i++) {
3202                 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3203                 h >>= 8;
3204         }
3205 }
3206 #endif
3207
3208 /** Open and/or initialize the lock region for the environment.
3209  * @param[in] env The MDB environment.
3210  * @param[in] lpath The pathname of the file used for the lock region.
3211  * @param[in] mode The Unix permissions for the file, if we create it.
3212  * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3213  * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3214  * @return 0 on success, non-zero on failure.
3215  */
3216 static int
3217 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3218 {
3219 #ifdef _WIN32
3220 #       define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3221 #else
3222 #       define MDB_ERRCODE_ROFS EROFS
3223 #ifdef O_CLOEXEC        /* Linux: Open file and set FD_CLOEXEC atomically */
3224 #       define MDB_CLOEXEC              O_CLOEXEC
3225 #else
3226         int fdflags;
3227 #       define MDB_CLOEXEC              0
3228 #endif
3229 #endif
3230         int rc;
3231         off_t size, rsize;
3232
3233 #ifdef _WIN32
3234         env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3235                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3236                 FILE_ATTRIBUTE_NORMAL, NULL);
3237 #else
3238         env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3239 #endif
3240         if (env->me_lfd == INVALID_HANDLE_VALUE) {
3241                 rc = ErrCode();
3242                 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3243                         return MDB_SUCCESS;
3244                 }
3245                 goto fail_errno;
3246         }
3247 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3248         /* Lose record locks when exec*() */
3249         if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3250                         fcntl(env->me_lfd, F_SETFD, fdflags);
3251 #endif
3252
3253         if (!(env->me_flags & MDB_NOTLS)) {
3254                 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3255                 if (rc)
3256                         goto fail;
3257                 env->me_flags |= MDB_ENV_TXKEY;
3258 #ifdef _WIN32
3259                 /* Windows TLS callbacks need help finding their TLS info. */
3260                 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3261                         rc = MDB_TLS_FULL;
3262                         goto fail;
3263                 }
3264                 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3265 #endif
3266         }
3267
3268         /* Try to get exclusive lock. If we succeed, then
3269          * nobody is using the lock region and we should initialize it.
3270          */
3271         if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3272
3273 #ifdef _WIN32
3274         size = GetFileSize(env->me_lfd, NULL);
3275 #else
3276         size = lseek(env->me_lfd, 0, SEEK_END);
3277 #endif
3278         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3279         if (size < rsize && *excl > 0) {
3280 #ifdef _WIN32
3281                 SetFilePointer(env->me_lfd, rsize, NULL, 0);
3282                 if (!SetEndOfFile(env->me_lfd)) goto fail_errno;
3283 #else
3284                 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3285 #endif
3286         } else {
3287                 rsize = size;
3288                 size = rsize - sizeof(MDB_txninfo);
3289                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3290         }
3291         {
3292 #ifdef _WIN32
3293                 HANDLE mh;
3294                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3295                         0, 0, NULL);
3296                 if (!mh) goto fail_errno;
3297                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3298                 CloseHandle(mh);
3299                 if (!env->me_txns) goto fail_errno;
3300 #else
3301                 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3302                         env->me_lfd, 0);
3303                 if (m == MAP_FAILED) goto fail_errno;
3304                 env->me_txns = m;
3305 #endif
3306         }
3307         if (*excl > 0) {
3308 #ifdef _WIN32
3309                 BY_HANDLE_FILE_INFORMATION stbuf;
3310                 struct {
3311                         DWORD volume;
3312                         DWORD nhigh;
3313                         DWORD nlow;
3314                 } idbuf;
3315                 MDB_val val;
3316                 char hexbuf[17];
3317
3318                 if (!mdb_sec_inited) {
3319                         InitializeSecurityDescriptor(&mdb_null_sd,
3320                                 SECURITY_DESCRIPTOR_REVISION);
3321                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3322                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3323                         mdb_all_sa.bInheritHandle = FALSE;
3324                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3325                         mdb_sec_inited = 1;
3326                 }
3327                 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3328                 idbuf.volume = stbuf.dwVolumeSerialNumber;
3329                 idbuf.nhigh  = stbuf.nFileIndexHigh;
3330                 idbuf.nlow   = stbuf.nFileIndexLow;
3331                 val.mv_data = &idbuf;
3332                 val.mv_size = sizeof(idbuf);
3333                 mdb_hash_hex(&val, hexbuf);
3334                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3335                 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3336                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3337                 if (!env->me_rmutex) goto fail_errno;
3338                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3339                 if (!env->me_wmutex) goto fail_errno;
3340 #elif defined(MDB_USE_POSIX_SEM)
3341                 struct stat stbuf;
3342                 struct {
3343                         dev_t dev;
3344                         ino_t ino;
3345                 } idbuf;
3346                 MDB_val val;
3347                 char hexbuf[17];
3348
3349                 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3350                 idbuf.dev = stbuf.st_dev;
3351                 idbuf.ino = stbuf.st_ino;
3352                 val.mv_data = &idbuf;
3353                 val.mv_size = sizeof(idbuf);
3354                 mdb_hash_hex(&val, hexbuf);
3355                 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3356                 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3357                 /* Clean up after a previous run, if needed:  Try to
3358                  * remove both semaphores before doing anything else.
3359                  */
3360                 sem_unlink(env->me_txns->mti_rmname);
3361                 sem_unlink(env->me_txns->mti_wmname);
3362                 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3363                         O_CREAT|O_EXCL, mode, 1);
3364                 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3365                 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3366                         O_CREAT|O_EXCL, mode, 1);
3367                 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3368 #else   /* MDB_USE_POSIX_SEM */
3369                 pthread_mutexattr_t mattr;
3370
3371                 if ((rc = pthread_mutexattr_init(&mattr))
3372                         || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3373                         || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3374                         || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3375                         goto fail;
3376                 pthread_mutexattr_destroy(&mattr);
3377 #endif  /* _WIN32 || MDB_USE_POSIX_SEM */
3378
3379                 env->me_txns->mti_version = MDB_VERSION;
3380                 env->me_txns->mti_magic = MDB_MAGIC;
3381                 env->me_txns->mti_txnid = 0;
3382                 env->me_txns->mti_numreaders = 0;
3383
3384         } else {
3385                 if (env->me_txns->mti_magic != MDB_MAGIC) {
3386                         DPUTS("lock region has invalid magic");
3387                         rc = MDB_INVALID;
3388                         goto fail;
3389                 }
3390                 if (env->me_txns->mti_version != MDB_VERSION) {
3391                         DPRINTF("lock region is version %u, expected version %u",
3392                                 env->me_txns->mti_version, MDB_VERSION);
3393                         rc = MDB_VERSION_MISMATCH;
3394                         goto fail;
3395                 }
3396                 rc = ErrCode();
3397                 if (rc != EACCES && rc != EAGAIN) {
3398                         goto fail;
3399                 }
3400 #ifdef _WIN32
3401                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3402                 if (!env->me_rmutex) goto fail_errno;
3403                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3404                 if (!env->me_wmutex) goto fail_errno;
3405 #elif defined(MDB_USE_POSIX_SEM)
3406                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3407                 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3408                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3409                 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3410 #endif
3411         }
3412         return MDB_SUCCESS;
3413
3414 fail_errno:
3415         rc = ErrCode();
3416 fail:
3417         return rc;
3418 }
3419
3420         /** The name of the lock file in the DB environment */
3421 #define LOCKNAME        "/lock.mdb"
3422         /** The name of the data file in the DB environment */
3423 #define DATANAME        "/data.mdb"
3424         /** The suffix of the lock file when no subdir is used */
3425 #define LOCKSUFF        "-lock"
3426         /** Only a subset of the @ref mdb_env flags can be changed
3427          *      at runtime. Changing other flags requires closing the
3428          *      environment and re-opening it with the new flags.
3429          */
3430 #define CHANGEABLE      (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3431 #define CHANGELESS      (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3432
3433 int
3434 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3435 {
3436         int             oflags, rc, len, excl = -1;
3437         char *lpath, *dpath;
3438
3439         if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3440                 return EINVAL;
3441
3442         len = strlen(path);
3443         if (flags & MDB_NOSUBDIR) {
3444                 rc = len + sizeof(LOCKSUFF) + len + 1;
3445         } else {
3446                 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3447         }
3448         lpath = malloc(rc);
3449         if (!lpath)
3450                 return ENOMEM;
3451         if (flags & MDB_NOSUBDIR) {
3452                 dpath = lpath + len + sizeof(LOCKSUFF);
3453                 sprintf(lpath, "%s" LOCKSUFF, path);
3454                 strcpy(dpath, path);
3455         } else {
3456                 dpath = lpath + len + sizeof(LOCKNAME);
3457                 sprintf(lpath, "%s" LOCKNAME, path);
3458                 sprintf(dpath, "%s" DATANAME, path);
3459         }
3460
3461         rc = MDB_SUCCESS;
3462         flags |= env->me_flags;
3463         if (flags & MDB_RDONLY) {
3464                 /* silently ignore WRITEMAP when we're only getting read access */
3465                 flags &= ~MDB_WRITEMAP;
3466         } else {
3467                 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3468                           (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3469                         rc = ENOMEM;
3470         }
3471         env->me_flags = flags |= MDB_ENV_ACTIVE;
3472         if (rc)
3473                 goto leave;
3474
3475         env->me_path = strdup(path);
3476         env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3477         env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3478         if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3479                 rc = ENOMEM;
3480                 goto leave;
3481         }
3482
3483         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3484         if (rc)
3485                 goto leave;
3486
3487 #ifdef _WIN32
3488         if (F_ISSET(flags, MDB_RDONLY)) {
3489                 oflags = GENERIC_READ;
3490                 len = OPEN_EXISTING;
3491         } else {
3492                 oflags = GENERIC_READ|GENERIC_WRITE;
3493                 len = OPEN_ALWAYS;
3494         }
3495         mode = FILE_ATTRIBUTE_NORMAL;
3496         env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3497                 NULL, len, mode, NULL);
3498 #else
3499         if (F_ISSET(flags, MDB_RDONLY))
3500                 oflags = O_RDONLY;
3501         else
3502                 oflags = O_RDWR | O_CREAT;
3503
3504         env->me_fd = open(dpath, oflags, mode);
3505 #endif
3506         if (env->me_fd == INVALID_HANDLE_VALUE) {
3507                 rc = ErrCode();
3508                 goto leave;
3509         }
3510
3511         if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3512                 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3513                         env->me_mfd = env->me_fd;
3514                 } else {
3515                         /* Synchronous fd for meta writes. Needed even with
3516                          * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3517                          */
3518 #ifdef _WIN32
3519                         env->me_mfd = CreateFile(dpath, oflags,
3520                                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3521                                 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3522 #else
3523                         env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3524 #endif
3525                         if (env->me_mfd == INVALID_HANDLE_VALUE) {
3526                                 rc = ErrCode();
3527                                 goto leave;
3528                         }
3529                 }
3530                 DPRINTF("opened dbenv %p", (void *) env);
3531                 if (excl > 0) {
3532                         rc = mdb_env_share_locks(env, &excl);
3533                 }
3534         }
3535
3536 leave:
3537         if (rc) {
3538                 mdb_env_close0(env, excl);
3539         }
3540         free(lpath);
3541         return rc;
3542 }
3543
3544 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
3545 static void
3546 mdb_env_close0(MDB_env *env, int excl)
3547 {
3548         int i;
3549
3550         if (!(env->me_flags & MDB_ENV_ACTIVE))
3551                 return;
3552
3553         /* Doing this here since me_dbxs may not exist during mdb_env_close */
3554         for (i = env->me_maxdbs; --i > MAIN_DBI; )
3555                 free(env->me_dbxs[i].md_name.mv_data);
3556
3557         free(env->me_dbflags);
3558         free(env->me_dbxs);
3559         free(env->me_path);
3560         free(env->me_dirty_list);
3561         if (env->me_free_pgs)
3562                 mdb_midl_free(env->me_free_pgs);
3563
3564         if (env->me_flags & MDB_ENV_TXKEY) {
3565                 pthread_key_delete(env->me_txkey);
3566 #ifdef _WIN32
3567                 /* Delete our key from the global list */
3568                 for (i=0; i<mdb_tls_nkeys; i++)
3569                         if (mdb_tls_keys[i] == env->me_txkey) {
3570                                 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3571                                 mdb_tls_nkeys--;
3572                                 break;
3573                         }
3574 #endif
3575         }
3576
3577         if (env->me_map) {
3578                 munmap(env->me_map, env->me_mapsize);
3579         }
3580         if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3581                 close(env->me_mfd);
3582         if (env->me_fd != INVALID_HANDLE_VALUE)
3583                 close(env->me_fd);
3584         if (env->me_txns) {
3585                 pid_t pid = env->me_pid;
3586                 /* Clearing readers is done in this function because
3587                  * me_txkey with its destructor must be disabled first.
3588                  */
3589                 for (i = env->me_numreaders; --i >= 0; )
3590                         if (env->me_txns->mti_readers[i].mr_pid == pid)
3591                                 env->me_txns->mti_readers[i].mr_pid = 0;
3592 #ifdef _WIN32
3593                 if (env->me_rmutex) {
3594                         CloseHandle(env->me_rmutex);
3595                         if (env->me_wmutex) CloseHandle(env->me_wmutex);
3596                 }
3597                 /* Windows automatically destroys the mutexes when
3598                  * the last handle closes.
3599                  */
3600 #elif defined(MDB_USE_POSIX_SEM)
3601                 if (env->me_rmutex != SEM_FAILED) {
3602                         sem_close(env->me_rmutex);
3603                         if (env->me_wmutex != SEM_FAILED)
3604                                 sem_close(env->me_wmutex);
3605                         /* If we have the filelock:  If we are the
3606                          * only remaining user, clean up semaphores.
3607                          */
3608                         if (excl == 0)
3609                                 mdb_env_excl_lock(env, &excl);
3610                         if (excl > 0) {
3611                                 sem_unlink(env->me_txns->mti_rmname);
3612                                 sem_unlink(env->me_txns->mti_wmname);
3613                         }
3614                 }
3615 #endif
3616                 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3617         }
3618         if (env->me_lfd != INVALID_HANDLE_VALUE) {
3619 #ifdef _WIN32
3620                 if (excl >= 0) {
3621                         /* Unlock the lockfile.  Windows would have unlocked it
3622                          * after closing anyway, but not necessarily at once.
3623                          */
3624                         UnlockFile(env->me_lfd, 0, 0, 1, 0);
3625                 }
3626 #endif
3627                 close(env->me_lfd);
3628         }
3629
3630         env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
3631 }
3632
3633 int
3634 mdb_env_copy(MDB_env *env, const char *path)
3635 {
3636         MDB_txn *txn = NULL;
3637         int rc, len;
3638         size_t wsize;
3639         char *lpath, *ptr;
3640         HANDLE newfd = INVALID_HANDLE_VALUE;
3641
3642         if (env->me_flags & MDB_NOSUBDIR) {
3643                 lpath = (char *)path;
3644         } else {
3645                 len = strlen(path);
3646                 len += sizeof(DATANAME);
3647                 lpath = malloc(len);
3648                 if (!lpath)
3649                         return ENOMEM;
3650                 sprintf(lpath, "%s" DATANAME, path);
3651         }
3652
3653         /* The destination path must exist, but the destination file must not.
3654          * We don't want the OS to cache the writes, since the source data is
3655          * already in the OS cache.
3656          */
3657 #ifdef _WIN32
3658         newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
3659                                 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
3660 #else
3661         newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
3662 #ifdef O_DIRECT
3663                 |O_DIRECT
3664 #endif
3665                 , 0666);
3666 #endif
3667         if (!(env->me_flags & MDB_NOSUBDIR))
3668                 free(lpath);
3669         if (newfd == INVALID_HANDLE_VALUE) {
3670                 rc = ErrCode();
3671                 goto leave;
3672         }
3673
3674 #ifdef F_NOCACHE        /* __APPLE__ */
3675         rc = fcntl(newfd, F_NOCACHE, 1);
3676         if (rc) {
3677                 rc = ErrCode();
3678                 goto leave;
3679         }
3680 #endif
3681
3682         /* Do the lock/unlock of the reader mutex before starting the
3683          * write txn.  Otherwise other read txns could block writers.
3684          */
3685         rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3686         if (rc)
3687                 goto leave;
3688
3689         if (env->me_txns) {
3690                 /* We must start the actual read txn after blocking writers */
3691                 mdb_txn_reset0(txn);
3692
3693                 /* Temporarily block writers until we snapshot the meta pages */
3694                 LOCK_MUTEX_W(env);
3695
3696                 rc = mdb_txn_renew0(txn);
3697                 if (rc) {
3698                         UNLOCK_MUTEX_W(env);
3699                         goto leave;
3700                 }
3701         }
3702
3703         wsize = env->me_psize * 2;
3704 #ifdef _WIN32
3705         {
3706                 DWORD len;
3707                 rc = WriteFile(newfd, env->me_map, wsize, &len, NULL);
3708                 rc = (len == wsize) ? MDB_SUCCESS : ErrCode();
3709         }
3710 #else
3711         rc = write(newfd, env->me_map, wsize);
3712         rc = (rc == (int)wsize) ? MDB_SUCCESS : ErrCode();
3713 #endif
3714         if (env->me_txns)
3715                 UNLOCK_MUTEX_W(env);
3716
3717         if (rc)
3718                 goto leave;
3719
3720         ptr = env->me_map + wsize;
3721         wsize = txn->mt_next_pgno * env->me_psize - wsize;
3722 #define MAX_WRITE       2147483648U
3723 #ifdef _WIN32
3724         while (wsize > 0) {
3725                 DWORD len, w2;
3726                 if (wsize > MAX_WRITE)
3727                         w2 = MAX_WRITE;
3728                 else
3729                         w2 = wsize;
3730                 rc = WriteFile(newfd, ptr, w2, &len, NULL);
3731                 rc = (len == w2) ? MDB_SUCCESS : ErrCode();
3732                 if (rc) break;
3733                 wsize -= w2;
3734                 ptr += w2;
3735         }
3736 #else
3737         while (wsize > 0) {
3738                 size_t w2;
3739                 ssize_t wres;
3740                 if (wsize > MAX_WRITE)
3741                         w2 = MAX_WRITE;
3742                 else
3743                         w2 = wsize;
3744                 wres = write(newfd, ptr, w2);
3745                 rc = (wres > 0) ? MDB_SUCCESS : ErrCode();
3746                 if (rc) break;
3747                 wsize -= wres;
3748                 ptr += wres;
3749         }
3750 #endif
3751
3752 leave:
3753         mdb_txn_abort(txn);
3754         if (newfd != INVALID_HANDLE_VALUE)
3755                 close(newfd);
3756
3757         return rc;
3758 }
3759
3760 void
3761 mdb_env_close(MDB_env *env)
3762 {
3763         MDB_page *dp;
3764
3765         if (env == NULL)
3766                 return;
3767
3768         VGMEMP_DESTROY(env);
3769         while ((dp = env->me_dpages) != NULL) {
3770                 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3771                 env->me_dpages = dp->mp_next;
3772                 free(dp);
3773         }
3774
3775         mdb_env_close0(env, 0);
3776         free(env);
3777 }
3778
3779 /** Compare two items pointing at aligned size_t's */
3780 static int
3781 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3782 {
3783         return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3784                 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3785 }
3786
3787 /** Compare two items pointing at aligned int's */
3788 static int
3789 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3790 {
3791         return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3792                 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3793 }
3794
3795 /** Compare two items pointing at ints of unknown alignment.
3796  *      Nodes and keys are guaranteed to be 2-byte aligned.
3797  */
3798 static int
3799 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3800 {
3801 #if BYTE_ORDER == LITTLE_ENDIAN
3802         unsigned short *u, *c;
3803         int x;
3804
3805         u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3806         c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3807         do {
3808                 x = *--u - *--c;
3809         } while(!x && u > (unsigned short *)a->mv_data);
3810         return x;
3811 #else
3812         return memcmp(a->mv_data, b->mv_data, a->mv_size);
3813 #endif
3814 }
3815
3816 /** Compare two items lexically */
3817 static int
3818 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3819 {
3820         int diff;
3821         ssize_t len_diff;
3822         unsigned int len;
3823
3824         len = a->mv_size;
3825         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3826         if (len_diff > 0) {
3827                 len = b->mv_size;
3828                 len_diff = 1;
3829         }
3830
3831         diff = memcmp(a->mv_data, b->mv_data, len);
3832         return diff ? diff : len_diff<0 ? -1 : len_diff;
3833 }
3834
3835 /** Compare two items in reverse byte order */
3836 static int
3837 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3838 {
3839         const unsigned char     *p1, *p2, *p1_lim;
3840         ssize_t len_diff;
3841         int diff;
3842
3843         p1_lim = (const unsigned char *)a->mv_data;
3844         p1 = (const unsigned char *)a->mv_data + a->mv_size;
3845         p2 = (const unsigned char *)b->mv_data + b->mv_size;
3846
3847         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3848         if (len_diff > 0) {
3849                 p1_lim += len_diff;
3850                 len_diff = 1;
3851         }
3852
3853         while (p1 > p1_lim) {
3854                 diff = *--p1 - *--p2;
3855                 if (diff)
3856                         return diff;
3857         }
3858         return len_diff<0 ? -1 : len_diff;
3859 }
3860
3861 /** Search for key within a page, using binary search.
3862  * Returns the smallest entry larger or equal to the key.
3863  * If exactp is non-null, stores whether the found entry was an exact match
3864  * in *exactp (1 or 0).
3865  * Updates the cursor index with the index of the found entry.
3866  * If no entry larger or equal to the key is found, returns NULL.
3867  */
3868 static MDB_node *
3869 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3870 {
3871         unsigned int     i = 0, nkeys;
3872         int              low, high;
3873         int              rc = 0;
3874         MDB_page *mp = mc->mc_pg[mc->mc_top];
3875         MDB_node        *node = NULL;
3876         MDB_val  nodekey;
3877         MDB_cmp_func *cmp;
3878         DKBUF;
3879
3880         nkeys = NUMKEYS(mp);
3881
3882 #if MDB_DEBUG
3883         {
3884         pgno_t pgno;
3885         COPY_PGNO(pgno, mp->mp_pgno);
3886         DPRINTF("searching %u keys in %s %spage %zu",
3887             nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3888             pgno);
3889         }
3890 #endif
3891
3892         assert(nkeys > 0);
3893
3894         low = IS_LEAF(mp) ? 0 : 1;
3895         high = nkeys - 1;
3896         cmp = mc->mc_dbx->md_cmp;
3897
3898         /* Branch pages have no data, so if using integer keys,
3899          * alignment is guaranteed. Use faster mdb_cmp_int.
3900          */
3901         if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3902                 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3903                         cmp = mdb_cmp_long;
3904                 else
3905                         cmp = mdb_cmp_int;
3906         }
3907
3908         if (IS_LEAF2(mp)) {
3909                 nodekey.mv_size = mc->mc_db->md_pad;
3910                 node = NODEPTR(mp, 0);  /* fake */
3911                 while (low <= high) {
3912                         i = (low + high) >> 1;
3913                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3914                         rc = cmp(key, &nodekey);
3915                         DPRINTF("found leaf index %u [%s], rc = %i",
3916                             i, DKEY(&nodekey), rc);
3917                         if (rc == 0)
3918                                 break;
3919                         if (rc > 0)
3920                                 low = i + 1;
3921                         else
3922                                 high = i - 1;
3923                 }
3924         } else {
3925                 while (low <= high) {
3926                         i = (low + high) >> 1;
3927
3928                         node = NODEPTR(mp, i);
3929                         nodekey.mv_size = NODEKSZ(node);
3930                         nodekey.mv_data = NODEKEY(node);
3931
3932                         rc = cmp(key, &nodekey);
3933 #if MDB_DEBUG
3934                         if (IS_LEAF(mp))
3935                                 DPRINTF("found leaf index %u [%s], rc = %i",
3936                                     i, DKEY(&nodekey), rc);
3937                         else
3938                                 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3939                                     i, DKEY(&nodekey), NODEPGNO(node), rc);
3940 #endif
3941                         if (rc == 0)
3942                                 break;
3943                         if (rc > 0)
3944                                 low = i + 1;
3945                         else
3946                                 high = i - 1;
3947                 }
3948         }
3949
3950         if (rc > 0) {   /* Found entry is less than the key. */
3951                 i++;    /* Skip to get the smallest entry larger than key. */
3952                 if (!IS_LEAF2(mp))
3953                         node = NODEPTR(mp, i);
3954         }
3955         if (exactp)
3956                 *exactp = (rc == 0);
3957         /* store the key index */
3958         mc->mc_ki[mc->mc_top] = i;
3959         if (i >= nkeys)
3960                 /* There is no entry larger or equal to the key. */
3961                 return NULL;
3962
3963         /* nodeptr is fake for LEAF2 */
3964         return node;
3965 }
3966
3967 #if 0
3968 static void
3969 mdb_cursor_adjust(MDB_cursor *mc, func)
3970 {
3971         MDB_cursor *m2;
3972
3973         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3974                 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3975                         func(mc, m2);
3976                 }
3977         }
3978 }
3979 #endif
3980
3981 /** Pop a page off the top of the cursor's stack. */
3982 static void
3983 mdb_cursor_pop(MDB_cursor *mc)
3984 {
3985         if (mc->mc_snum) {
3986 #ifndef MDB_DEBUG_SKIP
3987                 MDB_page        *top = mc->mc_pg[mc->mc_top];
3988 #endif
3989                 mc->mc_snum--;
3990                 if (mc->mc_snum)
3991                         mc->mc_top--;
3992
3993                 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3994                         mc->mc_dbi, (void *) mc);
3995         }
3996 }
3997
3998 /** Push a page onto the top of the cursor's stack. */
3999 static int
4000 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4001 {
4002         DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
4003                 mc->mc_dbi, (void *) mc);
4004
4005         if (mc->mc_snum >= CURSOR_STACK) {
4006                 assert(mc->mc_snum < CURSOR_STACK);
4007                 return MDB_CURSOR_FULL;
4008         }
4009
4010         mc->mc_top = mc->mc_snum++;
4011         mc->mc_pg[mc->mc_top] = mp;
4012         mc->mc_ki[mc->mc_top] = 0;
4013
4014         return MDB_SUCCESS;
4015 }
4016
4017 /** Find the address of the page corresponding to a given page number.
4018  * @param[in] txn the transaction for this access.
4019  * @param[in] pgno the page number for the page to retrieve.
4020  * @param[out] ret address of a pointer where the page's address will be stored.
4021  * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4022  * @return 0 on success, non-zero on failure.
4023  */
4024 static int
4025 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4026 {
4027         MDB_page *p = NULL;
4028         int level;
4029
4030         if (!((txn->mt_flags & MDB_TXN_RDONLY) |
4031                   (txn->mt_env->me_flags & MDB_WRITEMAP)))
4032         {
4033                 MDB_txn *tx2 = txn;
4034                 level = 1;
4035                 do {
4036                         MDB_ID2L dl = tx2->mt_u.dirty_list;
4037                         if (dl[0].mid) {
4038                                 unsigned x = mdb_mid2l_search(dl, pgno);
4039                                 if (x <= dl[0].mid && dl[x].mid == pgno) {
4040                                         p = dl[x].mptr;
4041                                         goto done;
4042                                 }
4043                         }
4044                         level++;
4045                 } while ((tx2 = tx2->mt_parent) != NULL);
4046         }
4047
4048         if (pgno < txn->mt_next_pgno) {
4049                 level = 0;
4050                 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4051         } else {
4052                 DPRINTF("page %zu not found", pgno);
4053                 assert(p != NULL);
4054                 return MDB_PAGE_NOTFOUND;
4055         }
4056
4057 done:
4058         *ret = p;
4059         if (lvl)
4060                 *lvl = level;
4061         return MDB_SUCCESS;
4062 }
4063
4064 /** Search for the page a given key should be in.
4065  * Pushes parent pages on the cursor stack. This function continues a
4066  * search on a cursor that has already been initialized. (Usually by
4067  * #mdb_page_search() but also by #mdb_node_move().)
4068  * @param[in,out] mc the cursor for this operation.
4069  * @param[in] key the key to search for. If NULL, search for the lowest
4070  * page. (This is used by #mdb_cursor_first().)
4071  * @param[in] modify If true, visited pages are updated with new page numbers.
4072  * @return 0 on success, non-zero on failure.
4073  */
4074 static int
4075 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4076 {
4077         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4078         DKBUF;
4079         int rc;
4080
4081
4082         while (IS_BRANCH(mp)) {
4083                 MDB_node        *node;
4084                 indx_t          i;
4085
4086                 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4087                 assert(NUMKEYS(mp) > 1);
4088                 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4089
4090                 if (key == NULL)        /* Initialize cursor to first page. */
4091                         i = 0;
4092                 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4093                                                         /* cursor to last page */
4094                         i = NUMKEYS(mp)-1;
4095                 } else {
4096                         int      exact;
4097                         node = mdb_node_search(mc, key, &exact);
4098                         if (node == NULL)
4099                                 i = NUMKEYS(mp) - 1;
4100                         else {
4101                                 i = mc->mc_ki[mc->mc_top];
4102                                 if (!exact) {
4103                                         assert(i > 0);
4104                                         i--;
4105                                 }
4106                         }
4107                 }
4108
4109                 if (key)
4110                         DPRINTF("following index %u for key [%s]",
4111                             i, DKEY(key));
4112                 assert(i < NUMKEYS(mp));
4113                 node = NODEPTR(mp, i);
4114
4115                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4116                         return rc;
4117
4118                 mc->mc_ki[mc->mc_top] = i;
4119                 if ((rc = mdb_cursor_push(mc, mp)))
4120                         return rc;
4121
4122                 if (modify) {
4123                         if ((rc = mdb_page_touch(mc)) != 0)
4124                                 return rc;
4125                         mp = mc->mc_pg[mc->mc_top];
4126                 }
4127         }
4128
4129         if (!IS_LEAF(mp)) {
4130                 DPRINTF("internal error, index points to a %02X page!?",
4131                     mp->mp_flags);
4132                 return MDB_CORRUPTED;
4133         }
4134
4135         DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4136             key ? DKEY(key) : NULL);
4137
4138         return MDB_SUCCESS;
4139 }
4140
4141 /** Search for the lowest key under the current branch page.
4142  * This just bypasses a NUMKEYS check in the current page
4143  * before calling mdb_page_search_root(), because the callers
4144  * are all in situations where the current page is known to
4145  * be underfilled.
4146  */
4147 static int
4148 mdb_page_search_lowest(MDB_cursor *mc)
4149 {
4150         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4151         MDB_node        *node = NODEPTR(mp, 0);
4152         int rc;
4153
4154         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4155                 return rc;
4156
4157         mc->mc_ki[mc->mc_top] = 0;
4158         if ((rc = mdb_cursor_push(mc, mp)))
4159                 return rc;
4160         return mdb_page_search_root(mc, NULL, 0);
4161 }
4162
4163 /** Search for the page a given key should be in.
4164  * Pushes parent pages on the cursor stack. This function just sets up
4165  * the search; it finds the root page for \b mc's database and sets this
4166  * as the root of the cursor's stack. Then #mdb_page_search_root() is
4167  * called to complete the search.
4168  * @param[in,out] mc the cursor for this operation.
4169  * @param[in] key the key to search for. If NULL, search for the lowest
4170  * page. (This is used by #mdb_cursor_first().)
4171  * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4172  *   If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4173  * @return 0 on success, non-zero on failure.
4174  */
4175 static int
4176 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4177 {
4178         int              rc;
4179         pgno_t           root;
4180
4181         /* Make sure the txn is still viable, then find the root from
4182          * the txn's db table.
4183          */
4184         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4185                 DPUTS("transaction has failed, must abort");
4186                 return EINVAL;
4187         } else {
4188                 /* Make sure we're using an up-to-date root */
4189                 if (mc->mc_dbi > MAIN_DBI) {
4190                         if ((*mc->mc_dbflag & DB_STALE) ||
4191                         ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4192                                 MDB_cursor mc2;
4193                                 unsigned char dbflag = 0;
4194                                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4195                                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4196                                 if (rc)
4197                                         return rc;
4198                                 if (*mc->mc_dbflag & DB_STALE) {
4199                                         MDB_val data;
4200                                         int exact = 0;
4201                                         uint16_t flags;
4202                                         MDB_node *leaf = mdb_node_search(&mc2,
4203                                                 &mc->mc_dbx->md_name, &exact);
4204                                         if (!exact)
4205                                                 return MDB_NOTFOUND;
4206                                         mdb_node_read(mc->mc_txn, leaf, &data);
4207                                         memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4208                                                 sizeof(uint16_t));
4209                                         /* The txn may not know this DBI, or another process may
4210                                          * have dropped and recreated the DB with other flags.
4211                                          */
4212                                         if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4213                                                 return MDB_INCOMPATIBLE;
4214                                         memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4215                                 }
4216                                 if (flags & MDB_PS_MODIFY)
4217                                         dbflag = DB_DIRTY;
4218                                 *mc->mc_dbflag &= ~DB_STALE;
4219                                 *mc->mc_dbflag |= dbflag;
4220                         }
4221                 }
4222                 root = mc->mc_db->md_root;
4223
4224                 if (root == P_INVALID) {                /* Tree is empty. */
4225                         DPUTS("tree is empty");
4226                         return MDB_NOTFOUND;
4227                 }
4228         }
4229
4230         assert(root > 1);
4231         if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4232                 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4233                         return rc;
4234
4235         mc->mc_snum = 1;
4236         mc->mc_top = 0;
4237
4238         DPRINTF("db %u root page %zu has flags 0x%X",
4239                 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4240
4241         if (flags & MDB_PS_MODIFY) {
4242                 if ((rc = mdb_page_touch(mc)))
4243                         return rc;
4244         }
4245
4246         if (flags & MDB_PS_ROOTONLY)
4247                 return MDB_SUCCESS;
4248
4249         return mdb_page_search_root(mc, key, flags);
4250 }
4251
4252 /** Return the data associated with a given node.
4253  * @param[in] txn The transaction for this operation.
4254  * @param[in] leaf The node being read.
4255  * @param[out] data Updated to point to the node's data.
4256  * @return 0 on success, non-zero on failure.
4257  */
4258 static int
4259 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4260 {
4261         MDB_page        *omp;           /* overflow page */
4262         pgno_t           pgno;
4263         int rc;
4264
4265         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4266                 data->mv_size = NODEDSZ(leaf);
4267                 data->mv_data = NODEDATA(leaf);
4268                 return MDB_SUCCESS;
4269         }
4270
4271         /* Read overflow data.
4272          */
4273         data->mv_size = NODEDSZ(leaf);
4274         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4275         if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4276                 DPRINTF("read overflow page %zu failed", pgno);
4277                 return rc;
4278         }
4279         data->mv_data = METADATA(omp);
4280
4281         return MDB_SUCCESS;
4282 }
4283
4284 int
4285 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4286     MDB_val *key, MDB_val *data)
4287 {
4288         MDB_cursor      mc;
4289         MDB_xcursor     mx;
4290         int exact = 0;
4291         DKBUF;
4292
4293         assert(key);
4294         assert(data);
4295         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4296
4297         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4298                 return EINVAL;
4299
4300         if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4301                 return EINVAL;
4302         }
4303
4304         mdb_cursor_init(&mc, txn, dbi, &mx);
4305         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4306 }
4307
4308 /** Find a sibling for a page.
4309  * Replaces the page at the top of the cursor's stack with the
4310  * specified sibling, if one exists.
4311  * @param[in] mc The cursor for this operation.
4312  * @param[in] move_right Non-zero if the right sibling is requested,
4313  * otherwise the left sibling.
4314  * @return 0 on success, non-zero on failure.
4315  */
4316 static int
4317 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4318 {
4319         int              rc;
4320         MDB_node        *indx;
4321         MDB_page        *mp;
4322
4323         if (mc->mc_snum < 2) {
4324                 return MDB_NOTFOUND;            /* root has no siblings */
4325         }
4326
4327         mdb_cursor_pop(mc);
4328         DPRINTF("parent page is page %zu, index %u",
4329                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4330
4331         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4332                        : (mc->mc_ki[mc->mc_top] == 0)) {
4333                 DPRINTF("no more keys left, moving to %s sibling",
4334                     move_right ? "right" : "left");
4335                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4336                         /* undo cursor_pop before returning */
4337                         mc->mc_top++;
4338                         mc->mc_snum++;
4339                         return rc;
4340                 }
4341         } else {
4342                 if (move_right)
4343                         mc->mc_ki[mc->mc_top]++;
4344                 else
4345                         mc->mc_ki[mc->mc_top]--;
4346                 DPRINTF("just moving to %s index key %u",
4347                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4348         }
4349         assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4350
4351         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4352         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4353                 return rc;
4354
4355         mdb_cursor_push(mc, mp);
4356         if (!move_right)
4357                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4358
4359         return MDB_SUCCESS;
4360 }
4361
4362 /** Move the cursor to the next data item. */
4363 static int
4364 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4365 {
4366         MDB_page        *mp;
4367         MDB_node        *leaf;
4368         int rc;
4369
4370         if (mc->mc_flags & C_EOF) {
4371                 return MDB_NOTFOUND;
4372         }
4373
4374         assert(mc->mc_flags & C_INITIALIZED);
4375
4376         mp = mc->mc_pg[mc->mc_top];
4377
4378         if (mc->mc_db->md_flags & MDB_DUPSORT) {
4379                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4380                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4381                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4382                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4383                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
4384                                         return rc;
4385                         }
4386                 } else {
4387                         mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4388                         if (op == MDB_NEXT_DUP)
4389                                 return MDB_NOTFOUND;
4390                 }
4391         }
4392
4393         DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4394
4395         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4396                 DPUTS("=====> move to next sibling page");
4397                 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
4398                         mc->mc_flags |= C_EOF;
4399                         mc->mc_flags &= ~C_INITIALIZED;
4400                         return MDB_NOTFOUND;
4401                 }
4402                 mp = mc->mc_pg[mc->mc_top];
4403                 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4404         } else
4405                 mc->mc_ki[mc->mc_top]++;
4406
4407         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4408             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4409
4410         if (IS_LEAF2(mp)) {
4411                 key->mv_size = mc->mc_db->md_pad;
4412                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4413                 return MDB_SUCCESS;
4414         }
4415
4416         assert(IS_LEAF(mp));
4417         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4418
4419         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4420                 mdb_xcursor_init1(mc, leaf);
4421         }
4422         if (data) {
4423                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4424                         return rc;
4425
4426                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4427                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4428                         if (rc != MDB_SUCCESS)
4429                                 return rc;
4430                 }
4431         }
4432
4433         MDB_GET_KEY(leaf, key);
4434         return MDB_SUCCESS;
4435 }
4436
4437 /** Move the cursor to the previous data item. */
4438 static int
4439 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4440 {
4441         MDB_page        *mp;
4442         MDB_node        *leaf;
4443         int rc;
4444
4445         assert(mc->mc_flags & C_INITIALIZED);
4446
4447         mp = mc->mc_pg[mc->mc_top];
4448
4449         if (mc->mc_db->md_flags & MDB_DUPSORT) {
4450                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4451                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4452                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4453                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4454                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
4455                                         return rc;
4456                         } else {
4457                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4458                                 if (op == MDB_PREV_DUP)
4459                                         return MDB_NOTFOUND;
4460                         }
4461                 }
4462         }
4463
4464         DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4465
4466         if (mc->mc_ki[mc->mc_top] == 0)  {
4467                 DPUTS("=====> move to prev sibling page");
4468                 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
4469                         mc->mc_flags &= ~C_INITIALIZED;
4470                         return MDB_NOTFOUND;
4471                 }
4472                 mp = mc->mc_pg[mc->mc_top];
4473                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4474                 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4475         } else
4476                 mc->mc_ki[mc->mc_top]--;
4477
4478         mc->mc_flags &= ~C_EOF;
4479
4480         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4481             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4482
4483         if (IS_LEAF2(mp)) {
4484                 key->mv_size = mc->mc_db->md_pad;
4485                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4486                 return MDB_SUCCESS;
4487         }
4488
4489         assert(IS_LEAF(mp));
4490         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4491
4492         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4493                 mdb_xcursor_init1(mc, leaf);
4494         }
4495         if (data) {
4496                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4497                         return rc;
4498
4499                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4500                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4501                         if (rc != MDB_SUCCESS)
4502                                 return rc;
4503                 }
4504         }
4505
4506         MDB_GET_KEY(leaf, key);
4507         return MDB_SUCCESS;
4508 }
4509
4510 /** Set the cursor on a specific data item. */
4511 static int
4512 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4513     MDB_cursor_op op, int *exactp)
4514 {
4515         int              rc;
4516         MDB_page        *mp;
4517         MDB_node        *leaf = NULL;
4518         DKBUF;
4519
4520         assert(mc);
4521         assert(key);
4522         assert(key->mv_size > 0);
4523
4524         /* See if we're already on the right page */
4525         if (mc->mc_flags & C_INITIALIZED) {
4526                 MDB_val nodekey;
4527
4528                 mp = mc->mc_pg[mc->mc_top];
4529                 if (!NUMKEYS(mp)) {
4530                         mc->mc_ki[mc->mc_top] = 0;
4531                         return MDB_NOTFOUND;
4532                 }
4533                 if (mp->mp_flags & P_LEAF2) {
4534                         nodekey.mv_size = mc->mc_db->md_pad;
4535                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4536                 } else {
4537                         leaf = NODEPTR(mp, 0);
4538                         MDB_GET_KEY(leaf, &nodekey);
4539                 }
4540                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4541                 if (rc == 0) {
4542                         /* Probably happens rarely, but first node on the page
4543                          * was the one we wanted.
4544                          */
4545                         mc->mc_ki[mc->mc_top] = 0;
4546                         if (exactp)
4547                                 *exactp = 1;
4548                         goto set1;
4549                 }
4550                 if (rc > 0) {
4551                         unsigned int i;
4552                         unsigned int nkeys = NUMKEYS(mp);
4553                         if (nkeys > 1) {
4554                                 if (mp->mp_flags & P_LEAF2) {
4555                                         nodekey.mv_data = LEAF2KEY(mp,
4556                                                  nkeys-1, nodekey.mv_size);
4557                                 } else {
4558                                         leaf = NODEPTR(mp, nkeys-1);
4559                                         MDB_GET_KEY(leaf, &nodekey);
4560                                 }
4561                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4562                                 if (rc == 0) {
4563                                         /* last node was the one we wanted */
4564                                         mc->mc_ki[mc->mc_top] = nkeys-1;
4565                                         if (exactp)
4566                                                 *exactp = 1;
4567                                         goto set1;
4568                                 }
4569                                 if (rc < 0) {
4570                                         if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4571                                                 /* This is definitely the right page, skip search_page */
4572                                                 if (mp->mp_flags & P_LEAF2) {
4573                                                         nodekey.mv_data = LEAF2KEY(mp,
4574                                                                  mc->mc_ki[mc->mc_top], nodekey.mv_size);
4575                                                 } else {
4576                                                         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4577                                                         MDB_GET_KEY(leaf, &nodekey);
4578                                                 }
4579                                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4580                                                 if (rc == 0) {
4581                                                         /* current node was the one we wanted */
4582                                                         if (exactp)
4583                                                                 *exactp = 1;
4584                                                         goto set1;
4585                                                 }
4586                                         }
4587                                         rc = 0;
4588                                         goto set2;
4589                                 }
4590                         }
4591                         /* If any parents have right-sibs, search.
4592                          * Otherwise, there's nothing further.
4593                          */
4594                         for (i=0; i<mc->mc_top; i++)
4595                                 if (mc->mc_ki[i] <
4596                                         NUMKEYS(mc->mc_pg[i])-1)
4597                                         break;
4598                         if (i == mc->mc_top) {
4599                                 /* There are no other pages */
4600                                 mc->mc_ki[mc->mc_top] = nkeys;
4601                                 return MDB_NOTFOUND;
4602                         }
4603                 }
4604                 if (!mc->mc_top) {
4605                         /* There are no other pages */
4606                         mc->mc_ki[mc->mc_top] = 0;
4607                         return MDB_NOTFOUND;
4608                 }
4609         }
4610
4611         rc = mdb_page_search(mc, key, 0);
4612         if (rc != MDB_SUCCESS)
4613                 return rc;
4614
4615         mp = mc->mc_pg[mc->mc_top];
4616         assert(IS_LEAF(mp));
4617
4618 set2:
4619         leaf = mdb_node_search(mc, key, exactp);
4620         if (exactp != NULL && !*exactp) {
4621                 /* MDB_SET specified and not an exact match. */
4622                 return MDB_NOTFOUND;
4623         }
4624
4625         if (leaf == NULL) {
4626                 DPUTS("===> inexact leaf not found, goto sibling");
4627                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
4628                         return rc;              /* no entries matched */
4629                 mp = mc->mc_pg[mc->mc_top];
4630                 assert(IS_LEAF(mp));
4631                 leaf = NODEPTR(mp, 0);
4632         }
4633
4634 set1:
4635         mc->mc_flags |= C_INITIALIZED;
4636         mc->mc_flags &= ~C_EOF;
4637
4638         if (IS_LEAF2(mp)) {
4639                 key->mv_size = mc->mc_db->md_pad;
4640                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4641                 return MDB_SUCCESS;
4642         }
4643
4644         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4645                 mdb_xcursor_init1(mc, leaf);
4646         }
4647         if (data) {
4648                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4649                         if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
4650                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4651                         } else {
4652                                 int ex2, *ex2p;
4653                                 if (op == MDB_GET_BOTH) {
4654                                         ex2p = &ex2;
4655                                         ex2 = 0;
4656                                 } else {
4657                                         ex2p = NULL;
4658                                 }
4659                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
4660                                 if (rc != MDB_SUCCESS)
4661                                         return rc;
4662                         }
4663                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
4664                         MDB_val d2;
4665                         if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
4666                                 return rc;
4667                         rc = mc->mc_dbx->md_dcmp(data, &d2);
4668                         if (rc) {
4669                                 if (op == MDB_GET_BOTH || rc > 0)
4670                                         return MDB_NOTFOUND;
4671                         }
4672
4673                 } else {
4674                         if (mc->mc_xcursor)
4675                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4676                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4677                                 return rc;
4678                 }
4679         }
4680
4681         /* The key already matches in all other cases */
4682         if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
4683                 MDB_GET_KEY(leaf, key);
4684         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
4685
4686         return rc;
4687 }
4688
4689 /** Move the cursor to the first item in the database. */
4690 static int
4691 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4692 {
4693         int              rc;
4694         MDB_node        *leaf;
4695
4696         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4697                 rc = mdb_page_search(mc, NULL, 0);
4698                 if (rc != MDB_SUCCESS)
4699                         return rc;
4700         }
4701         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4702
4703         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
4704         mc->mc_flags |= C_INITIALIZED;
4705         mc->mc_flags &= ~C_EOF;
4706
4707         mc->mc_ki[mc->mc_top] = 0;
4708
4709         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4710                 key->mv_size = mc->mc_db->md_pad;
4711                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4712                 return MDB_SUCCESS;
4713         }
4714
4715         if (data) {
4716                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4717                         mdb_xcursor_init1(mc, leaf);
4718                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4719                         if (rc)
4720                                 return rc;
4721                 } else {
4722                         if (mc->mc_xcursor)
4723                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4724                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4725                                 return rc;
4726                 }
4727         }
4728         MDB_GET_KEY(leaf, key);
4729         return MDB_SUCCESS;
4730 }
4731
4732 /** Move the cursor to the last item in the database. */
4733 static int
4734 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4735 {
4736         int              rc;
4737         MDB_node        *leaf;
4738
4739         if (!(mc->mc_flags & C_EOF)) {
4740
4741                 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4742                         MDB_val lkey;
4743
4744                         lkey.mv_size = MDB_MAXKEYSIZE+1;
4745                         lkey.mv_data = NULL;
4746                         rc = mdb_page_search(mc, &lkey, 0);
4747                         if (rc != MDB_SUCCESS)
4748                                 return rc;
4749                 }
4750                 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4751
4752         }
4753         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4754         mc->mc_flags |= C_INITIALIZED|C_EOF;
4755         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4756
4757         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4758                 key->mv_size = mc->mc_db->md_pad;
4759                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4760                 return MDB_SUCCESS;
4761         }
4762
4763         if (data) {
4764                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4765                         mdb_xcursor_init1(mc, leaf);
4766                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4767                         if (rc)
4768                                 return rc;
4769                 } else {
4770                         if (mc->mc_xcursor)
4771                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4772                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4773                                 return rc;
4774                 }
4775         }
4776
4777         MDB_GET_KEY(leaf, key);
4778         return MDB_SUCCESS;
4779 }
4780
4781 int
4782 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4783     MDB_cursor_op op)
4784 {
4785         int              rc;
4786         int              exact = 0;
4787
4788         assert(mc);
4789
4790         switch (op) {
4791         case MDB_GET_CURRENT:
4792                 if (!(mc->mc_flags & C_INITIALIZED)) {
4793                         rc = EINVAL;
4794                 } else {
4795                         MDB_page *mp = mc->mc_pg[mc->mc_top];
4796                         if (!NUMKEYS(mp)) {
4797                                 mc->mc_ki[mc->mc_top] = 0;
4798                                 rc = MDB_NOTFOUND;
4799                                 break;
4800                         }
4801                         rc = MDB_SUCCESS;
4802                         if (IS_LEAF2(mp)) {
4803                                 key->mv_size = mc->mc_db->md_pad;
4804                                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4805                         } else {
4806                                 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4807                                 MDB_GET_KEY(leaf, key);
4808                                 if (data) {
4809                                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4810                                                 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
4811                                         } else {
4812                                                 rc = mdb_node_read(mc->mc_txn, leaf, data);
4813                                         }
4814                                 }
4815                         }
4816                 }
4817                 break;
4818         case MDB_GET_BOTH:
4819         case MDB_GET_BOTH_RANGE:
4820                 if (data == NULL || mc->mc_xcursor == NULL) {
4821                         rc = EINVAL;
4822                         break;
4823                 }
4824                 /* FALLTHRU */
4825         case MDB_SET:
4826         case MDB_SET_KEY:
4827         case MDB_SET_RANGE:
4828                 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4829                         rc = EINVAL;
4830                 } else if (op == MDB_SET_RANGE)
4831                         rc = mdb_cursor_set(mc, key, data, op, NULL);
4832                 else
4833                         rc = mdb_cursor_set(mc, key, data, op, &exact);
4834                 break;
4835         case MDB_GET_MULTIPLE:
4836                 if (data == NULL ||
4837                         !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4838                         !(mc->mc_flags & C_INITIALIZED)) {
4839                         rc = EINVAL;
4840                         break;
4841                 }
4842                 rc = MDB_SUCCESS;
4843                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4844                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4845                         break;
4846                 goto fetchm;
4847         case MDB_NEXT_MULTIPLE:
4848                 if (data == NULL ||
4849                         !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4850                         rc = EINVAL;
4851                         break;
4852                 }
4853                 if (!(mc->mc_flags & C_INITIALIZED))
4854                         rc = mdb_cursor_first(mc, key, data);
4855                 else
4856                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4857                 if (rc == MDB_SUCCESS) {
4858                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4859                                 MDB_cursor *mx;
4860 fetchm:
4861                                 mx = &mc->mc_xcursor->mx_cursor;
4862                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4863                                         mx->mc_db->md_pad;
4864                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4865                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4866                         } else {
4867                                 rc = MDB_NOTFOUND;
4868                         }
4869                 }
4870                 break;
4871         case MDB_NEXT:
4872         case MDB_NEXT_DUP:
4873         case MDB_NEXT_NODUP:
4874                 if (!(mc->mc_flags & C_INITIALIZED))
4875                         rc = mdb_cursor_first(mc, key, data);
4876                 else
4877                         rc = mdb_cursor_next(mc, key, data, op);
4878                 break;
4879         case MDB_PREV:
4880         case MDB_PREV_DUP:
4881         case MDB_PREV_NODUP:
4882                 if (!(mc->mc_flags & C_INITIALIZED)) {
4883                         rc = mdb_cursor_last(mc, key, data);
4884                         mc->mc_flags |= C_INITIALIZED;
4885                         mc->mc_ki[mc->mc_top]++;
4886                 }
4887                 rc = mdb_cursor_prev(mc, key, data, op);
4888                 break;
4889         case MDB_FIRST:
4890                 rc = mdb_cursor_first(mc, key, data);
4891                 break;
4892         case MDB_FIRST_DUP:
4893                 if (data == NULL ||
4894                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4895                         !(mc->mc_flags & C_INITIALIZED) ||
4896                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4897                         rc = EINVAL;
4898                         break;
4899                 }
4900                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4901                 break;
4902         case MDB_LAST:
4903                 rc = mdb_cursor_last(mc, key, data);
4904                 break;
4905         case MDB_LAST_DUP:
4906                 if (data == NULL ||
4907                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4908                         !(mc->mc_flags & C_INITIALIZED) ||
4909                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4910                         rc = EINVAL;
4911                         break;
4912                 }
4913                 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4914                 break;
4915         default:
4916                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4917                 rc = EINVAL;
4918                 break;
4919         }
4920
4921         return rc;
4922 }
4923
4924 /** Touch all the pages in the cursor stack.
4925  *      Makes sure all the pages are writable, before attempting a write operation.
4926  * @param[in] mc The cursor to operate on.
4927  */
4928 static int
4929 mdb_cursor_touch(MDB_cursor *mc)
4930 {
4931         int rc;
4932
4933         if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4934                 MDB_cursor mc2;
4935                 MDB_xcursor mcx;
4936                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
4937                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4938                 if (rc)
4939                          return rc;
4940                 *mc->mc_dbflag |= DB_DIRTY;
4941         }
4942         for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4943                 rc = mdb_page_touch(mc);
4944                 if (rc)
4945                         return rc;
4946         }
4947         mc->mc_top = mc->mc_snum-1;
4948         return MDB_SUCCESS;
4949 }
4950
4951 int
4952 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4953     unsigned int flags)
4954 {
4955         MDB_node        *leaf = NULL;
4956         MDB_val xdata, *rdata, dkey;
4957         MDB_page        *fp;
4958         MDB_db dummy;
4959         int do_sub = 0, insert = 0;
4960         unsigned int mcount = 0;
4961         size_t nsize;
4962         int rc, rc2;
4963         MDB_pagebuf pbuf;
4964         char dbuf[MDB_MAXKEYSIZE+1];
4965         unsigned int nflags;
4966         DKBUF;
4967
4968         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4969                 return EACCES;
4970
4971         if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
4972                 return EINVAL;
4973
4974         if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
4975                 return EINVAL;
4976
4977 #if SIZE_MAX > MAXDATASIZE
4978         if (data->mv_size > MAXDATASIZE)
4979                 return EINVAL;
4980 #endif
4981
4982         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4983                 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4984
4985         dkey.mv_size = 0;
4986
4987         if (flags == MDB_CURRENT) {
4988                 if (!(mc->mc_flags & C_INITIALIZED))
4989                         return EINVAL;
4990                 rc = MDB_SUCCESS;
4991         } else if (mc->mc_db->md_root == P_INVALID) {
4992                 MDB_page *np;
4993                 /* new database, write a root leaf page */
4994                 DPUTS("allocating new root leaf page");
4995                 if ((rc = mdb_page_new(mc, P_LEAF, 1, &np))) {
4996                         return rc;
4997                 }
4998                 mc->mc_snum = 0;
4999                 mdb_cursor_push(mc, np);
5000                 mc->mc_db->md_root = np->mp_pgno;
5001                 mc->mc_db->md_depth++;
5002                 *mc->mc_dbflag |= DB_DIRTY;
5003                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5004                         == MDB_DUPFIXED)
5005                         np->mp_flags |= P_LEAF2;
5006                 mc->mc_flags |= C_INITIALIZED;
5007                 rc = MDB_NOTFOUND;
5008                 goto top;
5009         } else {
5010                 int exact = 0;
5011                 MDB_val d2;
5012                 if (flags & MDB_APPEND) {
5013                         MDB_val k2;
5014                         rc = mdb_cursor_last(mc, &k2, &d2);
5015                         if (rc == 0) {
5016                                 rc = mc->mc_dbx->md_cmp(key, &k2);
5017                                 if (rc > 0) {
5018                                         rc = MDB_NOTFOUND;
5019                                         mc->mc_ki[mc->mc_top]++;
5020                                 } else {
5021                                         /* new key is <= last key */
5022                                         rc = MDB_KEYEXIST;
5023                                 }
5024                         }
5025                 } else {
5026                 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5027                 }
5028                 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5029                         DPRINTF("duplicate key [%s]", DKEY(key));
5030                         *data = d2;
5031                         return MDB_KEYEXIST;
5032                 }
5033                 if (rc && rc != MDB_NOTFOUND)
5034                         return rc;
5035         }
5036
5037         /* Cursor is positioned, now make sure all pages are writable */
5038         rc2 = mdb_cursor_touch(mc);
5039         if (rc2)
5040                 return rc2;
5041
5042 top:
5043         /* The key already exists */
5044         if (rc == MDB_SUCCESS) {
5045                 /* there's only a key anyway, so this is a no-op */
5046                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5047                         unsigned int ksize = mc->mc_db->md_pad;
5048                         if (key->mv_size != ksize)
5049                                 return EINVAL;
5050                         if (flags == MDB_CURRENT) {
5051                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5052                                 memcpy(ptr, key->mv_data, ksize);
5053                         }
5054                         return MDB_SUCCESS;
5055                 }
5056
5057                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5058
5059                 /* DB has dups? */
5060                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5061                         /* Was a single item before, must convert now */
5062 more:
5063                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5064                                 /* Just overwrite the current item */
5065                                 if (flags == MDB_CURRENT)
5066                                         goto current;
5067
5068                                 dkey.mv_size = NODEDSZ(leaf);
5069                                 dkey.mv_data = NODEDATA(leaf);
5070 #if UINT_MAX < SIZE_MAX
5071                                 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5072 #ifdef MISALIGNED_OK
5073                                         mc->mc_dbx->md_dcmp = mdb_cmp_long;
5074 #else
5075                                         mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5076 #endif
5077 #endif
5078                                 /* if data matches, ignore it */
5079                                 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5080                                         return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5081
5082                                 /* create a fake page for the dup items */
5083                                 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5084                                 dkey.mv_data = dbuf;
5085                                 fp = (MDB_page *)&pbuf;
5086                                 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5087                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5088                                 fp->mp_lower = PAGEHDRSZ;
5089                                 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5090                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5091                                         fp->mp_flags |= P_LEAF2;
5092                                         fp->mp_pad = data->mv_size;
5093                                         fp->mp_upper += 2 * data->mv_size;      /* leave space for 2 more */
5094                                 } else {
5095                                         fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5096                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
5097                                 }
5098                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5099                                 do_sub = 1;
5100                                 rdata = &xdata;
5101                                 xdata.mv_size = fp->mp_upper;
5102                                 xdata.mv_data = fp;
5103                                 flags |= F_DUPDATA;
5104                                 goto new_sub;
5105                         }
5106                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5107                                 /* See if we need to convert from fake page to subDB */
5108                                 MDB_page *mp;
5109                                 unsigned int offset;
5110                                 unsigned int i;
5111
5112                                 fp = NODEDATA(leaf);
5113                                 if (flags == MDB_CURRENT) {
5114 reuse:
5115                                         fp->mp_flags |= P_DIRTY;
5116                                         COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5117                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5118                                         flags |= F_DUPDATA;
5119                                         goto put_sub;
5120                                 }
5121                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5122                                         offset = fp->mp_pad;
5123                                         if (SIZELEFT(fp) >= offset)
5124                                                 goto reuse;
5125                                         offset *= 4;    /* space for 4 more */
5126                                 } else {
5127                                         offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5128                                 }
5129                                 offset += offset & 1;
5130                                 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5131                                         offset >= mc->mc_txn->mt_env->me_nodemax) {
5132                                         /* yes, convert it */
5133                                         dummy.md_flags = 0;
5134                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5135                                                 dummy.md_pad = fp->mp_pad;
5136                                                 dummy.md_flags = MDB_DUPFIXED;
5137                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5138                                                         dummy.md_flags |= MDB_INTEGERKEY;
5139                                         }
5140                                         dummy.md_depth = 1;
5141                                         dummy.md_branch_pages = 0;
5142                                         dummy.md_leaf_pages = 1;
5143                                         dummy.md_overflow_pages = 0;
5144                                         dummy.md_entries = NUMKEYS(fp);
5145                                         rdata = &xdata;
5146                                         xdata.mv_size = sizeof(MDB_db);
5147                                         xdata.mv_data = &dummy;
5148                                         if ((rc = mdb_page_alloc(mc, 1, &mp)))
5149                                                 return rc;
5150                                         offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5151                                         flags |= F_DUPDATA|F_SUBDATA;
5152                                         dummy.md_root = mp->mp_pgno;
5153                                 } else {
5154                                         /* no, just grow it */
5155                                         rdata = &xdata;
5156                                         xdata.mv_size = NODEDSZ(leaf) + offset;
5157                                         xdata.mv_data = &pbuf;
5158                                         mp = (MDB_page *)&pbuf;
5159                                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5160                                         flags |= F_DUPDATA;
5161                                 }
5162                                 mp->mp_flags = fp->mp_flags | P_DIRTY;
5163                                 mp->mp_pad   = fp->mp_pad;
5164                                 mp->mp_lower = fp->mp_lower;
5165                                 mp->mp_upper = fp->mp_upper + offset;
5166                                 if (IS_LEAF2(fp)) {
5167                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5168                                 } else {
5169                                         nsize = NODEDSZ(leaf) - fp->mp_upper;
5170                                         memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5171                                         for (i=0; i<NUMKEYS(fp); i++)
5172                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5173                                 }
5174                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5175                                 do_sub = 1;
5176                                 goto new_sub;
5177                         }
5178                         /* data is on sub-DB, just store it */
5179                         flags |= F_DUPDATA|F_SUBDATA;
5180                         goto put_sub;
5181                 }
5182 current:
5183                 /* overflow page overwrites need special handling */
5184                 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5185                         MDB_page *omp;
5186                         pgno_t pg;
5187                         unsigned psize = mc->mc_txn->mt_env->me_psize;
5188                         int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5189
5190                         memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5191                         if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5192                                 return rc2;
5193                         ovpages = omp->mp_pages;
5194
5195                         /* Is the ov page writable and large enough? */
5196                         if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
5197                                 /* yes, overwrite it. Note in this case we don't
5198                                  * bother to try shrinking the page if the new data
5199                                  * is smaller than the overflow threshold.
5200                                  */
5201                                 if (level > 1) {
5202                                         /* It is writable only in a parent txn */
5203                                         size_t sz = (size_t) psize * ovpages, off;
5204                                         MDB_page *np = mdb_page_malloc(mc, ovpages);
5205                                         MDB_ID2 id2;
5206                                         if (!np)
5207                                                 return ENOMEM;
5208                                         id2.mid = pg;
5209                                         id2.mptr = np;
5210                                         mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5211                                         if (!(flags & MDB_RESERVE)) {
5212                                                 /* Copy end of page, adjusting alignment so
5213                                                  * compiler may copy words instead of bytes.
5214                                                  */
5215                                                 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5216                                                 memcpy((size_t *)((char *)np + off),
5217                                                         (size_t *)((char *)omp + off), sz - off);
5218                                                 sz = PAGEHDRSZ;
5219                                         }
5220                                         memcpy(np, omp, sz); /* Copy beginning of page */
5221                                         omp = np;
5222                                 }
5223                                 SETDSZ(leaf, data->mv_size);
5224                                 if (F_ISSET(flags, MDB_RESERVE))
5225                                         data->mv_data = METADATA(omp);
5226                                 else
5227                                         memcpy(METADATA(omp), data->mv_data, data->mv_size);
5228                                 goto done;
5229                         } else {
5230                                 /* no, free ovpages */
5231                                 int i;
5232                                 mc->mc_db->md_overflow_pages -= ovpages;
5233                                 for (i=0; i<ovpages; i++) {
5234                                         DPRINTF("freed ov page %zu", pg);
5235                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5236                                         pg++;
5237                                 }
5238                         }
5239                 } else if (NODEDSZ(leaf) == data->mv_size) {
5240                         /* same size, just replace it. Note that we could
5241                          * also reuse this node if the new data is smaller,
5242                          * but instead we opt to shrink the node in that case.
5243                          */
5244                         if (F_ISSET(flags, MDB_RESERVE))
5245                                 data->mv_data = NODEDATA(leaf);
5246                         else if (data->mv_size)
5247                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5248                         else
5249                                 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5250                         goto done;
5251                 }
5252                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5253                 mc->mc_db->md_entries--;
5254         } else {
5255                 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5256                 insert = 1;
5257         }
5258
5259         rdata = data;
5260
5261 new_sub:
5262         nflags = flags & NODE_ADD_FLAGS;
5263         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5264         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5265                 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5266                         nflags &= ~MDB_APPEND;
5267                 if (!insert)
5268                         nflags |= MDB_SPLIT_REPLACE;
5269                 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5270         } else {
5271                 /* There is room already in this leaf page. */
5272                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5273                 if (rc == 0 && !do_sub && insert) {
5274                         /* Adjust other cursors pointing to mp */
5275                         MDB_cursor *m2, *m3;
5276                         MDB_dbi dbi = mc->mc_dbi;
5277                         unsigned i = mc->mc_top;
5278                         MDB_page *mp = mc->mc_pg[i];
5279
5280                         if (mc->mc_flags & C_SUB)
5281                                 dbi--;
5282
5283                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5284                                 if (mc->mc_flags & C_SUB)
5285                                         m3 = &m2->mc_xcursor->mx_cursor;
5286                                 else
5287                                         m3 = m2;
5288                                 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5289                                 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5290                                         m3->mc_ki[i]++;
5291                                 }
5292                         }
5293                 }
5294         }
5295
5296         if (rc != MDB_SUCCESS)
5297                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5298         else {
5299                 /* Now store the actual data in the child DB. Note that we're
5300                  * storing the user data in the keys field, so there are strict
5301                  * size limits on dupdata. The actual data fields of the child
5302                  * DB are all zero size.
5303                  */
5304                 if (do_sub) {
5305                         int xflags;
5306 put_sub:
5307                         xdata.mv_size = 0;
5308                         xdata.mv_data = "";
5309                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5310                         if (flags & MDB_CURRENT) {
5311                                 xflags = MDB_CURRENT;
5312                         } else {
5313                                 mdb_xcursor_init1(mc, leaf);
5314                                 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
5315                         }
5316                         /* converted, write the original data first */
5317                         if (dkey.mv_size) {
5318                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5319                                 if (rc)
5320                                         return rc;
5321                                 {
5322                                         /* Adjust other cursors pointing to mp */
5323                                         MDB_cursor *m2;
5324                                         unsigned i = mc->mc_top;
5325                                         MDB_page *mp = mc->mc_pg[i];
5326
5327                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5328                                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5329                                                 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5330                                                         mdb_xcursor_init1(m2, leaf);
5331                                                 }
5332                                         }
5333                                 }
5334                                 /* we've done our job */
5335                                 dkey.mv_size = 0;
5336                         }
5337                         if (flags & MDB_APPENDDUP)
5338                                 xflags |= MDB_APPEND;
5339                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5340                         if (flags & F_SUBDATA) {
5341                                 void *db = NODEDATA(leaf);
5342                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5343                         }
5344                 }
5345                 /* sub-writes might have failed so check rc again.
5346                  * Don't increment count if we just replaced an existing item.
5347                  */
5348                 if (!rc && !(flags & MDB_CURRENT))
5349                         mc->mc_db->md_entries++;
5350                 if (flags & MDB_MULTIPLE) {
5351                         mcount++;
5352                         if (mcount < data[1].mv_size) {
5353                                 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5354                                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5355                                 goto more;
5356                         }
5357                 }
5358         }
5359 done:
5360         /* If we succeeded and the key didn't exist before, make sure
5361          * the cursor is marked valid.
5362          */
5363         if (!rc && insert)
5364                 mc->mc_flags |= C_INITIALIZED;
5365         return rc;
5366 }
5367
5368 int
5369 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5370 {
5371         MDB_node        *leaf;
5372         int rc;
5373
5374         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5375                 return EACCES;
5376
5377         if (!(mc->mc_flags & C_INITIALIZED))
5378                 return EINVAL;
5379
5380         rc = mdb_cursor_touch(mc);
5381         if (rc)
5382                 return rc;
5383
5384         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5385
5386         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5387                 if (flags != MDB_NODUPDATA) {
5388                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5389                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5390                         }
5391                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
5392                         /* If sub-DB still has entries, we're done */
5393                         if (mc->mc_xcursor->mx_db.md_entries) {
5394                                 if (leaf->mn_flags & F_SUBDATA) {
5395                                         /* update subDB info */
5396                                         void *db = NODEDATA(leaf);
5397                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5398                                 } else {
5399                                         /* shrink fake page */
5400                                         mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5401                                 }
5402                                 mc->mc_db->md_entries--;
5403                                 return rc;
5404                         }
5405                         /* otherwise fall thru and delete the sub-DB */
5406                 }
5407
5408                 if (leaf->mn_flags & F_SUBDATA) {
5409                         /* add all the child DB's pages to the free list */
5410                         rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5411                         if (rc == MDB_SUCCESS) {
5412                                 mc->mc_db->md_entries -=
5413                                         mc->mc_xcursor->mx_db.md_entries;
5414                         }
5415                 }
5416         }
5417
5418         return mdb_cursor_del0(mc, leaf);
5419 }
5420
5421 /** Allocate and initialize new pages for a database.
5422  * @param[in] mc a cursor on the database being added to.
5423  * @param[in] flags flags defining what type of page is being allocated.
5424  * @param[in] num the number of pages to allocate. This is usually 1,
5425  * unless allocating overflow pages for a large record.
5426  * @param[out] mp Address of a page, or NULL on failure.
5427  * @return 0 on success, non-zero on failure.
5428  */
5429 static int
5430 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5431 {
5432         MDB_page        *np;
5433         int rc;
5434
5435         if ((rc = mdb_page_alloc(mc, num, &np)))
5436                 return rc;
5437         DPRINTF("allocated new mpage %zu, page size %u",
5438             np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5439         np->mp_flags = flags | P_DIRTY;
5440         np->mp_lower = PAGEHDRSZ;
5441         np->mp_upper = mc->mc_txn->mt_env->me_psize;
5442
5443         if (IS_BRANCH(np))
5444                 mc->mc_db->md_branch_pages++;
5445         else if (IS_LEAF(np))
5446                 mc->mc_db->md_leaf_pages++;
5447         else if (IS_OVERFLOW(np)) {
5448                 mc->mc_db->md_overflow_pages += num;
5449                 np->mp_pages = num;
5450         }
5451         *mp = np;
5452
5453         return 0;
5454 }
5455
5456 /** Calculate the size of a leaf node.
5457  * The size depends on the environment's page size; if a data item
5458  * is too large it will be put onto an overflow page and the node
5459  * size will only include the key and not the data. Sizes are always
5460  * rounded up to an even number of bytes, to guarantee 2-byte alignment
5461  * of the #MDB_node headers.
5462  * @param[in] env The environment handle.
5463  * @param[in] key The key for the node.
5464  * @param[in] data The data for the node.
5465  * @return The number of bytes needed to store the node.
5466  */
5467 static size_t
5468 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5469 {
5470         size_t           sz;
5471
5472         sz = LEAFSIZE(key, data);
5473         if (sz >= env->me_nodemax) {
5474                 /* put on overflow page */
5475                 sz -= data->mv_size - sizeof(pgno_t);
5476         }
5477         sz += sz & 1;
5478
5479         return sz + sizeof(indx_t);
5480 }
5481
5482 /** Calculate the size of a branch node.
5483  * The size should depend on the environment's page size but since
5484  * we currently don't support spilling large keys onto overflow
5485  * pages, it's simply the size of the #MDB_node header plus the
5486  * size of the key. Sizes are always rounded up to an even number
5487  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5488  * @param[in] env The environment handle.
5489  * @param[in] key The key for the node.
5490  * @return The number of bytes needed to store the node.
5491  */
5492 static size_t
5493 mdb_branch_size(MDB_env *env, MDB_val *key)
5494 {
5495         size_t           sz;
5496
5497         sz = INDXSIZE(key);
5498         if (sz >= env->me_nodemax) {
5499                 /* put on overflow page */
5500                 /* not implemented */
5501                 /* sz -= key->size - sizeof(pgno_t); */
5502         }
5503
5504         return sz + sizeof(indx_t);
5505 }
5506
5507 /** Add a node to the page pointed to by the cursor.
5508  * @param[in] mc The cursor for this operation.
5509  * @param[in] indx The index on the page where the new node should be added.
5510  * @param[in] key The key for the new node.
5511  * @param[in] data The data for the new node, if any.
5512  * @param[in] pgno The page number, if adding a branch node.
5513  * @param[in] flags Flags for the node.
5514  * @return 0 on success, non-zero on failure. Possible errors are:
5515  * <ul>
5516  *      <li>ENOMEM - failed to allocate overflow pages for the node.
5517  *      <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5518  *      should never happen since all callers already calculate the
5519  *      page's free space before calling this function.
5520  * </ul>
5521  */
5522 static int
5523 mdb_node_add(MDB_cursor *mc, indx_t indx,
5524     MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5525 {
5526         unsigned int     i;
5527         size_t           node_size = NODESIZE;
5528         indx_t           ofs;
5529         MDB_node        *node;
5530         MDB_page        *mp = mc->mc_pg[mc->mc_top];
5531         MDB_page        *ofp = NULL;            /* overflow page */
5532         DKBUF;
5533
5534         assert(mp->mp_upper >= mp->mp_lower);
5535
5536         DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5537             IS_LEAF(mp) ? "leaf" : "branch",
5538                 IS_SUBP(mp) ? "sub-" : "",
5539             mp->mp_pgno, indx, data ? data->mv_size : 0,
5540                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5541
5542         if (IS_LEAF2(mp)) {
5543                 /* Move higher keys up one slot. */
5544                 int ksize = mc->mc_db->md_pad, dif;
5545                 char *ptr = LEAF2KEY(mp, indx, ksize);
5546                 dif = NUMKEYS(mp) - indx;
5547                 if (dif > 0)
5548                         memmove(ptr+ksize, ptr, dif*ksize);
5549                 /* insert new key */
5550                 memcpy(ptr, key->mv_data, ksize);
5551
5552                 /* Just using these for counting */
5553                 mp->mp_lower += sizeof(indx_t);
5554                 mp->mp_upper -= ksize - sizeof(indx_t);
5555                 return MDB_SUCCESS;
5556         }
5557
5558         if (key != NULL)
5559                 node_size += key->mv_size;
5560
5561         if (IS_LEAF(mp)) {
5562                 assert(data);
5563                 if (F_ISSET(flags, F_BIGDATA)) {
5564                         /* Data already on overflow page. */
5565                         node_size += sizeof(pgno_t);
5566                 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
5567                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5568                         int rc;
5569                         /* Put data on overflow page. */
5570                         DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
5571                             data->mv_size, node_size+data->mv_size);
5572                         node_size += sizeof(pgno_t);
5573                         if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
5574                                 return rc;
5575                         DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
5576                         flags |= F_BIGDATA;
5577                 } else {
5578                         node_size += data->mv_size;
5579                 }
5580         }
5581         node_size += node_size & 1;
5582
5583         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
5584                 DPRINTF("not enough room in page %zu, got %u ptrs",
5585                     mp->mp_pgno, NUMKEYS(mp));
5586                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
5587                     mp->mp_upper - mp->mp_lower);
5588                 DPRINTF("node size = %zu", node_size);
5589                 return MDB_PAGE_FULL;
5590         }
5591
5592         /* Move higher pointers up one slot. */
5593         for (i = NUMKEYS(mp); i > indx; i--)
5594                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
5595
5596         /* Adjust free space offsets. */
5597         ofs = mp->mp_upper - node_size;
5598         assert(ofs >= mp->mp_lower + sizeof(indx_t));
5599         mp->mp_ptrs[indx] = ofs;
5600         mp->mp_upper = ofs;
5601         mp->mp_lower += sizeof(indx_t);
5602
5603         /* Write the node data. */
5604         node = NODEPTR(mp, indx);
5605         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
5606         node->mn_flags = flags;
5607         if (IS_LEAF(mp))
5608                 SETDSZ(node,data->mv_size);
5609         else
5610                 SETPGNO(node,pgno);
5611
5612         if (key)
5613                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5614
5615         if (IS_LEAF(mp)) {
5616                 assert(key);
5617                 if (ofp == NULL) {
5618                         if (F_ISSET(flags, F_BIGDATA))
5619                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
5620                                     sizeof(pgno_t));
5621                         else if (F_ISSET(flags, MDB_RESERVE))
5622                                 data->mv_data = node->mn_data + key->mv_size;
5623                         else
5624                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
5625                                     data->mv_size);
5626                 } else {
5627                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
5628                             sizeof(pgno_t));
5629                         if (F_ISSET(flags, MDB_RESERVE))
5630                                 data->mv_data = METADATA(ofp);
5631                         else
5632                                 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
5633                 }
5634         }
5635
5636         return MDB_SUCCESS;
5637 }
5638
5639 /** Delete the specified node from a page.
5640  * @param[in] mp The page to operate on.
5641  * @param[in] indx The index of the node to delete.
5642  * @param[in] ksize The size of a node. Only used if the page is
5643  * part of a #MDB_DUPFIXED database.
5644  */
5645 static void
5646 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
5647 {
5648         unsigned int     sz;
5649         indx_t           i, j, numkeys, ptr;
5650         MDB_node        *node;
5651         char            *base;
5652
5653 #if MDB_DEBUG
5654         {
5655         pgno_t pgno;
5656         COPY_PGNO(pgno, mp->mp_pgno);
5657         DPRINTF("delete node %u on %s page %zu", indx,
5658             IS_LEAF(mp) ? "leaf" : "branch", pgno);
5659         }
5660 #endif
5661         assert(indx < NUMKEYS(mp));
5662
5663         if (IS_LEAF2(mp)) {
5664                 int x = NUMKEYS(mp) - 1 - indx;
5665                 base = LEAF2KEY(mp, indx, ksize);
5666                 if (x)
5667                         memmove(base, base + ksize, x * ksize);
5668                 mp->mp_lower -= sizeof(indx_t);
5669                 mp->mp_upper += ksize - sizeof(indx_t);
5670                 return;
5671         }
5672
5673         node = NODEPTR(mp, indx);
5674         sz = NODESIZE + node->mn_ksize;
5675         if (IS_LEAF(mp)) {
5676                 if (F_ISSET(node->mn_flags, F_BIGDATA))
5677                         sz += sizeof(pgno_t);
5678                 else
5679                         sz += NODEDSZ(node);
5680         }
5681         sz += sz & 1;
5682
5683         ptr = mp->mp_ptrs[indx];
5684         numkeys = NUMKEYS(mp);
5685         for (i = j = 0; i < numkeys; i++) {
5686                 if (i != indx) {
5687                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
5688                         if (mp->mp_ptrs[i] < ptr)
5689                                 mp->mp_ptrs[j] += sz;
5690                         j++;
5691                 }
5692         }
5693
5694         base = (char *)mp + mp->mp_upper;
5695         memmove(base + sz, base, ptr - mp->mp_upper);
5696
5697         mp->mp_lower -= sizeof(indx_t);
5698         mp->mp_upper += sz;
5699 }
5700
5701 /** Compact the main page after deleting a node on a subpage.
5702  * @param[in] mp The main page to operate on.
5703  * @param[in] indx The index of the subpage on the main page.
5704  */
5705 static void
5706 mdb_node_shrink(MDB_page *mp, indx_t indx)
5707 {
5708         MDB_node *node;
5709         MDB_page *sp, *xp;
5710         char *base;
5711         int osize, nsize;
5712         int delta;
5713         indx_t           i, numkeys, ptr;
5714
5715         node = NODEPTR(mp, indx);
5716         sp = (MDB_page *)NODEDATA(node);
5717         osize = NODEDSZ(node);
5718
5719         delta = sp->mp_upper - sp->mp_lower;
5720         SETDSZ(node, osize - delta);
5721         xp = (MDB_page *)((char *)sp + delta);
5722
5723         /* shift subpage upward */
5724         if (IS_LEAF2(sp)) {
5725                 nsize = NUMKEYS(sp) * sp->mp_pad;
5726                 memmove(METADATA(xp), METADATA(sp), nsize);
5727         } else {
5728                 int i;
5729                 nsize = osize - sp->mp_upper;
5730                 numkeys = NUMKEYS(sp);
5731                 for (i=numkeys-1; i>=0; i--)
5732                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
5733         }
5734         xp->mp_upper = sp->mp_lower;
5735         xp->mp_lower = sp->mp_lower;
5736         xp->mp_flags = sp->mp_flags;
5737         xp->mp_pad = sp->mp_pad;
5738         COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
5739
5740         /* shift lower nodes upward */
5741         ptr = mp->mp_ptrs[indx];
5742         numkeys = NUMKEYS(mp);
5743         for (i = 0; i < numkeys; i++) {
5744                 if (mp->mp_ptrs[i] <= ptr)
5745                         mp->mp_ptrs[i] += delta;
5746         }
5747
5748         base = (char *)mp + mp->mp_upper;
5749         memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
5750         mp->mp_upper += delta;
5751 }
5752
5753 /** Initial setup of a sorted-dups cursor.
5754  * Sorted duplicates are implemented as a sub-database for the given key.
5755  * The duplicate data items are actually keys of the sub-database.
5756  * Operations on the duplicate data items are performed using a sub-cursor
5757  * initialized when the sub-database is first accessed. This function does
5758  * the preliminary setup of the sub-cursor, filling in the fields that
5759  * depend only on the parent DB.
5760  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5761  */
5762 static void
5763 mdb_xcursor_init0(MDB_cursor *mc)
5764 {
5765         MDB_xcursor *mx = mc->mc_xcursor;
5766
5767         mx->mx_cursor.mc_xcursor = NULL;
5768         mx->mx_cursor.mc_txn = mc->mc_txn;
5769         mx->mx_cursor.mc_db = &mx->mx_db;
5770         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
5771         mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
5772         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
5773         mx->mx_cursor.mc_snum = 0;
5774         mx->mx_cursor.mc_top = 0;
5775         mx->mx_cursor.mc_flags = C_SUB;
5776         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
5777         mx->mx_dbx.md_dcmp = NULL;
5778         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
5779 }
5780
5781 /** Final setup of a sorted-dups cursor.
5782  *      Sets up the fields that depend on the data from the main cursor.
5783  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5784  * @param[in] node The data containing the #MDB_db record for the
5785  * sorted-dup database.
5786  */
5787 static void
5788 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5789 {
5790         MDB_xcursor *mx = mc->mc_xcursor;
5791
5792         if (node->mn_flags & F_SUBDATA) {
5793                 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5794                 mx->mx_cursor.mc_pg[0] = 0;
5795                 mx->mx_cursor.mc_snum = 0;
5796                 mx->mx_cursor.mc_flags = C_SUB;
5797         } else {
5798                 MDB_page *fp = NODEDATA(node);
5799                 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5800                 mx->mx_db.md_flags = 0;
5801                 mx->mx_db.md_depth = 1;
5802                 mx->mx_db.md_branch_pages = 0;
5803                 mx->mx_db.md_leaf_pages = 1;
5804                 mx->mx_db.md_overflow_pages = 0;
5805                 mx->mx_db.md_entries = NUMKEYS(fp);
5806                 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5807                 mx->mx_cursor.mc_snum = 1;
5808                 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5809                 mx->mx_cursor.mc_top = 0;
5810                 mx->mx_cursor.mc_pg[0] = fp;
5811                 mx->mx_cursor.mc_ki[0] = 0;
5812                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5813                         mx->mx_db.md_flags = MDB_DUPFIXED;
5814                         mx->mx_db.md_pad = fp->mp_pad;
5815                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5816                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5817                 }
5818         }
5819         DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5820                 mx->mx_db.md_root);
5821         mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
5822                 DB_DIRTY : 0);
5823         mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5824         mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5825 #if UINT_MAX < SIZE_MAX
5826         if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5827 #ifdef MISALIGNED_OK
5828                 mx->mx_dbx.md_cmp = mdb_cmp_long;
5829 #else
5830                 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5831 #endif
5832 #endif
5833 }
5834
5835 /** Initialize a cursor for a given transaction and database. */
5836 static void
5837 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5838 {
5839         mc->mc_orig = NULL;
5840         mc->mc_dbi = dbi;
5841         mc->mc_txn = txn;
5842         mc->mc_db = &txn->mt_dbs[dbi];
5843         mc->mc_dbx = &txn->mt_dbxs[dbi];
5844         mc->mc_dbflag = &txn->mt_dbflags[dbi];
5845         mc->mc_snum = 0;
5846         mc->mc_top = 0;
5847         mc->mc_pg[0] = 0;
5848         mc->mc_flags = 0;
5849         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5850                 assert(mx != NULL);
5851                 mc->mc_xcursor = mx;
5852                 mdb_xcursor_init0(mc);
5853         } else {
5854                 mc->mc_xcursor = NULL;
5855         }
5856         if (*mc->mc_dbflag & DB_STALE) {
5857                 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5858         }
5859 }
5860
5861 int
5862 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5863 {
5864         MDB_cursor      *mc;
5865         size_t size = sizeof(MDB_cursor);
5866
5867         if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
5868                 return EINVAL;
5869
5870         /* Allow read access to the freelist */
5871         if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5872                 return EINVAL;
5873
5874         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5875                 size += sizeof(MDB_xcursor);
5876
5877         if ((mc = malloc(size)) != NULL) {
5878                 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
5879                 if (txn->mt_cursors) {
5880                         mc->mc_next = txn->mt_cursors[dbi];
5881                         txn->mt_cursors[dbi] = mc;
5882                         mc->mc_flags |= C_UNTRACK;
5883                 }
5884                 mc->mc_flags |= C_ALLOCD;
5885         } else {
5886                 return ENOMEM;
5887         }
5888
5889         *ret = mc;
5890
5891         return MDB_SUCCESS;
5892 }
5893
5894 int
5895 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
5896 {
5897         unsigned flags;
5898
5899         if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
5900                 return EINVAL;
5901
5902         if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
5903                 return EINVAL;
5904
5905         flags = mc->mc_flags;
5906
5907         mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
5908
5909         mc->mc_flags |= (flags & C_ALLOCD);
5910         return MDB_SUCCESS;
5911 }
5912
5913 /* Return the count of duplicate data items for the current key */
5914 int
5915 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5916 {
5917         MDB_node        *leaf;
5918
5919         if (mc == NULL || countp == NULL)
5920                 return EINVAL;
5921
5922         if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5923                 return EINVAL;
5924
5925         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5926         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5927                 *countp = 1;
5928         } else {
5929                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5930                         return EINVAL;
5931
5932                 *countp = mc->mc_xcursor->mx_db.md_entries;
5933         }
5934         return MDB_SUCCESS;
5935 }
5936
5937 void
5938 mdb_cursor_close(MDB_cursor *mc)
5939 {
5940         if (mc != NULL) {
5941                 /* remove from txn, if tracked */
5942                 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
5943                         MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5944                         while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5945                         if (*prev == mc)
5946                                 *prev = mc->mc_next;
5947                 }
5948                 if (mc->mc_flags & C_ALLOCD)
5949                         free(mc);
5950         }
5951 }
5952
5953 MDB_txn *
5954 mdb_cursor_txn(MDB_cursor *mc)
5955 {
5956         if (!mc) return NULL;
5957         return mc->mc_txn;
5958 }
5959
5960 MDB_dbi
5961 mdb_cursor_dbi(MDB_cursor *mc)
5962 {
5963         assert(mc != NULL);
5964         return mc->mc_dbi;
5965 }
5966
5967 /** Replace the key for a node with a new key.
5968  * @param[in] mc Cursor pointing to the node to operate on.
5969  * @param[in] key The new key to use.
5970  * @return 0 on success, non-zero on failure.
5971  */
5972 static int
5973 mdb_update_key(MDB_cursor *mc, MDB_val *key)
5974 {
5975         MDB_page                *mp;
5976         MDB_node                *node;
5977         char                    *base;
5978         size_t                   len;
5979         int                      delta, delta0;
5980         indx_t                   ptr, i, numkeys, indx;
5981         DKBUF;
5982
5983         indx = mc->mc_ki[mc->mc_top];
5984         mp = mc->mc_pg[mc->mc_top];
5985         node = NODEPTR(mp, indx);
5986         ptr = mp->mp_ptrs[indx];
5987 #if MDB_DEBUG
5988         {
5989                 MDB_val k2;
5990                 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
5991                 k2.mv_data = NODEKEY(node);
5992                 k2.mv_size = node->mn_ksize;
5993                 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5994                         indx, ptr,
5995                         mdb_dkey(&k2, kbuf2),
5996                         DKEY(key),
5997                         mp->mp_pgno);
5998         }
5999 #endif
6000
6001         delta0 = delta = key->mv_size - node->mn_ksize;
6002
6003         /* Must be 2-byte aligned. If new key is
6004          * shorter by 1, the shift will be skipped.
6005          */
6006         delta += (delta & 1);
6007         if (delta) {
6008                 if (delta > 0 && SIZELEFT(mp) < delta) {
6009                         pgno_t pgno;
6010                         /* not enough space left, do a delete and split */
6011                         DPRINTF("Not enough room, delta = %d, splitting...", delta);
6012                         pgno = NODEPGNO(node);
6013                         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6014                         return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6015                 }
6016
6017                 numkeys = NUMKEYS(mp);
6018                 for (i = 0; i < numkeys; i++) {
6019                         if (mp->mp_ptrs[i] <= ptr)
6020                                 mp->mp_ptrs[i] -= delta;
6021                 }
6022
6023                 base = (char *)mp + mp->mp_upper;
6024                 len = ptr - mp->mp_upper + NODESIZE;
6025                 memmove(base - delta, base, len);
6026                 mp->mp_upper -= delta;
6027
6028                 node = NODEPTR(mp, indx);
6029         }
6030
6031         /* But even if no shift was needed, update ksize */
6032         if (delta0)
6033                 node->mn_ksize = key->mv_size;
6034
6035         if (key->mv_size)
6036                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6037
6038         return MDB_SUCCESS;
6039 }
6040
6041 static void
6042 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6043
6044 /** Move a node from csrc to cdst.
6045  */
6046 static int
6047 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6048 {
6049         MDB_node                *srcnode;
6050         MDB_val          key, data;
6051         pgno_t  srcpg;
6052         MDB_cursor mn;
6053         int                      rc;
6054         unsigned short flags;
6055
6056         DKBUF;
6057
6058         /* Mark src and dst as dirty. */
6059         if ((rc = mdb_page_touch(csrc)) ||
6060             (rc = mdb_page_touch(cdst)))
6061                 return rc;
6062
6063         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6064                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
6065                 key.mv_size = csrc->mc_db->md_pad;
6066                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6067                 data.mv_size = 0;
6068                 data.mv_data = NULL;
6069                 srcpg = 0;
6070                 flags = 0;
6071         } else {
6072                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6073                 assert(!((long)srcnode&1));
6074                 srcpg = NODEPGNO(srcnode);
6075                 flags = srcnode->mn_flags;
6076                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6077                         unsigned int snum = csrc->mc_snum;
6078                         MDB_node *s2;
6079                         /* must find the lowest key below src */
6080                         mdb_page_search_lowest(csrc);
6081                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6082                                 key.mv_size = csrc->mc_db->md_pad;
6083                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6084                         } else {
6085                                 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6086                                 key.mv_size = NODEKSZ(s2);
6087                                 key.mv_data = NODEKEY(s2);
6088                         }
6089                         csrc->mc_snum = snum--;
6090                         csrc->mc_top = snum;
6091                 } else {
6092                         key.mv_size = NODEKSZ(srcnode);
6093                         key.mv_data = NODEKEY(srcnode);
6094                 }
6095                 data.mv_size = NODEDSZ(srcnode);
6096                 data.mv_data = NODEDATA(srcnode);
6097         }
6098         if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6099                 unsigned int snum = cdst->mc_snum;
6100                 MDB_node *s2;
6101                 MDB_val bkey;
6102                 /* must find the lowest key below dst */
6103                 mdb_page_search_lowest(cdst);
6104                 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6105                         bkey.mv_size = cdst->mc_db->md_pad;
6106                         bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6107                 } else {
6108                         s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6109                         bkey.mv_size = NODEKSZ(s2);
6110                         bkey.mv_data = NODEKEY(s2);
6111                 }
6112                 cdst->mc_snum = snum--;
6113                 cdst->mc_top = snum;
6114                 mdb_cursor_copy(cdst, &mn);
6115                 mn.mc_ki[snum] = 0;
6116                 rc = mdb_update_key(&mn, &bkey);
6117                 if (rc)
6118                         return rc;
6119         }
6120
6121         DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6122             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6123             csrc->mc_ki[csrc->mc_top],
6124                 DKEY(&key),
6125             csrc->mc_pg[csrc->mc_top]->mp_pgno,
6126             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6127
6128         /* Add the node to the destination page.
6129          */
6130         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6131         if (rc != MDB_SUCCESS)
6132                 return rc;
6133
6134         /* Delete the node from the source page.
6135          */
6136         mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6137
6138         {
6139                 /* Adjust other cursors pointing to mp */
6140                 MDB_cursor *m2, *m3;
6141                 MDB_dbi dbi = csrc->mc_dbi;
6142                 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6143
6144                 if (csrc->mc_flags & C_SUB)
6145                         dbi--;
6146
6147                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6148                         if (m2 == csrc) continue;
6149                         if (csrc->mc_flags & C_SUB)
6150                                 m3 = &m2->mc_xcursor->mx_cursor;
6151                         else
6152                                 m3 = m2;
6153                         if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6154                                 csrc->mc_ki[csrc->mc_top]) {
6155                                 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6156                                 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6157                         }
6158                 }
6159         }
6160
6161         /* Update the parent separators.
6162          */
6163         if (csrc->mc_ki[csrc->mc_top] == 0) {
6164                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6165                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6166                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6167                         } else {
6168                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6169                                 key.mv_size = NODEKSZ(srcnode);
6170                                 key.mv_data = NODEKEY(srcnode);
6171                         }
6172                         DPRINTF("update separator for source page %zu to [%s]",
6173                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6174                         mdb_cursor_copy(csrc, &mn);
6175                         mn.mc_snum--;
6176                         mn.mc_top--;
6177                         if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6178                                 return rc;
6179                 }
6180                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6181                         MDB_val  nullkey;
6182                         indx_t  ix = csrc->mc_ki[csrc->mc_top];
6183                         nullkey.mv_size = 0;
6184                         csrc->mc_ki[csrc->mc_top] = 0;
6185                         rc = mdb_update_key(csrc, &nullkey);
6186                         csrc->mc_ki[csrc->mc_top] = ix;
6187                         assert(rc == MDB_SUCCESS);
6188                 }
6189         }
6190
6191         if (cdst->mc_ki[cdst->mc_top] == 0) {
6192                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6193                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6194                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6195                         } else {
6196                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6197                                 key.mv_size = NODEKSZ(srcnode);
6198                                 key.mv_data = NODEKEY(srcnode);
6199                         }
6200                         DPRINTF("update separator for destination page %zu to [%s]",
6201                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6202                         mdb_cursor_copy(cdst, &mn);
6203                         mn.mc_snum--;
6204                         mn.mc_top--;
6205                         if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6206                                 return rc;
6207                 }
6208                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6209                         MDB_val  nullkey;
6210                         indx_t  ix = cdst->mc_ki[cdst->mc_top];
6211                         nullkey.mv_size = 0;
6212                         cdst->mc_ki[cdst->mc_top] = 0;
6213                         rc = mdb_update_key(cdst, &nullkey);
6214                         cdst->mc_ki[cdst->mc_top] = ix;
6215                         assert(rc == MDB_SUCCESS);
6216                 }
6217         }
6218
6219         return MDB_SUCCESS;
6220 }
6221
6222 /** Merge one page into another.
6223  *  The nodes from the page pointed to by \b csrc will
6224  *      be copied to the page pointed to by \b cdst and then
6225  *      the \b csrc page will be freed.
6226  * @param[in] csrc Cursor pointing to the source page.
6227  * @param[in] cdst Cursor pointing to the destination page.
6228  */
6229 static int
6230 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6231 {
6232         int                      rc;
6233         indx_t                   i, j;
6234         MDB_node                *srcnode;
6235         MDB_val          key, data;
6236         unsigned        nkeys;
6237
6238         DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6239                 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6240
6241         assert(csrc->mc_snum > 1);      /* can't merge root page */
6242         assert(cdst->mc_snum > 1);
6243
6244         /* Mark dst as dirty. */
6245         if ((rc = mdb_page_touch(cdst)))
6246                 return rc;
6247
6248         /* Move all nodes from src to dst.
6249          */
6250         j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6251         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6252                 key.mv_size = csrc->mc_db->md_pad;
6253                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6254                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6255                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6256                         if (rc != MDB_SUCCESS)
6257                                 return rc;
6258                         key.mv_data = (char *)key.mv_data + key.mv_size;
6259                 }
6260         } else {
6261                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6262                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6263                         if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6264                                 unsigned int snum = csrc->mc_snum;
6265                                 MDB_node *s2;
6266                                 /* must find the lowest key below src */
6267                                 mdb_page_search_lowest(csrc);
6268                                 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6269                                         key.mv_size = csrc->mc_db->md_pad;
6270                                         key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6271                                 } else {
6272                                         s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6273                                         key.mv_size = NODEKSZ(s2);
6274                                         key.mv_data = NODEKEY(s2);
6275                                 }
6276                                 csrc->mc_snum = snum--;
6277                                 csrc->mc_top = snum;
6278                         } else {
6279                                 key.mv_size = srcnode->mn_ksize;
6280                                 key.mv_data = NODEKEY(srcnode);
6281                         }
6282
6283                         data.mv_size = NODEDSZ(srcnode);
6284                         data.mv_data = NODEDATA(srcnode);
6285                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6286                         if (rc != MDB_SUCCESS)
6287                                 return rc;
6288                 }
6289         }
6290
6291         DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6292             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);
6293
6294         /* Unlink the src page from parent and add to free list.
6295          */
6296         mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6297         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6298                 key.mv_size = 0;
6299                 csrc->mc_top--;
6300                 rc = mdb_update_key(csrc, &key);
6301                 csrc->mc_top++;
6302                 if (rc)
6303                         return rc;
6304         }
6305
6306         mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
6307         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6308                 csrc->mc_db->md_leaf_pages--;
6309         else
6310                 csrc->mc_db->md_branch_pages--;
6311         {
6312                 /* Adjust other cursors pointing to mp */
6313                 MDB_cursor *m2, *m3;
6314                 MDB_dbi dbi = csrc->mc_dbi;
6315                 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6316
6317                 if (csrc->mc_flags & C_SUB)
6318                         dbi--;
6319
6320                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6321                         if (csrc->mc_flags & C_SUB)
6322                                 m3 = &m2->mc_xcursor->mx_cursor;
6323                         else
6324                                 m3 = m2;
6325                         if (m3 == csrc) continue;
6326                         if (m3->mc_snum < csrc->mc_snum) continue;
6327                         if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6328                                 m3->mc_pg[csrc->mc_top] = mp;
6329                                 m3->mc_ki[csrc->mc_top] += nkeys;
6330                         }
6331                 }
6332         }
6333         mdb_cursor_pop(csrc);
6334
6335         return mdb_rebalance(csrc);
6336 }
6337
6338 /** Copy the contents of a cursor.
6339  * @param[in] csrc The cursor to copy from.
6340  * @param[out] cdst The cursor to copy to.
6341  */
6342 static void
6343 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6344 {
6345         unsigned int i;
6346
6347         cdst->mc_txn = csrc->mc_txn;
6348         cdst->mc_dbi = csrc->mc_dbi;
6349         cdst->mc_db  = csrc->mc_db;
6350         cdst->mc_dbx = csrc->mc_dbx;
6351         cdst->mc_snum = csrc->mc_snum;
6352         cdst->mc_top = csrc->mc_top;
6353         cdst->mc_flags = csrc->mc_flags;
6354
6355         for (i=0; i<csrc->mc_snum; i++) {
6356                 cdst->mc_pg[i] = csrc->mc_pg[i];
6357                 cdst->mc_ki[i] = csrc->mc_ki[i];
6358         }
6359 }
6360
6361 /** Rebalance the tree after a delete operation.
6362  * @param[in] mc Cursor pointing to the page where rebalancing
6363  * should begin.
6364  * @return 0 on success, non-zero on failure.
6365  */
6366 static int
6367 mdb_rebalance(MDB_cursor *mc)
6368 {
6369         MDB_node        *node;
6370         int rc;
6371         unsigned int ptop, minkeys;
6372         MDB_cursor      mn;
6373
6374         minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6375 #if MDB_DEBUG
6376         {
6377         pgno_t pgno;
6378         COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6379         DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6380             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6381             pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6382         }
6383 #endif
6384
6385         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6386                 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6387 #if MDB_DEBUG
6388                 pgno_t pgno;
6389                 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6390                 DPRINTF("no need to rebalance page %zu, above fill threshold",
6391                     pgno);
6392 #endif
6393                 return MDB_SUCCESS;
6394         }
6395
6396         if (mc->mc_snum < 2) {
6397                 MDB_page *mp = mc->mc_pg[0];
6398                 if (IS_SUBP(mp)) {
6399                         DPUTS("Can't rebalance a subpage, ignoring");
6400                         return MDB_SUCCESS;
6401                 }
6402                 if (NUMKEYS(mp) == 0) {
6403                         DPUTS("tree is completely empty");
6404                         mc->mc_db->md_root = P_INVALID;
6405                         mc->mc_db->md_depth = 0;
6406                         mc->mc_db->md_leaf_pages = 0;
6407                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6408                         mc->mc_snum = 0;
6409                         mc->mc_top = 0;
6410                         {
6411                                 /* Adjust other cursors pointing to mp */
6412                                 MDB_cursor *m2, *m3;
6413                                 MDB_dbi dbi = mc->mc_dbi;
6414
6415                                 if (mc->mc_flags & C_SUB)
6416                                         dbi--;
6417
6418                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6419                                         if (m2 == mc) continue;
6420                                         if (mc->mc_flags & C_SUB)
6421                                                 m3 = &m2->mc_xcursor->mx_cursor;
6422                                         else
6423                                                 m3 = m2;
6424                                         if (m3->mc_snum < mc->mc_snum) continue;
6425                                         if (m3->mc_pg[0] == mp) {
6426                                                 m3->mc_snum = 0;
6427                                                 m3->mc_top = 0;
6428                                         }
6429                                 }
6430                         }
6431                 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6432                         DPUTS("collapsing root page!");
6433                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6434                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6435                         rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
6436                         if (rc)
6437                                 return rc;
6438                         mc->mc_db->md_depth--;
6439                         mc->mc_db->md_branch_pages--;
6440                         {
6441                                 /* Adjust other cursors pointing to mp */
6442                                 MDB_cursor *m2, *m3;
6443                                 MDB_dbi dbi = mc->mc_dbi;
6444
6445                                 if (mc->mc_flags & C_SUB)
6446                                         dbi--;
6447
6448                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6449                                         if (m2 == mc) continue;
6450                                         if (mc->mc_flags & C_SUB)
6451                                                 m3 = &m2->mc_xcursor->mx_cursor;
6452                                         else
6453                                                 m3 = m2;
6454                                         if (m3->mc_snum < mc->mc_snum) continue;
6455                                         if (m3->mc_pg[0] == mp) {
6456                                                 m3->mc_pg[0] = mc->mc_pg[0];
6457                                                 m3->mc_snum = 1;
6458                                                 m3->mc_top = 0;
6459                                         }
6460                                 }
6461                         }
6462                 } else
6463                         DPUTS("root page doesn't need rebalancing");
6464                 return MDB_SUCCESS;
6465         }
6466
6467         /* The parent (branch page) must have at least 2 pointers,
6468          * otherwise the tree is invalid.
6469          */
6470         ptop = mc->mc_top-1;
6471         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6472
6473         /* Leaf page fill factor is below the threshold.
6474          * Try to move keys from left or right neighbor, or
6475          * merge with a neighbor page.
6476          */
6477
6478         /* Find neighbors.
6479          */
6480         mdb_cursor_copy(mc, &mn);
6481         mn.mc_xcursor = NULL;
6482
6483         if (mc->mc_ki[ptop] == 0) {
6484                 /* We're the leftmost leaf in our parent.
6485                  */
6486                 DPUTS("reading right neighbor");
6487                 mn.mc_ki[ptop]++;
6488                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6489                 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6490                 if (rc)
6491                         return rc;
6492                 mn.mc_ki[mn.mc_top] = 0;
6493                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6494         } else {
6495                 /* There is at least one neighbor to the left.
6496                  */
6497                 DPUTS("reading left neighbor");
6498                 mn.mc_ki[ptop]--;
6499                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6500                 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6501                 if (rc)
6502                         return rc;
6503                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6504                 mc->mc_ki[mc->mc_top] = 0;
6505         }
6506
6507         DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6508             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);
6509
6510         /* If the neighbor page is above threshold and has enough keys,
6511          * move one key from it. Otherwise we should try to merge them.
6512          * (A branch page must never have less than 2 keys.)
6513          */
6514         minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
6515         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
6516                 return mdb_node_move(&mn, mc);
6517         else {
6518                 if (mc->mc_ki[ptop] == 0)
6519                         rc = mdb_page_merge(&mn, mc);
6520                 else
6521                         rc = mdb_page_merge(mc, &mn);
6522                 mc->mc_flags &= ~C_INITIALIZED;
6523         }
6524         return rc;
6525 }
6526
6527 /** Complete a delete operation started by #mdb_cursor_del(). */
6528 static int
6529 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6530 {
6531         int rc;
6532
6533         /* add overflow pages to free list */
6534         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6535                 int i, ovpages;
6536                 MDB_page *omp;
6537                 pgno_t pg;
6538
6539                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6540                 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) != 0)
6541                         return rc;
6542                 assert(IS_OVERFLOW(omp));
6543                 ovpages = omp->mp_pages;
6544                 mc->mc_db->md_overflow_pages -= ovpages;
6545                 for (i=0; i<ovpages; i++) {
6546                         DPRINTF("freed ov page %zu", pg);
6547                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6548                         pg++;
6549                 }
6550         }
6551         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
6552         mc->mc_db->md_entries--;
6553         rc = mdb_rebalance(mc);
6554         if (rc != MDB_SUCCESS)
6555                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6556         /* if mc points past last node in page, invalidate */
6557         else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6558                 mc->mc_flags &= ~C_INITIALIZED;
6559
6560         return rc;
6561 }
6562
6563 int
6564 mdb_del(MDB_txn *txn, MDB_dbi dbi,
6565     MDB_val *key, MDB_val *data)
6566 {
6567         MDB_cursor mc;
6568         MDB_xcursor mx;
6569         MDB_cursor_op op;
6570         MDB_val rdata, *xdata;
6571         int              rc, exact;
6572         DKBUF;
6573
6574         assert(key != NULL);
6575
6576         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
6577
6578         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6579                 return EINVAL;
6580
6581         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6582                 return EACCES;
6583         }
6584
6585         if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6586                 return EINVAL;
6587         }
6588
6589         mdb_cursor_init(&mc, txn, dbi, &mx);
6590
6591         exact = 0;
6592         if (data) {
6593                 op = MDB_GET_BOTH;
6594                 rdata = *data;
6595                 xdata = &rdata;
6596         } else {
6597                 op = MDB_SET;
6598                 xdata = NULL;
6599         }
6600         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
6601         if (rc == 0) {
6602                 /* let mdb_page_split know about this cursor if needed:
6603                  * delete will trigger a rebalance; if it needs to move
6604                  * a node from one page to another, it will have to
6605                  * update the parent's separator key(s). If the new sepkey
6606                  * is larger than the current one, the parent page may
6607                  * run out of space, triggering a split. We need this
6608                  * cursor to be consistent until the end of the rebalance.
6609                  */
6610                 mc.mc_next = txn->mt_cursors[dbi];
6611                 txn->mt_cursors[dbi] = &mc;
6612                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
6613                 txn->mt_cursors[dbi] = mc.mc_next;
6614         }
6615         return rc;
6616 }
6617
6618 /** Split a page and insert a new node.
6619  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
6620  * The cursor will be updated to point to the actual page and index where
6621  * the node got inserted after the split.
6622  * @param[in] newkey The key for the newly inserted node.
6623  * @param[in] newdata The data for the newly inserted node.
6624  * @param[in] newpgno The page number, if the new node is a branch node.
6625  * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
6626  * @return 0 on success, non-zero on failure.
6627  */
6628 static int
6629 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
6630         unsigned int nflags)
6631 {
6632         unsigned int flags;
6633         int              rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
6634         indx_t           newindx;
6635         pgno_t           pgno = 0;
6636         unsigned int     i, j, split_indx, nkeys, pmax;
6637         MDB_node        *node;
6638         MDB_val  sepkey, rkey, xdata, *rdata = &xdata;
6639         MDB_page        *copy;
6640         MDB_page        *mp, *rp, *pp;
6641         unsigned int ptop;
6642         MDB_cursor      mn;
6643         DKBUF;
6644
6645         mp = mc->mc_pg[mc->mc_top];
6646         newindx = mc->mc_ki[mc->mc_top];
6647
6648         DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
6649             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
6650             DKEY(newkey), mc->mc_ki[mc->mc_top]);
6651
6652         /* Create a right sibling. */
6653         if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
6654                 return rc;
6655         DPRINTF("new right sibling: page %zu", rp->mp_pgno);
6656
6657         if (mc->mc_snum < 2) {
6658                 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
6659                         return rc;
6660                 /* shift current top to make room for new parent */
6661                 mc->mc_pg[1] = mc->mc_pg[0];
6662                 mc->mc_ki[1] = mc->mc_ki[0];
6663                 mc->mc_pg[0] = pp;
6664                 mc->mc_ki[0] = 0;
6665                 mc->mc_db->md_root = pp->mp_pgno;
6666                 DPRINTF("root split! new root = %zu", pp->mp_pgno);
6667                 mc->mc_db->md_depth++;
6668                 new_root = 1;
6669
6670                 /* Add left (implicit) pointer. */
6671                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
6672                         /* undo the pre-push */
6673                         mc->mc_pg[0] = mc->mc_pg[1];
6674                         mc->mc_ki[0] = mc->mc_ki[1];
6675                         mc->mc_db->md_root = mp->mp_pgno;
6676                         mc->mc_db->md_depth--;
6677                         return rc;
6678                 }
6679                 mc->mc_snum = 2;
6680                 mc->mc_top = 1;
6681                 ptop = 0;
6682         } else {
6683                 ptop = mc->mc_top-1;
6684                 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
6685         }
6686
6687         mc->mc_flags |= C_SPLITTING;
6688         mdb_cursor_copy(mc, &mn);
6689         mn.mc_pg[mn.mc_top] = rp;
6690         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
6691
6692         if (nflags & MDB_APPEND) {
6693                 mn.mc_ki[mn.mc_top] = 0;
6694                 sepkey = *newkey;
6695                 split_indx = newindx;
6696                 nkeys = 0;
6697                 goto newsep;
6698         }
6699
6700         nkeys = NUMKEYS(mp);
6701         split_indx = nkeys / 2;
6702         if (newindx < split_indx)
6703                 newpos = 0;
6704
6705         if (IS_LEAF2(rp)) {
6706                 char *split, *ins;
6707                 int x;
6708                 unsigned int lsize, rsize, ksize;
6709                 /* Move half of the keys to the right sibling */
6710                 copy = NULL;
6711                 x = mc->mc_ki[mc->mc_top] - split_indx;
6712                 ksize = mc->mc_db->md_pad;
6713                 split = LEAF2KEY(mp, split_indx, ksize);
6714                 rsize = (nkeys - split_indx) * ksize;
6715                 lsize = (nkeys - split_indx) * sizeof(indx_t);
6716                 mp->mp_lower -= lsize;
6717                 rp->mp_lower += lsize;
6718                 mp->mp_upper += rsize - lsize;
6719                 rp->mp_upper -= rsize - lsize;
6720                 sepkey.mv_size = ksize;
6721                 if (newindx == split_indx) {
6722                         sepkey.mv_data = newkey->mv_data;
6723                 } else {
6724                         sepkey.mv_data = split;
6725                 }
6726                 if (x<0) {
6727                         ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
6728                         memcpy(rp->mp_ptrs, split, rsize);
6729                         sepkey.mv_data = rp->mp_ptrs;
6730                         memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
6731                         memcpy(ins, newkey->mv_data, ksize);
6732                         mp->mp_lower += sizeof(indx_t);
6733                         mp->mp_upper -= ksize - sizeof(indx_t);
6734                 } else {
6735                         if (x)
6736                                 memcpy(rp->mp_ptrs, split, x * ksize);
6737                         ins = LEAF2KEY(rp, x, ksize);
6738                         memcpy(ins, newkey->mv_data, ksize);
6739                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
6740                         rp->mp_lower += sizeof(indx_t);
6741                         rp->mp_upper -= ksize - sizeof(indx_t);
6742                         mc->mc_ki[mc->mc_top] = x;
6743                         mc->mc_pg[mc->mc_top] = rp;
6744                 }
6745                 goto newsep;
6746         }
6747
6748         /* For leaf pages, check the split point based on what
6749          * fits where, since otherwise mdb_node_add can fail.
6750          *
6751          * This check is only needed when the data items are
6752          * relatively large, such that being off by one will
6753          * make the difference between success or failure.
6754          *
6755          * It's also relevant if a page happens to be laid out
6756          * such that one half of its nodes are all "small" and
6757          * the other half of its nodes are "large." If the new
6758          * item is also "large" and falls on the half with
6759          * "large" nodes, it also may not fit.
6760          */
6761         if (IS_LEAF(mp)) {
6762                 unsigned int psize, nsize;
6763                 /* Maximum free space in an empty page */
6764                 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
6765                 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
6766                 if ((nkeys < 20) || (nsize > pmax/16)) {
6767                         if (newindx <= split_indx) {
6768                                 psize = nsize;
6769                                 newpos = 0;
6770                                 for (i=0; i<split_indx; i++) {
6771                                         node = NODEPTR(mp, i);
6772                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6773                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
6774                                                 psize += sizeof(pgno_t);
6775                                         else
6776                                                 psize += NODEDSZ(node);
6777                                         psize += psize & 1;
6778                                         if (psize > pmax) {
6779                                                 if (i <= newindx) {
6780                                                         split_indx = newindx;
6781                                                         if (i < newindx)
6782                                                                 newpos = 1;
6783                                                 }
6784                                                 else
6785                                                         split_indx = i;
6786                                                 break;
6787                                         }
6788                                 }
6789                         } else {
6790                                 psize = nsize;
6791                                 for (i=nkeys-1; i>=split_indx; i--) {
6792                                         node = NODEPTR(mp, i);
6793                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6794                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
6795                                                 psize += sizeof(pgno_t);
6796                                         else
6797                                                 psize += NODEDSZ(node);
6798                                         psize += psize & 1;
6799                                         if (psize > pmax) {
6800                                                 if (i >= newindx) {
6801                                                         split_indx = newindx;
6802                                                         newpos = 0;
6803                                                 } else
6804                                                         split_indx = i+1;
6805                                                 break;
6806                                         }
6807                                 }
6808                         }
6809                 }
6810         }
6811
6812         /* First find the separating key between the split pages.
6813          * The case where newindx == split_indx is ambiguous; the
6814          * new item could go to the new page or stay on the original
6815          * page. If newpos == 1 it goes to the new page.
6816          */
6817         if (newindx == split_indx && newpos) {
6818                 sepkey.mv_size = newkey->mv_size;
6819                 sepkey.mv_data = newkey->mv_data;
6820         } else {
6821                 node = NODEPTR(mp, split_indx);
6822                 sepkey.mv_size = node->mn_ksize;
6823                 sepkey.mv_data = NODEKEY(node);
6824         }
6825
6826 newsep:
6827         DPRINTF("separator is [%s]", DKEY(&sepkey));
6828
6829         /* Copy separator key to the parent.
6830          */
6831         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
6832                 mn.mc_snum--;
6833                 mn.mc_top--;
6834                 did_split = 1;
6835                 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
6836
6837                 /* root split? */
6838                 if (mn.mc_snum == mc->mc_snum) {
6839                         mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
6840                         mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
6841                         mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
6842                         mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
6843                         mc->mc_snum++;
6844                         mc->mc_top++;
6845                         ptop++;
6846                 }
6847                 /* Right page might now have changed parent.
6848                  * Check if left page also changed parent.
6849                  */
6850                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6851                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6852                         for (i=0; i<ptop; i++) {
6853                                 mc->mc_pg[i] = mn.mc_pg[i];
6854                                 mc->mc_ki[i] = mn.mc_ki[i];
6855                         }
6856                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
6857                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6858                 }
6859         } else {
6860                 mn.mc_top--;
6861                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
6862                 mn.mc_top++;
6863         }
6864         mc->mc_flags ^= C_SPLITTING;
6865         if (rc != MDB_SUCCESS) {
6866                 return rc;
6867         }
6868         if (nflags & MDB_APPEND) {
6869                 mc->mc_pg[mc->mc_top] = rp;
6870                 mc->mc_ki[mc->mc_top] = 0;
6871                 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6872                 if (rc)
6873                         return rc;
6874                 for (i=0; i<mc->mc_top; i++)
6875                         mc->mc_ki[i] = mn.mc_ki[i];
6876                 goto done;
6877         }
6878         if (IS_LEAF2(rp)) {
6879                 goto done;
6880         }
6881
6882         /* Move half of the keys to the right sibling. */
6883
6884         /* grab a page to hold a temporary copy */
6885         copy = mdb_page_malloc(mc, 1);
6886         if (copy == NULL)
6887                 return ENOMEM;
6888
6889         copy->mp_pgno  = mp->mp_pgno;
6890         copy->mp_flags = mp->mp_flags;
6891         copy->mp_lower = PAGEHDRSZ;
6892         copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6893         mc->mc_pg[mc->mc_top] = copy;
6894         for (i = j = 0; i <= nkeys; j++) {
6895                 if (i == split_indx) {
6896                 /* Insert in right sibling. */
6897                 /* Reset insert index for right sibling. */
6898                         if (i != newindx || (newpos ^ ins_new)) {
6899                                 j = 0;
6900                                 mc->mc_pg[mc->mc_top] = rp;
6901                         }
6902                 }
6903
6904                 if (i == newindx && !ins_new) {
6905                         /* Insert the original entry that caused the split. */
6906                         rkey.mv_data = newkey->mv_data;
6907                         rkey.mv_size = newkey->mv_size;
6908                         if (IS_LEAF(mp)) {
6909                                 rdata = newdata;
6910                         } else
6911                                 pgno = newpgno;
6912                         flags = nflags;
6913
6914                         ins_new = 1;
6915
6916                         /* Update index for the new key. */
6917                         mc->mc_ki[mc->mc_top] = j;
6918                 } else if (i == nkeys) {
6919                         break;
6920                 } else {
6921                         node = NODEPTR(mp, i);
6922                         rkey.mv_data = NODEKEY(node);
6923                         rkey.mv_size = node->mn_ksize;
6924                         if (IS_LEAF(mp)) {
6925                                 xdata.mv_data = NODEDATA(node);
6926                                 xdata.mv_size = NODEDSZ(node);
6927                                 rdata = &xdata;
6928                         } else
6929                                 pgno = NODEPGNO(node);
6930                         flags = node->mn_flags;
6931
6932                         i++;
6933                 }
6934
6935                 if (!IS_LEAF(mp) && j == 0) {
6936                         /* First branch index doesn't need key data. */
6937                         rkey.mv_size = 0;
6938                 }
6939
6940                 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6941                 if (rc) break;
6942         }
6943
6944         nkeys = NUMKEYS(copy);
6945         for (i=0; i<nkeys; i++)
6946                 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6947         mp->mp_lower = copy->mp_lower;
6948         mp->mp_upper = copy->mp_upper;
6949         memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6950                 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6951
6952         /* reset back to original page */
6953         if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6954                 mc->mc_pg[mc->mc_top] = mp;
6955                 if (nflags & MDB_RESERVE) {
6956                         node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6957                         if (!(node->mn_flags & F_BIGDATA))
6958                                 newdata->mv_data = NODEDATA(node);
6959                 }
6960         } else {
6961                 mc->mc_ki[ptop]++;
6962                 /* Make sure mc_ki is still valid.
6963                  */
6964                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6965                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6966                         for (i=0; i<ptop; i++) {
6967                                 mc->mc_pg[i] = mn.mc_pg[i];
6968                                 mc->mc_ki[i] = mn.mc_ki[i];
6969                         }
6970                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
6971                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6972                 }
6973         }
6974
6975         /* return tmp page to freelist */
6976         mdb_page_free(mc->mc_txn->mt_env, copy);
6977 done:
6978         {
6979                 /* Adjust other cursors pointing to mp */
6980                 MDB_cursor *m2, *m3;
6981                 MDB_dbi dbi = mc->mc_dbi;
6982                 int fixup = NUMKEYS(mp);
6983
6984                 if (mc->mc_flags & C_SUB)
6985                         dbi--;
6986
6987                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6988                         if (m2 == mc) continue;
6989                         if (mc->mc_flags & C_SUB)
6990                                 m3 = &m2->mc_xcursor->mx_cursor;
6991                         else
6992                                 m3 = m2;
6993                         if (!(m3->mc_flags & C_INITIALIZED))
6994                                 continue;
6995                         if (m3->mc_flags & C_SPLITTING)
6996                                 continue;
6997                         if (new_root) {
6998                                 int k;
6999                                 /* root split */
7000                                 for (k=m3->mc_top; k>=0; k--) {
7001                                         m3->mc_ki[k+1] = m3->mc_ki[k];
7002                                         m3->mc_pg[k+1] = m3->mc_pg[k];
7003                                 }
7004                                 if (m3->mc_ki[0] >= split_indx) {
7005                                         m3->mc_ki[0] = 1;
7006                                 } else {
7007                                         m3->mc_ki[0] = 0;
7008                                 }
7009                                 m3->mc_pg[0] = mc->mc_pg[0];
7010                                 m3->mc_snum++;
7011                                 m3->mc_top++;
7012                         }
7013                         if (m3->mc_pg[mc->mc_top] == mp) {
7014                                 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7015                                         m3->mc_ki[mc->mc_top]++;
7016                                 if (m3->mc_ki[mc->mc_top] >= fixup) {
7017                                         m3->mc_pg[mc->mc_top] = rp;
7018                                         m3->mc_ki[mc->mc_top] -= fixup;
7019                                         m3->mc_ki[ptop] = mn.mc_ki[ptop];
7020                                 }
7021                         } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7022                                 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7023                                 m3->mc_ki[ptop]++;
7024                         }
7025                 }
7026         }
7027         return rc;
7028 }
7029
7030 int
7031 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7032     MDB_val *key, MDB_val *data, unsigned int flags)
7033 {
7034         MDB_cursor mc;
7035         MDB_xcursor mx;
7036
7037         assert(key != NULL);
7038         assert(data != NULL);
7039
7040         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7041                 return EINVAL;
7042
7043         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7044                 return EACCES;
7045         }
7046
7047         if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7048                 return EINVAL;
7049         }
7050
7051         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7052                 return EINVAL;
7053
7054         mdb_cursor_init(&mc, txn, dbi, &mx);
7055         return mdb_cursor_put(&mc, key, data, flags);
7056 }
7057
7058 int
7059 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7060 {
7061         if ((flag & CHANGEABLE) != flag)
7062                 return EINVAL;
7063         if (onoff)
7064                 env->me_flags |= flag;
7065         else
7066                 env->me_flags &= ~flag;
7067         return MDB_SUCCESS;
7068 }
7069
7070 int
7071 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7072 {
7073         if (!env || !arg)
7074                 return EINVAL;
7075
7076         *arg = env->me_flags;
7077         return MDB_SUCCESS;
7078 }
7079
7080 int
7081 mdb_env_get_path(MDB_env *env, const char **arg)
7082 {
7083         if (!env || !arg)
7084                 return EINVAL;
7085
7086         *arg = env->me_path;
7087         return MDB_SUCCESS;
7088 }
7089
7090 /** Common code for #mdb_stat() and #mdb_env_stat().
7091  * @param[in] env the environment to operate in.
7092  * @param[in] db the #MDB_db record containing the stats to return.
7093  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7094  * @return 0, this function always succeeds.
7095  */
7096 static int
7097 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7098 {
7099         arg->ms_psize = env->me_psize;
7100         arg->ms_depth = db->md_depth;
7101         arg->ms_branch_pages = db->md_branch_pages;
7102         arg->ms_leaf_pages = db->md_leaf_pages;
7103         arg->ms_overflow_pages = db->md_overflow_pages;
7104         arg->ms_entries = db->md_entries;
7105
7106         return MDB_SUCCESS;
7107 }
7108 int
7109 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7110 {
7111         int toggle;
7112
7113         if (env == NULL || arg == NULL)
7114                 return EINVAL;
7115
7116         toggle = mdb_env_pick_meta(env);
7117
7118         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7119 }
7120
7121 int
7122 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7123 {
7124         int toggle;
7125
7126         if (env == NULL || arg == NULL)
7127                 return EINVAL;
7128
7129         toggle = mdb_env_pick_meta(env);
7130         arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7131         arg->me_mapsize = env->me_mapsize;
7132         arg->me_maxreaders = env->me_maxreaders;
7133         arg->me_numreaders = env->me_numreaders;
7134         arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7135         arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7136         return MDB_SUCCESS;
7137 }
7138
7139 /** Set the default comparison functions for a database.
7140  * Called immediately after a database is opened to set the defaults.
7141  * The user can then override them with #mdb_set_compare() or
7142  * #mdb_set_dupsort().
7143  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7144  * @param[in] dbi A database handle returned by #mdb_dbi_open()
7145  */
7146 static void
7147 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7148 {
7149         uint16_t f = txn->mt_dbs[dbi].md_flags;
7150
7151         txn->mt_dbxs[dbi].md_cmp =
7152                 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7153                 (f & MDB_INTEGERKEY) ? mdb_cmp_cint  : mdb_cmp_memn;
7154
7155         txn->mt_dbxs[dbi].md_dcmp =
7156                 !(f & MDB_DUPSORT) ? 0 :
7157                 ((f & MDB_INTEGERDUP)
7158                  ? ((f & MDB_DUPFIXED)   ? mdb_cmp_int   : mdb_cmp_cint)
7159                  : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7160 }
7161
7162 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7163 {
7164         MDB_val key, data;
7165         MDB_dbi i;
7166         MDB_cursor mc;
7167         int rc, dbflag, exact;
7168         unsigned int unused = 0;
7169         size_t len;
7170
7171         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7172                 mdb_default_cmp(txn, FREE_DBI);
7173         }
7174
7175         if ((flags & VALID_FLAGS) != flags)
7176                 return EINVAL;
7177
7178         /* main DB? */
7179         if (!name) {
7180                 *dbi = MAIN_DBI;
7181                 if (flags & PERSISTENT_FLAGS) {
7182                         uint16_t f2 = flags & PERSISTENT_FLAGS;
7183                         /* make sure flag changes get committed */
7184                         if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7185                                 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7186                                 txn->mt_flags |= MDB_TXN_DIRTY;
7187                         }
7188                 }
7189                 mdb_default_cmp(txn, MAIN_DBI);
7190                 return MDB_SUCCESS;
7191         }
7192
7193         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7194                 mdb_default_cmp(txn, MAIN_DBI);
7195         }
7196
7197         /* Is the DB already open? */
7198         len = strlen(name);
7199         for (i=2; i<txn->mt_numdbs; i++) {
7200                 if (!txn->mt_dbxs[i].md_name.mv_size) {
7201                         /* Remember this free slot */
7202                         if (!unused) unused = i;
7203                         continue;
7204                 }
7205                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7206                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7207                         *dbi = i;
7208                         return MDB_SUCCESS;
7209                 }
7210         }
7211
7212         /* If no free slot and max hit, fail */
7213         if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7214                 return MDB_DBS_FULL;
7215
7216         /* Cannot mix named databases with some mainDB flags */
7217         if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7218                 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7219
7220         /* Find the DB info */
7221         dbflag = DB_NEW|DB_VALID;
7222         exact = 0;
7223         key.mv_size = len;
7224         key.mv_data = (void *)name;
7225         mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7226         rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7227         if (rc == MDB_SUCCESS) {
7228                 /* make sure this is actually a DB */
7229                 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7230                 if (!(node->mn_flags & F_SUBDATA))
7231                         return EINVAL;
7232         } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7233                 /* Create if requested */
7234                 MDB_db dummy;
7235                 data.mv_size = sizeof(MDB_db);
7236                 data.mv_data = &dummy;
7237                 memset(&dummy, 0, sizeof(dummy));
7238                 dummy.md_root = P_INVALID;
7239                 dummy.md_flags = flags & PERSISTENT_FLAGS;
7240                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7241                 dbflag |= DB_DIRTY;
7242         }
7243
7244         /* OK, got info, add to table */
7245         if (rc == MDB_SUCCESS) {
7246                 unsigned int slot = unused ? unused : txn->mt_numdbs;
7247                 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7248                 txn->mt_dbxs[slot].md_name.mv_size = len;
7249                 txn->mt_dbxs[slot].md_rel = NULL;
7250                 txn->mt_dbflags[slot] = dbflag;
7251                 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7252                 *dbi = slot;
7253                 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7254                 mdb_default_cmp(txn, slot);
7255                 if (!unused) {
7256                         txn->mt_numdbs++;
7257                 }
7258         }
7259
7260         return rc;
7261 }
7262
7263 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7264 {
7265         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7266                 return EINVAL;
7267
7268         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7269 }
7270
7271 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7272 {
7273         char *ptr;
7274         if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7275                 return;
7276         ptr = env->me_dbxs[dbi].md_name.mv_data;
7277         env->me_dbxs[dbi].md_name.mv_data = NULL;
7278         env->me_dbxs[dbi].md_name.mv_size = 0;
7279         env->me_dbflags[dbi] = 0;
7280         free(ptr);
7281 }
7282
7283 /** Add all the DB's pages to the free list.
7284  * @param[in] mc Cursor on the DB to free.
7285  * @param[in] subs non-Zero to check for sub-DBs in this DB.
7286  * @return 0 on success, non-zero on failure.
7287  */
7288 static int
7289 mdb_drop0(MDB_cursor *mc, int subs)
7290 {
7291         int rc;
7292
7293         rc = mdb_page_search(mc, NULL, 0);
7294         if (rc == MDB_SUCCESS) {
7295                 MDB_node *ni;
7296                 MDB_cursor mx;
7297                 unsigned int i;
7298
7299                 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7300                 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7301                         mdb_cursor_pop(mc);
7302
7303                 mdb_cursor_copy(mc, &mx);
7304                 while (mc->mc_snum > 0) {
7305                         if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
7306                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7307                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7308                                         if (ni->mn_flags & F_BIGDATA) {
7309                                                 int j, ovpages;
7310                                                 MDB_page *omp;
7311                                                 pgno_t pg;
7312                                                 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7313                                                 rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL);
7314                                                 if (rc != 0)
7315                                                         return rc;
7316                                                 assert(IS_OVERFLOW(omp));
7317                                                 ovpages = omp->mp_pages;
7318                                                 for (j=0; j<ovpages; j++) {
7319                                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
7320                                                         pg++;
7321                                                 }
7322                                         } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7323                                                 mdb_xcursor_init1(mc, ni);
7324                                                 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7325                                                 if (rc)
7326                                                         return rc;
7327                                         }
7328                                 }
7329                         } else {
7330                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7331                                         pgno_t pg;
7332                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7333                                         pg = NODEPGNO(ni);
7334                                         /* free it */
7335                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
7336                                 }
7337                         }
7338                         if (!mc->mc_top)
7339                                 break;
7340                         mc->mc_ki[mc->mc_top] = i;
7341                         rc = mdb_cursor_sibling(mc, 1);
7342                         if (rc) {
7343                                 /* no more siblings, go back to beginning
7344                                  * of previous level.
7345                                  */
7346                                 mdb_cursor_pop(mc);
7347                                 mc->mc_ki[0] = 0;
7348                                 for (i=1; i<mc->mc_snum; i++) {
7349                                         mc->mc_ki[i] = 0;
7350                                         mc->mc_pg[i] = mx.mc_pg[i];
7351                                 }
7352                         }
7353                 }
7354                 /* free it */
7355                 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
7356                         mc->mc_db->md_root);
7357         }
7358         return 0;
7359 }
7360
7361 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7362 {
7363         MDB_cursor *mc;
7364         int rc;
7365
7366         if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7367                 return EINVAL;
7368
7369         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7370                 return EACCES;
7371
7372         rc = mdb_cursor_open(txn, dbi, &mc);
7373         if (rc)
7374                 return rc;
7375
7376         rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7377         if (rc)
7378                 goto leave;
7379
7380         /* Can't delete the main DB */
7381         if (del && dbi > MAIN_DBI) {
7382                 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7383                 if (!rc) {
7384                         txn->mt_dbflags[dbi] = DB_STALE;
7385                         mdb_dbi_close(txn->mt_env, dbi);
7386                 }
7387         } else {
7388                 /* reset the DB record, mark it dirty */
7389                 txn->mt_dbflags[dbi] |= DB_DIRTY;
7390                 txn->mt_dbs[dbi].md_depth = 0;
7391                 txn->mt_dbs[dbi].md_branch_pages = 0;
7392                 txn->mt_dbs[dbi].md_leaf_pages = 0;
7393                 txn->mt_dbs[dbi].md_overflow_pages = 0;
7394                 txn->mt_dbs[dbi].md_entries = 0;
7395                 txn->mt_dbs[dbi].md_root = P_INVALID;
7396
7397                 txn->mt_flags |= MDB_TXN_DIRTY;
7398         }
7399 leave:
7400         mdb_cursor_close(mc);
7401         return rc;
7402 }
7403
7404 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7405 {
7406         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7407                 return EINVAL;
7408
7409         txn->mt_dbxs[dbi].md_cmp = cmp;
7410         return MDB_SUCCESS;
7411 }
7412
7413 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7414 {
7415         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7416                 return EINVAL;
7417
7418         txn->mt_dbxs[dbi].md_dcmp = cmp;
7419         return MDB_SUCCESS;
7420 }
7421
7422 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7423 {
7424         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7425                 return EINVAL;
7426
7427         txn->mt_dbxs[dbi].md_rel = rel;
7428         return MDB_SUCCESS;
7429 }
7430
7431 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7432 {
7433         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7434                 return EINVAL;
7435
7436         txn->mt_dbxs[dbi].md_relctx = ctx;
7437         return MDB_SUCCESS;
7438 }
7439
7440 /** @} */