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