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