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