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