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