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