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