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