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