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