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