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