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