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