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