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