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