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