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