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