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