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