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