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