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