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