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