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