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