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