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