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