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