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