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