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