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