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