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