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