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