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