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