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