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