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