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