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