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