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