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